Tutorial 2c: Running the Simulation
With the generation of the Compton and Synchrotron matrices, we are now ready to run the simulation. This simulation will be run using the functions contained within the DiplodocusTransport sub-package.
Backend Setup
Before we can run any simulation we need to set some backend parameters, those being the Precision of the simulation (either Float64 or Float32) and the Backend. This Backend tells the solver what hardware to behind the scenes. Here we choose to run our simulation on a CPU by specifying CPUBackend(). If we had a Nvidea GPU we could use this instead by setting it to CUDABackend().
using Diplodocus
Precision::DataType = Float32
Backend::AbstractBackend = CPUBackend()Setting Characteristic Scales
Next we define any simulation specific scales in SI units. This will override the default scales, which are specified in Characteristic Scales
CHAR_length::Float64 = 1e14 # m = 1e16 cmHere we have defined the characteristic length to be the radius of our spherical region.
TIP
The characteristic speed is always taken to be the speed of light, so the characteristic time for this simulation is then defined as
Phase-Space Setup
Spatial Grids
We need to define the spatial geometry on which we are going to simulate. In this tutorial we are considering a single spherical region in flat spacetime. The metric will therefore be Minkowski() and we will use Spherical() coordinates. By default, the radial boundary condition for Spherical coordinates is taken to be Closed i.e. no particle may leave (see Metrics, Coordinates, and Tetrads). We can change this by modifying the keyword parameter xp_BC=Escape(), when defining the coordinates. As out particles are isotropic we must use Escape which ignores the particles direction of propagation and just uses their momentum to determine whether they escape or not, as otherwise if we used Open the angle averaged direction of propagation is zero and no particles would leave the zone. We also want a uniform magnetic field in out spherical domain so we need to define the tetrad as a UniformElectromagneticFieldTetrad with a magnetic field strength B0=1e-3.
metric::AbstractMetric = Minkowski()
coordinates::AbstractCoordinates = Spherical(xp_BC=Escape())
tetrad::AbstractTetrad = UniformElectromagneticFieldTetrad(B0=1e-3,E0=0.0)This tetrad assumes the magentic field is uniform but we can make the code treat it as isotropic when defining the effects of synchrotron emission later on.
In code units or domain is a unit sphere so we shall define the x,y,z coordinate grids to match:
x_grid::AbstractSpacetimeGrid = UniformGrid(1.0,0.0,1)
y_grid::AbstractSpacetimeGrid = UniformGrid(pi,0.0,1)
z_grid::AbstractSpacetimeGrid = UniformGrid(2pi,0.0,1)No matter the type of spatial coordinates, they are always mapped to
Momentum Grids
Next we similarly define the momentum space grids and the list of particles to be included in the simulation. For momentum space, Diplodocus uses a local spherical coordinate basis, therefore, the momentum coordinates should be Spherical. As for the grids for each coordinate, we should choose the same values as were used to generate the collision matrices.
name_list::Vector{String} = ["Ele","Pho"];
px_up_list::Vector{Float64} = [4.0,4.0]
px_low_list::Vector{Float64} = [-5.0,-18.0]
px_grid_list::Vector{String} = ["l","l"]
px_num_list::Vector{Int64} = [144,352]
py_up_list::Vector{Float64} = [1.0,1.0]
py_low_list::Vector{Float64} = [-1.0,-1.0]
py_grid_list::Vector{String} = ["u","u"]
py_num_list::Vector{Int64} = [1,1]
pz_up_list::Vector{Float64} = [2.0*pi,2.0*pi]
pz_low_list::Vector{Float64} = [0.0,0.0]
pz_grid_list::Vector{String} = ["u","u"]
pz_num_list::Vector{Int64} = [1,1]WARNING
Momentum-space grids must match those used in generating the collision matrices
Build the Phase Space
Last part of the phase-space setup is to actually build the phase space using what we have defined above
PhaseSpace = PhaseSpaceStruct()Interactions and Forces
With the phase space now set up we can define what interactions and forces take place on this phase space.
Defining what Interactions to Include
In our case we only have a single binary interaction to consider. For this we need to define two things: the Binary_list, a Vector of BinaryInteractions that define the binary interactions to include; and a Binary_Domain that defines where these interactions will take place.
TIP
For larger simulations with large spatial grids, you can use the Binary_Domain to specify to tell the solver only to consider binary interactions in certain areas and speed up simulations.
Binary_list::Vector{BinaryInteraction} = [BinaryInteraction("Ele","Pho","Ele","Pho")]
Binary_Domain = InclusiveDomainMask(PhaseSpace)Here the InclusiveDomainMask sets a mask to include all spatial cells, i.e. the single spatial cell of our simulation. We now need to tell the solver what emissive interaction to include. For step has a few more options. First we must list out the values of the external parameter with which we sampled the synchrotron emission matrices, here B_sample, which is just a single value. Then we define the domain over which to include the synchrotron Sync_Domain and then build an Emission_list that is a Vector of EmissiveInteractions:
B_sampled::Vector{Float64} = [1e-3];
Sync_Domain = InclusiveDomainMask(PhaseSpace);
Emission_list::Vector{EmissiveInteraction} = [EmissiveInteraction(name1="Ele",name2="Ele",name3="Pho",EmiName="Sync",Ext_sampled=B_sampled,mode=Iso(),Force=true,Domain=Sync_Domain)]The EmissiveInteraction takes a mode argument, which we set to Iso() to tell the code to treat the magnetic field as isotropic when calculating synchrotron emissions (this is technically unneeded here as our momentum domains are isotropic, but can be used to replicate turbulent, tangled, magnetic fields with anisotropic momentum grids). We also set Force=true to tell the code to apply the corresponding synchrotron cooling force (radiation reaction) to the electrons. This will also correct the synchrotron emission spectra to ensure that energy is conserved between cooling and emission.
Last we specify that there are no other forces to include:
Forces_list::Vector{AbstractForce} = []Building the Interaction and Force Matrices
Now that we hae defined what interactions and forces to include, we need to build the matrices that the solver will actually use to dictate the time stepping of the simulation.
First we define the DataDirectory where any saved collision matrices are saved and will be loaded from.
DataDirectory = joinpath(pwd(),"Data","Tutorial2")Then we build three sets of matrices: BinM for the binary interactions, EmiM for the emissive interactions and FluxM for phase-space transport.
BinM = BuildBinaryMatrices(PhaseSpace,Binary_list,Binary_Domain,DataDirectory;Bin_corrected=true,Bin_sparse=true)
EmiM = BuildEmissionMatrices(PhaseSpace,Emission_list,DataDirectory,BinM;Emi_corrected=true)
FluxM = BuildFluxMatrices(PhaseSpace,Forces_list)Here we have used the argument Bin_corrected=true to use the number and energy density correct binary collision matrices, and the argument Bin_sparse=true to define the binary collision matrix as a sparse matrix. The size of all these matrices is determined by the resolution of the phase-space grids and the sparsity of the interactions. The total size will be printed to the standard output once these matrices are built.
TIP
If there are lots of particles involved in a simulation the binary collision matrix (typically the largest matrix) may become sparse enough to warrant using Bin_sparse=true to save memory and speed up the solver. This is only works if the sparsity is grater than around 70%.
Setting the Initial and Injection Conditions
With the phase space and interactions all set up, we can now define the initial and injection conditions of our simulation. To do this we first initialise two state vectors Initial and Injection using:
Initial = InitialiseInitialCondition(PhaseSpace)
Injection = InitialiseInjectionCondition(PhaseSpace)These two state vectors are currently empty, but we can use several functions to add to them a variety of initial and injection conditions Initial and Injection Conditions. For this tutorial, we don't need to set any initial electrons but we do need to set some to be injected. This injected population is of the form of a power-law with an exponential decay, so we can use InjectionPowerLawExpDecay!:
InjectionPowerLawExpDecay!(Injection,PhaseSpace,"Ele",2.0,10^1.9,10^2.1;num_Inj=1.0,rate_Inj=1.0)This will inject a power-law distribution of electrons with minimum momentum of 2. The total number of particles injected is set by num_Inj and the rate at which they are injected is set by rate_Inj, both given in characteristic units. But we want to inject a population of electrons with a compactness Compactness to calculate the compactness of Injection and then scale by this value to get the desired compactness:
compactness = Compactness(Injection,PhaseSpace,"Ele")
Injection /= compactnessTIP
The function InjectionPowerLawExpDecay! modifies Injection but does not reset it, therefore if you call this function multiple times or additionally call other other injection condition functions, they will all add to each other, allowing a wide range of injection conditions to be applied simultaneously.
Running the Solver
Defining the Time-Stepping Method
For this physical situation we are examining we should expect the system to be highly non-linear and stiff. Because of this the timescale for synchrotron and inverse-Compton scattering is much shorter than the timescale of particle escape. If we were to use the ForwardEulerStruct method, the timestep would be limited by the shortest timescale, much shorter than dt_initial, meaning the simulation would need a very large number of timesteps and hence a long time to complete. For cases such as this, an exponential integration method is more appropriate as these methods are designed to handle systems with large differences in timescales. One such method is implemented in DiplodocusTransport, the ExponentialRosenbrockEulerKrylovStruct method. This method uses a Krylov subspace approximation to calculate the matrix exponential of the system, allowing it to take timesteps much larger than the shortest timescale. We can define this method as follows:
method = ExponentialRosenbrockEulerKrylovStruct(PhaseSpace,Initial,Injection,BinM,EmiM,FluxM;mB=128)where the keyword argument mB sets the size of the Krylov subspace. The larger this value, the more accurate the approximation of the matrix exponential, but also the longer it will take to compute.
With this method we can take large time steps, we shall choose the initial timestep size dt_initial, and a Vector of times at which to save the simulation t_save:
dt_initial::Float64 = 1.0
t_save::Vector{Float64} = range(0.0,1e1,length=11)Here the initial timestep will be 1.0 characteristic times, and the simulation will run from
TIP
When constructed the ExponentialRosenbrockEulerKrylovStruct method includes a field (method.dt_initial) which suggests a suitable initial timestep based on the smallest advection time scale of the system. That is not needed here but is useful for more complex simulations with more complex spacial grids.
File saving only requires us to define a fileName and fileLocation where the output will be saved. The output is saved in the JLD2 file format, a Julia native version of HDF5.
fileName = "tutorial2_output.jld2"
fileLocation = joinpath(pwd(),"Data","Tutorial2")Actually Running the Solver
Everything is now all set up and we can run the solver using the Solve function:
sol = Solve(method,dt_initial,t_save;fileName=fileName,fileLocation=fileLocation,progress=true,Verbose=2)If all went well, this should have taken less than a second to run! We can now move on to plotting and examining the results!