Beispiel #1
0
 def setUp(self):
   self.species = species.Species(0, 1, 1, [])
   self.attacker = species.Species(0, 1, 1, [])
   self.attacker.setTraits([trait.Trait.carnivore])
   self.defender = species.Species(0, 1, 1, [])
   self.neighborleft = species.Species(0, 1, 1, [])
   self.neighborright = species.Species(0, 1, 1, [])
Beispiel #2
0
    def setUp(self):
        self.player = player.Player(1, [], 0)
        self.strat = strategy.Strategy()

        self.carnivore = species.Species(0, 1, 1, [])
        self.carnivore.setTraits([trait.Trait.carnivore])
        self.fat_carnivore = species.Species(0, 1, 1, [])
        self.fat_carnivore.setTraits([trait.Trait.carnivore])
        self.fat_carnivore.setBodySize(5)

        self.herbavore = species.Species(0, 1, 1, [])
        self.fat_herbavore = species.Species(0, 1, 1, [])
        self.fat_herbavore.setBodySize(4)

        self.fat_tissue = species.Species(0, 1, 1, [])
        self.fat_tissue.setBodySize(3)
        self.fat_tissue.setTraits([trait.Trait.fat_tissue])
        self.fat_fat_tissue = species.Species(0, 1, 1, [])
        self.fat_fat_tissue.setBodySize(6)
        self.fat_fat_tissue.setTraits([trait.Trait.fat_tissue])

        self.opherb = species.Species(0, 1, 1, [])
        self.opfatherb = species.Species(0, 1, 1, [])
        self.opfatherb.setBodySize(4)

        self.opponent1 = player.Player(1, [], 0)
        self.opponent1.setSpeciesBoards([self.opherb, self.opfatherb])
        self.opponents = [self.opponent1]

        self.dealer = dealer.Dealer()
        self.dealer.setListOfPlayers([self.player, self.opponent1])
        self.dealer.setWateringHole(4)
Beispiel #3
0
    def parse_loSpecies(self, LOS):
        """
		make a list of Species from a JSON LOS. A JSON Species+ is:
			[["food",Nat],
		     ["body",Nat],
		     ["population",Nat],
		     ["traits",LOT]
		     ["fat-food" ,Nat]]
		"""
        species_list = []
        for speciesboard in LOS:
            keywords = ((speciesboard[0][0] == "food")
                        and (speciesboard[1][0] == "body")
                        and (speciesboard[2][0] == "population")
                        and (speciesboard[3][0] == "traits"))
            if speciesboard and keywords:
                this_species = species.Species(
                    speciesboard[0][1], speciesboard[1][1], speciesboard[2][1],
                    self.parse_traits(speciesboard[3][1]))
                if this_species.hasFatTissue():
                    try:
                        this_species.setFatFood(speciesboard[4][1])
                    except IndexError:
                        pass
                species_list.append(this_species)
            elif not keywords:
                raise Exception("Keywords don't match")
        return species_list
Beispiel #4
0
    def __speciate(self, report=False):
        """ Group chromosomes into species by similarity """
        if self._gtype == Blu_Chromosome:
            for indiv in self.__population:
                indiv.updateModPointers()

        # Speciate the population
        for individual in self:
            found = False
            for s in self.__species:
                if individual.distance(
                        s.representant) < Config.compatibility_threshold:
                    s.add(individual)
                    found = True
                    break

            if not found:  # create a new species for this lone chromosome
                self.__species.append(species.Species(individual))
        # python technical note:
        # we need a "working copy" list when removing elements while looping
        # otherwise we might end up having sync issues
        for s in self.__species[:]:
            # this happens when no chromosomes are compatible with the species
            if len(s) == 0:
                if report:
                    print "Removing species %d for being empty" % s.id
                # remove empty species
                self.__species.remove(s)

        if self._gtype == Mod_Chromosome:
            Config.mod_species = [s.id for s in self.__species if len(s) > 0]

        self.__set_compatibility_threshold()
Beispiel #5
0
def get_input_spp(sppfile):

    spp = open(sppfile, "r").read().splitlines()
    input_species = {}

    for s in spp:
        s_clean = s.replace("_", " ")
        log.debug("Making species object for '%s'" % (s))
        input_species[s_clean] = species.Species(s_clean, s)

    return input_species
Beispiel #6
0
    def testCreationFromPlanet(self):
        # What info do we need from a planet?
        config = {
            "planet": {
                "world_type": "Ocean",
                "size": "Standard",
                "surface_temp": "287.4",
                "hydro_cover": 80
            }
        }

        new_species = species.Species(self.random_seed, config)
Beispiel #7
0
def get_species(session, uri):
    """
  using the URI given of a certain species , the species details are retrieved and returned from the API
  """
    if uri is None:
        return
    one_species = session.get(uri).json()

    if one_species is not None:
        species_obj = species.Species(
            one_species['name'], one_species['average_lifespan'],
            get_world(session, one_species['homeworld']))
        return species_obj
Beispiel #8
0
def get_aln_spp(alnfile):
    log.debug("Opening alignment '%s'" % (alnfile))

    aln = open(alnfile, "r")
    sites = int(aln.readline().split()[1])

    #get a dictionary of names in the smith alignment, keyed by genus
    aln_spp = {}

    for line in iter(aln):
        name = line.split()[0]
        name_clean = name.replace("_", " ")
        dna = line.split()[1]
        data = sites - dna.count("-")
        s = species.Species(name_clean, name)
        s.data = data
        aln_spp[name_clean] = s

    return aln_spp
Beispiel #9
0
 def __speciate(self):
     """ Group chromosomes into species by similarity """ 
     # Speciate the population
     for c in self:
         found = False    
         for s in self.__species:
             if s.representative.id == c.id:
                 s.add(c)
                 found = True
                 break    
             # if c.species_id is not None try this species first  
             if c.species_id == s.id and not found:
                 if c.distance(s.representative) < Config.compatibility_threshold:    
                     s.add(c)
                     found = True
                     break
         
         if not found:
             for s in self.__species:      
                 if c.distance(s.representative) < Config.compatibility_threshold:
                     s.add(c)                               
                     #print 'chromo %s added to species %s' %(c.id, s.id)
                     found = True
                     break # we found a compatible species, so let's skip to the next
             
         if not found: # create a new species for this lone chromosome
             self.__species.append(species.Species(c))  
    
     # Controls compatibility threshold
     if len(self.__species) > Config.species_size:
         Config.compatibility_threshold += Config.compatibility_change
     elif len(self.__species) < Config.species_size:
         if Config.compatibility_threshold > Config.compatibility_change:
             Config.compatibility_threshold -= Config.compatibility_change
         else:
             print 'Compatibility threshold cannot be changed (minimum value has been reached)'            
Beispiel #10
0
    with open(outputFileName + '.dat', 'w') as outputFile:
        for config in levelList:
            outputFile.write('\n')
            for level in config.term.levels:
                writeStr = config.ID + ', ' + str(level.J) + ', ' + str(
                    level.energy)

                if outputFileName == 'calculated':
                    writeStr += ' ' + config.method + '\n'
                else:
                    writeStr += '\n'

                outputFile.writelines(writeStr)

    return levelList


if __name__ == '__main__':
    O = species.Species('O')

    #allSpecies = [allSpecies]

    NIST = readNISTSpectra(O)
    theory = calculateExpectedStates(O, 5)
    calcEnergy = CalcEnergy(5, O, NIST, theory, O)

    allLevels = calcEnergy.populateTheory()

    for config in allLevels:
        if config.term.checkLevelEnergies() != None:
            print(config.ID, config.core.term.getTermString())
Beispiel #11
0
import matplotlib.pyplot as plt

############### SORT LEVELS ##################

constants = util.Constants()

