Ejemplo n.º 1
0
def time_particlescalars():
    import postpic as pp
    import timeit
    pp.chooseCode('dummy')
    dr1 = pp.readDump(0.01e6, dimensions=3)
    dr2 = pp.readDump(1.0e6, dimensions=3)
    ms1 = pp.MultiSpecies(dr1, 'electron')
    ms2 = pp.MultiSpecies(dr2, 'electron')
    testexprs = [
        'x', 'x + y + z', 'gamma', 'beta', 'angle_xy', 'angle_xaxis',
        'sqrt(x**2 + y**2 + z**2)', 'r_xyz',
        '(gamma > 1.5) & (angle_xaxis < 0.2) & (r_xyz < 2)'
    ]
    print('')
    print(
        'calculation times for n million particles, averaged over 3 calculations each...'
    )
    headformat = ' {:2s}  | {:6s} | {:6s} | {:s}'
    print(headformat.format('n', ' t', ' t/n', 'per particle quantity'))
    print(headformat.format('', ' ms', 'ms/mio', ''))

    def timeexpr(expr, ms):
        t = timeit.Timer(lambda: ms(expr))
        tc = t.timeit(number=3) / 3.0
        npartmio = len(ms) / 1e6
        print('{:4.2f} | {:6.2f} | {:6.2f} | "{}"'.format(
            npartmio, tc * 1e3, (tc * 1e3) / npartmio, expr))

    for expr in testexprs:
        for ms in (ms1, ms2):
            timeexpr(expr, ms)
Ejemplo n.º 2
0
 def test_kspace_propagate(self):
     pp.chooseCode('dummy')
     dr = pp.readDump(10000, dimensions=2)
     kspace = pp.helper.kspace("Ex",
                               fields=dict(Ex=dr.Ex(),
                                           By=dr.By(),
                                           Bz=dr.Bz()))
     pp.helper.kspace_propagate(kspace, 0.1, moving_window_vect=(1, 0))
Ejemplo n.º 3
0
 def test_kspace_epoch_like(self):
     pp.chooseCode('dummy')
     for d in (1,2,3):
         dr = pp.readDump(10000, dimensions=d)
         fields = dict(Ex=dr.Ex(), By=dr.By(), Bz=dr.Bz())
         for k, v in fields.items():
             print(k, v.extent)
         kspace = pp.helper.kspace_epoch_like("Ex", fields, 0.1)
Ejemplo n.º 4
0
 def test_kspace_epoch_like(self):
     pp.chooseCode('dummy')
     for d in (1, 2, 3):
         dr = pp.readDump(10000, dimensions=d)
         fields = dict(Ex=dr.Ex(), By=dr.By(), Bz=dr.Bz())
         for k, v in fields.items():
             print(k, v.extent)
         kspace = pp.helper.kspace_epoch_like("Ex", fields, 0.1)
Ejemplo n.º 5
0
    def test_kspace(self):
        pp.chooseCode('dummy')
        for d in (1,2,3):
            dr = pp.readDump(10000, dimensions=d)
            kspace = pp.helper.kspace("Ex", fields=dict(Ex=dr.Ex(), By=dr.By(), Bz=dr.Bz()))

        omega = pp.helper.omega_yee_factory([ax.grid[1] - ax.grid[0] for ax in dr.Ey().axes], 1e-10)
        kspace = pp.helper.kspace("Ex", fields=dict(Ex=dr.Ex(), By=dr.By(), Bz=dr.Bz()), omega_func=omega)

        kspace = pp.helper.kspace("Ex", fields=dict(Ex=dr.Ex(), By=dr.By(), Bz=dr.Bz()), extent=[0, 0.5, 0, 0.5, 0, 0.5])
Ejemplo n.º 6
0
def time_particleidsort():
    import postpic as pp
    import numpy as np
    from timeit import default_timer as timer
    pp.chooseCode('dummy')
    dr = pp.readDump(1e6, dimensions=3)
    ms = pp.MultiSpecies(dr, 'electron')

    def timeid(ms, ids):
        t0 = timer()
        ms2 = ms.compress(ids)
        tf = timer()
        print('npart = {:.1e}, fraction_taken ={:6.2f}%, time ={:6.2f}ms' \
              .format(len(ms), len(ms2)/len(ms)*100, (tf-t0)*1e3))

    print('')
    print('time to take a fraction of the particles by their ids')
    timeid(ms, np.arange(100))
    timeid(ms, np.arange(len(ms) / 20))
    timeid(ms, np.arange(len(ms)))
Ejemplo n.º 7
0
def time_particleidfilter():
    import postpic as pp
    import numpy as np
    from timeit import default_timer as timer
    pp.chooseCode('dummy')
    dr = pp.readDump(1e6, dimensions=3)
    ms = pp.MultiSpecies(dr, 'electron')

    def timefilter(ms, expr):
        t0 = timer()
        ms2 = ms.filter(expr)
        tf = timer()
        print('npart = {:.1e}, fraction_taken = {:6.2f}%, time = {:6.2f}ms, expr: "{}"' \
              .format(len(ms), len(ms2)/len(ms)*100, (tf-t0)*1e3, expr))

    print('')
    print('time to filter to a fraction of the particles by expression')
    timefilter(ms, 'x > 0')
    timefilter(ms, 'gamma > 1.5')
    timefilter(ms, '(gamma > 1.5) & (angle_xaxis < 0.2) & (r_xyz < 2)')
Ejemplo n.º 8
0
    def test_kspace(self):
        pp.chooseCode('dummy')
        for d in (1, 2, 3):
            dr = pp.readDump(10000, dimensions=d)
            kspace = pp.helper.kspace("Ex",
                                      fields=dict(Ex=dr.Ex(),
                                                  By=dr.By(),
                                                  Bz=dr.Bz()))

        omega = pp.helper.omega_yee_factory(
            [ax.grid[1] - ax.grid[0] for ax in dr.Ey().axes], 1e-10)
        kspace = pp.helper.kspace("Ex",
                                  fields=dict(Ex=dr.Ex(),
                                              By=dr.By(),
                                              Bz=dr.Bz()),
                                  omega_func=omega)

        kspace = pp.helper.kspace("Ex",
                                  fields=dict(Ex=dr.Ex(),
                                              By=dr.By(),
                                              Bz=dr.Bz()),
                                  extent=[0, 0.5, 0, 0.5, 0, 0.5])
