Beispiel #1
0
def check_identical_fields( folder1, folder2 ):
    ts1 = OpenPMDTimeSeries( folder1 )
    ts2 = OpenPMDTimeSeries( folder2 )
    # Check the vector fields
    for field, coord in [("J", "z"), ("E","r"), ("E","z"), ("B","t")]:
        print("Checking %s%s" %(field, coord))
        field1, info = ts1.get_field(field, coord, iteration=0)
        field2, info = ts2.get_field(field, coord, iteration=0)
        # For 0 fields, do not use allclose
        if abs(field1).max() == 0:
            assert abs(field2).max() == 0
        else:
            assert np.allclose(
                field1/abs(field1).max(), field2/abs(field2).max() )
    # Check the rho field
    print("Checking rho")
    field1, info = ts1.get_field("rho", iteration=0)
    field2, info = ts2.get_field("rho", iteration=0)
    assert np.allclose( field1/abs(field1).max(), field2/abs(field2).max() )
Beispiel #2
0
def check_theory_gaussian():
    """
    Check that the transverse E and B field are close to the high-gamma
    theory for a gaussian bunch
    """
    ts = OpenPMDTimeSeries( os.path.join(temporary_dir, 'diags_serial/hdf5/') )
    Ex, info = ts.get_field( 'E', 'x', iteration=0 )
    By, info = ts.get_field( 'B', 'y', iteration=0 )
    r, z = np.meshgrid( info.r, info.z, indexing='ij' )
    # High-gamma theory for Gaussian bunch
    Eth = -Q/(2*np.pi)**1.5/sig_z/epsilon_0/r * \
        (1 - np.exp(-0.5*r**2/sig_r**2)) * \
        np.exp( -0.5*(z-zf)**2/sig_z**2)
    Bth = Eth/c
    # Check that the fields agree
    assert np.allclose( Ex, Eth, atol=0.1*Eth.max() )
    assert np.allclose( By, Bth, atol=0.1*Bth.max() )
Beispiel #3
0
# read in the longitdunal electric field component
path_to_data = '../../rsfbpic/package_data'
field_name = 'E'
coord = 'z'
iteration = 280
mode = 0
theta = 0.
plot = False

# open the file; instantiate "time series" object
time_series = OpenPMDTimeSeries(path_to_data)

# read the specified field
ez, info_ez = time_series.get_field(iteration=iteration, \
                                    field=field_name, \
                                    coord=coord, \
                                    m=mode, \
                                    theta=theta, \
                                    plot=plot)