nMax = 30

speciesList = [
    'C', 'C+', 'N', 'N+', 'N++', 'O', 'O+', 'O++', 'F+', 'F++', 'F+++', 'Ne++',
    'Ne+++'
]

allSpecies = []
for speciesStr in speciesList:
    speciesObj = species.Species(speciesStr)
    allSpecies.append([speciesObj, spectra.readNISTSpectra(speciesObj)])

O = species.Species('O')
N = species.Species('N')
OI = species.Species('O+')
NI = species.Species('N+')

use = NI

NIST = spectra.readNISTSpectra(use)
theory = spectra.calculateExpectedStates(use, nMax)

calcEnergy = spectra.CalcEnergy(nMax, use, NIST, theory, allSpecies)
completeLevels, calculatedLevels = calcEnergy.populateTheory()
Beispiel #12
0
    def testCreationWithConstraints(self):
        config = {"species": {"land_dwelling": True, "habitat": "Arctic"}}

        new_species = species.Species(self.random_seed, config)
        self.assertEqual("Arctic", new_species.habitat)
        self.assertTrue(new_species.sphere)
Beispiel #13
0
 def setUp(self):
     self.random_seed = 1  # Ensure that our tests are reproducible
     self.species = species.Species(self.random_seed)
    def setUp(self):
        self.parse_json = parse_json.ParseJSON()
        self.false = json.dumps(False)
        self.spec1 = species.Species(0, 1, 1, ["carnivore"])
        self.spec2 = species.Species(1, 3, 3, ["herding"])
        self.spec3 = species.Species(1, 2, 4, ["carnivore", "ambush"])
        self.spec4 = species.Species(0, 3, 2, [])

        self.spec5 = species.Species(0, 4, 2, ["carnivore"])
        self.spec6 = species.Species(1, 3, 3, ["herding"])
        self.spec7 = species.Species(1, 2, 4, ["carnivore", "ambush"])
        self.spec8 = species.Species(0, 1, 2, [])

        self.spec9 = species.Species(0, 1, 1, ["symbiosis"])
        self.spec10 = species.Species(0, 3, 1, ["warning-call"])
        self.spec11 = species.Species(2, 2, 2, [])
        self.spec12 = species.Species(0, 1, 1, [])

        self.spec13 = species.Species(0, 1, 1, [])
        self.spec14 = species.Species(0, 5, 1, ["fat-tissue"])
        self.spec14.setFatFood(5)
        self.spec15 = species.Species(0, 6, 1, ["warning-call"])
        self.spec16 = species.Species(2, 2, 2, [])

        self.spec17 = species.Species(0, 1, 1, [])
        self.spec18 = species.Species(0, 1, 1, [])
        self.spec19 = species.Species(0, 3, 2, ["carnivore", "fat-tissue"])
        self.spec19.setFatFood(3)
        self.spec20 = species.Species(3, 3, 6, [])

        self.spec21 = species.Species(0, 5, 4, [])
        self.spec22 = species.Species(2, 2, 2, [])

        self.player1 = player.Player(1, [self.spec1], 0)
        self.player2 = player.Player(2, [self.spec2, self.spec3], 0)
        self.player3 = player.Player(3, [self.spec4], 0)

        self.player4 = player.Player(1, [self.spec5], 0)
        self.player5 = player.Player(2, [self.spec6, self.spec7], 0)
        self.player6 = player.Player(3, [self.spec8], 0)

        self.player7 = player.Player(1, [self.spec9], 0)
        self.player8 = player.Player(2, [self.spec10, self.spec11], 0)
        self.player9 = player.Player(3, [self.spec12], 0)

        self.player10 = player.Player(1, [self.spec13], 0)
        self.player11 = player.Player(2, [self.spec14, self.spec15], 0)
        self.player12 = player.Player(3, [self.spec16], 0)

        self.player13 = player.Player(1, [self.spec17], 0)
        self.player14 = player.Player(2, [self.spec18, self.spec19], 0)
        self.player15 = player.Player(3, [self.spec20], 0)

        self.player16 = player.Player(1, [], 0)

        self.json_spec1 = [["food", 0], ["body", 1], ["population", 1],
                           ["traits", ["carnivore"]]]
        self.json_spec2 = [["food", 1], ["body", 3], ["population", 3],
                           ["traits", ["herding"]]]
        self.json_spec3 = [["food", 1], ["body", 2], ["population", 4],
                           ["traits", ["carnivore", "ambush"]]]
        self.json_spec4 = [["food", 0], ["body", 3], ["population", 2],
                           ["traits", []]]
        self.json_spec5 = [["food", 0], ["body", 4], ["population", 2],
                           ["traits", ["carnivore"]]]
        self.json_spec6 = [["food", 1], ["body", 3], ["population", 3],
                           ["traits", ["herding"]]]
        self.json_spec7 = [["food", 1], ["body", 2], ["population", 4],
                           ["traits", ["carnivore", "ambush"]]]
        self.json_spec8 = [["food", 0], ["body", 1], ["population", 1],
                           ["traits", []]]
        self.json_spec9 = [["food", 0], ["body", 1], ["population", 1],
                           ["traits", ["symbiosis"]]]
        self.json_spec10 = [["food", 0], ["body", 3], ["population", 1],
                            ["traits", ["warning-call"]]]
        self.json_spec11 = [["food", 2], ["body", 2], ["population", 2],
                            ["traits", []]]
        self.json_spec12 = [["food", 0], ["body", 1], ["population", 1],
                            ["traits", []]]
        self.json_spec13 = [["food", 0], ["body", 1], ["population", 1],
                            ["traits", []]]
        self.json_spec14 = [["food", 0], ["body", 5], ["population", 1],
                            ["traits", ["fat-tissue"]], ["fat-food", 5]]
        self.json_spec15 = [["food", 0], ["body", 6], ["population", 1],
                            ["traits", ["warning-call"]]]
        self.json_spec16 = [["food", 2], ["body", 2], ["population", 2],
                            ["traits", []]]
        self.json_spec17 = [["food", 0], ["body", 1], ["population", 1],
                            ["traits", []]]
        self.json_spec18 = [["food", 0], ["body", 1], ["population", 1],
                            ["traits", []]]
        self.json_spec19 = [["food", 0], ["body", 3], ["population", 2],
                            ["traits", ["carnivore", "fat-tissue"]],
                            ["fat-food", 3]]
        self.json_spec20 = [["food", 3], ["body", 3], ["population", 6],
                            ["traits", []]]
        self.json_spec21 = [["food", 0], ["body", 5], ["population", 4],
                            ["traits", []]]
        self.json_spec22 = [["food", 2], ["body", 2], ["population", 2],
                            ["traits", []]]

        self.json_player1 = [["id", 1],
                             [
                                 "species",
                                 [[["food", 0], ["body", 1], ["population", 1],
                                   ["traits", ["carnivore"]]]]
                             ], ["bag", 0]]
        self.json_player2 = [["id", 2],
                             [
                                 "species",
                                 [[["food", 1], ["body", 3], ["population", 3],
                                   ["traits", ["herding"]]],
                                  [["food", 1], ["body", 2], ["population", 4],
                                   ["traits", ["carnivore", "ambush"]]]]
                             ], ["bag", 0]]
        self.json_player3 = [["id", 3],
                             [
                                 "species",
                                 [[["food", 0], ["body", 3], ["population", 2],
                                   ["traits", []]]]
                             ], ["bag", 0]]
        self.json_player4 = [["id", 1],
                             [
                                 "species",
                                 [[["food", 0], ["body", 4], ["population", 2],
                                   ["traits", ["carnivore"]]]]
                             ], ["bag", 0]]
        self.json_player5 = [["id", 2],
                             [
                                 "species",
                                 [[["food", 1], ["body", 3], ["population", 3],
                                   ["traits", ["herding"]]],
                                  [["food", 1], ["body", 2], ["population", 4],
                                   ["traits", ["carnivore", "ambush"]]]]
                             ], ["bag", 0]]
        self.json_player6 = [["id", 3],
                             [
                                 "species",
                                 [[["food", 0], ["body", 1], ["population", 2],
                                   ["traits", []]]]
                             ], ["bag", 0]]
        self.json_player7 = [["id", 1],
                             [
                                 "species",
                                 [[["food", 0], ["body", 1], ["population", 1],
                                   ["traits", ["symbiosis"]]],
                                  [["food", 0], ["body", 3], ["population", 1],
                                   ["traits", ["warning-call"]]]]
                             ], ["bag", 0]]
        self.json_player8 = [["id", 2],
                             [
                                 "species",
                                 [[["food", 2], ["body", 2], ["population", 2],
                                   ["traits", []]],
                                  [["food", 0], ["body", 1], ["population", 1],
                                   ["traits", []]]]
                             ], ["bag", 0]]
        self.json_player9 = [["id", 3],
                             [
                                 "species",
                                 [[["food", 0], ["body", 1], ["population", 1],
                                   ["traits", []]]]
                             ], ["bag", 0]]
        self.json_player10 = [["id", 1],
                              [
                                  "species",
                                  [[["food", 0], ["body",
                                                  5], ["population", 1],
                                    ["traits", ["fat-tissue"]],
                                    ["fat-food", 5]],
                                   [["food", 0], ["body", 6],
                                    ["population", 1],
                                    ["traits", ["warning-call"]]]]
                              ], ["bag", 0]]
        self.json_player11 = [["id", 2],
                              [
                                  "species",
                                  [[["food", 2], ["body", 2],
                                    ["population", 2], ["traits", []]],
                                   [["food", 0], ["body", 1],
                                    ["population", 1], ["traits", []]]]
                              ], ["bag", 0]]
        self.json_player12 = [["id", 3],
                              [
                                  "species",
                                  [[["food", 0], ["body", 1],
                                    ["population", 1], ["traits", []]]]
                              ], ["bag", 0]]
        self.json_player13 = [["id", 1],
                              [
                                  "species",
                                  [[["food", 0], ["body", 3],
                                    ["population", 2],
                                    ["traits", ["carnivore", "fat-tissue"]],
                                    ["fat-food", 3]]]
                              ], ["bag", 0]]
        self.json_player14 = [["id", 2],
                              [
                                  "species",
                                  [[["food", 3], ["body", 3],
                                    ["population", 6], ["traits", []]],
                                   [["food", 0], ["body", 5],
                                    ["population", 4], ["traits", []]]]
                              ], ["bag", 0]]
        self.json_player15 = [["id", 3],
                              [
                                  "species",
                                  [[["food", 2], ["body", 2],
                                    ["population", 2], ["traits", []]]]
                              ], ["bag", 0]]
        self.json_player16 = [["id", 3], ["species", []], ["bag", 0]]
