예제 #1
0
 def __init__(self, problem, _noParticles=POP_SIZE):
     self.noParticles = _noParticles
     self.v = []
     for i in range(self.noParticles):
         x = Particle()
         x.evaluate(problem)
         self.v.append(x)
예제 #2
0
    def collision(self):

        for collision in self.collision_ids:
            if collision == 'enemy' and not self.bullet_type == 'enemy_bullet':
                if len(Mediator.PARTICLES) < 25:
                    for i in range(random.randint(3, 6)):
                        Mediator.PARTICLES.append(
                            Particle(self.pos.copy(), self.vel.copy(), 'test'))
                self.remove()

            if collision == 'fast_enemy' and not self.bullet_type == 'fast_enemy_bullet':
                if len(Mediator.PARTICLES) < 25:
                    for i in range(random.randint(3, 5)):
                        Mediator.PARTICLES.append(
                            Particle(self.pos.copy(), self.vel.copy(), 'test'))

                self.remove()

            if collision == 'player' and not self.bullet_type == 'player_bullet':
                if len(Mediator.PARTICLES) < 25:
                    for i in range(random.randint(3, 5)):
                        Mediator.PARTICLES.append(
                            Particle(self.pos.copy(), self.vel.copy(), 'test'))

                self.remove()

        self.collision_ids.clear()
    def __init__(self, aCostFunction, aNumberOfParticles):

        super().__init__(aCostFunction);

        # Save the best particle at each iteration
        #self.best_solution_set = [];

        # Add a particle
        self.current_solution_set.append(Particle(self.objective_function.number_of_dimensions, self.objective_function.boundary_set, aCostFunction, self))

        # Keep track of the best particle
        best_particle_index = 0;

        # Create the particles
        while len(self.current_solution_set) < aNumberOfParticles:
            self.current_solution_set.append(Particle(self.objective_function.number_of_dimensions, self.objective_function.boundary_set, aCostFunction, self))

            # The new particle is better
            # Minimisation
            if self.current_solution_set[best_particle_index].cost > self.current_solution_set[-1].cost:
                best_particle_index = len(self.current_solution_set) - 1;

        # Store the best particle
        #self.best_solution_set.append(copy.deepcopy(best_particle))
        self.best_solution = self.current_solution_set[best_particle_index].copy();
예제 #4
0
 def __init__(self,
              npart=40,
              inertia=.5,
              phi=(2, 2, 2),
              dimensions=(100, 100),
              maxvelocity=1,
              Q=Problem1,
              inertiaPrime=1):
     self._inertia = inertia
     self.phi = phi
     self.globalBestFitness = 0
     self.maxvelocity = 1
     self.globalBest = None
     self.Q = Q
     self.inertiaPrime = inertiaPrime
     self.swarm = []
     #Create and initialize the swarm
     for i in range(npart):
         pos = np.zeros(len(dimensions))
         for j in range(len(dimensions)):
             pos[j] = random.randint(-1 * dimensions[j] / 2,
                                     dimensions[j] / 2)
         particle = Particle(pos, dimensions)
         fitness = particle.updateFitness(Q)
         if fitness > self.globalBestFitness or self.globalBestFitness == 0:
             self.globalBestFitness = fitness
             self.globalBest = particle.pos
         self.swarm.append(particle)
예제 #5
0
def draw():
    global particles
    background(0)

    if len(particles) == 0:  # catch for empty particle list
        particles.append(Particle(width, height, width / 2, height / 2))

    for n in reversed(range(len(particles))):
        particles[n].display()
        particles[n].update()
        particles[n].keep_inside_window()

        if key_is_pressed:
            wind = Wind(mouse_x, mouse_y)
            wind_force = wind.wind_force(particles[n].location)
            particles[n].applyForce(wind_force)

        if particles[n].is_dead:
            particles.pop(n)
            print(f"Particle {n+1} died")

        if len(particles) >= 20:
            particles.pop(0)
            return

        if mouse_is_pressed:
            particles.append(Particle(width, height, 500, 100))
            for m in range(len(particles)):
                particles[m].follow(mouse_x, mouse_y)
            print(f"there are {len(particles)} particles.")
            return
예제 #6
0
    def __init__(self):
        SceneBase.__init__(self)
        playerimage = pygame.transform.scale(pygame.image.load("Images/player.png"), (30, 30))
        # creates the Player character in the location 20, 20
        self.player = Player.Player(30, 30, playerimage)

        blueParticle = pygame.image.load("Images/particle_blue.png")
        redParticle = pygame.image.load("Images/particle_red.png")
        # Defines the starting positions of the first two Particles for level 1 of the game
        self.particle1 = Particle.Particle(100, 100, False, None, redParticle, False)
        self.particle2 = Particle.Particle(100, 200, True, self.particle1, blueParticle, False)  # Particle 2 is entangled to Particle one

        # Defines the position for the first goal for level 1 of the game
        self.goal = Goal.Goal(400, 400)

        # NOTE: Negative numbers in wall declarations ruin collision detection
        self.leftWall = Wall.Wall(0, 0, 20, 600)
        self.rightWall = Wall.Wall(780, 0, 20, 600)
        self.topWall = Wall.Wall(0, 0, 800, 20)
        self.bottomWall = Wall.Wall(0, 580, 800, 20)
        self.door = Door.Door(760, 300, 20, 100)
        self.walls=[self.leftWall,self.rightWall,self.bottomWall,self.topWall]

        # Defines the objects that the Player character cannot pass through
        self.entities = [self.player,self.particle1, self.particle2, self.leftWall, self.rightWall, self.topWall, self.bottomWall]
        self.particles=[self.particle1,self.particle2]
        self.startTime=int(round(time.time()))
        pygame.mixer.music.load('A Strange Charm.wav')
        pygame.mixer.music.play(-1)
    def __init__(self, aCostFunction, aNumberOfParticles, initial_guess=None):

        super().__init__(aCostFunction, initial_guess)

        # Name of the algorithm
        self.full_name = "Particle Swarm Optimisation"
        self.short_name = "PSO"
        self.number_created_children = 0

        # Add initial guess if any
        if not isinstance(self.initial_guess, NoneType):
            self.current_solution_set.append(
                PART.Particle(self.objective_function, self,
                              self.initial_guess))

        # Create the swarm
        while (self.getNumberOfParticles() < aNumberOfParticles):
            self.current_solution_set.append(
                PART.Particle(self.objective_function, self,
                              self.objective_function.initialRandomGuess()))

        # Number of new particles created
        self.number_created_particles = self.getNumberOfParticles()

        # Number of new particles moved
        self.number_moved_particles = 0

        # Store the best particle
        self.best_solution = None
        self.average_objective_value = None
        self.saveBestParticle()
예제 #8
0
    def update(self, measurement, measCovariance, measWeight):
        weights = map(lambda state: Particle.calculateWeight(
            state, measurement, measCovariance),
                      self.particleSet)  #extract weights from particles

        # normalize weights so they sum to 1 (numpy.random.choice won't work if this isn't true)
        weightSum = sum(weights)

        numSampled = int(self.numParticles * measWeight)
        # weighted sample (measWeight * numParticles) particles
        newParticleSet = []

        if weightSum == 0:  #all particle weights are 0
            numSampled /= 2  #trust this measurement less
            rospy.loginfo("weights summed to zero for " + str(measurement))
            newMeasCov = [[measCovariance[0][0], measCovariance[0][1]],
                          [measCovariance[1][0], measCovariance[1][1]]]
            newMeas = [measurement[0], measurement[1]]
            for i in range(numSampled):
                #randomly sample particles and replace positions with a sample from the measurement
                p = self.getRandomParticle(None)
                [nx, ny] = np.random.multivariate_normal(newMeas, newMeasCov)
                newParticleSet.append(
                    Particle.Particle(nx, ny, p.t, p.vt, p.vn, p.w, p.at,
                                      p.an))
        else:
            weights = map(lambda weight: weight / weightSum, weights)
            for i in range(numSampled):
                newParticleSet.append(self.getRandomParticle(weights))

        # uniformly randomly sample rest of particles
        for i in range(self.numParticles - numSampled):
            newParticleSet.append(self.getRandomParticle(None))

        self.particleSet = newParticleSet
예제 #9
0
class Event(object):
    a = Particle()
    b = Particle()
    time = 0.0
    countA = 0
    countB = 0

    def __init__(self, t, a, b):
        self.a = a
        self.b = b
        self.time = t
        if not a == None:
            self.countA = self.a.count()
        else:
            self.countA = -1
        if not b == None:
            self.countB = self.b.count()
        else:
            self.countB = -1

    def compareTo(self, that):
        that = Event()
        return self.time - that.time

    def isValid(self):
        if (self.a != None) and (self.a.count() != self.countA):
            return False
        if (self.b != None) and (self.b.count() != self.countB):
            return False
        return True
예제 #10
0
 def twobodyparticledecay(self,particle,products): # takes a list of two particles and decays them.
     
     ''' Get Produced hadron masses '''
     Decaytables = Decaydictionary.Decays()
     particle4vector = particle.Getvector4D()
     product1code = products[0]
     product2code = products[1]
     
     mass1 = Decaytables.Getmass(product1code)
     mass2 = Decaytables.Getmass(product2code)
     
    
     ''' Get boost class which contains useful boosting functions '''
     
     #print "boost in two body called"
     boost = Boosts.boost4D(particle4vector)
     
     ''' CMF mass of the string (mass of decaying object) '''
     cmsvector = boost.GetCMF()
     Mass = cmsvector[0]
     mom3 = Mass/2
     mom3 *= self.Sqrtlambda1(Mass,mass1,mass2)
     
     ''' Do the random angle generation '''
     randomphi = random.random()
     randomtheta = random.uniform(-1,1)
     phi = 2.*numpy.pi*randomphi
     sinphi = numpy.sin(phi)
     cosphi = numpy.cos(phi)
     theta = numpy.pi*randomtheta
     sintheta = numpy.sin(theta)
     costheta = numpy.cos(theta)
     
     ''' start setting the 4 vectors of the products '''
     
     mom = Fourvector.vector4D(0.,sintheta*cosphi,sintheta*sinphi,costheta)
     mom *= mom3
     E1 = numpy.sqrt(mass1*mass1+mom3*mom3)
     E2 = numpy.sqrt(mass2*mass2+mom3*mom3)
     finalvec1 = Fourvector.vector4D()
     finalvec1[0] = E1
     finalvec1 += mom
     finalvec2 = Fourvector.vector4D()
     finalvec2[0] = E2
     finalvec2 -= mom
     
     ''' Boost back into the lab frame '''
     print  "Is the crash here"
     finalvec1 = boost/finalvec1 #hadron
     finalvec2 = boost/finalvec2 #photon
     
     ''' Create the particles and return them in a list '''
     
     finalproduct1 = Particle.particle4D(product1code,finalvec1)
     finalproduct2 = Particle.particle4D(product2code,finalvec2)
     
     return [finalproduct1, finalproduct2]
