Python 调用STK接口的常用操作

Python如何调用STK接口编程-CSDN博客这里说的一样,STK Help文档里面其实有讲,但也有不少坑。所以这边整理了一些对Satellite, Target, Aircraft等对象的基本操作:

生成STK场景:

python 复制代码
import pymysql
import win32com

from win32com.client import GetActiveObject
import comtypes
from comtypes.client import CreateObject
from comtypes.gen import STKUtil
from comtypes.gen import STKObjects
from comtypes.gen import AgSTKGraphicsLib
from comtypes.gen import AgSTKVgtLib
from comtypes.gen import AgUiApplicationLib
from comtypes.gen import AgUiCoreLib
from comtypes.gen import stdole
from comtypes.gen import STKObjects

class STKWindow:
    def __init__(self,flag=False):
        if flag==True:
            self.uiApplication = win32com.client.Dispatch('STK11.Application')
            self.uiApplication.Visible = True
            self.uiApplication = CreateObject('STK11.Application')
            self.uiApplication.Visible = True

            # Get our IAgStkObjectRoot interface
            self.root = self.uiApplication.Personality2
        elif flag==False:
            try:
                self.uiApplication=GetActiveObject('STK11.Application')
                self.root = self.uiApplication.Personality2
                self.sc=self.root.CurrentScenario
                self.scIAg=self.sc.QueryInterface(STKObjects.IAgScenario)
            except:
                print("no active STK or Scenario") 
        else:
            self.uiApplication = win32com.client.Dispatch('STK11.Application')
            self.uiApplication.Visible = True
            self.uiApplication = CreateObject('STK11.Application')
            self.uiApplication.Visible = True
            self.root = self.uiApplication.Personality2
            self.root.Load(flag)
            self.sc=self.root.CurrentScenario
            self.scIAg=self.sc.QueryInterface(STKObjects.IAgScenario)
            
    
    def newScenario(self,name,startTime,endTime):
        self.root.NewScenario(name)
        self.sc=self.root.CurrentScenario
        self.scIAg=self.sc.QueryInterface(STKObjects.IAgScenario)
        scIAg.SetTimePeriod(startTime,endTime)
        self.root.Rewind()
        return self.sc

def connect(sql):
    conn = pymysql.connect(host="127.0.0.1",user ="root", passwd ="123456", db = "task scheduling", port=3306,charset = 'utf8')
    cur =conn.cursor() 
    cur.execute(sql)
    if sql.strip()[:6].upper()=='SELECT':
        res=cur.fetchall()
    else:
        coon.commit()
        res='ok'
    cur.close()
    conn.close()
    return res

Spacecraft:

python 复制代码
class Spacecraft:
    def __init__(self,name,Type='',Time='1 Jan 2020 00:00:00.000',revolve=10,inclination=0,RAAN=0,argumentOfPerigee=0,eccentricity=0,MeanAnomaly=0):
        self.name=name
        self.Type=Type
        self.Time=Time
        self.revolve=revolve
        self.inclination=inclination
        self.RAAN=RAAN
        self.argumentOfPerigee=argumentOfPerigee
        self.eccentricity=eccentricity
        self.MeanAnomaly=MeanAnomaly
        self.uniqueNumber=18
        self.cmds=[]
        self.cmds.append('New / */Satellite %s' %name)
        self.cmds.append('New / */Satellite %s' %name)
        
    def queryFromSecenario(self,sc):
        try:
            sats=sc.Children.GetElements(self.uniqueNumber)
            sat=sats.Item(self.name)
            return sat
        except:
            return None
    
    def deleteFromSecenario(self,sc):
        if self.queryFromSecenario(sc):
            sc.Children.Unload(self.uniqueNumber,self.name)
            return 'already deleted'
        else:
            return 'not exist'
        
    def addToScenario(self,root,sc):
        if self.queryFromSecenario(sc):
#             'can not add, this name already exists'
            return None
        sat=sc.Children.New(self.uniqueNumber, self.name) # eSatellite 
        satIAg= sat.QueryInterface(STKObjects.IAgSatellite)
        satIAg.PropagatorSupportedTypes
        satIAg.SetPropagatorType(STKObjects.ePropagatorJ4Perturbation)
        satProp = satIAg.Propagator
        satProp=satProp.QueryInterface(STKObjects.IAgVePropagatorJ4Perturbation)
        
        satProp.InitialState.Epoch=self.Time
        
        keplerian = satProp.InitialState.Representation.ConvertTo(STKUtil.eOrbitStateClassical)
        keplerian2 = keplerian.QueryInterface(STKObjects.IAgOrbitStateClassical)
        keplerian2.SizeShapeType =STKObjects.eSizeShapeMeanMotion
#         keplerian2.SizeShapeType =STKObjects.eSizeShapeSemimajorAxis
        keplerian2.LocationType = STKObjects.eLocationMeanAnomaly
        keplerian2.Orientation.AscNodeType = STKObjects.eAscNodeRAAN
        root.UnitPreferences.Item('AngleUnit').SetCurrentUnit('revs')
        root.UnitPreferences.Item('TimeUnit').SetCurrentUnit('day')
        root.UnitPreferences.Item('Distance').SetCurrentUnit('km')
        print(keplerian2.SizeShape)
        keplerian2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeMeanMotion).MeanMotion = self.revolve
        keplerian2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeMeanMotion).Eccentricity = self.eccentricity