Beispiel #15
0
        for subShell in core[0]:
            #print(subShell)
            coreShells.append(SubShell(subShell[0], subShell[1], subShell[2]))
        core = Core(coreShells, core[1])

    for n in range(core.maxN+1, nMax+1, 1):
        for L in range(0, nMax, 1):
            excitedShell = SubShell(n, L, 1)
            excitedState = ExcitedState(excitedShell)
            configuration = Configuration(core, excitedState)
            states.append(configuration)

    return states

nMax = 10
He = species.Species('He')
O = species.Species('O')
NIST = readNISTSpectra(He)
theory = calculateExpectedStates(He, 10)

NISTStateIDs = []
for state in NIST:
    for IDterm in state.ID:
        NISTStateIDs.append(IDterm)

for state in theory:
    for termID in state.ID:
        if termID in NISTStateIDs:


'''
Beispiel #16
0
import plotter

import matplotlib.pyplot as plt

############### SORT LEVELS ##################


constants = util.Constants()

nMax = 20

speciesList = ['C', 'C+', 'N', 'N+', 'N++', 'O', 'O+', 'O++', 'F+', 'F++', 'F+++', 'Ne++', 'Ne+++']
useList = ['O', 'N', 'O+', 'N+']

for useName in useList:
    use = species.Species(useName)
    allSpecies = []
    for speciesStr in speciesList:
        speciesObj = species.Species(speciesStr)
        allSpecies.append([speciesObj, spectra.readNISTSpectra(speciesObj)])

    NIST = spectra.readNISTSpectra(use)
    theory = spectra.calculateExpectedStates(use, nMax)

    calcEnergy = spectra.CalcEnergy(nMax, use, NIST, theory, allSpecies)
    completeLevels, calculatedLevels = calcEnergy.populateTheory()

    calculatedLevels = spectra.sortSpectra(calculatedLevels, None)
    completeLevels = spectra.sortSpectra(completeLevels, None)
    NISTSorted = spectra.sortSpectra(NIST, None)
Beispiel #17
0
#!/usr/bin/python3
import sys
sys.path.append("/home/alacny/Programowanie/Python/Pandemic/lib")
import species as h
johny=[h.Species(), h.Species(), h.Species(), h.Species(), h.Species(), \
        h.Species(), h.Species(), h.Species(), h.Species(), h.Species()]
for i in range(0, 10):
    johny[i].setPOfInf(70)
    #    johny[i].setImmune()
    johny[i].setInfection()
    print(johny[i].getIllness())
Beispiel #18
0
        #Urm = potential(rm, J)
        #print(J, rm, Urm)


        
        warnings.simplefilter('error')
        try:
            rm = fsolve(potentialDerivative, re*1.7, args=J)
            Urm = potential(rm, J)        
            #print(J, rm, Urm)
            return rm, Urm
        except RuntimeWarning:
            return False


N2 = species.Species('N2')
O2 = species.Species('O2')
#print(N2.spectralData['Te'])

energyModes = EnergyModes(O2)
#asdf = energyModes.vibrational(0)

Q = energyModes.getEnergy(300)

print(Q)

'''
n = 0
v = 3
J = 1
Beispiel #19
0
def initlpa():
    global zstart0, zpos, xp0, yp0, zp0, wp0, l_moving_window, diagnosticsScript, laser_total_length, Eamp, laser_duration, laser_risetime, laser_waist, laser_amplitude, laser_phase, laser_profile, k0, w0, vg, max_diff_density, max_radius, max_parab_radius, norm_diff_density, betafrm, Lplasma, zstart_plasma, zstart_ions, length_pramp, length_pramp_exit, length_iramp, Lions, length_iramp_exit, dens_ions, dens0, ions, rp0, zstart_laser, em, laser_radius, laser_radius1, live_plot_freq, elec, prot, ions, zstart_laser1, zstart_ions_lab, Tstart_laser1, laser_amplitude1, laser_phase1, laser_profile1, k1, w1, ZR1, laser_total_length1, Eamp1, laser_duration1, laser_risetime1
    global bigRun
    global runDim

    # --- flags turning off unnecessary diagnostics (ignore for now)
    warp.top.ifzmmnt = 0
    warp.top.itmomnts = 0
    warp.top.itplps = 0
    warp.top.itplfreq = 0
    warp.top.zzmomnts = 0
    warp.top.zzplps = 0
    warp.top.zzplfreq = 0
    warp.top.nhist = warp.top.nt
    warp.top.iflabwn = 0
    warp.w3d.lrhodia3d = False
    warp.w3d.lgetese3d = False
    warp.w3d.lgtlchg3d = False
    #EnableAll()

    #-------------------------------------------------------------------------------
    # main parameters
    #-------------------------------------------------------------------------------
    if runDim == 3:
        dim = "3d"
    else:
        dim = "2d"
    dpi = 100  # graphics resolution
    l_test = 0  # Will open output window on screen
    # and stop before entering main loop.
    l_gist = 0  # Turns gist plotting on/off
    l_restart = False  # To restart simulation from an old run (works?)
    restart_dump = ""  # dump file to restart from (works?)
    l_moving_window = 1  # on/off (Galilean) moving window
    l_plasma = 1  # on/off plasma
    l_ions = 1  # on/off plasma ions
    l_external_field = 1  # on/off external field for the injection pulse
    l_beam = 0  # on/off electron beam
    l_injectplane = 1  # on/off beam injection through plane
    l_usesavedist = 0  # if on, uses dump of beam particles distribution
    savedist = 'unitdist4sym300000'  # beam initial distribution file
    svstride = 100  # loads only every svstride particles from dump
    l_smooth = 1  # on/off smoothing of current density
    l_laser = 1  # on/off laser
    l_pdump = 0  # on/off regular dump of beam data
    stencil = 0  # 0 = Yee; 1 = Yee-enlarged (Karkkainen) on EF,B; 2 = Yee-enlarged (Karkkainen) on E,F
    # use 0 or 1; 2 does not verify Gauss Law
    if dim == "1d": stencil = 0
    # coefficient to multiply default time step that is set at the EM solver CFL
    if bigRun:
        dtcoef = 0.25 / 4.0
    else:
        dtcoef = 1.0

    warp.top.depos_order = 3  # particles deposition order (1=linear, 2=quadratic, 3=cubic)
    warp.top.efetch = 4  # field gather type (1=from nodes "momentum conserving"; 4=from Yee mesh "energy conserving")
    nzstations = 50  # number of beam diag z-stations
    l_pselect = 0  # on/off selection of particles (i.e. remove halo) for diagnostics
    warp.top.runid = "lpa_basic"  # run name
    warp.top.pline1 = "basic lpa"  # comment line on plots
    warp.top.runmaker = "J.-L. Vay,"  # run makers
    warp.top.lrelativ = True  # on/off relativity (for particles push)
    warp.top.pgroup.lebcancel_pusher = True  # flag for particle pusher (0=Boris pusher; 1=Vay PoP 08 pusher)
    l_verbose = 0  # verbosity level (0=off; 1=on)

    #-------------------------------------------------------------------------------
    # diagnostics parameters + a few other settings
    #-------------------------------------------------------------------------------
    hist_freq = 50  # frequency (in time steps) of beam history data saving
    live_plot_freq = 2800 * 2  #2400  # frequency (in time steps) of live plots (off is l_test is off)

    #-------------------------------------------------------------------------------
    # boosted frame
    #-------------------------------------------------------------------------------
    gammafrm = 1.
    betafrm = math.sqrt(1. - 1. / gammafrm**2)
    if gammafrm > 1.:  # turns ON plasma ions if in boosted frame
        l_ions = 1
        l_moving_window = 1

    #-------------------------------------------------------------------------------
    # some units for convenience (& clarity)
    #-------------------------------------------------------------------------------
    microns = 1.e-6
    femtoseconds = 1.e-15

    lambda_laser_lab = 5.0 * microns  # wavelength
    lambda_laser_lab1 = 0.4 * microns  # wavelength for the second laser

    #-------------------------------------------------------------------------------
    # plasma density, length and ramps
    #-------------------------------------------------------------------------------
    # --- in lab frame
    dfact = 1.  # coefficient factor for plasma density (for scaled simulations)
    dens0lab = dfact * 2.0e23  # plasma density (flat section)
    wplab = math.sqrt(dens0lab * warp.echarge**2 /
                      (warp.eps0 * warp.emass))  # plasma frequency
    kplab = wplab / warp.clight  # plasma wavenumber
    lambda_plasma_lab = 2. * math.pi / kplab  # plasma wavelength
    length_pramp_lab = 15. * lambda_laser_lab / (
        dfact**1.5)  #15.                     # plasma entrance ramp length
    length_pramp_exit_lab = 15. * lambda_laser_lab / (
        dfact**1.5)  #15.                  # plasma exit ramp length
    Lplasma_lab = 10000. * lambda_laser_lab / dfact**1.5  #500.                        # plasma total length (including ramps)
    zstart_plasma_lab = 30. * lambda_laser_lab / dfact**1.5  #40.
    # --- in boosted frame
    dens0 = dens0lab * gammafrm  # plasma density
    length_pramp = length_pramp_lab / gammafrm  # plasma ramp length
    length_pramp_exit = length_pramp_exit_lab / gammafrm  # plasma ramp length
    Lplasma = Lplasma_lab / gammafrm  # plasma total length
    zstart_plasma = zstart_plasma_lab / gammafrm  # plasma starting point

    #-------------------------------------------------------------------------------
    # ions density, length and ramps
    #-------------------------------------------------------------------------------
    # --- in lab frame
    dens_ions_lab = 0.1 * dens0lab  # ions density (flat section)
    length_iramp_lab = 5. * lambda_laser_lab / (
        dfact**1.5)  #4.                      # ions entrance ramp length
    length_iramp_exit_lab = 5. * lambda_laser_lab / (
        dfact**1.5)  #4.                  # ions exit ramp length
    Lions_lab = 20. * lambda_laser_lab / dfact**1.5  #16.                        # ions total length (including ramps)
    zstart_ions_lab = 60. * lambda_laser_lab / (dfact**1.5)  #80.
    # --- in boosted frame
    dens_ions = dens_ions_lab * gammafrm  # ions density
    length_iramp = length_iramp_lab / gammafrm  # ions ramp length
    length_iramp_exit = length_iramp_exit_lab / gammafrm  # ions ramp length
    Lions = Lions_lab / gammafrm  # ions total length
    zstart_ions = zstart_ions_lab / gammafrm  # ions starting point

    #-------------------------------------------------------------------------------
    # laser parameters
    #-------------------------------------------------------------------------------
    # --- in lab frame
    KP_L = 2.0  # normalized length - standard gaussian form P=P0*numpy.exp(-2xi^2/L^2)
    KP_SIGMA = 3.02  # normalized transverse spot size - standard gaussian form I=I0*numpy.exp(-2r^2/SIGMA^2)
    laser_radius = KP_SIGMA / kplab
    laser_waist = laser_radius * 2.354820  # radius -> FWHM
    laser_length_lab = 4.75 * lambda_laser_lab  #4.75    # laser length
    laser_duration_lab = laser_length_lab / warp.clight  # laser duration
    laser_risetime_lab = 3. * laser_duration_lab  #
    laser_dura_fwhm_lab = 1.1774 * laser_duration_lab
    laser_polangle = 0  # polarization (0=aligned with x; math.pi/2=aligned with y)
    a0 = 1.17  # normalized potential vector (amplitude)
    k0lab = 2. * math.pi / lambda_laser_lab
    w0lab = k0lab * warp.clight
    ZR = 0.5 * k0lab * (laser_waist**2)  # Rayleigh length
    zstart_laser_lab = 0.

    # --- in boosted frame
    lambda_laser = lambda_laser_lab * gammafrm * (1. + betafrm)  # wavelength
    laser_duration = laser_duration_lab * gammafrm * (1. + betafrm)
    laser_length = laser_duration / warp.clight
    laser_risetime = 3. * laser_duration
    laser_dura_fwhm = 1.1774 * laser_duration
    zstart_laser = 0.
    k0 = 2. * math.pi / lambda_laser
    w0 = k0 * warp.clight
    Eamp = a0 * w0 * warp.emass * warp.clight / warp.echarge
    Bamp = Eamp / warp.clight
    if l_laser == 0:
        Eamp *= 1.e-15
        Bamp *= 1.e-15

    #-------------------------add second laser---------------------------------
    KP_L1 = 2.0  # normalized length - standard gaussian form P=P0*numpy.exp(-2xi^2/L^2)
    KP_SIGMA1 = 2. * math.pi / 15.  # normalized transverse spot size - standard gaussian form I=I0*numpy.exp(-2r^2/SIGMA^2)
    laser_radius1 = KP_SIGMA1 / kplab
    laser_waist1 = laser_radius1 * 2.354820  # radius -> FWHM
    laser_length_lab1 = 10. * lambda_laser_lab1  # laser length
    laser_duration_lab1 = laser_length_lab1 / warp.clight  # laser duration (FWHM)
    laser_risetime_lab1 = 3. * laser_duration_lab1
    laser_dura_fwhm_lab1 = 1.1774 * laser_duration_lab1
    laser_polangle1 = 0  # polarization (0=aligned with x; math.pi/2=aligned with y)
    a1 = 0.135  # normalized potential vector (amplitude)
    k1lab = 2. * math.pi / lambda_laser_lab1
    w1lab = k1lab * warp.clight
    ZR1 = 0.5 * k1lab * (laser_waist1**2)  # Rayleigh length
    #zstart_laser_lab1  = (7.6-28.)*lambda_laser_lab
    # --- in boosted frame
    lambda_laser1 = lambda_laser_lab1 * gammafrm * (1. + betafrm)  # wavelength
    laser_duration1 = laser_duration_lab1 * gammafrm * (1. + betafrm)
    laser_length1 = laser_duration1 / warp.clight
    laser_risetime1 = 3. * laser_duration1
    laser_dura_fwhm1 = 1.1774 * laser_duration1
    #zstart_laser1  = zstart_laser_lab1/gammafrm
    k1 = 2. * math.pi / lambda_laser1
    w1 = k1 * warp.clight
    Eamp1 = a1 * w1 * warp.emass * warp.clight / warp.echarge
    Bamp1 = Eamp1 / warp.clight
    if l_laser == 0:
        Eamp1 *= 1.e-15
        Bamp1 *= 1.e-15

    #-------------------------------------------------------------------------------
    # plasma cont'd
    #-------------------------------------------------------------------------------
    K = k0lab / kplab
    Ld = LINEAR_DEPHASING = 0.5 * lambda_plasma_lab**3 / lambda_laser_lab**2  # linear dephasing length
    BETAG_LINEAR_LAB = math.sqrt(1 - (1. / K) *
                                 (1. / K))  # linear beta of wake in lab
    GAMMAG_LINEAR_LAB = 1. / math.sqrt(
        1 - BETAG_LINEAR_LAB * BETAG_LINEAR_LAB)  # linear gamma of wake in lab
    BETAG_LINEAR = (BETAG_LINEAR_LAB - betafrm) / (
        1. - BETAG_LINEAR_LAB * betafrm
    )  # linear beta of wake in simulation frame
    GAMMAG_LINEAR = 1. / math.sqrt(
        1 - BETAG_LINEAR *
        BETAG_LINEAR)  # linear gamma of wake in simulation frame
    kp = kplab * (gammafrm * (1. - BETAG_LINEAR_LAB * betafrm))
    lambda_plasma = 2. * math.pi / kp
    densc = warp.emass * warp.eps0 * w0lab**2 / warp.echarge**2  # critical density

    #-------------------------------------------------------------------------------
    # print some plasma parameters to the screen
    #-------------------------------------------------------------------------------
    print("the laser group velocity is: ")
    print BETAG_LINEAR * warp.clight
    print("the laser spot size is: ")
    print laser_waist
    print("the Rayleigh length is: ")
    print ZR
    print("the laser wavelength is: ")
    print lambda_laser
    print("the second laser spot size is: ")
    print laser_waist1
    print("the Rayleigh length is: ")
    print ZR1
    print("the laser wavelength is: ")
    print lambda_laser1
    print("the plasma wavelength is: ")
    print lambda_plasma
    print("the plasma length is: ")
    print Lplasma

    #-------------------------------------------------------------------------------
    # e-beam
    #-------------------------------------------------------------------------------
    # --- in lab frame
    E_BEAM_GAMMA = GAMMAG_LINEAR_LAB * 1.5
    E_BEAM_ENERGY_MEV = 0.511 * (E_BEAM_GAMMA - 1.)
    E_BEAM_BETA = math.sqrt(1. - 1. / (E_BEAM_GAMMA * E_BEAM_GAMMA))
    E_BEAM_U = E_BEAM_GAMMA * E_BEAM_BETA
    E_BEAM_RADIUS = 0.825e-6 / math.sqrt(dfact)
    E_BEAM_LENGTH = 0.85e-6 / math.sqrt(dfact)

    # --- transverse spread (RMS Gaussian)
    GAMMAVXSIGMA = 0.
    GAMMAVYSIGMA = 0.
    # --- longitudinal spread (RMS Gaussian)
    GAMMAVZSIGMA = 0.

    E_BEAM_DENSITY_PEAK = 1.0e10
    E_BEAM_PHASE = 5. * math.pi / 4.
    E_BEAM_DISTANCE_BEHIND_LASER = E_BEAM_PHASE / kplab

    #-------------------------------------------------------------------------------
    # number of grid cells
    #-------------------------------------------------------------------------------
    # --- transverse
    # --- longitudinal
    if bigRun:
        nx = 1200
        nzplambda = 60
    else:
        if runDim == 3:
            nx = 1200 / 12
            nzplambda = 60 / 12
        else:
            nx = 1200 / 6
            nzplambda = 60 / 6

    #-------------------------------------------------------------------------------
    # number of plasma macro-particles/cell
    #-------------------------------------------------------------------------------
    nppcellx = 1  #2
    nppcelly = 1
    nppcellz = 2

    if dim == "2d":
        nppcelly = 1
    if dim == "1d":
        nppcellx = nppcelly = 1

    #-------------------------------------------------------------------------------
    # grid dimensions, nb cells and BC
    #-------------------------------------------------------------------------------
    warp.w3d.xmmax = 3.0 * laser_radius
    warp.w3d.xmmin = -warp.w3d.xmmax
    warp.w3d.ymmax = warp.w3d.xmmax
    warp.w3d.ymmin = -warp.w3d.ymmax
    warp.w3d.nx = nx
    warp.w3d.ny = warp.w3d.nx
    warp.w3d.dy = (warp.w3d.ymmax - warp.w3d.ymmin) / warp.w3d.ny
    if dim in ["1d"]:
        warp.w3d.nx = 2
        warp.w3d.xmmin = -float(warp.w3d.nx) / 2
        warp.w3d.xmmax = float(warp.w3d.nx) / 2
    if dim in ["1d", "2d"]:
        warp.w3d.ny = 2
        warp.w3d.ymmin = -float(warp.w3d.ny) / 2
        warp.w3d.ymmax = float(warp.w3d.ny) / 2
    warp.w3d.zmmin = -3.5 * lambda_plasma
    warp.w3d.zmmax = 3. * lambda_laser  #/nzplambda
    warp.w3d.nz = int(
        (warp.w3d.zmmax - warp.w3d.zmmin) * nzplambda / lambda_laser)
    warp.w3d.dx = (warp.w3d.xmmax - warp.w3d.xmmin) / warp.w3d.nx
    warp.w3d.dy = (warp.w3d.ymmax - warp.w3d.ymmin) / warp.w3d.ny
    warp.w3d.dz = (warp.w3d.zmmax - warp.w3d.zmmin) / warp.w3d.nz

    # --- enforces dx = dz (= dy) in boosted frame
    if 0:  #gammafrm>1:
        if warp.w3d.dz < warp.w3d.dx:
            # x (and y) dimensions are rescaled if needed
            warp.w3d.dx = warp.w3d.dz
            warp.w3d.nx = 2 * warp.nint(
                0.5 * (warp.w3d.xmmax - warp.w3d.xmmin) / warp.w3d.dx)
            warp.w3d.xmmax = warp.w3d.nx * warp.w3d.dx / 2
            warp.w3d.xmmin = -warp.w3d.xmmax
            if dim == '3d':
                warp.w3d.dy = warp.w3d.dz
                warp.w3d.ny = 2 * warp.nint(
                    0.5 * (warp.w3d.ymmax - warp.w3d.ymmin) / warp.w3d.dy)
                warp.w3d.ymmax = warp.w3d.ny * warp.w3d.dy / 2
                warp.w3d.ymmin = -warp.w3d.ymmax
        elif warp.w3d.dx < warp.w3d.dz:
            # z dimensions are rescaled if needed
            warp.w3d.dz = warp.w3d.dx
            warp.w3d.nz = warp.nint(
                (warp.w3d.zmmax - warp.w3d.zmmin) / warp.w3d.dz)
            warp.w3d.zmmax = warp.w3d.zmmin + warp.w3d.nz * warp.w3d.dz

    if gammafrm > 10.:
        if dim == "1d":
            dt0 = warp.w3d.dz / warp.clight
        if dim == "2d":
            dt0 = 1. / (warp.clight *
                        math.sqrt(1. / warp.w3d.dx**2 + 1. / warp.w3d.dz**2))
        if dim == "3d":
            dt0 = 1. / (warp.clight *
                        math.sqrt(1. / warp.w3d.dx**2 + 1. / warp.w3d.dy**2 +
                                  1. / warp.w3d.dz**2))
        mydt = warp.w3d.dz / (math.sqrt(2.) * warp.clight)
        dtcoef = min(1., mydt / dt0)

    # --- sets field boundary conditions
    warp.w3d.bound0 = warp.w3d.boundnz = warp.openbc
    #warp.w3d.bound0  = warp.w3d.boundnz = -1 # reflective longitudinal BC
    warp.w3d.boundxy = warp.periodic  #-1                # reflective transverse BC

    # --- sets particles boundary conditions
    warp.top.pboundxy = warp.periodic  #reflect#absorb
    warp.top.pbound0 = warp.absorb
    warp.top.pboundnz = warp.absorb

    if dim == "1d":
        warp.w3d.boundxy = warp.periodic
        warp.top.pboundxy = warp.periodic

    #-------------------------------------------------------------------------------
    # Plasma channel
    #-------------------------------------------------------------------------------
    #  Matched spot size in channel (a0)
    #  Note - to decrease channel dN at SIGMA, make matchspot > SIGMA
    #  then dN/dN_matched = (SIGMA^4/matchspot^4), e.g. 5.7% increase in matchspot -> 20% detuning of dN
    #  tor: matchspot/sigma = (dN_matched/dN)^0.25

    channel_region = 3.0 * laser_radius
    CHANNELFAC = 0.4  # factor by which density rise is less than matched density (to compensate self guide)
    matchspot = laser_radius * (1 / CHANNELFAC)**0.25  # channel
    max_parab_radius = 0.8 * channel_region
    max_radius = 0.96 * channel_region
    diff_density = gammafrm * 1.13e14 / (
        matchspot**4
    )  #formula for the channel density without the radius squared term
    if dim == "1d": diff_density = 0.
    norm_diff_density = diff_density / dens0  #the normalized channel density without the radius squared term
    max_diff_density = norm_diff_density * (
        max_parab_radius**2)  #the maximum normalized channel density

    #-------------------------------------------------------------------------------
    # set max time
    #-------------------------------------------------------------------------------
    tmaxlab = (Lplasma_lab) / warp.clight
    tmax = tmaxlab / gammafrm

    #-------------------------------------------------------------------------------
    # dump/plots intervals (in pico-seconds)
    #-------------------------------------------------------------------------------
    dump_intervals = tmax / 20
    beamdump_intervals = tmax / 10
    plot_intervals = tmax / 10

    #-------------------------------------------------------------------------------
    # set particles
    #-------------------------------------------------------------------------------
    weight = 1. * dens0 * warp.w3d.dx * warp.w3d.dy * warp.w3d.dz / (
        nppcellx * nppcelly * nppcellz)  # weight of plasma macro-particles
    weightbeam = 0.  # needs to be fixed

    # --- create plasma electron species
    elec = species.Species(type=species.Electron, weight=weight)
    # --- create plasma electron species
    prot = species.Species(type=species.Proton, weight=weight)
    # --- create e- beam species
    if l_beam:
        beam = species.Species(type=species.Electron, weight=weightbeam)
    # --- create plasma ion species
    # --- in this example, initial charge state is +5
    # --- charge states +6 and +7 are also considered
    ielec = species.Species(type=species.Electron, weight=weight)
    if l_ions:
        nions = 2
        ions = []
        for i in range(nions):
            ions.append(
                species.Species(type=species.Krypton,
                                charge_state=i + 8,
                                weight=weight,
                                name='ions %g' % i))

    warp.top.pgroup.ndts = warp.nint(1. / dtcoef)
    ielec.ndts = 1

    #warp.top.pgroup.sm*=1000000

    #  ions.sm*=1.e20  # to give virtually infinite mass to ions
    warp.top.wpid = warp.nextpid(
    )  # creates data space for variable weights (needed for plasma ramps)
    if runDim == 3:
        warp.top.xbirthpid = warp.nextpid()
        warp.top.ybirthpid = warp.nextpid()
        warp.top.zbirthpid = warp.nextpid()
        warp.top.uxbirthpid = warp.nextpid()
        warp.top.uybirthpid = warp.nextpid()
        warp.top.uzbirthpid = warp.nextpid()

    warp.top.depos_order[...] = warp.top.depos_order[
        0, 0]  # sets deposition order of all species = those of species 0
    warp.top.efetch[...] = warp.top.efetch[0]  # same for field gathering
    if dim in ["1d", "2d"]:
        warp.top.depos_order[1, :] = 1
    if dim == "1d":
        warp.top.depos_order[0, :] = 1

    #-------------------------------------------------------------------------------
    # set smoothing of current density
    #-------------------------------------------------------------------------------
    if l_smooth:
        # --- 1 time nilinear (0.25,0.5,0.25) + 1 time relocalization (-1, 3/2,-1.)
        npass_smooth = [[1, 1], [0, 0], [4, 1]]
        alpha_smooth = [[0.5, 3. / 2], [0.5, 3.], [0.5, 3. / 1]]
        stride_smooth = [[1, 1], [1, 1], [1, 1]]
        if dim == '1d':
            for i in range(len(npass_smooth[0])):
                npass_smooth[0][i] = 0
        if dim in ['1d', '2d']:
            for i in range(len(npass_smooth[0])):
                npass_smooth[1][i] = 0
    else:
        npass_smooth = [[0], [0], [0]]
        alpha_smooth = [[1.], [1.], [1.]]
        stride_smooth = [[1], [1], [1]]

    #-------------------------------------------------------------------------------
    # initializes WARP
    #-------------------------------------------------------------------------------
    warp.top.fstype = -1  # sets field solver to None (desactivates electrostatic solver)
    warp.package('w3d')
    warp.generate()

    #-------------------------------------------------------------------------------
    # set a few shortcuts
    #-------------------------------------------------------------------------------
    pg = warp.top.pgroup

    #-------------------------------------------------------------------------------
    # sets tunnel ionizations
    #-------------------------------------------------------------------------------
    tunnel_ioniz = tunnel_ionization.TunnelIonization(stride=1)
    for i in range(len(ions) - 1):
        # --- For each ionization level, add tunnel ionization event by registering
        # --- incident and emitted species.
        tunnel_ioniz.add(incident_species=ions[i],
                         emitted_species=[ions[i + 1], ielec])

    #-------------------------------------------------------------------------------
    # set input plasma density arrays
    #-------------------------------------------------------------------------------
    # --- set intial positions and weights
    zpos = zstart0 = 0.
    nppcell = nppcellx * nppcelly * nppcellz
    dx = warp.w3d.dx / nppcellx
    dy = warp.w3d.dy / nppcelly
    dz = warp.w3d.dz / nppcellz
    nx = nppcellx * warp.w3d.nx
    ny = nppcelly * warp.w3d.ny
    nz = nppcellz

    if dim in ["1d", "2d"]:
        if dim == "1d":
            nx = 1
            xp0, zp0 = warp.getmesh2d(0., dx, 0, dz / 2, dz, nz - 1)
            yp0 = xp0 * 0.
        else:
            xp0, zp0 = warp.getmesh2d(warp.w3d.xmmin + dx / 2, dx, nx - 1,
                                      -warp.w3d.dz + dz / 2, dz, nz - 1)
            yp0 = xp0 * 0.
    else:
        xp0, yp0, zp0 = warp.getmesh3d(warp.w3d.xmmin + dx / 2, dx, nx - 1,
                                       warp.w3d.ymmin + dy / 2, dy, ny - 1,
                                       -warp.w3d.dz + dz / 2, dz, nz - 1)

    zp0 -= warp.minnd(zp0)  # ensures that zp0 starts at 0

    # --- transform to 1D arrays
    xp0 = xp0.flatten()
    yp0 = yp0.flatten()
    zp0 = zp0.flatten()

    # --- select particles within computational box of local processor
    ii=warp.compress((xp0>=warp.w3d.xmminlocal) & (xp0<warp.w3d.xmmaxlocal) & \
                (yp0>=warp.w3d.ymminlocal) & (yp0<warp.w3d.ymmaxlocal),numpy.arange(len(xp0)))
    xp0 = warp.take(xp0, ii)
    yp0 = warp.take(yp0, ii)
    zp0 = warp.take(zp0, ii)

    # --- select particles within max_radius
    rp0 = numpy.sqrt(xp0**2 + yp0**2)
    ii = warp.compress(rp0 <= max_radius, numpy.arange(len(rp0)))
    xp0 = warp.take(xp0, ii)
    yp0 = warp.take(yp0, ii)
    zp0 = warp.take(zp0, ii)
    rp0 = numpy.sqrt(xp0**2 + yp0**2)

    # --- set the transverse profile
    wp0 = plasma_trans_profile(rp0)

    if l_plasma:
        warp.installuserinjection(loadplasma)

    #-------------------------------------------------------------------------------
    # set laser pulse numpy.shape
    #-------------------------------------------------------------------------------

    #-------------------------------------------------------------------------------
    # set laser amplitude by combining the pulse numpy.shape, laser profile, and laser phase
    #-------------------------------------------------------------------------------

    #------------------------------ add second laser--------------------------------#----------------set the time delay between two lasers--------------------------
    T_generate_laser = laser_risetime - laser_risetime1  #2*laser_dura_fwhm  # time for generate laser pulses
    Tstart_laser1 = T_generate_laser
    zstart_laser1 = zstart_laser - 21.25 * lambda_laser
    vg = math.sqrt(1 - kplab * kplab / k1lab / k1lab) * warp.clight

    #-------------------------------------------------------------------------------
    # initializes main field solver block
    #-------------------------------------------------------------------------------
    laser_func_dict = {}
    laser_func_dict[0] = laser_func
    if not l_external_field:
        laser_func_dict[1] = laser_func1

    em = warp.EM3D(
        laser_func=laser_func_dict,  # laser_func=laser_func,
        laser_source_z=0.,
        laser_source_v=-betafrm * warp.clight,
        laser_polangle=laser_polangle,
        laser_mode=2,
        laser_emax=10 * Eamp,
        stencil=stencil,
        npass_smooth=npass_smooth,
        alpha_smooth=alpha_smooth,
        stride_smooth=stride_smooth,
        l_2dxz=dim == "2d",
        l_1dz=dim == "1d",
        dtcoef=dtcoef,
        #                 l_enableovercycle=True,
        l_verbose=l_verbose)

    if l_external_field:
        warp.installothereuser(add_external_laser)

    #-------------------------------------------------------------------------------
    # restarts from dump file
    #-------------------------------------------------------------------------------
    if l_restart:
        restore(dump_file)

    #-------------------------------------------------------------------------------
    # intializes e- beam
    #-------------------------------------------------------------------------------
    if l_beam:
        # --- add beam particles
        np_beam = 4000
        warp.top.vbeam = E_BEAM_BETA * warp.clight
        if me == 0:  # --- do only if processor 0
            if np_beam == 1:
                # --- loads single test electron
                beam.addpart(x=array([0.]),
                             y=array([0.]),
                             z=array([0.]),
                             vx=array([0.]),
                             vy=array([0.]),
                             vz=array(
                                 [E_BEAM_GAMMA * E_BEAM_BETA * warp.clight]),
                             gi=array([1. / E_BEAM_GAMMA]),
                             lmomentum=True,
                             lallindomain=True)
            else:
                # --- loads e- beam
                if l_usesavedist:
                    # --- loads distribution from file
                    try:
                        ff = PR.PR(savedist + '.pdb')
                    except:
                        ff = PR.PR(savedist + '.pyp')
                    ux = ff.xp[::svstride] * GAMMAVXSIGMA
                    uy = ff.yp[::svstride] * GAMMAVYSIGMA
                    uz = ff.dp[::
                               svstride] * GAMMAVZSIGMA + E_BEAM_GAMMA * E_BEAM_BETA * warp.clight
                    gi = 1. / math.sqrt(1. + (ux**2 + uy**2 + uz**2) /
                                        warp.clight**2)
                    beam.addpart(ff.x[::svstride] * E_BEAM_RADIUS * 2,
                                 ff.y[::svstride] * E_BEAM_RADIUS * 2,
                                 ff.z[::svstride] * E_BEAM_LENGTH,
                                 ux,
                                 uy,
                                 uz,
                                 gi=gi,
                                 lmomentum=True,
                                 lallindomain=True)
                else:
                    # --- loads gaussian electron beam
                    beam.add_gaussian_dist(np=np_beam,
                                           deltax=E_BEAM_RADIUS * 2 * 1,
                                           deltay=E_BEAM_RADIUS * 2 * 1,
                                           deltaz=E_BEAM_LENGTH,
                                           vthx=GAMMAVXSIGMA * 1,
                                           vthy=GAMMAVYSIGMA * 1,
                                           vthz=GAMMAVZSIGMA,
                                           zmean=0.,
                                           vzmean=E_BEAM_GAMMA * E_BEAM_BETA *
                                           warp.clight,
                                           lmomentum=True,
                                           lallindomain=True,
                                           zdist='regular')
        np_beam = beam.getn()
        # --- sets e- beam macro-particles weight
        if dim == "1d":
            beam.sw = (E_BEAM_DENSITY_PEAK *
                       ((E_BEAM_RADIUS * 2) * warp.w3d.dx * warp.w3d.dy *
                        E_BEAM_LENGTH * (2. * math.pi))) / np_beam
        if dim == "2d":
            beam.sw = (E_BEAM_DENSITY_PEAK *
                       ((E_BEAM_RADIUS * 2) * warp.w3d.dy * E_BEAM_LENGTH *
                        (2. * math.pi))) / np_beam
        if dim == "3d":
            beam.sw = (E_BEAM_DENSITY_PEAK *
                       ((E_BEAM_RADIUS * 2)**2 * E_BEAM_LENGTH *
                        (2. * math.pi) * 1.5)) / np_beam
        # --- install e- beam diagnostic routine
        if sum(pg.nps) > 0:
            # --- set beam position in lab frame
            pg.zp += zstart0 - E_BEAM_DISTANCE_BEHIND_LASER - 0.5 * laser_total_length_lab
        # --- transform particle positions and velocity to boosted frame
        bf = Boosted_Frame(gammafrm, l_setselfb=0)
        zinit = getz().copy()
        bf.boost(beam,
                 l_inject_plane=l_injectplane,
                 lallindomain=1,
                 l_rmzmean=0,
                 zinject=-5. * warp.w3d.dz)
        particleboundaries3d(warp.top.pgroup, -1, False)

    #-------------------------------------------------------------------------------
    # register solver
    #-------------------------------------------------------------------------------
    print 'register solver'
    warp.registersolver(em)
    if runDim == 3:
        em.finalize()
    print warp.getregisteredsolver().dict_of_grids

    #-------------------------------------------------------------------------------
    # sets moving window velocity
    #-------------------------------------------------------------------------------
    if l_moving_window:
        #warp.top.vbeamfrm=BETAG_LINEAR*warp.clight
        warp.top.vbeamfrm = warp.clight
    #-------------------------------------------------------------------------------
    # set a few shortcuts
    #-------------------------------------------------------------------------------
    #el=elec
    #f = em.fields
    #bhist=numpy.ones([nions,warp.w3d.nz+1])
    #bhist[1:,:]=0.
    #def accuhist():
    # global bhist
    # for i in range(nions-2,-1,-1):
    #  Ex = em.gatherex()
    #  Ey = em.gatherey()
    # if me==0:
    #  E = math.sqrt(Ex*Ex+Ey*Ey)
    # E0 = numpy.where(E<=1.e-10*Eamp,1.e-10*Eamp,E)
    # dn = numpy.where(E==0.,0.,top.dt*tunnel_ioniz.GetADKrateSI(abs(E0),i+8,ions[i].type,top.dt))
    # bhist[i+1,:]+=dn*bhist[i]
    # bhist[i,:]-=dn*bhist[i]

    #installafterstep(accuhist)

    #window(1,hcp='lineout.cgm',dump=1,display='')
    #window(2,hcp='Ex.cgm',dump=1,display='')

    #if enableWarpLivePlots :
    #    installafterstep(liveplots)

    # make it visible to visit
    warp.listofallspecies = species.listofallspecies

    # add filtered species for ionized electrons
    # for now it should be at index 2...
    iElec = warp.listofallspecies[2]
    iElecCore = WarpVisItSpeciesFilters.CreateFilteredSpecies(
        iElec, 'HaloFilter', 'halo')
    warp.listofallspecies.append(iElecCore)

    # print species
    i = 0
    for s in warp.listofallspecies:
        print 'species %d %s %s' % (i, s.type.name, str(s.name))
        i += 1

    if (len(warp.listofallspecies) < 1):
        raise RuntimeError('no particle species!')

    return
