0% found this document useful (0 votes)
4 views71 pages

GMAT API Usersguide

The document outlines the DRAFT GMAT Application Programming Interface (API) Release R2022a, detailing its system design and user guide. It describes GMAT as a spacecraft mission design tool, providing an overview of its architecture, core components, and API functionalities for users. The document includes installation instructions, usage examples, best practices, and additional resources for developers and API users.

Uploaded by

Lukas Messina
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views71 pages

GMAT API Usersguide

The document outlines the DRAFT GMAT Application Programming Interface (API) Release R2022a, detailing its system design and user guide. It describes GMAT as a spacecraft mission design tool, providing an overview of its architecture, core components, and API functionalities for users. The document includes installation instructions, usage examples, best practices, and additional resources for developers and API users.

Uploaded by

Lukas Messina
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DRAFT GMAT Application

Programming Interface
Release R2022a

Alex Campbell, Darrel Conway, and John McGreevy

Sep 27, 2022


CONTENTS:

1 Introduction 1

2 System Design 3
2.1 GMAT Architectural Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 The API Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3 GMAT API User’s Guide 7


3.1 Setting up the GMAT API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Conventions in the API Examples and Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.3 Object Usage with the GMAT API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5 Functions Used in the GMAT API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

4 Script Usage 17
4.1 API Functions for Script Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

5 Tutorial: Accessing GMAT Propagation and Navigation Features 21


5.1 Verifying Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.2 Getting Started with the API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.3 Spacecraft Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.4 Force Model Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.5 Propagator Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.6 The GMAT API and Plug-in Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.7 Measurement Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

6 Usage Examples 37
6.1 Time and Coordinate Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.2 API Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.3 API Examples in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6.4 Example: MONTE-GMAT Interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

7 API Best Practices 47


7.1 General Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
7.2 Java and MATLAB Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
7.3 Python Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

A GMAT API Cheat Sheet 49


A.1 Loading the API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
A.2 Asking for Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
A.3 GMAT Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

i
A.4 GMAT Script Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

B API Notebook Walkthroughs 53


B.1 State Management with the GMAT API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
B.2 Propagation with the GMAT API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

C Bibliography 65

D Change History 67

ii
CHAPTER

ONE

INTRODUCTION

The General Mission Analysis Tool, GMAT, is a general purpose spacecraft mission design, analysis, and operations
tool. GMAT is in active development, and has been used for multiple spacecraft missions. GMAT is the operational
tool for maneuver design and navigation on several missions in the Goddard Space Flight Center’s Flight Dynamics
Facility. It is used for mission design at GSFC and at numerous other organizations throughout the world. GMAT is a
free and open source tool, available at the GMAT wiki [GmatWiki].
Core capabilities of GMAT can be accessed using an Application Programming Interface (API). This document de-
scribes the GMAT API, and includes sample usage from Python and MATLAB using Java.
GMAT is coded using an object oriented approach documented in the GMAT Architectural Specification [Architec-
ture]. The system has been under development since 2002. Users interact with GMAT through a spacecraft domain
specific language built into the system, modeled on the MATLAB programming language. The GMAT API opens the
system’s object model to users that want to interact directly with the core system components, outside of the scripted
interfaces used when running the application.
The materials presented in this document are divided into two sections:
• The first section documents the design of the API. In it, you will find an extremely high level overview of the
GMAT code and a matching API overview, a discussion of the philosophy governing the API that includes use
cases, and a description of the additions to the GMAT code base added for the API that enable the examples and
features requested by the user community.
• The second section is a user’s guide for the GMAT API. It contains instructions for installing the API code, a
“Getting Started” tutorial for initial use of the API, and additional hints, tips, and use case descriptions designed
to help you start using the GMAT API.
This documentation concludes with appendices that provide additional API guidelines, review notes, and other infor-
mation for developers and API users.

1
DRAFT GMAT Application Programming Interface, Release R2022a

2 Chapter 1. Introduction
CHAPTER

TWO

SYSTEM DESIGN

2.1 GMAT Architectural Components

The GMAT API exposes core GMAT classes and processes to API users. In order to understand the API, it is useful to
understand at a high level how GMAT works, and how the API encapsulates the GMAT design for use outside of the
program.

2.1.1 The GMAT Architecture

The GMAT system consists of a set of components that set up a framework for executing spacecraft mission analysis
simulations, and a set of components used to define and run the simulation. The former is referred to as the GMAT
engine. The latter defines the components that users script when they run a simulation. Fig. 2.1 shows the connections
between the components of the GMAT engine. The main control element of GMAT is a component called the Moder-
ator. GMAT’s Moderator provides an interface into the inner working of GMAT, and manages user interactions with
the system. Simulations are run in a Sandbox, using clones of user objects created in factories and stored in the GMAT
configuration. Users interact with GMAT through interpreters that convert script or GUI descriptions of simulation
components into the objects used for the simulation. The results of a simulation are passed, through a Publisher, to
subscribing components, which write files or display data for the user. In a nutshell, that is the architecture shown in
Fig. 2.1.
Another view of the components used in GMAT is shown in the component stack diagram in Fig. 2.2. GMAT is built on
a set of utility functions used for string, vector and matrix manipulations, core numerical operations, file manipulations,
and general purpose time and state representations. The GMAT Engine components are built on these utilities, as are
the classes defining the objects used in a GMAT simulation. User interfaces into the GMAT system are built on top of
these core elements of the system.
All of the user configured simulation components are built on a class, GmatBase, that provides the serialization in-
terfaces used to set the properties of the components through object fields. GmatBase provides the interfaces used
when reading and writing simulation objects, either to script files or to panels on the GMAT graphical user interface.
Resources - objects like the spacecraft model, coordinate systems, force models, propagators, environmental elements,
hardware components, and numerical engines used for estimating, targeting, and optimizing - are all built on top of
the GmatBase class, as is the mission timeline scripted as a sequence of GMAT commands. The mission timeline is
referred to as the GMAT mission control sequence in the documentation.
Most users of the GMAT API do not interact directly with the components of the GMAT engine. Those components
are described in the GMAT Architectural Specification [Architecture]. Typical users of the GMAT API fall into two
groups: users that use GMAT components in their work, and users that manipulate scripted components prior to, during,
or after the execution of a script. The API design documented below focuses on these users.

3
DRAFT GMAT Application Programming Interface, Release R2022a

Fig. 2.1: The GMAT engine, showing interactions between the components.

4 Chapter 2. System Design


DRAFT GMAT Application Programming Interface, Release R2022a

Fig. 2.2: The GMAT component stack.

2.2 The API Design

Fig. 2.2 shows an overview of the GMAT component stack. The stack for the GMAT API, shown in Fig. 2.3, has a
similar appearance. Users interact with the GMAT API through an interface layer built using the Simplified Wrapper
and Interface Generator, SWIG. SWIG generates interfaces and shared libraries for Python and Java, and can gener-
ate similar interface code for other languages when needed. Classes in GMAT’s code base are exposed through this
interface using language specific wrappers. Users interact with the GMAT classes through these wrappers.
Using the SWIG interface code, users can work directly with GMAT classes on a class by class/object by object level.
Users that work this way need a pretty complete understanding of object linkages and interactions in GMAT. Using
that expertise, they either imitate many of the steps that are performed by the GMAT engine when GMAT is run or
make calls to the components of the engine to perform the required actions.
Most users would rather work at a less detailed level than this object by object interaction. There are two groups of users
in this category: those that are familiar with GMAT and want to use the API to run GMAT scripts, making API calls
to adapt their scripts along the way, and those that want to use capabilities provided by GMAT inside of models that
they are running in a tool like MATLAB or Python, or in a compiled application written in a language like Java. The
API provides a set of helper functions that encapsulate the GMAT engine behind calls that simplify the management
tasks of the GMAT engine for these users. These API helpers are exposed through the SWIG interface layer for use by
these API users.
A driving feature of the GMAT API is the incorporation of usability features for the API user community. During
the prototyping exercise for the API, the development team found that the SWIG system provides a simple mechanism
for exposing GMAT components in the Python, Java, and MATLAB environments. However, users working in those
systems still found it difficult to use the prototype API because of a lack of on line documentation and apparent incon-
sistencies in the methods in GMAT. The production API addresses the first of these issues through the incorporation
of class and object level help functions for classes that are identified as “API ready.” Interface inconsistencies are ad-
dressed through the addition of methods to the source code that simplify the class and object interfaces, leaving in place
where necessary the interfaces that appear to API users to be inconsistent because of internal code needs in the GMAT
system.

2.2. The API Design 5


DRAFT GMAT Application Programming Interface, Release R2022a

Fig. 2.3: The GMAT API stack.

6 Chapter 2. System Design


CHAPTER

THREE

GMAT API USER’S GUIDE

This chapter contains information and general guidelines for using the GMAT API, along with example use cases,
presented in a tutorial fashion.

3.1 Setting up the GMAT API

The GMAT API is included in the GMAT release code beginning with the GMAT R2020a release of the system on
SourceForge. The API subsystem included in these packages has been tested using Python and MATLAB calls to the
API.

3.1.1 Installation

Installation of the API is complete when the GMAT release bundle is installed on the user’s workstation.

Direct Usage

The API can be used immediately by users that want to run it from the GMAT bin directory. Simply open a session
in MATLAB or Python, change directories to the GMAT bin folder, and load the GMAT system into the executing
environment. The examples shown later in this document can then be run directly in that environment.

Running the API Outside of the GMAT Folders

Users that want to run the API from a different location from the GMAT system need to perform additional steps to
configure the system to address two features of the system:
1. GMAT uses a set of data files for its core functions.
2. Running environments need to be able to find the GMAT API interfaces.
The following paragraphs address the configuration settings for these two items.

7
DRAFT GMAT Application Programming Interface, Release R2022a

File Location Access

GMAT uses a text data file, gmat_startup_file.txt, to identify and locate GMAT plug-in components, planetary
ephemerides, gravitational potentials, and a large variety of other data files required during a run. The GMAT API
operates using this data file by default, but that causes problems when running outside of the GMAT folder structure.
Rather than change the GMAT startup file, API users can accomplish the folder structure definition by creating an API
specific startup file. A python scipt to create this file, [Link] is in the api folder in the main GMAT
folder, as well as more detailed instructions in API_README.txt.
Once the api_startup_file is created, you are ready to configure your Python or MATLAB environment.

External Access from Python

Note: External access from Python requires configuration of an API startup file, as described in the File Location
Access text, above.

The API is loaded from a Python process running outside of the GMAT folders using the load_gmat.py module found
in the GMAT api folder. The simplest way to proceed is to edit that file in place:
1. Open load_gmat.py in a text editor.
2. Change the “<TopLevelGMATFolder>” entry near the top of the file to the absolute path to your top level GMAT
folder. Make sure that the path is enclosed in quotation marks.
Windows users will also need to change backslash characters in this string either to double backslashes or to
forward slashes so that the Python interpreter can handle the path correctly.
3. Save the file.
4. Copy the edited load_gmat.py file into the folder that is used for the API run.
Note one advantage of editing the load_gmat file in the api folder is that this file can be copied into any folder
that needs access to the API. In other words, once the file has the absolute path set, it can be copied to any folder
that needs to act as the home folder for an API run.
Test the configuration to make certain that the API can be run. Note that, rather than directly importing load_gmat,
you will want to preserve the imported symbols. This preservation is done using the syntax “from module import *”,
as shown in this Linux example:

$ cd APIFromHere/
$ python3
>>> from load_gmat import *
>>> sat = [Link]("Spacecraft","Sat")
>>> [Link]()
Current GMAT Objects

EarthMJ2000Eq
EarthMJ2000Ec
EarthFixed
EarthICRF
SolarSystemBarycenter
Sat

The SolarSystem contains the following bodies:


(continues on next page)

8 Chapter 3. GMAT API User’s Guide


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)

[Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, Luna]

>>>

External Access from MATLAB

Note: External access from MATLAB requires configuration of an API startup file, as described in the File Location
Access text, above.

The API is loaded from a MATLAB console running outside of the GMAT folders using the load_gmat.m module found
in the GMAT bin folder. That file configures MATLAB to use the API. The simplest way to use it is to add the GMAT
bin folder to your MATLAB path, either in the running MATLAB environment or in the MATLAB configuration on
your workstation. You can test the configuration to make certain that the API can be run following the steps below,
which run the API from the folder APIFromHere outside of the GMAT installation folders:

$ cd APIFromHere/
$ matlab -nodesktop

To get started, type doc.


For product information, visit [Link].

>> addpath('/<TopLevelGMATFolder>/bin/')
>> load_gmat
No script provided to load.

ans =

