Пример #1
0
def init_molecule():
    """Create Particles p1 and p2 inside boundaries and return a molecule
    connecting them"""

    p1 = particle.Particle(np.array([.2, .2]), 1)
    p2 = particle.Particle(np.array([.8, .8]), 2)
    return molecule.Molecule(p1.pos, p2.pos, p1.m, p2.m, 1, .5)
Пример #2
0
def threesome_paricle_initialize(x1, y1, x2, y2, x3, y3, o1, o2, o3, BoxL,
                                 sigma):
    ptcls = []
    ptcls.append(particle.Particle(x1, y1, sigma, o1, BoxL))
    ptcls.append(particle.Particle(x2, y2, sigma, o2, BoxL))
    ptcls.append(particle.Particle(x3, y3, sigma, o3, BoxL))
    return ptcls
def pair_production(photon):

    if photon.name != "photon":
        raise TypeError("Did not input a valid photon for pair production")
    else:

        k_checked = photon.energy

        try:
            E_neg_checked = pair_pdf.sample_secondary_energy(k_checked)
        except:
            print("-------------!!-------------")
            print(
                "Sampling recursion limit reached, giving both particles equal energies"
            )
            print("-------------!!-------------")
            E_neg_checked = k_checked / 2

        E_plus_checked = k_checked - E_neg_checked

        phi, dtheta = brem_dir.sample_direction(k_checked)
        e_minus_dir = np.array([photon.direction[0] + dtheta, phi])
        e_plus_dir = np.array([photon.direction[0] + dtheta, -phi])

        return [
            pcl.Particle("electron", E_neg_checked, photon.position,
                         e_minus_dir),
            pcl.Particle("positron", E_plus_checked, photon.position,
                         e_plus_dir)
        ]
Пример #4
0
def init_molecule():
    """Create Particles p1 and p2 inside boundaries and return a molecule
    connecting them"""
    p1 = particle.Particle(np.random.rand(2), initial_p1_mass)
    p2 = particle.Particle(np.random.rand(2), initial_p2_mass)
    return molecule.Molecule(p1.pos, p2.pos, p1.m, p2.m, initial_k,
                             initial_e_length)
Пример #5
0
 def __init__(self, P1_position, P2_position, P1_mass, P2_mass, k_spring,
              equilibrium_length):
     '''Create diatomic molecule with positions of both particles, their masses, a spring constant, and equilibrium length'''
     self.p1 = particle.Particle(P1_position, P1_mass)
     self.p2 = particle.Particle(P2_position, P2_mass)
     self.k = k_spring
     self.L0 = equilibrium_length
Пример #6
0
 def __init__(self, p1, p2, m1, m2, k, L0):
     self.p1 = particle.Particle(p1, m1)
     self.p2 = particle.Particle(p2, m2)
     self.m1 = m1
     self.m2 = m2
     self.k = k
     self.L0 = L0
def simulate_once(speed_scale):
    """
    Run a new simulation with the given speed scale and return its final 
    state.
    
    Arguments:
        speed_scale: standard deviation of the gaussian used to generat the
                     velocities.
                     
    Returns: the final state of the simulation as a dictionary.
    """

    container = pa.Particle(sp.zeros(ndims),
                            sp.zeros(ndims),
                            radius=container_scale,
                            mass=1e20,
                            immovable=True)

    sim = si.Simulation(container, ndims=ndims)

    velocities = []

    # Add many particles at random, ensuring there are no overlaps
    for i in xrange(nballs - 1):
        velocity = sp.random.normal(size=ndims, scale=speed_scale)
        position = sim.find_unused_position(radius)

        new_particle = pa.Particle(position, velocity, radius=radius, mass=1)
        sim.add_particle(new_particle)
        velocities.append(velocity)

    # Ensure that the average velocity is zero
    position = sim.find_unused_position(radius)
    correcting_particle_velocity = -sp.sum(velocities, axis=0)

    sim.add_particle(
        pa.Particle(position,
                    correcting_particle_velocity,
                    radius=radius,
                    mass=1))

    sim.first_step()

    for i in xrange(iterations):
        sim.next_step()

    states = sim.get_states()

    return states[-1]