Beispiel #20
0
sys.path.append("/home/alacny/Programowanie/Python/Pandemic/lib")
import species as h
import world as w

# Initial number of persons
maxP=100
# Range of infection
rInf=10

# Max time of the simulation
tMax = 10000

# Creating persons
person=[]
for i in range(0,maxP):
   person.append(h.Species())

# Initial infection
person[0].raiseInfection(1)
person[0].goToXY(0,0)

outF = open("pandemic.out","w")
outNInf = open("infected.out","w")

# Number of infected species
nInf=1
# Main loop
for t in range(0,tMax):
# Moving persons
    x=list()
    y=list()
def AddToReaction(name, reaction):
    reaction.append(species.Species(name))
Beispiel #22
0
import util
import species

import matplotlib.pyplot as plt

############### SORT LEVELS ##################

constants = util.Constants()

nMax = 30

speciesList = ['O', 'O+', 'F+', 'Ne++']

allSpecies = []
for speciesStr in speciesList:
    speciesObj = species.Species(speciesStr)
    allSpecies.append([speciesObj, spectra.readNISTSpectra(speciesObj)])

O = species.Species('O')

use = O

NIST = spectra.readNISTSpectra(use)
theory = spectra.calculateExpectedStates(use, nMax)

calcEnergy = spectra.CalcEnergy(nMax, use, NIST, theory, allSpecies)
completeLevels, calculatedLevels = calcEnergy.populateTheory()

