Beispiel #1
0
 def telescope(self):
     self.c.DeviceType = 'Telescope'
     return CreateObject(self.choose())
Beispiel #2
0
        COMMETHOD([], HRESULT, 'SetOverlayIcon', (['in'], c_int, 'hwnd'),
                  (['in'], POINTER(IUnknown), 'hIcon'),
                  (['in'], c_wchar_p, 'pszDescription')),
        COMMETHOD([], HRESULT, 'SetThumbnailTooltip', (['in'], c_int, 'hwnd'),
                  (['in'], c_wchar_p, 'pszTip')),
        COMMETHOD([], HRESULT, 'SetThumbnailClip', (['in'], c_int, 'hwnd'),
                  (['in'], POINTER(tagRECT), 'prcClip')),
    ]


class TaskbarList(CoClass):
    _com_interfaces_ = [ITaskbarList3]
    _reg_clsid_ = COMGUID('{56FDF344-FD6D-11D0-958A-006097C9A090}')


_taskbar = CreateObject(TaskbarList)
_taskbar.HrInit()


def _get_wsa_error():
    err = WSAGetLastError()
    try:
        return socket.errorTab[err]
    except KeyError:
        return os.strerror(err)


def dup(s):
    '''Duplicate a SOCKET.'''
    info = WSAPROTOCOL_INFO()
    if WSADuplicateSocket(s, os.getpid(), byref(info)):
#生成一百以内带退位减法 带进位加法

from comtypes.client import CreateObject,Constants
import random


app = CreateObject("Excel.Application")
excel_constants = Constants(app)

template_file = "g:/口算作业模板.xlsx"
out_dir = "g:\\"
out_name = out_dir+"口算"

max_number = 100
ratio_sub = 0.6 #减法题的比例
ratio_carry = 0.8 # 进退位比例
total_page = 40 # 总页数
seciton_per_page = 2 #每页的小节数
row_per_section = 10 #每页的行数
col_per_section = 3 #每页的列数
row_starts=[2, 16]

total_add_with_carry = 0 #带进位加法题目数
total_add_with_no_carry=0 #不带进位加法题目数
total_sub_decomposition = 0 #带退位减法题目数
total_sub_no_decomposition=0 #不带退位减法题目数

workbook = app.Workbooks.open(template_file)
# print(workbook.ActiveSheet.Cells(1,1).Value())

random.seed()
Beispiel #4
0
from comtypes.client import CreateObject, GetModule

#### Using the IviScope interface ####
GetModule('IviScopeTypeLib.dll')
from comtypes.gen import IviScopeLib

ivi_scope = CreateObject('Tkdpo2k3k4k.Tkdpo2k3k4k',
                         interface=IviScopeLib.IIviScope)
ivi_scope.Initialize('USB0::0x0699::0x0411::C012048::INSTR', False, False, '')

ivi_scope.Acquisition.ConfigureRecord(TimePerRecord=.1,
                                      MinNumPts=1000,
                                      AcquisitionStartTime=0)
ch1 = ivi_scope.Channels.Item('CH1')
ch1.Configure(Range=.1,
              Offset=0.1,
              Coupling=IviScopeLib.IviScopeVerticalCouplingDC,
              ProbeAttenuation=1,
              Enabled=True)

ch1.Offset = 0.05  # Channel parameters can be configured using properties

waveform = ivi_scope.Measurements.Item('CH1').ReadWaveform(
    MaxTimeMilliseconds=100)

print "Waveform :", waveform[0]
print "Time Origin :", waveform[1]
print "Time Step :", waveform[2]

#### Using the Tkdpo2k3k4k interface ####
from comtypes.gen import Tkdpo2k3k4kLib
 def __init__(self, rr_x=1000, rr_y=1000):
     self.rr = CreateObject("RoboRealm.API.1")
     self.rr_x = rr_x
     self.rr_y = rr_y
def main():
    """ This is the main script to convert a ArcMap-Project"""
    export_name = arcpy.GetParameterAsText(0)

    if not export_name:
        export_name = "C:\\temp\\test.qgs"

    if export_name.endswith(".qgs") or export_name.endswith(".qgz"):
        export_name_short = export_name[:-4]
    else:
        export_name_short = export_name

    qgs_file_name = u"{}.qgs".format(export_name_short)
    qgs_file = codecs.open(qgs_file_name, "w", encoding="utf-8")

    logging = Logger.get_logger(export_name_short)

    xml_document = Document()

    arcpy.AddMessage("Scanning Project and collecting Layer-Information")

    # take Infos from opened ArcMap-Project -> to access the arcObjects
    arc_app = CreateObject(ArcGisModules.module_framework.AppROT,
                           interface=ArcGisModules.module_framework.IAppROT)
    arc_doc = change_interface(
        arc_app.Item(0).Document, ArcGisModules.module_map_ui.IMxDocument)
    arc_doc_info = change_interface(arc_doc,
                                    ArcGisModules.module_carto.IDocumentInfo2)

    header = create_header(xml_document, arc_doc_info)

    if not arc_doc.ActiveView.IsMapActivated:
        arc_doc.ActiveView = arc_doc.FocusMap

    project_path = ""
    try:
        project_path = os.path.dirname(arc_doc_info.Folder)
    except TypeError:
        print "There is no ArcMap-Project open - Will Crash!"
    arcpy.env.workspace = project_path
    arcpy.env.overwriteOutput = True

    # this is the arcpy connection to the document
    mxd_path = os.path.join(arc_doc_info.Path)
    mxd = arcpy.mapping.MapDocument(mxd_path)

    print 'Start Writing'

    for counter, dataframe in enumerate(arcpy.mapping.ListDataFrames(mxd)):
        if counter == 0:
            print 'Creating MapSpatialReferenceSystem.'
            MapSpatialReferenceSystem.create_map_srs_element(
                xml_document, header, dataframe)

        arc_dataframe = arc_doc.Maps.Item[counter]
        layer_list = arcpy.mapping.ListLayers(dataframe)

        arcpy.AddMessage("{} Layers are in the Dataframe".format(
            str(len(layer_list))))

        ProjectLayers.create_project_layers_element(xml_document, header,
                                                    layer_list, arc_dataframe)
        broken_layer_list = brokenLayers.BrokenLayers.broken_layer_list
        for broken_layer in broken_layer_list:
            if broken_layer in layer_list:
                layer_list.remove(broken_layer)
        MapLegend.create_map_legend_element(xml_document, header, layer_list,
                                            dataframe)
        LayerTree.create_layertree(xml_document, header, layer_list, dataframe)
        MapProperties.create_map_properties_element(xml_document, header)

    if len(arcpy.mapping.ListDataFrames(mxd)) > 1:
        VisibilityPresets.initialize_visibility(xml_document, header, mxd)

    arcpy.AddMessage("Creating Layout")
    logging.info("Creating Layout")
    layout = Layout(xml_document, header, arc_doc, mxd).create_layout()

    arcpy.AddMessage("Creating Metadata")
    Metadata.create_metadata(xml_document, header, arc_app)

    try:
        xml_document.writexml(qgs_file,
                              indent="  ",
                              addindent="  ",
                              newl="\n",
                              encoding="UTF-8")
        arcpy.AddMessage("Project saved!")
        arcpy.AddMessage('QGIS-File written')
    finally:
        qgs_file.close()

    if export_name.endswith(".qgz"):
        qgd_file_name = u"{}.qgd".format(export_name_short)
        qgd_file = open(qgd_file_name, "w")
        qgd_file.close()

        with ZipFile(u"{}.qgz".format(export_name_short), "w") as newzip:
            newzip.write(qgs_file_name, os.path.basename(qgs_file.name))
            newzip.write(qgd_file_name, os.path.basename(qgd_file.name))

        arcpy.AddMessage(' and zipped.')
        try:
            os.remove(qgs_file_name)
            os.remove(qgd_file_name)
        except OSError as e:
            print("Error: %s - %s." % (e.filename, e.strerror))
