C++ Module: gravityEffector

Executive Summary

Abstract class that is used to implement an effector impacting a GRAVITY body that does not itself maintain a state or represent a changing component of the body (for example: gravity, thrusters, solar radiation pressure, etc.)

The module PDF Description contains further information on this module’s function, how to run it, as well as testing.

Message Connection Descriptions

The following table lists all the module input and output messages. The module msg connection is set by the user from python. The msg type contains a link to the message structure definition, while the description provides information on what this message is used for.

gravityEffector module input and output messages

GravityEffector Module I/O Messages

Msg Variable Name

Msg Type

Description

centralBodyOutMsg

SpicePlanetStateMsgPayload

Central planet body state output message.

The gravity effector contains a list of GravBodyData objects which contain the planet mass and size properties etc. The following table lists the Spice planet ephemeris input message that can be connected to a GravBodyData object. If no message is connected, then the planet has zero position and orientation information by default.

GravBodyData module input and output messages

GravBodyData Message Interfaces

Msg Variable Name

Msg Type

Description

planetBodyInMsg

SpicePlanetStateMsgPayload

Planet spice ephemeris input message.

User Guide

The user must provide a list of GravBodyData objects to the spacecraft using:

scObject.gravField.gravBodies = spacecraft.GravBodyVector(gravBodyList)

Each gravity body data object can be created using:

earth = gravityEffector.GravBodyData()
earth.planetName = 'earth_planet_data'
earth.mu = 0.3986004415E+15  # meters^3/s^2
earth.radEquator = 6378136.6  # meters
earth.isCentralBody = False

Note that the simIncludeGradBody.py helper file contains a gravity body factor class to facilitate setting up gravity bodies.

Spherical Harmonics Reference Radius and Gravitational Parameter

useSphericalHarmonicsGravityModel(file, maxDeg) loads the reference radius and the gravitational parameter of the first row of the coefficient file into spherHarm.radEquator and spherHarm.muBody. When the body is initialized:

  • The field keeps the reference radius of the file, since the normalized coefficients are only valid with the reference radius of their model. radEquator of the GravBodyData is used only if spherHarm.radEquator is not positive, for example when the coefficients were set directly instead of being loaded from a file. To evaluate the field with a different reference radius, set spherHarm.radEquator.

  • The gravitational parameter of the field is replaced by mu of the GravBodyData, so that the field and gravity-gradient torque use the same value. Body initialization raises BasiliskError if mu is not finite and positive, even when the file supplies a valid GM. To use the file GM, explicitly set planet.mu = planet.spherHarm.muBody after loading the file and before initializing the simulation. No warning is given when a valid body GM differs from the gravitational parameter of the file.

Spherical Harmonics Coefficient Tables and Initialization

When setting spherHarm.cBar, spherHarm.sBar, and spherHarm.maxDeg directly, both coefficient tables must contain at least maxDeg + 1 rows. Row l holds orders zero through l and must contain at least l + 1 entries. This includes degree zero, which requires one row with at least one entry in each table. Additional columns and rows above maxDeg are ignored, so padded tables and truncation of a higher-degree model are supported.

Both initialization overloads discard the previous recurrence tables on each attempt. In Python, direct initializeParameters() calls return None on success or an error string identifying an incomplete coefficient table. Initialization through GravBodyData raises BasiliskError on failure. After correcting a rejected configuration, initialize successfully before evaluating the field. For example:

from Basilisk.simulation import sphericalHarmonicsGravityModel

model = sphericalHarmonicsGravityModel.SphericalHarmonicsGravityModel()
model.muBody = 3.986004415e14  # [m^3/s^2]
model.radEquator = 6378136.3  # [m]
model.maxDeg = 2
model.cBar = [[1.0], [0.0, 0.0], [-4.84e-4, 0.0, 2.44e-6]]  # [-]
model.sBar = [[0.0], [0.0, 0.0], [0.0, 0.0, -1.40e-6]]  # [-]
error = model.initializeParameters()
if error is not None:
    raise ValueError(error)
position = [7.0e6, 1.0e6, 2.0e6]  # [m] Body-fixed position
acceleration = model.computeField(position)  # [m/s^2]

computeField() raises BasiliskError if initialization has not succeeded, the requested degree exceeds either the current maxDeg or the last successfully initialized degree, or a required coefficient row or entry is missing. These checks also apply after public attributes are changed. Reinitialize before evaluating degrees above the initialized range. Changing coefficient values within that range does not require reinitialization, provided the required table dimensions remain valid. The explicit-degree overload checks only the coefficient rows used by that evaluation, allowing lower-degree evaluation even when unused higher-degree rows are incomplete.

Potential Energy

All gravity-model computePotentialEnergy(position) methods accept a position relative to the gravity body in its body-fixed frame and return potential energy per unit spacecraft mass in \(\mathrm{m^2/s^2}\), with zero at infinity. The point-mass limit is \(-\mu/r\). For the polyhedral model this is the negative of the positive potential used in the Werner and Scheeres formulation. The spherical-harmonic model currently returns only the point-mass potential; its higher-degree acceleration terms are not included in the energy calculation.

