GravDyn
GravDyn is a Python package for computing gravitational fields of irregular celestial bodies using multiple modeling approaches, including point-mass, polyhedral models, and expansion-based methods.
It is designed for research in celestial mechanics, spacecraft dynamics, and asteroid modeling.
Version history
v0.1.3
- Fixed the principal-axes mesh-alignment diagnostic. The validation now treats eigenvector sign changes correctly: a principal axis (\mathbf{v}) and (-\mathbf{v}) represent the same physical direction.
- This prevents correctly aligned meshes from being incorrectly reported as misaligned when the recomputed principal axes differ only by sign.
- Moved the potential files required by the Expansion model from the GitHub repository to the LINEA GravDyn dataset repository.
v0.1.2
- Completed the core functions for gravitational-potential calculations across the package models.
Earlier preliminary versions
- Versions v0.1.0 and v0.1.1 were internal preliminary releases and are no longer available or supported.
Features
- Mesh validation and preprocessing (centering, scaling, alignment)
- Polyhedral gravity model preparation
- Multiple gravity computation methods:
- Point-mass model
- Polyhedral model
- Tetrahedron-center approximation (JAX optimized)
- Potential expansion methods
- Support for single and batch evaluation of field points
- JAX acceleration for high-performance computation
Installation
pip install gravdyn
or (development mode):
git clone https://github.com/safwanaljbaae/gravdyn.git
cd gravdyn
pip install -e .
Getting Started
Install dependencies
From the repository root, install the package and its dependencies:
pip install -e .
Sample data
The Data/ directory contains shape models for some asteroids (e.g. Apophis/, Bennu/, Psyche/). Each asteroid folder contains:
| File | Description |
|---|---|
shape_v.dat |
Vertex coordinates (N × 3) |
shape_f.dat |
Triangular face indices (M × 3) |
Pot_Expansion/ |
Pre-computed expansion potential files (pot_*.dat) |
Run the full pipeline
The script apply_gravdyn.py at the repository root runs the complete workflow (shape verification → point-mass → Werner polyhedral → mascon → expansion → comparison plot) for a user-selected asteroid.
- Open
apply_gravdyn.pyand set the target asteroid, mass, and density (see the commented examples for options, or add a new one). - Run from the repository root:
python apply_gravdyn.py
Outputs are saved as CSV files (pot_Werner.csv, pot_Mascon.csv, etc.) and a comparison plot (d_pot.png) inside Data/<asteroid>/.
Run individual steps
Example scripts are also available in examples/:
python examples/basic_usage_shape_verification.py
python examples/basic_usage_prepare_polyhedral_model.py --asteroid Apophis
python examples/basic_usage_prepare_expansion_model.py --asteroid Apophis
python examples/basic_usage_generate_layered_mascons.py
python examples/basic_usage_potential_model.py
All examples expect to be run from the examples/ directory and use ../Data/ as the data path.
Workflow Overview
Typical usage follows three steps:
1. Shape verification and preprocessing
from gravdyn import shape_verification
shape_verification(
asteroid_name="Apophis", # Name of the asteroid (used for folder structure and outputs)
mass=5.3e10, # Total mass [kg]
density=1.75e0, # Bulk density [kg/m^3]
base_dir="/caminho/completo/para/Data", # Base directory containing the asteroid data
vertices_file="vertices.dat", # File with vertex coordinates (N x 3)
faces_file="faces.dat" # File with triangular faces (M x 3 indices)
)
This function prepares and validates a polyhedral shape model of an irregular body through a sequence of geometric and physical adjustments. It starts by loading the vertices and faces from disk and building a triangular mesh, which is first visualized to check that the geometry looks correct. The mesh is then shifted so that its center of mass lies at the origin, providing a consistent reference frame. After that, it is rescaled so that its volume matches the value implied by the given mass and density, ensuring physical consistency. Once the scaling is done, the inertia tensor is computed and diagonalized to find the principal axes, and the mesh is rotated to align with them. In the end, the updated mesh and visualization outputs are saved, making the model ready for use in gravitational field calculations and dynamical simulations.
2. Prepare polyhedral model
from gravdyn import prepare_werner_model
data = prepare_werner_model(
asteroid="Apophis", # Name of the asteroid → used to locate its folder
base_dir="/caminho/completo/para/Data", # Base directory containing shape and model files
verbose=True # If True, prints progress and file status messages
)
This function generates the geometric quantities required to evaluate the gravitational field of an irregular body using the classical polyhedral formulation. The vertices and faces are loaded first. From this geometry, the function computes the centroids of the faces and edges and finds the set of edges that are related to the mesh. The geometric vectors-edge directions, face normals, and relative position vectors, that are required for the polyhedral gravity equations are then constructed as discussed in Scheeres (2012).
These quantities correspond directly to the terms appearing in the polyhedral potential formulation, where the gravitational potential is expressed as a sum of contributions from edges and faces, involving dyadic products and geometric factors such as logarithmic edge terms and solid angles. This formulation, originally developed by Werner and widely used in asteroid dynamics, is summarized in Orbital Motion in Strongly Perturbed Environments by Daniel J. Scheeres and enables accurate computation of the gravitational field of arbitrarily shaped, constant-density bodies.
References:
- Scheeres D. (2012) Orbital Motion in Strongly Perturbed Environments: Applications to Asteroid, Comet and Planetary Satellite Orbiters. Springer Praxis Books, Springer Berlin Heidelberg, URL https://books.google.cl/books?id=bRtJPgAACAAJ
3. Build potential derivatives
from gravdyn import build_potential_derivatives
d_exprs, d_funcs = build_potential_derivatives(
name_central_body="Apophis", # Name of the central body
pattern="pot_*.dat", # Pattern used to find partial potential files
n_files=100, # Maximum number of potential parts to load
gm0=1.0, # Gravitational parameter used in the substitution
lambdify_backend="jax", # Backend used to create fast numerical functions
base_dir="/caminho/completo/para/Data", # Root directory containing the body data
verbose=True, # If True, prints progress messages
)
This function constructs the gravitational potential of an irregular body from a set of precomputed expansion terms and then derives its spatial gradients. It starts from a symbolic representation of the potential, typically obtained by decomposing the body into tetrahedral elements and expressing the field as a series expansion. In this framework, the (1/r) kernel is expanded using Legendre polynomials so that the total potential becomes a sum of contributions from each tetrahedron.
The function checks whether the derivatives of the potential are already available. If they are, it simply loads them. If not, it reconstructs the full potential by combining the partial expansion terms, substitutes the relevant physical parameters, and differentiates with respect to x, y, and z to obtain the gradient. These symbolic expressions are then converted into numerical functions using sympy.lambdify, so they can be evaluated efficiently during simulations. There is also the option to generate Fortran code, which can be useful when performance matters or when integrating with external tools. If the required derivative files are not found locally, the function attempts to retrieve them from the project’s repository; if they are not available there either, they must be generated separately, which can take time depending on the size of the expansion.
This approach follows the general idea behind the Potential Series Expansion Method. Rather than evaluating the gravitational field directly from the geometry at every step, it builds an analytical representation once and reuses it (Mota et al. 2023). The accuracy depends on the order of the expansion, but the computational cost is significantly reduced compared to the classical polyhedral method.
References:
- Mota M. L., Aljbaae S., and Prado A. F. B. A. The potential series expansion method: application to the asteroid (87) Sylvia. European Physical Journal Special Topics, 232(18-19):2961–2966, December 2023
4. Generate layered mascon model
from gravdyn import generate_layered_mascons
df_mascons = generate_layered_mascons(
base_dir="/caminho/completo/para/Data",
asteroid="Apophis",
total_mass=5.3e10,
densities=[1.5, 1.8, 2.0],
output_csv="layered_mascons.csv"
)
This function generates a layered mascon (mass concentration) model from a triangulated polyhedron. The polyhedron is assumed to be represented by triangular faces, where each face together with the origin defines one tetrahedron. Each tetrahedron is then subdivided radially into n layers, where n = len(densities). One point mass (mascon) is assigned to each layer using the exact center of mass computed as the difference between two similar tetrahedra.
The input densities control the relative mass distribution among layers. The masses are first computed from the density values, then rescaled so that the final sum equals exactly the provided total_mass. Using uniform densities produces a layered discretization of a homogeneous body, while varying densities allows modeling of internal density variations.
The output is a DataFrame with columns: ['x', 'y', 'z', 'mass', 'face_id', 'layer_id', 'density_input'], containing the coordinates, masses, face associations, and layer indices for each mascon. For more details on this method and its validation, we refer the reader to Chanut et al, 2017 and Aljbaae et. al, 2021.
References:
-
Chanut T. G. G., Aljbaae S.,Prado A. F. B. A., and Carruba V. Dynamics in the vicinity of (101955) Bennu: solar radiation pressure effects in equatorial orbits. MNRAS, 470:2687–2701, September 2017. URL: https://academic.oup.com/mnras/article/470/3/2687/3829898
-
Aljbaae S., Souchay J., Carruba V., Sanchez D. M., and Prado A. F. B. A. Influence of Apophis’ spin axis variations on a spacecraft during the 2029 close approach with Earth. Romanian Astronomical Journal, 31(3):317–337, November 2021. URL: https://www.astro.ro/~roaj/31_3/20-2119apophis2b.pdf
5. Compute gravitational field
Point-mass model
from gravdyn import pot_point_mass
p, acc = pot_point_mass(mu=1e5, stat=[1.0, 0.0, 0.0])
Polyhedral model
from gravdyn import prepare_werner_model, batched_werner_potential
polyhedral_data = prepare_werner_model(
asteroid="Apophis",
base_dir="/caminho/completo/para/Data",
verbose=False,
)
p, acc = batched_werner_potential(gm_body=1e5,
stat=[1.0, 0.0, 0.0],
polyhedral_data=polyhedral_data,
batch_size=2000)
Expansion model
from gravdyn import build_potential_derivatives, pot_expansion
f_pot_expansion, f_d_pot_expansion = build_potential_derivatives(
name_central_body="Apophis",
pattern="pot_*.dat",
gm0=1e5,
lambdify_backend="jax",
base_dir="/caminho/completo/para/Data",
verbose=True,
)
p, acc = pot_expansion(
stat=[1.0, 0.0, 0.0],
f_pot_expansion=f_pot_expansion,
f_d_pot_expansion=f_d_pot_expansion,
)
Tetrahedron-center
from gravdyn import load_tetrahedron_data, batched_pot_mascon
data_shape = load_tetrahedron_data(
asteroid="Apophis",
base_dir="/caminho/completo/para/Data",
tetrahedron_data_file="layered_mascons.csv"
)
p, acc = batched_pot_mascon([1.0, 0.0, 0.0], data_shape, batch_size=20000)
Supported Models
| Model | Accuracy | Speed | Notes |
|---|---|---|---|
| Point Mass | Low | Very fast | Baseline model |
| Tetrahedron Center | Medium | Fast | Approximation |
| Polyhedral Model | High | Moderate | Physically accurate |
| Expansion Method | High | Very fast | Requires symbolic prep |
⚡ Performance Notes
- JAX is used for vectorization and JIT compilation
- First call includes compilation overhead
- Subsequent calls are significantly faster
⚠️ Limitations
- Mesh must be closed and valid (no holes)
- Numerical stability depends on distance from surface
- Polyhedral model can be computationally expensive for large meshes
GUI Application
GravDyn includes a graphical user interface for interactive visualization and potential field computation. Launch it with:
python -m gravdyn.gui.gravdyn_gui
The GUI provides three tabs:
- Shape Viewer — Load and visualize asteroid mesh models in 3D
- Potential — Compute gravitational fields using different models and export results
- Settings — (Coming soon)
How to Cite
If you use GravDyn in academic work, please cite:
License
This package is provided for academic and research use only. Modification and redistribution require permission from the authors.
Support and contact
Questions, bug reports, and feature requests should be submitted through the GitHub Issues page of this repository.
For scientific questions, collaborations, or requests related to new PSEM models, please contact:
Safwan Aljbaae
Universidad de Atacama, Instituto de Astronomía y Ciencias Planetarias
Email: safwan.aljbaae@gmail.com
Author
Safwan Aljbaae
Universidad de Atacama
Email: safwan.aljbaae@gmail.com
Metadata
Release files for gravdyn 0.1.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gravdyn-0.1.3.tar.gz | 63.9 kB | Without provenance | Details for gravdyn-0.1.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gravdyn-0.1.3-py3-none-any.whl | Python 3 | none | any | Details for gravdyn-0.1.3-py3-none-any.whl |
Total release size: 111.3 kB
Release files / gravdyn-0.1.3.tar.gz
| Download URL | gravdyn-0.1.3.tar.gz |
|---|---|
| Size | 63.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
565d01ad21a97fae7f12fc80a7ecd4559850cb1222decb296c41c328d98ada51
|
|
BLAKE2b-256 checksum How to use checksums |
203ea67bcf42de13fb1d5d3d3b47a131ce198f783875820c6a4c3243b5787b56
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.4
|
Release files / gravdyn-0.1.3-py3-none-any.whl
| Download URL | gravdyn-0.1.3-py3-none-any.whl |
|---|---|
| Size | 47.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4e3b63a5e61eb965d2d7bc7ceb8cc83d9e9b4fee0fe66234b86f1b2463c4bd24
|
|
BLAKE2b-256 checksum How to use checksums |
92cb82b7a013b1e35e283faed2958276cf34ac6a1378c36032e76c682b5a71c9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.4
|
Security for gravdyn 0.1.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.