Swiftest API reference

Contents

Swiftest API reference#

This section of the documentation provides a detailed reference for the Production classes in the Swiftest project.

Simulation#

The Simulation class is the main class for the Swiftest project.

class swiftest.simulation.Simulation(simdir='simdata', param_file='param.in', read_param=False, read_data=False, read_init_cond=None, read_collisions=None, read_encounters=None, clean=False, dask=False, codename='Swiftest', integrator='symba', coarray=False, verbose=True, **kwargs)[source]#

Bases: object

Defines the basic Swift/Swifter/Swiftest simulation object.

run(dask=False, **kwargs)[source]#

Runs a Swiftest integration.

Uses the parameters set by the param dictionary unless overridden by keyword arguments. Accepts any keyword arguments that can be passed to set_parameter.

Parameters:
  • dask (bool, default False) – If true, will use Dask to lazily load data (useful for very large datasets)

  • **kwargs (Any) – Any valid keyword arguments accepted by set_parameter()

Returns:

None

set_simulation_time(t0=None, tstart=None, tstop=None, dt=None, istep_out=None, tstep_out=None, nstep_out=None, dump_cadence=None, **kwargs)[source]#

Set the parameters that control how a simulation is run, such as start and stop time, step size, and the cadence of output to both the screen and to file. Returns a dictionary of the parameters that were set.

Parameters:
  • t0 (float, optional) – The reference time for the start of the simulation. Defaults is 0.0

  • tstart (float, optional) – The start time for a restarted simulation. For a new simulation, tstart will be set to t0 automatically.

  • tstop (float, optional) – The stopping time for a simulation. tstop must be greater than tstart.

  • dt (float, optional) – The step size of the simulation. dt must be less than or equal to tstop-dstart.

  • istep_out (int, optional) – The number of time steps between output saves to file. Only istep_out or tstep_out can be set. Parameter input file equivalent is ISTEP_OUT

  • tstep_out (float, optional) –

    The approximate time between when outputs are written to file. Passing this computes:

    `istep_out = floor(tstep_out/dt)`.
    

    Only istep_out or tstep_out can be set. Parameter input file equivalent is None

  • nstep_out (int, optional) –

    The total number of times that outputs are written to file. Passing this allows for a geometric progression of output steps:

    TSTART, f**0 * TSTEP_OUT, f**1 * TSTEP_OUT, f**2 * TSTEP_OUT, 
, f**(nstep_out-1) * TSTEP_OUT

    where f is a factor that can stretch (or shrink) the time between outputs. Setting:

    nstep_out = int((tstart - tstop) / (tstep_out))
    

    is equivalent to the standard linear output (i.e. f==1) and is the same as not passing anything for this argument. Passing nstep_out requires passing either istep_out or tstep_out as well.

  • dump_cadence (int, optional) – The number of output steps (given by istep_out) between when the saved data is dumped to a file. Setting it to 0 is equivalent to only dumping data to file at the end of the simulation. Default value is 10. Parameter input file equivalent is DUMP_CADENCE

  • **kwargs – A dictionary of additional keyword argument. This allows this method to be called by the more general set_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

time_dict (dict) – A dictionary containing the requested parameters

get_simulation_time(arg_list=None, **kwargs)[source]#

