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.

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, AGI developed an STK Python API to provide the following:

  • Cross-platform support: For both Windows and Linux, you can employ code written using the Python API interacting with STK Engine without modifications, assuming that you follow the usual cross-platform Python guidelines.
  • Usability improvements:
    • The new API provides definitions for all enumerations. With win32com, enumerations had to be defined manually based on the corresponding numerical value.
    • You get 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 outlines a portion of the basic STK Object Model representation of a Place object:

In the Connect section of Using Core Libraries, 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 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:

  1. Click Library Reference → STK Object Model → STK Objects.
  2. Scroll down the alphabetical list until you find the entry entitled "AgStkObjectRoot".
  3. Click AgStkObjectRoot to reveal detailed information and important links, including a link to the IAgStkObjectRoot interface.
  4. 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 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.

The STK Programming help has many object-specific Python code snippets to assist you. 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 this FAQ article for details on compatible versions. Before starting this lesson, verify that you have a working Python environment. This example uses the built-in Jupyter Notebooks. You may also use your preferred Python environment (i.e., WinPython, Spyder, Anaconda, or others).

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.

  1. Create a new STK scenario.
  2. Click Create a Scenario.
  3. Enter the following in the New Scenario Wizard:
    OptionValue
    NameSTK_Python_Training
    Start TimeDefault Start Time
    Stop TimeDefault Stop Time
  4. Click OK .

Integrating STK and Python

Launch the Python Scripting Interface.

  1. Click View on the STK menu bar.
  2. Select Toolbars.
  3. Select Integrated Jupyter Notebooks for Python.
  4. 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.
  5. Click Launch Python Scripting Interface ().
  6. If not specified, click the ellipsis button () in the Python Interpreter Path field to set the Python install path.
  7. 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.
  8. 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.
  9. You can create a new script on open by selecting the Create new script on open check box.

  10. Click Launch.
  11. 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.

Setting up your workspace

You will be using Jupyter notebooks. You will add cells and enter your 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:

  1. Set up your workspace.
  2. 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.

    # STK library imports
    from agi.stk12.stkdesktop import STKDesktop
    from agi.stk12.stkobjects import *
    from agi.stk12.stkutil import *
    from agi.stk12.vgt import *
    # if using astrogator uncomment the below
    # from agi.stk12.stkobjects.astrogator
    # if using aviator uncomment the below
    # from agi.stk12.stkobjects.aviator
    # Python helper library imports
    import os
  3. 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()
  4. Grab a handle on the STK application root.
  5. 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.

    root = stk.Root
  6. Check that the root object has been built correctly and check the type(). The output will be agi.stk.stkobjects.AgStkObjectRoot.
    type(root)
  7. Once the above lines are entered into the cell, click Run. This will create a new STK window.

Connecting and designing 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.

  1. Click insert cell below to add a new cell.
  2. Copy the following code to create a new scenario.
  3.  
    # 1. Define a scenario object.
    scenario = root.CurrentScenario
  4. Copy the following code to set the analysis period.
  5. # 2. Set the analytical time period.
     
    scenario.SetTimePeriod('Today','+24hr')
  6. Copy the following code to reset the animation time.
  7. # 3. Reset the animation time to the newly established start time.
    root.Rewind();
  8. Click Run.

Inserting and Configuring 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.

  1. Click insert cell below to add a new cell.
  2. 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.
  3. # 1. Add a target object to the scenario.
    target = AgTarget(scenario.Children.New(AgESTKObjectType.eTarget,"GroundTarget"))
  4. Copy the following code to move the target object to the desired location.
  5. #2. Move the Target object to a desired location.
    target.Position.AssignGeodetic(50,-100,0)
  6. Copy the following code to add a satellite object to the scenario.
  7. #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.
    print(scenario.StartTime)
    print(scenario.StopTime)
  8. Copy the following code to propagate the satellite object for the length of the scenario.
  9. #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');
  10. Click Run.

Computing 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.

  1. Go to the STK Programming Interface Help files.
  2. 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.
  3. If you cannot locate the code, expand the followingClosed
    1. The location of the required code snippets is STK Programming Interface > Using Core Libraries > STK Object Model > Python Code Snippets. Locate STK Objects > Access. The required snippet is Compute an access between two STK Objects (using IAgStkObject interface).
    2. access = satellite.GetAccessToObject(target)
      access.ComputeAccess();
  4. In the JupyterNotebook, click insert cell below to add a new cell.
  5. Enter the above text to the new cell and click Run.

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.

  1. Click insert cell below to add a new cell.
  2. Copy the following code to add calls to the access data provider. This will retrieve and view the access data in Python.
  3. accessDP = access.DataProviders.Item('Access Data')
    results = accessDP.Exec(scenario.StartTime, scenario.StopTime)
    accessStartTimes = results.DataSets.GetDataSetByName('Start Time').GetValues()
    accessStopTimes = results.DataSets.GetDataSetByName('Stop Time').GetValues()
    print(accessStartTimes,accessStopTimes)
  4. Click Run.

You can also pull the Start and 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

  1. Click insert cell below to add a new cell.
  2. 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.
  3. satelliteDP = satellite.DataProviders.Item('LLA State')
    satelliteDP2 = satelliteDP.Group.Item('Fixed')
    rptElements = ['Time', 'Lat', 'Lon', 'Alt']
    satelliteDPTimeVar = satelliteDP2.ExecElements(accessStartTimes,accessStopTimes, 60, rptElements)
    satelliteAltitude = satelliteDPTimeVar.DataSets.GetDataSetByName('Alt').GetValues()
    print(satelliteAltitude)
  4. Click Run.

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.