#         keplerian2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeSemimajorAxis).SemimajorAxis = self.SemimajorAxis
#         keplerian2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeSemimajorAxis).Eccentricity = self.Eccentricity
        root.UnitPreferences.Item('AngleUnit').SetCurrentUnit('deg')
        root.UnitPreferences.Item('TimeUnit').SetCurrentUnit('sec')
        keplerian2.Orientation.Inclination = self.inclination
        keplerian2.Orientation.ArgOfPerigee = self.argumentOfPerigee
        keplerian2.Orientation.AscNode.QueryInterface(STKObjects.IAgOrientationAscNodeRAAN).Value = self.RAAN
        keplerian2.Location.QueryInterface(STKObjects.IAgClassicalLocationMeanAnomaly).Value = self.MeanAnomaly
        satProp.InitialState.Representation.Assign(keplerian)
        satProp.Propagate()
        self.sat=sat
        self.satIAg=satIAg
        return satIAg

Target:

python 复制代码
class Target:
    def __init__(self,name,Longitude=0,Latitude=0,Altitude=0):
        self.name=name
        self.Longitude=Longitude
        self.Latitude=Latitude
        self.Altitude=Altitude
        self.uniqueNumber=23
        
    def queryFromSecenario(self,sc):
        try:
            targets=sc.Children.GetElements(self.uniqueNumber)
            target=targets.Item(self.name)
            return target
        except:
            return None
        
    def deleteFromSecenario(self,sc):
        if self.queryFromSecenario(sc):
            sc.Children.Unload(self.uniqueNumber,self.name)
            return 'already deleted'
        else:
            return 'not exist'
    
    def addToScenario(self,sc):
        if self.queryFromSecenario(sc):
#             'can not add, this name already exists'
            return None
        target = sc.Children.New(self.uniqueNumber, self.name) 
        targetIAg = target.QueryInterface(STKObjects.IAgTarget)
        pos = targetIAg.Position
        pos.AssignGeodetic(self.Latitude,self.Longitude,self.Altitude)
        self.targetIAg=targetIAg
        self.target=target
        return targetIAg

Aircraft:

python 复制代码
class Aircraft:
    def __init__(self,name):
        self.name=name
        self.uniqueNumber=1
        
    def queryFromSecenario(self,sc):
        try:
            aircrafts=sc.Children.GetElements(self.uniqueNumber)
            aircraft=aircrafts.Item(self.name)
            return aircraft
        except:
            return None
        
    def deleteFromSecenario(self,sc):
        if self.queryFromSecenario(sc):
            sc.Children.Unload(self.uniqueNumber,self.name)
            return 'already deleted'
        else:
            return 'not exist'
    
    def addToScenario(self,sc):
        if self.queryFromSecenario(sc):
#             'can not add, this name already exists'
            return None
        aircraft = sc.Children.New(self.uniqueNumber, self.name) 
        aircraftIAg = aircraft.QueryInterface(STKObjects.IAgAircraft)
        self.aircraftIAg=aircraftIAg
        self.aircraft=aircraft
        return aircraftIAg
    
    def addWayPoints(self,points):
        self.aircraftIAg.SetRouteType(STKObjects.ePropagatorGreatArc)
        route = self.aircraftIAg.Route
        route = route.QueryInterface(STKObjects.IAgVePropagatorGreatArc)
        route.Method=STKObjects.AgEVeWayPtCompMethod(0)
        
        try:
            for point in points:
                waypoint = route.Waypoints.Add()
                waypoint.Longitude = point[0]
                waypoint.Latitude = point[1]
                waypoint.Altitude = point[2]
                waypoint.Speed=point[3]

            route.Propagate()
            return 'add waypoints successfully'
        except:
            return 'add waypoints unsuccessfully'
    
    def removeWayPoints(self):
        self.aircraftIAg.SetRouteType(STKObjects.ePropagatorGreatArc)
        route = self.aircraftIAg.Route
        route = route.QueryInterface(STKObjects.IAgVePropagatorGreatArc)
        route.Waypoints.RemoveAll()
            
        route.Propagate()

Ship:

python 复制代码
class Ship:
    def __init__(self,name):
        self.name=name
        self.uniqueNumber=21
        
    def queryFromSecenario(self,sc):
        try:
            ships=sc.Children.GetElements(self.uniqueNumber)
            ship=ships.Item(self.name)
            return ship
        except:
            return None
        
    def deleteFromSecenario(self,sc):
        if self.queryFromSecenario(sc):
            sc.Children.Unload(self.uniqueNumber,self.name)
            return 'already deleted'
        else:
            return 'not exist'
    
    def addToScenario(self,sc):
        if self.queryFromSecenario(sc):