Returns a subset of the parameter dictionary containing the current simulation time parameters.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the simulation time parameters to extract. Default is all of: [“t0”, “tstart”, “tstop”, “dt”, “istep_out”, “tstep_out”, “dump_cadence”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

time_dict (dict) – A dictionary containing the requested parameters

set_parameter(**kwargs)[source]#

Setter for all possible parameters. This will call each of the specialized setters using keyword arguments.

If no arguments are passed, then either values from the param_file or default values will be used.

Parameters:
  • **kwargs (dict) – See list of valid parameters and their defaults below

  • param_file (str, path-like, or file-like, default None) – Name of the parameter input file that will be passed to the integrator. If passed, then the file will be read in and the parameters set from them, but can be overriden by any explicit arguments

  • codename ({“Swiftest”, “Swifter”, “Swift”}, default “Swiftest”) – Name of the n-body code that will be used. Parameter input file equivalent is None

  • integrator ({“symba”,”rmvs”,”whm”,”helio”,”ringmoons”}, default “symba”) – Name of the n-body integrator that will be used when executing a run. Parameter input file equivalent is None

  • t0 (float, default 0.0) – The reference time for the start of the simulation. Defaults is 0.0. Parameter input file equivalent is T0

  • tstart (float, default 0.0) – The start time for a restarted simulation. For a new simulation, tstart will be set to t0 automatically. Parameter input file equivalent is TSTART

  • tstop (float, optional) – The stopping time for a simulation. tstop must be greater than tstart. Parameter input file equivalent is TSTOP

  • dt (float, optional) – The step size of the simulation. dt must be less than or equal to tstop-tstart. Parameter input file equivalent is DT

  • istep_out (int, optional) – The number of time steps between output saves to file. Only istep_out or tstep_out can be set. Parameter input file equivalent is ISTEP_OUT

  • tstep_out (float, optional) – The approximate time between when outputs are written to file. Passing this computes:

    istep_out = floor(tstep_out / dt)
    

    Only istep_out or tstep_out can be set. tstep_out must be less than tstop. Parameter input file equivalent is None

  • nstep_out (int, optional) – The total number of times that outputs are written to file. Passing this allows for a geometric progression of output steps:

    TSTART, f**0 * TSTEP_OUT, f**1 * TSTEP_OUT, f**2 * TSTEP_OUT, ..., f ** (nstep_out - 1) * TSTEP_OUT
    

    where f is a factor that can stretch (or shrink) the time between outputs. Setting:

    nstep_out = int((tstart - tstop) / (tstep_out))
    

    is equivalent to the standard linear output (i.e. f==1) and is the same as not passing anything for this argument. Passing nstep_out requires passing either istep_out or tstep_out as well.

  • dump_cadence (int, optional) – The number of output steps (given by istep_out) between when the saved data is dumped to a file. Setting it to 0 is equivalent to only dumping data to file at the end of the simulation. Default value is 10. Parameter input file equivalent is DUMP_CADENCE

  • init_cond_file_type ({“NETCDF_DOUBLE”, “NETCDF_FLOAT”, “ASCII”}, default “NETCDF_DOUBLE”) – The file type containing initial conditions for the simulation.

    • “NETCDF_DOUBLE” A single initial conditions input file in NetCDF file format of type NETCDF_DOUBLE.

    • “NETCDF_FLOAT” A single initial conditions input file in NetCDF file format of type NETCDF_FLOAT.

    • “ASCII” Three initial conditions files in ASCII format. The individual files define the central body,

    massive body, and test particle initial conditions. Parameter input file equivalent is IN_TYPE

  • init_cond_file_name (str, path-like, or dict, optional) – Name of the input initial condition file or files. Whether to pass a single file name or a dictionary depends on the argument passed to init_cond_file_type. If init_cond_file_type={“NETCDF_DOUBLE”,”NETCDF_FLOAT”}, then this will be a single file name. If init_cond_file_type=”ASCII” then this must be a dictionary where:

    init_cond_file_name = {
        "CB" - [path to central body initial conditions file] (Swiftest only),
        "PL" - [path to massive body initial conditions file],
        "TP" - [path to test particle initial conditions file] }
    

    If no file name is provided then the following default file names will be used.

    • “NETCDF_DOUBLE”, “NETCDF_FLOAT” init_cond_file_name = “init_cond.nc”

    • “ASCII” init_cond_file_name = {“CB” : “cb.in”, “PL” : “pl.in”, “TP” : “tp.in”}

    Parameter input file equivalent is NC_IN, CB_IN, PL_IN, TP_IN

  • init_cond_format ({“EL”, “XV”}, default “XV”) – Indicates whether the input initial conditions are given as orbital elements or cartesian position and velocity vectors. If codename is “Swift” or “Swifter”, EL initial conditions are converted to XV. Parameter input file equivalent is IN_FORM

  • output_file_type ({“NETCDF_DOUBLE”, “NETCDF_FLOAT”,”REAL4”,”REAL8”,”XDR4”,”XDR8”}, default “NETCDF_DOUBLE”) – The file type for the outputs of the simulation. Compatible file types depend on the codename argument.

    • Swiftest - Only “NETCDF_DOUBLE” or “NETCDF_FLOAT” supported.

    • Swifter - Only “REAL4”,”REAL8”,”XDR4” or “XDR8” supported.

    • Swift - Only “REAL4” supported.

    Parameter input file equivalent is OUT_TYPE

  • output_file_name (str or path-like, optional) – Name of output file to generate. If not supplied, then one of the default file names are used, depending on the value passed to output_file_type. The default is “data.nc”. Parameter input file equivalent is BIN_OUT

  • output_format ({“XV”,”XVEL”}, default “XVEL”) – Specifies the format for the data saved to the output file. If “XV” then cartesian position and velocity vectors for all bodies are stored. If “XVEL” then the orbital elements are also stored. Parameter input file equivalent is OUT_FORM

  • simdir (PathLike, optional) – Directory where simulation data will be stored, including the parameter file, initial conditions file, output file

  • MU (str, optional) – The mass unit system to use. Case-insensitive valid options are

    • “Msun” - Solar mass

    • “Mearth” - Earth mass

    • “kg” - kilograms

    • “g”,”gm” - grams

  • DU (str, optional) – The distance unit system to use. Case-insensitive valid options are

    • “AU” - Astronomical Unit

    • “Rearth” - Earth radius

    • “km” - kilometer

    • “m” - meter

    • “cm” - centimeter

  • TU (str, optional) – The time unit system to use. Case-insensitive valid options are

    • “y”,”YR”,”year”,”years” - Year

    • “d”,”day”,”days” - Julian day

    • “s”,”sec”,”seconds”,”second” - second

    Parameter input file equivalent is None

  • MU2KG (float, optional) – The conversion factor to multiply by the mass unit that would convert it to kilogram. Setting this overrides MU Parameter input file equivalent is MU2KG

  • DU2M (float, optional) – The conversion factor to multiply by the distance unit that would convert it to meter. Setting this overrides DU Parameter input file equivalent is DU2M

  • TU2S (float, optional) – The conversion factor to multiply by the time unit that would convert it to seconds. Setting this overrides TU Parameter input file equivalent is TU2S

  • MU_name (str, optional) – The name of the mass unit. When setting one of the standard units via MU a name will be automatically set for the unit, so this argument will override the automatic name. Parameter input file equivalent is None

  • DU_name (str, optional) – The name of the distance unit. When setting one of the standard units via DU a name will be automatically set for the unit, so this argument will override the automatic name. Parameter input file equivalent is None

  • TU_name (str, optional) – The name of the time unit. When setting one of the standard units via TU a name will be automatically set for the unit, so this argument will override the automatic name. Parameter input file equivalent is None

  • rmin (float, default value is the radius of the central body in the unit system defined by the unit input arguments.) – Minimum distance of the simulation Parameter input file equivalent are CHK_QMIN, CHK_RMIN, CHK_QMIN_RANGE[0]

  • rmax (float, default value is 10000 AU in the unit system defined by the unit input arguments.) – Maximum distance of the simulation (CHK_RMAX, CHK_QMIN_RANGE[1]) Parameter input file equivalent are CHK_RMAX, CHK_QMIN_RANGE[1]

  • qmin_coord (str, {“HELIO”, “BARY”}, default “HELIO”) – coordinate frame to use for checking the minimum periapsis distance Parameter input file equivalent is QMIN_COORD

  • mtiny (float, optional) – The minimum mass of fully interacting bodies. Bodies below this mass interact with the larger bodies, but not each other (SyMBA only). Only mtiny or gmtiny is accepted, not both. Parameter input file equivalent is None

  • gmtiny (float, optional) – The minimum G*mass of fully interacting bodies. Bodies below this mass interact with the larger bodies, but not each other (SyMBA only). Only mtiny or gmtiny is accepted, not both. Parameter input file equivalent is GMTINY

  • close_encounter_check (bool, default True) – Check for close encounters between bodies. If set to True, then the radii of massive bodies must be included in initial conditions. Parameter input file equivalent is CHK_CLOSE

  • encounter_save ({“NONE”,”TRAJECTORY”,”CLOSEST”, “BOTH”}, default “NONE”) – Indicate if and how encounter data should be saved. If set to “TRAJECTORY”, the position and velocity vectors of all bodies undergoing close encounters are saved at each intermediate step to the encounter files. If set to “CLOSEST”, the position and velocities at the point of closest approach between pairs of bodies are computed and stored to the encounter files. If set to “BOTH”, then this stores the values that would be computed in “TRAJECTORY” and “CLOSEST”. If set to “NONE” no trajectory information is saved. WARNING - Enabling this feature could lead to very large files.

  • general_relativity (bool, default True) – Include the post-Newtonian correction in acceleration calculations. Parameter input file equivalent is “GR”

  • collision_model ({“MERGE”,”BOUNCE”,”FRAGGLE”}, default “MERGE”) – This is used to set the collision/fragmentation model. This argument only applies to Swiftest-SyMBA simulations and will be ignored otherwise. Parameter input file equivalent is “COLLISION_MODEL”

  • minimum_fragment_gmass (float, optional) – If fragmentation is turned on, this sets the mimimum G*mass of a collisional fragment that can be generated if a fragmentation model is enabled. Ignored otherwise. Only set one of minimum_fragment_gmass or minimum_fragment_mass Parameter input file equivalent is None

  • minimum_fragment_mass (float, optional) – If fragmentation is turned on, this sets the mimimum mass of a collisional fragment that can be generated. if a fragmentation model is enabled. Ignored otherwise Only set one of minimum_fragment_gmass or minimum_fragment_mass Parameter input file equivalent is MIN_GMFRAG

  • nfrag_reduction (float, optional) – If fragmentation is turned on, this is a reduction factor used to limit the number of fragments generated in a collision. For instance, if the SFD of the collision would generated 300 fragments above the minimum_fragment_mass, then a value of nfrag_reduction = 30.0 would reduce it to 10. Currently only used by the Fraggle collision model.

  • rotation (bool, default True) – If set to True, this turns on rotation tracking and radius, rotation vector, and moments of inertia values must be included in the initial conditions. This argument only applies to Swiftest-SyMBA simulations. It will be ignored otherwise. Parameter input file equivalent is ROTATION

  • compute_conservation_values (bool, default True for SyMBA, otherwise False) – Turns on the computation of energy, angular momentum, and mass conservation and reports the values every output step of a running simulation. Parameter input file equivalent is ENERGY

  • extra_force (bool, default False) – Turns on user-defined force function. Parameter input file equivalent is EXTRA_FORCE

  • big_discard (bool, default False) – Includes big bodies when performing a discard (Swifter only) Parameter input file equivalent is BIG_DISCARD

  • rhill_present (bool, default False) – Include the Hill’s radius with the input files . Parameter input file equivalent is RHILL_PRESENT

  • restart (bool, default False) – If true, will restart an old run. The file given by output_file_name must exist before the run can execute. If false, will start a new run. If the file given by output_file_name exists, it will be replaced when the run is executed. Parameter input file equivalent is OUT_STAT

  • interaction_loops ({“TRIANGULAR”,”FLAT”}, default “TRIANGULAR”) – Swiftest Experimental feature Specifies which algorithm to use for the computation of body-body gravitational forces.

    • “TRIANGULAR” - Upper-triangular double-loops.

    • “FLAT” - Body-body interation pairs are flattened into a 1-D array.

    Parameter input file equivalent is INTERACTION_LOOPS

  • encounter_check_loops ({“TRIANGULAR”,”SORTSWEEP”}, default “TRIANGULAR”) – Swiftest Experimental feature Specifies which algorithm to use for checking whether bodies are in a close encounter state or not.

    • “TRIANGULAR” - Upper-triangular double-loops.

    • “SORTSWEEP” - A Sort-Sweep algorithm is used to reduce the population of potential close encounter bodies. This algorithm is still in development, and does not necessarily speed up the encounter checking. Use with caution.

    Parameter input file equivalent is ENCOUNTER_CHECK

  • dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

  • coarray (bool, default False) – If true, will employ Coarrays on test particle structures to run in single program/multiple data parallel mode. In order to use this capability, Swiftest must be compiled for Coarray support. Only certain integrators can use Coarrays. RMVS, WHM, Helio are all compatible, but SyMBA is not, due to the way tp-pl close encounters are handeled.

  • verbose (bool, default False) – If set to True, then more information is printed by Simulation methods as they are executed. Setting to False suppresses most messages other than errors and some warnings.

  • seed (ArrayLike of int, optional) – Seed for the random number generator. If not set, then a random seed is generated. Parameter input file equivalent is SEED

Returns:

param (dict) – A dictionary of all Simulation parameters that changed

get_parameter(**kwargs)[source]#

Setter for all possible parameters. Calls each of the specialized setters using keyword arguments.

Parameters:

**kwargs (Any) – Any of the arguments defined in Simulation. If none provided, it returns all arguments.

Returns:

param (dict) – A dictionary of all Simulation parameters requested

set_integrator(codename='Swiftest', integrator=None, mtiny=None, gmtiny=None, **kwargs)[source]#

Sets the integrator to be used when running a simulation. Returns a dictionary of the parameters that were set.

Parameters:
  • codename ({“swiftest”, “swifter”, “swift”}, optional) – The name of the code to use. Case-insensitive valid options are swiftest, swifter, and swift. Currently only swiftest is is supported for excuting runs with the run() method.

  • integrator ({“symba”,”rmvs”,”whm”,”helio”,”ringmoons”}, optional) – Name of the n-body integrator that will be used when executing a run.

  • mtiny (float, optional) – The minimum mass of fully interacting bodies. Bodies below this mass interact with the larger bodies, but not each other (SyMBA only). Only mtiny or gmtiny is accepted, not both.

  • gmtiny (float, optional) – The minimum G*mass of fully interacting bodies. Bodies below this mass interact with the larger bodies, but not each other (SyMBA only). Only mtiny or gmtiny is accepted, not both.

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general set_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

integrator_dict (dict) – A dictionary containing the subset of the parameter dictonary that was updated by this setter

get_integrator(arg_list=None, **kwargs)[source]#

Returns a subset of the parameter dictionary containing the current values of the distance range parameters.

If the verbose option is set in the Simulation object, then it will also print the values.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the features to extract. Default is all of: [“integrator”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

integrator_dict (dict) – The subset of the dictionary containing the code name if codename is selected

set_feature(close_encounter_check=None, general_relativity=None, collision_model=None, minimum_fragment_gmass=None, minimum_fragment_mass=None, nfrag_reduction=None, rotation=None, compute_conservation_values=None, extra_force=None, big_discard=None, rhill_present=None, yarkovsky=None, yarkovsky_schach=None, radiation=None, tides=None, interaction_loops=None, encounter_check_loops=None, encounter_save=None, coarray=None, simdir=None, seed=None, **kwargs)[source]#

Turns on or off various features of a simulation.

Parameters:
  • close_encounter_check (bool, optional) – Check for close encounters between bodies. If set to True, then the radii of massive bodies must be included in initial conditions.

  • encounter_save ({“NONE”,”TRAJECTORY”,”CLOSEST”,”BOTH”}, default “NONE”) – Indicate if and how encounter data should be saved. If set to “TRAJECTORY”, the position and velocity vectors of all bodies undergoing close encounter are saved at each intermediate step to the encounter files. If set to “CLOSEST”, the position and velocities at the point of closest approach between pairs of bodies are computed and stored to the encounter files. If set to “BOTH”, then this stores the values that would be computed in “TRAJECTORY” and “CLOSEST”. If set to “NONE” no trajectory information is saved. WARNING - Enabling this feature could lead to very large files.

  • general_relativity (bool, optional) – Include the post-Newtonian correction in acceleration calculations.

  • collision_model ({“MERGE”,”BOUNCE”,”FRAGGLE”}, default “MERGE”) – This is used to set the collision/fragmentation model. This argument only applies to Swiftest-SyMBA simulations. It will be ignored otherwise. Parameter input file equivalent is COLLISION_MODEL

  • minimum_fragment_gmass (float, optional) – If fragmentation is turned on, this sets the mimimum G*mass of a collisional fragment that can be generated if a fragmentation model is enabled. Ignored otherwise. Only set one of minimum_fragment_gmass or minimum_fragment_mass Parameter input file equivalent is None

  • minimum_fragment_mass (float, optional) – If fragmentation is turned on, this sets the mimimum mass of a collisional fragment that can be generated. if a fragmentation model is enabled. Ignored otherwise Only set one of minimum_fragment_gmass or minimum_fragment_mass Parameter input file equivalent is MIN_GMFRAG

  • nfrag_reduction (float, optional) – If fragmentation is turned on, this is a reduction factor used to limit the number of fragments generated in a collision. For instance, if the SFD of the collision would generated 300 fragments above the minimum_fragment_mass, then a value of nfrag_reduction = 30.0 would reduce it to 10. Currently only used by the Fraggle collision model.

  • rotation (bool, optional) – If set to True, this turns on rotation tracking and radius, rotation vector, and moments of inertia values must be included in the initial conditions. This argument only applies to Swiftest-SyMBA simulations. It will be ignored otherwise.

  • compute_conservation_values (bool, optional) – Turns on the computation of energy, angular momentum, and mass conservation and reports the values every output step of a running simulation.

  • extra_force (bool, optional) – Turns on user-defined force function.

  • big_discard (bool, optional) – Includes big bodies when performing a discard (Swifter only)

  • rhill_present (bool, optional) – Include the Hill’s radius with the input files.

  • interaction_loops ({“TRIANGULAR”,”FLAT”}, default “TRIANGULAR”) – Swiftest Experimental feature Specifies which algorithm to use for the computation of body-body gravitational forces.

    • “TRIANGULAR” : Upper-triangular double-loops .

    • “FLAT” : Body-body interation pairs are flattened into a 1-D array.

  • encounter_check_loops ({“TRIANGULAR”,”SORTSWEEP”}, default “TRIANGULAR”) – Swiftest Experimental feature Specifies which algorithm to use for checking whether bodies are in a close encounter state or not.

    • “TRIANGULAR” : Upper-triangular double-loops.

    • “SORTSWEEP” : A Sort-Sweep algorithm is used to reduce the population of potential close encounter bodies. This algorithm is still in development, and does not necessarily speed up the encounter checking. Use with caution.

  • coarray (bool, default False) – If true, will employ Coarrays on test particle structures to run in single program/multiple data parallel mode. In order to use this capability, Swiftest must be compiled for Coarray support. Only certain integrators can use Coarrays: RMVS, WHM, Helio are all compatible, but SyMBA is not, due to the way tp-pl close encounters are handeled.

  • tides (bool, optional) – Turns on tidal model (IN DEVELOPMENT - IGNORED)

  • yarkovsky (bool, optional) – Turns on Yarkovsky model

  • yarkovsky_schach (bool, optional) – Turns on Yarkovsky-Schach model

  • radiation (bool, optional) – Turns on radiation pressure + PR drag model (IN DEVELOPMENT - IGNORED)

  • YORP (bool, optional) – Turns on YORP model (IN DEVELOPMENT - IGNORED)

  • simdir (PathLike, optional) – Directory where simulation data will be stored, including the parameter file, initial conditions file, output file, dump files, and log files.

  • seed (ArrayLike of int, optional) – Seed for the random number generator. If not set, then a random seed is generated. Parameter input file equivalent is SEED

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general set_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

feature_dict (dict) – A dictionary containing the requested features.

get_feature(arg_list=None, **kwargs)[source]#

Returns a subset of the parameter dictionary containing the current value of the feature boolean values.

If the verbose option is set in the Simulation object, then it will also print the values.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the features to extract. Default is all of: [“close_encounter_check”, “general_relativity”, “collision_model”, “rotation”, “compute_conservation_values”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

feature_dict (dict) – A dictionary containing the requested features.

set_init_cond_files(init_cond_file_type=None, init_cond_file_name=None, init_cond_format=None, **kwargs)[source]#

Sets the initial condition file parameters in the parameters dictionary.

Parameters:
  • init_cond_file_type ({“NETCDF_DOUBLE”, “NETCDF_FLOAT”, “ASCII”}, optional) – The file type containing initial conditions for the simulation

    • NETCDF_DOUBLE: A single initial conditions input file in NetCDF file format of type NETCDF_DOUBLE

    • NETCDF_FLOAT: A single initial conditions input file in NetCDF file format of type NETCDF_FLOAT

    • ASCII : Three initial conditions files in ASCII format. The individual files define the central body, massive body, and test particle initial conditions.

  • init_cond_file_name (str, path-like, or dict, optional) – Name of the input initial condition file or files. Whether to pass a single file name or a dictionary depends on the argument passed to init_cond_file_type: If init_cond_file_type={“NETCDF_DOUBLE”,”NETCDF_FLOAT”}, then this will be a single file name. If init_cond_file_type=”ASCII” then this must be a dictionary where:

    init_cond_file_name = {
        "CB" : *path to central body initial conditions file* (Swiftest only),
        "PL" : *path to massive body initial conditions file*,
        "TP" : *path to test particle initial conditions file*
        }
    

    If no file name is provided then the following default file names will be used.

    • NETCDF_DOUBLE, NETCDF_FLOAT: init_cond_file_name = “init_cond.nc”

    • ASCII: init_cond_file_name = {“CB” : “cb.in”, “PL” : “pl.in”, “TP” : “tp.in”}

  • init_cond_format ({“EL”, “XV”}) – Indicates whether the input initial conditions are given as orbital elements or cartesian position and velocity vectors. If codename is “Swift” or “Swifter”, EL initial conditions are converted to XV.

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general set_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

init_cond_file_dict (dict) – A dictionary containing the requested parameters

get_init_cond_files(arg_list=None, **kwargs)[source]#

Returns a subset of the parameter dictionary containing the current initial condition file parameters.

If the verbose option is set in the Simulation object, then it will also print the values.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the simulation time parameters to extract. Default is all of: [“init_cond_file_type”, “init_cond_file_name”, “init_cond_format”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

init_cond_file_dict (dict) – A dictionary containing the requested parameters

set_output_files(output_file_type=None, output_file_name=None, output_format=None, restart=None, simdir=None, **kwargs)[source]#

Sets the output file parameters in the parameter dictionary.

Parameters:
  • output_file_type ({“NETCDF_DOUBLE”, “NETCDF_FLOAT”,”REAL4”,”REAL8”,”XDR4”,”XDR8”}, optional) – The file type for the outputs of the simulation. Compatible file types depend on the codename argument.

    • Swiftest: Only “NETCDF_DOUBLE” or “NETCDF_FLOAT” supported.

    • Swifter: Only “REAL4”,”REAL8”,”XDR4” or “XDR8” supported.

    • Swift: Only “REAL4” supported.

  • output_file_name (str or path-like, optional) – Name of output file to generate. If not supplied, then one of the default file names are used, depending on the value passed to output_file_type. If one of the NetCDF types are used, the default is “data.nc”. Otherwise, the default is “bin.dat”.

  • output_format ({“XV”,”XVEL”}, optional) – Specifies the format for the data saved to the output file. If “XV” then cartesian position and velocity vectors for all bodies are stored. If “XVEL” then the orbital elements are also stored.

  • restart (bool, optional) – Indicates whether this is a restart of an old run or a new run.

  • simdir (PathLike, optional) – Directory where simulation data will be stored, including the parameter file, initial conditions file, output file

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general set_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

output_file_dict (dict) – A dictionary containing the requested parameters

get_output_files(arg_list=None, **kwargs)[source]#

Returns a subset of the parameter dictionary containing the current output file parameters.

If the verbose option is set in the Simulation object, then it will also print the values.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the simulation time parameters to extract. Default is all of: [“output_file_type”, “output_file_name”, “output_format”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

output_file_dict (dict) – A dictionary containing the requested parameters

set_unit_system(MU=None, DU=None, TU=None, MU2KG=None, DU2M=None, TU2S=None, MU_name=None, DU_name=None, TU_name=None, recompute_unit_values=True, **kwargs)[source]#

Setter for setting the unit conversion between one of the standard sets.

The units can be set one of two ways

  1. The user can supply string values to the arguments MU, DU, and TU to select between common systems

  2. The user can supply float values to the arguments MU2KG, DU2M, and TU2S to manually set the conversion factor between the desired unit and the SI unit (kg-m-s).

The two sets of arguments are mutually exclusive. Any values passed to MU2KG, DU2M, or TU2S will override any specified in MU, DU, or TU, respectively. The default system is Msun-AU-YR. MU, DU, and TU are case-insenstive

Parameters:
  • MU (str, optional) – The mass unit system to use. Case-insensitive valid options are

    • “Msun” - Solar mass

    • “Mearth” - Earth mass

    • “kg” - kilograms

    • “g”,”gm” - grams

  • DU (str, optional) – The distance unit system to use. Case-insensitive valid options are

    • “AU” - Astronomical Unit

    • “Rearth” - Earth radius

    • “km” - kilometer

    • “m” - meter

    • “cm” - centimeter

  • TU (str, optional) – The time unit system to use. Case-insensitive valid options are

    • “y”,”YR”,”year”,”years” - Year

    • “d”,”day”,”days” - Julian day

    • “s”,”sec”,”seconds”,”second” - second

  • MU2KG (float, optional) – The conversion factor to multiply by the mass unit that would convert it to kilogram. Setting this overrides MU

  • DU2M (float, optional) – The conversion factor to multiply by the distance unit that would convert it to meter. Setting this overrides DU

  • TU2S (float, optional) – The conversion factor to multiply by the time unit that would convert it to seconds. Setting this overrides TU

  • MU_name (str, optional) – The name of the mass unit. When setting one of the standard units via MU a name will be automatically set for the unit, so this argument will override the automatic name.

  • DU_name (str, optional) – The name of the distance unit. When setting one of the standard units via DU a name will be automatically set for the unit, so this argument will override the automatic name.

  • TU_name (str, optional) – The name of the time unit. When setting one of the standard units via TU a name will be automatically set for the unit, so this argument will override the automatic name.

  • recompute_unit_values (bool, default True) – Recompute all values into the new unit system. This is a destructive operation, however if not executed then the values contained in the parameter file and input/output data files computed previously may not be consistent with the new unit conversion factors.

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general set_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

unit_dict (dict) – A dictionary containing the requested unit conversion parameters

get_unit_system(arg_list=None, **kwargs)[source]#

Returns a subset of the parameter dictionary containing the current simulation unit system.

If the verbose option is set in the Simulation object, then it will also print the values.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the simulation unit system Default is all of [“MU”, “DU”, “TU”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

unit_dict (dict) – A dictionary containing the requested unit conversion parameters

set_distance_range(rmin=None, rmax=None, qmin_coord=None, **kwargs)[source]#

Sets the minimum and maximum distances of the simulation.

Parameters:
  • rmin (float) – Minimum distance of the simulation (CHK_QMIN, CHK_RMIN, CHK_QMIN_RANGE[0])

  • rmax (float) – Maximum distance of the simulation (CHK_RMAX, CHK_QMIN_RANGE[1])

  • qmin_coord (str, {“HELIO”, “BARY”}) – coordinate frame to use for CHK_QMIN

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general set_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

range_dict (dict) – A dictionary containing the requested parameters.

get_distance_range(arg_list=None, **kwargs)[source]#

Returns a subset of the parameter dictionary containing the current values of the distance range parameters.

If the verbose option is set in the Simulation object, then it will also print the values.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the features to extract. Default is all of [“rmin”, “rmax”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

range_dict (dict) – A dictionary containing the requested parameters.

add_solar_system_body(name=None, ephemeris_id=None, date=None, align_to_central_body_rotation=False, **kwargs)[source]#

Adds a solar system body to an existing simulation Dataset from the JPL Horizons ephemeris service.

The JPL Horizons service will be searched for a body matching the string passed by name, or alternatively ephemeris_id if passed. Bodies will be named in the Swiftest initial conditions Dataset using name. Use ephemeris_id to have finer control over which body is searched in Horizons while using a custom name.

If name is not passed, then the target name property is used as the name. You must pass either name and/or ephemeris_id.

When passing name == “Earth” or name == “Pluto”, it a body is generated that has initial conditions matching the system barycenter and mass equal to the sum of Earth+Moon or Pluto+Charon. To obtain initial conditions for either Earth or Pluto alone, pass ephemeris_id == “399” for Earth or ephemeris_id == “999” for Pluto.

Parameters:
  • name (str, optional | List[str]) – Add solar system body by name. This will be the name used in the Swiftest initial conditions Dataset unless not supplied

  • ephemeris_id (int | List[int], optional but must be the same length as name if passed.) – In that case, the id is passed to the ephemeris service and the name is used.

  • date (str, optional) – ISO-formatted date sto use when obtaining the ephemerides in the format YYYY-MM-DD. Defaults to value set by ephemeris_date.

  • align_to_central_body_rotation (bool, default False) – If True, the cartesian coordinates will be aligned to the rotation pole of the central body. Otherwise, the This is only valid for when rotation is enabled.

  • verbose (bool, default True) – If True, then warnings will be printed if the name is already in use in the Dataset.

  • **kwargs (Any) – Additional keyword arguments to pass to the query method (i.e. astroquery.Horizons)

Returns:

None – initial conditions data stored as a SwiftestDataset in the init_cond instance variable

get_ephemeris_date(arg_list=None, **kwargs)[source]#

Prints the current value of the ephemeris date.

Parameters:
  • arg_list (str | List[str], optional) – A single string or list of strings containing the names of the features to extract. Default is all of: [“integrator”]

  • **kwargs (Any) – A dictionary of additional keyword argument. This allows this method to be called by the more general get_parameter method, which takes all possible Simulation parameters as arguments, so these are ignored.

Returns:

ephemeris_date (str) – The ISO-formatted date string for the ephemeris computation

add_body(name=None, a=None, e=None, inc=None, capom=None, omega=None, capm=None, rh=None, vh=None, mass=None, Gmass=None, radius=None, rhill=None, rot=None, Ip=None, rotphase=None, j2rp2=None, j4rp4=None, c_lm=None, align_to_central_body_rotation=False, albedo=None, emissivity=None, rot_k=None, gamma=None, k2=None, Q=None, **kwargs)[source]#

Adds a body (test particle or massive body) to the internal Dataset given a set of either orbital elements or cartesian state vectors.

If orbital elements are passed, cartesian state vectors are computed and vice versa, using the currently-assigned central body, so cannot both be passed. Input all angles in degrees and dimensional quantities in the unit system defined in the current Simulation instance.

This method will update the data attribute with the new body or bodies added to the existing Dataset.

Parameters:
  • name (str or array-like of str, optional) – Name or names of Bodies. If none passed, name will be “Body{id}”

  • a (float or array-like of float, optional) – semimajor axis for param[‘IN_FORM’] == “EL”

  • e (float or array-like of float, optional) – eccentricity for param[‘IN_FORM’] == “EL”

  • inc (float or array-like of float, optional) – inclination for param[‘IN_FORM’] == “EL”

  • capom (float or array-like of float, optional) – longitude of ascending node for param[‘IN_FORM’] == “EL”

  • omega (float or array-like of float, optional) – argument of periapsis for param[‘IN_FORM’] == “EL”

  • capm (float or array-like of float, optional) – mean anomaly for param[‘IN_FORM’] == “EL”

  • rh ((n,3) array-like of float, optional) – Position vector array.

  • vh ((n,3) array-like of float, optional) – Velocity vector array.

  • mass (float or array-like of float, optional) – mass values if these are massive bodies (only one of mass or Gmass can be passed)

  • Gmass (float or array-like of float, optional) – G*mass values if these are massive bodies (only one of mass or Gmass can be passed)

  • radius (float or array-like of float, optional) – Radius values if these are massive bodies

  • rhill (float or array-like of float, optional) – Hill’s radius values if these are massive bodies

  • rot ((3) or (n,3) array-like of float, optional) – Rotation rate vectors if these are massive bodies with rotation enabled.

  • Ip ((3) or (n,3) array-like of float, optional) – Principal axes moments of inertia vectors if these are massive bodies with rotation enabled.

  • rotphase (float, optional) – rotation phase angle in degreesif these are massive bodies with rotation enabled

  • j2rp2 (float, optional) – Non-normalized J2 values (e.g. J2*R**2, where R is the body radius) if this is a central body (only one of J2 or c_lm can be passed)

  • j4rp4 (float, optional) – Non-normalized J4 values (e.g. J4*R**4, where R is the body radius) if this is a central body (only one of J4 or c_lm can be passed)

  • c_lm ((2,l_max+1,l_max+1) array-like of float, optional) – Spherical harmonics coefficients if this is a central body (only one of J2/J4 or c_lm can be passed)

  • align_to_central_body_rotation (bool, default False) – If True, the cartesian coordinates will be aligned to the rotation pole of the central body. This is only valid for when rotation is enabled.

  • albedo (float or array-like of float, optional) – Albedo values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • emissivity (float or array-like of float, optional) – Emissivity values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • rot_k (float or array-like of float, optional) – Rotational constant K values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • gamma (float or array-like of float, optional) – Thermal inertia values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • k2 (float or array-like of float, optional) – Tidal love number k2

  • Q (float or array-like of float, optional) – Tidal quality factor Q

Returns:

None – Sets the data and init_cond instance variables each with a SwiftestDataset containing the body or bodies that were added

add_ring(r_p, m_p, mass_distribution, albedo=None, emissivity=None, rot_k=None, gamma=None, obliquity=None, a_pl=None, Y_21=None, delta=None, **kwargs)[source]#

Add a 1D eulerian ring to a simulation.

Parameters:
  • r_p (float) – Radius of ring particles (DU)

  • m_p (float) – Mass of ring particles in each bin (MU).

  • mass_distribution (dict) – Dictionary describing the mass distribution of the ring. Options are: - “powerlaw”: Power-law mass distribution. Must also contain keys “nbins”, “alpha”, “sigma0”, “r_outer”. - “gaussian”: Gaussian mass distribution. Must also contain keys “nbins”, “sigma0”, “mu” and “dev”. - “arbitrary”: Arbitrary mass distribution. Must also contain keys “sigma” (an array of surface mass densities), “r_inner” and “r_outer” (the inner and outer radii of the ring).

  • albedo (float, optional) – Bond albedo of ring particles (for Yarkovsky-Schach effect)

  • emissivity (float, optional) – Emissivity values of ring particles (for Yarkovsky-Schach effect)

  • rot_k (float, optional) – Rotational constant K values of ring particles (for Yarkovsky-Schach effect)

  • gamma (float, optional) – Thermal inertia values of ring particles (for Yarkovsky-Schach effect)

  • obliquity (float, optional) – Obliquity of the host planet

  • a_pl (float, optional) – semi-major axis of the planet from the Sun

  • Y_21 (list of floats, optional) – 2nd row-1st column element of the Yarkovsky directional matrix (for Yarkovsky-Schach effect)

  • delta (list of floats, optional) – Planetary shadow width at various distances

  • **kwargs (Any) – Additional keyword arguments. These are ignored.

calc_Yarkovsky_direction_matrix_Y_21(nbins, rmag, albedo, emissivity, gamma)[source]#
calc_planet_shadow_width(r, obliquity)[source]#
remove_body(name=None, id=None)[source]#

Removes a body (test particle or massive body) from the internal Dataset.

This method will update data and init_cond attributes with the body or bodies removed.

Only name or id may be passed, but not both.

Parameters:
  • name (str or array-like of str, optional) – Name or names of bodies to remove.

  • id (int or array-like of int, optional) – Id value or values of bodies to removed.

Returns:

None

modify_body(name=None, id=None, a=None, e=None, inc=None, capom=None, omega=None, capm=None, rh=None, vh=None, mass=None, Gmass=None, radius=None, rhill=None, rot=None, Ip=None, rotphase=None, j2rp2=None, j4rp4=None, c_lm=None, albedo=None, emissivity=None, rot_k=None, gamma=None, k2=None, Q=None, align_to_central_body_rotation=False, framenum=-1, **kwargs)[source]#

Modifies an existing body in the internal Dataset given a new value of either the orbital elements or cartesian state vectors, or the physical property of the body (mass, radius, etc).

Input all angles in degrees and dimensions in the units defined in the current Simulation instance. Currently, this will only modify the last entry of the body in the time dimension. This method will update the data attribute with the modified body or bodies added to the existing Dataset.

Parameters:
  • name (str or array-like of str, optional) – Name or names of bodies to modify.

  • id (int or array-like of int, optional) – Id value or values of bodies to modify. Only one of name or id may be passed, but not both.

  • a (float or array-like of float, optional) – semimajor axis for param[‘IN_FORM’] == “EL”

  • e (float or array-like of float, optional) – eccentricity for param[‘IN_FORM’] == “EL”

  • inc (float or array-like of float, optional) – inclination for param[‘IN_FORM’] == “EL”

  • capom (float or array-like of float, optional) – longitude of ascending node for param[‘IN_FORM’] == “EL”

  • omega (float or array-like of float, optional) – argument of periapsis for param[‘IN_FORM’] == “EL”

  • capm (float or array-like of float, optional) – mean anomaly for param[‘IN_FORM’] == “EL”

  • rh ((n,3) array-like of float, optional) – Position vector array.

  • vh ((n,3) array-like of float, optional) – Velocity vector array.

  • mass (float or array-like of float, optional) – mass values if these are massive bodies (only one of mass or Gmass can be passed)

  • Gmass (float or array-like of float, optional) – G*mass values if these are massive bodies (only one of mass or Gmass can be passed)

  • radius (float or array-like of float, optional) – Radius values if these are massive bodies

  • rhill (float or array-like of float, optional) – Hill’s radius values if these are massive bodies

  • rot ((3) or (n,3) array-like of float, optional) – Rotation rate vectors if these are massive bodies with rotation enabled.

  • Ip ((3) or (n,3) array-like of float, optional) – Principal axes moments of inertia vectors if these are massive bodies with rotation enabled.

  • rotphase (float, optional) – rotation phase angle in degreesif these are massive bodies with rotation enabled

  • j2rp2 (float, optional) – Non-normalized J2 values (e.g. J2*R**2, where R is the body radius) if this is a central body (only one of J2 or c_lm can be passed)

  • j4rp4 (float, optional) – Non-normalized J4 values (e.g. J4*R**4, where R is the body radius) if this is a central body (only one of J4 or c_lm can be passed)

  • c_lm ((2,l_max+1,l_max+1) array-like of float, optional) – Spherical harmonics coefficients if this is a central body (only one of J2/J4 or c_lm can be passed)

  • albedo (float or array-like of float, optional) – Albedo values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • emissivity (float or array-like of float, optional) – Emissivity values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • rot_k (float or array-like of float, optional) – Rotational constant K values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • gamma (float or array-like of float, optional) – Thermal inertia values if these are massive bodies and the radiation (Yarkovsky, PR, YS, Rad Pressure) effects are being modeled.

  • k2 (float or array-like of float, optional) – Tidal love number k2

  • Q (float or array-like of float, optional) – Tidal quality factor Q

  • align_to_central_body_rotation (bool, default False) – If True, the cartesian coordinates will be aligned to the rotation pole of the central body. This is only valid for when rotation is enabled.

  • framenum (int, default -1) – Frame number to modify. If -1, the last frame is modified.

Returns:

None – Sets the data and init_cond instance variables each with a SwiftestDataset containing the body or bodies that were added

read_param(param_file=None, codename=None, **kwargs)[source]#

Reads in an input parameter file and stores the values in the param dictionary.

Parameters:
  • param_file (str or path-like, default is the value of the Simulation object’s internal param_file.) – File name of the input parameter file

  • codename ({“Swiftest”, “Swifter”, “Swift”}, default is the value of the Simulation object’s internal codename instance variable) – Type of parameter file, either “Swift”, “Swifter”, or “Swiftest”

Returns:

None

read_init_cond(init_cond_file_name=None, init_cond_file_type=None, init_cond_format=None, dask=False, **kwargs)[source]#

Reads in a set of initial conditions from file and stores them as the init_cond and data instance variables.

Parameters:
  • init_cond_file_name (str, path-like, or dict, optional) – Name of the input initial condition file or files. Whether to pass a single file name or a dictionary depends on the argument passed to init_cond_file_type. If init_cond_file_type={“NETCDF_DOUBLE”,”NETCDF_FLOAT”}, then this will be a single file name. If init_cond_file_type=”ASCII” then this must be a dictionary where:

    init_cond_file_name = {
        "CB" - [path to central body initial conditions file] (Swiftest only),
        "PL" - [path to massive body initial conditions file],
        "TP" - [path to test particle initial conditions file] }
    

    If no file name is provided then the following default file names will be used.

    • “NETCDF_DOUBLE”, “NETCDF_FLOAT” init_cond_file_name = “init_cond.nc”

    • “ASCII” init_cond_file_name = {“CB” : “cb.in”, “PL” : “pl.in”, “TP” : “tp.in”}

    Parameter input file equivalent is NC_IN, CB_IN, PL_IN, TP_IN

  • init_cond_file_type ({“NETCDF_DOUBLE”, “NETCDF_FLOAT”, “ASCII”}, default “NETCDF_DOUBLE”) – The file type containing initial conditions for the simulation.

    • “NETCDF_DOUBLE” A single initial conditions input file in NetCDF file format of type NETCDF_DOUBLE.

    • “NETCDF_FLOAT” A single initial conditions input file in NetCDF file format of type NETCDF_FLOAT.

    • “ASCII” Three initial conditions files in ASCII format. The individual files define the central body,

    massive body, and test particle initial conditions. Parameter input file equivalent is IN_TYPE

  • init_cond_format ({“EL”, “XV”}, default “XV”) – Indicates whether the input initial conditions are given as orbital elements or cartesian position and velocity vectors. If codename is “Swift” or “Swifter”, EL initial conditions are converted to XV. Parameter input file equivalent is IN_FORM

  • dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

Returns:

None

write_param(codename=None, param_file=None, param=None, **kwargs)[source]#

Writes to a param.in file and determines whether the output format needs to be converted between Swift/Swifter/Swiftest.

Parameters:
  • codename ({“Swiftest”, “Swifter”, “Swift”}, optional) – Alternative name of the n-body code that the parameter file will be formatted for. Defaults to current instance variable codename

  • param_file (str or path-like, optional) – Alternative file name of the input parameter file. Defaults to current instance variable self.param_file

  • param (Dict, optional) – An alternative parameter dictionary to write out. Defaults to the current instance variable self.param

  • **kwargs (Any) – A dictionary of additional keyword argument. These are ignored.

Returns:

None

convert(param_file, newcodename='Swiftest', plname='pl.swiftest.in', tpname='tp.swiftest.in', cbname='cb.swiftest.in', conversion_questions=None, dask=False, **kwargs)[source]#

Converts simulation input files from one format to another (Swift, Swifter, or Swiftest).

Parameters:
  • param_file (string) – File name of the input parameter file

  • newcodename (string) – Name of the desired format (Swift/Swifter/Swiftest)

  • plname (string) – File name of the massive body input file

  • tpname (string) – File name of the test particle input file

  • cbname (string) – File name of the central body input file

  • conversion_questions (dictronary) – Dictionary of additional parameters required to convert between formats

  • dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

Returns:

oldparam (Dict) – The old parameter configuration.

read_output_file(read_init_cond=True, read_encounters=True, read_collisions=True, dask=False, **kwargs)[source]#

Reads in simulation data from an output file and stores it as a SwiftestDataset in the data instance variable.

Parameters:
  • read_init_cond (bool, default True) – Read in an initial conditions file along with the output file. Default is True

  • dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

Returns:

None – Sets the data instance variable xarray dataset

read_encounter_file(dask=False, **kwargs)[source]#

Reads in an encounter history file and stores it as a SwiftestDataset in the encounters instance variable.

Parameters:

dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

Returns:

None – Sets the encounters instance variable SwiftestDataset

read_collision_file(dask=False, **kwargs)[source]#

Reads in a collision history file and stores it as an Xarray Dataset in the collisions instance variable.

Parameters:
  • dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

  • **kwargs (Any) – A dictionary of additional keyword arguments.

Returns:

None – Sets the collisions instance variable xarray dataset

read_ring_file(dask=False, **kwargs)[source]#

Reads in a Ringmoons history file and stores it as an Xarray Dataset in the ring instance variable.

Parameters:
  • dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

  • **kwargs (Any) – A dictionary of additional keyword arguments.

Returns:

None – Sets the collisions instance variable xarray dataset

follow(codestyle='Swifter', dask=False, **kwargs)[source]#

An implementation of the Swift tool_follow algorithm. Under development. Currently only for Swift simulations.

Parameters:
  • codestyle (str, default “Swifter”) – Name of the desired format (Swift/Swifter/Swiftest)

  • dask (bool, default False) – Use Dask to lazily load data (useful for very large datasets)

  • **kwargs (Any) – A dictionary of additional keyword arguments.

Returns:

xarray dataset – Dataset containing the variables retrieved from the follow algorithm

save(codename=None, param_file=None, param=None, framenum=-1, **kwargs)[source]#

Saves an xarray dataset to a set of input files.

Parameters:
  • codename ({“Swiftest”, “Swifter”, “Swift”}, optional) – Alternative name of the n-body code that the parameter file will be formatted for. Defaults to current instance variable self.codename

  • param_file (str or path-like, optional) – Alternative file name of the input parameter file. Defaults to current instance variable self.param_file

  • param (Dict, optional) – An alternative parameter dictionary to write out. Defaults to the current instance variable self.param

  • framenum (int Default=-1) – Time frame to use to generate the initial conditions. If this argument is not passed, the default is to use the last frame in the dataset.

  • **kwargs (Any) – A dictionary of additional keyword argument.

Returns:

None

clean(deep=False, **kwargs)[source]#

Cleans up simulation directory by deleting old files (dump, logs, and output files).

Parameters:
  • deep (bool, default False) – If True, also delete the entire simulation directory.

  • **kwargs (Any) – A dictionary of additional keyword arguments.

Returns:

None

property param#

A dictionary of simulation parameters. These are stored in the param.in file.

Type:

Dict

property data#

A dataset containing the simulation data.

Type:

SwiftestDataset

property init_cond#

A dataset containing the initial conditions.

Type:

SwiftestDataset

property encounters#

A dataset containing the encounter history.

Type:

SwiftestDataset

property collisions#

A dataset containing the collision history.

Type:

SwiftestDataset

property ring#

A dataset containing the ring model in the Ringmoons integrator.

Type:

SwiftestDataset

property simdir#

The simulation directory.

Type:

Path

property param_file#

The parameter file.

Type:

Path

property MU_name#

The name of the mass unit currently defined in the simulation.

Type:

str

property DU_name#

The name of the distance unit currently defined in the simulation.

Type:

str

property TU_name#

The name of the time unit currently defined in the simulation.

Type:

str

property MU2KG#

The conversion factor from mass unit to kilograms.

Type:

np.float64

property KG2MU#

The conversion factor from kilograms to mass unit.

Type:

np.float64

property DU2M#

The conversion factor from distance unit to meters.

Type:

np.float64

property M2DU#

The conversion factor from meters to distance unit.

Type:

np.float64

property TU2S#

The conversion factor from time unit to seconds.

Type:

np.float64

property S2TU#

The conversion factor from seconds to time unit.

Type:

np.float64

property GU#

The gravitational constant in the simulation units.

Type:

np.float64

property integrator#

The name of the integrator used in the simulation. Currently supports “symba”, “rmvs”, “whm”, “helio”, and “ringmoons”.

Type:

Literal[“symba”,”rmvs”,”whm”,”helio”,”ringmoons”]

property codename#

The name of the n-body code used in the simulation. Currently supports “Swiftest”, “Swifter”, and “Swift”.

Type:

Literal[“Swiftest”,”Swifter”,”Swift”]

property verbose#

A boolean value indicating whether verbose output is enabled.

Type:

bool

property restart#

A boolean value indicating whether the run should be restarted from a previous output.

Type:

bool

property ephemeris_date#

ISO-formatted date sto use when obtaining the ephemerides in the format YYYY-MM-DD.

property ring_file#

Path to the ring file in a Ringmoons integrator.

Data Representation#

SwiftestDataset#

class swiftest.data.SwiftestDataset(ds=None, **kwargs)[source]#

Bases: Dataset

A xarray.Dataset-like, multi-dimensional, in memory, array database. Inherits from xarray.Dataset and has its own set of methods and attributes specific to the Swiftest project.

Parameters:
  • *args – Arguments for the xarray.Dataset class

  • **kwargs – Keyword arguments for the xarray.Dataset class

Notes

See xarray.Dataset for further information about Datasets.

classmethod from_dataframe(dataframe)[source]#

Override to make the result a swiftest.SwiftestDataset class.

classmethod from_dict(data, **kwargs)[source]#

Override to make the result a swiftest.SwiftestDataset class.

rotate(rotvec=None, pole=None, skip_vars=('space', 'Ip'))[source]#

Rotates the coordinate system such that the z-axis is aligned with an input pole. The new pole is defined by the input vector.

This will change all variables in the Dataset that have the “space” dimension, except for those passed to the skip_vars parameter.

Parameters:
  • ds (SwiftestDataset) – Dataset containing the vector quantity

  • rotvec ((N,3) or (3,) float array) – Rotation vector

  • pole ((3) float array) – New pole vector

  • skip_vars (list of str, optional) – List of variable names to skip. The default is [‘space’,’Ip’].

Returns:

ds (SwiftestDataset) – Dataset with the new pole vector applied to all variables with the “space” dimension

Notes

You can pass either rotvec or pole, but not both. If both, or none, are passed, the function will raise an exception.

el2xv(GMcb=None)[source]#

Converts a Dataset’s orbital elements to Cartesian state vectors. The DataArray must have the appropriate dimensions for orbital elements.

Parameters:

GMcb (xr.DataArray or float) – Gravitational parameter of the central body

Returns:

SwiftestDataset – Dataset containing the computed state vectors (position ‘rh’ and velocity ‘vh’).

xv2el(GMcb=None)[source]#

Converts A Dataset’s Cartesian state vectors to orbital elements. The DataArray must have the “space” dimension.

Parameters:

GMcb (xr.DataArray or float) – Gravitational parameter of the central body

Returns:

SwiftestDataset – Dataset containing the computed orbital elements.

SwiftestDataArray#

class swiftest.data.SwiftestDataArray(*args, **kwargs)[source]#

Bases: DataArray

N-dimensional xarray.DataArray-like array. Inherits from xarray.DataArray and has its own set of methods and attributes specific to the Swiftest project.

Parameters:
  • *args – Arguments for the xarray.DataArray class

  • **kwargs – Keyword arguments for the xarray.DataArray class

Notes

See xarray.DataArray for further information about DataArrays.

to_dataset()[source]#

Converts a SwiftestDataArray into a SwiftestDataset with a single data variable.

magnitude(name=None)[source]#

Computes the magnitude of a vector quantity. Note: The DataArray must have the “space” dimension.

Parameters:

name (str, optional) – Name of the new DataArray. By default, the string “_mag” is appended to the original name.

Returns:

mag (SwiftestDataArray) – DataArray containing the magnitude of the vector quantity

rotate(rotation)[source]#

Rotates a vector quantity using a rotation matrix. The DataArray must have the “space” dimension.

Parameters:

rotation ((3) float array) – Rotation vector

item(*args)#

Copy an element of an array to a standard Python scalar and return it.

Parameters:

*args (Arguments (variable number and type)) –

  • none: in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned.

  • int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return.

  • tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array.

Returns:

z (Standard Python scalar object) – A copy of the specified element of the array as a suitable Python scalar

Notes

When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.

item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.

Examples

>>> import numpy as np
>>> np.random.seed(123)
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[2, 2, 6],
       [1, 3, 6],
       [1, 0, 1]])
>>> x.item(3)
1
>>> x.item(7)
0
>>> x.item((0, 1))
2
>>> x.item((2, 2))
1

For an array with object dtype, elements are returned as-is.

>>> a = np.array([np.int64(1)], dtype=np.object_)
>>> a.item() #return np.int64
np.int64(1)
searchsorted(v, side='left', sorter=None)#

Find indices where elements of v should be inserted in a to maintain order.

For full documentation, see numpy.searchsorted.

See also

numpy.searchsorted

equivalent function

Initial Conditions Generation Functions#

init_cond.get_solar_system_body(name[, ...])

Initializes a Swiftest dataset containing the major planets of the Solar System at a particular data from JPL/Horizons.

init_cond.horizons_query(id, ...[, ...])

Queries JPL/Horizons for a body matching the id.

init_cond.get_solar_system_body_mass_rotation(id)

Parses the raw output from JPL Horizons in order to extract physical properties of a body if they exist.

Gravitional Harmonics Functions#

shgrav.clm_from_ellipsoid(mass, density, a)

Creates and returns the gravity coefficients for an ellipsoid with principal axes a, b, c upto a certain maximum degree lmax.

shgrav.clm_from_relief(mass, density, grid)

Creates and returns the gravity coefficients for a body with a given DH grid upto a certain maximum degree lmax.

Input/Output Processing Functions#

A collection of functions for processing simulation files.

Reading and writing simulation parameter and initial conditions files#

io.process_netcdf_input(ds, param)

Performs several tasks to convert raw NetCDF files output by the Fortran program into a form that is used by the Python side.

io.read_swiftest_param(param_file_name, param)

Reads in a Swiftest param.in file and saves it as a dictionary.

io.read_swifter_param(param_file_name[, verbose])

Reads in a Swifter param.in file and saves it as a dictionary.

io.read_swift_param(param_file_name[, ...])

Reads in a Swift param.in file and saves it as a dictionary.

io.write_swift_param(param, param_file_name)

Writes a Swift param.in file.

io.write_labeled_param(param, param_file_name)

Writes a Swifter/Swiftest param.in file.

io.select_active_from_frame(ds, param[, ...])

Selects a particular frame from a DataSet and returns only the active particles in that frame.

io.swiftest_xr2infile(ds, param[, in_type, ...])

Writes a set of Swiftest input files from a single frame of a Swiftest xarray dataset.

Tools for fixing differences between NetCDF-Fortran and xarray data structures#

io.swiftest2xr(param[, verbose, dask])

Converts a Swiftest binary data file into an xarray DataSet.

io.reorder_dims(ds)

Re-order dimension coordinates so that they are in the same order as the Fortran side.

io.fix_types(ds[, itype, ftype])

Converts all variables in the dataset to the specified type.

Tools#

Miscellaneous helper functions

tool.wrap_angle(angle)

Converts angles to be between 0 and 360 degrees.

tool.follow_swift(ds[, ifol, nskp])

Emulates the Swift version of tool_follow.f It will generate a file called follow.out containing 10 columns (angles are all in degrees).

Core#

Compiled Fortran routines for the core of the Swiftest project.

core.driver(integrator, param_file_name, ...)

core.el2xv(mu, a, e, inc, capom, omega, capm)

Convert orbital elements to state vectors

core.xv2el(mu, rh, vh)

Convert state vectors to orbital elements

Constants#

The constants module defines several astronomical and physical constants. Below is a description of each constant:

Constant

Description

GC

The gravitational constant (G) from Astropy constants, in SI units (m^3 kg^-1 s^-2).

AU2M

Astronomical Unit in meters, representing the average distance from the Earth to the Sun.

GMSun

Standard gravitational parameter for the Sun in m^3 s^-2.

MSun

Mass of the Sun in kilograms.

RSun

Radius of the Sun in meters.

MEarth

Mass of the Earth in kilograms.

REarth

Radius of the Earth in meters.

GMEarth

Standard gravitational parameter for the Earth in m^3 s^-2.

JD2S

Number of seconds in a Julian day.

YR2S

Number of seconds in a Julian year (365.25 days).

einsteinC

Speed of light in vacuum in meters per second.

J2Sun

Solar quadrupole moment coefficient (J2), indicating the extent of the Sun’s equatorial bulge.

J4Sun

Higher order coefficient (J4) for the Sun’s shape, indicating asymmetry in its mass distribution.

rotpoleSun

SkyCoord object representing the rotation pole of the Sun in right ascension (ra) and declination (dec), converted to Cartesian coordinates.

rotSun

Angular velocity of the Sun’s rotation in radians per second, considering an average rotational period of 25.05 days.

Fortran API Documentation#

For detailed documentation of the Fortran API, see the Fortran API.