Part 13:
Integrating STK with Python
STK Pro, STK Premium (Air), STK Premium (Space), or STK Enterprise
You can obtain the necessary licenses for this training by contacting AGI Support at support@agi.com or 1-800-924-7244.
This lesson requires STK 12.2 or newer to complete it in its entirety. It includes new features introduced in STK 12.2. If you have STK 12.1 or earlier, you can find that lesson here.
Capabilities covered
This lesson covers the following STK Capabilities:
- STK Pro
- STK Integration
Problem statement
You will be analyzing the behavior of a satellite when it has contact with a ground site. The task will be repetitive and you consider methods of automating the process and extracting the data. Knowing that you can integrate STK with other tools you decide to explore the process.
Solution
Analysis in STK can be integrated and automated with code. You decide to run the process with Python. Using the resources on the STK Help and Github, you explore how to model a mission with a script.
From this tutorial you will learn how to:
- Connect STK to a programming interface
- Build a mission through a script
- Extract data from STK
A recorded PowerPoint Presentation , Jupyter Notebook, and Python script accompany this lesson. It is recommended that you follow the presentation while performing the tasks. If you don't want to use the shared files, you can type the commands right in the Python Command Window.
Familiarize yourself with the STK Programming Interface Help
Before attempting to code anything, take a moment to familiarize yourself with the STK Programming Interface Help system. After going through the Help, you will dive into Integrating STK and Python. This example is done with the built-in user interface, which was introduced in STK 12.2. However, you can view the archived lesson using Jupyter Notebook and Python here.
Historically, integrating STK Desktop and STK Engine was achieved with either win32com or through the comtypes Python module. In STK 12.1, a new STK Python API was developed to provide the following:
- Cross-platform support: Code written using the new API interacting with STK Engine can be used on Windows and on Linux without modifications (assuming the usual cross platform Python guidelines are followed).
- Usability improvements:
- The new API provides definitions for all enumerations. With win32com, enumerations had to be defined manually based on the corresponding numerical value.
- Better IDE support through type hints (based on the typing module).
For STK 12.2 and newer, you can use Jupyter notebooks directly inside STK with the Python User Interface. This enables you to use Python scripting language to:
- Automate STK from Windows or Linux platforms
- Streamline your workflow
- Provide a more interactive development experience
The Python API has also been expanded to support STK events and to expose the globe and map controls, enablng you to develop custom applications in Python.
Resources for Integrating STK are available both online and locally if installed with the STK installation. You can access these in several different ways:
- Go directly to the online STK Programming Help page: help.agi.com/stkdevkit/.
- Launch STK Programming Help from within STK. Click Help on the menu bar and select Programing Interface Help.
- Launch the STK Help via the windows Start Menu: Select Start → STK 12 → STK 12 - Programming Interface Help.
You will find a wealth of information within the STK Programing Interface Help system, including integration tutorials, code snippets, decision trees, and library references.
The help system tree looks like this:
Within the Using Core Libraries directory, you will find additional information on using the STK Object Model and Connect.
The STK Object Model section listed under Using Core Libraries contains useful code snippets in various programming languages. It also contains information on the various COM libraries that make up the STK Object Model. This information includes useful diagrams that help visualize how the STK Object Model is structured. For example, this small excerpt from the STK Object diagrams which outlines a portion of the basic STK Object Model representation of a Place object:
In the using Core Libraries - Connect section, you will find useful Getting Started information outlining the basics of Connect command and response formats. The section also contains useful code snippets that demonstrate the syntax for various Connect commands. Here is an example of a code snippet showing how to create a new missile object:
This snippet utilizes STK Object Model to send the Connect command. The raw Connect command is the string being passed to root.ExecuteCommand().
You can and should explore more of the help sections, but one last important section to point out is the Library Reference section.
Under Library Reference, you will find documentation on the STK Object Model, Connect Command Library, Data Providers, and more. The STK Object Model documentation is organized by the individual libraries, so there is a section for STK Objects, a section for STK Util, and so on with each section encapsulating certain aspects of functionality. Within each section items are broken down further by their type. When needed, this can make it quicker to find the exact item you are looking for.
The Connect Command Library, listed under Library Reference, houses the documentation for all of the Connect commands. In this case commands are listed in several different formats, including alphabetically, by object, and by capability to assist in locating the exact reference needed.
Try it
To find help for the AgStkObjectRoot class:
- Click Library Reference → STK Object Model → STK Objects.
- Scroll down the alphabetical list until you find the entry entitled "AgStkObjectRoot".
- Click AgStkObjectRoot to display detailed information and important links, including a link to the IAgStkObjectRoot interface.
- From there, you can access a listing of all the members (methods and properties) of the interface associated with the AgStkObjectRoot object. Similarly, you can find help for any other object or interface, as well as any method, property, or enumeration.
A quick way to find help on a given type is to use the Search tab of the Help system. For example, suppose you are interested in the AgECoordinateSystem enum. If you enter "AgECoordinateSystem" in the search field and click List Topics, a list of pages containing that term appears. The entry for the AgECoordinateSystem reference page will appear at the top. Select that entry to display a page defining the enum and listing its members.
A final note on the STK Programming Interface Help system
In addition to help on programming issues, the help provides information about the real-world context in which the application is to be used. For example, the STK Object Model help page for the SpinAxisConeAngle property tells you that it is writable, is of the Variant data type, and belongs to the IAgSnPtSpinning interface. In addition, it tells you that the property represents "the cone angle used in defining the spin axis; i.e., the angle between the spin axis and the sensor boresight." This latter information is useful in deciding whether or not and how to use the property in your application, but since the help is mainly intended to provide guidance on programming issues it is best to also reference the STK Help System, where there is generally more information. For example, the help page for “Spinning Sensor Pointing” not only gives more detailed context information but also includes a drawing of spin axis geometry that illustrates the spin axis cone angle quite clearly.
Integrating STK and Python
The STK Programming Interface help has many object-specific Python code snippets to assist you. Visit our FAQ site to learn more about Python-STK COM Integration . Additional Python Resources are on Github .
Before you start: Integrating STK with Python
Watch the following video. Then follow the steps below, which incorporate the systems and missions you work on (sample inputs provided).This lesson was written with Python 3.7.7, but you can use other versions of Python. See
Creating an STK Scenario
There are several ways to open Jupyter Notebooks. You will try opening it inside STK. You may download the script linked above or follow below. First, create an STK scenario.
- Create a new STK scenario.
- Click .
- Enter the following in the New Scenario Wizard:
Option Value Name STK_Python_Training Start Time Default Start Time Stop Time Default Stop Time - Click .
Integrating STK and Python
Launch the Python Scripting Interface.
- Click View on the STK menu bar.
- Select Toolbars.
- Select Integrated Jupyter Notebooks for Python.
- Examine the three buttons. The first button from the left opens the interface, the second opens the Github, and the final one opens the Programming Help.
- Click Launch Python Scripting Interface (
).
- If not specified, click the ellipsis button (
) in the Python Interpreter Path field to set the Python install path.
- If not specified, click the ellipsis button (
) in the Path to script or folder field to set the folder location where you would like to save your script. By default it will be saved to your C:<user path>\Documents\STK 12\PythonScripts.
- Clear the Create new script on open check box. In this lesson, you will use a notebook file available in your install or from download.
- Click Launch.
- Either Download or browse to the installed Python_Jupyter_STK_Training.ipynb file located at STK Install Folder\Data\Resources\stktraining\scripts.
- Save the file to the path specified in the Path to script or folder option above.
You can create a new script on open by selecting the Create new script on open check box.
Setting up your workspace
You will be using Jupyter notebooks. You will add cells and enter our script into sections and run them. You may also use the completed script by adding or writing in any missing lines of code. If you are building your script from scratch, use the following commands and paste them into the notebook cell:
- Set up your workspace.
-
Connect to the STK instance. Use the appropriate scrip below depending on how you connect to STK.
Use STK_PID environment variable when using the Jupiter Notebook plugin and have multiple instances of STK running.
STK_PID = os.getenv('STK_PID')stk = STKDesktop.AttachToApplication(pid=int(STK_PID))Use STKDesktop.AttachToApplication() without reference to STK_PID when running a single instance of STK. It does not matter if you are in a notebook or not.
stk = STKDesktop.AttachToApplication() - Grab a handle on the STK application root.
-
Check that the root object has been built correctly and check the type(). The output will be agi.stk.stkobjects.AgStkObjectRoot.
type(root)
- Once the above lines are entered into the cell, click . This will create a new STK window.
The new STK Python API is only available with STK 12.1 or newer. If not installed, use pip to install it. Example code: pip install "C:\Program Files\AGI\STK 12\bin\AgPythonAPI\agi.stk<..ver..>-py3-none-any.whl" . If using an older version of STK, then use win32com or comtypes.
Recall that the AgStkObjectRoot object is at the apex of the STK Object Model. The associated IAgStkObjectRoot interface will provide the methods and properties to load or create new scenarios and access the Object Model Unit preferences. Through the stk command you have a pointer to the IAgUiApplication interface; however, the STK Python API provides a direct handle to the IAgStkObjectRoot via the Root property in STKDesktop or the NewObjectRoot() method in STKEngine.
Connect and design a new scenario
Now that you have launched STK via the Python interface, see if you can create a new scenario and set the time period via Python. Create a new scenario and analysis period and reset the animation time.
- Click to add a new cell.
- Copy the following code to create a new scenario.
- Copy the following code to set the analysis period.
- Copy the following code to reset the animation time.
- Click .
# 1. Define a scenario object.
scenario = root.CurrentScenario
# 2. Set the analytical time period.
scenario.SetTimePeriod('Today','+24hr')
# 3. Reset the animation time to the newly established start time.
root.Rewind();
Insert and Configure Objects
With a new scenario created, it's time to populate the scenario with objects. Use the STK Python API and the STK Connect commands, via the ExecuteCommand method, to create a facility and a LEO satellite.
- Click to add a new cell.
- Copy the following code to add a target object to the scenario. Casting the object returned from the New() method allows for better intellisense in your IDE but is optional; the object returned will be AgTarget at runtime even without the case.
- Copy the following code to move the target object to the desired location.
- Copy the following code to add a satellite object to the scenario.
- Copy the following code to propagate the satellite object for the length of the scenario.
- Click .
# 1. Add a target object to the scenario.
#2. Move the Target object to a desired location.
#3. Add a Satellite object to the scenario.
satellite = AgSatellite(root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite,"LeoSat"))
#Examine the below connect command before running. In it we will be using the Set State Classical connect command. Rather than manually setting the times we will use the define scenario times. Print them to confirm.
#4. Propagate the Satellite object's orbit.
root.ExecuteCommand('SetState */Satellite/LeoSat Classical TwoBody "' + str(scenario.StartTime) + '" "' + str(scenario.StopTime) + '" 60 ICRF "' + str(scenario.StartTime) + '" 7200000.0 0.0 90 0.0 0.0 0.0');
Compute Access Between Objects
You now have a scenario with a Target object and a Satellite object. Determine when the Satellite object can access the Target object.
- Go to the STK Programming Interface Help files.
- Locate the code needed to compute an access between two STK Objects using the IAgStkObject interface. The access is between the Satellite object and the Target object.
- If you cannot locate the code, expand the following
- In the JupyterNotebook, click to add a new cell.
- Enter the above text to the new cell and click .
Retrieve Access Data From STK
Now that the scenario is fully built, the final task is to extract data and perform a basic analysis. You have just computed access between the two objects, so you can use the STK data providers to pull data out of the scenario.
- Click to add a new cell.
- Copy the following code to add calls to the access data provider. This will retrieve and view the access data in Python.
- Click .
accessDP = access.DataProviders.Item('Access Data')
print(accessStartTimes,accessStopTimes)
You can also pull the Start & Stop times in Python using the following lines of code.
accessIntervals = access.ComputedAccessIntervalTimes
dataProviderElements = ['Start Time', 'Stop Time']
for i in range(0,accessIntervals.Count):
times = accessIntervals.GetInterval(i)
print(times)
More information is available in STK Object Model Tutorial.
Retrieve the Satellite Altitude Data From STK
- Click to add a new cell.
- Copy the following code to add a call to the satellite's LLA state data provider. Retrieve and view the altitude of the satellite during an access interval. In the following lines, note how the data providers must follow the data provider folder, subfolder, and selection.
- Click .
satelliteDP = satellite.DataProviders.Item('LLA State')
print(satelliteAltitude)
Save your scenario
You have just completed the Integrating STK with Python tutorial using Jupyter Notebooks. Don't forget to save your work. With your scenario safely saved, you can close out of STK. You can expand and automate workflows like these for quickly building and analyzing missions.
Don't forget to save your work!