calculatedLevels = spectra.sortSpectra(calculatedLevels, 'calculated')
completeLevels = spectra.sortSpectra(completeLevels, 'complete')
Beispiel #23
0
def generate_Species(obj):
    if isinstance(obj, parseobj.AnyCallable):
        obj = obj._as_ParseObj()

    if isinstance(obj, parseobj.ParseObj):
        sp = species.Species()
        for elem in obj._elements():
            su = species.Subunit(elem.name)
            if elem.args is not None:
                for mod in elem.args:
                    if is_parseobj(mod) and mod._size() == 1:
                        arg = mod._elements()[0]
                        name, binding = arg.name, arg.modification
                        if binding is None:
                            su.add_modification(name, "", "")
                        else:
                            binding = str(binding)
                            if not (binding.isdigit() or binding == ""
                                or binding[0] == "_"):
                                raise RuntimeError, (
                                    "invalid binding [%s] given." % (binding))
                            su.add_modification(name, "", binding)
                    elif (isinstance(mod, parseobj.InvExp)
                        and is_parseobj(mod._target())
                        and mod._target()._size() == 1):
                        arg = mod._target()._elements()[0]
                        name, binding = arg.name, arg.modification
                        if binding is not None:
                            raise RuntimeError, (
                                "invalid binding [%s] given." % (binding))
                        su.add_exclusion(name)
                    elif isinstance(mod, tuple):
                        if any([not isinstance(dom, parseobj.AnyCallable)
                            for dom in mod]):
                            raise RuntimeError, (
                                "invalid commutative definition [%s] found"
                                % (str(mod)))

                        doms = [dom._elements()[0].name for dom in mod]
                        su.set_commutative(doms)
                    else:
                        raise RuntimeError, (
                            "invalid argument [%s] found." % str(mod))
            if elem.kwargs is not None:
                for name, value in elem.kwargs.items():
                    if is_parseobj(value) and value._size() == 1:
                        arg = value._elements()[0]
                        state, binding = str(arg.name), arg.modification
                        if binding is None:
                            su.add_modification(name, state, "")
                        else:
                            binding = str(binding)
                            if not (binding.isdigit() or binding == ""
                                or binding[0] == "_"):
                                raise RuntimeError, (
                                    "invalid binding [%s] given." % (binding))
                            su.add_modification(name, state, binding)
                    elif ((isinstance(value, list) or isinstance(value, tuple))
                        and all([is_parseobj(dom) and dom._size() == 1
                            for dom in value])):
                        doms = tuple(dom._elements()[0].name for dom in value)
                        su.add_domain_class(name, doms)

                        if isinstance(value, tuple):
                            su.set_commutative(doms)
                    else:
                        raise RuntimeError, (
                            "invalid argument [%s] found." % str(value))
            sp.add_subunit(su)
        return (sp, )
    elif isinstance(obj, parseobj.InvExp):
        return (None, )
    elif isinstance(obj, parseobj.AddExp):
        subobjs = obj._elements()
        return tuple(generate_Species(subobj)[0] for subobj in subobjs)

    raise RuntimeError, 'invalid expression; "%s" given' % str(obj)
Beispiel #24
0
 def setUp(self):
     self.spec = species.Species(0, 1, 1, [])