### Output of time setup Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Problem_Specific/DeckAccess/DeckAccess.ipynb Example output showing the current time and scenario start/stop times. ```text Output: Now = 16 Jul 2021 17:16:36 Scenario Start = 16 Jul 2021 00:00:00.000 Scenario Stop = 16 Jul 2021 23:59:59.999 ``` -------------------------------- ### Setup and find EOIR sensors Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Scenario_Analysis/EOIR_Synthetic_Scene_and_Data_Generation/Generalized_EOIR_Image_Data_Generation.ipynb Attaches to STK, gets the current scenario, and defines functions to find EOIR sensors and create output folders. Requires the STK Python API installed and a scenario with animation time and time step set. ```python # Replace X with your version #. The python api must be installed prior to running this code # pip install "C:\Program Files\AGI\STK 12\bin\AgPythonAPI\agi.stk12-12.X.0-py3-none-any.whl" import os from datetime import timedelta from datetime import datetime from agi.stk12.stkdesktop import STKDesktop from agi.stk12.stkobjects import * # This section gets the IAgStkObjectRoot interface stk = STKDesktop.AttachToApplication() stk.UserControl = True root = stk.Root scenario = root.CurrentScenario def findObjects(): # If the scenario has multiple objects with sensors, sweep through them all. # We want to check if the objects have EOIR sensors & ignore other payloads. parClass = [] parName = [] chlClass = [] chlName = [] if scenario.HasChildren == True: for i, parObj in enumerate(scenario.Children): for j, type in enumerate(parObj.Children): if parObj.HasChildren == True and parObj.Children.Item(j).ClassName == 'Sensor': if parObj.Children.Item(j).PatternType.name == 'eSnEOIR': parClass.append(parObj.ClassName) parName.append(parObj.InstanceName) chlClass.append(parObj.Children.Item(j).ClassName) chlName.append(parObj.Children.Item(j).InstanceName) else: pass else: pass else: print("Scenario is empty.") return parClass,parName,chlClass,chlName def createfolders(filepath,sensor): # Generate folders for the data to go # Directory structure is based on sensor name newdir = os.mkdir("{}output/".format(filepath)) for (i) in sensor: #print("{}output/{}".format(filepath,i)) os.mkdir("{}output/{}".format(filepath,i)) ``` -------------------------------- ### Create a Place from Facility Database (VB.NET) Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/FacilityTargetPlace/Create a place from facility database.txt VB.NET equivalent of the C# example. Uses the same Connect commands to get the database directory, import a place from the facility database, and retrieve the place object. ```VB.NET ' Get STK database location using Connect Dim result As IAgExecCmdResult = root.ExecuteCommand("GetDirectory / Database Facility") Dim facDataDir As String = result(0) Dim filelocation As String = Path.Combine(facDataDir, "stkFacility.fd") ' Import object from database using Connect Dim command As String = "ImportFromDB * Facility """ + filelocation + """ Class Place SiteName Weilheim" root.ExecuteCommand(command) Dim place As IAgPlace = TryCast(root.GetObjectFromPath("Place/Weilheim"), IAgPlace) ``` -------------------------------- ### First-time STK connection setup with comtypes Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Scenario_Building/STK_OM_Tutorial/STK_OM_Tutorial_Complete.ipynb Run this cell once on a new computer to create the comtypes wrappers. It creates an STK application instance, gets the root interface, and generates the Python wrappers. After running, comment out this cell. ```python # # Import the comtypes package to connect to an external application # import comtypes # from comtypes.client import CreateObject # # Create a new instance of STK # app = CreateObject('STK12.Application') # app.Visible = True # Needed to view the user interface application # # Get the IAgStkObjectRoot interface # root = app.Personality2 # # Note: When 'root=uiApplication.Personality2' is executed, the comtypes library automatically creates a gen folder that contains # # STKObjects and other Python wrappers for the STK libraries. After running this at least once on your computer, the libraries # # should be imported before the 'uiApplication=CreateObject("STK12.Application")' line for improved performance. # # The Astrogator wrapper needs to specifically be loaded with the line below, then AgStkGatorLib is created. # comtypes.client.GetModule((comtypes.GUID("{FEAEF02E-48CE-42AE-B99B-FB9871A69E4B}") ,1,0)) # # View the location and newly generated wrappers # import os as os # print(comtypes.client.gen_dir, '\n') # print(os.listdir(comtypes.client.gen_dir)) # # After running this cell comment out this cell. # # Use "Ctrl" + "a" to select all of the cell content, then Use "Ctrl" + "/" to toggle comments in Jupyter Notebooks ``` -------------------------------- ### Start STK and Get Object References Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Matlab/Problem_Specific/SimulinkAttitudeControlLoop/UsingSimulink_v4.pdf Creates an instance of STK10 via ActiveX and gets the object model root. This is the first step to interact with STK from MATLAB. ```matlab %create an instance of STK10 uiapp = actxserver('STK10.Application'); uiapp.visible = 1; %get the object model root for STK10 root = uiapp.Personality2; ``` -------------------------------- ### S-Function setup routine: function setup(block) Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Matlab/Problem_Specific/SimulinkAttitudeControlLoop/UsingSimulink_v4.pdf Registers input/output ports, sets sample time to 0.1 seconds (10 Hz), and registers methods (Start, Outputs, SetInputPortSamplingMode, PostPropagationSetup). Defines port dimensions, datatype as double, and complexity as real. ```matlab function setup(block) %% Register number of input and output ports block.NumInputPorts = 1; block.NumOutputPorts = 6; % Override input port properties block.InputPort(1).Dimensions = 3; block.InputPort(1).DatatypeID = 0; % double block.InputPort(1).Complexity = 'Real'; block.InputPort(1).DirectFeedthrough = true; % Override output port properties block.OutputPort(1).Dimensions = 4; block.OutputPort(1).DatatypeID = 0; % double block.OutputPort(1).Complexity = 'Real'; block.OutputPort(2).Dimensions = 3; block.OutputPort(2).DatatypeID = 0; % double block.OutputPort(2).Complexity = 'Real'; block.OutputPort(3).Dimensions = 3; block.OutputPort(3).DatatypeID = 0; % double block.OutputPort(3).Complexity = 'Real'; block.OutputPort(4).Dimensions = 4; block.OutputPort(4).DatatypeID = 0; % double block.OutputPort(4).Complexity = 'Real'; block.OutputPort(5).Dimensions = 3; block.OutputPort(5).DatatypeID = 0; % double block.OutputPort(5).Complexity = 'Real'; block.OutputPort(6).Dimensions = 3; block.OutputPort(6).DatatypeID = 0; % double block.OutputPort(6).Complexity = 'Real'; %% Set block sample time block.SampleTimes = [0.1 0]; %% Register methods block.RegBlockMethod('Start', @Start); block.RegBlockMethod('Outputs', @Output); block.RegBlockMethod('SetInputPortSamplingMode', @SetInpPortFrameData); block.RegBlockMethod('PostPropagationSetup', @DoPostPropSetup); ``` -------------------------------- ### Start STK Engine and Get Version Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkEngineContainerization/linux/stk-engine-jupyter/notebooks/AccessExample.ipynb Starts the STK Engine application without graphics, creates a new object root, and prints the STK version. ```python stk = STKEngine.StartApplication(noGraphics=True) root = stk.NewObjectRoot() print(root.ExecuteCommand("GetStkVersion /")[0]) ``` -------------------------------- ### First-time STK connection setup with comtypes Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Scenario_Building/AstrogatorObjectModel/Astrogator_OM_Tutorial.ipynb Uncomment and run this cell the first time you connect to STK with Python on a new computer. It creates an STK application instance, gets the IAgStkObjectRoot interface, and loads the Astrogator wrapper (AgStkGatorLib) via comtypes.client.GetModule. After running once, comment out the cell to improve performance. ```python # # Import the comtypes package to connect to an external application # import comtypes # from comtypes.client import CreateObject # # Create a new instance of STK # app = CreateObject('STK12.Application') # app.Visible = True # Needed to view the user interface application # # Get the IAgStkObjectRoot interface # root = app.Personality2 # # Note: When 'root=uiApplication.Personality2' is executed, the comtypes library automatically creates a gen folder that contains # # STKObjects and other Python wrappers for the STK libraries. After running this at least once on your computer, the libraries # # should be imported before the 'uiApplication=CreateObject("STK12.Application")' line for improved performance. # # The Astrogator wrapper needs to specifically be loaded with the line below, then AgStkGatorLib is created. # comtypes.client.GetModule((comtypes.GUID("{FEAEF02E-48CE-42AE-B99B-FB9871A69E4B") ,1,0)) # # View the location and newly generated wrappers # import os as os # print(comtypes.client.gen_dir, '\n') # print(os.listdir(comtypes.client.gen_dir)) # # After running this cell comment out this cell. # # Use "Ctrl" + "a" to select all of the cell content, then Use "Ctrl" + "/" to toggle comments in Jupyter Notebooks ``` -------------------------------- ### RealTime example: JavaScript for STK real-time aircraft simulation Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Html/General_Utilities/RealTime.htm Sets up an STK aircraft for real-time simulation. It creates the aircraft, configures real-time properties (look-ahead, history, attitude), starts animation, and then uses a timer to send position updates. The example generates its own position data and uses 'now' as a time keyword. It includes a stop mechanism that pauses animation and clears the timer. ```JavaScript Dim app Set app = window.external set stk = app.Personality2 function go() { lat = 0; lon = 0; alt = 10000; if (goButton.value == "GO"){ goButton.value = "STOP"; } else { goButton.value = "GO"; return; } stk.ExecuteCommand("Message / ClearAllMessages"); alert ("Initial setup here!\nThis includes turning verbose and ack off \(if communicating to STK via TCP/IP\). For this example, I'll set VerboseON so that you can see the CONNECT traffic in the STK Message Viewer."); stk.ExecuteCommand("Message / ClearAllMessages"); stk.ExecuteCommand("ConControl / VerboseOn"); alert ("Set up defualt units which will be used by the CONNECT commands."); stk.ExecuteCommand("Message / ClearAllMessages"); stk.ExecuteCommand("SetUnits / METER EPOCHSEC SEC DEGREE"); alert ("Create the new object \(Aircraft\), and define its properties."); result = stk.ExecuteCommand("DoesObjExist / \*/Aircraft/MyRealTimeAircraft"); if (result(0) == "1") { stk.ExecuteCommand("Unload / \*/Aircraft/MyRealTimeAircraft"); } stk.ExecuteCommand("Message / ClearAllMessages"); stk.ExecuteCommand("New / \*/Aircraft MyRealTimeAircraft"); stk.ExecuteCommand("Realtime \*/Aircraft/MyRealTimeAircraft SetProp SetLookAhead DeadReckon 500 1 10"); stk.ExecuteCommand("RealTime \*/Aircraft/MyRealTimeAircraft SetHistory 3600 5"); stk.ExecuteCommand("SetAttitude \*/Aircraft/MyRealTimeAircraft RealTime Extrapolate 500 3600"); stk.ExecuteCommand("Graphics \*/Aircraft/MyRealTimeAircraft SetAttrType RealTime"); alert ("Set up STK to animate in real time with a refresh rate of .1 second, and begin the animation"); stk.ExecuteCommand("Message / ClearAllMessages"); stk.ExecuteCommand("SetAnimation \* AnimationMode RealTime RealTimeOffset 0 RefreshDelta .1 RefreshMode RefreshDelta"); stk.ExecuteCommand("Animate \* Start"); alert ("This is where I'll start a java script timer and create position/attitude data. This is when you would start processing your realtime data feed. I'll be sending in data sets every second. You'll notice that I'm using 'now' as a keyword in the CONNECT commands - this is just a shortcut which pulls the time from the system clock. You can use an actual date/time value. If your system clock is not insync with the data feed, you may need to apply an animation real time offset."); MyTimer = setInterval("timer\_function()", 1000); stk.ExecuteCommand("Message / ClearAllMessages"); } function timer\_function () { if (goButton.value == "GO"){ clearInterval( MyTimer ); stk.ExecuteCommand("Message / ClearAllMessages"); stk.ExecuteCommand("Animate \* Pause"); alert ("Real Time Processing has been termintated!!!"); return; } stk.ExecuteCommand("SetPosition \*/Aircraft/MyRealTimeAircraft LLA \"now\" " + lat + " " + lon + " " + alt); if (lon == 0){ stk.ExecuteCommand("VO \* ViewFromTo Normal From Aircraft/MyRealTimeAircraft To Aircraft/MyRealTimeAircraft"); } lon = lon + .01; lat = 60 \* Math.sin(lon \* (Math.PI/180)); alt = alt + (Math.random() - .5); } ``` -------------------------------- ### Start STK Parallel Computing Services Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkEngineContainerization/linux/stk-parallel-computing-server/README.md Starts the Coordinator and Agent containers, with the Coordinator listening on port 9090. The --scale agent=2 starts two agent containers for demonstration purposes. ```bash docker compose up -d --scale agent=2 ``` -------------------------------- ### generateSensorPointingFile.m - Example call Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Matlab/General_Utilities/README.md Example call to generateSensorPointingFile for a specified sensor, generating pointing files for each access interval. ```matlab generateSensorPointingFile('Satellite/LEOSat/Sensor/LEOsensor', 'LEOSensorAttitude', 60) ``` -------------------------------- ### filterObjectsByType.m - Find satellites starting with 'gps' Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Matlab/General_Utilities/README.md Example call to filterObjectsByType to find all satellites whose names start with 'gps'. ```matlab FilterObjectsByType('Satellite', 'gps') ``` -------------------------------- ### Setup environment and create data folders Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Scenario_Analysis/ConstellationAndNetworkRouting/DataTransfer.ipynb Imports required libraries (numpy, pandas, STK, networkx, etc.) and creates folders for saving nodes, positions, strands, edges, and network data. Also sets pandas display option and ignores numpy indexing warnings. ```python import numpy as np import pandas as pd pd.set_option("max_colwidth", 120) from agi.stk12.stkdesktop import STKDesktop from agi.stk12.utilities.colors import Colors from agi.stk12.stkobjects import * from agi.stk12.stkutil import * from agi.stk12.vgt import * import seaborn as sns import matplotlib.pyplot as plt from matplotlib import cm from chainPathLib2 import * import time import networkx as nx folders = [ "SavedNodes", "SavedPositions", "SavedStrands", "SavedEdges", "SavedNetworkData", ] for folder in folders: if not os.path.exists(folder): os.makedirs(folder) import warnings warnings.filterwarnings("ignore") # Ignore some numpy indexing warnings ``` -------------------------------- ### Get starting and ending nodes of the chains Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Scenario_Analysis/ConstellationAndNetworkRouting/ConstellationAnalysisUsingPrebuiltChains.ipynb Calls getStartingAndEndingNodes to retrieve the starting and ending nodes for the given chain names. The output shows lists of Place objects for the starting and ending nodes. ```python # Get starting nodes and ending nodes of the chains startingNodes, endingNodes = getStartingAndEndingNodes(stkRoot, chainNames) startingNodes, endingNodes ``` ```text Result: (['Place/Network1Place4', 'Place/Network1Place1', 'Place/Network1Place5', 'Place/Network1Place2', 'Place/Network1Place3'], ['Place/Network2Place3', 'Place/Network2Place5', 'Place/Network2Place2', 'Place/Network2Place1', 'Place/Network2Place4']) ``` -------------------------------- ### Run client_example.py in Docker container Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkEngineContainerization/linux/stk-parallel-computing-server/README.md Executes the client_example.py script inside a Python container with the STK Parallel Computing Server Python API. Mounts the script to /tmp/client_example.py and sets the coordinator hostname and port. Replace {version} with the version number (e.g., 2.9.0). If the coordinator host port was changed, use that port for COORDINATOR_PORT. ```bash docker run --rm -v /client_example.py:/tmp/client_example.py -e COORDINATOR_HOSTNAME=coordinator -e COORDINATOR_PORT=9090 -w /tmp --network stk-parallel-computing-server ansys/stk/stk-parallel-computing-server-python:{version}-ubi-8 client_example.py ``` -------------------------------- ### Command-line usage example Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkEngineApplications/CSharp/StkMetaDataExtractor/README.md Run the utility from the command line with two arguments: the path to a scenario file (*.sc or *.vdf) and the desired output directory. The output XML and CZML files will be named after the scenario. ```plaintext StkMetadataExtractor.exe "c:\Temp\sampleScenario.vdf" "c:\Temp" ``` -------------------------------- ### VB.NET: Find event interval start and stop times Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Analysis Workbench/Time/Time InstanceInterval/Determines the start and stop times of the event interval.txt Uses IAgCrdnEventInterval.FindInterval() to get the interval result. If the interval is valid, prints the start and stop times to the console. ```VB.NET Dim eventInterval As IAgCrdnEventInterval = provider.EventIntervals("AvailabilityTimeSpan") Dim interval As IAgCrdnEventIntervalResult = eventInterval.FindInterval() If interval.IsValid Then Console.WriteLine("Interval Start: " + interval.Interval.Start) Console.WriteLine("Interval Stop: " + interval.Interval.[Stop]) End If ``` -------------------------------- ### C#: Find event interval start and stop times Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Analysis Workbench/Time/Time InstanceInterval/Determines the start and stop times of the event interval.txt Uses IAgCrdnEventInterval.FindInterval() to get the interval result. If the interval is valid, prints the start and stop times to the console. ```C# IAgCrdnEventInterval eventInterval = provider.EventIntervals["AvailabilityTimeSpan"]; IAgCrdnEventIntervalResult interval = eventInterval.FindInterval(); if (interval.IsValid) { Console.WriteLine("Interval Start: " + interval.Interval.Start); Console.WriteLine("Interval Stop: " + interval.Interval.Stop); } ``` -------------------------------- ### VB.NET: Create Facility from Database using Connect Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/FacilityTargetPlace/Create a facility from facility database.txt VB.NET equivalent of the C# example. It retrieves the facility database directory, constructs the path, imports the 'Weilheim' facility via ImportFromDB, and obtains the IAgFacility object. ```VB.NET ' Get STK database location using Connect Dim result As IAgExecCmdResult = root.ExecuteCommand("GetDirectory / Database Facility") Dim facDataDir As String = result(0) Dim filelocation As String = Path.Combine(facDataDir, "stkFacility.fd") ' Import object from database using Connect Dim command As String = "ImportFromDB * Facility """ + filelocation + """ Class Facility SiteName Weilheim" root.ExecuteCommand(command) Dim facility As IAgFacility = TryCast(root.GetObjectFromPath("Facility/Weilheim"), IAgFacility) ``` -------------------------------- ### Get starting and ending nodes from constellations Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Scenario_Analysis/ConstellationAndNetworkRouting/ConstellationAnalysisMultiDomainAndMultiHop.ipynb Retrieves the nodes belonging to the starting and ending constellations using the helper functions getNodesFromConstellation. The result is a tuple of lists of node paths. ```python # Get starting nodes and ending nodes from the constellations startingNodes = getNodesFromConstellation(stkRoot, startingConstellation) endingNodes = getNodesFromConstellation(stkRoot, endingConstellation) startingNodes, endingNodes ``` ```text Result: (['Target/Target1', 'Target/Target2', 'Target/Target3', 'Target/Target4', 'Target/Target5', 'Missile/Missile1'], ['Facility/Facility1', 'Facility/Facility2', 'Facility/Facility3']) ``` -------------------------------- ### Setup sensor and ODTK for imaging Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Problem_Specific/EOIRTrackingInTheLoop/EOIRInTheLoop.ipynb Initializes sensor handles, sets up ODTK scenario and filter, creates VGT points and vectors, and configures visualization. Requires ODTK and STK objects. ```python # Get handles and setup for intiial config sensor = root.GetObjectFromPath(sensorPath) vectors = sensor.Vgt.Vectors sensorName = sensorPath.split("/")[-1] if ( differenceImages == True ): # Differencing only works for staring images, don't update the sensor pointing updateSensorMethod = "" # Use a sensor type of Fixed or Fixed in Axes if you are updating the sensor pointing if sensor.PointingType == AgESnPointing.eSnPtFixedAxes: axes = sensor.Pointing.ReferenceAxes[:-5] else: axes = "/".join(sensorPath.split("/")[1:3]) + " Body" print("Assuming Parent Body axes and the sensor pointing type is Fixed") # Set up ODTK if updateSensorMethod.lower() == "odtk": # Get ODTK handles ODScenario = ODTK.Scenario(0) ODSat = ODScenario.Satellite(ODSatName) ODFilter = ODScenario.Filter(ODFilterName) ODObject = ODScenario.Satellite(ODTargetName) # Add measurement file measurementFile = sensorName + ".geosc" open(measurementFile, "w").close() # Clear RADecfile measurementFiles = ODScenario.Measurements.Files measurementFiles.clear() newFile = measurementFiles.NewElem() newFile.Filename = os.getcwd() + "\\" + measurementFile measurementFiles.push_back(newFile) ODScenario.Measurements.Files(0).Enabled = True # Run filter with no Obs ODFilter.ProcessControl.StopMode = "TimeSpan" ODFilter.ProcessControl.TimeSpan = (tstop - tstart) / 3600 ODFilter.Go() ODFilter.ProcessControl.StopMode = "LastMeasurement" predictionTimeSpan = 3600 # sec ODFilter.Output.STKEphemeris.Predict.TimeSpan = ( predictionTimeSpan / 60 ) # Convert to mins ephemerisFile = ODFilter.Output.STKEphemeris.Files(0).FileName() # Set up VGT points = sensor.Vgt.Points if not points.Contains("EstimatedTargetLocation"): point = points.Factory.Create( "EstimatedTargetLocation", "Estimated Pointing Location", AgECrdnPointType.eCrdnPointTypeFile, ) point.Filename = ephemerisFile point = points.Item("EstimatedTargetLocation") if not vectors.Contains("PointingDirection"): vector = vectors.Factory.Create( "PointingDirection", "Estimated Pointing Direction", AgECrdnVectorType.eCrdnVectorTypeDisplacement, ) vector.Destination.SetPath(sensorPath[2:] + " EstimatedTargetLocation") # Set up filter run visualization if visualizeOD == True: if sc.Children.Contains( AgESTKObjectType.eSatellite, targetPath.split("/")[-1] + "Filter" ): satVis = root.GetObjectFromPath(targetPath + "Filter") else: satVis = sc.Children.New( AgESTKObjectType.eSatellite, targetPath.split("/")[-1] + "Filter" ) satVis.SetPropagatorType(AgEVePropagatorType.ePropagatorStkExternal) satVis.Propagator.Filename = ephemerisFile satVis.VO.Covariance.Attributes.IsVisible = True satVis.VO.OrbitSystems.RemoveAll() satVis.VO.OrbitSystems.InertialByWindow.IsVisible = False satVis.VO.OrbitSystems.Add(targetPath.split("*/")[-1] + " RIC System") # Set up measurement vector if not vectors.Contains("MeasurementDirection"): vectors.Factory.Create( "MeasurementDirection", "Measurement Direction", AgECrdnVectorType.eCrdnVectorTypeFixedInAxes, ) vector = vectors.Item("MeasurementDirection") vector.ReferenceAxes.SetPath(axes) # Update initial pointing if updateSensorMethod.lower() == "previousmeasurementdirection": sensor.Pointing.Orientation.AssignAzEl( azStart, elStart, AgEAzElAboutBoresight.eAzElAboutBoresightRotate ) # Get the access handle if useAccessConstraintsToLimitObs == True: access = sensor.GetAccess(targetPath) # Get pixel size ( horizontalPixels, verticalPixels, horizontalAngle, verticalAngle, ) = getSensorFOVAndPixels(sensor) horizontalDegPerPixel = horizontalAngle / horizontalPixels verticalDegPerPixel = verticalAngle / verticalPixels horizontalCenter = horizontalPixels / 2 + 0.5 verticalCenter = verticalPixels / 2 + 0.5 # Update RA and Dec based on pixel size if usePixelSizeForStd == True: RAstd = horizontalDegPerPixel * 3600 DECstd = ( verticalDegPerPixel * 3600 ) # Be careful if this exceeds 99 arc Seconds, should add a check, could also leave blank to use ODTK values if RAstd >= 100 or DECstd >= 100: print("Setting standard deviations to use ODTK values") RAstd = 00.0 DECstd = 00.0 # Set up times and measurements times = np.arange(tstart, tstop, tstep) times = np.append(times, tstop).round( 3 ) # round to 1/1000th of a sec get rid of numerical issues timesWithTaggedImages = [] measurementsAzElErrors = [] meaurementsAzEl = [] sensorPointingHistory = [] imageFolder = os.getcwd() + "\\Images" t1 = time.time() ``` -------------------------------- ### Access intervals JSON response example Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkEngineContainerization/linux/stk-engine-webservice/README.md Example JSON response returned by the web service when accessing the /access endpoint. It contains an array of access intervals with start and stop times. ```json { "accessIntervals":[ {"start":"...","stop":"..."}, {"start":"...","stop":"..."}, {"start":"...","stop":"..."}, {"start":"...","stop":"..."} ] } ``` -------------------------------- ### Create a Place from Facility Database (C#) Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/FacilityTargetPlace/Create a place from facility database.txt Uses the Connect command 'GetDirectory / Database Facility' to get the STK database location, then imports a place from the facility database using 'ImportFromDB * Facility "" Class Place SiteName Weilheim'. Finally, retrieves the place object via 'root.GetObjectFromPath("Place/Weilheim")'. ```C# // Get STK database location using Connect IAgExecCmdResult result = root.ExecuteCommand("GetDirectory / Database Facility"); string facDataDir = result[0]; string filelocation = Path.Combine(facDataDir, "stkFacility.fd"); // Import object from database using Connect string command = "ImportFromDB * Facility \"" + filelocation + "\" Class Place SiteName Weilheim"; root.ExecuteCommand(command); IAgPlace place = root.GetObjectFromPath("Place/Weilheim") as IAgPlace; ``` -------------------------------- ### Get access interval times Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/General_Utilities/AzElPolarPlot/AzElPolarPlot_win32com.ipynb Retrieves access interval start and stop times from the 'Access Data' provider. ```python # Get all the access interval start and stop times accessReport = access.DataProviders.Item("Access Data") accessIntervals = accessReport.ExecElements( scenario.StartTime, scenario.Stoptime, ["Access Number", "Start Time", "Stop Time"] ) accessIntervals = list(accessIntervals.DataSets.ToArray()) ``` -------------------------------- ### Configure MTO with C# Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/MTO/Configure MTO.txt C# example that sets the scenario time period, creates multiple MTO tracks, and adds interpolated points to each track. It uses BeginUpdate and EndUpdate to delay updates for performance. ```C# // IAgMto mto: Mto Object IAgScenario scenario = root.CurrentScenario as IAgScenario; scenario.SetTimePeriod("1 Feb 2008 12:00:00.000", "2 Feb 2008 12:00:00.000"); // Number of tracks and points to add double trackCount = 10; double pointCount = 20; // Initial values from which we will interpolate double lat0 = 40.04; double lon0 = -75.595; double alt0 = 0; root.BeginUpdate(); // Call BeginUpdate for STK engine to delay updates for (int i = 0; i < trackCount; ++i) { IAgMtoTrack track = mto.Tracks.Add(i); IAgDate date = root.ConversionUtility.NewDate("UTCG", scenario.StartTime as string); // Interpolate mto points for (int j = 0; j < pointCount; ++j) { double lat = lat0 + 1 * i; double lon = lon0 + 0.1 * j; double alt = alt0; date = date.Add("sec", 120); track.Points.AddPoint(date.Format("UTCG"), lat, lon, alt); } } root.EndUpdate(); ``` -------------------------------- ### C#: Create Facility from Database using Connect Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/FacilityTargetPlace/Create a facility from facility database.txt Uses the Connect command GetDirectory to find the STK facility database, then imports a facility named 'Weilheim' using ImportFromDB. The resulting IAgFacility object is retrieved via GetObjectFromPath. ```C# // Get STK database location using Connect IAgExecCmdResult result = root.ExecuteCommand("GetDirectory / Database Facility"); string facDataDir = result[0]; string filelocation = Path.Combine(facDataDir, @"stkFacility.fd"); // Import object from database using Connect string command = "ImportFromDB * Facility \"" + filelocation + "\" Class Facility SiteName Weilheim"; root.ExecuteCommand(command); IAgFacility facility = root.GetObjectFromPath("Facility/Weilheim") as IAgFacility; ``` -------------------------------- ### Get provider in VB.NET Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Analysis Workbench/Get a Vector Geometry Tool provider.txt Retrieves an IAgCrdnProvider using root.GetProvider(path) in VB.NET, with the same path semantics as the C# example. ```VB.NET // String path: A short name referring to an instance of STK Object or Central Body 'Returns a provider associated with the specified ' instance of an STK Object or a Central Body. Dim provider As IAgCrdnProvider = root.GetProvider(path) ``` -------------------------------- ### Configure Launch Segment in C# Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/Satellite/Basic/Orbit/Astrogator/Configure launch segment.txt C# example that inserts a launch segment into the main sequence, configures launch properties (central body, epoch, step size, pre-launch time, time of flight, ascent type, initial acceleration), sets the display system to geocentric with latitude, longitude, and radius, and configures burnout velocity options. ```csharp // Add launch sequence and retrieve the IAgVAMCSSegment segment = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeLaunch, "MyLaunch", "-"); IAgVAMCSLaunch launch = segment as IAgVAMCSLaunch; // Configure launch properties launch.CentralBodyName = "Mars"; launch.Epoch = "1 Jan 2012 12:00:00.000"; launch.StepSize = 6; launch.UsePreviousSegmentState = false; launch.PreLaunchTime = 1; launch.TimeOfFlight = 500; launch.AscentType = AgEVAAscentType.eVAAscentTypeEllipseQuarticMotion; launch.InitialAcceleration = 0.02; // Configure display type launch.SetDisplaySystemType(AgEVALaunchDisplaySystem.eVADisplaySystemGeocentric); IAgVADisplaySystemGeocentric llr = (IAgVADisplaySystemGeocentric)launch.DisplaySystem; llr.Latitude = 35.581; llr.Longitude = -92.263; llr.Radius = 1000; // Configure launch type launch.AscentType = AgEVAAscentType.eVAAscentTypeEllipseQuarticMotion; launch.InitialAcceleration = 0.02; launch.AscentType = AgEVAAscentType.eVAAscentTypeEllipseCubicMotion; // Configure burnout type IAgVABurnoutVelocity velocity = launch.BurnoutVelocity; velocity.BurnoutOption = AgEVABurnoutOptions.eVABurnoutOptionsInertialVelocity; velocity.InertialVelocity = 20.0; velocity.InertialHorizontalFPA = 22; velocity.InertialVelocityAzimuth = 55; velocity.BurnoutOption = AgEVABurnoutOptions.eVABurnoutOptionsFixedVelocity; velocity.FixedVelocity = 20; ``` -------------------------------- ### Get current time and set scenario time period Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Python/Problem_Specific/DeckAccess/DeckAccess.ipynb Gets the current time and adds one second to create start and stop times for the scenario. It also prints the current time and the scenario start/stop times. ```python # Get the current time and add 1 second from datetime import datetime from datetime import timedelta now = datetime.now() nowSTK = now.strftime("%d %b %Y %H:%M:%S") nowplus = now + timedelta(seconds=1) nowSTKplus = nowplus.strftime("%d %b %Y %H:%M:%S") startTime = nowSTK stopTime = nowSTKplus print("Now = " + nowSTK) # Create times to set the scenario time period which includes now strs = nowSTK.split(" ") start = strs[0] + " " + strs[1] + " " + strs[2] + " 00:00:00.000" stop = strs[0] + " " + strs[1] + " " + strs[2] + " 23:59:59.999" print("Scenario Start = " + start) print("Scenario Stop = " + stop) ``` -------------------------------- ### Set Explicit Start Time and Add Waypoints (VB.NET) Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/Vehicles/Basic/Trajectory/Great Arc/Sets the ephemeris start time to an explicit time and then add waypoints relative to that time.txt VB.NET equivalent of the C# example. Sets the ephemeris start time to 'Tomorrow' using IAgCrdnEventSmartEpoch.SetExplicitTime, defines waypoints with time offsets, propagates with SetPointsSmoothRateAndPropagate, and prints waypoint details. ```vbnet ' Set the epoch time to tomorrow. Dim startEpoch As IAgCrdnEventSmartEpoch = propagator.EphemerisInterval.GetStartEpoch() startEpoch.SetExplicitTime("Tomorrow") propagator.EphemerisInterval.SetStartEpoch(startEpoch) ' Waypoints time start from explicit start time that we set above. Dim waypointsAndTimes As Array = New Object(,) {{40.329, -76.366, 0, 0.0154, 0}, {40.38, -76.359, 0, 0.0154, 0}, {40.406, -76.329, 0, 0.0154, 0}, {40.417, -76.311, 0, 0.0154, 0}} propagator.SetPointsSmoothRateAndPropagate(waypointsAndTimes) Dim i As Integer = 0 While i < propagator.Waypoints.Count Console.WriteLine("Waypoint {0}, Lat = {1}, Lon = {2}, Time = {3}", i, propagator.Waypoints(i).Latitude, propagator.Waypoints(i).Longitude, propagator.Waypoints(i).Time) System.Threading.Interlocked.Increment(i) End While ``` -------------------------------- ### Add a company logo with a texture overlay (C#) Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/3D Windows/Overlays/Screen Overlays/Add a company logo with a texture overlay.txt C# example using the STK Object Model to load an image file as a texture and add it as a screen overlay. Sets the overlay size to half the texture dimensions, translucency to 0.1, origin to center-right, and adds it to the overlay manager. ```csharp // AgStkObjectRoot root: STK Object Model root // String imageFile: The image file IAgStkGraphicsSceneManager manager = ((IAgScenario)root.CurrentScenario).SceneManager; IAgStkGraphicsScreenOverlayCollectionBase overlayManager = (IAgStkGraphicsScreenOverlayCollectionBase)manager.ScreenOverlays.Overlays; IAgStkGraphicsRendererTexture2D texture2D = manager.Textures.LoadFromStringUri( imageFile); IAgStkGraphicsTextureScreenOverlay overlay = manager.Initializers.TextureScreenOverlay.InitializeWithXYWidthHeight( 10, 0, texture2D.Template.Width / 2, texture2D.Template.Height / 2); ((IAgStkGraphicsOverlay)overlay).Translucency = 0.1f; ((IAgStkGraphicsOverlay)overlay).Origin = AgEStkGraphicsScreenOverlayOrigin.eStkGraphicsScreenOverlayOriginCenterRight; overlay.Texture = texture2D; overlayManager.Add((IAgStkGraphicsScreenOverlay)overlay); ``` -------------------------------- ### createEphemerisFile.m - Example object paths and coordinate systems Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkAutomation/Matlab/General_Utilities/README.md Shows example values for the objPath and coordSys variables used in createEphemerisFile.m. Update these in the script's input section before running. ```matlab objPath = 'Aircraft/Aircraft1'; objPath = 'Missile/Missile1'; objPath = 'LaunchVehicle/LaunchVehicle1'; coordSys = 'CentralBody/Earth ICRF'; coordSys = 'CentralBody/Moon L2'; coordSys = 'Satellite/Satellite2 RIC'; ``` -------------------------------- ### Execute parallel computing tasks Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkEngineContainerization/linux/stk-parallel-computing-server/README.md Runs the client_example.py script in a Docker container with Python 3 and the STK Parallel Computing Server Python API installed. ```bash docker compose -f docker-compose.python.yml run --rm python client_example.py ``` -------------------------------- ### Start STK and get IAgStkObjectRoot in C# Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Initialization/Start STK and get a reference to IAgStkObjectRoot.txt Creates an STK application instance, loads the STK personality, makes it visible, and casts the Personality2 property to IAgStkObjectRoot. ```C# // Create an instance of STK AgUiApplication uiApplication = new AgUiApplication(); uiApplication.LoadPersonality("STK"); uiApplication.Visible = true; // Get our IAgStkObjectRoot interface IAgStkObjectRoot stkRoot = uiApplication.Personality2 as IAgStkObjectRoot; ``` -------------------------------- ### Configure Basic Acceleration Model in C# Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/Aviator/Configure the basic acceleration performance model of an aircraft.txt C# example that retrieves the built-in basic acceleration model, sets level turn bank angle, climb/descent max pull-up G, attitude roll rate, simple aerodynamics parameters, simple propulsion parameters, and saves the aircraft to the catalog. ```csharp // Get the acceleration type IAgAvtrAircraftAcceleration acceleration = aircraft.Acceleration; // Get the build in performance model IAgAvtrAircraftBasicAccelerationModel basicAccModel = acceleration.GetBuiltInModel(); // Get the level turns options IAgAvtrLevelTurns levelTurns = basicAccModel.LevelTurns; // Set a max bank angle of 25 levelTurns.SetLevelTurn(AgEAvtrTurnMode.eTurnModeBankAngle, 25); // Get the climb and descent transition options IAgAvtrClimbAndDescentTransitions climbAndDescent = basicAccModel.ClimbAndDescentTransitions; // Set the max pull up G to 1 climbAndDescent.MaxPullUpG = 1.2; // Get the attitude transition options IAgAvtrAttitudeTransitions attitudeTransitions = basicAccModel.AttitudeTransitions; // Set the max roll rate to 25 attitudeTransitions.RollRate = 25; // Get the aerodynamics IAgAvtrAircraftAero aero = basicAccModel.Aerodynamics; // Use simple aerodynamics aero.AeroStrategy = AgEAvtrAircraftAeroStrategy.eAircraftAeroSimple; // Get the options for the simple aerodynamics and set some parameters IAgAvtrAircraftSimpleAero simpleAero = aero.ModeAsSimple; simpleAero.SRef = 5; simpleAero.ClMax = 3.1; simpleAero.Cd = 0.05; // Get the propulsion IAgAvtrAircraftProp prop = basicAccModel.Propulsion; // Use simple propulsion prop.PropStrategy = AgEAvtrAircraftPropStrategy.eAircraftPropSimple; // Get the simple propulsion options and set some parameters IAgAvtrAircraftSimpleProp simpleProp = prop.ModeAsSimple; simpleProp.MaxThrustAccel = 0.6; simpleProp.MinThrustDecel = 0.4; simpleProp.SetDensityScaling(true, 0.02); // Save the changes to the catalog aircraft.GetAsCatalogItem().Save(); ``` -------------------------------- ### VB.NET: Create and configure start stop times event array Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Analysis Workbench/Time/Time InstanceArray/Create and configure start stop times event array.txt Equivalent VB.NET version of the C# example. Creates an event array with start and stop times, sets the reference intervals to 'LightingIntervals.Sunlight' and the start/stop option to 'eCrdnStartStopOptionCountStartOnly'. Then finds times and prints each time and interval start/stop to the console. ```VB.NET Dim eventArray As IAgCrdnEventArray = provider.EventArrays.Factory.CreateEventArrayStartStopTimes("MyEventArrayStartStopTimes", "MyDescription") Dim asStartStopTimes As IAgCrdnEventArrayStartStopTimes = TryCast(eventArray, IAgCrdnEventArrayStartStopTimes) asStartStopTimes.ReferenceIntervals = provider.EventIntervalLists("LightingIntervals.Sunlight") asStartStopTimes.StartStopOption = AgECrdnStartStopOption.eCrdnStartStopOptionCountStartOnly Dim timeArrays As IAgCrdnFindTimesResult = eventArray.FindTimes() If timeArrays.IsValid Then Console.WriteLine("Times") Dim numTimes As Integer = timeArrays.Times.GetLength(0) Dim i As Integer = 0 While i < numTimes Console.WriteLine(timeArrays.Times.GetValue(i)) System.Threading.Interlocked.Increment(i) End While For Each timeArray As IAgCrdnInterval In timeArrays.Intervals Console.WriteLine("Start: " + timeArray.Start) Console.WriteLine("Stop: " + timeArray.[Stop]) Next End If ``` -------------------------------- ### C#: Create Satellite from Database using Connect Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/STK Objects/Satellite/Create a satellite from the satellite database.txt Uses root.ExecuteCommand to get the satellite database directory, then constructs the file path and common name, and finally imports the satellite with the ImportFromDB command. ```C# // Get STK database location using Connect IAgExecCmdResult result = root.ExecuteCommand("GetDirectory / Database Satellite"); string satDataDir = result[0]; string filelocation = "\"" + Path.Combine(satDataDir, @"stkAllTLE.sd") + "\""; string commonname = "\"hst\""; // Import object from database using Connect string command = String.Format("ImportFromDB * Satellite {0} Constellation ImportedFromSatDB Propagate On CommonName {1}", filelocation, commonname); root.ExecuteCommand(command); ``` -------------------------------- ### Start STK and get IAgStkObjectRoot in VB.NET Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Initialization/Start STK and get a reference to IAgStkObjectRoot.txt Creates an STK application instance, loads the STK personality, makes it visible, and casts Personality2 to IAgStkObjectRoot using TryCast. ```VB.NET ' Create an instance of STK Dim uiApplication As New AgUiApplication() uiApplication.LoadPersonality("STK") uiApplication.Visible = True ' Get our IAgStkObjectRoot interface Dim stkRoot As IAgStkObjectRoot = TryCast(uiApplication.Personality2, IAgStkObjectRoot) ``` -------------------------------- ### Start STK and get IAgStkObjectRoot in MATLAB Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Initialization/Start STK and get a reference to IAgStkObjectRoot.txt Uses actxserver to create an STK application instance, sets Visible to 1, and retrieves the Personality2 property as the root object. ```MATLAB %Create an instance of STK uiApplication = actxserver('STK13.application'); uiApplication.Visible = 1; %Get our IAgStkObjectRoot interface root = uiApplication.Personality2; ``` -------------------------------- ### Get terrain altitude profile in VB.NET Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/Utilities/Gets the altitude profile of the terrain.txt Placeholder snippet for the VB.NET version of the terrain altitude profile example. Only the comment indicating the terrain file path is shown. ```VB.NET // String terrainFile: Path of Terrain file ``` -------------------------------- ### Retrieve interval data provider and execute (VB.NET) Source: https://github.com/analyticalgraphicsinc/stkcodeexamples/blob/master/StkCodeSnippets/DataProviders/Coarse grain approach to retrieving a interval data provider.txt Uses IAgDataPrvInterval and IAgDrResult to get the 'Lighting Times//Sunlight' provider and execute it with a 20-second interval starting at '1 Jan 2012 12:00:00.000'. ```VB.NET Dim dp As IAgDataPrvInterval = facility.DataProviders.GetDataPrvIntervalFromPath("Lighting Times//Sunlight") Dim result As IAgDrResult = dp.Exec("1 Jan 2012 12:00:00.000", "1 Jan 2012 12:00:20.000") ```