Exemplo n.º 1
0
    def get_current(self,
                    t=None,
                    iteration=None,
                    species=None,
                    select=None,
                    bins=100,
                    plot=False,
                    **kw):
        """
        Calculate the electric current along the z-axis for selected particles.

        Parameters
        ----------
         t : float (in seconds), optional
            Time at which to obtain the data (if this does not correspond to
            an available file, the last file before `t` will be used)
            Either `t` or `iteration` should be given by the user

        iteration : int
            The iteration at which to obtain the data
            Either `t` or `iteration` should be given by the user

        species : string
            Particle species to use for calculations

        select : dict, optional
            Either None or a dictionary of rules
            to select the particles, of the form
            'x' : [-4., 10.]   (Particles having x between -4 and 10 meters)
            'z' : [0, 100] (Particles having z between 0 and 100 meters)

        bins : int, optional
            Number of bins along the z-axis in which to calculate the current

        plot : bool, optional
           Whether to plot the requested quantity

        **kw : dict, otional
           Additional options to be passed to matplotlib's `plot` method
        Returns
        -------
        A tuple of arrays containig
        - The current in each bin in Ampere
        - A FieldMetaInformation object
          (see object's docstring for more details)

        """
        # Get particle data
        z, uz, uy, ux, w, q = self.get_particle(
            var_list=['z', 'uz', 'uy', 'ux', 'w', 'charge'],
            t=t,
            iteration=iteration,
            species=species,
            select=select)
        # Length to be seperated in bins

        if w.size > 0:
            min_z = np.min(z)
            len_z = np.max(z) - min_z
            # Calculate Lorentz factor for all particles
            gamma = np.sqrt(1 + ux**2 + uy**2 + uz**2)
            # Calculate particle velocities
            vz = uz / gamma * const.c
            # Length to be seperated in bins
            len_z = np.max(z) - np.min(z)
            vzq_sum, _ = np.histogram(z, bins=bins, weights=(vz * w * q))
            # Calculate the current in each bin
            current = np.abs(vzq_sum * bins / (len_z))
        else:
            current = np.zeros(bins)
            len_z = 0
            min_z = 0
        # Info object with central position of the bins
        info = FieldMetaInformation({0: 'z'},
                                    current.shape,
                                    grid_spacing=(len_z / bins, ),
                                    grid_unitSI=1,
                                    global_offset=(min_z + len_z / bins / 2, ),
                                    position=(0, ))
        # Plot the result if needed
        if plot:
            check_matplotlib()
            iteration = self.iterations[self._current_i]
            time_s = self.t[self._current_i]
            plt.plot(info.z, current, **kw)
            plt.title("Current at %.2e s   (iteration %d)" %
                      (time_s, iteration),
                      fontsize=self.plotter.fontsize)
            plt.xlabel('$z \;(m)$', fontsize=self.plotter.fontsize)
            plt.ylabel('$I \;(A)$', fontsize=self.plotter.fontsize)
        # Return the current and bin centers
        return (current, info)
Exemplo n.º 2
0
    def get_spectrum(self,
                     t=None,
                     iteration=None,
                     pol=None,
                     m='all',
                     plot=False,
                     **kw):
        """
        Return the spectrum of the laser
        (Absolute value of the Fourier transform of the fields.)

        Parameters
        ----------
        t : float (in seconds), optional
            Time at which to obtain the data (if this does not correspond to
            an available file, the last file before `t` will be used)
            Either `t` or `iteration` should be given by the user.

        iteration : int
            The iteration at which to obtain the data
            Either `t` or `iteration` should be given by the user.

        pol : string
            Polarization of the field. Options are 'x', 'y'

        m : int or str, optional
           Only used for thetaMode geometry
           Either 'all' (for the sum of all the modes)
           or an integer (for the selection of a particular mode)

        plot: bool, optional
           Whether to plot the data

        **kw : dict, otional
           Additional options to be passed to matplotlib's `plot` method

        Returns
        -------
        A tuple with:
            - The 1D spectrum on axis
            - A FieldMetaInformation object
        """
        # Check if polarization has been entered
        if pol not in ['x', 'y']:
            raise ValueError('The `pol` argument is missing or erroneous.')
        # Get a lineout along the 'z' axis,
        slice_across = self._get_slicing_for_longitudinal_lineout()

        # Get field data
        field1d, info = self.get_field(t=t,
                                       iteration=iteration,
                                       field='E',
                                       coord=pol,
                                       m=m,
                                       slice_across=slice_across)
        # FFT of 1d data
        dt = (info.z[1] - info.z[0]) / const.c  # Integration step for the FFT
        fft_field = np.fft.fft(field1d) * dt
        # Take half of the data (positive frequencies only)
        spectrum = abs(fft_field[:int(len(fft_field) / 2)])
        # Create a FieldMetaInformation object
        T = (info.zmax - info.zmin) / const.c
        spect_info = FieldMetaInformation({0: 'omega'},
                                          spectrum.shape,
                                          grid_spacing=(2 * np.pi / T, ),
                                          grid_unitSI=1,
                                          global_offset=(0, ),
                                          position=(0, ))

        # Plot the field if required
        if plot:
            check_matplotlib()
            iteration = self.iterations[self._current_i]
            time_s = self.t[self._current_i]
            plt.plot(spect_info.omega, spectrum, **kw)
            plt.xlabel('$\omega \; (rad.s^{-1})$',
                       fontsize=self.plotter.fontsize)
            plt.ylabel('Spectrum', fontsize=self.plotter.fontsize)
            plt.title("Spectrum at %.2e s   (iteration %d)" %
                      (time_s, iteration),
                      fontsize=self.plotter.fontsize)
        return (spectrum, spect_info)