GravBodyData.computePotentialEnergyInertial(position, timeNanos) accepts an inertial position relative to the body and performs the frame conversion at the requested simulation time. Like acceleration evaluation, it uses the loaded planet ephemeris and advances its orientation from the message timestamp. An absent or all-zero orientation uses the same identity fallback as acceleration.

The spacecraft’s reported totOrbEnergy includes mass times the specific potential. Planet positions and orientations for this calculation are evaluated at the output epoch, even when the integrator’s last stage occurs earlier. For an isolated, static polyhedral body, orbital energy is conserved up to integration error. A rotating, non-axisymmetric body can exchange energy with the orbit. For uniform rotation about a fixed axis through the body’s center, the conserved quantity is the Jacobi integral \(E/m-\boldsymbol{\omega}\cdot(\mathbf{r}\times\mathbf{v})\), using position and velocity relative to that center in an inertial frame.

Custom C++ gravity models must follow the body-fixed position and negative potential-energy convention of GravityModel.computePotentialEnergy(). The C++ GravityEffector.updateEnergyContributions() method also requires the evaluation time in nanoseconds so it does not depend on a cached integrator-stage time. Python calls to individual gravity models retain their existing signatures, including the positionWrtPlanet_N keyword on the GravityModel base-class wrapper and the point-mass and spherical-harmonic potential methods. This historical keyword still takes a body-fixed position despite its _N suffix. The point-mass and spherical-harmonic potentials are radial, so their potential energy is independent of the position frame’s orientation.

Planet Orientation

The planet orientation is read from planetBodyInMsg together with its time derivative J20002Pfix_dot. Between message updates the orientation is advanced as a rotation about the planet angular velocity, which keeps the orientation matrix orthonormal at every integrator stage. A first-order update of the matrix elements would scale the evaluated field by a relative error of order \((\omega\,\Delta t)^2\). The advanced orientation and its time derivative at the same epoch are stored as the state-engine properties [planetName].J20002Pfix and [planetName].J20002Pfix_dot, both in the \([PN]\) convention of the planet state message.


class GravBodyData
#include <gravityEffector.h>

Container for gravitational body data

This class is designed to hold all of the information for a gravity body. The nominal use-case has it initialized at the python level and attached to dynamics using the AddGravityBody method.

Public Functions

GravBodyData()

Initializes localPlanet to zero except for localPlanet.J20002Pfix, which is initialized to the identity matrix. Additionally, initializes gravityModel to a PointMassGravityModel.

void initBody(int64_t moduleID)

Initializes the gravityModel, logging and raising an error if the initialization fails.

Eigen::Vector3d computeGravityInertial(Eigen::Vector3d r_I, uint64_t simTimeNanos)

Compute gravitational acceleration in inertial coordinates.

Parameters:
  • r_I – Position relative to this body in inertial coordinates [m].

  • simTimeNanos – Evaluation time [ns].

Returns:

Acceleration in inertial coordinates [m/s^2].

double computePotentialEnergyInertial(const Eigen::Vector3d &r_I, uint64_t simTimeNanos) const

Compute specific gravitational potential energy from an inertial position.

Note

Uses the same extrapolated body orientation as computeGravityInertial().

Parameters:
  • r_I – Position relative to this body in inertial coordinates [m].

  • simTimeNanos – Evaluation time [ns].

Returns:

Specific potential energy, with zero at infinity [m^2/s^2].

void loadEphemeris()

Read the ephemeris data from planetBodyInMsg if it’s linked. Otherwise, zeros this->localPlanet.

void registerProperties(DynParamManager &statesIn)

Creates the following properies in the given statesIn object.

- [planetName].r_PN_N
- [planetName].v_PN_N
- [planetName].mu
- [planetName].J20002Pfix
- [planetName].J20002Pfix_dot

vr_PN_N, v_PN_N, and mu are initialized to zero, while J20002Pfix and J20002Pfix_dot are initialized to the values stored in this->localPlanet. This usually means that J20002Pfix is initialized to the identity matrix and J20002Pfix_dot to zero.

Public Members

bool isCentralBody = false

Flag indicating that object is center

std::shared_ptr<GravityModel> gravityModel

Model used to compute the gravity of the object

double mu = 0

[m3/s^2] central body gravitational parameter, also used by the spherical harmonics field, which requires a finite, positive value

double radEquator = 0

[m] Equatorial radius for the body, used as the spherical harmonics reference radius only if the model has none (e.g. not loaded from a file)

double radiusRatio = 1

[] ratio of polar over equatorial radius

std::string planetName = ""

Gravitational body name, this is used as the Spice name if spiceInterface is used

std::string displayName = ""

This is the name that is displayed in Vizard. If not set, Vizard shows planetName

std::string modelDictionaryKey = ""

“” will result in using the current default for the celestial body’s given name, otherwise key will be matched if possible to available model in internal model dictionary