Instance of GMAT Moderator is initialized. No script ready to run.

>> sat = [Link]('Spacecraft','MySat')

sat =

Object of type Spacecraft named MySat

>> [Link]()

ans =

Current GMAT Objects

EarthMJ2000Eq
EarthMJ2000Ec
EarthFixed
EarthICRF
SolarSystemBarycenter
MySat

(continues on next page)

3.1. Setting up the GMAT API 9


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


The SolarSystem contains the following bodies:

[Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, Luna]

>>

3.1.2 Loading the API

Packaging

The GMAT API is packaged in a set of libraries encapsulating specific pieces of functionality.

Table 3.1: The component packages built for GMAT’s API


Package Contents Description
Name
gmat GMAT Utilities and Utility classes used in the rest of GMAT, that do not depend on other GMAT
Core Components components, built from gmatutil code.
Classes used for most of the GMAT spacecraft modeling, along with the
GMAT “engine” that drives the main application, built from gmatbase code.
station Ground station Code used to model ground stations
models
navigation Estimation Compo- Classes used for the GMAT orbit determination subsystem.
nents

Initialization

There are some differences in how to initialize the API between Python, Java, and MATLAB, however they all follow
the same basic process. The API is first loaded into the interfacing language, and then the GMAT executive is initial-
ized through the Moderator. The process of initializing the API is detailed in the sections below for each supported
language. The initialization example for each language creates an instance of the Moderator object named myMod that
has been initialized. The result variable is a flag which returns True if the initialization was successful, or False if
unsuccessful.

Python

The API is loaded from the GMAT bin folder into Python with an import command
Python initialization example:

import gmatpy as gmat

At this point, the GMAT Python API is not initialized. A user can initialize it using the Setup() command, or by making
any call to an API specific function.
The API can be loaded into from any folder from Python if by following the External Access from Python instructions,
above.

10 Chapter 3. GMAT API User’s Guide


DRAFT GMAT Application Programming Interface, Release R2022a

Java

Java requires an extra step compared to Python. Not only does the GMAT API need to be imported, a shared library
must also be loaded

import gmat.*;

public class main {

public static void main(String[] args) {

Moderator myMod;
boolean result;

// Load the GMAT library


[Link]("gmat"); // On Windows

myMod = [Link]();
result = [Link]("gmat_startup_file.txt");
}
}

At this point, the GMAT Java API is initialized.

MATLAB

While the MATLAB interface uses the Java API, there are a few extra steps required due to how Java packages are
used inside MATLAB. The . To simplify this, a MATLAB script which performs all the initialization, load_gmat.m,
is included with the GMAT installation in the <install-dir>/bin directory. The load_gmat script also optionally takes
as an input the filename of a GMAT script to load, and a filename to a custom startup file.

[myMod, gmatStartupPath, result] = load_gmat("[Link]");

The extra steps in initializing the GMAT API through MATLAB is because every GMAT library and JAR file needs
to be loaded explicitly, and it needs to be loaded by the Java instance inside MATLAB instead of by MATLAB itself.
For more details, see the comments inside the load_gmat.m file.

3.1. Setting up the GMAT API 11


DRAFT GMAT Application Programming Interface, Release R2022a

3.2 Conventions in the API Examples and Use Cases

The usage section of this documentation shows API users how to perform several common tasks using the GMAT API.

3.2.1 General Conventions

• Numbers that would normally display as 16 digits are truncated to fit on the page when necessary.
• Extraneous white space has been removed from some output.
• Interactive and scripted code segments are shown offset in special blocks, like this:

>>> import gmatpy as gmat

Interactive Python blocks, like the one shown above, include Python’s triple bracket marker. Blocks from Python
script files do not have this marker:

import gmatpy as gmat

Interactive MATLAB elements are displayed similarly, with MATLAB’s Command Window line marker:

>> load_gmat

Note that the typesetting for MATLAB is also different from the Python settings.

3.2.2 User Workspace and GMAT Typography

This documentation provides examples in the two application environments supported by the core GMAT API devel-
opment team: Python and MATLAB (via Java). The API is built using SWIG, and can be built for other platforms.
This documentation does not address other platforms.
Work performed using the API involves interactions with objects created in GMAT that are accessed in the user’s
application environment. This results in references in the user’s environment of objects in the GMAT environment.
The following conventions are observed in this document to help clarify this component dichotomy:
• Objects created in GMAT use camel-cased names. User references to those objects are presented in lowercase.
For instance, the Python script line

mysat = [Link]("Spacecraft", "MySat")

creates a GMAT Spacecraft object named “MySat,” stored in GMAT, that a user accesses through their mysat
environment variable.

3.3 Object Usage with the GMAT API

The goal of this section is to help you start using the GMAT API quickly, while introducing features of the interface in
a natural progression of steps needed to solve a simple orbital state conversion problem.

12 Chapter 3. GMAT API User’s Guide


DRAFT GMAT Application Programming Interface, Release R2022a

3.4 Overview

The GMAT API is built using the Simplified Wrapper and Interface Generator, SWIG. SWIG connects code written in
C and C++ with a variety of high level languages. The production GMAT API provides Python and Java connections
for GMAT functionality. C++ programmers can also use the API specific code interfaces through direct calls into the
GMAT libraries. The following sections describe the provided interfaces. Following that, three levels of interface
usage are described:
1. Usage based primarily on GMAT scripting, with API generated component changes.
2. High level usage of GMAT components to meet specific user needs.
3. Class and object level access to GMAT components for expert users.

3.4.1 GMAT API Interfaces

The production GMAT API is built with Python and Java wrappers. The Java wrappers are used to also provide the
MATLAB interface into the API.

The Python Interface

The Python wrappers are identified by the suffix “_py.” Python imports are provided as .py files, which connect to
associated shared library files. The Python API is packaged in the gmatpy folder contained in the GMAT bin folder.
The API is loaded by importing that folder into the Python environment.

The Java and MATLAB Interface

The Java interface is provided in Java Archive (jar) files and associated libraries. These files include the GMAT base
code API interfaces and the interfaces to the components used in the navigation subsystem, tabulated below.

Table 3.2: Java archives for the GMAT API


Java Wrapper Python Wrapper Contents
[Link] gmat_py.py GMAT Base and utility code
[Link] station_py.py Groundstation components
[Link] navigation_py.py Orbit determination components

MATLAB users load the GMAT API by calling the load_gmat.m MATLAB script in the GMAT bin folder.

3.4.2 Interface Complexity

The GMAT API is designed for three different styles of usage: Users working with configurations based on GMAT
scripting, users that work with GMAT objects through API calls, and users that work at a low level with GMAT objects
directly.

3.4. Overview 13
DRAFT GMAT Application Programming Interface, Release R2022a

GMAT Script Drivers

One use for the GMAT API is to act as a front end for GMAT mission runs. In this context, the user starts a runtime
environment for the controlling language (e.g. a Python session or MATLAB), loads and initializes GMAT using the
API, and then loads a GMAT script into the running environment. At this point the user might manipulate setting on
the GMAT objects used in the script to tailor the run. Once the configuration is ready, the API is used to run the script.
More details can be found in the Script Usage chapter.

High Level Access

A second use of the GMAT API is as a tool for using intermediate level GMAT objects to model portions of an analysis
problem, and to feed the modeled results back to the driving system for further analysis. When used this way, the
GMAT API provides proven and tested components used to meet the user’s needs for building blocks for a problem
running outside of GMAT. Examples of this type of usage include
• Converting state data from one coordinate system into another
• Accessing the GMAT force models for accelerations and Jacobians of a given state.
• Accessing the Navigation measurement models for retrieve calculated measurement values.
The walk-through provided in the Tutorial: Accessing GMAT Propagation and Navigation Features chapter covers the
techniques needed for high level object access and usage.

Component Level Access

Some API users need access to the details of GMAT’s components in order to control them at a fine-grained level
during use, to extend them with new computed data during use, or to monitor and report their state during use. These
users may want to configure the objects by hand, and may want to manipulate the objects differently from the ways
anticipated by the GMAT developers. The GMAT API allows for this level of access to GMAT’s components. The
Doxygen generated object level documentation provides a guide to this type of usage.

3.5 Functions Used in the GMAT API

The GMAT API provides several functions that simplify GMAT use from Java and Python. GMAT’s user classes
include member functions, called methods, that provide interfaces into GMAT objects that help simplify calls into the
GMAT objects. These features of the API are described in this chapter. Script users may also want to refer to the Script
Usage chapter for information about functions tailored to running GMAT scripts through the API.

3.5.1 General API Functions

API specific code in can be broken into three blocks: General API functions used to interact with the system, functions
specific to driving GMAT using script files, and methods that are implemented on the GMAT classes to simplify object
interactions using the API.

14 Chapter 3. GMAT API User’s Guide


DRAFT GMAT Application Programming Interface, Release R2022a

Table 3.3: General Purpose Functions Controlling the API


Function Example Return Value Description
Help [Link](“MySat”) string Returns help for the input
item
Setup [Link](“[Link]”) void Initializes the GMAT sys-
tem with a custom startup
file
Initialize [Link]() none Sets up interconnections
between objects and re-
ports on missing pieces
ShowObjects [Link]() string Lists the configured ob-
jects
ShowClasses [Link](“Burn”) string Lists the classes available
of a given type
Construct object Creates an instance of a
[Link]( class with a given name
“Spacecraft”,”Sat”) and adds it to the GMAT
configuration
Copy [Link](sat, “Sat2”) Creates a new object using
the settings on an existing
object
GetObject [Link](“Sat”) object Retrieves an object from
the configuration

3.5.2 GMAT Object Methods

GMAT’s user classes have been updated with member functions (or methods) that facilitate use for the objects by API
users. These methods are shown in Table 3.4.

Table 3.4: Methods added to GMAT objects for API users


Function Example Return Value Description
Help [Link]() string Retrieves help for an object
SetField [Link](“X”,0.0) bool Sets a field on an object
GetField [Link](“X”) string Retrieves the setting for a field as a string
GetNumber [Link](“X”) double Retrieves the setting for numerical field

3.5. Functions Used in the GMAT API 15


DRAFT GMAT Application Programming Interface, Release R2022a

16 Chapter 3. GMAT API User’s Guide


CHAPTER

FOUR

SCRIPT USAGE

The GMAT API can be used as a front end for driving the GMAT application in a “headless” mode. You might want
to do this to run GMAT remotely, to script product generation, or to perform a large scale run like a Monte-Carlo run
or a scan through a set of parameters. This section introduces the API features that make these processes possible.

4.1 API Functions for Script Users

The GMAT API includes five functions, shown in Table 4.1 specifically designed for script based usage.

Table 4.1: Functions Used to Run Scripts in the API


Function Example Return Value Description
LoadScript Load- bool Loads a script into the GMAT system
Script(“script”)
RunScript RunScript() bool Runs a loaded script
SaveScript SaveScript(“script”) bool Saves the configured objects to a file
GetRuntimeOb- GetRuntimeObject GmatBase* Retrieves an object from a GMAT run
ject (“Sat”)
GetRunSummary GetRunSummary() String Retrieves a listing of the spacecraft data from a script
run for each command in the script

4.1.1 Background: The GMAT Run Script Process

In GMAT, when a user runs a script three steps are taken:


1. The script is read and GMAT objects are created that match the objects described by the script.
• GMAT Resources are stored in the GMAT Configuration.
• GMAT Commands are connected together to create the Mission Control Sequence.
2. The objects from the script are copied (“cloned”) into a memory location, the Sandbox, used for the run.
• This creates a new set of objects used for the run.
• After cloning, these run time objects are connected together as needed and initialized.
3. The Mission Control Sequence is executed sequentially, starting from the first command in the sequence. Com-
mand execution manipulates the run time objects to simulate the scripted mission.
API users drive this process using the functions in Table 4.1.

17
DRAFT GMAT Application Programming Interface, Release R2022a

4.1.2 Driving a Script From the API

API users take the following steps to execute a script:


1. Start the API environment (e.g. Python or MATLAB) from the GMAT bin directory or start the application and
change the current directory to the GMAT bin directory.
2. Load GMAT into the environment. The MATLAB implementation includes a scripted function for this process.
• Python: import gmatpy
• MATLAB: load_gmat()
3. Read a script into the loaded GMAT engine.
• Python: [Link](script_path_and_name)
• MATLAB: [Link](script_path_and_name)
4. Run the script. This step performs the run time object cloning and initialization and then executes the Mission
Control Sequence.
• Python: [Link]()
• MATLAB: [Link]()

4.2 Examples

The sections above describe in general terms how to run GMAT scripts from the API. The following sample usage
shows these features in Python and MATLAB.