print()
print("axes = ", info_ez.axes)
print()
print("rmin, rmax = ", info_ez.rmin, "; ", info_ez.rmax)
print("zmin, zmax = ", info_ez.zmin, "; ", info_ez.zmax)
print()
print("dz = ", info_ez.dz)
print("dr = ", info_ez.dr)
print()
# print("r = ", info_ez.r)
# print("z = ", info_ez.z)
print("N_cells_r = ", len(info_ez.r))
Beispiel #4
0
class OpenPMDFieldReader(FieldReaderBase):
    def __init__(self, location, speciesName, dataName, firstTimeStep):
        # First check whether openPMD is installed
        if not openpmd_installed:
            raise RunTimeError(
                "You need to install openPMD-viewer, e.g. with:\n"
                "pip install openPMD-viewer")
        # Store an openPMD timeseries object
        # (Its API is used in order to conveniently extract data from the file)
        self.openpmd_ts = OpenPMDTimeSeries(location, check_all_files=False)
        self.openpmd_dataName = dataName
        # Initialize the instance
        FieldReaderBase.__init__(self, location, speciesName, dataName,
                                 firstTimeStep)

    def _ReadBasicData(self):
        file_content = self._OpenFile(self.firstTimeStep)
        self._ReadInternalName(file_content)
        self._DetermineFieldDimension(file_content)
        self._GetMatrixShape(file_content)
        self._ReadSimulationProperties(file_content)
        file_content.close()

    def _GetMatrixShape(self, file_content):
        _, dataset = openpmd_find_dataset(file_content, self.internalName)
        self.matrixShape = openpmd_get_shape(dataset)

    def _ReadInternalName(self, file_content):
        self.internalName = self.openpmd_dataName

    def _DetermineFieldDimension(self, file_content):
        # Find the name of the field ; vector fields like E are encoded as "E/x"
        fieldname = self.internalName.split("/")[0]
        geometry = self.openpmd_ts.fields_metadata[fieldname]['geometry']
        if geometry == '3dcartesian':
            self.fieldDimension = "3D"
        elif geometry == '2dcartesian':
            self.fieldDimension = "2D"
        else:
            raise ValueError("Unsupported geometry: %s" % geometry)

    def _Read1DSlice(self, timeStep, slicePositionX, slicePositionY=None):
        # Find the name of the field ; vector fields like E are encoded as "E/x"
        field_and_coord = self.internalName.split("/")
        if self.fieldDimension == '2D':
            fieldData, _ = self.openpmd_ts.get_field(*field_and_coord,
                                                     iteration=timeStep)
            elementsX = self.matrixShape[-2]
            selectedRow = round(elementsX * (float(slicePositionX) / 100))
            sliceData = np.array(fieldData[selectedRow])
        elif self.fieldDimension == '3D':
            # Slice first along X
            fieldData = self._Read2DSlice(None, slicePositionX, timeStep)
            # Then slice along Y
            elementsY = self.matrixShape[-2]
            selectedY = round(elementsY * (float(slicePositionY) / 100))
            sliceData = np.array(fieldData[selectedY])
        return sliceData

    def _Read2DSlice(self, sliceAxis, slicePosition, timeStep):
        # Find the name of the field ; vector fields like E are encoded as "E/x"
        field_and_coord = self.internalName.split("/")
        # Convert the `slicePosition` from a 0-to-100 number to -1 to 1
        slicing = -1. + 2 * slicePosition / 100.
        # Extract the slice
        sliceData, _ = self.openpmd_ts.get_field(*field_and_coord,
                                                 iteration=timeStep,
                                                 slicing_dir="x",
                                                 slicing=slicing)
        return sliceData

    def _ReadAllFieldData(self, timeStep):
        # Find the name of the field ; vector fields like E are encoded as "E/x"
        field_and_coord = self.internalName.split("/")
        fieldData, _ = self.openpmd_ts.get_field(*field_and_coord,
                                                 iteration=timeStep,
                                                 slicing=None)
        return fieldData

    def _ReadAxisData(self, timeStep):
        # Find the name of the field ; vector fields like E are encoded as "E/x"
        field_and_coord = self.internalName.split("/")
        # Note: the code below has very bad performance because
        # it automatically reads the field data, just to extract the metadata
        # TODO: improve in the future
        _, field_meta_data = self.openpmd_ts.get_field(*field_and_coord,
                                                       iteration=timeStep,
                                                       slicing=None)
        # Construct the `axisData` from the object `field_meta_data`
        axisData = {}
        axisData["x"] = getattr(field_meta_data, "z")
        axisData["y"] = getattr(field_meta_data, "x")
        if self.fieldDimension == "3D":
            axisData["z"] = getattr(field_meta_data, "y")
        return axisData

    def _ReadTime(self, timeStep):
        # The line below sets the attribute `_current_i` of openpmd_ts
        self.openpmd_ts._find_output(None, timeStep)
        # This sets the corresponding time
        self.currentTime = self.openpmd_ts.t[self.openpmd_ts._current_i]

    def _ReadUnits(self):
        file_content = self._OpenFile(self.firstTimeStep)
        # OpenPMD data always provide conversion to SI units
        self.axisUnits["x"] = "m"
        self.axisUnits["y"] = "m"
        self.axisUnits["z"] = "m"
        self.timeUnits = "t"
        self.dataUnits = "arb.u."  # TODO find the exact unit; needs navigation in file
        file_content.close()

    def _ReadSimulationProperties(self, file_content):
        # TODO: add the proper resolution
        self.grid_resolution = None
        self.grid_size = None
        self.grid_units = "m"

    def _OpenFile(self, timeStep):
        # The line below sets the attribute `_current_i` of openpmd_ts
        self.openpmd_ts._find_output(None, timeStep)
        # This finds the full path to the corresponding file
        fileName = self.openpmd_ts.h5_files[self.openpmd_ts._current_i]
        file_content = H5File(fileName, 'r')
        return file_content
factor = 1
a0PerSnapshot = []
PulsewaistPerSnapshot = []
PulselengthPerSnapshot = []
EzMinPerSnapshot = []
MaxFrequencyTrailingPulse = []

#for i in range(0,int(ts_laser.iterations.size/factor)):
for i in range(10800, 10801):
    iter = 10800
    #iter = ts_laser.iterations[factor*i]
    print('Iteration:%d' % iter)

    Ez, info_Ez = ts_particles.get_field(iteration=iter,
                                         field='E',
                                         coord='z',
                                         plot=True,
                                         **particles)
    #plt.clim(-5e8,5e8)
    plt.savefig('%s/Ez_Iteration%09i.png' % (Path + '/Ez', iter),
                bbox_inches='tight')
    plt.close()

    fig2, axis2 = plt.subplots()
    plt.locator_params(nbins=20, axis='y')
    plt.locator_params(nbins=20, axis='x')
    plt.plot(Ez[600])
    #axis2.xaxis.grid(linestyle='solid',color='gray',linewidth=0.1)
    #axis2.yaxis.grid(linestyle='solid',color='gray',linewidth=0.1)

    plt.savefig('EzLineout_%09i.png' % (iter), bbox_inches='tight')