#             'can not add, this name already exists'
            return None
        ship = sc.Children.New(self.uniqueNumber, self.name) 
        shipIAg = ship.QueryInterface(STKObjects.IAgShip)
        self.shipIAg=shipIAg
        self.ship=ship
        return shipIAg
    
    def addWayPoints(self,points):
        self.shipIAg.SetRouteType(STKObjects.ePropagatorGreatArc)
        route = self.shipIAg.Route
        route = route.QueryInterface(STKObjects.IAgVePropagatorGreatArc)
        route.Method=STKObjects.AgEVeWayPtCompMethod(0)
        
        try:
            for point in points:
                waypoint = route.Waypoints.Add()
                waypoint.Longitude = point[0]
                waypoint.Latitude = point[1]
                waypoint.Altitude = point[2]
                waypoint.Speed=point[3]

            route.Propagate()
            return 'add waypoints successfully'
        except:
            return 'add waypoints unsuccessfully'
    
    def removeWayPoints(self):
        self.shipIAg.SetRouteType(STKObjects.ePropagatorGreatArc)
        route = self.shipIAg.Route
        route = route.QueryInterface(STKObjects.IAgVePropagatorGreatArc)
        route.Waypoints.RemoveAll()
            
        route.Propagate()

获取可见性:

python 复制代码
def addAccess(Monitor,Monitored):
    Monitor=Monitor.QueryInterface(STKObjects.IAgStkObject)
    Monitored=Monitored.QueryInterface(STKObjects.IAgStkObject)
    access = Monitor.GetAccessToObject(Monitored)
    access.ComputeAccess()
    results = access.ComputedAccessIntervalTimes
    results=results.ToArray(0,results.Count)
    return results

使用示例:

python 复制代码
def addAccess(Monitor,Monitored):
    Monitor=Monitor.QueryInterface(STKObjects.IAgStkObject)
    Monitored=Monitored.QueryInterface(STKObjects.IAgStkObject)
    access = Monitor.GetAccessToObject(Monitored)
    access.ComputeAccess()
    results = access.ComputedAccessIntervalTimes
    results=results.ToArray(0,results.Count)
    return results

# open STK and creat Scenario
STKW=STKWindow('E:/AGI/STKFiles/test1/test1.sc')
sc=STKW.newScenario('test1',"1 Jan 2020 00:00:00.000 ","8 Jan 2020 00:00:00.000 ")


# select satellites from datebase
sql="select name,type,time,revolve,inclination,RAAN,argumentOfPerigee,eccentricity,MeanAnomaly from spacecraft"
sat=connect(sql)[0]
# (self,name,Type,Time,revolve=10,inclination=0,RAAN=0,argumentOfPerigee=0,eccentricity=0,MeanAnomaly=0):
sat=Spacecraft(sat[0],sat[1],sat[2],sat[3],sat[4],sat[5],sat[6],sat[7],sat[8])

sql='select name,Longitude,Latitude,Altitude from Target'
target=connect(sql)[0]
target=Target(target[0],target[1],target[2],target[3])


# new satellite and Target
addSat=sat.addToScenario(STKW.root,STKW.sc)
addTarget=target.addToScenario(STKW.sc)


# sat.deleteFromSecenario(STKW.sc)
# target.deleteFromSecenario(STKW.sc)


#add access
accessTimes=addAccess(sat.satIAg,target.targetIAg)
for accessTime in accessTimes:
    print(accessTime)
# sats = STKW.root.CurrentScenario.Children.GetElements(18)

# print(type(sats.Item('satellite1')),type(sat.satIAg))



aircraft=Aircraft('aircraft1')
aircraft.addToScenario(STKW.sc)

sql="select Longitude,Latitude,Altitude,Speed from aircraft"
waypoints=connect(sql)
aircraft.addWayPoints(waypoints)



ship=Ship('ship1')
ship.addToScenario(STKW.sc)

sql="select Longitude,Latitude,Altitude,Speed from ship"
waypoints=connect(sql)
for point in waypoints:
    print(point[0])
ship.addWayPoints(waypoints)


STKW.root.SaveAs('E:/AGI/STKFiles/test1/test1')



ship = sc.Children.New(21, 'ship1') 
shipIAg = ship.QueryInterface(STKObjects.IAgShip)
shipIAg.SetRouteType(STKObjects.ePropagatorGreatArc)
route = shipIAg.Route
route = route.QueryInterface(STKObjects.IAgVePropagatorGreatArc)
route.Method=STKObjects.AgEVeWayPtCompMethod(0)

waypoint1 = route.Waypoints.Add()
waypoint1.Latitude = 39
waypoint1.Longitude = -79
waypoint1.Altitude = 10
waypoint1.Speed=0.001

waypoint2 = route.Waypoints.Add()
waypoint2.Latitude = 40
waypoint2.Longitude = -80
waypoint2.Altitude = 10
waypoint2.Speed=0.001

waypoint3 = route.Waypoints.Add()
waypoint3.Latitude = 41
waypoint3.Longitude = -81
waypoint3.Altitude = 10
waypoint3.Speed=0.001

route.Propagate()
相关推荐
花酒锄作田12 小时前
Pydantic校验配置文件
python
hboot13 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python