예제 #11
0
 def plot_simple(self, key_x, key_y, colour='black'):
     plt.figure()
     plt.title(self.name)
     plt.xlabel(key_x)
     plt.ylabel(key_y)
     plt.scatter(self.values[:, Particle.what_index(key_x)],
                 self.values[:, Particle.what_index(key_y)],
                 marker='o',
                 color=colour)
     plt.show()
예제 #12
0
def CreateObject():
    TParticle = Particle.NewParticle(30)
    Particle.SetSprite(TParticle, "sp009")
    Particle.SetnDirection(TParticle, 1.0, 1.0, 0.0)
    Particle.SetCor(TParticle, 0.0, 0.0, -0.1)
    Particle.SetnColor(TParticle, 1.0, 0.8, 1.0, 1.0)
    Particle.SetkColor(TParticle, 1.0, 0.0, 0.0, 0.0)
    Particle.SetSpeed(TParticle, 4, 400, 400)
    Particle.SetLife(TParticle, 0.6)
    Particle.Init(TParticle)
    TempObject = GaoObject.NewGaoObject()
    GaoObject.SetShipType(TempObject, 3)
    GaoObject.SetExplosion(TempObject, "sp011", "sp012")
    GaoObject.SetName(TempObject, "DragonFly")
    GaoObject.SetModel(TempObject, "Ship1")
    GaoObject.SetTypeGun(TempObject, 2)
    GaoObject.SetParticlePos(TempObject, 1, 1, 0, 0)
    GaoObject.SetParamsHS(
        TempObject,
        30.0,  #Shield
        30.0,  #MaxShield
        0.5,  #SpeedRShield
        10.0,  #Health
        10.0,  #MaxHealth
        100.0,  #GunEnergy
        100.0,  #MaxGunEnergy
        0.6)  #SpeedRGunEnergy
    GaoObject.SetPFS(
        TempObject,
        14.0,  #Max Power
        1.0,  #Mass
        150)  #Speed Rotation

    GaoObject.WriteParticle(TempObject, TParticle)
    return TempObject
예제 #13
0
def Fire2():
    global fire_list, p

    #while loop for creating the particles
    p = 0
    while p < 5:
        fire = Particle() #create the object
        fire.img_number = random.randint(0,1) #random number for a random image particle
        fire.x = random.randint(fire2_pos_x,fire2_pos_x + 13) #set the x position of the fire to a random integer between 595 and 608
        fire.y = 25
        fire.vel_x = random.randint(-1,1)/2 #x velocity of the fire particle. Dividing by 2 to give a float
        fire.vel_y = random.randint(1,4) #y velocity of the fire particle.
        fire.size = random.randint(1,30) #random size of the fire particle.
        fire.opacity = 0.5
        
        fire_list.append(fire) #add the particle to the list

        p += 1 #increase the control variable by 1


    #while loop for drawing the fire particles with their respective velocities
    for fire in fire_list:
        fire.y += fire.vel_y #increase the y velocity of the fire particle by vel_y
        fire.x += fire.vel_x #increase the x velocity of the fire particle by vel_x
        
        fire.size -= 0.2 #decrease the size of the fire particle by 0.2
        fire.opacity -= 0.01 #decrease the opacity of the fire particle by 0.01

        jmss.drawImage(fire_img_list[fire.img_number], x = fire.x, y = fire.y, width = fire.size, height = fire.size, opacity = fire.opacity)        

        #once the fire particle gets above 110, delete it from the list
        if fire.y > max_fire_y:
            fire_list.remove(fire)        
예제 #14
0
 def input(self):
     for e in self.entities:
         e.handleInput()
         if e.health <= 0:
             explosion = Particle(None, None, ExplosionGraphics(self.screen, self.explosion))
             explosion.rect = e.rect
             explosion.centerx = e.rect.centerx - 100
             self.entities.remove(e)
             self.particles.append(explosion)
     for player in self.players:
         player.renew(self)
예제 #15
0
    def __init__(self, w, h, title):
        super(mySim, self).__init__(w, h, title)

        self.particle = []
        self.particle2 = []
        for i in range(100):
            self.particle.append(Particle.Particle())
        for i in range(100):
            self.particle2.append(Particle.Particle())

        self.initObjects()
예제 #16
0
    def __init__(self, w, h, title):
        super(mySim, self).__init__(w, h, title)
        self.steam = []
        self.particle = []
        for i in range(n):
            #self.particle.append(Particle.Particle())
            self.steam.append(Particle.Particle())

        for i in range(nn):
            self.particle.append(Particle.Particle())
        self.teapot = teapot.Teapot()
        self.initObjects()
예제 #17
0
 def predict(self, a):
     a = Particle()
     if a == None:
         return
     for i in range(len(self.particles)):
         dt = a.timeToHit(self.particles[i])
         e = Event(self.t + dt, a, self.particles[i])
         self.pq.insert(e)
     e1 = Event(self.t + a.timeToHitVerticalWall(), a, None)
     e2 = Event(self.t + a.timeToHitHorizontalWall(), None, a)
     self.pq.insert(e1)
     self.pq.insert(e2)
예제 #18
0
 def graph(c_l, color_l, key_x, key_y):
     fig, ax = plt.subplots()
     ax.set_xlabel(key_x)
     ax.set_ylabel(key_y)
     for i, c in enumerate(c_l):
         ax = plt.scatter(c.values[:, Particle.what_index(key_x)],
                          c.values[:, Particle.what_index(key_y)],
                          marker='o',
                          alpha=0.5,
                          color=color_l[i],
                          label=c.name)
     ax = plt.legend()