Exemplo n.º 3
0
    def get_spectrogram(self,
                        t=None,
                        iteration=None,
                        pol=None,
                        plot=False,
                        **kw):
        """
        Calculates the spectrogram of a laserpulse, by the FROG method.

        Mathematically:
        $$ s(\omega, \tau) = | \int_{-\infty}^{\infty} E(t) |E(t-\tau)|^2
            \exp( -i\omega t) dt |^2 $$
        See Trebino, R: Frequency Resolved Optical Gating: The measurements of
        Ultrashort Laser Pulses: year 2000: formula 5.2

        The time is centered around the laser pulse.

        Parameters
        ----------
        t : float (in seconds), optional
            Time at which to obtain the data (if this does not correspond to
            an available file, the last file before `t` will be used)
            Either `t` or `iteration` should be given by the user.

        iteration : int
            The iteration at which to obtain the data
            Either `t` or `iteration` should be given by the user.

        pol : string
            Polarization of the laser field. Options are 'x', 'y'

        plot: bool, optional
            Whether to plot the spectrogram

        **kw : dict, otional
           Additional options to be passed to matplotlib's `imshow` method

        Returns
        -------
        - A 2d array with spectrogram
        - info : a FieldMetaInformation object
           (see the corresponding docstring)
        """
        # Get a lineout along the 'z' axis
        slice_across = self._get_slicing_for_longitudinal_lineout()

        # Get the field envelope
        env, _ = self.get_laser_envelope(t=t,
                                         iteration=iteration,
                                         pol=pol,
                                         slice_across=slice_across)
        # Get the field
        E, info = self.get_field(t=t,
                                 iteration=iteration,
                                 field='E',
                                 coord=pol,
                                 slice_across=slice_across)
        Nz = len(E)
        # Get time domain of the data
        tmin = info.zmin / const.c
        tmax = info.zmax / const.c
        T = tmax - tmin
        dt = T / Nz
        # Normalize the Envelope
        env /= np.sqrt(np.trapz(env**2, dx=dt))
        # Allocate array for the gating function and the spectrogran
        E_shift = np.zeros_like(E)
        spectrogram = np.zeros((2 * Nz, Nz))
        # Loop over the time variable of the spectrogram
        for i in range(Nz * 2):
            itau = i % Nz
            # Shift the E field and fill the rest with zeros
            if i < Nz:
                E_shift[:itau] = env[Nz - itau:Nz]
                E_shift[itau:] = 0
            else:
                E_shift[itau:] = env[:Nz - itau]
                E_shift[:itau] = 0
            EE = E * E_shift**2
            fft_EE = np.fft.fft(EE)
            spectrogram[i, :] = np.abs(fft_EE)**2
        # Rotate and flip array to have input form of imshow
        spectrogram = np.flipud(np.rot90(spectrogram[:, int(Nz / 2):]))
        # Find the time at which the wigner transform is the highest
        maxi, maxj = np.unravel_index(spectrogram.argmax(), spectrogram.shape)
        tmin = -(T - T / spectrogram.shape[1] * maxj)
        info = FieldMetaInformation({
            0: 'omega',
            1: 't'
        },
                                    spectrogram.shape,
                                    grid_spacing=(2 * np.pi / T, dt / 2.),
                                    grid_unitSI=1,
                                    global_offset=(0, tmin),
                                    position=(0, 0))

        # Plot the result if needed
        if plot:
            check_matplotlib()
            iteration = self.iterations[self._current_i]
            time_s = self.t[self._current_i]
            plt.imshow(spectrogram,
                       extent=info.imshow_extent,
                       aspect='auto',
                       **kw)
            plt.title("Spectrogram at %.2e s   (iteration %d)" %
                      (time_s, iteration),
                      fontsize=self.plotter.fontsize)
            plt.xlabel('$t \;(s)$', fontsize=self.plotter.fontsize)
            plt.ylabel('$\omega \;(rad.s^{-1})$',
                       fontsize=self.plotter.fontsize)
        return (spectrogram, info)