4.2.1 Example: Running a Sample Mission

The first example shows how to run a sample mission from the API and retrieve data generated from the run. The
example runs the sample mission Ex_GEOTransfer.script in the GMAT samples folder, then accesses the targeted
maneuvers from the script and computes the total delta-V needed for the run.

Python

Use of the API in Python is performed through direct calls to the functions described above.

Listing 4.1: Sample Run: Calculating the Delta-V for the GEO Transfer,
Run in Python
1 $ python3
2 Python 3.6.7 (default, Oct 22 2018, 11:32:17)
3 [GCC 8.2.0] on linux
4 Type "help", "copyright", "credits" or "license" for more information.
5 >>> import gmatpy as gmat
6 >>> [Link]("../samples/Ex_GEOTransfer.script")
7 True
8 >>> [Link]()
9 True
10 >>> TOI = [Link]("TOI")
11 >>> MCC = [Link]("MCC")
(continues on next page)

18 Chapter 4. Script Usage


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


12 >>> MOI = [Link]("MOI")
13 >>> toidv = float([Link]("Element1"))
14 >>> mccdv = (float([Link]("Element1"))**2+float([Link]("Element2"))**2)**0.5
15 >>> moidv = float([Link]("Element1"))
16 >>> deltaV = abs(toidv)+mccdv+abs(moidv)
17 >>> print("Total Delta-V Cost: ", deltaV, " km/s")
18 Total Delta-V Cost: 4.394839062410714 km/s
19 >>> exit()

MATLAB

Loading the GMAT API in MATLAB is a moderately complicated procedure, so the API developers have wrapped the
load process in a MATLAB function, load_gmat.m. The function takes two optional arguments: the name of a script,
and the startup file used to initialize GMAT. The example shown below leaves both inputs blank so that it closely
matches the Python example, above.

Listing 4.2: Sample Run: Calculating the Delta-V for the GEO Transfer,
Run in MATLAB
1 >> load_gmat()
2 Initialize Moderator Status: 1
3 No script provided to load.
4

5 ans =
6

7 Instance of GMAT Moderator is initialized. No script ready to run.


8

9 >> [Link]("../samples/Ex_GEOTransfer.script")
10

11 ans =
12

13 logical
14

15 1
16

17 >> [Link]()
18

19 ans =
20

21 logical
22

23 1
24

25 >> TOI = [Link]("TOI");


26 >> MCC = [Link]("MCC");
27 >> MOI = [Link]("MOI");
28 >> toidv = str2num([Link]("Element1"));
29 >> mccdv = sqrt(str2num([Link]("Element1"))^2+str2num([Link]("Element2"))^2);
30 >> moidv = str2num([Link]("Element1"));
31 >> DeltaV = abs(toidv)+mccdv+abs(moidv)
32

(continues on next page)

4.2. Examples 19
DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


33 DeltaV =
34

35 4.394839062410714
36

37 >> exit

20 Chapter 4. Script Usage


CHAPTER

FIVE

TUTORIAL: ACCESSING GMAT PROPAGATION AND NAVIGATION


FEATURES

The use case demonstration for the first GMAT API Beta build focuses on using the API for models that exercise core
GMAT functions. For the purposes of this release of the API, the target use case suite shows how to setup and use force
models, propagators, and measurement models. The implemented functionality in the Beta release includes the ability
to drive GMAT scripts as well. That capability is described separately in Script Usage.
The goal of the use cases described here is to build a GMAT measurement model from core components, using the
API functions. GMAT’s measurement models require a propagation component in order to solve the light transit time
portion of the modeling. Propagation requires configuration of both a numerical integrator and of a force model, along
with a spacecraft that supplies model parameters. This guide will walk Python and MATLAB users through the process
of configuring these components in order to assemble a range measurement.
The problem demonstrated in the example code here provides modeling for an Earth orbiting spacecraft, “EarthOrbiter.”
The spacecraft is an 80 kg vehicle modeled in a polar orbit with a 6600 km semimajor axis. That ensures that we need
to configure a fair number of system parameters in order to build the simulation.

5.1 Verifying Setup

The GMAT API is included in releases of GMAT beginning with the R2020a release of the system. Once GMAT is
installed, the API can be accessed from inside of the folder containing the GMAT application.
• For Python, change directories to the GMAT bin folder and access the API help system:

>>> import gmatpy as gmat


>>> [Link]()

---------------------------------------
GMAT Application Programmer's Interface
---------------------------------------
...

• For MATLAB users


– Start MATLAB
– Change directories to the installed GMAT bin directory
– Load the API and access the help system:

>> load_gmat()
No script provided to load.
(continues on next page)

21
DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)

ans =

Instance of GMAT Moderator is initialized. No script ready to run.

>> [Link]()

ans =

---------------------------------------
GMAT Application Programmer's Interface
---------------------------------------
...

5.2 Getting Started with the API

Note: This section introduces several API functions and tools for users new to GMAT’s API by experimenting inter-
actively with the system in Python. This section introduces interaction with the GMAT API, but is not necessary for
the force model, propagation, and measurement configuration described below.

The modeling for this use case uses an Earth centered coordinate system with axes oriented in the mean of J2000
Equatorial frame. The coordinate system can be built using the Construct function of the API. The Python code for
this object creation is:

import gmatpy as gmat


eartheq = [Link]("CoordinateSystem", "EarthMJ2000Eq", "Earth", "MJ2000Eq")

Users can view the list of objects that have been built during a run using the ShowObjects() function:

>>> [Link]()
Current GMAT Objects

EarthMJ2000Eq

The SolarSystem contains the following bodies:

[Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, Luna]
>>>

The code above created a coordinate system object, an axis system object, and connected those objects together for later
use. The object cannot be fully exercised at this point because it is missing some key connections to the modeled space
environment, consisting of a solar system model, member planets and the Sun and Moon, along with other internal
objects used to tie a user’s components together.
For this example, the solar system is not yet connected to the new coordinate system, and the bodies needed for use
- the Earth, for example - are also not yet connected. The coordinate system object’s state can be checked using its
“IsInitialized()” method:

22 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


DRAFT GMAT Application Programming Interface, Release R2022a

>>> [Link]()
False

Objects that are ready for use return True from this call. The API prepares the objects for use with the Initialize()
function:

>>> [Link]()
>>> [Link]()
True

The Initialize() function prepares all of the objects that the user has created for use, and reports any objects that could
not be prepared because of missing settings.
Objects can be removed individually from GMAT using the Clear(ObjectName) function, or all once using the Clear()
function without specifying an object:

>>> [Link]()
Current GMAT Objects

EarthMJ2000Eq

>>> [Link]("EarthMJ2000Eq")
'The object EarthMJ2000Eq has been removed from GMAT.'
>>> [Link]()
Current GMAT Objects

>>> eartheq = [Link]("CoordinateSystem", "EMJ2k", "Earth", "MJ2000Eq")


>>> [Link]()
Current GMAT Objects

EMJ2k

>>> [Link]()
'All configured objects have been removed from GMAT.'
>>> [Link]()
Current GMAT Objects

>>>

The full set of GMAT API commands are described in Functions Used in the GMAT API.
The functions used above are presented working interactively in the GMAT API. In the remainder of this section, the
configuration is built in a Python script included with the GMAT release in the API folder. Matching MATLAB .m
scripts are included in the API folder for users more comfortable working in that environment.

5.2. Getting Started with the API 23


DRAFT GMAT Application Programming Interface, Release R2022a

5.3 Spacecraft Configuration

Note: The Spacecraft Configuration and Force Model Setup examples are located in the
Ex_R2020a_BasicForceModel.py file. An example of the full configuration, showing one configuration for the
exercises, is in the Ex_R2020a_CompleteForceModel file.
To use one of these files, copy the file you plan to use into GMAT’s bin folder.

Spacecraft configuration requires that we define the initial spacecraft state data for the orbiter, and then configure the
spacecraft properties needed for the force modeling.

5.3.1 Construction and The Initial State

Using this coordinate system, the spacecraft state can be configured. For this example, the spacecraft is in a circular
polar orbit at the moon on July 20, 2020. The orbital state is set using the scripting

# Load GMAT into memory


import gmatpy as gmat

# Spacecraft configuration preliminaries


earthorb = [Link]("Spacecraft", "EarthOrbiter")
[Link]("DateFormat", "UTCGregorian")
[Link]("Epoch", "20 Jul 2020 12:00:00.000")

[Link]("CoordinateSystem", "EarthMJ2000Eq")
[Link]("DisplayStateType", "Keplerian")

# Orbital state
[Link]("SMA", 6600)
[Link]("ECC", 0.05)
[Link]("INC", 78)
[Link]("RAAN", 45)
[Link]("AOP", 90)
[Link]("TA", 180)

5.3.2 Additional Spacecraft Parameters

The force model used for this example may include full field Earth gravity, point mass effects from the Sun and Moon
(“Luna” for GMAT), Jacchia-Roberts drag, and solar radiation pressure. The latter forces require settings for the
reflectivity and drag coefficients of the spacecraft, its surface areas for those forces, and the spacecraft mass. These
settings are made using the SetField method, and resemble the corresponding GMAT scripting:

# Spacecraft ballistic properties for the SRP and Drag models


[Link]("SRPArea", 2.5)
[Link]("Cr", 1.75)
[Link]("DragArea", 1.8)
[Link]("Cd", 2.1)
[Link]("DryMass", 80)

For reference, the GMAT scripting for this configuration is

24 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


DRAFT GMAT Application Programming Interface, Release R2022a

Create Spacecraft EarthOrbiter;


GMAT [Link] = UTCGregorian;
GMAT [Link] = '20 Jul 2020 12:00:00.000';
GMAT [Link] = MoonEc;
GMAT [Link] = Keplerian;
GMAT [Link] = 4000;
GMAT [Link] = 0.05;
GMAT [Link] = 78;
GMAT [Link] = 45;
GMAT [Link] = 90;
GMAT [Link] = 180;
GMAT [Link] = 80;
GMAT [Link] = 2.1;
GMAT [Link] = 1.75;
GMAT [Link] = 1.8;
GMAT [Link] = 2.5;

Note: Differences between Python and MATLAB code


The code shown above and throughout this section is Python code. In the MATLAB version of this example, there are
several differences worth noting because of the platform differences:
1. GMAT is loaded using the MATLAB load_gmat.m script. This script loads the GMAT libraries into MATLAB,
initializes the GMAT system by reading a startup file and loading plugins and configuration data identified in
that file, and optionally loads a GMAT script into memory.
2. Access to the GMAT functions is made using a call into a nested “gmat” class built for the underlying Java code.
In general, where Python users type

sat = [Link]("Spacecraft","Sat")

MATLAB users enter

sat = [Link]('Spacecraft','Sat');

3. Type identification requires a call that sets the object type. In the Python implementation of the API, changes
from the base GmatBase type to the derived type is automatic. In MATLAB/Java, the user needs to perform the
cast. Where Python users type

sat = [Link]("Spacecraft","Sat")

to work with a Spacecraft object, MATLAB users that need to interact with the object as a Spacecraft need to
enter

sat = [Link]('Spacecraft','Sat');
sat = [Link](sat);

A MATLAB class, GMATAPI, is provided in the bin folder which contains static functions that automatically
handle the change from the base GmatBase type to the derived type just like in the Python API. MATLAB users
can now type

sat = [Link]('Spacecraft','Sat');

This type setting becomes important when objects are passed to other objects using methods that require specific
object type, as is the case when setting forces on a dynamics model or spacecraft on a propagation state manager

5.3. Spacecraft Configuration 25


DRAFT GMAT Application Programming Interface, Release R2022a

(examples below).

5.4 Force Model Setup

GMAT hides the complexity of force modeling in the internal ODEModel class, which is aliased to the label “Force-
Model” in GMAT scripting. The GMAT scripting for the force model used here is

Create ForceModel FM;


GMAT [Link] = Earth;
GMAT [Link] = {Earth};
GMAT [Link] = 8;
GMAT [Link] = 8;
GMAT [Link] = '[Link]';

5.4.1 Basic Force Model Configuration

Using the API is similar for force configuration, but not identical. The GMAT scripting hides the creation of individual
forces and their collection into the ODEModel force container. Settings on the forces in an ODEModel are made by
passing those settings from the force container to the corresponding force. API users access the forces directly, setting
their parameters and force by force and passing the configured forces into the ODEModel container. The model scripted
above is configured using the scripting

# Force model settings


fm = [Link]("ForceModel", "FM")
[Link]("CentralBody", "Earth")

# An 8x8 JGM-3 Gravity Model