Ejemplo n.º 9
0
def main():
    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib
    matplotlib.use('Agg')

    # choose the dummy reader. This reader will create fake data for testing.
    pp.chooseCode('dummy')

    # Create a dummy reader with 300 particles, not initialized with a seed and use
    # uniform distribution
    dr = pp.readDump(300, seed=None, randfunc=np.random.random)
    # set and create directory for pictures.
    savedir = '_examplepictures/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr,
                                     outdir=savedir,
                                     autosave=True,
                                     project='particleshapedemo')

    # we will need a refrence to the MultiSpecies quite often
    from postpic import MultiSpecies as MS

    # create MultiSpecies object for every particle species that exists.
    pas = [MS(dr, s) for s in dr.listSpecies()]

    # --- 1D visualization of particle contributions ---

    def particleshapedemo(shape):
        import postpic.cythonfunctions as cf
        import matplotlib.pyplot as plt
        ptclpos = np.array([4.5, 9.75, 15.0, 20.25])
        y, edges = cf.histogram(ptclpos, bins=25, range=(0, 25), shape=shape)
        x = np.convolve(edges, [0.5, 0.5], mode='valid')
        fig = plt.figure()
        fig.suptitle('ParticleShape: {:s}'.format(str(shape)))
        ax = fig.add_subplot(111)
        ax.plot(x, y)
        ax.set_ylim((0, 1))
        ax.set_xticks(x, minor=True)
        ax.grid(which='minor')
        for ix in ptclpos:
            ax.axvline(x=ix, color='y')
        fig.savefig(savedir + 'particleshapedemo{:s}.png'.format(str(shape)),
                    dpi=160)
        plt.close(fig)

    if True:
        particleshapedemo(0)
        particleshapedemo(1)
        particleshapedemo(2)

    # --- 1D ---
    if True:
        pa = pas[0]
        plotargs = {'ylim': (0, 1600), 'log10plot': False}

        # 1 particle per cell
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 300,
                               'shape': 0
                           },
                           title='1ppc_order0',
                           rangex=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 300,
                               'shape': 1
                           },
                           title='1ppc_order1',
                           rangex=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 300,
                               'shape': 2
                           },
                           title='1ppc_order2',
                           rangex=(0, 1)), **plotargs)

        # 3 particles per cell
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 100,
                               'shape': 0
                           },
                           title='3ppc_order0',
                           rangex=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 100,
                               'shape': 1
                           },
                           title='3ppc_order1',
                           rangex=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 100,
                               'shape': 2
                           },
                           title='3ppc_order2',
                           rangex=(0, 1)), **plotargs)

        # 10 particles per cell
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 30,
                               'shape': 0
                           },
                           title='10ppc_order0',
                           rangex=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 30,
                               'shape': 1
                           },
                           title='10ppc_order1',
                           rangex=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           optargsh={
                               'bins': 30,
                               'shape': 2
                           },
                           title='10ppc_order2',
                           rangex=(0, 1)), **plotargs)

    # --- 2D ---
    if True:
        dr = pp.readDump(300 * 30, seed=None, randfunc=np.random.random)
        pa = MS(dr, dr.listSpecies()[0])
        plotargs = {'clim': (0, 3e4), 'log10plot': False}

        # 1 particle per cell
        plotter.plotField(
            pa.createField(MS.X,
                           MS.Y,
                           optargsh={
                               'bins': (300, 30),
                               'shape': 0
                           },
                           title='1ppc_order0',
                           rangex=(0, 1),
                           rangey=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           MS.Y,
                           optargsh={
                               'bins': (300, 30),
                               'shape': 1
                           },
                           title='1ppc_order1',
                           rangex=(0, 1),
                           rangey=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           MS.Y,
                           optargsh={
                               'bins': (300, 30),
                               'shape': 2
                           },
                           title='1ppc_order2',
                           rangex=(0, 1),
                           rangey=(0, 1)), **plotargs)

        # 3 particles per cell
        plotter.plotField(
            pa.createField(MS.X,
                           MS.Y,
                           optargsh={
                               'bins': (100, 10),
                               'shape': 0
                           },
                           title='3ppc_order0',
                           rangex=(0, 1),
                           rangey=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           MS.Y,
                           optargsh={
                               'bins': (100, 10),
                               'shape': 1
                           },
                           title='3ppc_order1',
                           rangex=(0, 1),
                           rangey=(0, 1)), **plotargs)
        plotter.plotField(
            pa.createField(MS.X,
                           MS.Y,
                           optargsh={
                               'bins': (100, 10),
                               'shape': 2
                           },
                           title='3ppc_order2',
                           rangex=(0, 1),
                           rangey=(0, 1)), **plotargs)

    # --- 3D ---
    if True:
        dr = pp.readDump(300 * 30,
                         seed=None,
                         randfunc=np.random.random,
                         dimensions=3)
        pa = MS(dr, dr.listSpecies()[0])
        # just try to create the field. not plotting routines yet
        f = pa.createField(MS.X,
                           MS.Y,
                           MS.Z,
                           optargsh={
                               'bins': (30, 30, 10),
                               'shape': 2
                           },
                           title='1ppc_order2',
                           rangex=(0, 1),
                           rangey=(0, 1),
                           rangez=(0, 1))
Ejemplo n.º 10
0
 def test_kspace_propagate(self):
     pp.chooseCode('dummy')
     dr = pp.readDump(10000, dimensions=2)
     kspace = pp.helper.kspace("Ex", fields=dict(Ex=dr.Ex(), By=dr.By(), Bz=dr.Bz()))
     pp.helper.kspace_propagate(kspace, 0.1, moving_window_vect=(1,0))
