astro-group-bristol / SyncSSCModel.jl

Radiative models for simulating emission spectra in various black hole jet models.
2 stars 2 forks source link

Parameters and how to manage them effectively #9

Closed phajy closed 1 year ago

phajy commented 2 years ago

I'm wondering what the best way is of keeping track of model parameters. The model has a lot of parameters (see, e.g., here) and I'm not sure of the best way of organising them.

One option is to create a structure. But there might be other examples of how to do this "properly". It would be good to have some default parameters that could then be adjusted if necessary. There are lots of parameters and we'll be adding some too so it would be good to have something like a structure so all the parameters could be passed around easily.

A quick Google search has found Parameters.jl but I haven't tried this and am not confident in identifying recommended, maintained packages.

fjebaker commented 2 years ago

Parameters.jl is an excellent choice for this, and is what we're using in the geodesic tracer also.

You can do something like

using Parameters

# ...

@with_kw struct MyParamStruct
    # set the default type of all parameters
    @deftype Float64

    "magnetic field strength in Gauss"
    B = 3.0E-6      
    # referencing previous fields is permitted with Parameters.jl
    "cyclotron energy in units of m_e*c^2"
    ϵ_B = B/4.414E13    
    "magnetic field energy density"
    u_B = B^2/8.0*pi   

    "normalisation of electron density"
    n_e0 = 500.0       
    "power law index of electron distribution function"
    p = 3.0            
    "minimum Lorentz factor of electrons"
    γ_min = 1.0E2      
    "maximum Lorentz factor of electrons"
    γ_max = 1.0E7      

    "Redshift"
    z = 0.01           
    "Bulk Lorentz factor"
    Γ = 2.6            
    "Angle between the direction of the blob's motion and the direction to the observer"
    θ = 0              
    "Hubble parameter"
    ho = 0.67          
    "Hublle constant in km s^-1 Mpc^-1"
    Ho = 100*ho        
    " Mass of BH in Solar Masses"
    M8 = 1E8           
end

By putting the comments in this format, tools like DocStringExtensions.jl can parse them to generate pretty documentation.

The @with_kw macro generates a number of different things for you, but most importantly it generates a constructor which allows you to modify only a handful of parameters:

# all default params
mps = MyParamStruct()

# change θ
mps = MyParamStruct(θ=deg2rad(45))

# change θ and z
mps = MyParamStruct(θ=deg2rad(45), z=0.04)

Structs in Julia are immutable by default, so mps is guaranteed to be constant for its lifetime, and allows accessing parameters with the familiar mps.z syntax.

phajy commented 2 years ago

Thanks, that's very helpful. I have a pull request which includes an update to use Parameters.jl. Oh, but I need to go back and take a look at the DocStringExtensions.jl.