Beispiel #7
0
import unittest
from ctypes import POINTER
from comtypes.automation import IDispatch
from comtypes.client import CreateObject
from comtypes import GUID

##from test import test_support
##from comtypes.unittests import support

try:
    GUID.from_progid("MSScriptControl.ScriptControl")
    CreateObject("MSScriptControl.ScriptControl")
except WindowsError:
    # doesn't exist on Windows CE or in 64-bit.
    pass
else:

    class Test(unittest.TestCase):
        def test_jscript(self):
            engine = CreateObject("MSScriptControl.ScriptControl")
            engine.Language = "JScript"
            # strange.
            #
            # engine.Eval returns a VARIANT containing a dispatch pointer.
            #
            # The dispatch pointer exposes this typeinfo (the number of
            # dispproperties varies, depending on the length of the list we pass
            # to Eval):
            #
            #class JScriptTypeInfo(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDispatch):
            #    'JScript Type Info'
Beispiel #8
0
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 30 12:37:18 2016

@author: thomasaref
"""

from pxi_backbone import PXI_Backbone, pp
from ctypes import create_string_buffer, byref, c_double, c_ulong, c_long

if 0:  #Code for generating COM module
    from comtypes.client import CreateObject
    s=CreateObject("afComSigGen.afCoSigGen")
from comtypes.gen import AFCOMSIGGENLib

class afSigGen(PXI_Backbone):
    def __init__(self):
        """initializes using PXI_Bacbone __init__ with particular arguments"""
        super(afSigGen, self).__init__(lib_name='afSigGenDll_32.dll', com_lib=AFCOMSIGGENLib)

    mode=pp('Mode', prefix='m') #Manual
    LO_reference=pp('LO_Reference', prefix='lorm') #OXCO, ExternalTerminated, ExternalDaisy, Internal
    modulation_source=pp('Manual_ModulationSource', prefix='ms') #CW, LVDS, ARB, AM, FM, ExtAnalog
    frequency=pp('Manual_Frequency', dtype=c_double)
    level=pp('Manual_Level', dtype=c_double)
    level_mode=pp("Manual_LevelMode", prefix="lm") #Auto, Frozen, Peak, Rms,

    #level_max=pp("Manual_LevelMax", dtype=c_double)
    output=pp('Manual_RfState', prefix=bool)

    arb_external_trigger_enable=pp('ARB_ExternalTrigger_Enable', prefix=bool)
Beispiel #9
0
def aoObj(myClass, myInterface):
    try:
        obj = CreateObject(myClass, interface=myInterface)
        return obj
    except:
        return None
Beispiel #10
0
def main():
    """ This function converts a style gallery to XML"""
    style_file_path = arcpy.GetParameterAsText(0)
    export_name_path = arcpy.GetParameterAsText(1)
    classes_to_export = arcpy.GetParameter(2)

    arcpy.AddMessage("Start Processing...")

    style_gallery = CreateObject(
        ArcGisModules.module_framework.StyleGallery,
        interface=ArcGisModules.module_display.IStyleGallery)

    storage = change_interface(
        style_gallery, ArcGisModules.module_display.IStyleGalleryStorage)
    style_file_service = CheckIfStyleFileIsAlreadyInStorageService()

    if storage.DefaultStylePath in style_file_path:
        style_gallery_name = style_file_path.replace(storage.DefaultStylePath,
                                                     "")
    else:
        style_gallery_name = style_file_path
    style_file_service.check_style_file(storage, style_gallery_name)

    if not style_file_service.style_file_exists_in_storage:
        storage.AddFile(style_file_path)

    qgis_style_xml = codecs.open(export_name_path, "w", encoding="utf-8")

    xml_document = Document()

    root_element = xml_document.createElement("qgis_style")
    root_element.setAttribute("version", "2")
    xml_document.appendChild(root_element)

    for class_to_export in classes_to_export:
        if class_to_export in [
                u'Marker Symbols', u'Fill Symbols', u'Line Symbols'
        ]:
            SymbolCreator(xml_document).create_symbols(style_gallery,
                                                       style_gallery_name,
                                                       class_to_export)
        elif class_to_export == u'Color Ramps':
            ColorRampCreator(xml_document).create_colorramps(
                style_gallery, style_gallery_name)
        elif class_to_export == u'Text Symbols':
            TextFormatCreator(xml_document).create_text_formats(
                style_gallery, style_gallery_name)
        elif class_to_export == u'Labels':
            LabelSettingsCreator(xml_document).create_label_settings(
                style_gallery, style_gallery_name)

    if not style_file_service.style_file_exists_in_storage:
        storage.RemoveFile(style_file_path)

    try:
        xml_document.writexml(qgis_style_xml,
                              indent="  ",
                              addindent="  ",
                              newl="\n",
                              encoding="UTF-8")
        arcpy.AddMessage("Style File saved!")
    finally:
        qgis_style_xml.close()
Beispiel #11
0
def RunSTK(dfSlice, tradeStudy, processNum, showSTK=False, saveEveryNIter=15):
    pythoncom.CoInitialize()
    fileNamekk = str.split(tradeStudy.fileName,
                           '.')[0] + str(processNum) + '.' + str.split(
                               tradeStudy.fileName, '.')[-1]
    fileName = os.getcwd() + '\\Results\\' + fileNamekk
    maxDur = tradeStudy.maxDur
    decayAlt = tradeStudy.decayAlt
    runHPOP = tradeStudy.runHPOP
    df = dfSlice.reset_index(drop=True)

    if 'epoch' in df.columns:
        epoch1 = df['epoch'].iloc[0]
        epoch2 = epoch1 + 1
        epochs = df['epoch'].to_numpy()
        if (epochs[0] == epochs[1:]).all():
            updateEachEpoch = False
        else:
            updateEachEpoch = True
            updateState = True
    else:
        epoch1 = 19253.166667
        epoch2 = 19254.166667
        updateEachEpoch = False

    # Connect to STK
    start = time.time()
    app = CreateObject('STK11.Application')
    app.Visible = showSTK
    app.UserControl = showSTK
    root = app.Personality2
    root.NewScenario('LifeTimeAnalysis' + str(processNum))

    print('LifeTimeAnalysis' + str(processNum) + ' has started.')
    epoch1 = str(epoch1)
    epoch2 = str(epoch2)
    root.ExecuteCommand('Units_Set * All DateFormat YYDDD')
    root.UnitPreferences.SetCurrentUnit('DateFormat', 'YYDDD')
    sc = root.CurrentScenario
    sc2 = root.CurrentScenario.QueryInterface(STKObjects.IAgScenario)
    sc2.SetTimePeriod(epoch1, epoch2)
    root.ExecuteCommand('Units_Set * All DateFormat EpYr')
    root.ExecuteCommand('Units_SetConnect / Distance km')
    root.UnitPreferences.SetCurrentUnit('DateFormat', 'EpYr')
    epoch1 = root.ConversionUtility.ConvertDate('YYDDD', 'EpYr', epoch1)
    satName = 'Satellite1'

    # Convert Dateframe to string
    dfstr = df.astype(str)

    # Figureout what needs to be updated at each iteration
    def updateFlags(tradeStudy):
        updateLTtradeStudy = False
        updateSatProp = False
        updateState = False
        varyCols = tradeStudy.varyCols

        if any(col in [
                'epoch', 'x', 'y', 'z', 'Vx', 'Vy', 'Vz', 'a', 'e', 'i', 'Aop',
                'RAAN', 'TA', 'Rp', 'Ra'
        ] for col in varyCols):
            updateState = True

        if any(col in ['Cd', 'Cr', 'Drag Area', 'Sun Area', 'Mass']
               for col in varyCols):
            updateSatProp = True

        if any(col in [
                'Orb Per Calc', 'Gaussian Quad', 'Flux Sigma Level',
                'SolarFluxFile', 'Density Model', '2nd Order Oblateness'
        ] for col in varyCols):
            updateLTtradeStudy = True

        if tradeStudy.howToVary.lower() == 'perturb':
            updateLTtradeStudy = False

        if tradeStudy.howToVary.lower() == 'lifetimevariations':
            updateLTtradeStudy = True
            updateSatProp = True
            updateState = True

        if tradeStudy.runHPOP == True:
            updateLTtradeStudy = True
            updateSatProp = True
            updateState = True

        return updateLTtradeStudy, updateSatProp, updateState

    # Convert drag model equivalent and HPOP solar flux file
    def atmDenEnu(atmDenStr):
        return {
            '1976 Standard': 0,
            'CIRA 1972': 1,
            'Harris-Priester': 3,
            'Jacchia-Roberts': 4,
            'Jacchia70Lifetime': 6,
            'Jacchia 1970': 6,
            'Jacchia 1971': 7,
            'NRLMSISE 2000': 8,
            'MSIS 1986': 9,
            'MSISE 1990': 10,
            'DTM 2012': STKObjects.eDTM2012,
        }[atmDenStr]

    def SolFluxSigEnu(SolarFluxLevel):
        return {
            -2: 'SolFlx_CSSI_Minus2.dat',
            -1: 'SolFlx_CSSI_Minus1.dat',
            0: 'SolFlx_CSSI.dat',
            1: 'SolFlx_CSSI_Plus1.dat',
            2: 'SolFlx_CSSI_Plus2.dat',
        }[SolarFluxLevel]

    # tradeStudyure the updates
    updateLTtradeStudy, updateSatProp, updateState = updateFlags(tradeStudy)

    if runHPOP == True:
        if len(df) > 0:
            for i in range(len(df)):
                if np.isnan(df['HPOP Years'][i]):  # Not previously run

                    # Create or get satellite
                    if sc.Children.Contains(STKObjects.eSatellite,
                                            satName) == True:
                        sat = root.GetObjectFromPath('Satellite/' + satName)
                        sat.Unload()
                    sat = sc.Children.New(STKObjects.eSatellite, satName)
                    sat2 = sat.QueryInterface(STKObjects.IAgSatellite)
                    prop = sat2.SetPropagatorType(STKObjects.ePropagatorHPOP)
                    prop = sat2.Propagator.QueryInterface(
                        STKObjects.IAgVePropagatorHPOP)

                    # Initialize satellite
                    if updateEachEpoch == True:
                        epYr = root.ConversionUtility.ConvertDate(
                            'YYDDD', 'EpYr', dfstr['epoch'].iloc[i])
                    else:
                        epYr = epoch1

                    prop.EphemerisInterval.SetExplicitInterval(
                        float(epYr),
                        float(epYr) + 1e-5)
                    prop.InitialState.OrbitEpoch.SetExplicitTime(epYr)
                    prop.InitialState.Representation.AssignCartesian(
                        STKUtil.eCoordinateSystemICRF, df['x'].iloc[i],
                        df['y'].iloc[i], df['z'].iloc[i], df['Vx'].iloc[i],
                        df['Vy'].iloc[i], df['Vz'].iloc[i])
                    prop.Propagate()

                    # tradeStudyure Lifetime and satellite
                    cmd = ('SetLifetime */Satellite/' + satName +
                           ' LimitType Duration DurationLimit ' +
                           str(maxDur * 365.25) + ' DecayAltitude ' +
                           str(decayAlt))
                    root.ExecuteCommand(cmd)

                    if updateLTtradeStudy == True:
                        cmd = ('SetLifetime */Satellite/' + satName +
                               ' DensityModel "' +
                               dfstr['Density Model'].iloc[i] + '"' +
                               ' FluxSigmaLevel ' +
                               dfstr['Flux Sigma Level'].iloc[i] +
                               ' OrbPerCalc ' + dfstr['Orb Per Calc'].iloc[i] +
                               ' GaussianQuad ' +
                               dfstr['Gaussian Quad'].iloc[i] + ' 2ndOrder ' +
                               dfstr['2nd Order Oblateness'].iloc[i])
                        root.ExecuteCommand(cmd)
                        cmd = (
                            'SetLifetime */Satellite/' + satName +
                            ' SolarFluxFile "C:\\ProgramData\\AGI\\STK 11 (x64)\\DynamicEarthData\\'
                            + dfstr['SolarFluxFile'].iloc[i] + '"')
                        root.ExecuteCommand(cmd)

                    if updateSatProp == True:
                        cmd = ('SetLifetime */Satellite/' + satName +
                               ' DragCoeff ' + dfstr['Cd'].iloc[i] +
                               ' ReflectCoeff ' + dfstr['Cr'].iloc[i] +
                               ' DragArea ' + dfstr['Drag Area'].iloc[i] +
                               ' SunArea ' + dfstr['Sun Area'].iloc[i] +
                               ' Mass ' + dfstr['Mass'].iloc[i])
                        root.ExecuteCommand(cmd)

                    # Run LT
                    cmd = 'Lifetime */Satellite/' + satName
                    start2 = time.time()
                    res = root.ExecuteCommand(cmd)
                    stop2 = time.time()

                    if res.Item(0).split()[1] == 'decay':
                        df.loc[i, 'LT Orbits'] = res.Item(0).split()[9]
                        df.loc[i, 'LT Years'] = float(
                            res.Item(0).split()[7]) - float(epYr)
                    elif res.Item(0).split()[-1] == 'begin.':
                        df.loc[i, 'LT Orbits'] = 0
                        df.loc[i, 'LT Years'] = 0
                    elif res.Item(0).split()[-1] == 'limit.':
                        df.loc[i, 'LT Orbits'] = 999999
                        df.loc[i, 'LT Years'] = maxDur
                    else:
                        print('i = ' + str(i) + '. ' + res.Item(0))
                    df.loc[i, 'LT Runtime'] = stop2 - start2

                    # tradeStudy HPOP

                    prop.EphemerisInterval.SetExplicitInterval(
                        float(epYr),
                        float(epYr) + maxDur)
                    prop.Step = 60
                    prop.Integrator.ReportEphemOnFixedTimeStep = False
                    if dfstr['Density Model'].iloc[i] in [
                            'NRLMSISE 2000', 'MSISE 1990'
                    ]:
                        prop.Integrator.UseVOP = False
                    else:
                        prop.Integrator.UseVOP = True
                    drag = prop.ForceModel.Drag.DragModel.QueryInterface(
                        STKObjects.IAgVeHPOPDragModelSpherical)
                    srp = prop.ForceModel.SolarRadiationPressure.SRPModel.Model.QueryInterface(
                        STKObjects.IAgSRPModelSpherical)
                    prop.ForceModel.Drag.SetSolarFluxGeoMagType(
                        STKObjects.eSolarFluxGeoMagUseFile)
                    dragFile = prop.ForceModel.Drag.SolarFluxGeoMag.QueryInterface(
                        STKObjects.IAgVeSolarFluxGeoMagUseFile)
                    prop.ForceModel.MoreOptions.Static.SatelliteMass = df[
                        'Mass'].iloc[i]
                    drag.Cd = df['Cd'].iloc[i]
                    drag.AreaMassRatio = df['Drag Area'].iloc[i] / df[
                        'Mass'].iloc[i]
                    srp.Cr = df['Cr'].iloc[i]
                    srp.AreaMassRatio = df['Sun Area'].iloc[i] / df[
                        'Mass'].iloc[i]
                    prop.ForceModel.Drag.AtmosphericDensityModel = atmDenEnu(
                        dfstr['Density Model'].iloc[i])
                    if dfstr['SolarFluxFile'].iloc[i] == 'SolFlx_CSSI.dat':
                        dragFile.File = 'C:\\ProgramData\\AGI\\STK 11 (x64)\\DynamicEarthData\\' + SolFluxSigEnu(
                            df['Flux Sigma Level'].iloc[i])
                    else:
                        dragFile.File = 'C:\\ProgramData\\AGI\\STK 11 (x64)\\DynamicEarthData\\' + dfstr[
                            'SolarFluxFile'].iloc[i]

                    # Run HPOP
                    startHPOP = time.time()
                    try:
                        prop.Propagate()
                    except:
                        pass
                    stopHPOP = time.time()

                    # Record Results
                    df.loc[i, 'HPOP Runtime'] = stopHPOP - startHPOP
                    startEph = float(
                        sat.Vgt.Events.Item(
                            'EphemerisStartTime').FindOccurrence().Epoch)
                    stopEph = float(
                        sat.Vgt.Events.Item(
                            'EphemerisStopTime').FindOccurrence().Epoch)
                    HPOPLT = stopEph - startEph
                    df.loc[i, 'HPOP Years'] = HPOPLT

                    stop = time.time()

                    print('LifeTimeAnalysis' + str(processNum) + ' ' +
                          str(i + 1) + ' of ' + str(len(df)) +
                          '. Total Time: ' + str(stop - start))
                    print('LifeTimeAnalysis' + str(processNum) +
                          ' HPOP Lifetime: ' +
                          df.loc[i, 'HPOP Years'].astype(str) + '. Runtime ' +
                          str(stopHPOP - startHPOP))
                    print(res.Item(0))

                    # Save as you go
                    df.to_csv(fileName)  # Save the file for future use
                    print('\t')
                    print('LifeTimeAnalysis' + str(processNum) + ' wrote to ' +
                          fileName)
                    print('\t')

                    # Unload satellite because HPOP properties sometimes don't get reset properly
                    sat.Unload()
    else:

        # Create or get satellite
        if sc.Children.Contains(STKObjects.eSatellite, satName) == False:
            sat = sc.Children.New(STKObjects.eSatellite, satName)
            sat2 = sat.QueryInterface(STKObjects.IAgSatellite)
            prop = sat2.SetPropagatorType(STKObjects.ePropagatorJ4Perturbation)
            prop = sat2.Propagator.QueryInterface(
                STKObjects.IAgVePropagatorJ4Perturbation)
        else:
            sat = root.GetObjectFromPath('Satellite/' + satName)
            sat2 = sat.QueryInterface(STKObjects.IAgSatellite)
            prop = sat2.Propagator.QueryInterface(
                STKObjects.IAgVePropagatorJ4Perturbation)

        # tradeStudyure Lifetime and satellite
        cmd = ('SetLifetime */Satellite/' + satName +
               ' LimitType Duration DurationLimit ' + str(maxDur * 365.25) +
               ' DecayAltitude ' + str(decayAlt))
        root.ExecuteCommand(cmd)

        ii = 0
        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 = 1e-3
        epYr = epoch1
        prop.InitialState.OrbitEpoch.SetExplicitTime(epYr)
        prop.StartTime = float(epYr)
        prop.StopTime = float(epYr) + 1e-10
        prop.Propagate()

        cmd = ('SetLifetime */Satellite/' + satName + ' DensityModel "' +
               dfstr['Density Model'].iloc[ii] + '"' + ' FluxSigmaLevel ' +
               dfstr['Flux Sigma Level'].iloc[ii] + ' OrbPerCalc ' +
               dfstr['Orb Per Calc'].iloc[ii] + ' GaussianQuad ' +
               dfstr['Gaussian Quad'].iloc[ii] + ' 2ndOrder ' +
               dfstr['2nd Order Oblateness'].iloc[ii])
        root.ExecuteCommand(cmd)
        cmd = (
            'SetLifetime */Satellite/' + satName +
            ' SolarFluxFile "C:\\ProgramData\\AGI\\STK 11 (x64)\\DynamicEarthData\\'
            + dfstr['SolarFluxFile'].iloc[ii] + '"')
        root.ExecuteCommand(cmd)

        cmd = ('SetLifetime */Satellite/' + satName + ' DragCoeff ' +
               dfstr['Cd'].iloc[ii] + ' ReflectCoeff ' + dfstr['Cr'].iloc[ii] +
               ' DragArea ' + dfstr['Drag Area'].iloc[ii] + ' SunArea ' +
               dfstr['Sun Area'].iloc[ii] + ' Mass ' + dfstr['Mass'].iloc[ii])
        root.ExecuteCommand(cmd)

        # Run Lifetime
        k = 0

        if len(df) > 0:
            for i in range(len(df)):
                if np.isnan(df['LT Years'][i]):  # Not previously run
                    if updateLTtradeStudy == True:
                        cmd = ('SetLifetime */Satellite/' + satName +
                               ' DensityModel "' +
                               dfstr['Density Model'].iloc[i] + '"' +
                               ' FluxSigmaLevel ' +
                               dfstr['Flux Sigma Level'].iloc[i] +
                               ' OrbPerCalc ' + dfstr['Orb Per Calc'].iloc[i] +
                               ' GaussianQuad ' +
                               dfstr['Gaussian Quad'].iloc[i] + ' 2ndOrder ' +
                               dfstr['2nd Order Oblateness'].iloc[i])
                        root.ExecuteCommand(cmd)
                        cmd = (
                            'SetLifetime */Satellite/' + satName +
                            ' SolarFluxFile "C:\\ProgramData\\AGI\\STK 11 (x64)\\DynamicEarthData\\'
                            + dfstr['SolarFluxFile'].iloc[i] + '"')
                        root.ExecuteCommand(cmd)

                    if updateSatProp == True:
                        cmd = ('SetLifetime */Satellite/' + satName +
                               ' DragCoeff ' + dfstr['Cd'].iloc[i] +
                               ' ReflectCoeff ' + dfstr['Cr'].iloc[i] +
                               ' DragArea ' + dfstr['Drag Area'].iloc[i] +
                               ' SunArea ' + dfstr['Sun Area'].iloc[i] +
                               ' Mass ' + dfstr['Mass'].iloc[i])
                        root.ExecuteCommand(cmd)

                    if updateEachEpoch == True:
                        epYr = root.ConversionUtility.ConvertDate(
                            'YYDDD', 'EpYr', dfstr['epoch'].iloc[i])
                        prop.InitialState.OrbitEpoch.SetExplicitTime(epYr)

                    if updateState == True:
                        prop.InitialState.Representation.AssignCartesian(
                            STKUtil.eCoordinateSystemICRF, df['x'].iloc[i],
                            df['y'].iloc[i], df['z'].iloc[i], df['Vx'].iloc[i],
                            df['Vy'].iloc[i], df['Vz'].iloc[i])
                        prop.Propagate()

                    cmd = 'Lifetime */Satellite/' + satName
                    start2 = time.time()
                    res = root.ExecuteCommand(cmd)
                    stop2 = time.time()

                    if res.Item(0).split()[1] == 'decay':
                        df.loc[i, 'LT Orbits'] = res.Item(0).split()[9]
                        df.loc[i, 'LT Years'] = float(
                            res.Item(0).split()[7]) - float(epYr)
                    elif res.Item(0).split()[-1] == 'begin.':
                        df.loc[i, 'LT Orbits'] = 0
                        df.loc[i, 'LT Years'] = 0
                    elif res.Item(0).split()[-1] == 'limit.':
                        df.loc[i, 'LT Orbits'] = 999999
                        df.loc[i, 'LT Years'] = maxDur
                    else:
                        print('i = ' + str(i) + '. ' + res.Item(0))
                    df.loc[i, 'LT Runtime'] = stop2 - start2
                    stop = time.time()

                    # Print results
                    if ((i + 1) % 5 == 0):
                        print('LifeTimeAnalysis' + str(processNum) + ' ' +
                              str(i + 1) + ' of ' + str(len(df)) +
                              '. Total Time: ' + str(stop - start))
        #             print('\t'+res.Item(0))

        # Save as you go
                    if ((i + 1) % saveEveryNIter == 0):
                        df.to_csv(fileName)  # Save the file for future use
                        print('\t')
                        print('LifeTimeAnalysis' + str(processNum) +
                              ' wrote to ' + fileName)
                        print('\t')

    # Save Results
    df.to_csv(fileName)  # Save the file for future use

    app.Quit()
    del app
    print('\t')
    print('LifeTimeAnalysis' + str(processNum) + ' done. Wrote to ' + fileName)
    print('\t')
    return str(processNum) + ' Done'
Beispiel #12
0
import comtypes.client
from comtypes.client import GetModule, CreateObject, GetEvents
GetModule(r'SKCOM.dll')

import comtypes.gen.SKCOMLib as sk
from utils import *
import threading
from function import predict

if 'skC' not in globals():
    skC = CreateObject(sk.SKCenterLib, interface=sk.ISKCenterLib)
if 'skQ' not in globals():
    skQ = CreateObject(sk.SKQuoteLib, interface=sk.ISKQuoteLib)
if 'skR' not in globals():
    skR = CreateObject(sk.SKReplyLib, interface=sk.ISKReplyLib)


class skR_events:
    def OnReplyMessage(self, bstrUserID, bstrMessage, sConfirmCode=0xFFFF):
        print('OnReplyMessage', bstrUserID, bstrMessage)
        return sConfirmCode


class SKQuoteLibEvents:
    def __init__(self):
        self.data = []

    def setTick(self, tickData):
        self.tickData = tickData

    def setStockNum(self, stockNum):
Beispiel #13
0
def run_stk_v2(stk_data_path, scenario_path, study_name, orbit_data,
               argument_of_perigees):

    # 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

    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)

    commands_idx = 0
    # Get target lighting before loop
    root.ExecuteCommand(commands[commands_idx])
    commands_idx += 1
    for i in range(orbit_data.shape[0] - 1):
        for k, arg_perigee in enumerate(argument_of_perigees):
            sim_file_name = '{}\{}\DVP_{}_{}perigee{}apogee_{}argperi'.format(
                stk_data_path, study_name, study_name, orbit_data[i + 1][0],
                orbit_data[i + 1][1], arg_perigee)

            for j in range(4):
                time_start = time.time()
                if j == 0:
                    print('Adjusting Satellite orbit...')
                    if not os.path.exists('{}_access.csv'.format(
                            sim_file_name)) or not os.path.exists(
                                '{}_range.txt'.format(sim_file_name)
                            ) or not os.path.exists(
                                '{}_lighting.csv'.format(sim_file_name)):
                        root.ExecuteCommand(commands[commands_idx])

                elif j == 1:
                    print('Generating SPS access report...')
                    if not os.path.exists(
                            '{}_access.csv'.format(sim_file_name)):
                        print(commands[commands_idx])
                        root.ExecuteCommand(commands[commands_idx])
                    else:
                        print(
                            'Access report for {} x {} km orbit at {} argument of perigee already exists'
                            .format(orbit_data[i + 1][0], orbit_data[i + 1][1],
                                    arg_perigee))

                elif j == 2:
                    print('Generating SPS range report...')
                    if not os.path.exists(
                            '{}_range.txt'.format(sim_file_name)):
                        print(commands[commands_idx])
                        root.ExecuteCommand(commands[commands_idx])
                    else:
                        print(
                            'Range report for {} x {} km orbit at {} argument of perigee already exists'
                            .format(orbit_data[i + 1][0], orbit_data[i + 1][1],
                                    arg_perigee))

                elif j == 3:
                    print('Generating SPS lighting report...')
                    if not os.path.exists(
                            '{}_lighting.csv'.format(sim_file_name)):
                        print(commands[commands_idx])
                        root.ExecuteCommand(commands[commands_idx])
                    else:
                        print(
                            'Lighting for {} x {} km orbit at {} argument of perigee already exists'
                            .format(orbit_data[i + 1][0], orbit_data[i + 1][1],
                                    arg_perigee))

                # Print progress update
                time_end = time.time()
                commands_idx += 1
                print('Progress: {}%, Execution Time: {} seconds'.format(
                    round(commands_idx * 100.0 / size, 2),
                    round(time_end - time_start, 5)))
                duration[commands_idx - 1] = 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)))
    def _doit(self, dynamic):
        self.xl = CreateObject("Excel.Application", dynamic=dynamic)

        xl = self.xl
        xl.Visible = 0
        self.assertEqual(xl.Visible, False)
        xl.Visible = 1
        self.assertEqual(xl.Visible, True)

        wb = xl.Workbooks.Add()

        # Test with empty-tuple argument
        xl.Range["A1", "C1"].Value[()] = (10, "20", 31.4)
        xl.Range["A2:C2"].Value[()] = ('x', 'y', 'z')
        # Test with empty slice argument
        xl.Range["A3:C3"].Value[:] = ('3', '2', '1')
        ## not (yet?) implemented:
        ##        xl.Range["A4:C4"].Value = ('3','2','1')

        # call property to retrieve value
        self.assertEqual(xl.Range["A1:C3"].Value(),
                         ((10.0, 20.0, 31.4), ("x", "y", "z"),
                          (3.0, 2.0, 1.0)))
        # index with empty tuple
        self.assertEqual(xl.Range["A1:C3"].Value[()],
                         ((10.0, 20.0, 31.4), ("x", "y", "z"),
                          (3.0, 2.0, 1.0)))
        # index with empty slice
        self.assertEqual(xl.Range["A1:C3"].Value[:],
                         ((10.0, 20.0, 31.4), ("x", "y", "z"),
                          (3.0, 2.0, 1.0)))
        self.assertEqual(xl.Range["A1:C3"].Value[xlRangeValueDefault],
                         ((10.0, 20.0, 31.4), ("x", "y", "z"),
                          (3.0, 2.0, 1.0)))
        self.assertEqual(xl.Range["A1", "C3"].Value[()],
                         ((10.0, 20.0, 31.4), ("x", "y", "z"),
                          (3.0, 2.0, 1.0)))

        r = xl.Range["A1:C3"]
        i = iter(r)

        # Test for iteration support in 'Range' interface
        self.assertEqual([c.Value() for c in xl.Range["A1:C3"]],
                         [10.0, 20.0, 31.4, "x", "y", "z", 3.0, 2.0, 1.0])

        # With pywin32, one could write xl.Cells(a, b)
        # With comtypes, one must write xl.Cells.Item(1, b)

        for i in range(20):
            xl.Cells.Item[i + 1, i + 1].Value[()] = "Hi %d" % i
            print(xl.Cells.Item[i + 1, i + 1].Value[()])

        for i in range(20):
            xl.Cells(i + 1, i + 1).Value[()] = "Hi %d" % i
            print(xl.Cells(i + 1, i + 1).Value[()])

        # test dates out with Excel
        xl.Range["A5"].Value[()] = "Excel time"
        xl.Range["B5"].Formula = "=Now()"
        self.assertEqual(xl.Cells.Item[5, 2].Formula, "=NOW()")

        xl.Range["A6"].Calculate()
        excel_time = xl.Range["B5"].Value[()]
        self.assertEqual(type(excel_time), datetime.datetime)
        python_time = datetime.datetime.now()

        self.assertTrue(python_time >= excel_time)
        self.assertTrue(
            python_time - excel_time < datetime.timedelta(seconds=1))

        # some random code, grabbed from c.l.p
        sh = wb.Worksheets[1]

        sh.Cells.Item[1, 1].Value[()] = "Hello World!"
        sh.Cells.Item[3, 3].Value[()] = "Hello World!"
        sh.Range[sh.Cells.Item[1, 1],
                 sh.Cells.Item[3, 3]].Copy(sh.Cells.Item[4, 1])
        sh.Range[sh.Cells.Item[4, 1], sh.Cells.Item[6, 3]].Select()
Beispiel #15
0
import sys
from comtypes.client import CreateObject
from comtypes.safearray import safearray_as_ndarray
import numpy as np

camID = 'ASCOM.ASICamera2.Camera'
print("camID = ", camID)

#cam = Dispatch(camID)
cam = CreateObject(camID)
print(dir(cam))
print("cam = ", cam)
print("cam.Connected = ", cam.Connected)

if not cam.Connected:
    cam.Connected = True

print("Camera Properties")

print("Binning (X x Y)      : ", cam.BinX, cam.BinY)
print("Camera State         : ", cam.CameraState)
print("Camera Size          : ", cam.CameraXSize, cam.CameraYSize)
print("CanGetCoolerPower    : ", cam.CanGetCoolerPower)
print("CanSetCCDTemperature : ", cam.CanSetCCDTemperature)
print("CCDTemperature       : ", cam.CCDTemperature)
print("Connected            : ", cam.Connected)
print("CoolerOn             : ", cam.CoolerOn)
print("CoolerPower          : ", cam.CoolerPower)
print("Description          : ", cam.Description)
print("DriverVersion        : ", cam.DriverVersion)
print("MaxBinX x MaxBinY    : ", cam.MaxBinX, cam.MaxBinY)
Beispiel #16
0
 def show_chooser(self, last_choice):
     chooser = CreateObject("ASCOM.Utilities.Chooser")
     chooser.DeviceType = "Camera"
     camera = chooser.Choose(last_choice)
     logging.debug(f'choice = {camera}')
     return camera
Beispiel #17
0
from comtypes.client import CreateObject, Constants
try:
    from comtypes.gen import TEMScripting
except:
    CreateObject("TEMScripting.Instrument")
    from comtypes.gen import TEMScripting

from comtypes.client import GetModule

from .acquisition import Acquisition
from .autoloader import AutoLoader
from .illumination import Illumination
from .temperatureControl import TemperatureControl
from .vacuum import Vacuum
from .camera import Camera
from .projection import Projection
from .gun import Gun
from .stage import Stage


class Instrument():

    try:
        instrument = CreateObject("TEMScripting.Instrument")
    except:
        print('Could not create instrument')

    acquisition = Acquisition(instrument)
    autoloader = AutoLoader(instrument)
    camera = Camera(instrument)
    gun = Gun(instrument)
Beispiel #18
0
 def __init__(self):
     #word文档转化为pdf文档时使用的格式为17
     self.wdFormatPDF = 17
     self.wdToPDF = CreateObject("Word.Application")
Beispiel #19
0
 def setUp(self):
     self.d = CreateObject("Scripting.Dictionary", dynamic=False)
Beispiel #20
0
 def create_object(self):
     return CreateObject("TestComServerLib.TestComServer",
                         clsctx=comtypes.CLSCTX_LOCAL_SERVER)
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()
Beispiel #22
0
    keplerian_i.Orientation.AscNode.QueryInterface(
        STKObjects.IAgOrientationAscNodeRAAN
    ).Value = ascnode  # 升交点赤经:赤道平面春分点向右与升交点夹角

    # 定义卫星在轨道中的位置
    keplerian_i.Location.QueryInterface(
        STKObjects.IAgClassicalLocationMeanAnomaly
    ).Value = location  #平近点角:卫星从近地点开始按平均轨道角速度运动转过的角度

    propagator_i.InitialState.Representation.Assign(keplerian)
    # 启动卫星
    propagator_i.Propagate()
    return satellite


app = CreateObject("STK11.Application")
# app.Visible= True
# app.UserControl= True

root = app.Personality2
root.NewScenario("get_orbit")
sc = root.CurrentScenario
sc2 = sc.QueryInterface(STKObjects.IAgScenario)
sc2.StartTime = '10 Jan 2020 04:00:00.000'
sc2.StopTime = '20 Jan 2020 04:00:00.000'

df = pd.DataFrame()
for i in range(10):
    ranum = np.random.rand()
    meanmotion = 7 * ranum + 7
    eccentricity = ranum
Beispiel #23
0
if not os.path.exists("images"):
    os.mkdir("images")
else:
    import shutil

    shutil.rmtree("images")
    os.mkdir("images")

image_directory = pathlib.Path("images")

import comtypes.client
#comtypes.client.gen_dir = None
from comtypes.client import CreateObject

word = CreateObject("Word.Application")
word.Visible = False

from comtypes.gen import Word as constants

imagemagick = "magick.exe"

# [(file name, word image, html image)]
results = []

if __name__ == "__main__":
    if len(sys.argv) != 1:
        file_names = [pathlib.Path(p) for p in sys.argv[1:]]
    else:
        file_names = list(pathlib.Path("docs").iterdir())
Beispiel #24
0
 def create_com_object():
     if not DLL_IS_LOADED:
         raise WindowsError("Could not locate Agilent DLLs")
     reader = CreateObject(
         'Agilent.MassSpectrometry.DataAnalysis.MassSpecDataReader')
     return reader
Beispiel #25
0
from InstrumentConfig import InstrumentQuantity
from numpy import log10, array
import numpy as np
#import visa
from comtypes.client import CreateObject#, GetModule
#from pythoncom import CoInitialize
from comtypes import CoInitialize


#Ensure module is created before importing
#Back up code to create module:
#GetModule("AgNA.dll")
try:
    import comtypes.gen.AgilentNALib as AgilentNALib
except ImportError:
    VNA=CreateObject('AgilentNA.AgilentNA')
    VNA.Release()
    import comtypes.gen.AgilentNALib as AgilentNALib


def cached_property(default_func):
    """a cached property decorator. only resets when set to None"""
    def get_value(self):
        if get_value.value is None:
            get_value.value=default_func(self)
        return get_value.value
    get_value.value=None

    def set_value(self, value):
        get_value.value=value
        
Beispiel #26
0
 def create_com_object_filter():
     if not DLL_IS_LOADED:
         raise WindowsError("Could not locate Agilent DLLs")
     no_filter = CreateObject(
         'Agilent.MassSpectrometry.DataAnalysis.MsdrPeakFilter')
     return no_filter
Beispiel #27
0
import pyttsx3 as pyttsx  #使用pyttsx实现
engine = pyttsx.init()  #初始化
engine.say('大家好')  #文字转化语音
engine.runAndWait()  #运行
#***********************************
from win32com.client import Dispatch  #导入Dispatch对象
sperker = Dispatch('SAPI.SpVoice')  #生成对象
str = open("1.txt", encoding="utf-8").read()  #打开文本
sperker.Speak(str)  #朗读
sperker.Speak('我是赵桐')
del sperker  #释放对象
#***********************************
from comtypes.client import CreateObject
from comtypes.gen import SpeechLib
engine = CreateObject("SAPI.SpVoice")
stream = CreateObject('SAPI.SpFileStream')  #输出流
stream.open('1.wav', SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream  #接通管道
f = open('1.txt', 'r', encoding='utf-8')  #读取文本内容
engine.speak(f.read())  #输出到1.wav
f.close()  #关闭文件
stream.close()  #输出流关闭
Beispiel #28
0
class EditableText (NVDAObjects.behaviors.EditableText):
	"""
	Provides latex-access support, but makes sure this is only in edit controls.  The normal editableText.EditableText class is not used any more in this plugin because we need to take advantage of selection changes for the matrix processor.
	
	This NVDAObject overlay class is used when NVDA enters accessible Editable text, and provides the user with all the events, scripts and gestures needed to use this plugin.
	
	See the l{__gestures} dict for all the key bindings that this plugin uses.  Some may also be found in the l{GlobalPlugin} class, in the same dict.
	
	Any method beginning with event_* is an NVDA event which gets fired on other system events.
	
	Any method that begins with script_* will get executed when the required l{InputGesture} is pressed, E.G. if a key is pressed, button on the mouse is clicked, etc.
	"""

	processMaths = False
	latex_access = CreateObject ("latex_access")

	# For the matrix:
	matrix = None
	row = None
	column = None

	def _caretScriptPostMovedHelper(self, speakUnit, gesture, info = None):
		"""