Beispiel #6
0
def test_cpu_gpu_deposition(show=False):
    "Function that is run by py.test, when doing `python setup.py test`"

    # Skip this test if cuda is not installed
    if not cuda_installed:
        return

    # Perform deposition for a few timesteps, with both the CPU and GPU
    for hardware in ['cpu', 'gpu']:
        if hardware == 'cpu':
            use_cuda = False
        elif hardware == 'gpu':
            use_cuda = True

        # Initialize the simulation object
        sim = Simulation(Nz,
                         zmax,
                         Nr,
                         rmax,
                         Nm,
                         dt,
                         p_zmin,
                         p_zmax,
                         p_rmin,
                         p_rmax,
                         p_nz,
                         p_nr,
                         p_nt,
                         n_e,
                         zmin=zmin,
                         use_cuda=use_cuda)

        # Tweak the velocity of the electron bunch
        gamma0 = 10.
        sim.ptcl[0].ux = sim.ptcl[0].x
        sim.ptcl[0].uy = sim.ptcl[0].y
        sim.ptcl[0].uz = np.sqrt(gamma0**2 - sim.ptcl[0].ux**2 -
                                 sim.ptcl[0].uy**2 - 1)
        sim.ptcl[0].inv_gamma = 1. / gamma0 * np.ones_like(sim.ptcl[0].x)
        sim.ptcl[0].m = 1e10

        # Add a field diagnostic
        sim.diags = [
            FieldDiagnostic(diag_period,
                            sim.fld,
                            fieldtypes=['rho', 'J'],
                            comm=sim.comm,
                            write_dir=os.path.join('tests', hardware))
        ]

        ### Run the simulation
        sim.step(N_step)

    # Check that the results are identical
    ts_cpu = OpenPMDTimeSeries('tests/cpu/hdf5')
    ts_gpu = OpenPMDTimeSeries('tests/gpu/hdf5')
    for iteration in ts_cpu.iterations:
        for field, coord in [('rho', ''), ('J', 'x'), ('J', 'z')]:
            # Jy is not tested because it is zero
            print('Testing %s at iteration %d' % (field + coord, iteration))
            F_cpu, info = ts_cpu.get_field(field, coord, iteration=iteration)
            F_gpu, info = ts_gpu.get_field(field, coord, iteration=iteration)
            tolerance = 1.e-13 * (abs(F_cpu).max() + abs(F_gpu).max())
            if not show:
                assert np.allclose(F_cpu, F_gpu, atol=tolerance)
            else:
                if not np.allclose(F_cpu, F_gpu, atol=tolerance):
                    plot_difference(field, coord, iteration, F_cpu, F_gpu,
                                    info)

    # Remove the files used
    shutil.rmtree('tests/cpu')
    shutil.rmtree('tests/gpu')
Beispiel #7
0
def run_cpu_gpu_deposition(show=False, particle_shape='cubic'):

    # Skip this test if cuda is not installed
    if not cuda_installed:
        return

    # Perform deposition for a few timesteps, with both the CPU and GPU
    for hardware in ['cpu', 'gpu']:
        if hardware == 'cpu':
            use_cuda = False
        elif hardware == 'gpu':
            use_cuda = True

        # Initialize the simulation object
        sim = Simulation(Nz,
                         zmax,
                         Nr,
                         rmax,
                         Nm,
                         dt,
                         zmin=zmin,
                         use_cuda=use_cuda,
                         particle_shape=particle_shape)
        sim.ptcl = []

        # Add an electron bunch (set the random seed first)
        np.random.seed(0)
        add_elec_bunch_gaussian(sim, sig_r, sig_z, n_emit, gamma0, sig_gamma,
                                Q, N)

        # Add a field diagnostic
        sim.diags = [
            FieldDiagnostic(diag_period,
                            sim.fld,
                            fieldtypes=['rho', 'J'],
                            comm=sim.comm,
                            write_dir=os.path.join('tests', hardware))
        ]

        ### Run the simulation
        sim.step(N_step)

    # Check that the results are identical
    ts_cpu = OpenPMDTimeSeries('tests/cpu/hdf5')
    ts_gpu = OpenPMDTimeSeries('tests/gpu/hdf5')
    for iteration in ts_cpu.iterations:
        for field, coord in [('rho', ''), ('J', 'x'), ('J', 'z')]:
            # Jy is not tested because it is zero
            print('Testing %s at iteration %d' % (field + coord, iteration))
            F_cpu, info = ts_cpu.get_field(field, coord, iteration=iteration)
            F_gpu, info = ts_gpu.get_field(field, coord, iteration=iteration)
            tolerance = 1.e-13 * (abs(F_cpu).max() + abs(F_gpu).max())
            if not show:
                assert np.allclose(F_cpu, F_gpu, atol=tolerance)
            else:
                if not np.allclose(F_cpu, F_gpu, atol=tolerance):
                    plot_difference(field, coord, iteration, F_cpu, F_gpu,
                                    info)

    # Remove the files used
    shutil.rmtree('tests/cpu')
    shutil.rmtree('tests/gpu')