earthgrav = [Link]("GravityField")
[Link]("BodyName","Earth")
[Link]("PotentialFile","../data/gravity/earth/[Link]")
[Link]("Degree",8)
[Link]("Order",8)

# Add force to the dynamics model


[Link](earthgrav)

Note the difference in the calls to Construct in this example. The dynamics model is created using the line

fm = [Link]("ForceModel", "FM")

and the gravity model component, with the code

earthgrav = [Link]("GravityField")

The dynamics model has a name, “FM.” The gravity field does not have a name. Objects constructed with names are
managed by the GMAT code running inside of the API library. Objects that do not have names are not managed by
the library. The object ownership for those objects is the responsibility of the code that creates the object. For the
dynamics model under construction here, the user has responsibility for the gravity field in this call:

# Unnamed: The user is responsible for this object


earthgrav = [Link]("GravityField")

26 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


DRAFT GMAT Application Programming Interface, Release R2022a

and then passes that responsibility to the dynamics model with this call:

# Add force to the dynamics model, passing ownership to the dynamics


[Link](earthgrav)

5.4.2 Connecting the Spacecraft

Before the force model can be used, it needs to be connected to the spacecraft that provides state data and force model
parameters. GMAT does this using a component called a Propagation State Manager (PSM). The PSM component is
not exposed to script users. It is built inside of the scripted Propagator object that connects together integrators and
force models.
Users that want to work directly with a force model can do so by creating a Propagation State Manager object and
working directly with it. The force model built above can be tested using this approach:

psm = [Link]()
[Link](earthorb)
[Link]()

The last line here, “[Link]()”, creates an internal state object that connects spacecraft properties to a vector of
data used by the force model. The propagation state manager is connected to the force model, and its state set as the
force model’s state, using the scripting

[Link](psm)
[Link]([Link]())

5.4.3 Testing the Model

The steps above produce a GMAT force model configuration that can be used from the user’s application framework.
All that remains is initialization of the objects, post initialization preparation, and then calls that exercise the model.
Initialization connects the force model to GMAT’s underlying resources, including the solar system objects and core
elements of the system infrastructure:

# Assemble all of the objects together


[Link]()

GMAT’s propagation subsystem, which includes the force model components, requires two additional steps before it
can be used. First the state vector needs to be set up for the force and propagation modeling. This step determines and
sets the size of the state and derivative vectors, and sets up mappings between the spacecraft that are modeled and that
state vector. The second step passes the parameters needed for modeling into the force model and propagator objects
that are used.
For direct access to the force modeling, the user needs to execute these steps directly:

# Finish force model setup:


## Map spacecraft state into the model
[Link]()
## Load physical parameters needed for the forces
[Link]()

Users can display the Cartesian form of the state vector used in the modeling by accessing the state vector from the
spacecraft:

5.4. Force Model Setup 27


DRAFT GMAT Application Programming Interface, Release R2022a

# Now access state and get derivative data


pstate = [Link]().GetState()
print("State Vector: ", pstate)

Finally, the force model can be exercised either in its raw form as used by the integrators by calling the GetDerivatives()
method:

[Link](pstate)
dv = [Link]()
print("Derivative: ", dv)

or by calling it for a specific spacecraft object through the GetDerivativesForSpacecraft() method:

vec = [Link](earthorb)
print("SCDerivative: ", vec)

When these pieces are assembled together, a run of the Ex_R2020a_BasicForceModel script shows the input state and
derivative outputs to the user:
Note: numbers have been truncated for display purposes

$ python3 Ex_R2020a_BasicForceModel.py
State Vector: [1018.819261, -1018.819261, -6778.562873, 5.226958, 5.226958, -1.374825e-
˓→15]

Derivative: [5.226958, 5.226958, -1.374825e-15, -0.00121383, 0.00121392, 0.00809840]

SCDerivative: 5.226958 5.226958 -1.374825e-15 -0.00121383 0.00121392 0.00809840

5.4.4 Exercises

1. Add point mass forces for the Sun and Moon to the force model. The GMAT class for point mass forces is named
“PointMassForce”.
2. Use the propagation state manager to turn on the A-Matrix computation for the force model by passing the
“AMatrix” setting to the propagation state manager using its SetProperty method.
3. Add a Jacchia-Roberts drag model and a solar radiation pressure model to the force model.

5.5 Propagator Setup

Note: The Propagator Setup example shown here is located in Ex_R2020a_PropagationStep.m file. It uses a basic
force model by importing from the Ex_R2020a_BasicFM file, a stripped down version of the force model used in the
previous section. An example of the full configuration, showing one solution for the exercises, is in the PropagateLoop
file.
To use one of the propagation files, copy the file you plan to use into GMAT’s bin folder. Also copy the
Ex_R2020a_BasicFM file.

In GMAT scripting the lines of script for a propagator,

28 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


DRAFT GMAT Application Programming Interface, Release R2022a

Create Propagator PDProp


GMAT [Link] = FM;
GMAT [Link] = PrinceDormand78;
GMAT [Link] = 60;
GMAT [Link] = 1.0e-12;
GMAT [Link] = 0.0;

create an object from the GMAT class PropSetup. This object is a container for an object that performs propagation
either numerically through an Integrator object or analytically through an object implementing an analytic algorithm.
The latter objects are used, in GMAT, for ephemeris propagators. The former are used for Runge-Kutta integrators,
predictor-correctors, and other numerical integration algorithms that require associated dynamics models. When the
propagator requires a dynamics model, that model is also managed by a PropSetup object. The key feature to know
for propagator configuration in the GMAT API is that a “Propagator” is actually a PropSetup object that contains the
propagation component and, for numerical integrators, a dynamics model.
Working interactively, an API user can see this relationship in Python:

>>> import gmatpy as gmat


>>> pdprop = [Link]("Propagator","PDProp")
>>> pdprop
<gmatpy.gmat_py.PropSetup; proxy of <Swig Object of type 'PropSetup *' at 0x7f26b76a57e0>
˓→ >

5.5.1 Propagator Component Setup

When a Propagator is scripted, a PropSetup is created that the user then configures for use. Using the provided MAT-
LAB example, the code that loads the force model and builds the PropSetup is

% Load GMAT into memory


[myMod, gmatStartupPath, result] = load_gmat();

Ex_R2020a_BasicFM;

% Build the propagation container class


pdprop = [Link]("Propagator","PDProp");

The PropSetup constructed here is a container for the objects used in propagation. The next step configuring this
container is creation and assignment of an integrator, performed using the steps

% Create and assign a numerical integrator for use in the propagation


gator = [Link]("PrinceDormand78");
[Link](gator);

The dynamics model also needs to be set on the PropSetup:

% Assign the force model imported from Ex_R2020a_BasicFM


[Link](fm);

Once the local references are set, the integrator settings can be made similarly to the dynamics model setting in the
previous section:

% Set some of the fields for the integration


[Link]("InitialStepSize", 60.0);
(continues on next page)

5.5. Propagator Setup 29


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


[Link]("Accuracy", 1.0e-12);
[Link]("MinStep", 0.0);

5.5.2 Spacecraft and Final Initialization

In the preceding section, the propagation state manager was built as a separate component and configured to connect
the spacecraft to the dynamics model. When working with a PropSetup component, the propagation state manager is
integrated into the component. As an alternative to the manual steps to configure the propagation state manager, the
PropSetup provides a function, PrepareInternals(), that handles this configuration for each propagated object added
through the AddPropObject() function, and completes the initialization of the component and its integrator:

% Setup the spacecraft that is propagated


[Link](earthorb);
[Link]();

GMAT’s PropSetup component works by creating copies of the propagator and dynamics models. Those copies need
to be set for the application environment so that the user can use them after configuration. The PropSetup provides a
simple mechanism for accessing its copies. The code that refreshes the local variables for them to be used, is

% Refresh the 'gator reference


gator = [Link]();

5.5.3 Running the Propagator

The propagator can now be used. A 60-second propagation is performed, showing the state data before and after the
step, using the code

% Take a 60 second step, showing the state before and after


[Link]()
[Link](60);
[Link]()

These calls produce this output from Ex_R2020a_PropagationStep.m:

>> Ex_R2020a_PropagationStep
Initialize Moderator Status: 1
No script provided to load.

ans =

1.0e+03 *

1.018819261603825
-1.018819261603827
-6.778562873085272
0.005226958779502
0.005226958779502
-0.000000000000000

(continues on next page)

30 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


ans =

1.0e+03 *

1.330028382856595
-0.703241487939055
-6.763990149325915
0.005142965479731
0.005288543267909
0.000485610549370

>>

5.5.4 Exercises

1. Modify the Ex_R2020a_PropagationStep example to use a force model that includes the point mass Sun and
Moon forces and solar radiation pressure.
2. Wrap the propagator in a loop so that propagation extends for a full day, displaying the epoch and position at
each propagation step.

5.6 The GMAT API and Plug-in Modules

GMAT plug-in modules package new functionality into shared libraries that GMAT loads when it starts up. The API’s
copy of GMAT loads these modules when they are identified in the GMAT startup file. Standard GMAT functions
work on components from plugins, but the API calls have several restrictions.

5.6.1 Wrapped Plugins

The Station and Estimation plugin libraries in GMAT include SWIG wrapper code for the contained classes. This
reduces the restrictions on those components.
As an example of the restrictions on wrapped plugin code, consider the Station plugin, which implements GMAT’s
GroundStation class. Users of GMAT’s GroundStation class can access the full feature set for the class. The user is
required in Python to cast constructed components to the derived class type by hand. The Python auto-cast feature in
the GMAT core code is not accessible from the plugin component as seen below:

>>> import gmatpy as gmat


>>> station = [Link]("GroundStation","Station")
>>> station
<gmatpy.gmat_py.GmatBase; proxy of <Swig Object of type 'GmatBase *' at 0x7fccdc983f60> >
>>> station=[Link](station)
>>> station
<gmatpy.station_py.GroundStation; proxy of <Swig Object of type 'GroundStation *' at␣
˓→0x7fccdc983fc0> >

>>>

Note that in this code, the station object returned from the call to the Construct() function is set as a GmatBase object.
In order to treat it as a GroundStation object, the user needed to call the [Link]() method on the object
in order for Python to identify the object’s subclass correctly.

5.6. The GMAT API and Plug-in Modules 31


DRAFT GMAT Application Programming Interface, Release R2022a

MATLAB API users are not required to explicity cast the class, provided they use the GMATAPI MATLAB class, as
shown below:

>> load_gmat();
No script provided to load.
>> station = [Link]("GroundStation","Station")

station =

Object of type GroundStation named Station

>> [Link]()

ans =

class [Link]

>>

5.6.2 Unwrapped Plugins

Plugin code that is not wrapped in SWIG can be accessed using the API, but only in a more restricted manner. As an
example, at this writing the VF13ad optimizer is available as a GMAT component for users inside of Goddard Space
Flight Center. The associated plugin builds a component with class name “VF13ad” that provides the optimization
functionality. The VF13ad optimizer is derived from an Optimizer base class in the GMAT core code. API users can
access that component as a GmatBase object, or as an Optimizer object, but not as a VF13ad object, as can be seen
here:

>>> import gmatpy as gmat


>>> vf13 = [Link]("VF13ad","VF13")
>>> vf13
<gmatpy.gmat_py.GmatBase; proxy of <Swig Object of type 'GmatBase *' at 0x7f615f50c2a0> >
>>> vf13 = [Link](vf13)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'gmatpy' has no attribute 'VF13ad'
>>> vf13 = [Link](vf13)
>>> vf13
<gmatpy.gmat_py.Optimizer; proxy of <Swig Object of type 'Optimizer *' at 0x7f614d9cff90>
˓→ >

>>> exit()

The underlying object remains a VF13ad component:

>>> [Link]()

VF13ad VF13

Field Type Value


--------------------------------------------------------

ShowProgress Boolean true


(continues on next page)

32 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


ReportStyle List Normal
ReportFile Filename <not set>
MaximumIterations Integer 200
Tolerance Real 1e-05
UseCentralDifferences Boolean false
FeasibilityTolerance Real 0.001

but, from the perspective of an API user, is manipulated as an Optimizer or GmatBase object.

5.7 Measurement Modeling

Note: The Measurement Modeling example shown here is located in Ex_R2020a_RangeMeasurement.m file (or the
Ex_R2020a_RangeMeasurement.py file for Python users).