ReadFunctor<SpicePlanetStateMsgPayload> planetBodyInMsg

planet spice ephemeris input message

SpicePlanetStateMsgPayload localPlanet

[-] Class storage of ephemeris info from scheduled portion

BSKLogger bskLogger

– BSK Logging

Private Functions

void computePlanetOrientation(uint64_t simTimeNanos, Eigen::Matrix3d &dcmAdvanced_NPfix, Eigen::Matrix3d &dcmAdvanced_NPfix_dot) const

Extrapolate the planet orientation and its derivative to an evaluation time.

Parameters:
  • simTimeNanos – Evaluation time [ns].

  • dcmAdvanced_NPfix – Output rotation from body-fixed to inertial coordinates [-].

  • dcmAdvanced_NPfix_dot – Output time derivative of dcmAdvanced_NPfix [1/s].

Private Members

Eigen::MatrixXd *r_PN_N

[m] (state engine property) planet inertial position vector

Eigen::MatrixXd *v_PN_N

[m/s] (state engine property) planet inertial velocity vector

Eigen::MatrixXd *muPlanet

[m/s] (state engine property) planet inertial velocity vector

Eigen::MatrixXd *J20002Pfix

[-] (state engine property) planet attitude [PN]

Eigen::MatrixXd *J20002Pfix_dot

[1/s] (state engine property) planet attitude rate [PN_dot]

uint64_t timeWritten = 0

[ns] time the input planet state message was written

Friends

friend class GravityEffector
class GravityEffector : public SysModel
#include <gravityEffector.h>

gravity effector class

Public Functions

void Reset(uint64_t currentSimNanos)

Initializes every GravBodyData associated with this GravityEffector

void UpdateState(uint64_t currentSimNanos)

Updates the central body, loads the ephemeris data for every GravBodyData, and writes the output messages.

void linkInStates(DynParamManager &statesIn)

Links the correlation between times property

void registerProperties(DynParamManager &statesIn)

Registers the gravity, inertial position, and inertial velocity properties. It also calls registerProperties for every associated GravBodyData.

void computeGravityField(Eigen::Vector3d r_cF_N, Eigen::Vector3d rDot_cF_N)

Calculate gravitational acceleration of s/c wrt inertial (no central body) or wrt central body

Parameters:
  • r_cF_N – is position of center of mass of s/c wrt frame

  • rDot_cF_N – is the derivative of above

void updateInertialPosAndVel(Eigen::Vector3d r_BF_N, Eigen::Vector3d rDot_BF_N)

Updates the inertial position and velocity properties

void updateEnergyContributions(Eigen::Vector3d r_cF_N, double &orbPotEnergyContr, uint64_t simTimeNanos)

Accumulate specific potential energy from the associated gravity bodies.

Parameters:
  • r_cF_N – Spacecraft center-of-mass position relative to the integration origin, in inertial coordinates [m].

  • orbPotEnergyContr – Specific potential energy accumulator [m^2/s^2].

  • simTimeNanos – Evaluation time for planet positions and orientations [ns].

void setGravBodies(std::vector<std::shared_ptr<GravBodyData>> gravBodies)

Sets the GravBodyData associated with this effector

void addGravBody(std::shared_ptr<GravBodyData> gravBody)

Adds a GravBodyData associated with this effector

Public Members

std::vector<std::shared_ptr<GravBodyData>> gravBodies

[-] Vector of bodies we feel gravity from

std::shared_ptr<GravBodyData> centralBody

Central body

std::string vehicleGravityPropName = "g_N"

[-] Name of the vehicle gravity acceleration property

std::string systemTimeCorrPropName = "systemTime"

[-] Name of the correlation between times

std::string inertialPositionPropName = "r_BN_N"

[-] Name of the inertial position property

std::string inertialVelocityPropName = "v_BN_N"

[-] Name of the inertial velocity property

Message<SpicePlanetStateMsgPayload> centralBodyOutMsg

central planet body state output message

BSKLogger bskLogger

– BSK Logging

Private Functions

Eigen::Vector3d getEulerSteppedGravBodyPosition(std::shared_ptr<GravBodyData> bodyData, uint64_t simTimeNanos)

Extrapolate a planet position with constant velocity.

Parameters:
  • bodyData – Planet data supplying the position and velocity.

  • simTimeNanos – Evaluation time [ns].

Returns:

Planet position in inertial coordinates [m].

void writeOutputMessages(uint64_t currentSimNanos)

Writes to centralBodyOutMsg if it is linked and there is a central body

Private Members

Eigen::MatrixXd *gravProperty

[-] g_N property for output

Eigen::MatrixXd *timeCorr

[-] Time correlation property

Eigen::MatrixXd *inertialPositionProperty

[m] r_N inertial position relative to system spice zeroBase/refBase coordinate frame, property for output.

Eigen::MatrixXd *inertialVelocityProperty

[m/s] v_N inertial velocity relative to system spice zeroBase/refBase coordinate frame, property for output.