Ejemplo n.º 11
0
def main():
    import os
    if not os.path.exists('examples/_openPMDdata'):
        os.mkdir('examples/_openPMDdata')
    download('https://github.com/openPMD/openPMD-example-datasets/'
           + 'raw/776ae3a96c02b20cfae56efafcbda6ca76d4c78d/example-2d.tar.gz',
             'examples/_openPMDdata/example-2d.tar.gz')

    import tarfile
    tar = tarfile.open('examples/_openPMDdata/example-2d.tar.gz')
    tar.extractall('examples/_openPMDdata')


    # now that files are downloaded and extracted, start data evaluation

    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib; matplotlib.use('Agg')
    pp.chooseCode('openpmd')
    dr = pp.readDump('examples/_openPMDdata/example-2d/hdf5/data00000300.h5')
    # set and create directory for pictures.
    savedir = '_examplepictures/openPMD/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr, outdir=savedir, autosave=True, project='OpenPMD')

    # we will need a refrence to the MultiSpecies quite often
    from postpic import MultiSpecies as MS

    # create MultiSpecies Object for every particle species that exists.
    pas = [MS(dr, s) for s in dr.listSpecies()]

    if True:
        # Plot Data from the FieldAnalyzer fa. This is very simple: every line creates one plot
        plotter.plotField(dr.Ex())  # plot 0
        plotter.plotField(dr.Ey())  # plot 1
        plotter.plotField(dr.Ez())  # plot 2
        plotter.plotField(dr.energydensityEM())  # plot 3

        # Using the MultiSpecies requires an additional step:
        # 1) The MultiSpecies.createField method will be used to create a Field object
        # with choosen particle scalars on every axis
        # 2) Plot the Field object
        optargsh={'bins': [200,50]}
        for pa in pas:
            # Remark on 2D or 3D Simulation:
            # the data fields for the plots in the following section are build by postpic
            # only from the particle data. The following plots would just the same,
            # if we would use the data of a 3D Simulation instead.

            # create a Field object nd holding the number density
            nd = pa.createField(MS.Z, MS.X, optargsh=optargsh,simextent=False)
            # plot the Field object nd
            plotter.plotField(nd, name='NumberDensity')   # plot 4
            # more advanced: create a field holding the total kinetic energy on grid
            ekin = pa.createField(MS.Z, MS.X, weights=MS.Ekin_MeV, optargsh=optargsh, simextent=False)
            # The Field objectes can be used for calculations. Here we use this to
            # calculate the average kinetic energy on grid and plot
            plotter.plotField(ekin / nd, name='Avg Kin Energy (MeV)')  # plot 5

            # use optargsh to force lower resolution
            # plot number density
            plotter.plotField(pa.createField(MS.Z, MS.X, optargsh=optargsh), lineoutx=True, lineouty=True)  # plot 6
            # plot phase space
            plotter.plotField(pa.createField(MS.Z, MS.P, optargsh=optargsh))  # plot 7
            plotter.plotField(pa.createField(MS.Z, MS.gamma, optargsh=optargsh))  # plot 8
            plotter.plotField(pa.createField(MS.Z, MS.beta, optargsh=optargsh))  # plot 9


    if True:
        # instead of reading a single dump read a collection of dumps using the simulationreader
        sr = pp.readSim('examples/_openPMDdata/example-2d/hdf5/*.h5')
        print('There are {:} dumps in this simulationreader object:'.format(len(sr)))
        # now you can iterate over the dumps written easily
        for dr in sr:
            print('Simulation time of current dump t = {:.2e} s'.format(dr.time()))
            # there are the frames of a movie:
            plotter.plotField(dr.Ez())
Ejemplo n.º 12
0
def main():
    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib; matplotlib.use('Agg')


    # choose the dummy reader. This reader will create fake data for testing.
    pp.chooseCode('dummy')

    dr = pp.readDump(3e5)  # Dummyreader takes a float as argument, not a string.
    # set and create directory for pictures.
    savedir = '_examplepictures/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr, outdir=savedir, autosave=True, project='simpleexample')

    # we will need a refrence to the MultiSpecies quite often
    from postpic import MultiSpecies as MS

    # create MultiSpecies Object for every particle species that exists.
    pas = [MS(dr, s) for s in dr.listSpecies()]

    if True:
        # Plot Data from the FieldAnalyzer fa. This is very simple: every line creates one plot
        plotter.plotField(dr.Ex())  # plot 0
        plotter.plotField(dr.Ey())  # plot 1
        plotter.plotField(dr.Ez())  # plot 2
        plotter.plotField(dr.energydensityEM())  # plot 3

        # Using the MultiSpecies requires an additional step:
        # 1) The MultiSpecies.createField method will be used to create a Field object
        # with choosen particle scalars on every axis
        # 2) Plot the Field object
        optargsh={'bins': [300,300]}
        for pa in pas:
            # create a Field object nd holding the number density
            nd = pa.createField(MS.X, MS.Y, optargsh=optargsh,simextent=True)
            # plot the Field object nd
            plotter.plotField(nd, name='NumberDensity')   # plot 4
            # more advanced: create a field holding the total kinetic energy on grid
            ekin = pa.createField(MS.X, MS.Y, weights=MS.Ekin_MeV, optargsh=optargsh, simextent=True)
            # The Field objectes can be used for calculations. Here we use this to
            # calculate the average kinetic energy on grid and plot
            plotter.plotField(ekin / nd, name='Avg Kin Energy (MeV)')  # plot 5

            # use optargsh to force lower resolution
            # plot number density
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh=optargsh), lineoutx=True, lineouty=True)  # plot 6
            # plot phase space
            plotter.plotField(pa.createField(MS.X, MS.P, optargsh=optargsh))  # plot 7
            plotter.plotField(pa.createField(MS.X, MS.gamma, optargsh=optargsh))  # plot 8
            plotter.plotField(pa.createField(MS.X, MS.beta, optargsh=optargsh))  # plot 9

            # same with high resolution
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': [1000,1000]}))  # plot 10
            plotter.plotField(pa.createField(MS.X, MS.P, optargsh={'bins': [1000,1000]}))  # plot 11

            # advanced: postpic has already defined a lot of particle scalars as Px, Py, Pz, P, X, Y, Z, gamma, beta, Ekin, Ekin_MeV, Ekin_MeV_amu, ... but if needed you can also define your own particle scalar on the fly.
            # In case its regularly used it should be added to postpic. If you dont know how, just let us know about your own useful particle scalar by email or adding an issue at
            # https://github.com/skuschel/postpic/issues

            # define your own particle scalar: p_r = sqrt(px**2 + py**2)/p
            def p_r(ms):
                return np.sqrt(ms.Px()**2 + ms.Py()**2) / ms.P()
            # add unit and name for automatic labeling when plotted with plotField method
            p_r.unit=''
            p_r.name='$\sqrt{P_x^2 + P_y^2} / P$'
            # define another own particle scalar: r = sqrt(x**2 + y**2)
            def r(ms):
                return np.sqrt(ms.X()**2 + ms.Y()**2)
            r.unit='m'
            r.name='r'
            # use the plotter with the particle scalars defined above.
            plotter.plotField(pa.createField(r, p_r, optargsh={'bins':[400,400]}))  # plot 12

            # choose particles by their properies
            def cf(ms):
                return ms.X() > 0.0  # only use particles with x > 0.0
            cf.name = 'x>0'
            pa.compressfn(cf)
            # plot 13, compare with plot 10
            plotter.plotField(pa.createField(MS.X, MS.Y, optargsh={'bins': [1000,1000]}))
            # plot 14, compare with plot 12
            plotter.plotField(pa.createField(r, p_r, optargsh={'bins':[400,400]}))
Ejemplo n.º 13
0
 def setUp(self):
     pp.chooseCode('dummy')
     self.dr = pp.readDump(10000)
#################
##  postpic define ###

import postpic as pp

print pp.__version__  # postpic version

