Skip to main content

Python package for computing gravitational fields of irregular celestial bodies using point-mass, polyhedral, and expansion-based methods.

Project description

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.


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/your-repo/gravdyn.git
cd gravdyn
pip install -e .

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.


Author

Safwan Aljbaae
Universidad de Atacama
Email: safwan.aljbaae@gmail.com

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gravdyn-0.1.2.tar.gz (59.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gravdyn-0.1.2-py3-none-any.whl (44.6 kB view details)

Uploaded Python 3

File details

Details for the file gravdyn-0.1.2.tar.gz.

File metadata

  • Download URL: gravdyn-0.1.2.tar.gz
  • Upload date:
  • Size: 59.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for gravdyn-0.1.2.tar.gz
Algorithm Hash digest
SHA256 4b6c370f0ac08c3b671160faacaeeb18814bc073a59fe3ea03aa9cff95e61782
MD5 e140cd46fa27d76ef170d7201d8e1dcc
BLAKE2b-256 cb5eb751887900f992e04eaece0393b863cc88e10b66dd925f995b8309de329d

See more details on using hashes here.

File details

Details for the file gravdyn-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: gravdyn-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 44.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for gravdyn-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b07732c8f687d85b75e8c854e5036101dcf9f618887871de51fb01a2704d3726
MD5 1edf6498290c3c6c3d8d1a14abd1aee3
BLAKE2b-256 8c24b6ac9e13cd72080ab2a9426a45c69fe5d48415f56943758aeecbef311d1c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page