def ImportFacilities(STKVersion, filepath): # ImportFacilities attaches to an open instance of STK and imports position data # from an Excel spreadsheet. Inputs include STK whole number version as an # integer and Excel file path. Units are assumed to be degrees and meters with a # header row in the Excel file for ID, LAT, LON, ALT. This function requires the # pandas Python library. # # Example: ImportFacilities(12, 'GroundSites.xlsx') import pandas as pd from comtypes.client import GetActiveObject # Grab a running instance of STK uiApplication = GetActiveObject(f'STK{STKVersion}.Application') root = uiApplication.Personality2 from comtypes.gen import STKObjects # Grab current scenario scenario = root.CurrentScenario uiApplication.Visible = True uiApplication.UserControl = True scenario2 = scenario.QueryInterface(STKObjects.IAgScenario) # Change the latitude and longitude to degrees root.UnitPreferences.Item('Latitude').SetCurrentUnit('deg') root.UnitPreferences.Item('Longitude').SetCurrentUnit('deg') # Change the distance to meters root.UnitPreferences.SetCurrentUnit('Distance', 'm') # Use pandas to read in excel sheet as a dataframe df = pd.read_excel(filepath) # Iterate through each row for i, row in df.iterrows(): facName = row['ID'] lat = row['LAT'] lon = row['LON'] alt = row['ALT'] type(facName) # There cannot be two objects with the same name in STK, so # if there is already a facility with the same name, delete it. if scenario.Children.Contains(STKObjects.eFacility, facName): obj = scenario.Children.Item(facName) obj.Unload() # Create the facility with the name listed in the excel sheet fac = scenario.Children.New(STKObjects.eFacility, facName) fac2 = fac.QueryInterface(STKObjects.IAgFacility) # Choose to not use terrain fac2.UseTerrain = False # Set the latitude, longitude, and altitude fac2.Position.AssignGeodetic(row['LAT'], row['LON'], row['ALT'])
def loadSats(df, maxSats=100, maxDur=100): # Load satellites try: app = GetActiveObject('STK11.Application') root = app.Personality2 except: app = CreateObject('STK11.Application') app.Visible = True app.UserControl = True root = app.Personality2 root.NewScenario('LifeTimeRuns') root.UnitPreferences.SetCurrentUnit('DateFormat', 'EpDay') sc = root.CurrentScenario # Color by Lifetime colors = ((df['LT Years'] - 0) * (1 / (maxDur - 0) * 255)).astype('uint8') colorsInt = [] for ii in range(len(colors)): colorsInt.append( int( '00' + "{0:#0{1}x}".format(colors.iloc[ii], 4)[2:] + "{0:#0{1}x}".format(255 - colors.iloc[ii], 4)[2:], 16)) # Loop through the df if len(df) <= maxSats: for ii in range(len(df)): satName = str(int(df['Run ID'].iloc[ii])) if sc.Children.Contains(STKObjects.eSatellite, satName) == False: sat = sc.Children.New(STKObjects.eSatellite, satName) sat2 = sat.QueryInterface(STKObjects.IAgSatellite) else: sat = root.GetObjectFromPath('Satellite/' + satName) sat2 = sat.QueryInterface(STKObjects.IAgSatellite) graphics = sat2.Graphics.Attributes.QueryInterface( STKObjects.IAgVeGfxAttributesBasic) graphics.Color = colorsInt[ii] prop = sat2.SetPropagatorType(STKObjects.ePropagatorJ4Perturbation) prop = sat2.Propagator.QueryInterface( STKObjects.IAgVePropagatorJ4Perturbation) prop.UseScenarioAnalysisTime = False prop.InitialState.Epoch = root.ConversionUtility.ConvertDate( 'YYDDD', 'EpDay', str(df['epoch'].iloc[ii])) prop.InitialState.Representation.AssignCartesian( STKUtil.eCoordinateSystemICRF, df['x'].iloc[ii], df['y'].iloc[ii], df['z'].iloc[ii], df['Vx'].iloc[ii], df['Vy'].iloc[ii], df['Vz'].iloc[ii]) prop.Step = 600 prop.StopTime = 1 prop.Propagate() else: print('Number of satellites is too large, ' + str(len(df)) + '. Please reduce the number of satellites to beneath ' + str(maxSats))
def STKMagGeneration(self, nameSat, dataStepSize): # Imports import comtypes from comtypes.client import GetActiveObject # Getting Open STK Application app = GetActiveObject("STK11.Application") app.Visible = True app.UserControl = True root = app.Personality2 from comtypes.gen import STKObjects # Getting Current STK Scenario sc = root.CurrentScenario sc2 = sc.QueryInterface(STKObjects.IAgScenario) root.Rewind() # Getting Satellite from STK sat = sc.Children.Item(nameSat) # Magnetic Field Data for the Satellite rptElements = ['Time', 'x', 'y', 'z'] magfieldWMMTimeVar = sat.DataProviders.GetDataPrvTimeVarFromPath( "Vectors(VNC)//MagField(WMM)") magResults = magfieldWMMTimeVar.ExecElements(sc2.StartTime, sc2.StopTime, dataStepSize, rptElements) #magtime=magResults.DataSets.Item(0).GetValues() magx = magResults.DataSets.Item(1).GetValues() magy = magResults.DataSets.Item(2).GetValues() magz = magResults.DataSets.Item(3).GetValues() # Exporting Magnetic Field Data to a CSV File csvFileName = sc.InstanceName + '_MagFieldData.csv' #rowColumnTitle = ['Mag x (nT)', 'Mag y (nT)', 'Mag z (nT)'] rowColumnTitle = ['x (nT)', 'y (nT)', 'z (nT)'] with open(csvFileName, "w", newline='') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(rowColumnTitle) for i, value in enumerate(magx): magxcurr = magx[i] magycurr = magy[i] magzcurr = magz[i] rowcurr = [str(magxcurr), str(magycurr), str(magzcurr)] filewriter.writerow(rowcurr) return csvFileName
def FilterObjectsByType(objType, name=''): from comtypes.client import GetActiveObject # Attach to STK app = GetActiveObject('STK11.Application') root = app.Personality2 # Send objects to an xml xml = root.AllInstanceNamesToXML() # split the xml by object paths objs = xml.split('path=') objs = objs[1:] # remove first string of '<' # Loop through each object and parse by object path objPaths = [] for i in range(len(objs)): obji = objs[i].split('"') objiPath = obji[1] # the 2nd string is the file path objiSplit = objiPath.split('/') objiClass = objiSplit[-2] objiName = objiSplit[-1] if objiClass.lower() == objType.lower(): if name.lower() in objiName.lower(): objPaths.append(objiPath) return objPaths
def get_stk(self): try: uiApp = GetActiveObject('STK11.Application') self.root = uiApp.Personality2 except Exception as e: print(e)
def StartSTK(): try: uiApp = GetActiveObject('STK12.Application') stkRoot = uiApp.Personality2 checkEmpty = stkRoot.Children.Count if checkEmpty == 0: uiApp.visible = 1 uiApp.userControl = 1 stkRoot.NewScenario('AviatorParametricDemo') scenario = stkRoot.CurrentScenario.QueryInterface( STKObjects.IAgScenario) else: ## Implement checking to see if I should close the scenario pass except: uiApp = CreateObject('STK12.Application') stkRoot = uiApp.Personality2 uiApp.visible = 1 uiApp.userControl = 1 stkRoot.NewScenario('AviatorParametricDemo') scenario = stkRoot.CurrentScenario.QueryInterface( STKObjects.IAgScenario) stkRoot.UnitPreferences.SetCurrentUnit('DateFormat', 'EpHr') return stkRoot
def ConnectToSTK(version=12,scenarioPath = cwd+'\\ConstellationWizardExampleScenario',scenarioName='ConstellationAnalysis'): # Launch or connect to STK try: app = GetActiveObject('STK{}.Application'.format(version)) root = app.Personality2 root.Isolate() except: app = CreateObject('STK{}.Application'.format(version)) app.Visible = True app.UserControl= True root = app.Personality2 root.Isolate() try: root.LoadScenario(scenarioPath+'\\'+scenarioName+'.sc') except: root.NewScenario(scenarioName) root.UnitPreferences.SetCurrentUnit('DateFormat','Epsec') root.ExecuteCommand('Units_SetConnect / Date "Epsec"') return root
def run(self): try: self.psapp = GetActiveObject("Photoshop.Application") # We don't want any Photoshop dialogs displayed during automated execution psDisplayNoDialogs = 3 # from enum PsDialogModes self.psapp.displayDialogs = psDisplayNoDialogs psAutomatic = 8 # from enum PsResampleMethod psPreserveDetails = 9 # from enum PsResampleMethod psBicubicSmoother = 6 # from enum PsResampleMethod psBicubicSharper = 5 # from enum PsResampleMethod psBicubicAutomatic = 7 # from enum PsResampleMethod psNearestNeighbor = 2 # from enum PsResampleMethod psBilinear = 3 # from enum PsResampleMethod psBicubic = 4 # from enum PsResampleMethod psNoResampling = 1 # from enum PsResampleMethod for file in self.filestoprocess: print("thread: " + file) docRef = self.psapp.Open(file) # if height is given, don't maintain aspect ratio if int(self.in_height) > 0: docRef.ResizeImage(self.in_width, self.in_height, None, psAutomatic) # time.sleep(3) # maintain aspect ratio else: doc_width = docRef.Width doc_height = docRef.Height # maintain aspect ratio new_height = (doc_height / doc_width) * self.in_width docRef.ResizeImage(self.in_width, new_height, None, psAutomatic) docRef.Save() docRef.Close() # to prevent application busy COM error time.sleep(1) except Exception as thread_err: print(thread_err)
def _make_COM(prog_id, allow_reuse=True): """ Create or get Windows COM object. Try to reuse an existing instance before creating a new one. """ com_object = None reuse_failed = False if allow_reuse: try: com_object = GetActiveObject(prog_id) except OSError: reuse_failed = True if not allow_reuse or reuse_failed: com_object = CreateObject(prog_id) return com_object
def filter_objects_by_type(objectType, name=''): # Returns a list of paths for the specified object type optionally filtered by a name string""" app = GetActiveObject('STK12.Application') root = app.Personality2 xml = root.AllInstanceNamesToXML() objs = xml.split('path=') objs = objs[1:] # remove first string of '<' objPaths = [] for i in range(len(objs)): obji = objs[i].split('"') objiPath = obji[1] # the 2nd string is the file path objiSplit = objiPath.split('/') objiClass = objiSplit[-2] objiName = objiSplit[-1] if objiClass.lower() == objectType.lower(): if name.lower() in objiName.lower(): objPaths.append(objiPath) return objPaths
msgbox("Les descros sont entrain d'être générés, une fenêtre va bientôt apparaître") detach(msgwait) TXT = "" for PA in RESULTS: TRs_all = RESULTS[PA]['TRs_all'] NRO = RESULTS[PA]['NRO'] PMZ_PT = RESULTS[PA]['PMZ_PT'] PA_PT = RESULTS[PA]['PA_PT'] CH = RESULTS[PA]['CH'] ADRESSE1 = RESULTS[PA]['ADRESSE1'] ADRESSE2 = RESULTS[PA]['ADRESSE2'] DATE = RESULTS[PA]['DATE'] try: Word = GetActiveObject("Word.Application") except: Word = CreateObject("Word.Application") Word.Display = False TXT = TXT + "\nRESEAU FTTH " + NRO + "\n" \ + "PMZ/PT" + PMZ_PT + "\n" \ + "PA/PT" + PA_PT + "\n" \ + "CH " + CH + "\n" \ + "ADRESSE: " + ADRESSE1 + "\n\n" pp(TRs_all) for TRs in TRs_all: for TR in TRs: file_name = TRs[TR]['maxPT'] type_cable = TR
STKObjects.IAgClassicalSizeShapeSemimajorAxis).Eccentricity = a2 # degrees 倾角 keplerian.Orientation.Inclination = a3 # degrees 近地点 keplerian.Orientation.ArgOfPerigee = a4 # RANN 设置轨道位置 keplerian.Orientation.AscNode.QueryInterface( STKObjects.IAgOrientationAscNodeRAAN).Value = a5 # 设置卫星在该轨道中的“相位” keplerian.Location.QueryInterface( STKObjects.IAgClassicalLocationTrueAnomaly).Value = a6 startTime = time.time() # init uiApplication = GetActiveObject('STK10.Application') uiApplication.Visible = False root = uiApplication.Personality2 sc = root.CurrentScenario sc2 = sc.QueryInterface(STKObjects.IAgScenario) # 获取星座 constellationTemp = sc.Children.Item('satellites') constellation = constellationTemp.QueryInterface(STKObjects.IAgConstellation) # 获取赤道、南极、月背点 chidaoTemp = sc.Children.Item('chidao') chidao = chidaoTemp.QueryInterface(STKObjects.IAgPlace) yuebeiTemp = sc.Children.Item('yuebei') yuebei = chidaoTemp.QueryInterface(STKObjects.IAgPlace) nanjiTemp = sc.Children.Item('nanji')
print('Initializing') #cwd = os.getcwd() input() objPath = sys.argv[1] print('Object Path: ' + sys.argv[1]) #print(sys.argv[2]) #print(sys.argv[3]) satName ='' deckAccessFile = 'C:\\GitHub\\EngineeringLab\\OperatorsToolBox\\Stk12.OperatorsToolBox\\Plugin Files'+'\\deckAccessRpt.txt' deckAccessTLE = 'C:\\GitHub\\EngineeringLab\\OperatorsToolBox\\Stk12.OperatorsToolBox\\Plugin Files'+'\\deckAccessTLE.tce' stkVersion = '12' # Launch or connect to STK try: app = GetActiveObject('STK{}.Application'.format(stkVersion)) root = app.Personality2 # app.Visible = True # app.UserControl= True except: print('Error connecting to the scenario') input("Press Key to exit") # Set the scenario time period sc = root.CurrentScenario sc2 = sc.QueryInterface(STKObjects.IAgScenario) #sc2.Animation.AnimStepValue = 30 # Set the animation time to be the same as the MTO data resolution # Turn on Antialiasing for better visualization. Options are: Off,FXAA,2,3,4 cmd = 'SoftVtr3d * AntiAlias 2' root.ExecuteCommand(cmd)
# -*- coding: utf-8 -*- """ Created on Tue Jan 12 12:52:59 2021 @author: Jackson Artis """ # Import necessary modules from comtypes.client import GetActiveObject from comtypes.gen import STKObjects from comtypes.gen import AgSTKVgtLib # Grab STK Instance app = GetActiveObject('STK12.Application') root = app.Personality2 scenario = root.CurrentScenario scenario2 = scenario.QueryInterface(STKObjects.IAgScenario) # Store scenario specific variables northFacName = 'Facility1' southFacName = 'Facility2' satName = 'Satellite1' desiredMaxAngle = 5 # Grab hold of object references and paths sat = scenario.Children.Item(satName) satellite = sat.QueryInterface(STKObjects.IAgSatellite) fac1 = scenario.Children.Item(northFacName) fac2 = scenario.Children.Item(southFacName) satPath = sat.Path
def process(PA): global ActiveWindow, Shapes, Word, TRs_all, xl, Visio global RESULTS # Bien gérer les erreurs try: # ouvrir le fichier excel et faire les initialisations de coutume xl = CreateObject("Excel.application") xl.Visible = False xl.DisplayAlerts = False PA_wb = xl.Workbooks.Open(PA) PA_wb.Sheets("synoptique-bilan µmodules").Select() # dans la sheet visée, détecter tout les objets OLE (qui seront # normalement tous des déssins visio) OLEObjects = PA_wb.Sheets("synoptique-bilan µmodules").OLEObjects() # pour chaque déssin ... for OLEObject in OLEObjects: # l'ouvrir dans Visio OLEObject.Verb(2) # prendre la main sur la fenêtre visio ouverte Visio = GetActiveObject("Visio.Application") # Visio.Visible = False Visio.DisplayAlerts = False ActiveWindow = Visio.ActiveWindow Page = ActiveWindow.Page Shapes = Page.Shapes # Ceci est pour les déssins plutôt compliqués, après chaque sélection des PB, le script # les affichera et demandra de confirmer si c'est bon ou non msg = "Voulez confirmer le nombre de PBs après chaque sélection?\n" \ + "(si c'est plan assez complexe mieux vaut répondre par oui)" yn = ynbox(msg) # allons-y! # On extrait d'abord les infos d'entête for shape in Shapes: text = shape.Text if text.startswith('NRO'): bloc_NRO = text elif text.startswith('PT'): # certaines shapes buguent je ne sais pas pourquoi, elles n'ont pas d'utilité try: blocs_PT.append(shape) except: blocs_PT = [shape] elif text.startswith('PA'): bloc_PA = text # On extrait la position x du PA pour prendre toutes les TR qui sont à droite PA_posx = get_XY(shape)[0] # Les deux blocs FI et PA tout deux commencent par PT, celui de PA est plus à gauche # on les différenciera par leur position if get_XY(blocs_PT[0])[0] < get_XY(blocs_PT[1])[0]: FI_bloc = blocs_PT[0] PA_bloc = blocs_PT[1] else: FI_bloc = blocs_PT[1] PA_bloc = blocs_PT[0] PA_PT = PA_bloc.Text.rsplit('\n')[0].replace('PT: ', '') PMZ_PT = FI_bloc.Text.rsplit('\n')[0].replace('PT: ', '') CH = PA_bloc.Text.rsplit('\n')[2].replace('CH: ', '') NRO = extract('NRO/PMZ/PA', bloc_NRO, 'NRO') ADRESSE1 = ' '.join(PA_bloc.Text.rsplit('\n')[3:5])\ .replace('Adresse: ', '') ADRESSE2 = ADRESSE1.rsplit('-')[0] # Les TRs du déssin courant TRs = {} # là ça va barder! for shape in Shapes: if shape.Text.startswith('TR'): # Seulement ceux qui sont plus à droite de PA if get_XY(shape)[0] > PA_posx: # Le text est un peu bizarre, il est vraiment en texte mais paraît être un # bytes! On doit le nettoyer TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '') # Extraire ne TR TR = TR_TXT.rsplit('FO')[0] \ .replace('\\n', ' ') + 'FO' # Si ce n'est pas un TR valide, passer if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR): continue # Si ce TR n'a pas encore été enregistré dans la liste TRs, l'enregistrer ## Initialiser la longueur à 0 ## Mettre le shape courant dans la liste "shapes" ## Initialiser une liste vide pour les CH ou IMB ou AP qui vont avec ## Initialiser une liste vide pour les PTs qui vont avec (pour le nommage) ## Et initialiser une variable "0" pour le PT qui est maximum (pour le nommage) if TR not in TRs: TRs[TR] = { 'LONG': 0, 'SHAPES': [shape.ID], 'CH/IMB/AP': [], 'PTs': [], 'maxPT': 0 } # Sinon si le TR est déjà dans TRs, ajouter le shape courant à "SHAPES" else: TRs[TR]['SHAPES'].append(shape.ID) # Essayer d'extraire la longueur du TR courant try: TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \ .replace('m', '')) except: TR_LONG = 0 # Et incrémenter la longueur du TR global corréspondant à cette ligne TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG # Message pour que l'utilisateur sélectionner les blocs PB pour chaque TR title1 = 'Sélectionnez les bloc' title2 = 'Confirmez la sélection' # Pour chaque TR dans TRs for TR in TRs: # Python n'a pas de "REDO", on hack avec un "WHILE" while True: # Sélectionner toutes les shapes de cette ligne de TR SelectShapes(TRs[TR]['SHAPES']) # Demander lui de sélectionner, quand il confirme continuer... if ccbox(TR, title1): # Une liste vide pour tout les PB dans ce TR CH_OR_IMB_OR_AP_all = [] # Une liste vide pour tout les PTs dans ce TR PTs = [] # Une liste vide pour tout les PBs dans ce TR PBs = [] # Un message au cas où l'utilisateur aurait choisit une confirmation msg = "Pour " + TR + "\nVous avez sélectionné:\n" # Le nombre de PBs sélectionnées (pour affichage dans la confirmation) selected_PBs = 0 # Au cas où il n'y aurait pas de PB valide, pas la peine de mettre une # fenêtre de confirmation, supposer tout de même qu'il y'en a ... yn_yes = True # Pour chaque fenêtre sélectionnée for selected in ActiveWindow.Selection: # (certains shapes n'aiment pas qu'on appelle leur .Text!!!!) try: TEXT = str(selected.Text) # Prendre seulement les blocs qui commencent par "PB" if not TEXT.startswith('PB'): continue # Incrémenter le nombre de PBs trouvés par +1 selected_PBs = selected_PBs + 1 # Enregister le PB, PT, l'adresse, et le text qui peut être un: ## Ch.XXXXX ## IMB/XXXXX/XXXX ## AP XXXX PB = TEXT.rsplit('\n')[0].rstrip() PT = TEXT.rsplit('\n')[2] ADR = TEXT.rsplit('\n')[3] CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4] # Si l'un de ces lignes ne se trouve pas à la bonne place if (not CH_OR_IMB_OR_AP.startswith('AP ') and not CH_OR_IMB_OR_AP.startswith('Ch.') and not CH_OR_IMB_OR_AP.startswith('IMB')): # Resélectionner les sélectionnés (pfff sert à rien ça!) SelectShapes([selected.ID]) # Et dire qu'il y a un truc qui cloche! msgbox("T'as surement encore fais une connerie dans tes" + "déssins, regarde ce bloc dans la ligne PT!\n" + "Je devrais trouver Ch.XXXX ou AP XXXX" + "ou IMB/XXXX/XXX mais j'ai trouvé\n" + CH_OR_IMB_OR_AP + "\n" + "Quand t'auras détécté l'erreur click sur OK") # Continuer ou quitter! cont = boolbox("Dois-je continuer ou fermer?", "Que faire?", ['Continuer?', 'Fermer?']) if not cont: exit(0) else: pass else: # Sinon, préparer le message de confirmation msg = msg + "- " + CH_OR_IMB_OR_AP + "\n" # Et ajouter le CH/IMB/AP à la liste CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP]) # Ajouter le PT de ce bloc à la liste PTs PTs.append(int(PT.replace('PT', ''))) # Ajouter le PB de ce bloc à la liste PBs PBs.append(PB) except: # Si quelque chose cloche, trouver une porte de sortie!!: SelectShapes([selected.ID]) msgbox("T'as surement encore fais une connerie dans tes" + "déssins, regarde ce bloc dans la ligne PT!\n" + "Quand t'auras détécté l'erreur click sur OK") cont = boolbox("Dois-je continuer ou fermer?", "Que faire?", ['Continuer?', 'Fermer?']) # Vraiment je ne sais pas à quoi sert ce que j'ai écrit dans les # 8 prochaines lignes!!!! if not cont: exit(0) else: msg = msg + "(RIEN!)" CH_OR_IMB_OR_AP_all = [] PTs = [] PBs = [] yn_yes = False # S'il n'a rien sélectionné if not selected_PBs: cont = boolbox("Tu n'as rien sélectionné! Tu confirmes" + " que ce n'est pas une connerie?", "Sélection vide!", ['Oui vas-y', 'Comme d\'hab! Une connerie']) # Soit on quitte! if cont: break # Soit c'est délibéré et on continue else: continue # Si l'utilisateur avait demandé une confirmation, la montrer # (S'il y a eu une erreur, yn_yes est False, et pas la peine de montrer la # confirmation) if yn and yn_yes: msg = msg + "(" + str(selected_PBs) + " sélectionnés)" conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?']) if conf: # Si c'est confirmé, stocher ces données pour le shape TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all TRs[TR]['PTs'] = PTs TRs[TR]['PBs'] = PBs break else: pass # Sinon s'il n'avait pas demandé de confirmation, stocker ces données # directement pour le shape else: TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all TRs[TR]['PTs'] = PTs TRs[TR]['PBs'] = PBs break # En cas d'erreur sortir :-( else: exit(0) # Il doit y avoir au moins un PT pour créer un fichier doc et xls avec le max des TRs if len(TRs[TR]['PTs']): TRs[TR]['DE_filename'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc' TRs[TR]['AR_filename'] = 'AR_PT%06d' % max(TRs[TR]['PTs']) + '.xls' # Les fichiers avec ce nom ne devront jamais voir le jour! else: TRs[TR]['DE_filename'] = 'je_ne_suis_pas_cense_exister.doc' TRs[TR]['AR_filename'] = 'je_ne_suis_pas_cense_exister.xls' # Un cas très particulier m'a forcé à ajourer la ligne suivant! TRs[TR]['PBs'] = [] # Si je n'ai trouvé aucun TR, montrer un message if TRs == {}: msgbox("il n'y pas de TR valide sur ce déssin") # Ajouter ces TRs à TR_all TRs_all.append(TRs) # Cacher le déssin Visio Visio.Visible = False # Demander qui est le client xl.Visible = True msg = "Quel est le client pour cette fiche PA?" choices = ["Circet","Engie"] client = buttonbox(msg, choices=choices) # Résultat globaux pour cette fiche PA RESULTS[PA] = { 'PA_REF': bloc_PA, 'client': client, 'TRs_all': TRs_all, 'NRO': NRO, 'PMZ_PT': PMZ_PT, 'PA_PT': PA_PT, 'CH': CH, 'ADRESSE1': ADRESSE1, 'ADRESSE2': ADRESSE2, 'DATE': DATE } # Quitter excel et passer à la prochaine fiche PA xl.Quit() return except: # En cas d'erreur innatendue! print(format_exc()) codebox("t'as encore fais une connerie! Fais moi un screen de malheur!", "Erreur", format_exc()) going()
from comtypes.client import GetActiveObject try: acad = GetActiveObject('AutoCAD.Application.23') doc = acad.ActiveDocument model = doc.ModelSpace doc.Utility.Prompt('\nCarregado com sucesso...\n') pass except Exception as error: print(error) pass EntitySelected = doc.Utility.GetEntity('\nSelecione uma linha : \n') COR = EntitySelected[0].color SP = EntitySelected[0].StartPoint EP = EntitySelected[0].EndPoint DLT = EntitySelected[0].Delta LYR = EntitySelected[0].Layer msg = '\nLinha com coordenada inicial em {0}, coordenada final em {1}, delta de {2}, na cor {3} e layer {4}\n'.format( SP, EP, DLT, COR, LYR) print(msg) doc.Utility.Prompt(msg)
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) # In[4]: # Launch or connect to STK try: app = GetActiveObject('STK12.Application') root = app.Personality2 app.Visible = True app.UserControl = True except: app = CreateObject('STK12.Application') app.Visible = True app.UserControl = True root = app.Personality2 sc = root.NewScenario('DeckAccessVis') # Set the scenario time period sc = root.CurrentScenario sc2 = sc.QueryInterface(STKObjects.IAgScenario) sc2.StopTime = stop sc2.StartTime = start
def orbm_run_stk(orbm_mode, tstart, tfinal, sc_Cd, sc_area_d, sc_Ck, sc_area_a, sc_Cr, sc_area_r, orb_a, orb_e, orb_i, orb_R, orb_w, orb_m, maintenance_tolerance, maintenance_margin, maintenance_fro, sc_mass, isp_min, isp_max): # The parameters below are not used, but will be set to defaults. thr_TankPressure = 0.1 # tank pressure (Pa) thr_TankVolume = 0.1 # tank volume (m^3) thr_FuelDensity = 0.1 # fuel density (kg/m^3) thr_FuelMass = 0.1 # fuel mass (kg) thr_MaximumFuelMass = 1.0 # max fuel mass (kg) # For thruster sizing and plotting, what range of Isp is needed? plot_Isp_Min = isp_min # s plot_Isp_Max = isp_max # s # Check below if you want the STK GUI to open up too (default True) stk_gui = True # User, check if you are using STK10 or STK11. By default, the comtypes GUID # is using the STK10 GUID code that allows the Astrogator wrapper to load. # Without successful loading, the AgStkGatorLib file cannot be recognised # and created in the comtypes gen folder, and AstroGator cannot be run. # GUID for STK10: 90E096F9-9615-4BA8-BA23-680F8D236959 # GUID for STK11: 090D317C-31A7-4AF7-89CD-25FE18F4017C # Replace below where necessary. if orbm_mode == 2: comtypes.client.GetModule((comtypes.GUID("{90E096F9-9615-4BA8-BA23-680F8D236959}"),1,0)) elif orbm_mode == 3: comtypes.client.GetModule((comtypes.GUID("{090D317C-31A7-4AF7-89CD-25FE18F4017C}"),1,0)) # As a rule of thumb, frozen repeat orbit maintenance generally takes about # 02x as much Delta-V per thrust as regular altitude maintenance due to the # need for the thrusts to bring the SC above the reference to maintain the # eastward-to-westward ground track shift. """ ####################################################################### TO THE USER: DO NOT CHANGE ANY OF THE CODE BELOW, AS THE CODE IS HIGHLY DEPENDENT ON INTERFACING WITH THE RIGHT POINTERS TO THE RIGHT CLASSES. EDIT THE CODE BELOW, AT YOUR RISK, AND ONLY IF YOU KNOW WHAT YOU ARE DOING! ####################################################################### """ # The program will now compute the total scenario time in seconds. months_dict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10,'Nov':11,'Dec':12} # Read the start epoch string as a datetime object tstart_dt = datetime.datetime(int(tstart[6:10]), int(months_dict[tstart[2:5]]), int(tstart[0]), int(tstart[11:13]), int(tstart[14:16]), int(tstart[17:19])) # Read the final epoch string as a datetime object tfinal_dt = datetime.datetime(int(tfinal[6:10]), int(months_dict[tfinal[2:5]]), int(tfinal[0]), int(tfinal[11:13]), int(tfinal[14:16]), int(tfinal[17:19])) # Read the time delta between start and final as a datetime-timedelta object tdelta_dt = tfinal_dt - tstart_dt # Compute the total scenario time in seconds tdelta = (tdelta_dt.days*86400) + tdelta_dt.seconds # int ############################################################################ ############################################################################ # The program will now compute what is the desired Delta-V per thrust # using a first order Taylor expansion of the Vis-Visa equation. GM = 398.6004415e12 # gravity constant x Earth mass (m**3/s**2) velocity = ((398.6004415e12)/(orb_a*1000))**0.5 delta_v = (0.25*velocity*maintenance_tolerance)/(orb_a * 1000) # km/s ############################################################################ ############################################################################ # First, try to close any existing STK applications. print("Closing any pre-existing STK applications... \n") print("Check if you need to save your existing scenarios? (Open the UI) \n") # Check if the user is running in STK 10 if orbm_mode == 2: try: uiApp = GetActiveObject('STK10.Application') uiApp.Quit() except: pass # Check if the user is running in STK 11 elif orbm_mode == 3: try: uiApp = GetActiveObject('STK11.Application') uiApp.Quit() except: pass ############################################################################ ############################################################################ # Start STK10 Application print("Creating a new STK application. \n") if orbm_mode == 2: uiApp = CreateObject("STK10.Application") elif orbm_mode == 3: uiApp = CreateObject("STK11.Application") uiApp.Visible = stk_gui uiApp.UserControl = stk_gui stkRoot = uiApp.Personality2 from comtypes.gen import STKObjects from comtypes.gen import STKUtil from comtypes.gen import AgStkGatorLib from comtypes.client import gen_dir print("Creating the STK scenario object. \n") stkRoot.NewScenario("Orbit_Maintenance") # Get a reference to the scenario object (null if no scenario loaded) scenario = stkRoot.CurrentScenario scenario2 = scenario.QueryInterface(STKObjects.IAgScenario) # Set the time period for the scenario. scenario2.SetTimePeriod( tstart, tfinal ) #Reset STK to the new start time stkRoot.Rewind() ############################################################################ ############################################################################ # This segment will create the life-time test satellite and propagate it. print("Creating the satellite (life-time) object. \n") sat = scenario.Children.New(STKObjects.eSatellite, 'Lifetime') sat2 = sat.QueryInterface(STKObjects.IAgSatellite) # You can gain access to the initial orbit state through the satellite's # propagator object. In the block below, get a pointer to the interface # IAgVePropagtorTwoBody. Then use that pointer to convert the orbit state # into the classical representation, and obtain a pointer to the interface # IAgOrbitStateClassical. sat2.SetPropagatorType(STKObjects.ePropagatorTwoBody) sat2prop = sat2.Propagator.QueryInterface(STKObjects.IAgVePropagatorTwoBody) sat2init = sat2prop.InitialState.Representation sat2state = sat2init.ConvertTo(STKUtil.eOrbitStateClassical) sat2state2 = sat2state.QueryInterface(STKObjects.IAgOrbitStateClassical) # With the IAgOrbitStateClassical interface you will be able to set the values # of the desired orbital elements. # The SizeShape property only provides a pointer to the IAgClassicalSizeShape # interface, which does not immediately provide access to the semimajor axis # or eccentricity values. To access those, you "cast" to the interface # IAgClassicalSizeShapeSemimajorAxis provided by the object # AgClassicalSizeShapeSemimajorAxis. sat2state2.SizeShapeType = STKObjects.eSizeShapeSemimajorAxis sat2state2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeSemimajorAxis).SemiMajorAxis = orb_a sat2state2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeSemimajorAxis).Eccentricity = orb_e # Set the inclination and argument of perigee sat2state2.Orientation.Inclination = orb_i sat2state2.Orientation.ArgOfPerigee = orb_w # For the RAAN, much as in the case of the semi-major axis and eccentricity, # you must first specify the AscNodeType, then provide the value for the # AscNode through the approriate interface. sat2state2.Orientation.AscNodeType = STKObjects.eAscNodeRAAN sat2state2.Orientation.AscNode.QueryInterface(STKObjects.IAgOrientationAscNodeRAAN).Value = orb_R # Set the mean anomaly sat2state2.LocationType = STKObjects.eLocationMeanAnomaly sat2state2.Location.QueryInterface(STKObjects.IAgClassicalLocationMeanAnomaly).Value = orb_m # Propagate the orbit sat2prop.InitialState.Representation.Assign(sat2state2) sat2prop.Propagate() # Prepare the STK Connect Command strings for the life-time computation. setLifeTime = 'SetLifetime */Satellite/Lifetime ' setLifeTimeDragCoeff = setLifeTime + 'DragCoeff ' + str(sc_Cd) setLifeTimeReflectCoeff = setLifeTime + 'ReflectCoeff ' + str(sc_Cr) setLifeTimeDragArea = setLifeTime + 'DragArea ' + str(sc_area_d) setLifeTimeSunArea = setLifeTime + 'SunArea ' + str(sc_area_r) setLifeTimeMass = setLifeTime + 'Mass ' + str(sc_mass) setLifeTimeLimitType = setLifeTime + 'LimitType Duration' setLifeTimeDurationLimit = setLifeTime + 'DurationLimit 3650' setLifeTimeDensityModel = setLifeTime + 'DensityModel Jacchia70Lifetime' # Execute the STK Connect Command strings for life-time computation settings. stkRoot.ExecuteCommand( setLifeTimeDragCoeff ) stkRoot.ExecuteCommand( setLifeTimeReflectCoeff ) stkRoot.ExecuteCommand( setLifeTimeDragArea ) stkRoot.ExecuteCommand( setLifeTimeSunArea ) stkRoot.ExecuteCommand( setLifeTimeMass ) stkRoot.ExecuteCommand( setLifeTimeLimitType ) stkRoot.ExecuteCommand( setLifeTimeDurationLimit ) stkRoot.ExecuteCommand( setLifeTimeDensityModel ) # Execute the STK Connect Command strings for life-time computation. resultsLifeTime = stkRoot.ExecuteCommand('Lifetime */Satellite/Lifetime') lifetime_str = resultsLifeTime.Item(0) + " \n" print(lifetime_str) # Finally, remove the test satellite used to compute the life time. sat.Unload() ############################################################################ ############################################################################ # This segment will create the test satellite and propagate it. print("Creating the satellite object with orbit maintenance. \n") satellite = scenario.Children.New(STKObjects.eSatellite, "Satellite") #print("Querying the IAgStkObject interface of the satellite. \n") satellite2 = satellite.QueryInterface(STKObjects.IAgSatellite) satellite2.SetPropagatorType(STKObjects.ePropagatorAstrogator) # Astrogator # For AstroGator, we need to access a special class called the IAgVADriverMCS. # Acquire an interface to the DriverMCS interface of Astrogator through the # propagator object. This is the central interface from which to control the # satellite via Astrogator. print("Creating the MCS interface object to Astrogator. \n") astg = satellite2.Propagator.QueryInterface(AgStkGatorLib.IAgVADriverMCS) mcs = astg.MainSequence mcs.RemoveAll() # Clear all sequences # Next, we set the initial states of the satellite. # The respective arguments are the segment type, name of segment, and the # name of the segment where the segment of interest is inserted before. mcs.Insert(AgStkGatorLib.eVASegmentStateInitial,'Initial State','-') # Get the initial state and query its interface mcs_init = mcs.Item('Initial State') mcs_init2 = mcs_init.QueryInterface(AgStkGatorLib.IAgVAMCSInitialState) # Set the orbit elements, get the elements and query its interface mcs_init2.SetElementType(1) # Keplerian mcs_elem = mcs_init2.Element mcs_init2.OrbitEpoch = tstart mcs_elem2 = mcs_elem.QueryInterface(AgStkGatorLib.IAgVAElementKeplerian) print("Creating and setting the orbit elements. \n") # Set the orbit elements mcs_elem2.ArgOfPeriapsis = orb_w mcs_elem2.Eccentricity = orb_e mcs_elem2.Inclination = orb_i mcs_elem2.RAAN = orb_R mcs_elem2.SemiMajorAxis = orb_a mcs_elem2.TrueAnomaly = orb_m print("Creating and setting the spacecraft parameters. \n") # Query the interface that allows setting of the spacecraft parameters mcs_scparams = mcs_init2.SpacecraftParameters mcs_scparams2 = mcs_scparams.QueryInterface(AgStkGatorLib.IAgVASpacecraftParameters) # Set the spacecraft parameters mcs_scparams2.Cd = sc_Cd mcs_scparams2.Ck = sc_Ck mcs_scparams2.Cr = sc_Cr mcs_scparams2.DryMass = sc_mass mcs_scparams2.DragArea = sc_area_d mcs_scparams2.RadiationPressureArea = sc_area_r mcs_scparams2.SolarRadiationPressureArea = sc_area_a print("Creating and setting spacecraft fuel tank parameters. \n") # Query the interface that allows setting of the fuel tank parameters mcs_fueltank = mcs_init2.FuelTank mcs_fueltank2 = mcs_fueltank.QueryInterface(AgStkGatorLib.IAgVAFuelTank) # Set the fuel tank parameters mcs_fueltank2.TankPressure = thr_TankPressure mcs_fueltank2.TankVolume = thr_TankVolume mcs_fueltank2.FuelDensity = thr_FuelDensity mcs_fueltank2.FuelMass = thr_FuelMass mcs_fueltank2.MaximumFuelMass = thr_MaximumFuelMass # Now we are going to set the automatic sequence conditions for station-keeping print("Creating the Automatic Sequence object. \n") acs = astg.AutoSequence acs.Add("Maintain") acs_main = acs.Item("Maintain") acs_main2 = acs_main.QueryInterface(AgStkGatorLib.IAgVAAutomaticSequence) acs_seq = acs_main2.Sequence # In the ACS, we add the propagate segment, change the propagate segment to # a UserSelect option, change the sequence to 'Maintain', and the stopping # condition of the UserSelect option should use a UserCalcObject that is the # Kozai-Iszak Mean SMA of the orbit. If the LEO crosses the mean SMA threshold # in the MCS, it will prompt the trigger of the ACS. # If the user is not maintaining an orbit for a frozen repeat, a single # thrust at the apogee should be good enough to raise its orbit. if maintenance_fro == False: # Begin inserting the propagation with an apogee thrust. Prop2Apo = acs_seq.Insert(AgStkGatorLib.eVASegmentTypePropagate,'Prop2Apo','-') ThrustApo = acs_seq.Insert(AgStkGatorLib.eVASegmentTypeManeuver,'ThrustApo','-') # Now we query the interfaces for all of them. Prop2Apo2 = Prop2Apo.QueryInterface(AgStkGatorLib.IAgVAMCSPropagate) ThrustApo2 = ThrustApo.QueryInterface(AgStkGatorLib.IAgVAMCSManeuver) # We set the Prop2Apo segment to perform an orbit propagation to the apogee. Prop2Apo2_SC = Prop2Apo2.StoppingConditions Prop2Apo2_SC.Add('Apoapsis') Prop2Apo2_SC.Cut('Duration') # Not sure why remove doesn't work # Then, we set the thruster fire levels at the apogee using a fixed thrust. ThrustApo2.Maneuver.SetAttitudeControlType(AgStkGatorLib.eVAAttitudeControlThrustVector) ThrustApo2_Vector = ThrustApo2.Maneuver.AttitudeControl.QueryInterface(AgStkGatorLib.IAgVAAttitudeControlImpulsiveThrustVector) ThrustApo2_Vector.DeltaVVector.AssignCartesian(delta_v, 0.0, 0.0); # If the user is maintaining an orbit for a frozen repeat, a second perigee # thrust is needed in order to minimise disrupting the osculating eccentricity. if maintenance_fro == True: # Insert the propagation to perigee with the perigee thrust. Prop2Peri = acs_seq.Insert(AgStkGatorLib.eVASegmentTypePropagate,'Prop2Peri','-') ThrustPeri = acs_seq.Insert(AgStkGatorLib.eVASegmentTypeManeuver,'ThrustPeri','-') # Now we query the interfaces for all of them. Prop2Peri2 = Prop2Peri.QueryInterface(AgStkGatorLib.IAgVAMCSPropagate) ThrustPeri2 = ThrustPeri.QueryInterface(AgStkGatorLib.IAgVAMCSManeuver) # We set the Prop2Peri segment to perform an orbit propagation to the perigee. Prop2Peri2_SC = Prop2Peri2.StoppingConditions Prop2Peri2_SC.Add('Periapsis') Prop2Peri2_SC.Cut('Duration') # Not sure why remove doesn't work # Then, we set the thruster fire levels at the perigee using a fixed thrust. ThrustPeri2.Maneuver.SetAttitudeControlType(AgStkGatorLib.eVAAttitudeControlThrustVector) ThrustPeri2_Vector = ThrustPeri2.Maneuver.AttitudeControl.QueryInterface(AgStkGatorLib.IAgVAAttitudeControlImpulsiveThrustVector) ThrustPeri2_Vector.DeltaVVector.AssignCartesian(delta_v, 0.0, 0.0); # Begin inserting the propagation with an apogee thrust. Prop2Apo = acs_seq.Insert(AgStkGatorLib.eVASegmentTypePropagate,'Prop2Apo','-') ThrustApo = acs_seq.Insert(AgStkGatorLib.eVASegmentTypeManeuver,'ThrustApo','-') # Now we query the interfaces for all of them. Prop2Apo2 = Prop2Apo.QueryInterface(AgStkGatorLib.IAgVAMCSPropagate) ThrustApo2 = ThrustApo.QueryInterface(AgStkGatorLib.IAgVAMCSManeuver) # We set the Prop2Apo segment to perform an orbit propagation to the apogee. Prop2Apo2_SC = Prop2Apo2.StoppingConditions Prop2Apo2_SC.Add('Apoapsis') Prop2Apo2_SC.Cut('Duration') # Not sure why remove doesn't work # Then, we set the thruster fire levels at the apogee using a fixed thrust. ThrustApo2.Maneuver.SetAttitudeControlType(AgStkGatorLib.eVAAttitudeControlThrustVector) ThrustApo2_Vector = ThrustApo2.Maneuver.AttitudeControl.QueryInterface(AgStkGatorLib.IAgVAAttitudeControlImpulsiveThrustVector) ThrustApo2_Vector.DeltaVVector.AssignCartesian(delta_v, 0.0, 0.0); # At this stage, the automatic sequence oject has been successfully built. # We just need to know how to call the automatic sequence whenever the stop # conditions have been met (i.e. when the satellite crosses the threshold) print("Setting the MCS segments and piecing everything together... \n") # For the MCS, it needs only a propagate segment, with a duration = tdelta. PropMain = mcs.Insert(AgStkGatorLib.eVASegmentTypePropagate,'PropMain','-') PropMain2 = PropMain.QueryInterface(AgStkGatorLib.IAgVAMCSPropagate) PropMain2_StopCon_Dura = PropMain2.StoppingConditions.Item(0) PropMain2_StopCon_Dura_Prop2 = PropMain2_StopCon_Dura.Properties.QueryInterface(AgStkGatorLib.IAgVAStoppingCondition) PropMain2_StopCon_Dura_Prop2.Trip = tdelta # We will add the mean semi-major axis as a stopping condition. PropMain2_StopCon_SMA = PropMain2.StoppingConditions.Add('UserSelect') PropMain2_StopCon_SMA_Properties = PropMain2_StopCon_SMA.Properties PropMain2_StopCon_SMA_Properties2 = PropMain2_StopCon_SMA_Properties.QueryInterface(AgStkGatorLib.IAgVAStoppingCondition) PropMain2_StopCon_SMA_Properties2.UserCalcObjectName = 'Mean Semimajor Axis' PropMain2_StopCon_SMA_Properties2.Trip = orb_a - maintenance_tolerance PropMain2_StopCon_SMA_Properties2.RepeatCount = 1 PropMain2_StopCon_SMA_Properties2.Sequence = 'Maintain' # AGIers say: You can set multiple stopping conditions for a propagate # segment. Astrogator stops propagating the satellite when it meets one of # the stopping conditions. # Run the MCS print("Running the mission control sequence now (this might take long)... \n") astg.RunMCS() print("Mission successfully ran! Now extracting orbital data. \n") # Now, we need to start extracting relevant data. The data we will need are: # 1 - Kozai-Iszak mean semimajor axes values. sat_epochs = [] sat_mean_sma = [] # 2 - Altitude values. sat_altitude = [] # Get the Kozai-Izsak Mean data providers pointer and interface to it. sat_ki_mean = satellite.DataProviders.Item("Kozai-Izsak Mean") sat_ki_mean2 = sat_ki_mean.QueryInterface(STKObjects.IAgDataProviderGroup) sat_ki_mean2_ICRF = sat_ki_mean2.Group.Item("ICRF") sat_ki_mean2_ICRF2 = sat_ki_mean2_ICRF.QueryInterface(STKObjects.IAgDataPrvTimeVar) sat_ki_mean2_ICRF2_Data = sat_ki_mean2_ICRF2.Exec(scenario2.StartTime, scenario2.StopTime, 3600) sat_ki_mean_sma = np.array(sat_ki_mean2_ICRF2_Data.DataSets.ToArray()) time_error_flag = False # Extract the Kozai-Izsak Mean semi major axis for epoch in range(0,len(sat_ki_mean_sma)): epochstr = sat_ki_mean_sma[epoch][0] # Read raw epoch string epochlis = epochstr.split() mean_sma = sat_ki_mean_sma[epoch][1] # Read raw mean SMA string yy = int(epochlis[2]) mm = int(months_dict[epochlis[1]]) dd = int(epochlis[0]) hh = int(epochlis[3][0:2]) mn = int(epochlis[3][3:5]) ss = int(epochlis[3][6:8]) # If STK outputs end-of-denominator numbers for some weird reason. if ss == 60: ss = 0 time_error_flag = True epoch_dt = datetime.datetime(yy,mm,dd,hh,mn,ss) if time_error_flag == True: epoch_dt = epoch_dt + datetime.timedelta(seconds=60) time_error_flag = False sat_epochs.append(epoch_dt) sat_mean_sma.append(float(mean_sma)) # Get the altitude values from the LLA State-Fixed pointer and interface to it. sat_alt = satellite.DataProviders.Item("LLA State") sat_alt2 = sat_alt.QueryInterface(STKObjects.IAgDataProviderGroup) sat_alt2_Fixed = sat_alt2.Group.Item("Fixed") sat_alt2_Fixed2 = sat_alt2_Fixed.QueryInterface(STKObjects.IAgDataPrvTimeVar) sat_alt2_Fixed2_Data = sat_alt2_Fixed2.Exec(scenario2.StartTime, scenario2.StopTime, 3600) sat_alt_data_final = np.array(sat_alt2_Fixed2_Data.DataSets.ToArray()) if len(sat_alt_data_final) != len(sat_ki_mean_sma): print("Warning! Something went wrong with the data provider parsing.") print("Length of altitude and SMA arrays do not match! Code broken? \n") # Extract the altitude values for epoch in range(0,len(sat_alt_data_final)): altitude = sat_alt_data_final[epoch][3] # Read raw mean SMA string sat_altitude.append(float(altitude)) # Get the maneuver summary data providers pointer and interface to it. sat_deltaV = satellite.DataProviders.Item("Maneuver Summary") sat_deltaV2 = sat_deltaV.QueryInterface(STKObjects.IAgDataPrvInterval) sat_deltaV2_Data = sat_deltaV2.Exec(scenario2.StartTime, scenario2.StopTime) sat_deltaV2_Array = np.array(sat_deltaV2_Data.DataSets.ToArray()) # Extract the Delta-V values deltaV_file = open("output_manoeuvre_stk.txt",'w') for thrust in sat_deltaV2_Array: thrust_str = thrust[0] + ' ' thrust_str += thrust[1] + ' ' thrust_str += thrust[2] + ' ' thrust_str += thrust[5] + ' \n' deltaV_file.write(thrust_str) deltaV_file.close() # Compute the total Delta-V and the total impulse needed. total_deltaV = len(sat_deltaV2_Array) * delta_v # Total impulse, inclusive of the margin of safety total_impulse = total_deltaV * 1000 * sc_mass * maintenance_margin Isp = np.linspace(plot_Isp_Min, plot_Isp_Max, 500) # Isp axis, in (s) Mf = total_impulse / (Isp*9.81) # Construct the summary information string objects impulse_str = "The total impulse needed: " impulse_str = impulse_str + str(total_impulse) + " \n" deltaV_str = "The total Delta-V (m/s) needed is " deltaV_str = deltaV_str + str(total_deltaV * 1000) + " \n" # Log the summary information summary_file = open("output_summary_stk.txt",'w') summary_file.write(lifetime_str) summary_file.write(impulse_str) summary_file.write(deltaV_str) summary_file.close() # Print the impulse and Delta-V requirements statement. print(impulse_str) print(deltaV_str) # Plotting of altitudes plt.figure(1) plt.title("Plot of Satellite Altitude (km) Against Date-Time") plt.ylabel('Altitude (km)') plt.xlabel('Date-Time') plt.scatter(sat_epochs,sat_altitude,s=4,alpha=0.3) plt.grid() # Plotting of Kozai-Izsak mean semi-major axes plt.figure(2) plt.title("Plot of Kozai-Izsak Mean Semimajor Axis (km) Against Date-Time") plt.ylabel('Kozai-Izsak Mean Semimajor Axis (km)') plt.xlabel('Date-Time') plt.plot(sat_epochs,sat_mean_sma) plt.grid() # Thruster sizing profile of Isp Against Mass plt.figure(3) plt.title("Thruster Profiling for Feasible ISPs (s) Against Fuel Mass (kg)") plt.ylabel('Mass of Fuel Required (kg)') plt.xlabel('Specific Impulse (s)') plt.plot(Isp, Mf) plt.grid() """ ######################################################################### Notes: This part of the code reads the text file of all the shortlisted, thrusters and then plots them along the Isp-to-fuel-mass sizing chart. ######################################################################### """ # Now we compare the mission propulsion requirements against thrusters. try: thr_file = open("thruster_shortlist.txt","r") except: # Otherwise, generate the file thr_file = open("thruster_shortlist.txt","w") thr_file.write("COMPANY ") thr_file.write("MODEL ") thr_file.write("ISP_S ") thr_file.write("FUEL_MASS_KG ") thr_file.write("THRUST_N ") thr_file.write("END \n") thr_file.write("ALIENA ") thr_file.write("MUSIC ") thr_file.write("1000 ") thr_file.write("3.000 ") thr_file.write("0.004 ") thr_file.write("END \n") thr_file.close() # Now, try to open the file thr_file = open("thruster_shortlist.txt","r") thr_compn = [] thr_model = [] thr_isp_s = [] thr_fuelm = [] thr_force = [] for line in thr_file: line_split = line.split() if line_split[0] != "COMPANY": thr_compn.append(str(line_split[0])) thr_model.append(str(line_split[1])) thr_isp_s.append(float(line_split[2])) thr_fuelm.append(float(line_split[3])) thr_force.append(str(line_split[4])) thr_file.close() # plot_Isp_Min = 200.0 # N s # plot_Isp_Max = 1250.0 # N s bwidth = (plot_Isp_Max - plot_Isp_Min)/50 barchart = plt.bar(thr_isp_s, thr_fuelm, width = bwidth, color='green') # Then, we label each thruster accordingly. barcount = 0 for rect in barchart: height = rect.get_height() bartext = thr_compn[barcount] + '\n' bartext = bartext + thr_model[barcount] + '\n' bartext = bartext + thr_force[barcount] + 'N' plt.text(rect.get_x() + rect.get_width()/2.0, rect.get_height(), bartext, ha='center', va='bottom') barcount += 1 return None
# Open a Photoshop document located in the Photoshop samples folder # You must first create a File object to pass into the open method. from comtypes.client import GetActiveObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") fileName = "C:\Git\PS_Samples_Files\Layer Comps.psd" docRef = app.Open(fileName)
# This sample script shows how to apply 3 different filters to # selections in the open document. # from win32com.client import Dispatch, GetActiveObject, GetObject from comtypes.client import GetActiveObject, CreateObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") # We don't want any Photoshop dialogs displayed during automated execution psDisplayNoDialogs = 3 # from enum PsDialogModes app.displayDialogs = psDisplayNoDialogs psPixels = 1 strtRulerUnits = app.Preferences.RulerUnits if strtRulerUnits is not psPixels: app.Preferences.RulerUnits = psPixels fileName = "C:\Git\PS_Samples_Files\Layer Comps.psd" docRef = app.Open(fileName) nLayerSets = len([(i, x) for i, x in enumerate(docRef.LayerSets, 1)]) # for some reason, len(docRef.LayerSets) return errors # So above list comprehension is same as below # nLayerSets = 0 # for layerSet in docRef.LayerSets: # nLayerSets += 1 nArtLayers = len([
def ForceComparison(): if True: # create new scenario uiApp = CreateObject('STK12.Application') uiApp.Visible = True uiApp.UserControl = True root = uiApp.Personality2 root.NewScenario("PerturbingForceComparison") else: # connect to running scenario uiApp = GetActiveObject('STK12.Application') uiApp.UserControl = True uiApp.Visible = True root = uiApp.Personality2 #################### ##### SCENARIO ##### #################### sc = root.CurrentScenario iagSc = sc.QueryInterface(STKObjects.IAgScenario) iagSc.AnalysisInterval.SetStartAndStopTimes("1 Jan 2020 00:00:00.00", "2 Jan 2020 00:00:00.00") root.Rewind ############################# ##### CREATE SATELLITES ##### ############################# sats = np.array(["LEO_300km", "LEO_400km", "LEO_600km", "LEO_800km", "GPS", "GEO"]) sma = np.array([6678, 6778, 6978, 7178, 26600, 42165]) inc = np.array([98.0, 98.0, 98.0, 98.0, 55.0, 0.0]) for thisSat in sats: print("Creating */Satellite/" + thisSat) oSat = sc.Children.New(STKObjects.eSatellite, thisSat) sat = oSat.QueryInterface(STKObjects.IAgSatellite) sat.SetPropagatorType(0) # ePropagatorHPOP prop = sat.Propagator.QueryInterface(STKObjects.IAgVePropagatorHPOP) prop.Step = 60 prop.InitialState.Representation.AssignClassical(11, sma[np.where(sats == thisSat)[0]], 0.0, inc[np.where(sats == thisSat)[0]], 0.0, 0.0, 0.0) forceModel = prop.ForceModel forceModel.CentralBodyGravity.File = 'C:\Program Files\AGI\STK 12\STKData\CentralBodies\Earth\WGS84_EGM96.grv' forceModel.CentralBodyGravity.MaxDegree = 21 forceModel.CentralBodyGravity.MaxOrder = 21 forceModel.Drag.Use=1 forceModel.Drag.DragModel.Cd=0.01 forceModel.Drag.DragModel.AreaMassRatio=0.01 forceModel.SolarRadiationPressure.Use=1 prop.Propagate() ###################################### ##### CREATE FORCE MODEL VECTORS ##### ###################################### # can't create ForceModel vectors with the OM so connect all the way vectors = [] ####################### ### GRAVITY VECTORS ### ####################### # Point Mass GravityVector(root, "PointMass", 0, 0) vectors.append("PointMass") # J2 GravityVector(root, "J2", 2, 0) vectors.append("J2") # J4 GravityVector(root, "J4", 4, 0) vectors.append("J4") # J2/2 GravityVector(root, "J2-2", 2, 2) vectors.append("J2-2") # J4/4 GravityVector(root, "J4-4", 4, 4) vectors.append("J4-4") # J8/8 GravityVector(root, "J8-8", 8, 8) vectors.append("J8-8") # J12/12 GravityVector(root, "J12-12", 12, 12) vectors.append("J12-12") # J24/24 GravityVector(root, "J24-24", 24, 24) vectors.append("J24-24") # J70/70 GravityVector(root, "J70-70", 70, 70) vectors.append("J70-70") ###################### ### CENTRAL BODIES ### ###################### # Sun thisVector = "SunForce" print("Creating vector: " + thisVector) vectors.append(thisVector) root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate SunForce \"Force Model\" Scale 1.0 CentralBody Earth") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force UseCBGravity Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Drag Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force SRP Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force ThirdBodyGravity Sun On FromCB") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force ThirdBodyGravity Moon Off") # Moon thisVector = "MoonForce" print("Creating vector: " + thisVector) vectors.append(thisVector) root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate MoonForce \"Force Model\" Scale 1.0 CentralBody Earth") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force UseCBGravity Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Drag Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force SRP Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force ThirdBodyGravity Sun Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force ThirdBodyGravity Moon On FromCB") # Mars CentralBodyForce(root, "Mars") vectors.append("MarsForce") # Jupiter CentralBodyForce(root, "Jupiter") vectors.append("JupiterForce") # Venus CentralBodyForce(root, "Venus") vectors.append("VenusForce") # drag thisVector = "Drag" print("Creating vector: " + thisVector + " using 1000 kg and 20 m^2 area") vectors.append(thisVector) root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate Drag \"Force Model\" Scale 1.0 CentralBody Earth") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force UseCBGravity Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Drag On 2.2 0.02 \"Jacchia 1970\" Manual 150 150 3.0") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force SRP Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force ThirdBodyGravity Sun Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force ThirdBodyGravity Moon Off") # srp thisVector = "SRP" print("Creating vector: " + thisVector + " using 1000 kg and 20 m^2 area") vectors.append(thisVector) root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate SRP \"Force Model\" Scale 1.0 CentralBody Earth") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force UseCBGravity Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Drag Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force SRP On") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force ThirdBodyGravity Sun Off") root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force ThirdBodyGravity Moon Off") #################### ##### ANALYSIS ##### #################### for thisSat in sats: print("Analyzing */Satellite/" + thisSat) oSat = root.GetObjectFromPath("*/Satellite/" + thisSat) # loop through vectors and vector differences of interest m = GetAverageMagnitudeNewton(root, oSat, "PointMass") m = GetAverageMagnitudeNewton(root, oSat, "J2") m = GetAverageMagnitudeNewton(root, oSat, "J2-2") m = GetAverageMagnitudeNewton(root, oSat, "J4") m = GetAverageMagnitudeNewton(root, oSat, "J4-4") m = GetAverageMagnitudeNewton(root, oSat, "J8-8") m = GetAverageMagnitudeNewton(root, oSat, "J12-12") m = GetAverageMagnitudeNewton(root, oSat, "J24-24") m = GetAverageMagnitudeNewton(root, oSat, "J70-70") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J2") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J2-2") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J4") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J4-4") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J8-8") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J12-12") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J24-24") m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J70-70") m = GetAverageDifferenceNewton(root, oSat, "J2-2", "J2") m = GetAverageDifferenceNewton(root, oSat, "J2", "J4") m = GetAverageDifferenceNewton(root, oSat, "J4-4", "J2-2") m = GetAverageDifferenceNewton(root, oSat, "J8-8", "J4-4") m = GetAverageDifferenceNewton(root, oSat, "J12-12", "J8-8") m = GetAverageDifferenceNewton(root, oSat, "J24-24", "J12-12") m = GetAverageDifferenceNewton(root, oSat, "J70-70", "J24-24") m = GetAverageMagnitudeNewton(root, oSat, "SunForce") m = GetAverageMagnitudeNewton(root, oSat, "MoonForce") m = GetAverageMagnitudeNewton(root, oSat, "MarsForce") m = GetAverageMagnitudeNewton(root, oSat, "JupiterForce") m = GetAverageMagnitudeNewton(root, oSat, "VenusForce") m = GetAverageMagnitudeNewton(root, oSat, "Drag") m = GetAverageMagnitudeNewton(root, oSat, "SRP") #################### ##### CLEAN-UP ##### #################### # delete vectors and satellites if False: for thisVector in vectors: root.ExecuteCommand("VectorTool * Satellite Delete VectorTemplate " + thisVector) for thisSat in sats: oThisSat = root.GetObjectFromPath("*/Satellite/" + thisSat) oThisSat.Unload()
# Create a new art layer and convert it to a text layer. # Set its contents, size and color. # from win32com.client import Dispatch, GetActiveObject from comtypes.client import GetActiveObject, CreateObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") strtRulerUnits = app.Preferences.RulerUnits strtTypeUnits = app.Preferences.TypeUnits psInches = 2 # from enum PsUnits psTypePoints = 5 # from enum PsTypeUnits app.Preferences.RulerUnits = psInches app.Preferences.TypeUnits = psTypePoints # suppress all dialogs psDisplayNoDialogs = 3 # from enum PsDialogModes app.displayDialogs = psDisplayNoDialogs # create a new document docRef = app.Documents.Add(7, 5, 72) # create text color properties textColor = CreateObject("Photoshop.SolidColor") textColor.RGB.Red = 225 textColor.RGB.Green = 0 textColor.RGB.Blue = 0 # add a new text layer to document and apply the text color
from comtypes.client import CreateObject from comtypes.client import GetActiveObject import array #Create Autocad file try: Aapp= GetActiveObject("AutoCad.Application") Aapp.Visible= True Adrawing=Aapp.ActiveDocument except: Aapp = CreateObject("AutoCad.Application") Aapp.Visible = True Adrawing = Aapp.ActiveDocument ms= Adrawing.Modelspace from comtypes.gen.AutoCAD import * from pyautocad import Autocad, APoint acad = Autocad() acad.prompt("Hello, Autocad from Python\n")
def process(PA): global ActiveWindow, Shapes, Word, TRs_all, xl, Visio global RESULTS try: # ouvrir le fichier excel et faire les initialisations de coutume xl = CreateObject("Excel.application") xl.Visible = False xl.DisplayAlerts = False wb = xl.Workbooks.Open(PA) wb.Sheets("synoptique-bilan µmodules").Select() # dans la sheet visée, détecter tout les objets OLE (qui seront # normalement tous des déssins visio) OLEObjects = wb.Sheets("synoptique-bilan µmodules").OLEObjects() # pour chaque déssin ... for OLEObject in OLEObjects: # l'ouvrir dans Visio OLEObject.Verb(2) # prendre la main sur la fenêtre visio ouverte Visio = GetActiveObject("Visio.Application") # Visio.Visible = False Visio.DisplayAlerts = False ActiveWindow = Visio.ActiveWindow Page = ActiveWindow.Page Shapes = Page.Shapes msg = "Voulez confirmer le nombre de PBs après chaque sélection?\n" \ + "(si c'est plan assez complexe mieux vaut répondre par oui)" yn = ynbox(msg) # allons-y! # On extrait d'abord les infos d'entête for shape in Shapes: text = shape.Text if text.startswith('NRO'): bloc_NRO = text elif text.startswith('PT'): try: blocs_PT.append(shape) except: blocs_PT = [shape] elif text.startswith('PA'): PA_posx = get_XY(shape)[0] if get_XY(blocs_PT[0])[0] > get_XY(blocs_PT[1])[0]: FI_bloc = blocs_PT[0] PA_bloc = blocs_PT[1] else: PA_bloc = blocs_PT[1] FI_bloc = blocs_PT[0] PA_PT = PA_bloc.Text.rsplit('\n')[0].replace('PT: ', '') PMZ_PT = FI_bloc.Text.rsplit('\n')[0].replace('PT: ', '') CH = PA_bloc.Text.rsplit('\n')[2].replace('CH: ', '') NRO = extract('NRO/PMZ/PA', bloc_NRO, 'NRO') ADRESSE1 = ' '.join(PA_bloc.Text.rsplit('\n')[3:5])\ .replace('Adresse: ', '') ADRESSE2 = ADRESSE1.rsplit('-')[0] TRs = {} empty_TRs = [] # là ça va barder! for shape in Shapes: if shape.Text.startswith('TR'): if get_XY(shape)[0] > PA_posx: TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '') TR = TR_TXT.rsplit('FO')[0] \ .replace('\\n', ' ') + 'FO' if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR): empty_TRs.append(shape.ID) continue if TR not in TRs: TRs[TR] = { 'LONG': 0, 'SHAPES': [shape.ID], 'CH/IMB/AP': [], 'PTs': [], 'maxPT': 0 } else: TRs[TR]['SHAPES'].append(shape.ID) try: TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \ .replace('m', '')) except: TR_LONG = 0 TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG title1 = 'Sélectionnez les bloc' title2 = 'Confirmez la sélection' for TR in TRs: while True: SelectShapes(TRs[TR]['SHAPES']) if ccbox(TR, title1): CH_OR_IMB_OR_AP_all = [] PTs = [] msg = "Pour " + TR + "\nVous avez sélectionné:\n" selected_PBs = 0 yn_yes = True for selected in ActiveWindow.Selection: try: TEXT = str(selected.Text) if not TEXT.startswith('PB'): continue selected_PBs = selected_PBs + 1 PT = TEXT.rsplit('\n')[2] ADR = TEXT.rsplit('\n')[3] CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4] if (not CH_OR_IMB_OR_AP.startswith('AP ') and not CH_OR_IMB_OR_AP.startswith('Ch.') and not CH_OR_IMB_OR_AP.startswith('IMB')): SelectShapes([selected.ID]) msgbox("T'as surement encore fais une connerie dans tes" + "déssins, regarde ce bloc dans la ligne PT!\n" + "Je devrais trouver Ch.XXXX ou AP XXXX" + "ou IMB/XXXX/XXX mais j'ai trouvé\n" + CH_OR_IMB_OR_AP + "\n" + "Quand t'auras détécté l'erreur click sur OK") cont = boolbox("Dois-je continuer ou fermer?", "Que faire?", ['Continuer?', 'Fermer?']) if not cont: exit(0) else: pass else: msg = msg + "- " + CH_OR_IMB_OR_AP + "\n" CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP]) PTs.append(int(PT.replace('PT', ''))) except: SelectShapes([selected.ID]) msgbox("T'as surement encore fais une connerie dans tes" + "déssins, regarde ce bloc dans la ligne PT!\n" + "Quand t'auras détécté l'erreur click sur OK") cont = boolbox("Dois-je continuer ou fermer?", "Que faire?", ['Continuer?', 'Fermer?']) if not cont: exit(0) else: msg = msg + "(RIEN!)" CH_OR_IMB_OR_AP_all = [] PTs = [] yn_yes = False if not selected_PBs: cont = boolbox("Tu n'as rien sélectionné! Tu confirmes" + " que ce n'est pas une connerie?", "Sélection vide!", ['Oui vas-y', 'Comme d\'hab! Une connerie']) if cont: break else: continue if yn and yn_yes: msg = msg + "(" + str(selected_PBs) + " sélectionnés)" conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?']) if conf: TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all TRs[TR]['PTs'] = PTs break else: pass else: TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all TRs[TR]['PTs'] = PTs break else: exit(0) if len(TRs[TR]['PTs']): TRs[TR]['maxPT'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc' else: TRs[TR]['maxPT'] = 'je_ne_suis_pas_cense_exister.doc' if TRs == {}: msgbox("il n'y pas de TR valide sur ce déssin") TRs_all.append(TRs) Visio.Visible = False RESULTS[PA] = { 'TRs_all': TRs_all, 'NRO': NRO, 'PMZ_PT': PMZ_PT, 'PA_PT': PA_PT, 'CH': CH, 'ADRESSE1': ADRESSE1, 'ADRESSE2': ADRESSE2, 'DATE': DATE } xl.Quit() return except: print(format_exc()) codebox("t'as encore fais une connerie! Fais moi un screen de malheur!", "Erreur", format_exc()) going()
def Annotations(STKVersion, ObjectName, ObjectType, accuracy, Events, EventNames, EventColors): numEvents = len(Events) from comtypes.client import CreateObject from comtypes.client import GetActiveObject uiApplication = GetActiveObject("STK{}.Application".format(STKVersion)) root = uiApplication.Personality2 from comtypes.gen import STKObjects from comtypes.gen import STKUtil scenario = root.CurrentScenario uiApplication.Visible = True uiApplication.UserControl = True scenarioObj = scenario.QueryInterface(STKObjects.IAgScenario) # This is specifically for the object type Launch Vehicle, but this can be changed to the # desired object Object = scenario.Children.Item(ObjectName) ObjectType = "STKObjects.IAg{}".format(ObjectType) ObjectObj = Object.QueryInterface(eval(ObjectType)) # Retrieve lat/lon/alt of object at desired times LLA = Object.DataProviders("LLA State") LLA2 = LLA.QueryInterface(STKObjects.IAgDataProviderGroup) LLAFixed = LLA2.Group.Item("Fixed") LLATV = LLAFixed.QueryInterface(STKObjects.IAgDataPrvTimeVar) LLAAlmost = LLATV.Exec(scenarioObj.StartTime, scenarioObj.StopTime, accuracy) Times = list(LLAAlmost.DataSets.Item(0).GetValues()) Lon = list(LLAAlmost.DataSets.Item(1).GetValues()) Lat = list(LLAAlmost.DataSets.Item(2).GetValues()) Alt = list(LLAAlmost.DataSets.Item(3).GetValues()) # clear old annotations root.ExecuteCommand('MapAnnotation * Delete All') root.ExecuteCommand('VO * Annotation Delete AllAnnotations Text') # for every event, grab lat, lon, alt and put annotation in STK for i in range(numEvents): # grab index that corresponds to time of event ind = Times.index(Events[i]) Latitude = str(Lat[ind]) Longitude = str(Lon[ind]) Altitude = str(Alt[ind]) # put annotation in 2D graphics cmd = ("MapAnnotation * Add " + str(i + 1) + ' Text String "' + EventNames[i] + '" Color ' + EventColors[i] + ' Position ' + Latitude + ' ' + Longitude) root.ExecuteCommand(cmd) # put annotation in 3D graphics cmd2 = ("VO * Annotation Add " + str(i + 1) + ' Text String "' + EventNames[i] + '" Coord LatLon Position ' + Latitude + ' ' + Longitude + Altitude + ' Color ' + EventColors[i]) root.ExecuteCommand(cmd2)
def run_stk_v2(scenario_path, study_name, orbit_data, stk_data_path): # This function opens an instance of STK, loads the desired scenario, and executes the # connect commands written by the previous functions from win32api import GetSystemMetrics # from IPython.display import Image, display, SVG import os import comtypes from comtypes.client import CreateObject from comtypes.client import GetActiveObject print('Opening STK...') # Open new instance of STK # app = CreateObject("STK11.Application") # Pass open instance of STK app = GetActiveObject('svchost.Application') app.Visible = True app.UserControl = True app.Top = 0 app.Left = 0 app.Width = int(GetSystemMetrics(0) / 2) app.Height = int(GetSystemMetrics(1) - 30) root = app.Personality2 comtypes.client.gen_dir os.listdir(comtypes.client.gen_dir) from comtypes.gen import STKObjects print('Loading scenario...') # Load predefined scenario, which contains satellite for which the orbit is varied # and the target for which the access time is calculated root.LoadScenario(r'{}'.format(scenario_path)) sc = root.CurrentScenario sc2 = sc.QueryInterface(STKObjects.IAgScenario) # sc2.SetTimePeriod("1 Jul 2008 10:00:00", "30 Jun 2010 10:00:00") print('Executing connect commands...') # Open file with connect commands, and execute them sequentially connect_command_file = 'CC_{}_OrbitStudy.txt'.format(study_name) with open(connect_command_file, 'r') as fh: commands = fh.readlines() size = len(commands) loop_start = time.time() duration = np.zeros(size) j = 0 for i in range(size): time_start = time.time() if j == 0: print('Adjusting Satellite orbit...') root.ExecuteCommand(commands[i]) j += 1 elif j == 1: print('Generating SPS access report...') if not os.path.exists('{}\DVP_{}_{}perigee{}apogee_{}meananom_access.csv'.format(stk_data_path, study_name, orbit_data[i + 1][0], orbit_data[i + 1][1], 180.0)): root.ExecuteCommand(commands[i]) else: print('Access report for {} x {} km orbit already exists'.format(orbit_data[i + 1][0], orbit_data[i + 1][1])) j += 1 elif j == 2: print('Generating SPS range report...') if not os.path.exists('{}\DVP_{}_{}perigee{}apogee_{}meananom_range.txt'.format(stk_data_path, study_name, orbit_data[i + 1][0], orbit_data[i + 1][1], 180.0)): root.ExecuteCommand(commands[i]) else: print('Range report for {} x {} km orbit already exists'.format(orbit_data[i + 1][0], orbit_data[i + 1][1])) j += 1 elif j == 3: print('Generating SPS lighting report...') if not os.path.exists('{}\DVP_{}_{}perigee{}apogee_{}meananom_lighting.csv'.format(stk_data_path, study_name, orbit_data[i + 1][0], orbit_data[i + 1][1], 180.0)): root.ExecuteCommand(commands[i]) else: print('Lighting for {} x {} km orbit already exists'.format(orbit_data[i + 1][0], orbit_data[i + 1][1])) j = 0 time_end = time.time() # Print progress update print('Progress: {}%, Execution Time: {} seconds'.format(round(i * 100.0 / (size - 1), 2), round(time_end - time_start, 5))) duration[i] = time_end - time_start loop_end = time.time() print('Total time to generate data: {} minutes'.format((loop_end - loop_start) / 60.0)) print('Average command execution time: {} seconds'.format(np.mean(duration)))
from comtypes.client import GetActiveObject, CreateObject try: excel = GetActiveObject('Excel.Application') pass except Exception as error: print(error) quit() workbook = excel.WorkBooks.Add() sheet = workbook.Sheets(1) excel.Visible = True sheet.Range('A1:E1').Value[:] = (1, 2, 3 , 4 , 5) print('Done...')
dictidx = [] for idx in range(0, len(dictList)): if dictList[idx]['name'] == namekey: dictidx = idx break if dictidx == []: print("Does not Exist") return dictidx valispace = valispace.API(url='https://app.valispace.com', username='******', password=keyring.get_password( "valispace", "kuldeep")) uiApplication = GetActiveObject('STK11.Application') root = uiApplication.Personality2 scenario1 = root.CurrentScenario scenario2 = scenario1.QueryInterface(STKObjects.IAgScenario) root.Rewind() # Fetch from Valispace ### Enter PROJECT NAME here ### project_Name = 'ValiSAT_STK_GEO' # Fetch project JSON object for above project name dict_project = valispace.get_project_by_name(name=project_Name) projectID = dict_project[0]['id']
# Get the active document and make a new selection. from comtypes.client import GetActiveObject, CreateObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") # create new document if no document is opened if len([(i, x) for i, x in enumerate(app.Documents, 1)]) < 1: psPixels = 1 strtRulerUnits = app.Preferences.RulerUnits app.Preferences.RulerUnits = psPixels psNewRGB = 2 # from enum PsNewDocumentMode psWhite = 1 # from enum PsDocumentFill docRef = app.Documents.Add(320, 240, 72, None, psNewRGB, psWhite) app.preferences.rulerUnits = strtRulerUnits else: docRef = app.ActiveDocument sel_area = ((50, 60), (150, 60), (150, 120), (50, 120)) psReplaceSelection = 1 # from enum PsSelectionType docRef.Selection.Select(sel_area, psReplaceSelection, 5.5, False)
def filter_objects_by_type(objectType, name=''): """Returns a list of paths for the specified object type optionally filtered by a name string""" # Only run if not already connected to STK app = GetActiveObject('STK11.Application')
def EtabsImport(doc, program, swm, modtypes, wallcrk, slabmode, colyr='None'): #Get Etabs or SAP2000 instance, assign it at EtabsObj variable try: if program == "ETABS": EtabsObj = GetActiveObject("CSI.ETABS.API.ETABSObject") elif program == "SAP2000": EtabsObj = GetActiveObject("CSI.SAP2000.API.SAPObject") except (OSError, COMError): if program == "ETABS": showerror( title=progname, message="ETABS is not running\nPlease open ETABS and try again", icon=ERROR) elif program == "SAP2000": showerror( title=progname, message= "SAP2000 is not running\nPlease open ETABS and try again", icon=ERROR) return #get model's instance, and initilaize the model myModel = EtabsObj.SapModel myUnit = 6 #kN_m_C myModel.InitializeNewModel(myUnit) ret = myModel.File.NewBlank() #Define Concrete Materials MAT_CONC = 2 #concrete enumeration matprop = myModel.PropMaterial matdict = doc.Dictionaries.Item("ConcMaterial") ''' Typical values of the material's XRecord, respectively Val[0]=label, Val[1]=Fc, Val[2]=E, Val[3]=StrainAtFc, Val[4]=UltimateStrain Val[5]=PoisonRatio, Val[6]=ThermalCoeff, Val[7]=UnitWeight ''' i = matdict.Count docname = doc.FullName for j in range(0, i): matXRecord = matdict.Item(j) mathandle = matXRecord.ObjectID dxfgrcd, val = XRecord_return_1(docname, mathandle, 8) #size = 8 ret = matprop.SetMaterial(str(val[0]), MAT_CONC) if program == "ETABS": ret = matprop.SetOConcrete_1(str(val[0]), val[1], False, 0, 2, 4, val[3], val[4], -0.1) elif program == "SAP2000": ret = matprop.SetOConcrete_1(str(val[0]), val[1], False, 0, 2, 2, val[3], val[4], -0.1) ret = matprop.SetWeightAndMass(str(val[0]), 1, val[7]) ret = matprop.SetMPIsotropic(str(val[0]), val[2], val[5], val[6]) mes = "Go and see " + str(val[0]) + " material definition" showinfo(title="User Debug Work", message=mes, icon=INFO) #Define Load Patterns DEAD = 1 LIVE = 3 OTHER = 8 if program == "SAP2000": ret = myModel.LoadPatterns.ADD( "LIVE", LIVE) #SAP2000 doesn't create "LIVE" by default loadpatdict = doc.Dictionaries.Item("LoadPatterns") icount = loadpatdict.Count for i in range(0, icount): loadpatXRecord = loadpatdict.Item(i) loadpathandle = loadpatXRecord.ObjectID dxfgrcd, val = XRecord_return_1(docname, loadpathandle, 2) #Set the Dead self weight multiplier, and add the rest of the load patterns if str(val[0]) == "Dead": if program == "ETABS": ret = myModel.LoadPatterns.SetSelfWTMultiplier( "Dead", float(swm)) elif program == "SAP2000": ret = myModel.LoadPatterns.SetSelfWTMultiplier( "DEAD", float(swm)) elif str(val[0]) == "Live": continue else: if str(val[1]) == "Dead": ret = myModel.LoadPatterns.Add(str(val[0]), DEAD) elif str(val[1]) == "Live": ret = myModel.LoadPatterns.Add(str(val[0]), LIVE) elif str(val[1]) == "Other": ret = myModel.LoadPatterns.Add(str(val[0]), OTHER) #Get modifiers of section properties for frames and slabs if modtypes == 'All set to 1': beammod = [1, 1, 1, 1, 1, 1, 1, 1] colmod = [1, 1, 1, 1, 1, 1, 1, 1] slabmod = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] wallmod = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] elif modtypes == 'As Per ACI M318 11': beammod = [1, 1, 1, 0.01, 0.35, 0.35, 1, 1] colmod = [1, 1, 1, 0.1, 0.7, 0.7, 1, 1] if slabmode == '2D': slabmod = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] elif slabmode == '3D': slabmod = [1, 1, 1, 0.25, 0.25, 1, 1, 1, 1, 1] if wallcrk == 'cracked': wallmod = [1, 1, 1, 0.35, 0.35, 1, 1, 1, 1, 1] elif wallcrk == 'uncracked': wallmod = [1, 1, 1, 0.7, 0.7, 1, 1, 1, 1, 1] elif modtypes == 'Torsional Modifiers Only': beammod = [1, 1, 1, 0.01, 1, 1, 1, 1] colmod = [1, 1, 1, 0.1, 1, 1, 1, 1] slabmod = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] wallmod = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] elif modtypes == 'Egyptian Standard': beammod = [1, 1, 1, 0.01, 1, 1, 1, 1] colmod = [1, 1, 1, 1, 1, 1, 1, 1] if slabmode == '2D': slabmod = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] elif slabmode == '3D': slabmod = [1, 1, 1, 1, 0.2, 0.2, 1, 1, 1, 1] if wallcrk == 'cracked': wallmod = [1, 1, 1, 0.35, 0.35, 1, 1, 1, 1, 1] elif wallcrk == 'uncracked': wallmod = [1, 1, 1, 0.7, 0.7, 1, 1, 1, 1, 1] #Get frame section properties frsecdict = doc.Dictionaries.Item("FrSecProp") icount = frsecdict.Count ''' Typical Values val[0]=label, val[1]=section shape, val[2]=material, val[3]=section type, val[4]=depth or diameter val[5]=breadth or radius, val[6]=unit weight ''' for i in range(0, icount): frsecXRecord = frsecdict.Item(i) frsecHandle = frsecXRecord.ObjectID dxfgrcd, val = XRecord_return_1(docname, frsecHandle, 7) propfr = myModel.PropFrame if str(val[1]) == "Rec": ret = propfr.SetRectangle(str(val[0]), str(val[2]), val[4], val[5]) if str(val[3]) == "Beam": ret = propfr.SetRebarBeam(str(val[0]), "A615Gr60", "A615Gr60", 0.06, 0.06, 0, 0, 0, 0) ret = propfr.SetModifiers(str(val[0]), beammod) elif str(val[3]) == "Column": ret = propfr.SetRebarColumn(str(val[0]), "A615Gr60", "A615Gr60", 1, 1, 0.04, 0, 3, 5, "#20", "#10", 0.015, 0, 0, False) ret = propfr.SetModifiers(str(val[0]), colmod) if str(val[1]) == "Circular": ret = propfr.SetCircle(str(val[0]), str(val[2]), str(val[4])) if str(val[3]) == "Beam": ret = propfr.SetRebarBeam(str(val[0]), "A615Gr60", "A615Gr60", 0.06, 0.06, 0, 0, 0, 0) ret = propfr.SetModifiers(str(val[0]), beammod) elif str(val[3]) == "Column": ret = propfr.SetRebarColumn(str(val[0]), "A615Gr60", "A615Gr60", 1, 1, 0.04, 0, 3, 5, "#20", "#10", 0.015, 0, 0, False) ret = propfr.SetModifiers(str(val[0]), colmod) #Get slab section properties propslab = myModel.PropArea slabsecpropdict = doc.Dictionaries.Item("SlabSecProp") icount = slabsecpropdict.Count SLAB = 0 DROP = 1 SHELLTHIN = 1 SHELLTHICK = 2 MEMBRANE_ETABS = 3 MEMBRANE_SAP = 5 ''' Typical values:- val[0]=label, val[1]=material, val[2]=Etabs thickness, val[3]=SAP2000 thickness, val[4]=unit weight ''' for i in range(0, icount): slabsecXRecord = slabsecpropdict.Item(i) slabsecHandle = slabsecXRecord.ObjectID dxfgrcd, val = XRecord_return_1(docname, slabsecHandle, 5) if modtypes == 'Egyptian Standard' and program == "SAP2000" and swm == '0': thk = val[3] else: thk = val[2] if program == "ETABS": ret = propslab.SetSlab(str(val[0]), SLAB, SHELLTHIN, str(val[1]), thk) elif program == "SAP2000": ret = propslab.SetShell_1(str(val[0]), SHELLTHIN, True, str(val[1]), 0, thk, thk) ret = propslab.SetModifiers(str(val[0]), slabmod) #Get wall section properties [at SAP2000 they will be defined as slab sections] wallsecpropdict = doc.Dictionaries.Item("WallSecProps") icount = wallsecpropdict.Count ''' Typical values:- val[0]=label, val[1]=thickness, val[2]=material ''' for i in range(0, icount): wallsecXRecord = wallsecpropdict.Item(i) wallsecHandle = wallsecXRecord.ObjectID dxfgrcd, val = XRecord_return_1(docname, wallsecHandle, 3) if program == "ETABS": ret = propslab.SetWall(str(val[0]), 1, SHELLTHIN, str(val[2]), val[1]) elif program == "SAP2000": ret = propslab.SetShell_1(str(val[0]), MEMBRANE_SAP, True, str(val[2]), 0, val[1], val[1]) ret = propslab.SetModifiers(str(val[0]), wallmod) #Get Pier IDs if program == "ETABS": pieriddict = doc.Dictionaries.Item("PierIDs") icount = pieriddict.Count for i in range(0, icount): pieridXRecord = pieriddict.Item(i) pieridHandle = pieridXRecord.ObjectID dxfgrcd, val = XRecord_return_1(docname, pieridHandle, 1) ret = myModel.PierLabel.SetPier(str(val[0])) #Get Spandrel IDs spandiddict = doc.Dictionaries.Item("SpandralIDs") icount = spandiddict.Count for i in range(0, icount): spandidXRecord = spandiddict.Item(i) spandidHandle = spandidXRecord.ObjectID dxfgrcd, val = XRecord_return_1(docname, spandidHandle, 1) ret = myModel.SpandrelLabel.SetSpandrel(str(val[0]), False) #From the columns' layer, get base level, then draw the columns (frames and walls) if colyr != 'None' and program == "ETABS": collayer = doc.Layers.Item(colyr) try: sscolyr = doc.SelectionSets.Add("ColumnsLayer") sshlyr = doc.SelectionSets.Add("ShWallLayer") except: sscolyr = doc.SelectionSets.Item("ColumnsLayer") sshlyr = doc.SelectionSets.Item("ShWallLayer") SELECT_ALL = 5 ftype = array.array('h', [0, 8]) #DXF of layers fdata = ['LINE', colyr] #columns' layer sscolyr.Select(SELECT_ALL, (0, 0, 0), (0, 0, 0), ftype, fdata) icount = sscolyr.Count for i in range(0, icount): elem = sscolyr.Item(i) sp = elem.StartPoint ep = elem.EndPoint if i == 0: baselevel = sp[ 2] #initialize baselevel from a valid (not hypothetical) value baselevel = min(sp[2], ep[2], baselevel) try: if baselevel == None: pass except: baselevel = None #get baselevel from Faces (if exist), it's user's responsibility to choose a layer of walls #sscolyr.Clear() fdata = ['3DFACE', colyr] sshlyr.Select(SELECT_ALL, (0, 0, 0), (0, 0, 0), ftype, fdata) icount = sshlyr.Count for i in range(0, icount): elem = sshlyr.Item(i) V1 = elem.Coordinate(0) V2 = elem.Coordinate(1) V3 = elem.Coordinate(2) V4 = elem.Coordinate(3) if i == 0 and baselevel == None: baselevel = V1[2] baselevel = min(V1[2], V2[2], V3[2], V4[2], baselevel) try: myModel.Story.SetElevation("Base", baselevel) except: showerror( title=progname, message= "Columns Layer has no column!\nClose the generated model and try again" ) return retprog = drawlines(docname, sscolyr, colyr, myModel, program, swm, False) #draw the currently selected lines if retprog == 0: return retprog = drawFaces(doc, docname, sshlyr, colyr, myModel, program, swm, False) #draw the currently selected Faces if retprog == 0: return sscolyr.Delete() sshlyr.Delete() #Draw the rest of lines and 3DFaces try: lines = doc.SelectionSets.Add("Frames") Faces = doc.SelectionSets.Add("Shells") Points = doc.SelectionSets.Add("Points") except: #the "try .. except" is to insure using the same selection set among multiple sessions without error lines = doc.SelectionSets.Item("Frames") Faces = doc.SelectionSets.Item("Shells") Points = doc.SelectionSets.Item("Points") icount = doc.Layers.Count for i in range(0, icount): layer = doc.Layers.Item(i) layername = layer.Name if layername != colyr: retprog = drawlines(docname, lines, layername, myModel, program, swm, True) if retprog == 0: return retprog = drawFaces(doc, docname, Faces, layername, myModel, program, swm, True) if retprog == 0: return drawPoints(docname, Points, layername, myModel, True) ret = myModel.View.RefreshView(0, True) showinfo(title=progname, message="Work is Done!") #importing is successful