pp.chooseCode('epoch')
dr = pp.readDump('Data/0020.sdf')
print(dr)
# the dumpreader knwos all the information of the simulation
print('The simulations was running on {} spatial dimensions.'.format(
    dr.simdimensions()))

# if needed, postpic can be bypassed and the underlying datastructure (sdf in this case)
# can be accessed directly via keys
print(dr.keys())
print dr['Header']

print(dr.listSpecies()
      )  # the multispecies Object is used to access particle data
ms = pp.MultiSpecies(dr, 'electron')
# ms is representing the species "Electrons"
print(ms)

x = ms('x')
print(len(x))

# you can look at  for a list of predefined values
#print pp.particle_scalars
Ejemplo n.º 15
0
 def setUp(self):
     self._tempfiles = []
     pp.chooseCode('DUMMY')
     self.dump = pp.datareader.readDump(100)
     self.testfield = self.dump.Ey()
Ejemplo n.º 16
0
 def setUp(self):
     pp.chooseCode('dummy')
     self.dr = pp.readDump(10000)
Ejemplo n.º 17
0
 def setUp(self):
     self._tempfiles = []
     pp.chooseCode('DUMMY')
     self.dump = pp.datareader.readDump(100)
     self.testfield = self.dump.Ey()
Ejemplo n.º 18
0
def main():
    import os
    import os.path as osp
    datadir = 'examples/kspace-test-2d'
    tarball = osp.join(datadir, 'kspace-test-2d-resources.tar.gz')
    tarball_url = 'https://blinne.net/files/postpic/kspace-test-2d-resources.tar.gz'
    if not os.path.exists(datadir):
        os.mkdir(datadir)
    s = download(tarball_url, tarball)

    if s:
        import hashlib
        chksum = hashlib.sha256(open(tarball, 'rb').read()).hexdigest()
        if chksum != "54bbeae19e1f412ddd475f565c2193e92922ed8a22e7eb3ecb4d73b5cf193b24":
            os.remove(tarball)
            s = False

    if not s:
        print('Failed to Download example data. Skipping this example.')
        return

    import tarfile
    tar = tarfile.open(tarball)
    tar.extractall(datadir)

    import matplotlib
    matplotlib.use('Agg')

    font = {'size': 12}
    matplotlib.rc('font', **font)

    import copy
    import postpic as pp
    import numpy as np
    import pickle

    try:
        import sdf
        sdfavail = True
    except ImportError:
        sdfavail = False

    # basic constants
    micro = 1e-6
    femto = 1e-15
    c = pp.PhysicalConstants.c

    # known parameters from simulation
    lam = 0.5 * micro
    k0 = 2 * np.pi / lam
    f0 = pp.PhysicalConstants.c / lam

    pymajorver = str(sys.version_info[0])

    if sdfavail:
        pp.chooseCode("EPOCH")

        dump = pp.readDump(osp.join(datadir, '0002.sdf'))
        plotter = pp.plotting.plottercls(dump, autosave=False)
        fields = dict()
        for fc in ['Ey', 'Bz']:
            fields[fc] = getattr(dump, fc)()
            fields[fc].saveto(osp.join(datadir, '0002_' + fc + pymajorver),
                              compressed=False)
        t = dump.time()
        dt = t / dump.timestep()
        pickle.dump(
            dict(t=t, dt=dt),
            open(osp.join(datadir, '0002_meta' + pymajorver + '.pickle'),
                 'wb'))
    else:
        fields = dict()
        for fc in ['Ey', 'Bz']:
            fields[fc] = pp.Field.loadfrom(
                osp.join(datadir, '0002_{}.npz').format(fc + pymajorver))
        meta = pickle.load(
            open(osp.join(datadir, '0002_meta' + pymajorver + '.pickle'),
                 'rb'))
        t = meta['t']
        dt = meta['dt']
        plotter = pp.plotting.plottercls(None, autosave=False)

    Ey = fields['Ey']
    # grid spacing from field
    dx = [ax.grid[1] - ax.grid[0] for ax in Ey.axes]

    #w0 = 2*np.pi*f0
    #w0 = pp.PhysicalConstants.c * k0

    wn = np.pi / dt
    omega_yee = pp.helper.omega_yee_factory(dx=dx, dt=dt)

    wyee = omega_yee([k0, 0])
    w0 = pp.helper.omega_free([k0, 0])

    print('dx', dx)
    print('t', t)
    print('dt', dt)
    print('wn', wn)
    print('w0', w0)
    print('wyee', wyee)
    print('wyee/w0', wyee / w0)
    print('wyee/wn', wyee / wn)
    print('lam/dx[0]', lam / dx[0])

    print('cos(1/2 wyee dt)', np.cos(1 / 2 * wyee * dt))

    vg_yee = c * np.cos(
        k0 * dx[0] /
        2.0) / np.sqrt(1 - (c * dt / dx[0] * np.sin(k0 * dx[0] / 2.0))**2)
    print('vg/c', vg_yee / c)

    r = np.sqrt(1.0 - (pp.PhysicalConstants.c * dt)**2 *
                (1 / dx[0] * np.sin(1 / 2.0 * k0 * dx[0]))**2)
    print('r', r)

    # In[2]:

    omega_yee = pp.helper.omega_yee_factory(dx=Ey.spacing, dt=dt)
    lin_int_response_omega = pp.helper._linear_interpolation_frequency_response(
        dt)
    lin_int_response_k = pp.helper._linear_interpolation_frequency_response_on_k(
        lin_int_response_omega,
        Ey.fft().axes, omega_yee)

    lin_int_response_k_vac = pp.helper._linear_interpolation_frequency_response_on_k(
        lin_int_response_omega,
        Ey.fft().axes, pp.helper.omega_free)

    # In[3]:

    _ = plotter.plotField(Ey[:, 0.0])

    # In[4]:

    kspace = dict()
    component = "Ey"

    # In[5]:

    #key = 'default epoch map=yee, omega=vac'
    key = 'linresponse map=yee, omega=vac'
    if sdfavail:
        kspace[key] = abs(dump.kspace_Ey(solver='yee'))
    else:
        kspace[key] = abs(
            pp.helper.kspace(component,
                             fields=dict(Ey=fields['Ey'],
                                         Bz=fields['Bz'].fft() /
                                         lin_int_response_k),
                             interpolation='fourier'))
        #  using the helper function `kspace_epoch_like` would yield same result:
        # kspace[key] = abs(pp.helper.kspace_epoch_like(component, fields=fields, dt=dt, omega_func=omega_yee))
    normalisation = 1.0 / np.max(kspace[key].matrix)
    kspace[key] *= normalisation
    kspace[key].name = r'corrected $\vec{k}$-space, $\omega_0=c|\vec{k}|$'
    kspace[key].unit = ''

    # In[6]:

    key = 'simple fft'
    kspace[key] = abs(Ey.fft()) * normalisation
    kspace[key].name = r'plain fft'
    kspace[key].unit = ''

    # In[7]:

    key = 'fourier'
    kspace[key] = abs(
        pp.helper.kspace(component, fields=fields,
                         interpolation='fourier')) * normalisation
    kspace[key].name = u'naïve $\\vec{k}$-space, $\\omega_0=c|\\vec{k}|$'
    kspace[key].unit = ''

    # In[8]:

    key = 'fourier yee'
    kspace[key] = abs(
        pp.helper.kspace(component,
                         fields=fields,
                         interpolation='fourier',
                         omega_func=omega_yee)) * normalisation
    kspace[
        key].name = u'naïve $\\vec{k}$-space, $\\omega_0=\\omega_\\mathrm{grid}$'
    kspace[key].unit = ''

    # In[9]:

    key = 'linresponse map=yee, omega=yee'
    kspace[key] = abs(
        pp.helper.kspace(component,
                         fields=dict(
                             Ey=fields['Ey'],
                             Bz=fields['Bz'].fft() / lin_int_response_k),
                         interpolation='fourier',
                         omega_func=omega_yee)) * normalisation
    kspace[
        key].name = r'corrected $\vec{k}$-space, $\omega_0=\omega_\mathrm{grid}$'
    kspace[key].unit = ''

    # In[10]:

    slices = [slice(360 - 120, 360 + 120), slice(120, 121)]

    # In[11]:

    keys = [
        'simple fft', 'fourier yee', 'fourier',
        'linresponse map=yee, omega=yee', 'linresponse map=yee, omega=vac'
    ]
    figure2 = plotter.plotFields1d(*[kspace[k][slices] for k in keys],
                                   log10plot=True,
                                   ylim=(5e-17, 5))
    figure2.set_figwidth(8)
    figure2.set_figheight(6)
    while figure2.axes[0].texts:
        figure2.axes[0].texts[-1].remove()

    figure2.axes[0].set_title('')
    figure2.axes[0].set_ylabel(r'$|E_y(k_x,0,0)|\, [a. u.]$')
    figure2.axes[0].set_xlabel(r'$k_x\,[m^{-1}]$')
    figure2.tight_layout()
    figure2.savefig(osp.join(datadir, 'gaussian-kspace.pdf'))

    print("Integrated ghost peaks")
    for k in keys:
        I = kspace[k][:0.0, :].integrate().matrix
        print(k, I)
        if k == 'linresponse map=yee, omega=vac':
            if I < 30000000.:
                print(
                    'linresponse map=yee, omega=vac value is low enough: YES')
            else:
                print('linresponse map=yee, omega=vac value is low enough: NO')
                print('Something is WRONG')
                sys.exit(1)

    # In[13]:

    if sdfavail:
        kspace_ey = dump.kspace_Ey(solver='yee')
    else:
        kspace_ey = pp.helper.kspace_epoch_like(component,
                                                fields=fields,
                                                dt=dt,
                                                omega_func=omega_yee)
    complex_ey = kspace_ey.fft()
    envelope_ey_2d = abs(complex_ey)[:, :].squeeze()
    try:
        from skimage.restoration import unwrap_phase
        phase_ey = complex_ey.replace_data(unwrap_phase(np.angle(complex_ey)))
    except ImportError:
        phase_ey = complex_ey.replace_data(np.angle(complex_ey))
    phase_ey_2d = phase_ey[:, :].squeeze()

    # In[14]:

    ey = complex_ey.real[-0.1e-5:0.2e-5, :]
    #ey = Ey

    ey.name = r'$E_y$'
    ey.unit = r'$\frac{\mathrm{V}}{\mathrm{m}}$'

    figure = plotter.plotField2d(ey)
    figure.set_figwidth(6)
    figure.axes[0].set_title(
        r'')  #$\Re E_y\ [\frac{\mathrm{V}}{\mathrm{m}}]$')
    figure.axes[0].set_xlabel(u'$x\\,[µm]$')
    figure.axes[0].set_ylabel(u'$y\\,[µm]$')

    import matplotlib.ticker as ticker
    ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x / 1e-6))
    figure.axes[0].xaxis.set_major_formatter(ticks_x)
    figure.axes[0].yaxis.set_major_formatter(ticks_x)

    try:
        figure.axes[0].images[0].colorbar.remove()
    except AttributeError:
        pass
    figure.colorbar(figure.axes[0].images[0],
                    format='%6.0e',
                    pad=0.15,
                    label=r'$\Re E_y\ [\frac{\mathrm{V}}{\mathrm{m}}]$')

    axes2 = figure.axes[0].twinx()
    axes2.set_ylabel(r'$\operatorname{Arg}(E_y)\, [\pi],\;|E_y|\, [a. u.]$')

    env = abs(complex_ey[-0.1e-5:0.2e-5, 0.0])
    m = np.max(env)
    env = (env / m * 40 / np.pi).squeeze()
    p = phase_ey[-0.1e-5:0.2e-5, 0.0].squeeze() / np.pi

    _ = axes2.plot(env.grid, env.matrix, label=r'$|E_y|\, [a. u.]$')
    _ = axes2.plot(p.grid,
                   p.matrix,
                   label=r'$\operatorname{Arg}(E_y)\, [\pi]$')

    handles, labels = axes2.get_legend_handles_labels()
    axes2.legend(handles, labels)

    #figure.axes[0].set_title(r'$E_y\,[V/m]$')

    figure.set_figwidth(6)
    figure.set_figheight(6)
    figure.tight_layout()
    figure.savefig(osp.join(datadir, 'gaussian-env-arg.pdf'))
