The following code snippets demonstrate tasks that are commonly encountered when working with the STK Object Model.
The code snippets in this topic were written using the win32com library from python. If you prefer to use the comtypes library, you will need to modify the snippets for them to work properly.
Start STK and get a reference to IAgStkObjectRoot starting a new STK instance
[Python]
from win32com.client import GetActiveObject uiApplication = win32com.client.Dispatch('STK13.Application') uiApplication.Visible = True
# Start new instance of STK from comtypes.client import CreateObject uiApplication = CreateObject('STK13.Application') uiApplication.Visible = True
# Get our IAgStkObjectRoot interface root = uiApplication.Personality2
Start STK and get a reference to IAgStkObjectRoot using a running STK instance
[Python]
# Get reference to running STK instance from win32com.client import GetActiveObject uiApplication = win32com.client.GetActiveObject('STK13.Application') uiApplication.Visible = True
# if using the comtypes Library from comtypes.client import GetActiveObject uiApplication=GetActiveObject('STK13.Application') uiApplication.Visible=True
# Get our IAgStkObjectRoot interface root = uiApplication.Personality2
# AvailableObstructions returns a one dimensional array of obstruction paths availableArray = thirdBodyConstraint.AvailableObstructions
# In this example add all available obstructions print('Available obstructions') for i in range(0,len(availableArray)): print(availableArray[i]) thirdBodyConstraint.AddObstruction(availableArray[i])
# AssignedObstructions returns a one dimensional array of obstruction paths assignedArray = thirdBodyConstraint.AssignedObstructions
print('Assigned obstructions') for i in range(0,len(assignedArray)): print(assignedArray[i])
# Print results for i in range(0,results.Count): result = results.Item(i) print('Time: #s HasAccess: #s' # (result.Time, str(result.AccessSatisfied)))
for j in range(0,result.Constraints.Count) constraint = result.Constraints.Item(j) print('Constraint: #s Object: #s Status: #s Value:#s' # (constraint.Constraint, constraint.ObjectPath, constraint.Status, str(constraint.Value())))
Compute and extract access interval times
[Python]
# IAgStkAccess access: Access calculation # Get and display the Computed Access Intervals intervalCollection = access.ComputedAccessIntervalTimes
# Set the intervals to use to the Computed Access Intervals computedIntervals = intervalCollection.ToArray(0, -1) access.SpecifyAccessIntervals(computedIntervals)
Configure the access analysis time period to specified time instants.
# For this code snippet, let's use the time interval when the satellite reached min and max altitude values. # Note, this assumes time at min happens before time at max. timeOfAltMin = satellite.Vgt.Events.Item('GroundTrajectory.Detic.LLA.Altitude.TimeOfMin') timeOfAltMax = satellite.Vgt.Events.Item('GroundTrajectory.Detic.LLA.Altitude.TimeOfMax')
# Set the access time period with the times we figured out above. access = satellite.GetAccessToObject(facility) access.AccessTimePeriod = 2 # eUserSpecAccessTime accessTimePeriod = access.AccessTimePeriodData
object1 = accesses[0][0] # e.g. "Satellite/MySatellite" object2 = accesses[0][1] # e.g. "Facility/MyFacility" computed = accesses[0][2] # e.g. True (if access has been computed)
# IAgAccessConstraintCollection accessConstraints: Access Constraint collection for i in range(accessConstraints.Count-1,0,-1): constraint = accessConstraints.Item(i).ConstraintName
if (constraint == 'LineOfSight') == False: if (constraint == 'ThirdBodyObstruction'): thirdBodyConstraint = accessConstraints.GetActiveNamedConstraint('ThirdBodyObstruction') assignedArray = thirdBodyConstraint.AssignedObstructions
for j in range (0,len(assignedArray)): thirdBodyConstraint.RemoveObstruction(assignedArray[j]) end
Create an area target (on the current scenario central body)
[Python]
#IAgStkObjectRoot root: STK Object Model Root
# Create the AreaTarget on the current scenario central body (use # NewOnCentralBody to specify explicitly the central body) areaTarget = root.CurrentScenario.Children.New(2, 'MyAreaTarget') # eAreaTarget
Define area target boundary and position from list of lat/lon/alt
# By using the fine grained interfaces, # BeginUpdate/EndUpdate prevent intermediate redraws root.BeginUpdate() areaTarget.AreaType = 1 # ePattern patterns = areaTarget.AreaTypeData patterns.Add(48.897, 18.637) patterns.Add(46.534, 13.919) patterns.Add(44.173, 21.476) root.EndUpdate() areaTarget.AutoCentroid = True
Define area target boundary and position from list of lat/lon/alt (using common tasks)
[Python]
# IAgStkObjectRoot root: STK Object Model Root # IAgAreaTarget areaTarget: AreaTarget object # Remove all points in the area target areaTarget.AreaTypeData.RemoveAll()
# By using the CommonTasks interface, # make an array of lattitude and longitude boundary points boundary = [ [29, -12],[29, 34],[6, 34],[6, -12] ]
# SetAreaTypePattern expects a two dimensional array of latitude and longitude values areaTarget.CommonTasks.SetAreaTypePattern(boundary)
# Get IAgAreaTypePatternCollection interface from AreaTypeData patternPoints = areaTarget.AreaTypeData
# ToArray returns a two dimensional array of latitude and longitude points areaTargetPoints = patternPoints.ToArray()
print ('All points in Area Target') for i in range(0,len(areaTargetPoints)): print('Latitude #s Longitude: #s' # (str(areaTargetPoints[i][0]), str(areaTargetPoints[i][1])))
# By using the CommonTasks interface areaTarget.CommonTasks.SetAreaTypeEllipse(85.25, 80.75, 44)
Create a chain (on the current scenario central body)
[Python]
# IAgStkObjectRoot root: STK Object Model Root # Create the Chain on the current scenario central body (use # NewOnCentralBody to specify explicitly the central body) chain = root.CurrentScenario.Children.New(4, 'MyChain') # eChain
# Specify our own time period chain.SetTimePeriodType(2) # eUserSpecifiedTimePeriod
# Get chain time period interface chainUserTimePeriod = chain.TimePeriod chainUserTimePeriod.SetTimePeriod(root.CurrentScenario.StartTime, root.CurrentScenario.StopTime) # Set to scenario period
# Compute the chain chain.ComputeAccess()
Define and compute a chain (basic)
[Python]
# IAgChain chain: Chain object
# Add some objects to chain (using STK path) chain.Objects.Add('Facility/MyFacility') chain.Objects.Add('Satellite/MySatellite')
# Compute the chain chain.ComputeAccess()
Prints the strand intervals of chain object
[Python]
# IAgChain chain: Chain Object # Compute the chain access if not done already. chain.ComputeAccess()
# Considered Start and Stop time print('Chain considered start time: #s' # chain.Vgt.Events.Item('ConsideredStartTime').FindOccurrence().Epoch) print('Chain considered stop time: #s' # chain.Vgt.Events.Item('ConsideredStopTime').FindOccurrence().Epoch)
for i in range(0,intervalListResult.IntervalCollections.Count):
if intervalListResult.IsValid:
print('Link Name: #s' # objectParticipationIntervals.Labels(i+1)) print('--------------') for j in range(0,intervalListResult.IntervalCollections.Item(i).Count):
Create a New CoverageDefinition (on the current scenario central body)
[Python]
# IAgScenario scenario: Scenario object #Create new Coverage Definition and set the Bounds to an area target coverage = scenario.Children.New(7, 'MyCoverage') coverage.Grid.BoundsType = 0 # eBoundsCustomRegions covGrid = coverage.Grid bounds = covGrid.Bounds bounds.AreaTargets.Add('AreaTarget/MyAreaTarget') #Define the Grid Resolution Res = covGrid.Resolution Res.LatLon = .5 #deg #Set the satellite as the Asset coverage.AssetList.Add('Satellite/MySatellite')
# Turn off Show Grid Points coverage.Graphics.Static.IsPointsVisible = False
Extracting Elements from Data Providers with Groups
[Python]
# IAgStkObjectRoot root: STK Object Model root # IAgSatellite satellite: Satellite object # IAgScenario scenario: Scenario object #Change DateFormat dimension to epoch seconds to make the data easier to handle in #Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') satPosDP = satellite.DataProviders.Item('Cartesian Position').Group.Item('ICRF').Exec(scenario.StartTime,scenario.StopTime,60) satx = satPosDP.DataSets.GetDataSetByName('x').GetValues saty = satPosDP.DataSets.GetDataSetByName('y').GetValues satz = satPosDP.DataSets.GetDataSetByName('z').GetValues
satVelDP = satellite.DataProviders.GetDataPrvTimeVarFromPath('Cartesian Velocity/ICRF').Exec(scenario.StartTime,scenario.StopTime,60) #There are 4 Methods to get DP From a Path depending on the kind of DP: # GetDataPrvTimeVarFromPath # GetDataPrvIntervalFromPath # GetDataPrvInfoFromPath # GetDataPrvFixedFromPath satvx = satVelDP.DataSets.GetDataSetByName('x').GetValues satvy = satVelDP.DataSets.GetDataSetByName('y').GetValues satvz = satVelDP.DataSets.GetDataSetByName('z').GetValues
Extracting Elements from Data Providers with PreData
[Python]
# IAgStkObjectRoot root: STK Object Model root # IAgFacility facility: Facility object # IAgScenario scenario: Scenario object #Change DateFormat dimension to epoch seconds to make the data easier to handle in #Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') facChooseDP = facility.DataProviders.Item('Points Choose System') dataProvCenter = facChooseDP.Group.Item('Center') #Choose the referense system you want to report the Center point in dataProvCenter.PreData = 'CentralBody/Earth TOD' rptElems = [ ['Time'],['x'],['y'],['z'] ] results = dataProvCenter.ExecElements(scenario.StartTime, scenario.StopTime, 60, rptElems) datasets = results.DataSets Time = datasets.GetDataSetByName('Time').GetValues facTODx = datasets.GetDataSetByName('x').GetValues facTODy = datasets.GetDataSetByName('y').GetValues facTODz = datasets.GetDataSetByName('z').GetValues
Set the Coverage Interval to an object's availability Analysis interval
# IAgStkObjectRoot root: STK Object Model root # IAgSatellite satellite: Satellite object #Change DateFormat dimension to epoch seconds to make the data easier to handle in #Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') satPassDP = satellite.DataProviders.Item('Precision Passes').ExecSingle(2600) pass = satPassDP.DataSets.GetDataSetByName('Precision Pass Number').GetValues
Getting Data for Specific Points and Elements
[Python]
# IAgStkObjectRoot root: STK Object Model root # IAgSatellite satellite: Satellite object #Change DateFormat dimension to epoch seconds to make the data easier to handle in #Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') times = [ [0],[15000],[20000],[55000] ] elems = [ ['Time'],['Precision Pass Number'] ] satPassesDP = satellite.DataProviders.Item('Precision Passes').ExecSingleElementsArray(times,elems) passes = satPassesDP.GetArray(1)
#Change DateFormat dimension to epoch seconds to make the data easier to handle in #Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') #Get the current scenario scenario = root.CurrentScenario #Set up the access object access = satellite.GetAccessToObject(facility) access.ComputeAccess() #Get the Access Data Provider accessDP = access.DataProviders.Item('Access Data').Exec(scenario.StartTime, scenario.StopTime)
# access_aer = satellite.GetAccessToObject(facility) access_aer.ComputeAccess() --- #STARTTIME, STOPTIME, STEPSIZE is time-varying data and not interval data dp=access_aer.DataProviders.Item('AER Data').Group.Item('Default').Exec(scenario.StartTime, scenario.StopTime, 60) -- azimuth = dp.DataSets.GetDataSetByName('Azimuth').GetValues elevation = dp.DataSets.GetDataSetByName('Elevation').GetValues range = dp.DataSets.GetDataSetByName('Range').GetValues
Using a Time Dependent Data Provider and requesting only specified elements
[Python]
# IAgStkObjectRoot root: STK Object Model root # IAgSatellite satellite: Satellite object # IAgScenario scenario: Scenario object #Change DateFormat dimension to epoch seconds to make the data easier to handle in #Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') elems = [ ['Time'],['q1'],['q2'],['q3'],['q4'] ] satDP = satellite.DataProviders.Item('Attitude Quaternions').ExecElements(scenario.StartTime, scenario.StopTime, 60, elems) #Whenever you pass an index to an array, you need to cast it to a long #equivalent (int32) satTime = satDP.DataSets.Item(0).GetValues satq1 = satDP.DataSets.Item(1).GetValues satq2 = satDP.DataSets.Item(2).GetValues satq3 = satDP.DataSets.Item(3).GetValues satq4 = satDP.DataSets.Item(4).GetValues
track1 = mto.Tracks.AddTrack(1,mtoTimes,mtoLats,mtoLons,mtoAlts) track1.Interpolate = True # Change the color of the track mto.Graphics.Tracks.GetTrackFromId(1).Color = 255
Load MTO track points from file
[Python]
# LoadPoints expects the path an Ephemeris file path # IAgMto mto: MTO Object track2 = mto.Tracks.Add(2) track2.Points.LoadPoints(r'C:\Program Files\AGI\STK_ODTK 13\STK\Help\stktraining\text\EphemerisLLATimePosVel_Example.e') track2.Interpolate = True
# IAgSatellite satellite: Satellite object keplerian = satellite.Propagator.InitialState.Representation.ConvertTo(1) # eOrbitStateClassical, Use the Classical Element interface keplerian.SizeShapeType = 0 # eSizeShapeAltitude, Changes from Ecc/Inc to Perigee/Apogee Altitude keplerian.LocationType = 5 # eLocationTrueAnomaly, Makes sure True Anomaly is being used keplerian.Orientation.AscNodeType = 0 # eAscNodeLAN, Use LAN instead of RAAN for data entry
# Assign the perigee and apogee altitude values: keplerian.SizeShape.PerigeeAltitude = 500 # km keplerian.SizeShape.ApogeeAltitude = 600 # km
# Assign the other desired orbital parameters: keplerian.Orientation.Inclination = 90 # deg keplerian.Orientation.ArgOfPerigee = 12 # deg keplerian.Orientation.AscNode.Value = 24 # deg keplerian.Location.Value = 180 # deg
# Apply the changes made to the satellite's state and propagate: satellite.Propagator.InitialState.Representation.Assign(keplerian) satellite.Propagator.Propagate()
# IAgSatellite satellite: Satellite object satellite.SetPropagatorType(4) # ePropagatorSGP4 propagator = satellite.Propagator propagator.UseScenarioAnalysisTime propagator.CommonTasks.AddSegsFromOnlineSource('25544') # International Space Station propagator.AutoUpdateEnabled = True propagator.Propagate()
Set satellite propagator to SPICE and propagate
[Python]
# IAgSatellite satellite: Satellite object # IAgStkObjectRoot root: STK Object Model Root satellite.SetPropagatorType(5) # ePropagatorSPICE propagator = satellite.propagator propagator.Spice = r'C:\Program Files\AGI\STK_ODTK 13\STK\STKData\Spice\planets.bsp' # Make sure this is a valid path propagator.BodyName = 'MARS'
propagator.StartTime = root.CurrentScenario.StartTime # Set to scenario start time propagator.StopTime = root.CurrentScenario.StopTime# # Set to scenario stop time propagator.Step = 60.0 propagator.Propagate()
# IAgSatellite satellite: Satellite object #Remove all data displays so you can easily pick one that may already be in #the list satellite.VO.DataDisplay.RemoveAll() #Add LLA data display and change size/title datadisplay = satellite.VO.DataDisplay.Add('LLA Position') datadisplay.IsVisible = True datadisplay.FontSize = 1 # eMedium datadisplay.TitleText = 'My Data Display' datadisplay.IsShowNameEnabled = False
# IAgSatellite satellite: Satellite object #Set the contours in the 2D properties contours = satellite.Graphics.ElevContours contours.IsVisible = True contours.NumOfDecimalDigits = 0 contours.Elevations.AddLevelRange(0,90,10) # Min, Max, Step #Turn the contours on in the 3D properties satellite.VO.ElevContours.IsVisible = True
Set 2D/3D Pass Display Properties
[Python]
# IAgSatellite satellite: Satellite object #Display one pass for ground track and orbit on 2D passdata = satellite.Graphics.PassData groundTrack = passdata.GroundTrack groundTrack.SetLeadDataType(5) # eDataOnePass groundTrack.SetTrailSameAsLead orbit = passdata.Orbit orbit.SetLeadDataType(5) # eDataOnePass orbit.SetTrailSameAsLead #Display one orbit pass and no ground track on 3D passdata3D = satellite.VO.Pass.TrackData.PassData groundTrack3D = passdata3D.GroundTrack groundTrack3D.SetLeadDataType(0) # eDataNone groundTrack3D.SetTrailSameAsLead orbit3D = passdata3D.Orbit orbit3D.SetLeadDataType(5) # eDataOnePass orbit3D.SetTrailSameAsLead
Set 2D/3D Range Contours
[Python]
# IAgSatellite satellite: Satellite object #Set a contour level in the 2D properties rangeContours = satellite.Graphics.RangeContours rangeContours.IsVisible = True rangeLevel = rangeContours.LevelAttributes.AddLevel(2000) # km rangeLevel.Color = 16711935 rangeLevel.LineWidth = 4 rangeLevel.LabelAngle = 90 rangeLevel.UserTextVisible = True rangeLevel.UserText = 'Range' #Turn the contours on in the 3D properties satellite.VO.RangeContours.IsVisible = True
# IAgSensor sensor: Sensor object # Change pattern and set sensor.CommonTasks.SetPatternRectangular(20,25) # Change pointing and set sensor.CommonTasks.SetPointingFixedAzEl(90,60,1) # eAzElAboutBoresightRotate # Change location and set sensor.SetLocationType(0) # eSnFixed sensor.LocationData.AssignCartesian(-.0004,-.0004,.004)
# IAgScenario scenario: Scenario object # Create a array of LLA values and interoplate them over the specified # central body positionArray = [ [35.017],[-118.540],[0],[44.570],[-96.474],[ 0],[ 31.101],[-82.619],[0] ] manager = scenario.SceneManager # Interpolate points over great arc interpolator = manager.Initializers.GreatArcInterpolator.InitializeWithCentralBody('Earth') interpolator.Granularity = .1 result = interpolator.Interpolate(positionArray)
# IAgStkObjectRoot root: STK Object Model Root # IAgCrdnProvider vgtSat: Vector Geometry Tool Interface # Change DateFormat dimension to epoch seconds to make the time easier to handle in # Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') timeInstFactory = vgtSat.Events.Factory timeEpoch = timeInstFactory.CreateEventEpoch('FixedTime','Fixed Epoch Time') timeEpoch.Epoch = 3600
Create a new Time Interval
[Python]
# IAgStkObjectRoot root: STK Object Model Root # IAgCrdnProvider vgtSat: Vector Geometry Tool Interface # Change DateFormat dimension to epoch seconds to make the time easier to handle in # Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') timeIntFactory = vgtSat.EventIntervals.Factory timeInterval = timeIntFactory.CreateEventIntervalFixed('TimeInterval','Fixed time interval') timeInterval.SetInterval(60,120)
# IAgSatellite satellite: Satellite object vgtSat = satellite.vgt # Get handle to the Center point on the satellite centerPtSat = vgtSat.Points.Item('Center') # Get handle to the Body Y Vector bodyYSat = vgtSat.Vectors.Item('Body.Y') # Get handle to the Body Axes bodyAxes = vgtSat.Axes.Item('Body') icrfAxes = vgtSat.Axes.Item('ICRF')
Get Times From Defined Time Instant and create an cell array
[Python]
# IAgStkObjectRoot root: STK Object Model Root # IAgCrdnProvider vgtSat: Vector Geometry Tool Interface # Change DateFormat dimension to epoch seconds to make the time easier to handle in # Python root.UnitPreferences.Item('DateFormat').SetCurrentUnit('EpSec') satStart= vgtSat.Events.Item('AvailabilityStartTime') start = satStart.FindOccurrence().Epoch