Пример #8
0
    def try_warp(self, dt):
        if self.owning_civ.upgrade_stats['warp_drive'] == 0:
            return
        if self.warp_drive_countdown > 0:
            return

        towards = (self.target.pos - self.pos).normalized()
        nearest, dist = helper.get_nearest(self.pos, self.scene.get_planets())
        if nearest:
            if dist < (nearest.get_radius() + WARP_PLANET_MIN_DIST)**2:
                return

        if self.warp_drive_t < 0.66:
            self.velocity = V2(0, 0)
            self.warp_drive_t += dt
            if int(self.warp_drive_t * 40) % 2 == 0:
                pvel = V2(random.random() - 0.5, random.random() - 0.5) * 15
                pvel -= towards * 25
                p = particle.Particle([PICO_WHITE, PICO_PINK], 1, self.pos,
                                      0.25 + random.random() * 0.25, pvel)
                self.scene.game_group.add(p)
            return

        exit_dist = (self.target.pos - self.pos).magnitude(
        ) - self.target.get_radius() - WARP_PLANET_MIN_DIST

        max_dist = self.owning_civ.upgrade_stats['warp_drive'] + 30
        dist = min(exit_dist, max_dist)

        print(dist)

        for i in range(0, int(dist), 4):
            p = self.pos + towards * i
            pvel = V2(random.random() - 0.5, random.random() - 0.5) * 15
            pvel += towards * 15
            p = particle.Particle([PICO_WHITE, PICO_PINK], 1, p,
                                  0.25 + random.random() * 0.5, pvel)
            self.scene.game_group.add(p)
            nearest, d = helper.get_nearest(p, self.scene.get_planets())
            if nearest and d < (nearest.get_radius() +
                                WARP_PLANET_MIN_DIST)**2:
                dist = i
                break

        self.warp_drive_t = 0

        self.pos = self.pos + towards * dist
        print(towards, dist, self.pos)
        self.warp_drive_countdown = WARP_DRIVE_TIME * (dist / max_dist)
Пример #9
0
 def emit_thrust_particles(self):
     pvel = V2(random.random() - 0.5, random.random() - 0.5) * 1
     pvel += -self.velocity / 2
     vn = helper.try_normalize(self.velocity)
     side = V2(vn.y, -vn.x)  # Sideways vector from forward
     p1 = particle.Particle(
         [PICO_WHITE, PICO_WHITE, PICO_YELLOW], 1, self.pos +
         -helper.try_normalize(self.velocity) * self.radius + side * 1.5, 1,
         pvel)
     self.scene.add_particle(p1)
     p2 = particle.Particle(
         [PICO_WHITE, PICO_WHITE, PICO_YELLOW], 1, self.pos +
         -helper.try_normalize(self.velocity) * self.radius - side * 1.5, 1,
         pvel)
     self.scene.add_particle(p2)
def claimConnectedDevices():
	credentialsJsonFile = open('credentials.json', 'r')
	credentials = json.load(credentialsJsonFile)
	credentialsJsonFile.close()
	particleLocal = particle.Local(credentials['ssid'], 
		credentials['wifi_password'], credentials['wifi_encryption'])

	print "Retrieving connected ports..."
	serialPorts = particleLocal.get_connected_ports()
	assert len(serialPorts) >= 2
	if len(serialPorts) > 2:
		serialPorts = serialPorts[0:2]

	print "Logging into cloud..."
	particleCloud = particle.Particle(
			credentials['particle_username'],
			credentials['particle_password'])
		
	for ii in range(len(serialPorts)):
		port = serialPorts[ii]
		otherPort = serialPorts[(ii+1)%2]
		print "Identifying device..."
		particleId = particleLocal.identify_device(port)
		print "Setting WiFi..."
		particleLocal.set_wifi(port)
		time.sleep(20)
		print "Claiming device..."
		particleCloud.claim_device(particleId)
Пример #11
0
    def __init__(self, n=100, seed=42424242, fname=None):
        if fname is None:
            self.n = n
            self.seed = seed
            random.seed(self.seed)

            self.particles = []
            for _ in range(self.n):
                self.particles.append(
                    particle.Particle(
                        r=[
                            random.random() - .5,
                            random.random() - .5,
                            random.random() - .5
                        ],
                        v=[
                            random.random() - .5,
                            random.random() - .5,
                            random.random() - .5
                        ],
                        m=1.  #random.random()
                    ))
        else:
            particles = self.load(fname)
            self.n = len(particles)
            self.seed = None
            self.particles = particles