GMAT’s Measurement Models are driven through the TrackingFileSet class. A TrackingFileSet defines a measurement
as a tracking configuration consisting of a signal path and measurement type. The signal path is defined by the nodes that
a measurement signal traverses to create the measurement. For example, the path may be ground station -> spacecraft
-> ground station for a range measurement.
The user configures the hardware for each node, assigning antennae, transmitters, receivers, and transponders as needed
to the stations and spacecraft used in the measurement. Error models are configured and assigned to each measurement,
media corrections are toggled, and ancillary components configured - like propagators when light time correction is
applied - to complete the configuration the user needs. The system is complex because the processes involved have
many options. This guide, and the sample script, step through the process element by element to build the model.

5.7.1 Spacecraft, Ground Stations, and Propagators

% Construct the PropSetup to control propagation (for light time)


prop = [Link]("PropSetup", "prop");
[Link]().SetField("ErrorControl", "None");
[Link]().SetNumber("MinStep", 0);

% Create objects for generating measurement


simsat = [Link]("Spacecraft", "SimSat");
gds = [Link]("GroundStation", "GDS");

% Configure Spacecraft initial conditions


[Link]("DateFormat", "A1ModJulian");
[Link]("Epoch", "21550");

% Configure GroundStation
[Link]("StateType", "Spherical");
[Link]("HorizonReference", "Ellipsoid");
[Link]("Location1", 0);
[Link]("Location2", 90.0);
[Link]("Location3", 0);

5.7. Measurement Modeling 33


DRAFT GMAT Application Programming Interface, Release R2022a

5.7.2 Hardware Components

% Create communication hardware


% Hardware for ground station
ant1 = [Link]("Antenna", "Antenna1");
tmit = [Link]("Transmitter", "Transmitter1");
[Link]("Frequency", 2067.5);
rec = [Link]("Receiver", "Receiver1");

% Hardware for spacecraft


ant2 = [Link]("Antenna", "Antenna2");
tpond = [Link]("Transponder", "Transponder1");
[Link]("TurnAroundRatio","240/221");

% Set fields
% Use Antenna1 for Transmitter1 and Receiver1
[Link]("PrimaryAntenna","Antenna1");
[Link]("PrimaryAntenna","Antenna1");

% Use Antenna2 for Transponder1


[Link]("PrimaryAntenna","Antenna2");

% Add Antenna2 and Transponder1 to spacecraft


[Link]("AddHardware","{Antenna2, Transponder1}");

% Add Antenna1, Transmitter1, and Receiver1 to station


[Link]("AddHardware","{Antenna1, Transmitter1, Receiver1}");

5.7.3 Error Models

% Define range measurements and error model


tem = [Link]("ErrorModel", "TheErrorModel");
% Specify these measurements are range measurements in km
[Link]("Type","Range");
[Link]("NoiseSigma", 0.050); % Standard deviation of noise
[Link]("Bias",0); % Bias in measurement

% Define doppler range rate measurements and error model


tem2 = [Link]("ErrorModel", "TheErrorModel2");
% Specify these measurements are doppler range rate measurements
[Link]("Type","RangeRate");
[Link]("NoiseSigma", 5e-5); % Standard deviation of noise
[Link]("Bias",0); % Bias in measurement

% Add ErrorModels to the ground station


[Link]("ErrorModels","{TheErrorModel, TheErrorModel2}");

34 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


DRAFT GMAT Application Programming Interface, Release R2022a

5.7.4 The Measurement

% Create a TrackingFileSet to manage the observations


tfs = [Link]("TrackingFileSet", "SimData");
[Link]("FileName","TrkFile_API_GN.gmd"); % Still needed even though it's' not␣
˓→written to

[Link]("UseLightTime", false);
[Link]("UseRelativityCorrection", false);
[Link]("UseETminusTAI", false);

% Define signal paths and measurement type(s)


% 2-way measurements are used here along the path GDS -> SimSat -> GDS
% Add range measurements to TrackingFileSet
[Link]("AddTrackingConfig", "{{GDS,SimSat,GDS}, Range}");
% Add doppler range rate measurements to TrackingFileSet
[Link]("AddTrackingConfig", "{{GDS,SimSat,GDS}, RangeRate}");
[Link](prop); % Tell TrackingFileSet the propagator to use

5.7.5 Exercising the Model

% Initialize the GMAT objects


[Link]()

% Calculate the measurement


tdas = [Link]();
numMeas = [Link]();

tda = [Link](0);
md0 = [Link]();
disp("GMAT Range Measurement Value:")
disp([Link]().get(0))

% Make sure this is correct


satState = [Link]();
gsPos = gds.GetMJ2000Position([Link]()).GetDataVector();
satPos = [Link]();
r = gsPos - satPos(1:3);
rNorm = norm(r);
disp("Numerical Range Measurement Value (no lighttime):")
disp(2*rNorm)

disp("")

xid = [Link]("CartesianX");
[Link](simsat,xid);
for ii = 0:5
deriv(ii+1) = [Link](0,ii);
end
disp("GMAT Range Measurement Derivatives:")
disp(deriv)
(continues on next page)

5.7. Measurement Modeling 35


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)

disp("")

tda = [Link](1);
md1 = [Link]();
disp("GMAT RangeRate Measurement Value:")
disp([Link]().get(0))

5.7.6 Exercises

1. Modify the one day propagation script to report the range measurement at each step where a valid measurement
can be computed.
2. Add a second ground station the Ex_R2020a_RangeMeasurement example and report its measurement data.

36 Chapter 5. Tutorial: Accessing GMAT Propagation and Navigation Features


CHAPTER

SIX

USAGE EXAMPLES

6.1 Time and Coordinate Conversions

One simple application of the GMAT API is the construction of routines that convert from one systm to another. Two
examples of that application are presented here: time system conversion and coordinate system conversion.

6.1.1 Time System Conversion

6.1.2 Coordinate System Conversion

>>> import gmatpy as gmat


>>> moonec = [Link]("CoordinateSystem", "MoonEc", "Luna", "MJ2000Ec")
>>> eartheq = [Link]("CoordinateSystem", "EarthEq", "Earth", "MJ2000Eq")
>>> instate = gmat.Rvector6()
>>> outstate = gmat.Rvector6()
>>> instate[0] = 4000.0
>>> instate[1] = 1000.0
>>> instate[2] = 0.0
>>> instate[3] = 0.1
>>> instate[4] = 0.4
>>> instate[5] = 3.1
>>> print(instate)
4000 1000 0 0.1 0.4 3.1
>>> cconverter = [Link]()
>>> [Link]()
>>> [Link](28718, instate, moonec, outstate, eartheq)
True
>>> print(outstate)
278537.716 272130.548 84187.769 -0.64373770 -0.28543905 3.30709590

37
DRAFT GMAT Application Programming Interface, Release R2022a

6.2 API Examples

Four Python sample use cases were coded using the prototype SWIG API to act as a guide to addressing the changes
that are needed for the production system. These cases ranged from a trivial time system conversion use case to a full
propagation use case. These cases, shown in SwigOldAndNew, were then reworked into the API syntax documented
here. The following section previews the changes coming to the GMAT API by presenting each of these cases as
planned for the API. The examples presented here are in Python. Java examples are presented in API Examples in
Java.

6.2.1 Case 1: Time System Conversion

GMAT supports five time systems: A.1 Atomic Time (A1), International Atomic Time (TAI), Coordinated Universal
Time (UTC), Barycentric Dynamical Time (TDB), and Terrestrial Time (TT). Times in GMAT are stored internally in a
modified Julian format, referenced to January 5, 1941 at noon. Conversions between these time systems are performed
using a time system converter, coded in the TimeSystemConverter singleton class. The time system converter also
provides routines to convert between modified Julian representations and Gregorian representations.
The simplest usage of the time system converter using GMAT’s API consists of two lines of code; lines 5 and 9 shown
here:

Listing 6.1: Python code for time conversions using the GMAT API
1 import gmatpy as gmat
2 [Link]()
3

4 # Get the converter


5 timeConverter = [Link]()
6

7 # Convert an epoch
8 UTCEpoch = 21738.22145
9 TAIEpoch = [Link](UTCEpoch, [Link], gmat.
˓→[Link])

This code shows two features of the API. The first line shows how a Python user loads the GMAT system and initializes
it for use. As part of the initialization process, several components are created in the GMAT module that are single
instance objects, following a singleton design pattern. These singletons are accessed from the API by calling .Instance()
on their names. Line 5 is an example of this usage. The time system converter singleton is accessed using the object
name TimeSystemConverter. In the python code, the object “timeConverter” is connected to the singleton, and then
used to convert a UTC epoch to the TAI time system on line 9.
At this point, the singleton is ready for the user to ineract with it directly. Using the API, the conversion is immediately
available:

>>> [Link](UTCEpoch)
'12 Jul 2000 17:18:53.280'
>>> TAIEpoch = [Link](UTCEpoch,2,1)
>>> [Link](TAIEpoch)
'12 Jul 2000 17:19:25.280'

The interactive call shows the correct time system difference arising from the number of leap seconds needed to convert
from UTC time to TAI time. Users can access the leap second count at a specified epoch directly as well:

>>> [Link](TAIEpoch)
32.0

38 Chapter 6. Usage Examples


DRAFT GMAT Application Programming Interface, Release R2022a

6.2.2 Case 2: Coordinate System Conversion

The time system converter is a stand alone component in GMAT. It does not require external components to perform
conversions. Coordinate systems are more complex. They require connections to other objects in order to compute
data. Table 6.1 shows the settings, required and optional, to define a GMAT coordinate system.

Table 6.1: Coordinate System Settings


Field Type Required? Description
AxisType AxisSystem ob- Yes Defines the orientation of the coordinate axes
ject
Origin SpacePoint object Yes Defines the coordinate system origin
Primary SpacePoint object No Reference body used in coordinate systems that need a pri-
mary body
Secondary SpacePoint object No Reference body used in coordinate systems that need a sec-
ondary body
J2000 Body Internal reference Yes Reference origin in GMAT (always set to Earth)
object
Solar System Solar System ob- Yes The solar system used in the run
ject

Coordinate systems are defined in GMAT as a collection of objects, using a core composite component that collect
together the axis system defining the directions for the coordinate system axes, the bodies used to set the coordinate
system origin and the axis references, and core GMAT settings used to tie the coordinate system into the rest of the
executing GMAT code. Many of the user objects in GMAT have a structure like this: a core object that uses other
objects to form a composite component consistent with the rest of the running GMAT system.
GMAT performs conversions between coordinate systems using a coordinate system converter, coded in the Coor-
dinateConverter class. The CoordinateConverter class maintains state information about the most recent conversion
performed. This state data would cause issues using a state converter in a single instance context, because the state data
from one conversion could be accessed in code requesting the state data from a second conversion. For that reason, the
CoordinateConverter class does not provide a singleton instance, and a separate object must be created for each use.
A basic use case for the coordinate system converter takes a state in Earth-centered Mean-of-J2000 Equatorial coordi-
nates and converts the state into Earth-centered Earth-fixed coordinates. The Python code demonstrating this conversion
using the GMAT API is

Listing 6.2: Python code for coordinate system conversions


1 import gmatpy as gmat
2

3 # Setup the GMAT data structures for the conversion