This method ensures that LaTeX translation occurs when the system caret moves, and also makes sure that normal behaviour occurs when l{processMaths} is off.
		"""

		if isScriptWaiting ():
			return

		if not info:
			try:
				info = self.makeTextInfo (textInfos.POSITION_CARET)
			except:
				return
		review.handleCaretMove(info)
		if speakUnit == textInfos.UNIT_LINE and EditableText.processMaths and not willSayAllResume(gesture):
			spokenLine = GetLine ()
			brailledLine = GetLine ()
			if not spokenLine and not brailledLine:# Is it a blank line?
				spokenLine = _("blank")
				brailledLine = _("")
			else:
				spokenLine = EditableText.latex_access.speech (spokenLine)
				brailledLine = EditableText.latex_access.nemeth (brailledLine)
			speech.speakMessage (spokenLine)
			braille.handler.message (brailledLine)
		else:
			if speakUnit and not willSayAllResume(gesture):
				info.expand(speakUnit)
				speech.speakTextInfo(info, unit=speakUnit, reason=controlTypes.REASON_CARET)
		braille.handler.handleCaretMove(self)

	def script_reportCurrentLine (self, gesture):
		"""
		This script reports the line that the current navigator object is focused on, and speaks/brailles it appropriately depending on the state of l{processMaths}.  If pressed twice quickly, the current line is spelt out.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}.
		"""

		obj=api.getFocusObject()
		treeInterceptor=obj.treeInterceptor
		if hasattr(treeInterceptor,'TextInfo') and not treeInterceptor.passThrough:
			obj=treeInterceptor
		try:
			info=obj.makeTextInfo(textInfos.POSITION_CARET)
		except (NotImplementedError, RuntimeError):
			info=obj.makeTextInfo(textInfos.POSITION_FIRST)
		info.expand(textInfos.UNIT_LINE)
		if getLastScriptRepeatCount()==0:
			if EditableText.processMaths:
				spokenLine = GetLine ()
				brailledLine = GetLine ()
				if not spokenLine and not brailledLine:# Is it a blank line?
					spokenLine = _("blank")
					brailledLine = _("")
				else:
					spokenLine = EditableText.latex_access.speech (spokenLine)
					brailledLine = EditableText.latex_access.nemeth (brailledLine)
				speech.speakMessage (spokenLine)
				braille.handler.message (brailledLine)
			else:
				speech.speakTextInfo(info,unit=textInfos.UNIT_LINE,reason=controlTypes.REASON_CARET)
		else:
			speech.speakSpelling(info.text)
	script_reportCurrentLine.__doc__ = _("If latex-access translation is on, Translates the current line into nemeth braille and speech.  If translation is turned off, the current line is spoken as normal.  If this keystroke is pressed twice, the current line is spellt out.")

	def script_toggleDollars_nemeth (self, gesture):
		"""
		Toggles the state of whether dollar signs should be brailled in nemeth LaTeX translation.
		@param gesture: the gesture to be passed through to nvda (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		dollars = EditableText.latex_access.toggle_dollars_nemeth ()
		if dollars == True:
			ui.message (_("nemeth dollars off"))
		else:
			ui.message (_("nemeth dollars on"))
	script_toggleDollars_nemeth.__doc__ = _("Toggles the state of whether dollar signs should be brailled in nemeth LaTeX translation.")

	def script_toggleDollars_speech (self, gesture):
		"""
		Toggles the state of whether dollar signs should be spoken in speech for LaTeX translation.
		@param gesture: the gesture to be passed through to nvda (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		dollars = EditableText.latex_access.toggle_dollars_speech ()
		if dollars == True:
			ui.message (_("speech dollars off"))
		else:
			ui.message (_("speech dollars on"))
	script_toggleDollars_speech.__doc__ = _("Toggles the state of whether dollar signs should be spoken in speech for LaTeX translation.")

	def script_toggleMaths (self, Gesture):
		"""A script to toggle the latex-access translation on or off.
		@param gesture: the gesture to be past through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}.
		"""
		if EditableText.processMaths:# is translation on?
			EditableText.processMaths = False
			ui.message (_("Maths to be read as plain latex"))
		else:
			EditableText.processMaths = True# translation was off.
			ui.message (_("Maths to be processed to a more verbal form"))
	script_toggleMaths.__doc__ = _("Toggles the speaking of mathematical expressions as either straight latex or a more verbal rendering.")

	def script_inputMatrix (self, gesture):
		"""
		This script creates the matrix COM Object, and initialises a matrix based on the text that is currently selected.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		EditableText.matrix = CreateObject ("latex_access_matrix")
		EditableText.row = 1
		EditableText.column = 1
		EditableText.matrix.tex_init(getSelectedText ())
		# The msg variable is here to say how many rows and columns have been initialised.
		msg = "Initialised"
		msg = msg + str (EditableText.matrix.rows)
		msg = msg + " by "
		msg = msg + str(EditableText.matrix.columns)
		msg = msg + " matrix"
		ui.message (_(msg))
	script_inputMatrix.__doc__ = _ ("Initialises a matrix.  First highlight it and then run this script to have it as an object.")

	def script_matrixRight (self, gesture):
		"""
		Moves the matrix one cell to the right.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.column < EditableText.matrix.columns:
			EditableText.column = EditableText.column + 1
			ui.message (_(EditableText.matrix.get_cell(EditableText.row, EditableText.column)))
		else:
			ui.message (_("End of row"))
	script_matrixRight.__doc__ = _ ("moves the matrix cursor right and then speaks and brailles the cell.")

	def script_matrixLeft (self, gesture):
		"""
		Moves the matrix one cell to the left.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.column > 1:
			EditableText.column = EditableText.column - 1
			ui.message (_ (EditableText.matrix.get_cell (EditableText.row, EditableText.column)))
		else:
			ui.message (_ ("Start of row"))
	script_matrixLeft.__doc__ = _ ("Moves the matrix cursor to the left one cell, then speaks and brailles it")

	def script_matrixDown (self, gesture):
		"""
		Moves the matrix one cell down.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.row < EditableText.matrix.rows:
			EditableText.row = EditableText.row + 1
			ui.message (_ (EditableText.matrix.get_cell (EditableText.row, EditableText.column)))
		else:
			ui.message (_ ("End of column"))
	script_matrixDown.__doc__ = _ ("Moves the matrix cursor down one cell, then speaks and brailles it.")

	def script_matrixUp (self, gesture):
		"""
		Moves the matrix one cell up.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.row > 1:
			EditableText.row = EditableText.row - 1
			ui.message (_ (EditableText.matrix.get_cell (EditableText.row, EditableText.column)))
		else:
			ui.message (_ ("Start of column"))
	script_matrixUp.__doc__ = _ ("Moves the matrix down one cell and then speaks and brailles it.")

	# For the input gestures:
	__gestures = {
		"kb:control+M": "toggleMaths",
		"kb:NVDA+UpArrow": "reportCurrentLine",
		"kb:control+D": "toggleDollars_nemeth",
		"kb:control+shift+D": "toggleDollars_speech",
		"kb:control+shift+M":"inputMatrix",
		"kb:control+shift+L": "matrixRight",
		"kb:control+shift+J": "matrixLeft",
		"kb:control+shift+K": "matrixDown",
		"kb:control+shift+I": "matrixUp",
	}