Пример #12
0
def resample(particles, numParticles):
    Q = [0.0] * numParticles

    idxArr = np.zeros((numParticles, 1), dtype=int)

    newParticles = [particle.Particle(0, 0, 0)] * numParticles

    # calculate CDF
    Q[0] = particles[0].weight
    for i in range(1, numParticles):
        Q[i] = particles[i].weight + Q[i - 1]

    t = np.random.rand(numParticles + 1, 1)
    T = np.sort(t, axis=0)
    T[numParticles] = 1

    i, j = 0, 0
    while i < numParticles:
        print(i, j, len(T), len(Q))
        if T[i] < Q[j]:
            idxArr[i] = j
            i += 1
        else:
            j += 1

    for i in range(numParticles):
        newParticles[i].x = particles[idxArr[i][0]].x
        newParticles[i].y = particles[idxArr[i][0]].y
        newParticles[i].weight = 1 / numParticles

    return newParticles
Пример #13
0
 def generateMultipole(self):
     self.pseudoparticle = particle.Particle(r=[0., 0., 0.],
                                             v=[0., 0., 0.],
                                             m=0.)
     if self.nparticles == 0:
         print("error")
     elif self.nparticles == 1:
         self.pseudoparticle.r[:] = self.particle.r
         self.pseudoparticle.v[:] = self.particle.v
         self.pseudoparticle.a[:] = self.particle.a
         self.pseudoparticle.m = self.particle.m
     else:
         for subnode in self.subnodes:
             if subnode is not None:
                 subnode.generateMultipole()
                 for i in range(3):
                     self.pseudoparticle.r[i] += subnode.pseudoparticle.r[
                         i] * subnode.pseudoparticle.m
                     self.pseudoparticle.v[i] += subnode.pseudoparticle.v[
                         i] * subnode.pseudoparticle.m
                     self.pseudoparticle.a[i] += subnode.pseudoparticle.a[
                         i] * subnode.pseudoparticle.m
                 self.pseudoparticle.m += subnode.pseudoparticle.m
         self.pseudoparticle.r = [
             cm / self.pseudoparticle.m for cm in self.pseudoparticle.r
         ]
         self.pseudoparticle.v = [
             cm / self.pseudoparticle.m for cm in self.pseudoparticle.v
         ]
         self.pseudoparticle.a = [
             cm / self.pseudoparticle.m for cm in self.pseudoparticle.a
         ]