4 mjd = gmat.A1Mjd(22326.977184)
5 rvIn = gmat.Rvector6(6988.427, 1073.884, 2247.333, 0.019982, 7.226988, -1.554962)
6 rvOut = gmat.Rvector6(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
7 UTCEpoch = 19053.293
8

9 # Create the converter


10 csConverter = [Link]()
11

12 # Create the input and output coordinate systems


13 eci = [Link]("CoordinateSystem", "ECI", "Earth", "MJ2000Eq")
14 ecef = [Link]("CoordinateSystem", "ECEF", "Earth", "BodyFixed")
15 [Link]()
16 [Link](UTCEpoch, rvIn, eci, rvOut, ecef)

6.2. API Examples 39


DRAFT GMAT Application Programming Interface, Release R2022a

The key features shown in this example for the API are:
• Default objects (like the solar system and Earth objects) are set automatically.
• GMAT objects are built using the Construct() command.

6.2.3 Cases 3 and 4: Force Modeling and Propagation

Force models in GMAT – or, more properly, dynamics models – are built by creating an object from the force con-
tainer class, ODEModel, and adding the constituent forces to that container. The ODEModel object is responsible for
accumulating the dynamics into a derivative vector. The dynamics are computed when the GetDerivatives() method is
called on the object. The resulting computation is stored in a class member, accessible using the GetDerivativeArray()
method.
The ODEModel class is one component of a more complicated propagation subsystem in GMAT. That subsystem
is designed with spacecraft propagation in mind. Force modeling requires an associated spacecraft object. During
initialization, an instance of the GMAT helper class, PropagationStateManager (PSM), is used to collect data and
assemble the state vector used to evaluate the dynamics. The PSM determines the size of the state vector by checking
to see if the 6 element Cartesian state, mass flow from spacecraft tanks, and the state transition matrix or state Jacobian
(A-matrix) are needed during the propagation. Once the size of the propagation state vector is determined, the complete
vector is assembled and initialized, and only then can the dynamics be evaluated.
The steps required for this initialization are largely implemented behind the scenes in the GMAT API. Users that want
to manage this setup by hand are referred to the sample code in SwigOldAndNew. The third example in that chapter
shows force model configuration. API users can access GMAT’s dynamics models by configuring the forces piece by
piece and assigning them to an ODEModel container. Here is an example of this process for an Earth point mass force
model:

Listing 6.3: Python code for force modeling using the API
1 import gmatpy as gmat
2

3 sat = [Link]("Spacecraft", "Sat")


4 [Link]("Cr", 1.4)
5 [Link]("SRPArea", 6.5)
6 [Link]("DryMass", 225)
7

8 psm = [Link]()
9 [Link](sat)
10 [Link]()
11

12 dynamics = [Link]("ODEModel", "EPM_SRP")


13 epm = [Link]("EarthPointMass")
14 srp = [Link]("SRP")
15 [Link](epm)
16 [Link](srp)
17 [Link](psm)
18 [Link]([Link]())
19

20 pstate = [7000.0, 0.0, 1000.0, 0.0, 8.0, -0.25]


21

22 [Link]()
23

24 [Link]()
25 [Link]()
(continues on next page)

40 Chapter 6. Usage Examples


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


26

27 [Link](pstate, 0.0)
28 pderiv = [Link]()

The setup for dynamics modeling above extends with little additional configuration to numerical integration. The
integration piece of the configuration adds the lines

Listing 6.4: Propagator setup and use in the API


1 prop = [Link]("PrinceDormand78", "MyIntegrator")
2 [Link](dynamics)
3

4 [Link]()
5

6 for i in range(10):
7 [Link](60.0)

To summarize: The goal of the GMAT API is to make API based configuration as simple as possible, while main-
taining full access to the capabilities of GMAT. Towards that end, the design of the API can be illustrated through a
representative example implementation of a propagation problem. A reference propagation in the GMAT API looks
like this:

Listing 6.5: The Propagation example in Python


1 import gmatpy as gmat
2

3 # Set up the spacecraft


4 sat = [Link]("Spacecraft", "Sat")
5 [Link]("Cr", 1.4)
6 [Link]("SRPArea", 6.5)
7 [Link]("DryMass", 225)
8

9 # Make a force container and set its spacecraft


10 dynamics = [Link]("ODEModel", "EPM_SRP")
11 [Link](sat)
12

13 # Set the forces


14 epm = [Link]("EarthPointMass")
15 srp = [Link]("SRP")
16 [Link](epm)
17 [Link](srp)
18

19 # Propagator configuration
20 prop = [Link]("PrinceDormand78", "MyIntegrator")
21 [Link](dynamics)
22

23 [Link]()
24

25 # Number of steps to take


26 count = 60
27

28 for i in range(count):
29 [Link](60.0)

6.2. API Examples 41


DRAFT GMAT Application Programming Interface, Release R2022a

6.2.4 Cases 5: Working with a GMAT Script

The script examples above show how an API user interacts with GMAT components directly. This final example shows
how a user can work with an existing GMAT script that needs to change settings on one of the scripted objects. For this
example, the GMAT sample mission that demonstrates finite burns is used. The full script is the Ex_FiniteBurn.script
file in the GMAT samples folder. Part of that script includes the definition of a chemical thruster, shown through the
thrust vector portion here:

Listing 6.6: The Thruster in GMAT’s FiniteBurn Sample Mission


1 Create ChemicalThruster engine1;
2 GMAT [Link] = Local;
3 GMAT [Link] = Earth;
4 GMAT [Link] = VNB;
5 GMAT engine1.ThrustDirection1 = 1;
6 GMAT engine1.ThrustDirection2 = 0;
7 GMAT engine1.ThrustDirection3 = 0;
8 ...

An API user might want to change the thrust direction before running the script. The following API code loads the
script, adds an orbit normal component to the thrust direction and then runs the script.

Listing 6.7: Changing an Object and then Running a Script


1 import gmatpy as gmat
2

3 [Link]("../samples/Ex_FiniteBurn.script")
4

5 Thruster = [Link]("engine1")
6 [Link]("ThrustDirection2", 1.0)
7

8 [Link]()

6.3 API Examples in Java

DesignExamples shows Python scripting for four common GMAT API use cases. This section shows those same use
cases in Java.

6.3.1 Time System Conversion

Listing 6.8: Time System Conversion in Java


1 import gmat.*;
2

3 public class TimeConvNew {


4

5 public static void main(String[] args) {


6

7 // Get the converter


8 TimeSystemConverter timeConverter = [Link];
9

(continues on next page)

42 Chapter 6. Usage Examples


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


10 // Convert an epoch
11 double UTCepoch = 21738.22145;
12 double TAIepoch = [Link](UTCepoch, UTC, TAI);
13 }
14 }

6.3.2 Coordinate System Conversion

Listing 6.9: Coordinate Conversion in Java


1 import gmat.*;
2

3 public class CoordConvNew {


4

5 public static void main(String[] args) {


6

7 // Initialize GMAT
8 [Link]("[Link]");
9

10 // Setup the GMAT data structures for the conversion


11 A1Mjd mjd = new A1Mjd(22326.977184);
12 Rvector6 rvIn = new Rvector6(6988.427, 1073.884, 2247.333, 0.019982, 7.226988, -
˓→1.554962);

13 Rvector6 rvOut = new Rvector6(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);


14

15 // Create the converter


16 CoordinateConverter csConverter = new CoordinateConverter();
17

18 // Create the input and output coordinate systems


19 CoordinateSystem eci = [Link]("CoordinateSystem",
20 "ECI", "Earth", "MJ2000Eq");
21 CoordinateSystem ecef = [Link]("CoordinateSystem",
22 "ECEF", "Earth", "BodyFixed");
23

24 [Link](mjd, rvIn, eci, rvOut, ecef);


25 }
26 }

6.3.3 Force Modeling

Listing 6.10: Force Model Creation and Use in Java


1 import gmat.*;
2

3 public class ForceModelNew {


4

5 public static void main(String[] args)


6 {
7 ODEModel dynamics = [Link]("ODEModel","FM");
(continues on next page)

6.3. API Examples in Java 43


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


8

9 PointMassForce epm = [Link]("PointMassForce","EPM");


10 [Link](epm);
11

12 [Link]();
13

14 [Link](state, dt);
15 double[] derivatives = [Link]();
16 }
17 }

6.3.4 Propagation

Listing 6.11: Propagation in Java


1 import gmat.*;
2

3 public class PropExampleNew {


4

5 public static void main(String[] args) {


6

7 // Setup the state for propagation


8 double[] state = {7000.0, 0.0, 1000.0, 0.0, 8.0, -0.25};
9 // Setup a Earth/Sun/Moon force model
10 // note: Use Moderator for the forces and Python memory management won't seg fault
11 ODEModel dynamics = [Link]("ODEModel", "Forces");
12

13 PhysicalModel epm = [Link]("PointMassForce", "EarthPointMass");


14 PhysicalModel spm = [Link]("PointMassForce", "SunPointMass");
15 PhysicalModel mpm = [Link]("PointMassForce", "MoonPointMass");
16 [Link]("BodyName", "Sun");
17 [Link]("BodyName", "Luna");
18

19 [Link](epm);
20 [Link](spm);
21 [Link](mpm);
22

23 // Propagator configuration
24 PrinceDormand78 prop = new PrinceDormand78("Propagator");
25 [Link](dynamics);
26

27 [Link]();
28

29 // Set the propagation state


30 [Link](state);
31

32 for (int i = 0; i < 10; i++) {


33 [Link](60.0);
34 }
35 }
36 }

44 Chapter 6. Usage Examples


DRAFT GMAT Application Programming Interface, Release R2022a

6.4 Example: MONTE-GMAT Interoperability

GMAT is able to work with other programs through the API. Examples have been made between GMAT and MONTE
for OSIRIS-REx and LUCY missions. In these examples, data will be shared between MONTE and GMAT using
interfaces built with MONTE’s native Python framework and GMAT’s API, accessed through Python.
For access to these example scripts contact the GMAT development team.

6.4.1 Ephemeris Sharing

Both GMAT and MONTE have ephemeris reading and writing capabilities. GMAT supports four types of spacecraft
ephemerides: Goddard specific “Code-500”, STK time-position-velocity (.e), CCSDS OEM, and SPICE SPK formats.
MONTE supports SPICE based SPK ephemerides, so that format is used for data interchange between the systems.
Ephemeris sharing between GMAT and MONTE is straightforward: use the system providing the ephemeris to generate
the file, and then import it into the other system.

6.4.2 Maneuver Sharing

Allow maneuver planning for both finite and impulse burns.

6.4.3 Covariance Sharing

Possible to share covariance arrays between MONTE and GMAT. The arrays are in slightly different formats so some
conversion will be necessary between the two programs.

6.4.4 Dynamics Sharing

Dynamics sharing is done through the External Force Model Plugin. (Currently an alpha feature as of R2022a)

6.4. Example: MONTE-GMAT Interoperability 45


DRAFT GMAT Application Programming Interface, Release R2022a

46 Chapter 6. Usage Examples


CHAPTER

SEVEN

API BEST PRACTICES

7.1 General Practices

API users work more closely with the core GMAT code than users that run GMAT through the console for GUI
applications. This feature of the API system adds responsibility for understanding how the system manages objects to
the list of items an API user must consider. The following items capture some of the lessons we have learned from
using the API.

7.1.1 Understand Object Ownership

The API provides a function, Construct(), that builds GMAT objects and retains object ownership in the GMAT module.
Objects created using Construct() remain GMAT’s responsibility for management. Sometimes, API users may need to
create objects directly by calling the object’s constructor, like this:

Listing 7.1: Creating a propagation state manager in Python


psm = [Link]()

or, in MATLAB:

Listing 7.2: Creating a propagation state manager in MATLAB


psm = [Link]()

The objects created this way are managed on the client side of the interface: in either Python or the MATLAB Java
systems. The garbage collectors on the client side will delete the underlying objects when it determines that the object
is no longer needed. This can cause memory management issues for objects that are passed to other GMAT objects.
The API code provides a mechanism to assign ownership to the component that needs it, using the setSwigOwnership()
method in Java code:

Listing 7.3: Managing ownership for a propagation state manager in


MATLAB
% Create the state manager
psm = [Link]();

% Hand the manager to a force model, and assign ownership to the GMAT object
[Link](psm);
[Link](false());

or the thisown setting in Python:

47
DRAFT GMAT Application Programming Interface, Release R2022a

Listing 7.4: Managing ownership for a propagation state manager in


Python
% Create the state manager
psm = [Link]();

% Hand the manager to a force model, and assign ownership to the GMAT object
[Link](psm);
[Link] = False

For either of these mechanisms, a false setting indicates that the client does not own the object.

7.2 Java and MATLAB Best Practices

• Adding the bin folder to your MATLAB path allows you to run the GMAT API from any other working directory
• Use the GMATAPI MATLAB class contained in the bin folder when using the API helper functions Construct(),
Copy(), GetObject(), or GetRuntimeObject(). These functions in the GMATAPI MATLAB class will automati-
cally perform class casting, so the object returned is the more specific type instead of just being of type GmatBase.
The GMATAPI MATLAB class also contains a SetClass() function which will also automatically perform the
class casting on any GmatBase object provided.

7.3 Python Best Practices

• The import function loads GMAT by loading all of the libraries in the gmatpy folder (gmat, station, etc). These
libraries can be imported separately if you do not need all of the API functions in your application.
• The import can rename the interface calls for user convenience. In this document we often load the engine using
import gmatpy as gmat
• The GMAT startup file is loaded the first time a GMAT API function is called. Users that want to
use a startup file that is different from the default file, gmat_startup_file.txt, can load their file using the
Setup(path_and_startup_file_name) function call.
This approach is used for running the API from folders outside of the GMAT bin folder, as described in Running
the API Outside of the GMAT Folders.

48 Chapter 7. API Best Practices


APPENDIX

GMAT API CHEAT SHEET

A.1 Loading the API

Python MATLAB
import gmatpy as gmat load_gmat

A.2 Asking for Help

Python MATLAB
[Link]() [Link]()
[Link](<topic>) [Link](<topic>)
[Link]() [Link]()
Examples
[Link](“ScriptUsage”) [Link](“Objects”)
[Link]() [Link]()

A.3 GMAT Objects

A.3.1 Listing Available Classes

Python MATLAB
[Link]() [Link]()
[Link](<type>) [Link](<type>)
Examples
[Link]() [Link]()
[Link](“PhysicalModel”) [Link](“Propagator”)

49
DRAFT GMAT Application Programming Interface, Release R2022a

A.3.2 Listing Created Objects

Python MATLAB
[Link]() [Link]()
[Link](<type>) [Link](<type>)
Examples
[Link]() [Link]()
[Link](“Spacecraft”) [Link](“Burn”)

A.3.3 Object Creation

Python MATLAB
obj = [Link](<type>,<name>) obj = [Link](<type>, <name>)
Examples
Python MATLAB
burn = [Link](“ImpulsiveBurn”, “Burn”) burn = [Link]( “ImpulsiveBurn”,”Burn”)

A.3.4 Object Field Access

Python MATLAB
value = [Link](<FieldLabel>) value = [Link](<FieldLabel>)
[Link](<FieldLabel>,<value>) [Link](<FieldLabel>,<value>)
[Link](<FieldLabel>) [Link](<FieldLabel>)
Examples
V = [Link](“Element1”) V = [Link](“Element1”)
[Link](“Element1”,1.5) SetField(“Element1”,1.5)
[Link](“Origin”,”Mars”) SetField(“Origin”,”Mars”)
V = [Link](“Element1”) V = [Link](“Element1”)

A.3.5 Object to Object Connections

Python MATLAB
[Link](<RefObject>) [Link](<RefObject>)
Examples
[Link](atmos) [Link](atmos)

50 Appendix A. GMAT API Cheat Sheet


DRAFT GMAT Application Programming Interface, Release R2022a

A.4 GMAT Script Access

A.4.1 Loading a GMAT script

Python MATLAB
[Link](<script>) [Link](<script>)
Examples
[Link]( “../sam- [Link]( “../sam-
ples/Ex_GEOTransfer.script”) ples/Ex_GEOTransfer.script”)

A.4.2 Running a GMAT script

Python MATLAB
[Link]() [Link]()

A.4.3 Saving a GMAT script

A.4.4 Accessing Run Data After a Run

Python MATLAB
[Link](<name>) [Link](<name>)
[Link]() [Link]()
Examples
[Link](“geoSat”) [Link](“geoSat”)

A.4. GMAT Script Access 51


DRAFT GMAT Application Programming Interface, Release R2022a

52 Appendix A. GMAT API Cheat Sheet


APPENDIX

API NOTEBOOK WALKTHROUGHS

API builds include several [Jupyter] notebooks illustrating specific features of the interface. These notebooks can be
found in the api/Jupyter folder of the GMAT build. Users with access to the Jupyter system can run these notebooks
interactively. Static versions of the notebooks are included in this chapter.

B.1 State Management with the GMAT API

The state data in GMAT can be a bit confusing. This notebook introduces the state variables as used for a GMAT
Spacecraft, and provides some pointers on the manipulation of the state data.

B.1.1 Prepare the GMAT Environment

Before the API can be used, it needs to be loaded into the Python system and initialized using a GMAT startup file.
This can be done from the GMAT bin folder by importing the gmatpy module, but using that approach tends to leave
pieces in the bin folder that may annoy other users. Running from an outside folder takes a few steps, which have been
captured in the run_gmat.py file imported here:

from run_gmat import *

B.1.2 Configure a Spacecraft

We’ll need an object that provides the state. Here’s a basic spacecraft, along with a reference to the state data inside of
the spacecraft:

sat = [Link]("Spacecraft","MySat")
iState = [Link]()

The state reference here, iState, operates on the member of the Spacecraft object that GMAT uses when running a sim-
ulation. The “internal state,” referenced by iState here, is the Earth-centered mean-of-J2000 equatorial representation
of position and velocity of the spacecraft MySat. The data is contained in a GmatState object:

iState

<gmatpy.gmat_py.GmatState; proxy of <Swig Object of type 'GmatState *' at 0x7f13ceed97e0>


˓→ >

GmatState objects are used to collect together an epoch and a vector of data. These data can be accessed directly:

53
DRAFT GMAT Application Programming Interface, Release R2022a

print("The state epoch is ", [Link](), ", the state has ", [Link](), "␣
˓→elements, and contains the data ", [Link]())

The state epoch is 21545.000000397937 , the state has 6 elements, and contains the␣
˓→data [-999.999, -999.999, -999.999, -999.999, -999.999, -999.999]

The data shown here is the default GmatState vector data for a spacecraft. The epoch is January 1, 2000 at 12:00:00.000
in TAIModJulian time, or 21545.00000039794 in A.1 ModJulian time. Note that GMAT uses A.1 Mod Julian as its
internal epoch system. The state has 6 elements The position and velocity data are filled in with the dummy entries
-999.999. Working with Cartesian and Keplerian Representations a spacecraft in GMAT has a second collection of
data: the state data for the spacecraft in the coordinate system set on the spacecraft. These data are the spacecraft’s
“display state,” named that way because they are the data displayed to the user. Users interact with the display state
similarly to the way they interact with the scripting language. Data for a Keplerian state can be set using the SetField()
method, as shown here:

[Link]("StateType", "Keplerian")
[Link]("SMA", 7015)
[Link]("ECC", 0.0011)
[Link]("INC", 98.6)
[Link]("RAAN", 75)
[Link]("AOP", 90)
[Link]("TA", 33.333)

At this point it can appear at first glance that the data is set, but it really is not. The spacecraft object cannot interpret the
state data. The data set using SetField needs more information than a spacecraft object can provide by itself. Specifi-
cally, the spacecraft here does not have a connected coordinate system. Cartesian state data set on the spacecraft does
not have connections defining the coordinate origin, nor the structures needed to set the orientation of the axes defining
directions. Additionally, the spacecraft does not have the the gravitational constant needed to interpret Keplerian data.
In this uninitialized state, the spacecraft uses its GmatState buffer to hold the data entries. We can see that the data is
not yet fully populated by posting queries to the spacecraft:

print("The internal state buffer just holds preinitialization data (Keplerian here): ",␣
˓→[Link]())

print("but access to the Keplerian state shows that it is not correct:", sat.
˓→GetKeplerianState())

The internal state buffer just holds preinitialization data (Keplerian here): [7015.0,␣
˓→0.0011, 98.6, 75.0, 90.0, 33.333]

but access to the Keplerian state shows that it is not correct: 0 0 ␣


˓→ 0 0 0 0

The GMAT objects are not yet initialized, so the Keplerian state data is not correct. Once we initialize the system, the
Keplerian state will be correct, and the internal state will be updated to the EarthMJ2000Eq system. The interobject
connections necessary for these settings are made by calling the API Initialize() function:

[Link]()
print("The initialized internal state buffer is EarthMJ2000Eq: ", [Link]())
print("and the Keplerian state is correct: ", [Link]())

The initialized internal state buffer is EarthMJ2000Eq: [-150.99058171804361, -3946.


˓→626071010534, 5789.742898439815, -2.23046049968889, -5.931020059857665, -4.

˓→095581409074377]

(continues on next page)

54 Appendix B. API Notebook Walkthroughs


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


and the Keplerian state is correct: 7015.000000000001 0.00110000000000004 98.
˓→59999999999999 75 90.00000000000402 33.33299999999598

Changes made to the state variables are now applied to the state as expected:

[Link]("SMA", 8000)
print("Internal state: ", [Link]())
print("Cartesianian ", [Link]())
print("Keplerian: ", [Link]())
print()
[Link]("INC", 45)
print("Internal state: ", [Link]())
print("Cartesianian ", [Link]())
print("Keplerian: ", [Link]())
print()
[Link]("TA", 50)
print("Internal state: ", [Link]())
print("Cartesianian ", [Link]())
print("Keplerian: ", [Link]())

Internal state: [-172.19168264352888, -4500.785255607168, 6602.700383110265, -2.


˓→088638988531676, -5.553902317709759, -3.835168124650226]

Cartesianian -172.1916826435289 -4500.785255607168 6602.700383110265 -2.


˓→088638988531676 -5.553902317709759 -3.835168124650226

Keplerian: 8000.000000000007 0.001100000000000707 98.59999999999999 75 ␣


˓→ 90.00000000001161 33.3329999999884

Internal state: [-5697.7414619496, -3020.2186545041395, 4721.90552145557, 1.


˓→1208679033712874, -6.413887097497282, -2.7427113896944304]

Cartesianian -5697.7414619496 -3020.21865450414 4721.90552145557 1.120867903371287 -


˓→6.413887097497282 -2.74271138969443

Keplerian: 8000.000000000011 0.001100000000000964 45.00000000000001 75.


˓→00000000000001 90.00000000001836 33.33299999998167

Internal state: [-5094.78342738948, -4974.9069027511405, 3633.5822378210464, 2.


˓→5169011956354206, -5.379735538828468, -3.8235178821457656]

Cartesianian -5094.78342738948 -4974.90690275114 3633.582237821046 2.


˓→516901195635421 -5.379735538828468 -3.823517882145766

Keplerian: 8000.000000000012 0.001100000000001075 45.00000000000001 75.


˓→00000000000001 90.00000000002314 49.99999999999523

B.1.3 Changing Coordinate Systems

The previous section shows how to access Cartesian and Keplerian representations of the system. In this section we
will work with a couple of different coordinate systems: an Earth fixed coordinate system named “ECF” and accessed
using the Python reference ecf, and a solar ecliptic system named “SolarEcliptic,” referenced as sec. These coordinate
systems are built using the code

ecf = [Link]("CoordinateSystem", "ECF", "Earth", "BodyFixed")


sec = [Link]("CoordinateSystem", "SolarEcliptic", "Sun", "MJ2000Ec")

B.1. State Management with the GMAT API 55


DRAFT GMAT Application Programming Interface, Release R2022a

In this section, the spacecraft sat defined previously will be used with the Earth fixed coordinate system, and a copy of
that spacecraft will be used with the solar ecliptic system. GMAT’s objects support a method, Copy(), that copies an
object into another object of the same type. Rather than set up a new spacecraft from scratch, we’ll use that framework
to get started by creating a new spacecraft and then setting the coordinate systems so that the original spacecraft uses
the ECI coordinate system and the new spacecraft uses the solar ecliptic system.

solsat = [Link]("Spacecraft","SolarSat")
[Link](sat)

# Now set coordinate systems


[Link]("CoordinateSystem","ECF")
[Link]("CoordinateSystem","SolarEcliptic")

We’ve reset the coordinate system names on the spacecraft at this point, but have yet to reset the associated objects
because the Initialize() function that connects objects together has not been called since making the reassignment. The
data reflects this state of the system:

# Show the data after setting the new coordinate systems, before initialization
print("The spacecraft ", [Link](), " initialization state is ", [Link]())
print("The internal state buffer: ", [Link]())
print("The ECF Cartesian State: ", [Link]())
print("The ECF Keplerian State: ", [Link]())
print()
print("The spacecraft ", [Link](), " initialization state is ", sat.
˓→IsInitialized())

print("The internal state buffer (SolarSat): ", [Link]().GetState())


print("The SolarEcliptic Cartesian State: ", [Link]())
print("The SolarEcliptic Keplerian State: ", [Link]())

The spacecraft MySat initialization state is True


The internal state buffer: [-5094.78342738948, -4974.9069027511405, 3633.5822378210464,
˓→ 2.5169011956354206, -5.379735538828468, -3.8235178821457656]

The ECF Cartesian State: -5094.78342738948 -4974.90690275114 3633.582237821046 2.


˓→516901195635421 -5.379735538828468 -3.823517882145766

The ECF Keplerian State: 8000.000000000012 0.001100000000001075 45.00000000000001 75.


˓→00000000000001 90.00000000002314 49.99999999999523

The spacecraft SolarSat initialization state is True


The internal state buffer (SolarSat): [-5094.78342738948, -4974.9069027511405, 3633.
˓→5822378210464, 2.5169011956354206, -5.379735538828468, -3.8235178821457656]

The SolarEcliptic Cartesian State: -5094.78342738948 -4974.90690275114 3633.


˓→582237821046 2.516901195635421 -5.379735538828468 -3.823517882145766

The SolarEcliptic Keplerian State: 8000.000000000012 0.001100000000001075 45.


˓→00000000000001 75.00000000000001 90.00000000002314 49.99999999999523

Note that the initialization state reported here is a bug: resetting object references should toggle the initialization flag,
but did not.
Once we initialize the system, replacing the coordinate system references with the correct objects, the data is once again
correct:

# Connect the GMAT objects together


[Link]()

(continues on next page)

56 Appendix B. API Notebook Walkthroughs


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


# And show the data in the new coordinate systems
print("The internal state buffer: ", [Link]())
print("The ECF Cartesian State: ", [Link]())
print("The ECF Keplerian State: ", [Link]())
print()
print("The internal state buffer (SolarSat): ", [Link]().GetState())
print("The SolarEcliptic Cartesian State: ", [Link]())
print("The SolarEcliptic Keplerian State: ", [Link]())

The internal state buffer: [-5094.78342738948, -4974.9069027511405, 3633.5822378210464,


˓→ 2.5169011956354206, -5.379735538828468, -3.8235178821457656]

The ECF Cartesian State: 3980.769626359613 -5904.072200723337 3633.84663580491 5.


˓→31337371013498 1.221190102125526 -3.82343374194999

The ECF Keplerian State: 7197.708272712511 0.1106817774544226 47.10837940070086 152.


˓→2889386356222 322.0637563061007 179.5887814511714

The internal state buffer (SolarSat): [-5094.78342738948, -4974.9069027511405, 3633.


˓→5822378210464, 2.5169011956354206, -5.379735538828468, -3.8235178821457656]

The SolarEcliptic Cartesian State: -26505087.9080278 144694001.6268158 4700.


˓→442019894719 -27.27732399951776 -11.92620879192113 -1.367891168160935

The SolarEcliptic Keplerian State: 144849901.1130946 0.2292154440704447 2.


˓→702016602265948 280.4191667873194 286.9680459339144 252.9931176051724

B.2 Propagation with the GMAT API

This document walks you through the configuration and use of the GMAT API for propagation.

B.2.1 Prepare the GMAT Environment

Before the API can be used, it needs to be loaded into the Python system and initialized using a GMAT startup file.
This can be done from the GMAT bin folder by importing the gmatpy module, but using that approach tends to leave
pieces in the bin folder that may annoy other users. Running from an outside folder takes a few steps, which have been
captured in the run_gmat.py file imported here:

from run_gmat import *

B.2.2 Configure a Spacecraft

We’ll need an object to propagate. Here’s a basic one:

sat = [Link]("Spacecraft","LeoSat")

[Link]("DateFormat", "UTCGregorian")
[Link]("Epoch", "27 Sep 2019 15:05:00.000")
[Link]("CoordinateSystem", "EarthMJ2000Eq")
[Link]("DisplayStateType", "Keplerian")
[Link]("SMA", 7005)
[Link]("ECC", 0.008)
(continues on next page)

B.2. Propagation with the GMAT API 57


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


[Link]("INC", 28.5)
[Link]("RAAN", 75)
[Link]("AOP", 90)
[Link]("TA", 45)

[Link]("DryMass", 50)
[Link]("Cd", 2.2)
[Link]("Cr", 1.8)
[Link]("DragArea", 1.5)
[Link]("SRPArea", 1.2)

B.2.3 Configure the Forces

Next we’ll set up a force model. For this example, we’ll use an Earth 8x8 potential model, with Sun and Moon point
masses and Jacchia-Roberts drag. In GMAT, forces are collected in the ODEModel class. That class is scripted as
a “ForceModel” in the script language. The API accepts either. The force model is built and its (empty) contents
displayed using

fm = [Link]("ForceModel", "TheForces")
[Link]()

ForceModel TheForces

Field Type Value


--------------------------------------------------------

CentralBody Object Earth


PrimaryBodies ObjectArray {}
PolyhedralBodies ObjectArray {}
PointMasses ObjectArray {}
Drag Object None
SRP OnOff Off
RelativisticCorrection OnOff Off
ErrorControl List RSSStep
UserDefined ObjectArray {}

''

B.2.4 Add the Potential Field

In this example, the spacecraft is in Earth orbit. The largest force for the model is the Earth gravity field. We’ll set it to
an 8x8 field and add it to the force model using the code

# An 8x8 JGM-3 Gravity Model


earthgrav = [Link]("GravityField")
[Link]("BodyName","Earth")
[Link]("Degree",8)
[Link]("Order",8)
[Link]("PotentialFile","[Link]")
(continues on next page)

58 Appendix B. API Notebook Walkthroughs


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)

# Add forces into the ODEModel container


[Link](earthgrav)

B.2.5 Add the other forces

Next we’ll build and add the Sun, Moon, and Drag forces, and then show the completed force model.
# The Point Masses
moongrav = [Link]("PointMassForce")
[Link]("BodyName","Luna")
sungrav = [Link]("PointMassForce")
[Link]("BodyName","Sun")

# Drag using Jacchia-Roberts


jrdrag = [Link]("DragForce")
[Link]("AtmosphereModel","JacchiaRoberts")

# Build and set the atmosphere for the model


atmos = [Link]("JacchiaRoberts")
[Link](atmos)

# Add all of the forces into the ODEModel container


[Link](moongrav)
[Link](sungrav)
[Link](jrdrag)

[Link]()

ForceModel TheForces

Field Type Value


--------------------------------------------------------

CentralBody Object Earth


PrimaryBodies ObjectArray {Earth}
PolyhedralBodies ObjectArray {}
PointMasses ObjectArray {Luna, Sun}
Drag Object JacchiaRoberts
SRP OnOff Off
RelativisticCorrection OnOff Off
ErrorControl List RSSStep
UserDefined ObjectArray {}

In GMAT, the force model scripting shows the settings for each force. In the API, you can examine the settings for the
individual forces:
[Link]()

GravityField

(continues on next page)

B.2. Propagation with the GMAT API 59


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


Field Type Value
--------------------------------------------------------

Degree Integer 8
Order Integer 8
StmLimit Integer 100
PotentialFile Filename [Link]
TideFile Filename
TideModel String None

or, with a little work, the scripting for the complete force model:

print([Link](0))

Create ForceModel TheForces;


GMAT [Link] = Earth;
GMAT [Link] = {Earth};
GMAT [Link] = {Luna, Sun};
GMAT [Link] = Off;
GMAT [Link] = Off;
GMAT [Link] = RSSStep;
GMAT [Link] = 8;
GMAT [Link] = 8;
GMAT [Link] = 100;
GMAT [Link] = '[Link]';
GMAT [Link] = 'None';
GMAT [Link] = JacchiaRoberts;
GMAT [Link] = 'ConstantFluxAndGeoMag';
GMAT [Link] = 'ConstantFluxAndGeoMag';
GMAT [Link] = '[Link]';
GMAT [Link] = '[Link]';
GMAT [Link].F107 = 150;
GMAT [Link].F107A = 150;
GMAT [Link] = 3;
GMAT [Link] = 'Nominal';
GMAT [Link] = 'NominalCycle';
GMAT [Link] = 'Spherical';

B.2.6 Configure the Integrator

Finally, in order to propagate, we need an integrator. For this example, we’ll use a Prince-Dormand 7(8) Runge-Kutta
integrator. The propagator is set using the code
# Build the propagation container that connect the integrator, force model, and␣
˓→spacecraft together

pdprop = [Link]("Propagator","PDProp")

# Create and assign a numerical integrator for use in the propagation


gator = [Link]("PrinceDormand78", "Gator")
[Link](gator)

(continues on next page)

60 Appendix B. API Notebook Walkthroughs


DRAFT GMAT Application Programming Interface, Release R2022a

(continued from previous page)


# Set some of the fields for the integration
[Link]("InitialStepSize", 60.0)
[Link]("Accuracy", 1.0e-12)
[Link]("MinStep", 0.0)

B.2.7 Connect the Objects Together

# Assign the force model imported from BasicFM


[Link](fm)

# Setup the spacecraft that is propagated


psm = [Link]()
[Link](sat)

True

B.2.8 Initialize the System and Propagate a Step

Finally, the system can be initialized and fired to see a single propagation step. Some of the code displayed here will
be folded into the API’s Initialize() function. For now, the steps needed to initialize the system for a propagation step
are:

# Perform top level initialization


[Link]()

# Refresh the object references from the propagator clones


fm = [Link]()
gator = [Link]()

[Link]()

# Pass the state manager to the dynamics model


[Link](psm)
[Link]([Link]())

# Assemble all of the force model objects together


[Link]()

# Finish the force model setup


[Link]()
[Link]()

# Initialize the Propagator components


[Link]()
[Link]()

True

B.2. Propagation with the GMAT API 61


DRAFT GMAT Application Programming Interface, Release R2022a

Note: Alternatively, the above code can be replaced with a call to the PrepareInternals() function on the propagator.
This also removes the need to manually configure the PropagationStateManager. The condensed code can be seen
below:

# Perform top level initialization


[Link]()

# Setup the spacecraft that is propagated


[Link](sat)
[Link]()

# Refresh the object references from the propagator clones


fm = [Link]()
gator = [Link]()

and we can then propagate, and start accumulating the data

# Take a 60 second step, showing the state before and after, and start buffering
# Buffers for the data
time = []
pos = []
vel = []

gatorstate = [Link]()
t = 0.0
r = []
v = []
for j in range(3):
[Link](gatorstate[j])
[Link](gatorstate[j+3])
[Link](t)
[Link](r)
[Link](v)

print("Starting state: ", t, r, v)

# Take a step and buffer it


[Link](60.0)
gatorstate = [Link]()
t = t + 60.0
r = []
v = []
for j in range(3):
[Link](gatorstate[j])
[Link](gatorstate[j+3])
[Link](t)
[Link](r)
[Link](v)

print("Propped state: ", t, r, v)

62 Appendix B. API Notebook Walkthroughs


DRAFT GMAT Application Programming Interface, Release R2022a

Starting state: 0.0 [-5455.495852919224, -3637.0485868833093, 2350.0571814448517] [3.


˓→1318014092807545, -6.423940627548709, -2.545227573417657]

Propped state: 60.0 [-5256.1378692623475, -4014.4902800853415, 2192.4488937848546] [3.


˓→51104729424038, -6.153042432990329, -2.7064897093764597]

Finally, we can run for a few orbits and show the results

for i in range(360):
# Take a step and buffer it
[Link](60.0)
gatorstate = [Link]()
t = t + 60.0
r = []
v = []
for j in range(3):
[Link](gatorstate[j])
[Link](gatorstate[j+3])
[Link](t)
[Link](r)
[Link](v)

import [Link] as plt


[Link]['[Link]'] = (15, 5)
[Link](time, pos)
[Link]()
[Link](time, vel)
[Link]()

B.2. Propagation with the GMAT API 63


DRAFT GMAT Application Programming Interface, Release R2022a

64 Appendix B. API Notebook Walkthroughs


APPENDIX

BIBLIOGRAPHY

[GmatWiki] [Link]
The GMAT Wiki at [Link] is the main public facing interface for GMAT development and release
activities.
[Architecture] The GMAT Development Team, “General Mission Analysis Tool (GMAT) Architectural
Specification,” NASA GSFC.
The GMAT Architectural Specification provides a good overview for the GMAT system. The document
is included with each GMAT release. The document overview can be viewed at [Link]
8090/display/GW/Architectural+Specification.
[CInterface] D. Conway, “GMAT API Tradeoff Study,” Thinking Systems, Inc., February 2012.
The GMAT CInterface plugin was an artifact of the original GMAT API study described here. One rec-
ommendation arising from this study was a set of automatic API generation tools, including SWIG.
[SWIGExperiment] D. Conway, “GMAT API Consultation Support,” Thinking Systems, Inc., December
2016.
Goddard personnel, assisted by contractors at Thinking Systems, Inc. and Emergent Space Technologies,
performed an in-house study of the use of SWIG as a tool for a production GMAT API. This document
describes that study.
[SWIG] Simplified Wrapper and Interface Generator (SWIG)
SWIG is an open source software development tool that connects programs written in C and C++ with
other high-level programming languages. The GMAT API is generated using the SWIG tool.
[Doxygen] [Link]
The detailed design information for GMAT is generated using the open source Doxygen documentation
generation tool.
[Jupyter] [Link]
Jupyter is an interactive tool that provides writers with the ability to intersperse documentation and Python
code. The resulting notebook files can be run interactively, enriching the user’s learning experience through
editable Python code that can be executed inside the notebook.

65
DRAFT GMAT Application Programming Interface, Release R2022a

66 Appendix C. Bibliography
APPENDIX

CHANGE HISTORY

Rev 0 December 05, 2018 Original draft specification.


Rev 1 March 29, 2019 Draft specification incorporating review comments.
Rev 2 October 11, 2019 Updates for the first beta release.
Rev 3 January 15, 2020 Updates for GMAT R2020a.
Rev 4 September 27, 2022 Updates for GMAT R2022a.

67

You might also like