예제 #19
0
def random_scan():
    number_of_points_checked = 0
    number_of_points = 100
    accepted_points = []

    higgs_creator = Particle.ParticleCreator(Higgs.Higgs, "configs/higgs.json")
    scalar_creator = Particle.ParticleCreator(Scalar.Scalar, "configs/scalar.json")
    fermion_creator = Particle.ParticleCreator(Fermion.Fermion, "configs/fermion.json")
    neutrino_creator = Particle.ParticleCreator(NeutrinoCouplings.Neutrino, "configs/neutrino_couplings.json")

    time_start = time.time()
    time_last_report = 0
    time_report_interval = 5

    while len(accepted_points) < number_of_points:

        time_running = time.time() - time_start
        if time_running > time_last_report + time_report_interval:
            time_last_report = time_running
            print("[{:0.1f}]: Checked: {}({:0.2f}/s), Accepted: {}({:0.2f}/s)".format(
                time_running,
                number_of_points_checked,
                number_of_points_checked/time_running,
                len(accepted_points),
                len(accepted_points)/time_running)
            )

        model = ModelSPheno.ModelSPheno(
            higgs_creator.create(),
            fermion_creator.create(),
            scalar_creator.create(),
            neutrino_creator.create(),
            calculate_branching_ratios=False,
            calculate_one_loop_masses=True
        )

        number_of_points_checked += 1

        try:
            model.calculate_dependent_variables()
        except:
            continue

        micromegas = MicroMegas(model.spheno_output_file_path)
        micromegas.calculate()

        if random.random() < calculate_likelihood(model):
            accepted_points.append(model)
            with open("saved_models/{}.json".format(datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S.%f")), "w") as f:
                f.write(
                    json.dumps(model, default=lambda object: object.__dict__, sort_keys=True, indent=4)
                )
예제 #20
0
파일: PSOSandbox.py 프로젝트: mepaling/CI
 def __init__(self, poolSize=128, maxIter=50, phi1=0.5, phi2=0.5):
     self.poolSize = poolSize
     self.maxIteration = maxIter
     self.phi1 = phi1
     self.phi2 = phi2
     self.PSOList = []
     self.bestPSOList = []
     self.hasiter = 1
     self.bestPSO = Particle.Particle()
     for _ in range(poolSize):
         p = Particle.Particle()
         p.generate()
         self.PSOList.append(p)
예제 #21
0
def Rain():

    #while loop for creating the particles
    p = 0
    while p < 1:
        rain = Particle() #create the object
        rain.img = rain_img #image of the rain particle
        rain.x = random.randint(0,800) #set the x position of the rain to a random integer between 0 and 800
        rain.y = 600
        rain.vel_y = random.randint(-15,-10) #y velocity of the rain particle.
        rain.size = 30 #rain particle size
        rain.opacity = 1 #rain particle opacity
        
        rain_list.append(rain)

        p += 1

    #while loop for drawing the fire particles with their respective velocities
    for rain in rain_list:
        rain.y += rain.vel_y #decrease the y velocity of the rain particle by vel_y
        
        jmss.drawImage(rain.img, x = rain.x, y = rain.y, width = rain.size, height = rain.size, opacity = rain.opacity)        

        #once the rain particle gets below 0 (below the screen), delete it from the list
        if rain.y < 0:
            rain_list.remove(rain)
    def resample(self):
        """resample particles"""
        ## for resampling, a roulette wheel implementaion used.
        ## http://ais.informatik.uni-freiburg.de/teaching/ss11/robotics/slides/11-pf-mcl.ppt.pdf
        resampledparticles = []
        index = int(np.random.uniform() * self.noOfParticles)
        maxW = max(self.weights)
        beta = 0.0
        maxV = 0.0
        indexOfMaxV = 0

        for i in range(self.noOfParticles - 1):
            if (i % 8) == 0:
                index2 = int(np.random.uniform() * self.noOfParticles)
                resampledparticles.append(
                    Particle.Particle(random.random() * self.maze.dimX,
                                      random.random() * self.maze.dimY,
                                      random.random() * math.pi * 2))
                resampledparticles[i].set_noise(5.0, 1.0, 1.0)
            else:
                beta = beta + np.random.uniform() * 2 * maxW
                while self.particles[index].weight < beta:
                    beta = beta - self.particles[index].weight
                    index = (index + 1) % self.noOfParticles
                resampledparticles.append(
                    Particle.Particle(self.particles[index].x,
                                      self.particles[index].y,
                                      self.particles[index].orientation))
                resampledparticles[i].set_noise(5.0, 1.0, 1.0)
                #if(self.particles[index].weight>maxW):
                #maxW = self.particles[index].weight
                #indexOfMaxV = i
        '''get the best particle'''
        tempW = 0
        for i in range(self.noOfParticles):
            if (self.particles[i].weight > tempW):
                tempW = self.particles[i].weight
                indexOfMaxV = i
        bestParticle = Particle.Particle(
            self.particles[indexOfMaxV].x, self.particles[indexOfMaxV].y,
            self.particles[indexOfMaxV].orientation)
        bestParticle.set_noise(5.0, 1.0, 1.0)
        resampledparticles.append(bestParticle)
        self.bestParticle = bestParticle

        for p in resampledparticles:
            p.add_noise(self.maze.dimX, self.maze.dimY)
        self.particles = []
        self.particles = resampledparticles
예제 #23
0
def masslessmomenta(lop):
    noparts = len(lop)
    newlist = []
    for i in range(noparts):
        if lop[i].Checkgluon() == False: # not a gluon is a quark
            ''' do momenta boosting things here '''

            mass = lop[i].Getinvariantmass()
            #print mass, "mass in invariant mass"
            vec = copy.deepcopy(lop[i].Getvector())
            #print vec, "vec  before"
            p_2 = 0
            for j in range(1,4): # just go over the momentum values, try my scaling formula

                p_2 += (vec[j]*vec[j])

            al = numpy.sqrt((mass*mass + p_2) / p_2)
            newvector = Fourvector.vector4D(vec[0], al*vec[1],al*vec[2],al*vec[3])
            ID = lop[i].GetID()
            #print ID, "id of theparticle "
            newparticle = Particle.particle4D(ID,newvector)
            newlist.append(newparticle)

            #print newparticle.Getinvariantmass(), "check inv mass"
            

        if lop[i].Checkgluon() == True:
            newlist.append(lop[i])
    return newlist
def calcPSOReducer():
    index = 1
    #bestSwarm = pso.Particle("0;0;0;0;0;0;0;10000000000000;0;0;0");
    PSOLogger.info("calcPSO reducer method is started...")
    swarmArray = []
    for line in sys.stdin:
        line = line.replace("1\t", "")
        PSOLogger.info("===>line is\n%s" % (line))
        swarm = pso.Particle(line)

        if index == 1:
            bestSwarm = swarm
            index = 0
        PSOLogger.info("swarm.persBestVal = %s and bestSwarm.persBestVal=%s" %
                       (swarm.persBestVal, bestSwarm.persBestVal))

        if swarm.persBestVal < bestSwarm.persBestVal:
            bestSwarm = swarm
            #swarm.globalBestPos = bestSwarm.particlePosition
            #swarm.globalBestVal = bestSwarm.fitness
        swarmArray.append(swarm)
        '''
        swarm.updatePos();
        swarm.fitnessEval(mapper.fitnessFunc);
        swarm.updateVelocity();
        print swarm.strRepr()
        '''
    for newSwarm in swarmArray:
        newSwarm.globalBestPos = bestSwarm.particlePosition
        newSwarm.globalBestVal = bestSwarm.fitness
        newSwarm.updatePos()
        newSwarm.fitnessEval(mapper.fitnessFunc)
        newSwarm.updateVelocity()
        print newSwarm.strRepr()
예제 #25
0
def easy_generate_pts(initial_con):
    '''intial position and intial velocity randomized
    use analyitical field instead of discrete data
    npt: number of particles
    '''
    initial_pos = initial_con[0]
    initial_vel = initial_con[1]
    norbits = 1
    dt = 0.01
    data_dump_path = "/Users/a1/downloads"
    p = pt.particle(initial_pos,
                    initial_vel,
                    dt,
                    dump_size=100000000,
                    data_dump_path=data_dump_path,
                    write_data=False,
                    silent=False,
                    periodic=True)

    # maybe need to calculate the field once again using the interpolator? Guess not.
    p.set_boundaries(radius_max=10, z_max=5,
                     z_min=-5)  # this is for Spheromak and Harris Sheet
    p.step(getDoubleHarrisField, int(norbits / dt),
           getDoubleHarrisELectricField)
    return p
예제 #26
0
def pso(num_particles, k, w, c1, c2, max_iter, data, score_funcs=None):
    swarm = []  # List to hold particles of the swarm
    global_best = []  # Global best position
    global_fitness = sys.maxsize  # Fitness value of the global best position
    g_fit = []  # Fitness history of the global best position

    # Create particle swarm and initialize global best position
    for i in range(num_particles):
        # Make a new particle
        cur_particle = Particle.Particle(k, w, c1, c2, data)
        swarm.append(cur_particle)

        # As new particles are created update the global best position
        particle_fitness = cur_particle.fitness(data)
        if particle_fitness < global_fitness:
            global_best = cur_particle.position
            global_fitness = particle_fitness

        # Track the global best fitness at each iteration
        g_fit.append(global_fitness)

    # Run particle swarm
    for i in range(max_iter):
        # Update global fitness if a particle in the swarm has a local fitness that is better
        for particle in swarm:
            if particle.fitness_val < global_fitness:
                global_best = particle.position
                global_fitness = particle.fitness_val
        g_fit.append(global_fitness)

        # Update the position and velocity of the particle
        for particle in swarm:
            particle.update_particle(global_best, data)

    return g_fit
예제 #27
0
def confined_init_r(pts):
    confined = []
    for pt in pts:
        if pt.is_out_of_bounds() is False:
            confined.append(pt)
    confined_init_x = []
    confined_init_y = []
    confined_init_z = []
    for i in range(len(confined)):
        new_confined_r = confined[i].get_r()
        new_confined_init_r = new_confined_r[0]
        new_confined_init_x = new_confined_init_r[0]
        new_confined_init_y = new_confined_init_r[1]
        new_confined_init_z = new_confined_init_r[2]
        confined_init_x.append(new_confined_init_x)
        confined_init_y.append(new_confined_init_y)
        confined_init_z.append(new_confined_init_z)
    confined_init_x = np.asarray(confined_init_x)
    confined_init_y = np.asarray(confined_init_y)
    confined_init_z = np.asarray(confined_init_z)
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(confined_init_x, confined_init_y, confined_init_z)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    plt.show()
예제 #28
0
def init_speed_vs_final_distance(pts):
    speed_0 = []
    dist_f = []
    for pt in pts:
        new_v = pt.get_v()
        new_r = pt.get_r()
        dist_f.append(np.sqrt(np.dot(new_r[-1], new_r[-1])))
        speed_0.append(np.sqrt(np.dot(new_v[0], new_v[0])))
    speed_0, dist_f = np.asarray(speed_0), np.asarray(dist_f)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(speed_0, dist_f)
    ax.set_xlabel('init speed')
    ax.set_ylabel('final distance')
    ax.set_title('initial speed vs the final distance')
    plt.show()
예제 #29
0
def generate_pts_vary(initial_con):
    initial_pos = initial_con[0]
    initial_vel = initial_con[1]
    sigma = initial_con[2]
    by0 = initial_con[3]
    norbits = 2
    dt = 0.1
    data_dump_path = "/Users/a1/downloads"
    p = pt.particle(initial_pos,
                    initial_vel,
                    dt,
                    dump_size=100000000,
                    data_dump_path=data_dump_path,
                    write_data=False,
                    silent=False,
                    periodic=True,
                    sigma=sigma,
                    by0=by0)

    # maybe need to calculate the field once again using the interpolator? Guess not.
    p.set_boundaries(radius_max=10, z_max=5,
                     z_min=-5)  # this is for Spheromak and Harris Sheet
    #p.step(getDoubleHarrisField, int(norbits / dt), getDoubleHarrisELectricField)
    p.step_only_harris(getDoubleHarrisField, int(norbits / dt),
                       getDoubleHarrisELectricField)
    return p
예제 #30
0
def get_max_final_speed(pts):
    speed_f = []
    for pt in pts:
        new_v = pt.get_v()
        speed_f.append(np.sqrt(np.dot(new_v[-1], new_v[-1])))
    speed_f = np.asarray(speed_f)
    return np.amax(speed_f)
예제 #31
0
def avr_final_speed(pts):
    final_speed = []
    for pt in pts:
        new_v = pt.get_v()
        final_speed.append(np.sqrt(np.dot(new_v[-1], new_v[-1])))
    final_speed = np.asarray(final_speed)
    return np.average(final_speed)
예제 #32
0
    def resample(self):
        """
		Resampling is done if number of particles drops below a threshold
		:return: None
		"""

        theta = [0, -0.1, 0, 0.1, 0]

        if self.total_particles - len(self.particles) > (self.total_particles /
                                                         2):
            self.particles.sort(key=lambda x: -x.weight)
            new = list(self.particles)

            for j in range(self.total_particles - len(self.particles)):
                i = j % (len(self.particles))
                new.append(
                    Particle(
                        self.particles[i].pose.x + random.uniform(0.1, 0.2),
                        self.particles[i].pose.y + random.uniform(0.1, 0.2),
                        self.particles[i].pose.theta + random.choice(theta),
                        self.particles[i].weight))

            self.particles = new
        else:
            print('no resampling: ' + str(len(self.particles)))
예제 #33
0
	def __init__(self, npart = 40, inertia=.5, phi = (2, 2, 2), dimensions = (100, 100), maxvelocity=1, Q = Problem1, inertiaPrime = 1):
		self._inertia = inertia
		self.phi = phi
		self.globalBestFitness = 0
		self.maxvelocity = 1
		self.globalBest = None
		self.Q = Q
		self.inertiaPrime = inertiaPrime
		self.swarm = []
		#Create and initialize the swarm
		for i in range(npart):
			pos = np.zeros(len(dimensions))
			for j in range(len(dimensions)):
				pos[j] = random.randint(-1 * dimensions[j]/2, dimensions[j]/2)
			particle = Particle(pos, dimensions)
			fitness = particle.updateFitness(Q)
			if fitness > self.globalBestFitness or self.globalBestFitness == 0:
				self.globalBestFitness = fitness
				self.globalBest = particle.pos
			self.swarm.append(particle)
        elif opt == '-T':
            temperature = float(arg)
        elif opt == '-v':
            viscosity = float(arg)
        elif opt == '-x':
            flow_coefs[0] = float(arg)
        elif opt == '-y':
            flow_coefs[1] = float(arg)
        elif opt == '-z':
            flow_coefs[2] = float(arg)
    if ndim < 1 or ndim > 3:
        print 'Invalid number of dimensions.'
        sys.exit(1)

    # Get a track.
    small_sphere = Particle(ndim, radius, viscosity, temperature)
    small_sphere.add_bulk_flow(flow_coefs[:ndim], time_step, nsteps)

    # The flow is computed in get_diffusion when correcting for it.
    # No need to call get_bulk_flow.
    small_sphere.get_diffusion(flow=True)

    # Display some results:
    print 'Number of dimensions:', ndim
    print 'Number of steps:', nsteps
    print 'Radius of particles:', radius, 'um'
    print 'Viscosity of solution:', viscosity, 'Ps'
    print 'Temperature of solution:', temperature, 'K'
    print 'Time step:', time_step, 's'
    print
    print 'Theoretical diffusion:', small_sphere.diffusion.theory
예제 #35
0
 def threebodyparticledecay(self,decayingparticle,producthadrons): # product hadrons = list of particles (from chosendecay in hadrondecay module)
     
     decayingvector = decayingparticle.Getvector4D()
     hadron1code = producthadrons[0]
     hadron2code = producthadrons[1]
     hadron3code = producthadrons[2]
     
     Decaytables = Decaydictionary.Decays()
     m1 = Decaytables.Getmass(hadron1code)
     m2 = Decaytables.Getmass(hadron2code)
     m3 = Decaytables.Getmass(hadron3code)
             
     
     boost = Boosts.boost4D(decayingvector)
     cmsvector = boost.GetCMF()
     Mass = cmsvector[0]
     
     ''' PLACE HOLDER HERE TO TRY AND GET A RESULT. NOT TOO CONCERNED ABOUT MOMENTA YET '''
     finalvec1 = Fourvector.vector4D(m1,0,0,0)
     finalvec2 = Fourvector.vector4D(m2,0,0,0)
     finalvec3 = Fourvector.vector4D(m3,0,0,0)
     
     product1 = Particle.particle4D(hadron1code,finalvec1)
     product2 = Particle.particle4D(hadron2code,finalvec2)
     product3 = Particle.particle4D(hadron3code,finalvec3)
     
     return [product1,product2,product3]
    
     while True:
         print "ARE WE STUCK IN THE TIME WARP LOOP. 3 - BODY DECAY"
         
         
         ''' Constrain m12 '''
         
         m12_min = m1 + m2
         m12_max = Mass - m3
         
         D_m12 = m12_max - m12_min
         rng = random.random()
         
         m12 = m12_min + rng * D_m12 # select a number randomly (uniform) between m12min and m12max.
         
         ''' Use m12 to constrain m23 '''
         
         E2 = (m12*m12 - m1*m1 + m2*m2) / (2*m12) # the energy of particle 2 in the rest frame of m12
         E3 = (Mass*Mass - m12*m12 - m3*m3) / (2*m12) # same but for 3
         
         m23_min = (E2 + E3)*(E2 + E3) - (numpy.sqrt(E2*E2 - m2*m2) + numpy.sqrt(E3*E3 - m3*m3))**2 # these two are m23 squared
         m23_max = (E2 + E3)*(E2 + E3) - (numpy.sqrt(E2*E2 - m2*m2) - numpy.sqrt(E3*E3 - m3*m3))**2
         
         D_m23 = numpy.sqrt(m23_max) - numpy.sqrt(m23_min)
         
         rng2 = random.random()
         
         m23 = numpy.sqrt(m23_min) + rng2 * D_m23
         
         ''' Calculate m13 from m12, m23 '''
         
         m13_2 = Mass*Mass + m1*m1 + m2+m2 + m3*m3 - m12*m12* - m23*m23
         m13 = numpy.sqrt(m13_2)
         
         ''' Hardcode the momenta functions ''' # Can use lambda as well to get the expressions
         
         p1 = (Mass/2) * self.Sqrtlambda1(Mass,m23,m1)
         #print p1, "p1"
         p2 = (Mass/2) * self.Sqrtlambda1(Mass,m13,m2)
         #print p2, "p2"
         p3 = (Mass/2) * self.Sqrtlambda1(Mass,m12,m3)
         #print p3, "p3"        
         
         ''' Generate the angles phi is isotropic '''
         
         randomphi = random.random()
         phi = 2.*numpy.pi*randomphi
         sinphi = numpy.sin(phi)
         cosphi = numpy.cos(phi)
         
         ''' Generate the thetas in the plane of decay '''
         
         # First momentum theta is random.
         
         randomtheta1 = random.uniform(-1,1)
         theta1 = numpy.pi*randomtheta1
         sintheta1 = numpy.sin(theta1)
         costheta1 = numpy.cos(theta1)
         
         # Second is also random, and helps determine the second. However have to generate sensible / possible angles
         for i in range(100):
             randomtheta2 = random.uniform(-1,1)
             theta2 = numpy.pi*randomtheta2
             sintheta2 = numpy.sin(theta2)
             costheta2 = numpy.cos(theta2)
             
             # Third constrained by the first two in order to balance momentum.
             
             sintheta3 = (-p1*sintheta1 - p2*sintheta2) / p3
             costheta3 = (-p1*costheta1 - p2*costheta2) / p3
             
             
             
             if abs(sintheta3) <= 1 and abs(costheta3) <= 1:
                 
                 ''' Build the 4 vectors '''
                 
                 vecE1 = numpy.sqrt(m1*m1 + p1*p1)
                 #print vecE1, "vecE1"
                 vecE2 = numpy.sqrt(m2*m2 + p2*p2)
                 #print vecE2, "vecE2"
                 vecE3 = numpy.sqrt(m3*m3 + p3*p3)
                 #print vecE3, "vecE3"
                 
                 finalvec1 = Fourvector.vector4D(vecE1,p1*sintheta1*cosphi,p1*sintheta1*sinphi,costheta1)
                 finalvec1 = boost/finalvec1
                 
                 finalvec2 = Fourvector.vector4D(vecE2,p2*sintheta2*cosphi,p2*sintheta2*sinphi,costheta2)
                 finalvec2 = boost/finalvec2
                 
                 finalvec3 = Fourvector.vector4D(vecE3,p3*sintheta3*cosphi,p3*sintheta3*sinphi,costheta3)
                 finalvec3 = boost/finalvec3
                 
                 
                 ''' Construct the particles '''
                 product1 = Particle.particle4D(hadron1code,finalvec1)
                 product2 = Particle.particle4D(hadron2code,finalvec2)
                 product3 = Particle.particle4D(hadron3code,finalvec3)
                 
                 return [product1,product2,product3]
예제 #36
0
      particle.w_inertia = .9 * particle.w_inertia

      Cf = 1.0 / pso_data.Ns 
      for dim in xrange(particle.Ndimensions):
        minp, maxp = particle.positionMinMaxList[dim]
        particle.velocityMax[dim] = Cf * (maxp - minp)

  if pso_data.current_iteration >= pso_data.max_iterations:
    RETURNVALUE = 2 # Codes seem kinda lame here

  print "Updating particle velocities and positions."
  # Update each of the particles with the record of how it's done.
  for ndx, res in enumerate(pso_data.current_particle_results):
    pso_data.particle_list[ndx].setFitness( res )

  bestparticle = Particle.determineBestParticle(pso_data.particle_list)

  print "Updated Positions:"
  for p_ndx, particle in enumerate(pso_data.particle_list):

    print "Particle %d Pre: \n\tPosition - %s, \n\tVelocity - %s" % (p_ndx, particle.position, particle.velocity)
    particle.updateVelocity(bestparticle)
    particle.updatePosition()
    print "Particle %d Post: \n\tPosition - %s, \n\tVelocity - %s" % (p_ndx, particle.position, particle.velocity)

  
  epopt.appendParticlePositionsToDisk( pso_data.OutputFile, pso_data.current_iteration, pso_data.particle_list)    
  pso_data.current_particle_results = []

# 
# pso is in the correct state, so we prepare a file of results to
        elif opt == '-n':
            nsteps = int(arg)
        elif opt == '-q':
            quiet = True
        elif opt == '-t':
            time_step = float(arg)
        elif opt == '-T':
            temperature = float(arg)
        elif opt == '-v':
            viscosity = float(arg)
    if ndim < 1 or ndim > 3:
        print 'Invalid number of dimensions.'
        sys.exit(1)

    # Get a track.
    small_sphere = Particle(ndim, radius, viscosity, temperature)
    small_sphere.generate_motion(nsteps, time_step)

    # Display some results:
    small_sphere.get_diffusion()

    print 'Number of dimensions:', ndim
    print 'Number of steps:', nsteps
    print 'Radius of particles:', radius, 'um'
    print 'Viscosity of solution:', viscosity, 'Ps'
    print 'Temperature of solution:', temperature, 'K'
    print 'Time step:', time_step, 's'
    print
    print 'Theoretical diffusion:', small_sphere.diffusion.theory
    print 'Diffusion:', small_sphere.diffusion.data
    print 'Standard error:', small_sphere.diffusion.std_err
예제 #38
0
파일: Space.py 프로젝트: anst/space
background = pygame.Surface((800, 600))
background.fill(background_color)

clock = pygame.time.Clock()

menu = Menu()

END_MUSIC_EVENT = pygame.USEREVENT + 0
pygame.mixer.music.set_endevent(END_MUSIC_EVENT)
sound = pygame.mixer.Sound("background.wav")
sound.play()

logic = Logic(pygame, screen)

ship = Ship(pygame, screen)
particle = Particle(pygame, screen,logic,0,0)

handler = EventHandler()

while clear():
  for event in pygame.event.get():
    if event.type == QUIT:
      sys.exit()
    elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
      handler.handle(event, pygame, screen, ship)
    elif event.type == END_MUSIC_EVENT and event.code == 0:
      sound.play()
  logic.hit_ship()
  if logic.win_game():
    clear()
    menu.draw_winner(pygame,screen,logic.score)
예제 #39
0
파일: Init.py 프로젝트: vimov/Deployer
def init():
  Ur.init()
  AbInitio.init()
  Particle.init()
  AttributeGroup.init()
  GroupInit()
  FSM.init()
  lfInit()
  Element.init()
  Component.init()
  List.init()
  elts.Init.init()
  validate.veInit()
  # Could this be computed from the reflectedName property of the types -- does
  # Python give access to the class hierarchy top-down?
  psviIndMap.update({'schema':DumpedSchema,
            'atomic':(SimpleType,AbInitio.AbInitio),
            'list':(SimpleType,List.List),
            'union':(SimpleType,Union),
            'complexTypeDefinition':ComplexType,
            'attributeUse':AttributeUse,
            'attributeDeclaration':Attribute,
            'particle':Particle.Particle,
            'modelGroupDefinition':(Group,ModelGroup),
            'modelGroup':Group,
            'elementDeclaration':Element.Element,
            'wildcard':Wildcard,
            'annotation':None,
            'enumeration':Enumeration,
            'whiteSpace':Whitespace,
            'pattern':Pattern,
            'maxInclusive':MaxInclusive,
            'minInclusive':MinInclusive,
            'fractionDigits':FractionDigits,
            'precision':Precision,
            'lexicalMappings':LexicalMappings,
            'attributeGroupDefinition':AttributeGroup.AttributeGroup,
            'key':Key,
            'keyref':Keyref,
            'unique':Unique,
            'xpath':xpathTemp})
  auxComponentMap.update({'namespaceSchemaInformation':namespaceSchemaInformation,
                          'valueConstraint':valueConstraint,
                          'namespaceConstraint':namespaceConstraint,
                          'contentType':contentType,
                          'schemaDocument':schemaDocument})
  _Nmtoken=("1.0",u'[-.:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u0131\u0134-\u013e\u0141-\u0148\u014a-\u017e\u0180-\u01c3\u01cd-\u01f0\u01f4-\u01f5\u01fa-\u0217\u0250-\u02a8\u02bb-\u02c1\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d6\u03da\u03dc\u03de\u03e0\u03e2-\u03f3\u0401-\u040c\u040e-\u044f\u0451-\u045c\u045e-\u0481\u0490-\u04c4\u04c7-\u04c8\u04cb-\u04cc\u04d0-\u04eb\u04ee-\u04f5\u04f8-\u04f9\u0531-\u0556\u0559\u0561-\u0586\u05d0-\u05ea\u05f0-\u05f2\u0621-\u063a\u0641-\u064a\u0671-\u06b7\u06ba-\u06be\u06c0-\u06ce\u06d0-\u06d3\u06d5\u06e5-\u06e6\u0905-\u0939\u093d\u0958-\u0961\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ae0\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b36-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60-\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0-\u0ce1\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60-\u0d61\u0e01-\u0e2e\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eae\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0f40-\u0f47\u0f49-\u0f69\u10a0-\u10c5\u10d0-\u10f6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110b-\u110c\u110e-\u1112\u113c\u113e\u1140\u114c\u114e\u1150\u1154-\u1155\u1159\u115f-\u1161\u1163\u1165\u1167\u1169\u116d-\u116e\u1172-\u1173\u1175\u119e\u11a8\u11ab\u11ae-\u11af\u11b7-\u11b8\u11ba\u11bc-\u11c2\u11eb\u11f0\u11f9\u1e00-\u1e9b\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2126\u212a-\u212b\u212e\u2180-\u2182\u3041-\u3094\u30a1-\u30fa\u3105-\u312c\uac00-\ud7a3\u4e00-\u9fa5\u3007\u3021-\u30290-9\u0660-\u0669\u06f0-\u06f9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be7-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05a1\u05a3-\u05b9\u05bb-\u05bd\u05bf\u05c1-\u05c2\u05c4\u064b-\u0652\u0670\u06d6-\u06dc\u06dd-\u06df\u06e0-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0901-\u0903\u093c\u093e-\u094c\u094d\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09bc\u09be\u09bf\u09c0-\u09c4\u09c7-\u09c8\u09cb-\u09cd\u09d7\u09e2-\u09e3\u0a02\u0a3c\u0a3e\u0a3f\u0a40-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a70-\u0a71\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0b01-\u0b03\u0b3c\u0b3e-\u0b43\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b82-\u0b83\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c82-\u0c83\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d43\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86-\u0f8b\u0f90-\u0f95\u0f97\u0f99-\u0fad\u0fb1-\u0fb7\u0fb9\u20d0-\u20dc\u20e1\u302a-\u302f\u3099\u309a\xb7\u02d0\u02d1\u0387\u0640\u0e46\u0ec6\u3005\u3031-\u3035\u309d-\u309e\u30fc-\u30fe]+')
  _Nmtoken11=("1.1",u'[-.0-9:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]+')
  _Name=("1.0",u'[_:A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u0131\u0134-\u013e\u0141-\u0148\u014a-\u017e\u0180-\u01c3\u01cd-\u01f0\u01f4-\u01f5\u01fa-\u0217\u0250-\u02a8\u02bb-\u02c1\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d6\u03da\u03dc\u03de\u03e0\u03e2-\u03f3\u0401-\u040c\u040e-\u044f\u0451-\u045c\u045e-\u0481\u0490-\u04c4\u04c7-\u04c8\u04cb-\u04cc\u04d0-\u04eb\u04ee-\u04f5\u04f8-\u04f9\u0531-\u0556\u0559\u0561-\u0586\u05d0-\u05ea\u05f0-\u05f2\u0621-\u063a\u0641-\u064a\u0671-\u06b7\u06ba-\u06be\u06c0-\u06ce\u06d0-\u06d3\u06d5\u06e5-\u06e6\u0905-\u0939\u093d\u0958-\u0961\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ae0\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b36-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60-\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0-\u0ce1\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60-\u0d61\u0e01-\u0e2e\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eae\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0f40-\u0f47\u0f49-\u0f69\u10a0-\u10c5\u10d0-\u10f6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110b-\u110c\u110e-\u1112\u113c\u113e\u1140\u114c\u114e\u1150\u1154-\u1155\u1159\u115f-\u1161\u1163\u1165\u1167\u1169\u116d-\u116e\u1172-\u1173\u1175\u119e\u11a8\u11ab\u11ae-\u11af\u11b7-\u11b8\u11ba\u11bc-\u11c2\u11eb\u11f0\u11f9\u1e00-\u1e9b\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2126\u212a-\u212b\u212e\u2180-\u2182\u3041-\u3094\u30a1-\u30fa\u3105-\u312c\uac00-\ud7a3\u4e00-\u9fa5\u3007\u3021-\u3029][-._:A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u0131\u0134-\u013e\u0141-\u0148\u014a-\u017e\u0180-\u01c3\u01cd-\u01f0\u01f4-\u01f5\u01fa-\u0217\u0250-\u02a8\u02bb-\u02c1\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d6\u03da\u03dc\u03de\u03e0\u03e2-\u03f3\u0401-\u040c\u040e-\u044f\u0451-\u045c\u045e-\u0481\u0490-\u04c4\u04c7-\u04c8\u04cb-\u04cc\u04d0-\u04eb\u04ee-\u04f5\u04f8-\u04f9\u0531-\u0556\u0559\u0561-\u0586\u05d0-\u05ea\u05f0-\u05f2\u0621-\u063a\u0641-\u064a\u0671-\u06b7\u06ba-\u06be\u06c0-\u06ce\u06d0-\u06d3\u06d5\u06e5-\u06e6\u0905-\u0939\u093d\u0958-\u0961\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ae0\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b36-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60-\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0-\u0ce1\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60-\u0d61\u0e01-\u0e2e\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eae\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0f40-\u0f47\u0f49-\u0f69\u10a0-\u10c5\u10d0-\u10f6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110b-\u110c\u110e-\u1112\u113c\u113e\u1140\u114c\u114e\u1150\u1154-\u1155\u1159\u115f-\u1161\u1163\u1165\u1167\u1169\u116d-\u116e\u1172-\u1173\u1175\u119e\u11a8\u11ab\u11ae-\u11af\u11b7-\u11b8\u11ba\u11bc-\u11c2\u11eb\u11f0\u11f9\u1e00-\u1e9b\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2126\u212a-\u212b\u212e\u2180-\u2182\u3041-\u3094\u30a1-\u30fa\u3105-\u312c\uac00-\ud7a3\u4e00-\u9fa5\u3007\u3021-\u30290-9\u0660-\u0669\u06f0-\u06f9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be7-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05a1\u05a3-\u05b9\u05bb-\u05bd\u05bf\u05c1-\u05c2\u05c4\u064b-\u0652\u0670\u06d6-\u06dc\u06dd-\u06df\u06e0-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0901-\u0903\u093c\u093e-\u094c\u094d\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09bc\u09be\u09bf\u09c0-\u09c4\u09c7-\u09c8\u09cb-\u09cd\u09d7\u09e2-\u09e3\u0a02\u0a3c\u0a3e\u0a3f\u0a40-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a70-\u0a71\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0b01-\u0b03\u0b3c\u0b3e-\u0b43\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b82-\u0b83\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c82-\u0c83\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d43\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86-\u0f8b\u0f90-\u0f95\u0f97\u0f99-\u0fad\u0fb1-\u0fb7\u0fb9\u20d0-\u20dc\u20e1\u302a-\u302f\u3099\u309a\xb7\u02d0\u02d1\u0387\u0640\u0e46\u0ec6\u3005\u3031-\u3035\u309d-\u309e\u30fc-\u30fe]*')
  _Name11=("1.1",u'[:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd][-.0-9:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]*')
  _language="([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]+)(-[a-zA-Z]{1,8})*"
  _NCName="[^:]*"
  builtinPats.extend([_Name,_Name11,_Nmtoken,_Nmtoken11,_language,_NCName])
  builtinTypeNames.extend([
    ('normalizedString','string',((Whitespace,"replace"),),0),
    ('token','normalizedString',((Whitespace,"collapse"),),0),
    ('language','token',
    ((Pattern,[_language]),),0),
    ('NMTOKEN','token',((Pattern,[_Nmtoken,_Nmtoken11]),),0),
    ('Name','token',((Pattern,[_Name,_Name11]),),0),
    ('NCName','Name',((Pattern,[_NCName]),),0),
    ('ID','NCName',(),1), ('IDREF','NCName',(),2), ('ENTITY','NCName',(),0),
    ('aPDecimal','pDecimal',((LexicalMappings,['nodecimal', 'decimal']),
                             (Precision,0)),0),
    ('integer','decimal',((FractionDigits,0),),0),
    ('nonPositiveInteger','integer',((MaxInclusive,0),),0),
    ('negativeInteger','nonPositiveInteger', ((MaxInclusive,-1),),0),
    ('long','integer',((MinInclusive,-9223372036854775808L),
    (MaxInclusive,9223372036854775807L)),0),
    ('int','long',((MinInclusive,-2147483648L),(MaxInclusive,2147483647)),0),
    ('short','int',((MinInclusive,-32768),(MaxInclusive,32767)),0),
    ('byte','short',((MinInclusive,-128),(MaxInclusive,127)),0),
    ('nonNegativeInteger','integer',((MinInclusive,0),),0),
    ('unsignedLong','nonNegativeInteger',((MaxInclusive,18446744073709551615L),),0),
    ('unsignedInt','unsignedLong',((MaxInclusive,4294967295L),),0),
    ('unsignedShort','unsignedInt',((MaxInclusive,65535),),0),
    ('unsignedByte','unsignedShort',((MaxInclusive,255),),0),
    ('positiveInteger','nonNegativeInteger',((MinInclusive,1),),0)])

  XSV.NCNamePat = re.compile("(%s)$"%_Name[1]);
  XSV.NCNamePat11 = re.compile("(%s)$"%_Name11[1]);
예제 #40
0
    def Decaystring(self,decayingstring,decayingquarknumber,hadronproducedID): #class that takes an (unboosted) mrs as an arguement and decays it, producing a particle and a new iteration of string.
        ''' NOTE - DECAYING SIDE ONLY CARES IF THE NUMBER IS POSITIVE OR NEGATIVE - I.E. PDG CODE OF QUARK / ANTIQUARK REPSECTIVELY '''
        #print "decaystring class reached"
        Decaytables = Decaydictionary.Decays()
        twobodyclass = Twobodydecay.twobodydecay4D()
        hadroncodetest = PDG_ID.PDG_Type(hadronproducedID)
        
        if hadroncodetest.isBaryon() is True:
            if self.__qPDG.isQuark() or self.__qbarPDG.isQuark() is True:
                baryonproducts = self.Baryonproduction(hadronproducedID,decayingquarknumber)
                if baryonproducts[1] == 0:
                    stringcontent = [baryonproducts[0],self.__qbarID]
                    #print stringcontent, "IS THERE SOMETHING WRONG HERE"
                if baryonproducts[1] == 1:
                    stringcontent = [self.__qID, baryonproducts[0]]
                    #print stringcontent, "HOW ABOUT HERE, IS THERE ERROR"
        
        ''' If the produced particle is a diquark i.e. producing diquarks at the ends of the string. just need to redistribute momentum via a two body decay '''
        if hadroncodetest.isDiquark() is True: # i.e. we're producing two diquarks, one at each end of the string
            recievingdiquark = self.Finddiquarkstringcontent(decayingquarknumber,hadronproducedID)
            #print recievingdiquark, "RECIEVINGDIQUARK"
            newstring = twobodyclass.Twobodydiquarks(decayingstring,hadronproducedID,recievingdiquark) # produce a new string, hadronproduced ID here is a DIQUARK.
            adc = Availabledecays.availabledecays4D(newstring)# AVAILABLE DECAY CLASS
            newproducts = adc.Finddecay()
            
            ''' Assign the new values to the parameters in the code. now producing a baryon from a diquark end '''
            decayingquarknumber = newproducts[0]
            #print decayingquarknumber, "DECAYINGQUARK NUMBER IN THE BARYONPROD"
            hadronproducedID = newproducts[1]   
            #print hadronproducedID, "HADRONPRODUCED ID IN THE BAREEREREREOWIJIW3ERJIOWEJ"     
            #print PDG_ID.PDG_Type.mass(PDG_ID.PDG_Type(hadronproducedID)), "HADRON MASS IN THE BARREEEEEE"
            #print "SUCESSFULLY DETERMINED A MASS"
            
            stringcontent = self.Getbaryonstringcontent(hadronproducedID,decayingquarknumber,recievingdiquark) # takes the (baryon, diquark) IDs. that have just been found
            decayingstring = copy.deepcopy(newstring)
            #print stringcontent, "stringcontent from the module"
            
            
            
        ''' If the produced particle is a meson, leaves behind a quark remnant at the end of the string '''
        
        if hadroncodetest.isMeson() is True:
            stringcontent = self.Findstringcontent(decayingquarknumber,hadronproducedID) # finds [quark, antiquark] of the string
            #print stringcontent, "DO WE GOT A PROBLEM HERE"
         
        ''' Get out the string information (ie the quark information) '''
        boostedstring = self.Booststringforward(decayingstring)
        quark1 = boostedstring.Getq()
        antiquark1 = boostedstring.Getqbar()
        quark1vector4D = quark1.Getvector4D()
        antiquark1vector4D = antiquark1.Getvector4D()
       
        ''' define particle produced values ''' # Initialise the particle for manipulation later. (hadron is object k)
        hadronmomentum = Fourvector.vector4D(1.,1.,1.,1.) # placeholder (used for class creation), is reset later
        hadron = Particle.particle4D(hadronproducedID,hadronmomentum)
        hadronmass = hadron.Getmass()
        
        '''Create p+, p-'''
        #print antiquark1vector4D.Getvector(), "#PRINT VECOTRS"
        #print quark1vector4D.Getvector()
        if quark1vector4D[3] < 0:
            p_plus = quark1vector4D[0] - quark1vector4D[3]
            p_minus = antiquark1vector4D[0] + antiquark1vector4D[3]  
            
        if quark1vector4D[3] > 0:
            p_plus = quark1vector4D[0] + quark1vector4D[3]
            p_minus = antiquark1vector4D[0] - antiquark1vector4D[3]  
        
        ''' Find the quark content of the string '''
        
            
        
        
        #print stringcontent[0], "stringcontent 0 "
        #print stringcontent[1], "stringcontent 1 "           
        
        ''' Try 100 hundred times to get a successful kperp and z value for the current string decay '''
        n = 0
        while True:
            n = n+1
            ##print "Are we stuck"
            #print "stringmass", boostedstring.Getstringmass()
            #print "hadronmass", hadronmass
            #print antiquark1vector4D.Getvector(), "#PRINT VECOTRS"
            #print quark1vector4D.Getvector()
        
            ''' Get k perp value '''
            kperp = self.Getkperphitmiss(boostedstring) # 0.305
            #print kperp, "kperp"
        
            ''' Get z value '''
            z_plus = self.Getzhitmiss(boostedstring,kperp,hadronmass) # 0.24
            z_minus = 1 - z_plus
            #print z_plus, "z_plus"
        
            ''' Create the k+- values '''
            k_plus = z_plus*p_plus
            k_minus = (hadronmass*hadronmass + kperp*kperp) / (z_plus*p_plus)
            ##print k_plus, "k_plus"
            ##print k_minus, "k_minus"
        
            ''' Create the angles for future resolving '''
            ''' phi is isotropic, and taken as angle to the quark. pi is added to phi to get the hadron angle '''
            q_phi = 2*numpy.pi*random.random()
            k_phi = q_phi + numpy.pi
            qnew_cosphi = numpy.cos(q_phi)
            qnew_sinphi = numpy.sin(q_phi)
            k_cosphi = numpy.cos(k_phi)
            k_sinphi = numpy.sin(k_phi)
             
            ''' Create the final vectors '''
            qnew_plus = z_minus * p_plus
            #print z_minus
            #print p_plus, "P PLUS"
            qnew_minus = (kperp*kperp) / (z_minus * p_plus)
        
            ''' Arrange arrays of [p+, p_, pcostheta, psintheta] '''
            qnew = [qnew_plus, qnew_minus, kperp*qnew_cosphi, kperp*qnew_sinphi]
            #print qnew, "QNEW"
            knew = [k_plus, k_minus, kperp*k_cosphi, kperp*k_sinphi]
            #print knew, "KNEW"
            antiqnew = [0,p_minus - k_minus - qnew_minus, 0, 0]
            #print antiqnew, "ANTIQNEW"
            
            ''' From the arrays constructed above, create the vectors E,p '''
            
            ''' Start with the particle '''
            k_E = (k_plus + k_minus) /2
            k_px = knew[2]
            k_py = knew[3]
            k_pz = (k_plus - k_minus) /2
            kmom = Fourvector.vector4D(k_E,k_px,k_py,k_pz)
            
            ''' And now for the quark in the string '''
            q_E = (qnew[0]+qnew[1])/2
            q_px = qnew[2]
            q_py = qnew[3]
            q_pz = (qnew[0]-qnew[1])/2
            qmom = Fourvector.vector4D(q_E,q_px,q_py,q_pz)
            
            ''' And now for the antiquark in the string '''
            antiq_E = (antiqnew[0] + antiqnew[1]) /2
            antiq_px = antiqnew[2]
            antiq_py = antiqnew[3]
            antiq_pz = (antiqnew[0] - antiqnew[1]) /2
            antiqmom = Fourvector.vector4D(antiq_E,antiq_px,antiq_py,antiq_pz) 
            
            ''' Testing the dynamics of the system - momentum should be conserved ''' 
            totalmom = antiqmom+qmom+kmom
            ##print p_plus*p_minus, "total cmf momentum of the system originally, i.e. 2E"
            ##print totalmom*totalmom, "Invariant mass squared of the final system"   
            
            ''' Now need to boost the system back into the lab frame '''
            ''' Adjust the quarks and create a new string, and boost to lab frame '''
            #print stringcontent, "STRINGCONTENT"
            quark2 = Particle.particle4D(float(stringcontent[0]),quark1.Getvector4D())
            #print hadronproducedID, "HADRON ID"
            ##print stringcontent[1], "ANTI QUARK NUMBER"

            antiquark2 = Particle.particle4D(float(stringcontent[1]),antiquark1.Getvector4D())
            quark2.Setmom(qmom)
            antiquark2.Setmom(antiqmom)
            quark1.Setmom(qmom)
            antiquark1.Setmom(antiqmom)
            newstring = MRS.mrs4D(quark2,antiquark2)
            newstring_labframe = self.Booststringback(newstring) # Final string, in the lab frame
            #print newstring_labframe.Getstringcontent(), "LABFRAME CONTENT"

            #testthequark = newstring_labframe.Getq()
            #print testthequark.Getinvariantmass(), "invariant mass of the quark in the string"
            
            ''' Now need to boost then adjust the produced hadron '''
            kmomrotated = self.__rotateboost.Rotatebackwards(kmom) # rotate out or rotated frame
            kmomboosted = self.__lorentzboost/kmomrotated          # boost into the lab frame (original frame)
            hadron.Setmom(kmomboosted)
           
            ##print Decaytables.Findminandmaxpairmass(newstring_labframe)[1], "testing the condition for failure here"
            ##print newstring_labframe.Getstringmass(), "stringmass in the new labframe"    
            ##print Decaytables.Stringdecaysmallesthadron(newstring_labframe), "result of the decaytables testing shit, searching for error"
            ##print newstring_labframe.Getstringcontent(), "stringcontent"
            
            #if n > 3:
                #sys.exit()
            ''' Check validity of the decay (cons of energy) '''
            if qnew_minus + k_minus >= quark1vector4D[0] + antiquark1vector4D[0]:
                #print qnew_minus
                #print k_minus
                #print quark1vector4D[0]
                #print antiquark1vector4D[0]
                #print "CONDITION 1 FAILED"
                continue
                
            if quark2.Checkquark() is True and antiquark2.Checkquark() is True:
                meson = Decaytables.GetFailsafe1hadron(newstring_labframe)
                #print meson, "STRINGDECAY ERROR MESSAGE. THIS IS WHAT TRYING TO GET MASS OF"
                #mass = Decaytables.Getmass(meson)
                if meson == 0:
                    continue
                mass = Decaytables.Getmass(meson)
                if newstring_labframe.Getstringmass() <= mass:
                    #print "CONDITION 2 FAILED"
                    continue
                break
            if Decaytables.GetFailsafe1hadron(newstring_labframe) == 0:  # if no possible stringcollapse avaiable, try and produce something with less mom frac
                #print "CONDITION 3 FAILED"
                continue # previous findminandmaxpairmass(string)[0]
            else:
                break
            
        kaoncheck = self.Checkforkaons(hadronproducedID)
        hadron.SetID(kaoncheck)
        #print "STRING SUCCESSFULLY DECAYED"
        return [newstring_labframe, hadron] # returns the new string and a hadron, both boosted into the lab frame
예제 #41
0
 def Twobodydiquarks(self,string,diquark1, diquark2):  
     
     stringvec4D = string.Gettotalvector4D()
     boost = Boosts.boost4D(stringvec4D)
     cmsvector = boost.GetCMF()
     Mass = cmsvector[0] # string mass
     
     
     
     
     
     ''' Get the hadron masses '''
     Decaytables = Decaydictionary.Decays()
     #hadronpair = Decaytables.Failsafe2complete(string)
     #need to get the diquarks for string ends.
     hadron1code = diquark1
     #print hadron1code, "hadron1code from diquark twobody"
     hadron2code = diquark2
     #print hadron2code, "hadron2code from diquark twobody"
     mass1 = Decaytables.Getmass(hadron1code)
     mass2 = Decaytables.Getmass(hadron2code)
     
     mom3 = Mass/2
     mom3 *= self.Sqrtlambda1(Mass,mass1,mass2)
     randomphi = random.random()
     randomtheta = random.uniform(-1,1)
     phi = 2.*numpy.pi*randomphi
     sinphi = numpy.sin(phi)
     cosphi = numpy.cos(phi)
     theta = numpy.pi*randomtheta
     sintheta = numpy.sin(theta)
     costheta = numpy.cos(theta)
     mom = Fourvector.vector4D(0.,sintheta*cosphi,sintheta*sinphi,costheta)
     mom *= mom3
     E1 = numpy.sqrt(mass1*mass1+mom3*mom3)
     E2 = numpy.sqrt(mass2*mass2+mom3*mom3)
     finalvec1 = Fourvector.vector4D()
     finalvec1[0] = E1
     finalvec1 += mom
     finalvec2 = Fourvector.vector4D()
     finalvec2[0] = E2
     finalvec2 -= mom
     finalvec1 = boost/finalvec1
     finalvec2 = boost/finalvec2
     
     ''' reset the final vecs to represent massless diquarks. Just need the flavour assignment '''
     finalvec1 = copy.deepcopy(string.Getqvector4D())
     finalvec2 = copy.deepcopy(string.Getqbarvector4D())
     
     finalhadron1 = Particle.particle4D(hadron1code,finalvec1)
     finalhadron2 = Particle.particle4D(hadron2code,finalvec2)
     
     if hadron1code > 0:
         newstring = MRS.mrs4D(finalhadron1,finalhadron2)
         
     if hadron1code < 0:
         newstring = MRS.mrs4D(finalhadron2,finalhadron1) # try to keep the negative / positive ids in the relative placements (kind of important)
         
     
     #print newstring.Getstringcontent(), "CHECKING THE TWO BODY MODULE"
     return newstring 
예제 #42
0
 def Failsafe1(self,string):
     ''' Get Produced hadron & photon masses '''
     Decaytables = Decaydictionary.Decays()
     Failsafe1hadron = Decaytables.GetFailsafe1hadron(string)
     if Failsafe1hadron == 0:
         Failsafe1hadron = 22 #  set to a photon
         #print "Failsafe1 being fed an unphysical string - setting the hadron to photon to avoid crash but investigate the problem"
         #print string.Getstringmass(), "stringmass"
         #print string.Getstringcontent(), "stringcontent"
     #print Failsafe1hadron
     hadronmass = Decaytables.Getmass(Failsafe1hadron) # mass1
     #print hadronmass, "hadronmass"
             
     photonmass = 0 # mass 2
     ''' Get boost class which contains useful boosting functions '''
     string4vector = string.Gettotalvector4D()       
     boost = Boosts.boost4D(string4vector)
     
     ''' CMF mass of the string (mass of decaying object) '''
     cmsvector = boost.GetCMF()
     Mass = cmsvector[0]
     mom3 = Mass/2
     mom3 *= self.Sqrtlambda1(Mass,hadronmass,photonmass)
     
     ''' Do the random angle generation '''
     randomphi = random.random()
     randomtheta = random.uniform(-1,1)
     phi = 2.*numpy.pi*randomphi
     sinphi = numpy.sin(phi)
     cosphi = numpy.cos(phi)
     theta = numpy.pi*randomtheta
     sintheta = numpy.sin(theta)
     costheta = numpy.cos(theta)
     
     ''' start setting the 4 vectors of the products '''
     
     mom = Fourvector.vector4D(0.,sintheta*cosphi,sintheta*sinphi,costheta)
     mom *= mom3
     E1 = numpy.sqrt(hadronmass*hadronmass+mom3*mom3)
     E2 = numpy.sqrt(photonmass*photonmass+mom3*mom3)
     finalvec1 = Fourvector.vector4D()
     finalvec1[0] = E1
     finalvec1 += mom
     finalvec2 = Fourvector.vector4D()
     finalvec2[0] = E2
     finalvec2 -= mom
     
     ''' Boost back into the lab frame '''
     
     finalvec1 = boost/finalvec1 #hadron
     finalvec2 = boost/finalvec2 #photon
     
     ''' Create the particles and return them in a list '''
     Failsafe1hadron = self.Checkforkaons(Failsafe1hadron)
     
     finalhadron = Particle.particle4D(Failsafe1hadron,finalvec1)
     finalphoton = Particle.particle4D(22,finalvec2)
     
     if abs(finalhadron.Getcode()) == 311:
         print "FOUND IT"
         sys.exit()
     
     return [finalhadron, finalphoton]
예제 #43
0
파일: PyLund.py 프로젝트: PyLund-MC/PyLund
mom1 = Fourvector.vector4D(numpy.sqrt(41),3.,4.,4.)
mom2 = Fourvector.vector4D(numpy.sqrt(45),2.,4.,5.)
mom3 = Fourvector.vector4D(numpy.sqrt(101),9,4.,2.) 
mom4 = Fourvector.vector4D(6,2,4.,4.)
mom5 = Fourvector.vector4D(6,-2.,-4.,-4.)

''' momenta for 91.2 GeV '''


mom10 = Fourvector.vector4D(91.2/2,35.,20.,numpy.sqrt(454.36))
mom11 = Fourvector.vector4D(91.2/2,-35.,-20.,-numpy.sqrt(454.36))

''' Create some quarks '''

dquark = Particle.particle4D(1,mom10)
uquark = Particle.particle4D(2,mom10)
squark = Particle.particle4D(3,mom10)
cquark = Particle.particle4D(4,mom10)
bquark = Particle.particle4D(5,mom10)
tquark = Particle.particle4D(6,mom10)

''' Create some antiquarks '''

antidquark = Particle.particle4D(-1,mom11)
antiuquark = Particle.particle4D(-2,mom11)
antisquark = Particle.particle4D(-3,mom11)
anticquark = Particle.particle4D(-4,mom11)
antibquark = Particle.particle4D(-5,mom11)
antitquark = Particle.particle4D(-6,mom11)
예제 #44
0
    def Failsafe2(self,string): # IN SITU. NEEDS NEW TABLES TO BE CODED.
        stringvec4D = string.Gettotalvector4D()
        boost = Boosts.boost4D(stringvec4D)
        cmsvector = boost.GetCMF()
        Mass = cmsvector[0] # string mass
        
        ''' Get the hadron masses '''
        Decaytables = Decaydictionary.Decays()
        hadronpair = Decaytables.Failsafe2complete(string)
        
        hadron1code = hadronpair[0]
        hadron2code = hadronpair[1]
        mass1 = Decaytables.Getmass(hadron1code)
        if mass1 == 0:
            print "mass 1 == 0"
            print hadron1code, "hadron1code"
            print hadron2code, "hadron2code"
            sys.exit()
        mass2 = Decaytables.Getmass(hadron2code)
        
        mom3 = Mass/2
        mom3 *= self.Sqrtlambda1(Mass,mass1,mass2)
        randomphi = random.random()
        randomtheta = random.uniform(-1,1)
        phi = 2.*numpy.pi*randomphi
        sinphi = numpy.sin(phi)
        cosphi = numpy.cos(phi)
        theta = numpy.pi*randomtheta
        sintheta = numpy.sin(theta)
        costheta = numpy.cos(theta)
        mom = Fourvector.vector4D(0.,sintheta*cosphi,sintheta*sinphi,costheta)
        mom *= mom3
        E1 = numpy.sqrt(mass1*mass1+mom3*mom3)
        E2 = numpy.sqrt(mass2*mass2+mom3*mom3)
        finalvec1 = Fourvector.vector4D()
        finalvec1[0] = E1
        finalvec1 += mom
        finalvec2 = Fourvector.vector4D()
        finalvec2[0] = E2
        finalvec2 -= mom
        finalvec1 = boost/finalvec1
        finalvec2 = boost/finalvec2
        
        finalvec1row = finalvec1.Getvector()
        finalvec2row = finalvec2.Getvector()
        for i in range(4):
            if math.isnan(finalvec1row[i]) == True:
                finalvec1 = Fourvector.vector4D(mass1,0,0,0)


            if math.isnan(finalvec2row[i]) == True:
                finalvec2 = Fourvector.vector4D(mass2,0,0,0) # if we have nan values, then produce them at reast. see how this works
                print Mass, "stringmass"
                print "reached the problem with double kaon produictiion"
                sys.exit()


        
        finalhadron1 = Particle.particle4D(hadron1code,finalvec1)
        finalhadron2 = Particle.particle4D(hadron2code,finalvec2)
        
        return [finalhadron1, finalhadron2]
예제 #45
0
def Convertfromhepmc():
    reader = hepmc.IO_GenEvent("INPUT", "r") # ryan.hepmc is the file for PYTHIA stuff

    evtnum = 0 # should be zero
    noheavyevents = 0
    evt = hepmc.GenEvent()
    reader.fill_next_event(evt)
    totaleventlist = []
    while evt.particles_size(): # evtnum < 50000
        ''' Loop for each event. I.e. each list of particles '''
        subeventlist = []
        evtnum+=1
        #print "Event %d: " % evtnum, evt
        #print "Particles: ", evt.particles()
        #print "Num particles: ", evt.particles_size()
        #print "Num vertices: ", evt.vertices_size()
        #for p in evt.particles():
        #    m = p.momentum() # "X,Y,Z,E"
        #    print m
        fsps = evt.fsParticles()
        #print "FS particles: ", fsps
        #print "Num FS particles: ", len(fsps)
        if evtnum % 100 == 0:
            print "Event %d" % evtnum
        for p in fsps:
            ''' Build the list of final state particles in PyLund, and fill their properties '''
            #print p
            m = p.momentum() # E,x,y,z
            colour = p.flow(1)
            anticolour = p.flow(2)
            #print "1", colour, "2", anticolour

            ''' Build properties into PyLund particle class and append the particle to the sublist '''
            partfv = Fourvector.vector4D(m.e(),m.px(),m.py(),m.pz())
            ID = p.pdg_id()
            newpart = Particle.particle4D(ID,partfv)#
            #print newpart.Getinvariantmass(), "particle invariant mass"
            newpart.Setcolour(colour)
            newpart.Setanticolour(anticolour)
            subeventlist.append(newpart)
        ''' Perform some checks on the list -- current edition removes photons and vetoes heavy events '''
        if Vetoheavies(subeventlist) == True: # If event contains a heavy quark. go to next iteration before append.
            noheavyevents += 1
            #print "\n\n"
            evt.clear()
            evt = reader.get_next_event()
            continue
        subeventlist = Removephotons(subeventlist) # remove the photons from the event.
        #print "Num fs particles", len(subeventlist) # WE REMOVE THE PHOTONS. NO FS PARTICLES DOES NOT INCLUDE THE PHOTONS.

        ''' The call the colour ordering function '''

        #print subeventlist
        subeventlist = Colourorderlist(subeventlist)
        #print subeventlist, "event list after colour ordering"
        #print checkcolours(subeventlist)
        #sys.exit()
        subeventlist = masslessmomenta(subeventlist) # attempting the massels mom

        subeventlist = Fixlowenergy(subeventlist)
        #print subeventlist, "event list after fixing low nergy gluons"
        #print energies(subeventlist)
        #print checkquark(subeventlist)
        #sys.exit()
        subeventlist = Gluonsplitting.Splitgluons(subeventlist)
        #print subeventlist, "event list after splitting the gluons"
        #print len(subeventlist), "number of particles fed into string former"
        subeventlist = Stringformer.Formstrings(subeventlist) # Convert the lists to strings!
        #print subeventlist, "sublist after forming all the strings."
        #sys.exit()
        totaleventlist.append(subeventlist)


        #print "\n\n"
        evt.clear()
        evt = reader.get_next_event()


    #print noheavyevents
    return totaleventlist # returns a list of lists that contain strings ready for feeding into PyLund!
예제 #46
0
def Getmh(left,dec_g,right,z,splitflavour): # return False if conditions not met. Otherwise return normal vector output.

	Decaytables = Decaydictionary.Decays()
	gvec4Dx = dec_g.Getvector4D()
	gvec4D = copy.deepcopy(gvec4Dx)
	sgl_flavour = copy.deepcopy(splitflavour)

	if right.Checkgluon() == True: # particle on the right is a gluon. only have to consider the left hand side particle.
		#print "right particle is gluon, check that part"
		# Need the information of the quark / antiquark on the left.
		leftvector4D = left.Getvector4D()
		#print leftvector4D, "left vector"
		if left.Checkdiquark() == False: # left is a quark. Have to assign according to that idea
			if left.GetID() > 0: # if the left is the quark. need antiflavour
				if splitflavour > 10: # i.e. were producing a diquark
					sgl_flavour = copy.deepcopy(splitflavour) # we want the positive again.
				# UNLESS THE FLAVOUR CREATED IS A DIQUARK
				if splitflavour < 10: # i.e. we not producing a diquark
					sgl_flavour *= -1 # we want the negative quark on the left of the gluon split

			if left.GetID() < 0: # we have an anti quark on the left somehow??. Perhaps we've already had some diquark produciton :/
				if splitflavour > 10:
					sgl_flavour = copy.deepcopy(splitflavour) * -1

				if splitflavour < 10:
					sgl_flavour = copy.deepcopy(splitflavour)

		if left.Checkdiquark() == True:
			if left.GetID() < 0: # negative diquark
				sgl_flavour = copy.deepcopy(splitflavour) * -1
			if left.GetID() > 0: # positive diquark
				#print "we haev a positive diquark"
				#print left.GetID(), "left ID"
				sys.exit()
				sgl_flavour = copy.deepcopy(splitflavour)


		sgl_vec4D = copy.deepcopy(gvec4D)
		#print sgl_vec4D.Getvector()[0], "Energy of the gluon"
		sgl_vec4D *= z
		#print "scaled vector", sgl_vec4D

		# get the scaled momentum.
		sgl = Particle.particle4D(sgl_flavour, sgl_vec4D)



		# Create a temp string to test for FS1 hadron. I.e. if there is a small hadron that can be made.
		#print left.GetID(), "left ID"
		#print left.Getvector(), "left vector"
		#print sgl_flavour, "sgl flavour"
		#print sgl.Getvector(), "sgl vector"
		string = MRS.mrs4D(left,sgl)
		#print string.Getstringmass(), "string mass of the left,sgl pair"

		fs1hadron = Decaytables.GetFailsafe1hadron(string)
		#print fs1hadron, "fs1hadron in the right split code"

		if fs1hadron == 0:
			return False # condition failed. cant produce a hadron.


		fs1mass = PDG_ID.PDG_Type.mass(PDG_ID.PDG_Type(fs1hadron))
		#print fs1mass

		totalmom = sgl_vec4D + leftvector4D
		if totalmom*totalmom < (fs1mass*fs1mass): # Condition that the resultant qqbar pair is heavy enough to at least form a hadron.
			return False # Condition failed. Need to reloop again for different z.

		# Provided above conditions are satisfied, return the particles in correct sides based on nature of the left quark.
		# create the other particle
		sgr_flavour = copy.deepcopy(sgl_flavour) * -1
		sgr_vec4D = copy.deepcopy(gvec4D)
		sgr_vec4D *= (1-z)

		''' Create a new proxy particle to form a string with the right hand side to check cons stuff '''
		copyright = copy.deepcopy(right)

		newrightflavour = 1
		if abs(sgr_flavour) > 10: # we have a diquark
			if sgr_flavour > 0: # positive diquark
				newrightflavour = 1
			if sgr_flavour < 0:
				newrightflavour = -1

		if abs(sgr_flavour) < 10: # we ahve a regular quarks
			if sgr_flavour > 0: # positive quark
				newrightflavour = -1
			if sgr_flavour < 0:
				newrightflavour = 1


		copyright.SetID(newrightflavour)
		#print copyright.Getvector(), "vector of the right hand side particle"

		#print sgr_vec4D, "vector of the right hand side gluon after split. They must be collinear or smthing"


		sgr = Particle.particle4D(sgr_flavour,sgr_vec4D)

		
		string2 = MRS.mrs4D(sgr,copyright)
		#print string2.Getstringmass(), "stringmass of the second pseudo string"
		fs1hadron2 = Decaytables.GetFailsafe1hadron(string2)
		if fs1hadron2 == 0:
			return False # new conditional

		if abs(splitflavour) > 10: # we have a diquark produced
			rightvec4D = right.Getvector4D()
			sgr4D = sgr.Getvector4D()
			inv = rightvec4D + sgr4D
			invmass = numpy.sqrt(inv * inv)
			if invmass < 2.5: # invariant mass is less than two for the decaying gluon and the right hand side particle. then veto diquark production
				return False
		
		# Flavours already flipped from the above condition. Should always be correct relative to the left and eachother.
		return [sgl,sgr]

	if right.Checkgluon() == False: # so the right side is a quark. need to account for both sides having sufficient mass to form hadrons.
		#print "right particle is a quark, see that algorithm"

		if left.Checkdiquark() == False:
			#print "left is not diquark"
			#print splitflavour, "splitflavour in this party"
			if left.GetID() > 0: # if the left is the quark. need antiflavour
				if splitflavour > 10: # i.e. were producing a diquark
					sgl_flavour = copy.deepcopy(splitflavour) # we want the positive again.
				# UNLESS THE FLAVOUR CREATED IS A DIQUARK
				if splitflavour < 10: # i.e. we not producing a diquark
					sgl_flavour *= -1 # we want the negative quark on the left of the gluon split

			if left.GetID() < 0: # we have an anti quark on the left somehow??. Perhaps we've already had some diquark produciton :/
				#print "left ID is less than zero"
				if splitflavour > 10:
					"we've reached the left neg, g diquark part"
					sgl_flavour = copy.deepcopy(splitflavour) * -1
					#print left.GetID()
					#print sgl_flavour, "flavour of sgl"

				if splitflavour < 10:
					sgl_flavour = copy.deepcopy(splitflavour)
			
		if left.Checkdiquark() == True:
			if left.GetID() < 0: # negative diquark
				sgl_flavour = copy.deepcopy(splitflavour) * -1
			if left.GetID() > 0: # positive diquark
				sgl_flavour = copy.deepcopy(splitflavour)

		sgl_vec4D = copy.deepcopy(gvec4D)
		print sgl_vec4D, "sgl vec4D"
		print sgl_vec4D * sgl_vec4D
		sgl_vec4D *= z
		 
		sgr_vec4D = copy.deepcopy(gvec4D)
		print sgr_vec4D, "sgrvec4D"
		sgr_vec4D *= (1-z)
		sgr_flavour = copy.deepcopy(sgl_flavour) * -1 # sgr is the anti of the sgl
		#print right.GetID(), "right ID"
		#print left.GetID(), "left ID"
		#print sgr_flavour, "sgrflavour"
		#print sgl_flavour, "sglflavour"

		sgl = Particle.particle4D(sgl_flavour,sgl_vec4D)
		sgr = Particle.particle4D(sgr_flavour,sgr_vec4D)

		string1 = MRS.mrs4D(left,sgl)
		#print string1.Getstringcontent(), "stringcontent of string 1 in gluon splitting rigt hand is quark"
		string2 = MRS.mrs4D(sgr,right)
		#print string2.Getstringcontent(), "stringcontent of string 2 in gs right hand is quark"
		#print string1.Getstringmass(), string2.Getstringmass(), "string masses of 1,2 respectuively"

		fs1hadron1 = Decaytables.GetFailsafe1hadron(string1)
		#print fs1hadron1
		if fs1hadron1 == 0:
			return False
		fs1hadron2 = Decaytables.GetFailsafe1hadron(string2)

		#print fs1hadron2
		if fs1hadron2 == 0:
			return False

		return [sgl,sgr]