Пример #14
0
    def kill(self):
        for ship in self.frozen_ships:
            self.unfreeze_ship(ship)
        for replica in self.frozen_replicas:
            replica.kill()
        self.countdown.kill()

        sound.play_explosion()
        base_angle = random.random() * 6.2818
        for x in range(self.image.get_width()):
            for y in range(self.image.get_height()):
                color = tuple(self.image.get_at((x,y)))
                if color[3] >= 128 and color[0:3] != PICO_BLACK:
                    _,a = (V2(x,y) - V2(self.width/2,self.height/2)).as_polar()
                    a *= 3.14159 / 180
                    ad = abs(helper.get_angle_delta(a, base_angle))
                    if ad > 3.14159/2:
                        a = base_angle + 3.14159
                    else:
                        a = base_angle
                    pvel = helper.from_angle(a) * 6
                    p = particle.Particle([
                        color[0:3],
                        color[0:3],
                        DARKEN_COLOR[color[0:3]]
                        ],
                        1,
                        self.pos + V2(x - self.width // 2,y - self.height // 2),
                        1.25 + random.random() ** 2,
                        pvel
                    )
                    self.scene.game_group.add(p)  

        return super().kill()
Пример #15
0
def generateBJetPrimary(jet_energy):
    '''
    Need to generate a b-hadron and some other primary tracks/particles
    Whilst ensuring they all share a common jet direction
    '''
    mPion = 140.
    mB = 5300.
    phi = np.pi / 4  #np.random.uniform(-np.pi,np.pi)
    theta = np.pi / 4  #np.random.uniform(0.,np.pi)
    B_energy = .8 * jet_energy  # an approximation of the 80% hadronization fraction of Bs
    B_momentum = np.sqrt(B_energy**2 - mB**2)
    candB = particle.Particle(mB, phi, theta, B_momentum)
    candB.setProperLifetime(1.5e-12)

    # this leaves 20% of the jet energy to assign to some light charged particles
    # done using two-decay methodology with virtual mass M
    # how many light particles is determined by a randomly assigning fractions of remainder energy
    energy_remainder = jet_energy - B_energy
    primary_particles = []
    while True:
        energy_frac_1 = np.random.uniform(8 * mPion, energy_remainder)
        if (energy_frac_1 < 16 * mPion):
            energy_frac_1 = energy_remainder
        primaryPion1, primaryPion2 = addTwoPrimaryTracks(
            energy_frac_1, phi, theta)
        energy_remainder -= energy_frac_1

        primary_particles.append(primaryPion1)
        primary_particles.append(primaryPion2)

        if (energy_remainder < 8 * mPion):
            #print("Error in energy measurement: " + str(energy_remainder / jet_energy))
            break

    return candB, primary_particles
Пример #16
0
    def special_stat_update(self, dt):
        # Regenerate
        self.health += self.get_stat("ship_regenerate") * dt

        self.bonus_attack_speed_time -= dt

        speed_factor = self.get_max_speed() / self.MAX_SPEED
        if speed_factor > 1:
            if self._timers['bonus_speed_particle_time'] > 0.15 / speed_factor:
                #e = explosion.Explosion(self.pos + helper.random_angle(), [PICO_BLUE, PICO_BLUE, PICO_BLUE, PICO_WHITE, PICO_WHITE, PICO_BLUE], 0.25, 3, line_width=1)
                colors = [
                    PICO_WHITE, PICO_BLUE, PICO_GREEN, PICO_PINK, PICO_PURPLE
                ]
                n = int((speed_factor - 1) * 3) + 1
                colors = colors[0:n]
                #ang = self.velocity.as_polar()[1] + 3.14159 + (random.random() - 0.5) * 3
                ang = (self.velocity.as_polar()[1] * 3.14159 / 180
                       ) + 3.14159 + (random.random() - 0.5) * 0.45 + math.sin(
                           self.time * 3 * speed_factor)
                if self.velocity.length_squared() == 0:
                    veln = V2(0, 0)
                else:
                    veln = helper.try_normalize(self.velocity)
                p = particle.Particle([random.choice(colors)], 1,
                                      self.pos + -veln * self.radius, 0.6,
                                      helper.from_angle(ang) * 8)
                self.scene.add_particle(p)
                self._timers['bonus_speed_particle_time'] = 0
Пример #17
0
    def __init__(self, surface, settings):
        self.surface = surface
        self.width = surface.get_width()
        self.height = surface.get_height()
        self.sprites = []
        self.particle = particle.Particle(surface)
        self.score = 0
        self.n_asteroids = 0
        self.text_y = 100
        self.settings = settings
        pygame.time.set_timer(self.SECOND_EVENT, 1000)

        # input state
        self.quit = False
        self.rotate_left = False
        self.rotate_right = False
        self.rotate_by = 0
        self.thrust = False
        self.info = False
        self.fire = False
        self.spawn = False
        self.show_particles = False
        self.enter = False
        self.next_level = False

        # the ship ... or none for no ship on screen
        self.player = None
        self.player_driver = None

        # countdown timer until next alien
        self.alien_time = random.randint(1000, 2000)
Пример #18
0
 def createParticleList(numberofParticles, volume: domain.Volume, speed,
                        mass, radius):
     return [
         particle.Particle(volume.randomPosition(), speed,
                           randomDirection(volume.dimensions), mass, radius)
         for x in range(numberofParticles)
     ]
Пример #19
0
    def __init__(self, surface):
        self.surface = surface
        self.width = surface.get_width()
        self.height = surface.get_height()
        self.sprites = []
        self.particle = particle.Particle(surface)
        self.score = 0
        self.n_asteroids = 0
        self.text_y = 100

        # input state
        self.quit = False
        self.rotate_left = False
        self.rotate_right = False
        self.rotate_by = 0
        self.thrust = False
        self.info = False
        self.fire = False
        self.spawn = False
        self.show_particles = True
        self.enter = False
        self.next_level = False

        # the ship ... or none for no ship on screen
        self.player = None

        # countdown timer until next alien
        self.alien_time = random.randint(1000, 2000)

        self.music_playing = True
        self.background_music = mixer.Sound(
            os.path.join("sounds", "hoarse_space_cadet.ogg"))
        self.background_channel = pygame.mixer.Channel(0)
        self.background_channel.play(self.background_music, loops=-1)
Пример #20
0
def main():
    search_space = s.Space(0.0, epsilon, 15, __function__)
    particles_vector = [
        p.Particle() for _ in range(search_space.num_particles)
    ]
    search_space.particles = particles_vector
    search_space.set_pbest()
    search_space.set_gbest()

    iteration = 0
    n_iterations = 1000
    val_prev = val_prev_1 = 0.0
    while iteration < n_iterations or search_space.gbest_value < epsilon:
        search_space.set_pbest()
        search_space.set_gbest()

        # JEŚLI PRZEZ TRZY ITERACJE NIE ZMIENI SIE WARTOŚĆ => BREAK
        if iteration == 0:
            val_prev = search_space.gbest_value
        else:
            val_prev_1 = val_prev
            val_prev = search_space.gbest_value

        print("POŁOŻENIE: ", search_space.gbest_position, " WARTOŚĆ: ",
              search_space.gbest_value)
        saveToFile(__function__, search_space.gbest_value)
        if abs(search_space.gbest_value - search_space.target
               ) <= search_space.epsilon or val_prev_1 == val_prev:
            break

        search_space.move_particles()
        iteration += 1
    print("Solution: ", search_space.gbest_position, " value ",
          search_space.gbest_value)
Пример #21
0
def random_initialize(nPartcles, BoxL, sigma):
    ptcls = [
        particle.Particle(uniform() * BoxL,
                          uniform() * BoxL, sigma,
                          uniform() * 2 * np.pi, BoxL)
        for _ in range(nPartcles)
    ]
    return ptcls
Пример #22
0
 def emit_thrust_particles(self):
     pvel = V2(random.random() - 0.5, random.random() - 0.5) * 5
     pvel += -self.velocity / 2
     p = particle.Particle(
         [PICO_WHITE, PICO_BLUE], 1,
         self.pos + -helper.try_normalize(self.velocity) * self.radius, 2,
         pvel)
     self.scene.add_particle(p)
Пример #23
0
 def generate_random_particle(self):
     """
     Generate a particle randomly within the bounds of map
     :return: a new particle instance
     """
     rospy.loginfo("Generating particles")
     x, y, theta = utils.generate_random_pose()
     return particle.Particle(x, y, theta, self.helper)
Пример #24
0
 def emit_thrust_particles(self):
     pvel = V2(random.random() - 0.5, random.random() - 0.5) * 5
     pvel += -self.velocity / 2
     p = particle.Particle(
         "assets/thrustparticle.png", 1,
         self.pos + -helper.try_normalize(self.velocity) * self.radius, 1,
         pvel)
     self.scene.add_particle(p)
Пример #25
0
	def __init__(self, num_particles, maxiter,no_of_nodes,start_node,end_node,graph,maximum_path_length):
	    
	    self.swarm=[]                                                    #array of paticle

        #####P is the Particle class

	    for i in range(0,num_particles):
	        self.swarm.append(P.Particle(no_of_nodes))  

	    self.global_best_cost=-1                                        #cost of Gbest
	    self.global_best_pos={}                                         #position of Gbest
	    self.global_path=[]                                             #decoded path corresponding to Gbest

	    i=0
	    while i < maxiter:
	        
	        for j in range(0,num_particles):
	           
	            # self.swarm[j].PrintParticle()
	            path=self.decode(self.swarm[j].position_i,graph,start_node,end_node,maximum_path_length)
	            
	            if path[-1]==end_node:
	                for x in path:
	                    print(x,end=" ")
	                print("\n")
	                self.swarm[j].counter=i
	                self.swarm[j].cost =self.cost_fun(graph,path)
	                ##if present cost is samller than cost of Pbest then update Pbest
	                if self.swarm[j].cost< self.swarm[j].cost_best_i:
	                	self.swarm[j].cost_best_i=self.swarm[j].cost
	                	self.swarm[j].pos_best_i =self.swarm[j].position_i
	                	self.swarm[j].path_loc = path
	               
	                
	            else:
	            	###if path is not valid then give penalty to the particle
	                self.swarm[j].cost=sys.maxsize
	                self.give_penalty(self.swarm[j],path)
	                
	        
	        ###update the Gbest
	        for j in range(0,num_particles):
	            if self.swarm[j].cost_best_i < self.global_best_cost or self.global_best_cost == -1:
	                self.global_best_pos=self.swarm[j].pos_best_i
	                self.global_best_cost=self.swarm[j].cost_best_i  
	                self.global_path = self.swarm[j].path_loc     


	        # cycle through swarm and update velocities and position
	        for j in range(0,num_particles):
	            if i-self.swarm[j].counter>=5:
	                self.swarm[j].reinitialize(i)
	                
	            else:
	                self.swarm[j].update_velocity(self.global_best_pos)
	                self.swarm[j].update_position()

	        i+=1
Пример #26
0
 def addparticle(self, particleline):
     if self.firstline is None:
         raise ValueError(
             "The first line for this event has not been set yet!")
     if self.done:
         raise ValueError(
             "finished() has already been called for this event, so no more particles can be added!"
         )
     particle.Particle(particleline, self)
Пример #27
0
 def createParticle(self, D, i):
     p = _particle.Particle(D, constantes.X_MIN(), constantes.X_MAX())
     b = _binarization.BinarizationStrategy(p.position_i,
                                            self.tTransferencia,
                                            self.tBinary)
     p.position_b = self.repara(b.get_binary())
     p.evaluate(self.costFunc, self.mcostos, self.mrestriccion, self.vrows,
                self.vcolumns)
     return p
Пример #28
0
def generateCJetPrimary(jet_energy):
    '''
    Need to generate a c-hadron and some other primary tracks/particles
    Whilst ensuring they all share a common jet direction
    '''
    mD = 2000.
    mPion = 140.
    phi = np.pi / 4
    theta = np.pi / 4
    D_energy = .5 * jet_energy  # an approximation of the 50% hadronization fraction of c
    D_momentum = np.sqrt(D_energy**2 - mD**2)
    candD = particle.Particle(mD, phi, theta, D_momentum)
    candD.setProperLifetime(1.0e-12)

    # Assign remainin energy to primary vertex tracks
    # randomly assigning fractions of remainder energy
    energy_remainder = 0.5 * jet_energy
    primary_particles = []

    # I have an idea to prevent the problem of trk distribution being only even
    if np.random.random() > 0.5:
        # randomly create a pion travelling along the jet axis? dunno...
        random_trk_E = 0.125 * jet_energy
        random_trk_mom = np.sqrt(random_trk_E**2 - mPion**2)
        jet_axis_pion = particle.Particle(mPion, phi, theta, random_trk_mom)
        primary_particles.append(jet_axis_pion)
        energy_remainder -= random_trk_E

    while True:
        energy_frac_1 = np.random.uniform(8 * mPion, energy_remainder)
        if (energy_frac_1 < 16 * mPion):
            energy_frac_1 = energy_remainder
        primaryPion1, primaryPion2 = addTwoPrimaryTracks(
            energy_frac_1, phi, theta)
        energy_remainder -= energy_frac_1

        primary_particles.append(primaryPion1)
        primary_particles.append(primaryPion2)

        if (energy_remainder < 8 * mPion):
            #print("Error in energy measurement: " + str(energy_remainder / jet_energy))
            break

    return candD, primary_particles
Пример #29
0
def innit_particles(num_particles=1000):
    # Initialize particles
    particles = []
    for i in range(num_particles):
        p = particle.Particle(500 * np.random.ranf() - 100,
                              500 * np.random.ranf() - 100,
                              2.0 * np.pi * np.random.ranf() - np.pi,
                              1.0 / num_particles)
        particles.append(p)
    return particles
Пример #30
0
def initialize(par_num, Lx, Ly, max_mass):
    for i in range(par_num):
        mass = random.randint(1, max_mass)
        vx = 0.0
        vy = 0.0
        x = random.uniform(-Lx, Lx)
        y = random.uniform(-Ly, Ly)
        part = pr.Particle(mass, x, y, vx, vy)
        pr.par_list.append(part)

    return pr.par_list