def 去块(self, x, y, z, 远程=False, 初=False): if not env.客户端 and not 初: self.记录.append(('去', x, y, z)) if env.客户端 and not 远程 and not 初: return if (x, y, z) not in self: # 防止线程冲突 return 块 = c世界.remove_block(x, y, z) if not env.客户端 and not 初 and 块: 物品 = block.掉落(块) if 物品: self.物品池.加(((x + 0.5, y + 0.5, z), 物品())) if env.客户端 and env.启用粒子 and not 初: for i in range(30): particle.particle(块, x + rd(0.1, 0.9), y + rd(0.1, 0.9), z + rd(0.1, 0.9), speed=4, t=rd(0.2, 0.4), size=0.1, 重力系数=0.6)
def beyondPS(self): self._byndPSCount = self._byndPSCount + 1 # add a pion decay particle - set the time to the decay lifetime and the s to the pathlength, eventweight to full # x,y,z to 0.0 and px,py to 0.0, pz to 0.01 so constructor does not tsc = pi.getTraceSpaceCoord() sd = tsc[0] xd = 0.0 yd = 0.0 zd = 0.0 pxd = 0.0 pyd = 0.0 pzd = 0.01 td = pi.getLifetime()*1E9 + t if (self._byndPSCount < printLimit): print ("pi in beyondPS: decayLength ", sd) pionLostDecay = particle.particle(runNumber, event, sd, xd, yd, zd, pxd, pyd, pzd, td, eventWeight, "pi+") print("beyond:PS about to add a pion") eH.addParticle("pionDecay", pionLostDecay) if (self._byndPSCount < printLimit): print ("at pionDecay lost") # add the pion flash neutrino ... set everything to zero - including eventWeight nuFlashLost = particle.particle(runNumber, event, sd, xd, yd, zd, pxd, pyd, pzd, td, 0.0, "numu") if (self._byndPSCount < printLimit): print ("at piFlashNu lost") eH.addParticle("piFlashNu", nuFlashLost) # add the muon from the pion flash ... set everything to zero - including eventWeight muonProdLost = particle.particle(runNumber, event, sd, xd, yd, zd, pxd, pyd, pzd, td, 0.0, "mu+") if (self._byndPSCount < printLimit): print ("at muonProduction lost") eH.addParticle("muonProduction",muonProdLost) return
def __init__(self, **kwargs): """ function: __init__ Function to initialize the class. This will prepare the instance for solving Parameters: -kwargs: Settings that deviate from the config file Returns: -None """ self.logger.info('Initializing the class...') # User variables self.config = config self.logger.info('Setting user defined variables..') for key in kwargs.keys(): self.config[key] = kwargs[key] self.logger.info('Finished setting the variables.') # Creating particles self.logger.info('Creating the particle instances...') self.particles = {} for key in pdg_id_lib: self.particles[pdg_id_lib[key]] = particle(pdg_id_lib[key]) self.particles['22_local'] = particle('22_local') self.logger.info('Finished particle creation') # Loading rates self.logger.info('Loading the rates...') self.emissivity() self.logger.info('Finished loading') self.logger.info('Finished initialization') return
def test_construct(): descString = "Checking new constructor" descriptions.append(descString) print(testTitle, ": ", descString) runNum = 43 eventNum = 67 x = 1.4 y = 2.3 z = 10.3 s = 10.8 px = 0.82 py = 0.45 pz = 4.67 t = 24.5 weight = 0.15 tSC = traceSpace.traceSpace(s, x, y, z, px / pz, py / pz) px = 1.02 py = 2.04 pz = 9.18 part = particle.particle(runNum, eventNum, s, x, y, z, px, py, pz, t, weight, "e+") mass = part.mass() E = mt.sqrt(mass * mass + px * px + py * py + pz * pz) p3 = np.array([px, py, pz]) p4 = np.array([E, p3], dtype=object) altPart = particle.particle(runNum, eventNum, s, x, y, z, p4, t, weight, "e+") assert part == altPart
def draw(self): x, y, z = self.位置 for i in range(3): particle.particle(14, x, y, z, speed=0.6, t=rd(0.5, 2.5), size=0.3, 重力系数=0.1)
def die(self): x, y, z = self.中心 for i in range(50): particle.particle(14, x, y + 0.2, z, speed=0.8, t=rd(0.3, 1), size=0.2, 重力系数=0.1) super().die()
def init(self, numParts): self.numParts = numParts for i in range(numParts): p = particle.particle() p.init() self.particles.append(p) self.initRandomColors()
def relativna_pogreska(): pogreska_postotak = [] vremena = [] dt = 0 promjena = 0.0001 t = domet_analiticki(10, 60, 0) for i in range(10000): dt = dt + promjena p1 = prt.particle(10, 60, 0, 0) pogreska = abs(((p1.range(dt) - t) / t) * 100) p1.reset() vremena.append(dt) pogreska_postotak.append(pogreska) x_cord = [vremena] y_cord = [pogreska_postotak] plt.scatter(x_cord, y_cord, s=0.2) plt.xlabel('vrijeme / dt') plt.ylabel('pogreška / %') plt.show() plt.plot(vremena[0:10000:100], pogreska_postotak[0:10000:100]) plt.xlabel('vrijeme / dt') plt.ylabel('pogreška / %') plt.show()
def start(center): vet_particles = [] for _ in range(maxParticles): m = p.particle() m.start(center) vet_particles.append(m) return vet_particles
def resample(p_list): new_list = [] u = np.random.uniform(0, 1./float(len(p_list)), 1)[0] j = 0 c = p_list[0].w for k in xrange(len(p_list)): # Divide the circle into equal parts. Move to the next particle only when b > cumulative weight b = (u + ((float(k))/(float(len(p_list))))) # print "heres b" # print b # print u if(b>1): print b quit() while (b > c): # print c j = (j+1) c = (c + p_list[j].w) new_list.append(particle(w = 1./float(len(p_list)),x = p_list[j].x)) return new_list
def test_print(): nuSIMPATH = os.getenv('nuSIMPATH') ##! Create instance, test built-in methods: ##! Create particle and print out ############################################################################# descString = "Create particle and print quantities" descriptions.append(descString) print(testTitle, ": ", descString) p = particle.particle(42, 125, 132.1, 0.1, 0.15, -100.0, 0.0, 0.2, 0.22, 5.12, 0.001, "pi+") # def __init__(self, runNum, eventNum, s, x, y, z, px, py, pz, t, eventWeight, particleType): # redirect standard out to a file restoreOut = sys.stdout fileName = os.path.join(nuSIMPATH, 'Scratch/particleTst.out') refFile = os.path.join(nuSIMPATH, '02-Tests/referenceOutput/particleTst.ref') print('filename is ', fileName) print('refFile is ', refFile) sys.stdout = open(fileName, "w") print(" __str__:", p) print(" --repr__", repr(p)) sys.stdout.close() sys.stdout = restoreOut # compare the standard output to a reference file a = os.popen('diff ' + fileName + ' ' + refFile) output = a.read() assert output == "" if (output == ""): pass else: testFails = testFails + 1 del p
def createHidrogen(self, pos, vel): velDir = self.randomUnitVector() axisDir = np.array( [velDir[0], (-velDir[0]**2 - velDir[2]**2) / velDir[1], velDir[2]]) axisDir = axisDir / np.linalg.norm(axisDir) self.particles.append( P.particle( -1 * axisDir * C.R / (1 + C.NUCLEUS_MASS / C.ELECTRON_MASS) + pos, -1 * velDir * C.V / (1 + C.NUCLEUS_MASS / C.ELECTRON_MASS) + vel, C.NUCLEUS_MASS, C.UNIT_CHARGE)) self.particles.append( P.particle( axisDir * C.R / (1 + C.ELECTRON_MASS / C.NUCLEUS_MASS) + pos, velDir * C.V / (1 + C.ELECTRON_MASS / C.NUCLEUS_MASS) + vel, C.ELECTRON_MASS, -C.UNIT_CHARGE))
def createGaussian(self, num, mass): mean = (self.args.bound/2) ppos = [] # array containing particle positions for i in range(0, num): # coordinate values for X, Y, and Z coords = [-1, -1, -1] # start each coordinate at -1 to ensure the loop runs once (Damn you Python for not having a Do-While) for j in range(0, 3): while coords[j] < 0 or self.args.bound < coords[j]: # ensure val is within range of particle boundaries coords[j] = round(gauss(mean, self.args.stdev), 6) m = round(float(mass), 2) # Set initial velocities to 0.0 for TESTING ONLY vx = 0.0 vy = 0.0 vz = 0.0 # vx = uniform(1,100) # vy = uniform(1,100) # vz = uniform(1,100) # Add new particle to ppos with no initial velocity # particle(id, m, x, y, z, vx, vy, vz) ppos.append(particle(i, m, coords[0], coords[1], coords[2], vx, vy, vz)) return ppos
def __init__(self, swarmSize, dimensions, weight_range, learning_rate_range, inertia_range, cog_constant, soc_constant, numberOfInformants): #--- PROPERTIES OF SWARM ----------------------------------------------------------------------- self.GLOBAL_fitnessBest = -1 self.GLOBAL_positionBest = [] self.weight_range = weight_range self.learning_rate_range = learning_rate_range self.inertia_range = inertia_range self.cog_constant = cog_constant self.soc_constant = soc_constant self.dimensions = dimensions self.swarmSize = swarmSize self.numberOfInformants = numberOfInformants #--- GENERATE SWARM ---------------------------------------------------------------------------- self.swarmArray = [] # create array to hold swarm particles for x in range(0, self.swarmSize): self.swarmArray.append( particle( dimensions, weight_range, learning_rate_range)) #removed x, swarmSize, numofinfo print(f"\nParticles with swarm size {swarmSize} generated.\n")
def add_neutron(): pygame.event.clear() pos=None while pos==None: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: pos=event.pos g.particles.append(particle.particle((pos[0]+move_position[0],c.world_height-pos[1]-move_position[1]), c.mn, 0, True))
def generate(self, add_particle): #photon energy and delta in nucleus rest frame w = c_double(0) d = c_double(0) self.dSigDwDt.GetRandom2(w, d) w = w.value d = d.value #polar angle theta theta_n = d * self.me / self.Ee_n #set the tree output self.tree_out.true_phot_w = w self.tree_out.true_phot_delta = d self.tree_out.true_phot_theta_n = theta_n #uniform azimuthal angle phi_n = 2. * TMath.Pi() * self.rand.Rndm() #uniform azimuthal angle #photon phot = add_particle(particle(22)) phot.stat = 1 phot.pxyze_prec = 9 #set the photon vector in nucleus rest frame px_n = w * TMath.Sin(theta_n) * TMath.Cos(phi_n) py_n = w * TMath.Sin(theta_n) * TMath.Sin(phi_n) pz_n = w * TMath.Cos(theta_n) phot.vec.SetPxPyPzE(px_n, py_n, pz_n, w) #transform the photon vector to laboratory frame phot.vec.Boost(-self.nbvec.x(), -self.nbvec.y(), -self.nbvec.z()) #rotate the photon for pz < 0 phot.vec.SetPxPyPzE(phot.vec.Px(), phot.vec.Py(), -phot.vec.Pz(), phot.vec.E()) #photon kinematics in generator output self.tree_out.true_phot_theta = phot.vec.Theta() self.tree_out.true_phot_phi = phot.vec.Phi() self.tree_out.true_phot_E = phot.vec.E() #scattered electron, initialize as beam electron = add_particle(beam(self.Ee, 11, -1)) electron.stat = 1 electron.pxyze_prec = 9 #constrain the scattered electron with the photon electron.vec -= phot.vec #electron kinematics in generator output self.tree_out.true_el_theta = electron.vec.Theta() self.tree_out.true_el_phi = electron.vec.Phi() self.tree_out.true_el_E = electron.vec.E()
def __init__(self, n_atoms, r_min, vval, n_steps, box_width): from matplotlib import pyplot as plt import numpy as np from matplotlib import animation, rc import particle import imp self.n_atoms imp.reload(particle) self.r_min = r_min self.particles = [] self.dt = (2 * r_min) / (vval) self.n_steps = n_steps self.box_width = box_width self.particles.append( particle.particle(-box_width / 2., 0., np.array([0.2, 0.]), 0)) self.particles.append( particle.particle(box_width / 2., 0., np.array([-0.2, 0.]), 1))
def resort(vet_particles): # print("@@@@@@@VVVVVVV@@@@@@@@@") # print_vet_particles(vet_particles) sorted_vet_particulas = [p.particle() for _ in range(maxParticles)] vetSort = [] size = 0 for m in vet_particles: # build vetSort, a ultima casa tem q ser 1 size = size + m.W # print("size: {}| peso: {}".format(size,m.W)) vetSort.append(size) # print("check last:",vetSort[-1]) # print(vetSort) n = random.uniform(0, 1) metodo = False # ir true metodo correto, else metodo q ele deixou if metodo: print('n vai roda') # # verificar aonde esse valor de N se encontra no intervalo de tempo do vetSort # # pegar esta posição e usar para buscar a particula na posição no vet_particles # # atribuir essa particula "grande" selecionada ao novo vet_particula ate fechar 1 do total de peso analisado # tot = 0 # for _ in range(len(vet_particles)): # for i,sz in enumerate(vetSort,0): # if n <= sz: # sorted_vet_particulas.append(vet_particles[i]) # pega a particula 'gorda' # frag = 1 / len(vet_particles) # tot = tot + frag # n = n + frag # # print("frag: {}|tot: {}|n: {}|".format(frag,tot,n)) # if n > 1: #se ele extrapolar o 1, n deveria ser adicionado ao N embaixo? # #perguntar pro professor # n = 0 # break # print("tot",tot) else: for z in range(len(vet_particles)): for i, sz in enumerate(vetSort, 0): if n <= sz: # print("casa: {}|sz: {}| n: {}|".format(i, sz, n)) M = vet_particles[i] sorted_vet_particulas[z].setAll( M) # pega a particula 'gorda' # print("peso P: ",vet_particles[i].W) n = random.uniform(0, 1) break # print("@@@@@@@------------@@@@@@@@@") # print_vet_particles(sorted_vet_particulas) # print("@@@@@@@^^^^^^^^^^^^@@@@@@@@@") return sorted_vet_particulas
def populate_real_space_matrix(self): if(self.mode == 1): self.real_space_list.append(particle.particle(1, self.Grid_Size/2, self.Grid_Size/2)) if(self.mode == 2): self.real_space_list.append(particle.particle(1, self.Grid_Size / 3, self.Grid_Size / 2)) self.real_space_list.append(particle.particle(1, self.Grid_Size - self.Grid_Size/3, self.Grid_Size / 2)) if(self.mode == 3): for x in range(0, self.Number_of_particles): temp_x = rand.uniform(0, 100) temp_y = rand.uniform(0, 100) temp_particle = particle.particle(1, temp_x, temp_y) # we are using the uniform mass of 1 self.real_space_list.append(temp_particle)
def GenerateMuon(self, runNum, eventNum, DcyCoord, P_mu, t, weight): s = DcyCoord[0] x = DcyCoord[1] y = DcyCoord[2] z = DcyCoord[3] px = P_mu[1][0] py = P_mu[1][1] pz = P_mu[1][2] pdg = self.__muPDG muon = particle.particle(runNum, eventNum, s, x, y, z, px, py, pz, t, weight, pdg) return muon
def GenerateNu(self, runNum, eventNum, DcyCoord, P_numu, t, weight): s = DcyCoord[0] x = DcyCoord[1] y = DcyCoord[2] z = DcyCoord[3] px = P_numu[1][0] py = P_numu[1][1] pz = P_numu[1][2] pdg = -14 numu = particle.particle(runNum, eventNum, s, x, y, z, px, py, pz, t, weight, pdg) return numu
def 爆炸(v): x, y, z = v for i in range(150): particle.particle(14, x, y, z, speed=5, t=rd(0.3, 1.3), size=0.3, 重力系数=0.15) for i in env.主世界.单位池: u = env.主世界.单位池[i] if (v - u.位置).mo < 4: u.基础速度 -= (v - u.位置).normalize() * 8 u.基础速度.z += 4 x, y, z = v.intize for dx in range(-3, 4): for dy in range(-3, 4): for dz in range(-3, 4): if (vec(x + dx, y + dy, z + dz) - v).mo < 3: env.主世界.去块(x + dx, y + dy, z + dz)
def init(): global plane, flake # Init OpenGL Utility Toolkit glutInit() # Init the Display Mode glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) # and window size glutInitWindowSize(width, height) # and the Window Title (the b in front, is to give the name in bitwise - opengl needs that) glutCreateWindow(b"HS-RM 3D-Animation Avalanche") # clear the screen glClearColor(0, 0, 0, 0) # MatrixMode for setup glMatrixMode(GL_PROJECTION) # set up a perspective projection matrix # void gluPerspective( GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar); gluPerspective(40.0, float(width) / height, 1, 300.0) # define a viewing transformation - Camera on Z axis 10 away # void gluLookAt(GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ); gluLookAt(0, 1, 5, 0, 0, 0, 0, 1, 0) # set MatrixMode for render glMatrixMode(GL_MODELVIEW) # to have a callback function we need to add a display function glutDisplayFunc(display) # load my plane plane = object.object([0, -1, 0], 'resources/plane.obj') # setup one particle flake = particle.particle([0, 1, 0], [0.0, 0.0, 0.0], 1, 'resources/flake.obj') # callback for keystroke glutKeyboardFunc(keyFunc) # callback for mousepress glutMouseFunc(mouseFunc) # Timer function for the 60 fps draw callback glutTimerFunc(1000 / 60, drawLoop, 1000 / 60) # glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program. # Once called, this routine will never return. It will call as necessary any callbacks that have been registered. glutMainLoop()
def __init__(self,count,dest, bound,W,c1,c2): self.swarms=[] self.particles=[] self.nSwarms=len(dest) self.bound=bound self.singCol=True for i in range(self.nSwarms): parts=[] for n in range(count/self.nSwarms): pos=[i*30,n*30] temp=particle(randP(bound),dest[i],bound) self.particles.append(temp) parts.append(temp) self.swarms.append(swarm(count/self.nSwarms,parts,defaultCol,dest[i],W,c1,c2))
def generate(self, add_particle): #energy for the current event en = self.emin + (self.emax - self.emin) * self.rand.Rndm() self.out.gen_E = en #print en #make the photon phot = particle(22) phot.vec.SetPxPyPzE(0, 0, -en, en) phot.stat = 1 phot.pxyze_prec = 9 #put the photon to the event add_particle(phot)
def makeHistory(self): # make sure the data structure is complete testParticle = particle.particle(-1, -1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.01, 0.0, 0.0, "pi+") self.addParticle("target", testParticle) self.addParticle("productionStraight", testParticle) self.addParticle("prodStraightEnd", testParticle) self.addParticle("pionDecay", testParticle) self.addParticle("muonProduction", testParticle) self.addParticle("piFlashNu", testParticle) self.addParticle("muonDecay", testParticle) self.addParticle("eProduction", testParticle) self.addParticle("numuProduction", testParticle) self.addParticle("nueProduction", testParticle) self.addParticle("numuDetector", testParticle) self.addParticle("nueDetector", testParticle)
def __init__(self, x0, N, t2, d): self.N = N self.ps = np.empty((N + 1, N + 1), dtype=np.object) self.t2 = t2 self.d = d i = 0 j = 0 assert len(x0) == (N + 1)**2 for x in range(len(x0)): p = particle(x0[x], np.array([i, j])) self.ps[i, j] = p if j < self.N: j += 1 else: j = 0 i += 1
def initialise(num_particles, bounds, velocity, mass, radius=1): ''' def : short for define, this is how all functions start initialise : this is the name we give the funciton, it can be anything, as long as there are no spaces. num_particles, bounds, velocity, mass : These are the inputs to the function, it will not be able to do anything if they are not provided radius=1 : this is also an input, however by setting it equal to 1, we have provided it with a default value, so we don't need to pass anything in unless we want a different value This is everything we need to set up the inputs of a python function. All these inputs will be accessible as variables inside the function body Next we write code that tells the function how to turn the inputs into output(s) ''' assert bounds.size == velocity.size # This is just to check that the dimensions are the same particles = np.array( [] ) # Create an empty numpy array, numpy arrays are fast and very feature packed! for x in range( num_particles): # This is a loop, it will run num_particles times, # each time it loops x will increase by 1 until it reaches num_particles-1 # x starts with a value of 0 #print(x) temp = particle.particle( np.multiply(bounds, np.random.rand(bounds.size)), np.copy(velocity), mass, radius) # Here we create a temporary particle particles = np.append( particles, temp) # We then stick it on the end of the particles array ''' Everything above here is an intermediate step. In this case, it is creating a variable called particles When it's finished, we need to tell the function that we would like to use it as the output. This is done using the "return" keyword, essentially saying return this object to whatever called the function ''' return particles
def changePCount(self,val): total=val perSwarm=total/self.nSwarms if len(self.particles)<total: self.particles=self.particles[:total] elif len(self.particles)>total: curr=len(self.particles) bound=self.particles[-1].bound for i in range(total-curr): self.particles.append(particle(randP(bound),dest[i],bound)) m=0 n=perSwarm for i in range(self.nSwarms): self.swarms[i].particles=self.particles[m:n] self.swarms[i].pCount=n-m m+=n n+=n
def __init__(self, pVec, material=part.gm.defaultMaterial): """ initialize with a parameter vector, (dIn, dOut, x0,v0) """ self.PS = ps.particleSolver( part.particle(pVec[:2], T=pVec[2], thermalTimestep=5e-5, kinematicTimestep=5e-5, x0=pVec[3:6], v0=pVec[6:9], nNodes=30, nStep=1000, material=material)) #self.PS.p.adaptiveTimestepping = False self.PS.p.thermalStep = float32(75.) self.hasRun = False
def runToy2D(): np.random.seed(0) random.seed(0) for i in range(20): print ' '*random.randint(0,70) + '*' # priors: aP = prior.uniform(-5,5) # will have 2D gaussian toy likelihood bP = prior.uniform(-5,5) g.priors = [aP,bP] # parameters ('name', x_init, isFrozen): a = particle.param('a',aP.sample(),False) b = particle.param('b',bP.sample(),False) g.initParams = [a,b] for i,p in enumerate(g.initParams): # important! p.setPrior(i) # which indexes are thawed: for i,p in enumerate(g.initParams): if(not p.isFrozen): g.thawedIdxs.append(i) # choose likelihood: g.likelihood = likelihood.toyGauss() # mass vector for parameters: g.masses = np.ones(len(g.initParams)) # create the initial particle set: particles = [] for i in range(g.nParticles): particles.append(particle.particle(g.initParams)) particles[i].assignPriorSample() # set the inference running: fname = '/Users/jmrv/Documents/school/mit/research/software/nest/samples/toy2d.txt' nested.sample(particles,fname) pos = posterior.posterior(fname) plotname = '/Users/jmrv/Documents/school/mit/research/software/nest/plots/toy2d.pdf' pos.plotMarginals(plotname)
def generate(self, add_particle): lin = "" while lin.find("Event finished") < 0: lin = self.inp.readline() if lin == "": raise IOError("No more events") line = lin.split() #kinematics from event header if line[0] != "I" and line[0] != "I," and len(line) == 30: self.tree_out.true_y = float(line[10]) self.tree_out.true_Q2 = float(line[11]) self.tree_out.true_x = float(line[12]) self.tree_out.true_W2 = float(line[13]) self.tree_out.true_Nu = float(line[14]) #skip non-particle lines and header if len(line) != 14: continue if line[0] == "I": continue #status, pdg and mother particle stat = int(line[1]) pdg = int(line[2]) mot = int(line[3]) #select the scattered electron if stat != 1 or pdg != 11 or mot != 3: continue #print line #electron momentum and energy px = float(line[6]) py = float(line[7]) pz = float(line[8]) en = float(line[9]) #generate the electron el = add_particle(particle(11)) el.vec.SetPxPyPzE(px, py, pz, en) el.stat = 1 el.pxyze_prec = 9
def readInputFile(self): file = self.args.ifile # particle positions - just like self.genParticles ppos = [] # velocity vectors try: with open(file, "r") as ifile: print "[+] Reading from input file \"%s\"" % file pstrings = ifile.readlines() for i in range(0, len(pstrings)): # header = "ID, mass, px,py,pz\n" # strip '\n' from line, then split into a list at commas p = pstrings[i].strip().split(",") # must cast values, because they are read in as strings by Python # casting should catch odd values as well (e.g. '40a' for a PID) ppos.append(particle(int(p[0]), float(p[1]), float(p[2]), float(p[3]), float(p[4]), float(p[5]), float(p[6]), float(p[7]))) return ppos except IOError: raise IOError("Error reading input file!")
def generate(self, add_particle): #energy spread de = 0 if self.espread is not None: de = self.espread.GetRandom() #electron energy and momentum along z en = self.Ee + de pz = -TMath.Sqrt(en**2 - self.me**2) #beam Lorentz vector beam = particle(11) beam.vec.SetPxPyPzE(0, 0, pz, en) beam.stat = 1 beam.pxyze_prec = 9 #put the beam electron to the event add_particle(beam)
def createRandom(self, num, mass): bound = self.args.bound ppos = [] # array containing particle positions for i in range(0, num): # Particle created of the form: [PID, X, Y, Z, M] x = round(uniform(0, bound), 6) y = round(uniform(0, bound), 6) z = round(uniform(0, bound), 6) m = round(float(mass), 2) # Set initial velocities to 0.0 for TESTING ONLY vx = 0.0 vy = 0.0 vz = 0.0 # vx = uniform(1,100) # vy = uniform(1,100) # vz = uniform(1,100) # Add new particle to ppos with no initial velocity # particle(id, m, x, y, z, vx, vy, vz) ppos.append(particle(i, m, x, y, z, vx, vy, vz)) return ppos
def createDisk(self, num, mass): print 'CreateDisk' rmin = 0.7*self.args.bound rmax = 0.9*self.args.bound ppos = [] vel_scale = 0.02 phis = np.linspace(0, 2*np.pi, num) zthick = (rmax - rmin)/2.0 pid = 0 for phi in phis: dist_scale = np.random.uniform(rmin, rmax) x = dist_scale*np.cos(phi) y = dist_scale*np.sin(phi) z = np.random.uniform(-zthick, zthick) vx = -1*vel_scale*np.sin(phi) vy = vel_scale*np.cos(phi) vz = 0.0 ppos.append(particle(pid, mass, x, y, z, vx, vy, vz)) pid += 1 return ppos
def runToy1D(): np.random.seed(1) random.seed(1) for i in range(20): print ' '*random.randint(0,70) + '*' # priors: aP = prior.uniform(-5,5) # single parameter. will have gaussian toy likelihood g.priors = [aP] # parameters ('name', x_init, isFrozen): a = particle.param('a',aP.sample(),False) g.initParams = [a] for i,p in enumerate(g.initParams): # important! p.setPrior(i) # which indexes are thawed: for i,p in enumerate(g.initParams): if(not p.isFrozen): g.thawedIdxs.append(i) # choose likelihood: g.likelihood = likelihood.toy1D() # mass vector for parameters: g.masses = np.ones(len(g.initParams))*0.05 # create the initial particle set: particles = [] for i in range(g.nParticles): particles.append(particle.particle(g.initParams,g.initStep)) particles[i].assignPriorSample() # set the inference running: nested.sample(particles)
def runSc(): np.random.seed(0) random.seed(0) for i in range(20): print ' '*random.randint(0,70) + '*' # priors: normP = prior.uniform(1e-2,1,isLog=True) # powerlaw norm alphaP = prior.uniform(2,4) # powerlaw power nHP = prior.uniform(1.0,3.0) # nH (absorption) scAreaP = prior.uniform(1e-6, 1e-3, isLog=True) # Sc line area area1P = prior.uniform(1e-6, 1e-3, isLog=True) # nuisance line 1 center1P = prior.uniform(3.5, 3.7) # sigma1P = prior.uniform(0.001, 0.010) # natural width area2P = prior.uniform(1e-5, 1e-4, isLog=True) # nuisance line 2 center2P = prior.uniform(3.75, 4.0) # sigma2P = prior.uniform(0.001, 0.010) # g.priors = [ normP, alphaP, \ nHP, \ scAreaP, \ #area1P,center1P,sigma1P, \ area2P,center2P,sigma2P ] # parameters ('name', x_init, isFrozen): norm = particle.param('norm',5e-2,False) alpha = particle.param('alpha',2.9,False) nH = particle.param('nH',2.0,True) scarea = particle.param('Sc area',1e-5,False) area1 = particle.param('area1',1e-5,False) center1 = particle.param('center1',3.6,False) sigma1 = particle.param('sigma1',0.005,False) area2 = particle.param('area2',1.8e-5,False) center2 = particle.param('center2',3.87,False) sigma2 = particle.param('sigma2',0.005,False) g.initParams = [ norm,alpha, \ nH, \ scarea, \ #area1,center1,sigma1, \ area2,center2,sigma2] for i,p in enumerate(g.initParams): p.setPrior(i) # which indexes are thawed: for i,p in enumerate(g.initParams): if(not p.isFrozen): g.thawedIdxs.append(i) # mass vector for parameters: g.masses = np.ones(len(g.initParams))*0.1 # data and likelihood: g.likelihood = likelihood.ScLike( g.datadir+'column.warf', g.datadir+'column.wrmf', g.datadir+'column.pi', g.modeldir+'phabs1e22.txt', [3.4,5]) # create the initial particle set: particles = [] for i in range(g.nParticles): particles.append(particle.particle(g.initParams)) particles[i].assignPriorSample() # set the inference running: fname = g.sampleDir+'samples.txt' nested.sample(particles,fname) pos = posterior.posterior(fname) plotname = g.plotDir+'sctest.pdf' pos.plotMarginals(plotname)
# Boundary conditions deltaV_NR = 1.0e-3 # 1.0 mV deltaV_R = 1.0e6 # 1.0 MV V_min = 1.0 V0 = dirBC(V_min) VN_NR = dirBC(V_min + deltaV_NR) VN_R = dirBC(V_min + deltaV_R) # Particle mass = scipy.constants.electron_mass charge = -scipy.constants.elementary_charge X0_particle = X0 V0_particle = 0.0 electron_NR = particle(mass,charge,[X0_particle],[V0_particle]) electron_R_Rpush = particle(mass,charge,[X0_particle],[V0_particle]) electron_R_NRpush = particle(mass,charge,[X0_particle],[V0_particle]) # Time steps T_NR = 0.99*pow(-2.0*mass*pow(LX,2.0)/(charge*deltaV_NR),0.5) T_R = 0.99*pow(-2.0*mass*pow(LX,2.0)/(charge*deltaV_R),0.5) steps = 100 DT_NR = T_NR/steps DT_R = T_R/steps # Solve for potential pot1D_NR = esSolve.laplace1D(NX,DX,V0,VN_NR,"gaussSeidel",relTol=0.0,absTol=1.0e-3*(deltaV_NR),useCython=False) pot1D_R = esSolve.laplace1D(NX,DX,V0,VN_R,"gaussSeidel",relTol=0.0,absTol=1.0e-3*(deltaV_R),useCython=False) # Compute E = - grad V on grid
import asyncore import os reldir = os.path.dirname(__file__) if not reldir: reldir = '.' else: # Append paths sys.path.append(reldir) from optparse import OptionParser from particle import particle parser = OptionParser() parser.add_option("-p", "--port", dest="port", help="port to connect on", metavar="port", type=int, default=10000) parser.add_option("-e", "--ebarrier", dest="ebarrier", help="energy barrier height", metavar="ebarrier", type=float, default=5.0) parser.add_option("-s", "--server", dest="server", help="server to connect to", metavar="server", type="string", default="localhost") parser.add_option("-t", "--timeout", dest="timeout", help="refuse to accept new jobs after t=timeout(hours)", metavar="timeout", type=float, default=0.0) (options, args) = parser.parse_args() print('Launching particle client, port: ', options.port, ' server: ', options.server, ' timeout: ', options.timeout) # ffs(A,B,n) sp = particle(options.server, options.port, options.ebarrier, options.timeout) asyncore.loop()
def generateNewParticle(params0, logLstar): p = particle.particle(params0) while p.distance == 0: cmc.evolve(p, logLstar) return p