Beispiel #29
0
def init(portName):
    # pickup global instances of port, ser and sapi variables
    global port, ser, sapivoice, sapistream, connected, directory

    _loadEyeShapes()
    _loadMotorDefs()

    silenceFile = os.path.join(directory, 'Silence1.wav')

    # get the sapi objects ready on Windows
    if platform.system() == "Windows":
        sapivoice = CreateObject("SAPI.SpVoice")
        sapistream = CreateObject("SAPI.SpFileStream")
        winsound.PlaySound(silenceFile, winsound.SND_FILENAME)

    # get the audio system warmed up on Mac
    if platform.system() == "Darwin":
        playsound(silenceFile)

    # get the audio system warmed up on linux
    if platform.system() == "Linux":
        os.system('aplay ' + silenceFile)

    # Search for the Picoh serial port
    ports = list(serial.tools.list_ports.comports())
    for p in ports:

        # If port has Picoh connected save the location
        if portName in p[1]:
            port = p[0]
            print("Picoh found on port:" + port)
            connected = True
        elif portName in p[0]:
            port = p[0]
            print("Picoh found on port:" + port)
            connected = True

    # If not found then try the first port
    if port == "":
        for p in ports:
            port = p[0]
            print("Picoh not found")
            connected = False
            break

    if port == "":
        print("Picoh port " + portName + " not found")
        return False

    # Open the serial port
    if connected:
        ser = serial.Serial(port, 19200)
        ser.timeout = None
        ser.write_timeout = None

    # Set read timeout and write timeouts to blocking

    # Make an initial call to Festival without playing the sound to check it's all okay
    text = "Hi"

    # Create a bash command with the desired text. The command writes two files, a .wav with the speech audio and a
    # .txt file containing the phonemes and the times.

    if synthesizer.lower() != "festival":
        _generateSpeechFile(text)
        

    _loadSpeechDatabase()

    return True
Beispiel #30
0
 def __init__(self, device_type='Camera'):
     self.c = CreateObject("ASCOM.Utilities.Chooser")
     self.c.DeviceType = device_type