Ejemplo n.º 19
0
 def setUp(self):
     pp.chooseCode('dummy')
     self.dr = pp.readDump(10000)
     self.p = pp.MultiSpecies(self.dr, 'electron')
Ejemplo n.º 20
0
def main():
    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib; matplotlib.use('Agg')


    # choose the dummy reader. This reader will create fake data for testing.
    pp.chooseCode('dummy')

    dr = pp.readDump(3e5)  # Dummyreader takes a float as argument, not a string.
    # set and create directory for pictures.
    savedir = '_examplepictures/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr, outdir=savedir, autosave=True, project='simpleexample')

    # we will need a refrence to the MultiSpecies quite often
    from postpic.particles import MultiSpecies

    # create MultiSpecies Object for every particle species that exists.
    pas = [MultiSpecies(dr, s) for s in dr.listSpecies()]

    if True:
        # Plot Data from the FieldAnalyzer fa. This is very simple: every line creates one plot
        plotter.plotField(dr.Ex())  # plot 0
        plotter.plotField(dr.Ey())  # plot 1
        plotter.plotField(dr.Ez())  # plot 2
        plotter.plotField(dr.energydensityEM())  # plot 3

        # Using the MultiSpecies requires an additional step:
        # 1) The MultiSpecies.createField method will be used to create a Field object
        # with choosen particle scalars on every axis
        # 2) Plot the Field object
        optargsh={'bins': [300,300]}
        for pa in pas:
            # create a Field object nd holding the number density
            nd = pa.createField('x', 'y', simextent=True, **optargsh)
            # plot the Field object nd
            plotter.plotField(nd, name='NumberDensity')   # plot 4
            # if you like to keep working with the just created number density
            # yourself, it will convert to an numpy array whenever needed:
            arr = np.asarray(nd)
            print('Shape of number density: {}'.format(arr.shape))

            # more advanced: create a field holding the total kinetic energy on grid
            ekin = pa.createField('x', 'y', weights='Ekin_MeV', simextent=True, **optargsh)
            # The Field objectes can be used for calculations. Here we use this to
            # calculate the average kinetic energy on grid and plot
            plotter.plotField(ekin / nd, name='Avg Kin Energy (MeV)')  # plot 5
            # use optargsh to force lower resolution
            # plot number density
            plotter.plotField(pa.createField('x', 'y', **optargsh), lineoutx=True, lineouty=True)  # plot 6
            # plot phase space
            plotter.plotField(pa.createField('x', 'p', **optargsh))  # plot 7
            plotter.plotField(pa.createField('x', 'gamma', **optargsh))  # plot 8
            plotter.plotField(pa.createField('x', 'beta', **optargsh))  # plot 9

            # same with high resolution
            plotter.plotField(pa.createField('x', 'y', bins=[1000,1000]))  # plot 10
            plotter.plotField(pa.createField('x', 'p', bins=[1000,1000]))  # plot 11

            # advanced: postpic has already defined a lot of particle scalars as Px, Py, Pz, P, X, Y, Z, gamma, beta, Ekin, Ekin_MeV, Ekin_MeV_amu, ... but if needed you can also define your own particle scalar on the fly.
            # In case its regularly used it should be added to postpic. If you dont know how, just let us know about your own useful particle scalar by email or adding an issue at
            # https://github.com/skuschel/postpic/issues

            # define your own particle scalar: p_r = sqrt(px**2 + py**2)/p
            plotter.plotField(pa.createField('sqrt(px**2 + py**2)/p', 'sqrt(x**2 + y**2)', bins=[400,400]))  # plot 12

            # however, since its unknown to the program, what quantities were calculated the axis of plot 12 will only say "unknown"
            # this can be avoided in two ways:
            # 1st: define your own ScalarProperty(name, expr, unit):
            p_perp = pp.particles.ScalarProperty('sqrt(px**2 + py**2)/p', name='p_perp', unit='kg*m/s')
            r_xy = pp.particles.ScalarProperty('sqrt(x**2 + y**2)', name='r_xy', unit='m')
            # this will create an identical plot, but correcly labled
            plotter.plotField(pa.createField(p_perp, r_xy, bins=[400,400]))  # plot 13
            # if those quantities are reused often, teach postip to recognize them within the string expression:
            pp.particles.particle_scalars.add(p_perp)
            #pp.particles.scalars.add(r_xy)  # we cannot execute this line, because r_xy is already predefinded
            plotter.plotField(pa.createField('p_perp', 'r_xy', bins=[400,400]))  # plot 14



            # choose particles by their properies
            # this has been the old interface, which would still work
            # def cf(ms):
            #     return ms('x') > 0.0  # only use particles with x > 0.0
            # cf.name = 'x>0.0'
            # pa.compress(cf)
            # nicer is the new filter function, which does exactly the same:
            pf = pa.filter('x>0')
            # plot 15, compare with plot 10
            plotter.plotField(pf.createField('x', 'y', bins=[1000,1000]))
            # plot 16, compare with plot 12
            plotter.plotField(pf.createField('p_perp', 'r_xy', bins=[400,400]))

            plotter.plotField(dr.divE())  # plot 13
Ejemplo n.º 21
0
def main():
    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib; matplotlib.use('Agg')


    # choose the dummy reader. This reader will create fake data for testing.
    pp.chooseCode('dummy')

    # Create a dummy reader with 300 particles, not initialized with a seed and use
    # uniform distribution
    dr = pp.readDump(300, seed=None, randfunc=np.random.random)
    # set and create directory for pictures.
    savedir = '_examplepictures/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr, outdir=savedir, autosave=True, project='particleshapedemo')

    # we will need a refrence to the MultiSpecies quite often
    from postpic import MultiSpecies as MS

    # create MultiSpecies object for every particle species that exists.
    pas = [MS(dr, s) for s in dr.listSpecies()]

    # --- 1D visualization of particle contributions ---

    def particleshapedemo(shape):
        from postpic.particles import histogramdd
        import matplotlib.pyplot as plt
        ptclpos = np.array([4.5, 9.75, 15.0, 20.25])
        y, (edges, ) = histogramdd(ptclpos, bins=25, range=(0,25), shape=shape)
        x = np.convolve(edges, [0.5, 0.5], mode='valid')
        fig = plt.figure()
        fig.suptitle('ParticleShape: {:s}'.format(str(shape)))
        ax = fig.add_subplot(111)
        ax.plot(x,y)
        ax.set_ylim((0,1))
        ax.set_xticks(x, minor=True)
        ax.grid(which='minor')
        for ix in ptclpos:
            ax.axvline(x=ix, color='y')
        fig.savefig(savedir + 'particleshapedemo{:s}.png'.format(str(shape)), dpi=160)
        plt.close(fig)

    if True:
        particleshapedemo(0)
        particleshapedemo(1)
        particleshapedemo(2)
        particleshapedemo(3)

    # --- 1D ---
    if True:
            pa = pas[0]
            plotargs = {'ylim': (0,1600), 'log10plot': False}

            # 1 particle per cell
            plotter.plotField(pa.createField('x', bins=300, shape=0, title='1ppc_order0', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=300, shape=1, title='1ppc_order1', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=300, shape=2, title='1ppc_order2', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=300, shape=3, title='1ppc_order3', rangex=(0,1)), **plotargs)

            # 3 particles per cell
            plotter.plotField(pa.createField('x', bins=100, shape=0, title='3ppc_order0', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=100, shape=1, title='3ppc_order1', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=100, shape=2, title='3ppc_order2', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=100, shape=3, title='3ppc_order3', rangex=(0,1)), **plotargs)

            # 10 particles per cell
            plotter.plotField(pa.createField('x', bins=30, shape=0, title='10ppc_order0', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=30, shape=1, title='10ppc_order1', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=30, shape=2, title='10ppc_order2', rangex=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', bins=30, shape=3, title='10ppc_order3', rangex=(0,1)), **plotargs)

    # --- 2D ---
    if True:
            dr = pp.readDump(300*30, seed=None, randfunc=np.random.random)
            pa = MS(dr, dr.listSpecies()[0])
            plotargs = {'clim': (0,3e4), 'log10plot': False}

            # 1 particle per cell
            plotter.plotField(pa.createField('x', 'y', bins=(300,30), shape=0, title='1ppc_order0', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', 'y', bins=(300,30), shape=1, title='1ppc_order1', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', 'y', bins=(300,30), shape=2, title='1ppc_order2', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', 'y', bins=(300,30), shape=3, title='1ppc_order3', rangex=(0,1), rangey=(0,1)), **plotargs)

            # 3 particles per cell
            plotter.plotField(pa.createField('x', 'y', bins=(100,10), shape=0, title='3ppc_order0', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', 'y', bins=(100,10), shape=1, title='3ppc_order1', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', 'y', bins=(100,10), shape=2, title='3ppc_order2', rangex=(0,1), rangey=(0,1)), **plotargs)
            plotter.plotField(pa.createField('x', 'y', bins=(100,10), shape=3, title='3ppc_order3', rangex=(0,1), rangey=(0,1)), **plotargs)


    # --- 3D ---
    if True:
        dr = pp.readDump(300*30, seed=None, randfunc=np.random.random, dimensions=3)
        pa = MS(dr, dr.listSpecies()[0])
        # just try to create the field. not plotting routines yet
        f = pa.createField('x', 'y', 'z', bins=(30,30,10), shape=2, title='1ppc_order2', rangex=(0,1), rangey=(0,1), rangez=(0,1))
        f = pa.createField('x', 'y', 'z', bins=(30,30,10), shape=3, title='1ppc_order3', rangex=(0,1), rangey=(0,1), rangez=(0,1))
Ejemplo n.º 22
0
tScale = 2. * np.pi / wL
tUnits = '$\\tau_L$'
EkScale = 1.e6 / (6.24e18)  # Convert to Mev: M (1e6), ev (C = 6.24e18*qe)
EkUnits = '(MeV)'
Ec = pScale * wL / qe
nC = eps0 * me * wL * wL / (qe * qe)
nScale = nC
qScale = 1e-12
qUnits = '(pC)'

xWindow = 9.  # plot region length
xForward = 6.  # plot region to show preceding xAf
linear = 0  # Linear scale plot on/off

# Read all frame data
postpic.chooseCode('EPOCH')
fdata = postpic.readDump(str(frame_file))

# Calculate required plot variables
##xGrid = fdata['Grid/Grid_mid'].data[0] / xScale
##tStart = np.abs(fdata['Grid/Grid_mid'].data[0][0]) / c
##t = (fdata['Header']['time'] - tStart) / tScale

##output_file = Path.cwd().joinpath(
##'nrg_protons_' + '{:04}'.format(args.frame) + save_ext)

##if args.hd:
##monitor_dpi = 96  # NOTE: This is for Jnana, may be different for Brahman.
##plt.figure(figsize=(1920 / monitor_dpi, 1080 / monitor_dpi),
##dpi=monitor_dpi)  # Gives us 1080p output
##mpl.rcParams.update({'font.size': 22})
Ejemplo n.º 23
0
def main():
    import os
    if not os.path.exists('examples/_openPMDdata'):
        os.mkdir('examples/_openPMDdata')
    download(
        'https://github.com/openPMD/openPMD-example-datasets/' +
        'raw/776ae3a96c02b20cfae56efafcbda6ca76d4c78d/example-2d.tar.gz',
        'examples/_openPMDdata/example-2d.tar.gz')

    import tarfile
    tar = tarfile.open('examples/_openPMDdata/example-2d.tar.gz')
    tar.extractall('examples/_openPMDdata')

    # now that files are downloaded and extracted, start data evaluation

    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib
    matplotlib.use('Agg')
    pp.chooseCode('openpmd')
    dr = pp.readDump('examples/_openPMDdata/example-2d/hdf5/data00000300.h5')
    print('The simulations was running on {} spatial dimensions.'.format(
        dr.simdimensions()))
    # set and create directory for pictures.
    savedir = '_examplepictures/openPMD/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr,
                                     outdir=savedir,
                                     autosave=True,
                                     project='openPMD')

    # we will need a refrence to the MultiSpecies quite often
    from postpic import MultiSpecies as MS

    # create MultiSpecies Object for every particle species that exists.
    pas = [MS(dr, s) for s in dr.listSpecies()]

    if True:
        # Plot Data from the FieldAnalyzer fa. This is very simple: every line creates one plot
        plotter.plotField(dr.Ex())  # plot 0
        plotter.plotField(dr.Ey())  # plot 1
        plotter.plotField(dr.Ez())  # plot 2
        plotter.plotField(dr.energydensityEM())  # plot 3

        # plot additional, derived fields if available in `dr.getderived()`
        #plotter.plotField(dr.createfieldfromkey("fields/e_chargeDensity"))

        # Using the MultiSpecies requires an additional step:
        # 1) The MultiSpecies.createField method will be used to create a Field object
        # with choosen particle scalars on every axis
        # 2) Plot the Field object
        optargsh = {'bins': [200, 50]}
        for pa in pas:
            # Remark on 2D or 3D Simulation:
            # the data fields for the plots in the following section are build by postpic
            # only from the particle data. The following plots would just the same,
            # if we would use the data of a 3D Simulation instead.

            # create a Field object nd holding the number density
            nd = pa.createField('z', 'x', simextent=False, **optargsh)
            # plot the Field object nd
            plotter.plotField(nd, name='NumberDensity')  # plot 4

            # create a Field object nd holding the charge density
            qd = pa.createField('z',
                                'x',
                                weights='charge',
                                simextent=False,
                                **optargsh)
            # plot the Field object qd
            plotter.plotField(qd, name='ChargeDensity')  # plot 5

            # more advanced: create a field holding the total kinetic energy on grid
            ekin = pa.createField('z',
                                  'x',
                                  weights='Ekin_MeV',
                                  simextent=False,
                                  **optargsh)
            # The Field objectes can be used for calculations. Here we use this to
            # calculate the average kinetic energy on grid and plot
            plotter.plotField(ekin / nd, name='Avg Kin Energy (MeV)')  # plot 6

            # use optargsh to force lower resolution
            # plot number density
            plotter.plotField(pa.createField('z', 'x', **optargsh),
                              lineoutx=True,
                              lineouty=True)  # plot 7
            # plot phase space
            plotter.plotField(pa.createField('z', 'p', **optargsh))  # plot 8
            plotter.plotField(pa.createField('z', 'gamma',
                                             **optargsh))  # plot 9
            plotter.plotField(pa.createField('z', 'beta',
                                             **optargsh))  # plot 10

    if True:
        # instead of reading a single dump read a collection of dumps using the simulationreader
        sr = pp.readSim('examples/_openPMDdata/example-2d/hdf5/*.h5')
        print('There are {:} dumps in this simulationreader object:'.format(
            len(sr)))
        # now you can iterate over the dumps written easily
        for dr in sr:
            print('Simulation time of current dump t = {:.2e} s'.format(
                dr.time()))
            # there are the frames of a movie:
            plotter.plotField(dr.Ez())
Ejemplo n.º 24
0
def main():
    import numpy as np
    import postpic as pp

    # postpic will use matplotlib for plotting. Changing matplotlibs backend
    # to "Agg" makes it possible to save plots without a display attached.
    # This is necessary to run this example within the "run-tests" script
    # on travis-ci.
    import matplotlib
    matplotlib.use('Agg')

    # choose the dummy reader. This reader will create fake data for testing.
    pp.chooseCode('dummy')

    dr = pp.readDump(
        3e5)  # Dummyreader takes a float as argument, not a string.
    # set and create directory for pictures.
    savedir = '_examplepictures/'
    import os
    if not os.path.exists(savedir):
        os.mkdir(savedir)

    # initialze the plotter object.
    # project name will be prepended to all output names
    plotter = pp.plotting.plottercls(dr,
                                     outdir=savedir,
                                     autosave=True,
                                     project='simpleexample')

    # we will need a refrence to the MultiSpecies quite often
    from postpic.particles import MultiSpecies

    # create MultiSpecies Object for every particle species that exists.
    pas = [MultiSpecies(dr, s) for s in dr.listSpecies()]

    if True:
        # Plot Data from the FieldAnalyzer fa. This is very simple: every line creates one plot
        plotter.plotField(dr.Ex())  # plot 0
        plotter.plotField(dr.Ey())  # plot 1
        plotter.plotField(dr.Ez())  # plot 2
        plotter.plotField(dr.energydensityEM())  # plot 3

        # Using the MultiSpecies requires an additional step:
        # 1) The MultiSpecies.createField method will be used to create a Field object
        # with choosen particle scalars on every axis
        # 2) Plot the Field object
        optargsh = {'bins': [300, 300]}
        for pa in pas:
            # create a Field object nd holding the number density
            nd = pa.createField('x', 'y', simextent=True, **optargsh)
            # plot the Field object nd
            plotter.plotField(nd, name='NumberDensity')  # plot 4
            # if you like to keep working with the just created number density
            # yourself, it will convert to an numpy array whenever needed:
            arr = np.asarray(nd)
            print('Shape of number density: {}'.format(arr.shape))

            # more advanced: create a field holding the total kinetic energy on grid
            ekin = pa.createField('x',
                                  'y',
                                  weights='Ekin_MeV',
                                  simextent=True,
                                  **optargsh)
            # The Field objectes can be used for calculations. Here we use this to
            # calculate the average kinetic energy on grid and plot
            plotter.plotField(ekin / nd, name='Avg Kin Energy (MeV)')  # plot 5
            # use optargsh to force lower resolution
            # plot number density
            plotter.plotField(pa.createField('x', 'y', **optargsh),
                              lineoutx=True,
                              lineouty=True)  # plot 6
            # plot phase space
            plotter.plotField(pa.createField('x', 'p', **optargsh))  # plot 7
            plotter.plotField(pa.createField('x', 'gamma',
                                             **optargsh))  # plot 8
            plotter.plotField(pa.createField('x', 'beta',
                                             **optargsh))  # plot 9

            # same with high resolution
            plotter.plotField(pa.createField('x', 'y', bins=[1000,
                                                             1000]))  # plot 10
            plotter.plotField(pa.createField('x', 'p', bins=[1000,
                                                             1000]))  # plot 11

            # advanced: postpic has already defined a lot of particle scalars as Px, Py, Pz, P, X, Y, Z, gamma, beta, Ekin, Ekin_MeV, Ekin_MeV_amu, ... but if needed you can also define your own particle scalar on the fly.
            # In case its regularly used it should be added to postpic. If you dont know how, just let us know about your own useful particle scalar by email or adding an issue at
            # https://github.com/skuschel/postpic/issues

            # define your own particle scalar: p_r = sqrt(px**2 + py**2)/p
            plotter.plotField(
                pa.createField('sqrt(px**2 + py**2)/p',
                               'sqrt(x**2 + y**2)',
                               bins=[400, 400]))  # plot 12

            # however, since its unknown to the program, what quantities were calculated the axis of plot 12 will only say "unknown"
            # this can be avoided in two ways:
            # 1st: define your own ScalarProperty(name, expr, unit):
            p_perp = pp.particles.ScalarProperty('sqrt(px**2 + py**2)/p',
                                                 name='p_perp',
                                                 unit='kg*m/s')
            r_xy = pp.particles.ScalarProperty('sqrt(x**2 + y**2)',
                                               name='r_xy',
                                               unit='m')
            # this will create an identical plot, but correcly labled
            plotter.plotField(pa.createField(p_perp, r_xy,
                                             bins=[400, 400]))  # plot 13
            # if those quantities are reused often, teach postip to recognize them within the string expression:
            pp.particles.particle_scalars.add(p_perp)
            #pp.particles.scalars.add(r_xy)  # we cannot execute this line, because r_xy is already predefinded
            plotter.plotField(pa.createField('p_perp', 'r_xy',
                                             bins=[400, 400]))  # plot 14

            # choose particles by their properies
            # this has been the old interface, which would still work
            # def cf(ms):
            #     return ms('x') > 0.0  # only use particles with x > 0.0
            # cf.name = 'x>0.0'
            # pa.compress(cf)
            # nicer is the new filter function, which does exactly the same:
            pf = pa.filter('x>0')
            # plot 15, compare with plot 10
            plotter.plotField(pf.createField('x', 'y', bins=[1000, 1000]))
            # plot 16, compare with plot 12
            plotter.plotField(pf.createField('p_perp', 'r_xy', bins=[400,
                                                                     400]))

            plotter.plotField(dr.divE())  # plot 13