def __init__(self, circuit, capacitorOptions="defaultCap.csv"): self.circuit = circuit self.capacitorOptions = pd.read_csv(capacitorOptions) self.path = os.path.join("\\", *circuit.split("\\")[1:-1]) try: sys.argv = ["makepy", "OpenDSSEngine.DSS"] makepy.main() self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") self.dssObj.Start("0") self.dssText = self.dssObj.Text print "OpenDSS foi iniciado com sucesso!" except: print "Erro ao iniciar OpenDSS!" try: self.dssText.Command = "compile '" + circuit + "'" except: print "Erro ao abrir " + circuit self.startCapacitors()
def __init__(self) -> None: self._config = Configuration() sys.argv = ['makepy', 'OpenDSSEngine.dss'] makepy.main() self._engine = win32com.client.Dispatch('OpenDSSEngine.dss') self._engine = win32com.client.gencache.EnsureDispatch( "OpenDSSEngine.dss") self._engine.Start(0) self._file = '' self._ckt = None self._load_profile = None self._weekday = None self._capacitors = None self._switches = None self._lines = None self._transformers = None self._regulator_controls = None self._loads = None self._generators = None self._vsources = None self._isources = None self._buses = None
def __init__(self, dssFileName, row): """ Compile OpenDSS model and initialize variables.""" # These variables provide direct interface into OpenDSS sys.argv = ["makepy", r"OpenDSSEngine.DSS"] makepy.main() # ensures early binding and improves speed # Create a new instance of the DSS self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") # Start the DSS if self.dssObj.Start(0) == False: print "DSS Failed to Start" else: #Assign a variable to each of the interfaces for easier access self.dssText = self.dssObj.Text self.dssCircuit = self.dssObj.ActiveCircuit # Maybe this one can help self.dssSolution = self.dssCircuit.Solution self.dssCktElement = self.dssCircuit.ActiveCktElement self.dssBus = self.dssCircuit.ActiveBus self.dssMeters = self.dssCircuit.Meters self.dssPDElement = self.dssCircuit.PDElements # Always a good idea to clear the DSS when loading a new circuit self.dssObj.ClearAll() # Load the given circuit master file into OpenDSS self.dssText.Command = "compile [" + dssFileName + "]" self.row = row
def __init__(self, dssFileName: str): """ :param dssFileName: Caminho completo do arquivo .dss """ self.dssFileName = dssFileName.replace('"', '') sys.argv = ["makepy", "OpenDSSEngine.DSS"] makepy.main() # Criar a conexão entre Python e OpenDSS self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") # Iniciar o Objeto DSS if not self.dssObj.Start(0): print("Problemas em iniciar o OpenDSS") else: # Criar variáveis para as principais interfaces self.dssText = Text(self.dssObj.Text) self.dssCircuit = Circuit(self.dssObj.ActiveCircuit) self.dssCktElement = CktElements(self.dssCircuit.ActiveCktElement(), self.dssObj.ActiveCircuit) self.dssBus = Bus(self.dssObj.ActiveCircuit, self.dssCircuit.ActiveBus()) self.dssLines = Lines(self.dssCircuit.Lines()) self.dssLoads = Loads(self.dssCircuit.Loads()) self.dssTransformers = Transformers(self.dssCircuit.Transformers()) self.dssMonitors = Monitors(self.dssCircuit.Monitors()) self.dssSolution = Solution(self.dssCircuit.Solution(), self.dssText) self.dssLinesCodes = LineCodes(self.dssCircuit.LineCodes()) self.dssLoadShapes = LoadShapes(self.dssCircuit.LoadShapes()) self.dir_principal = self.DataPath(self.dssFileName.rstrip(self.dssFileName.split('/')[len(self.dssFileName.split('/'))-1])) self.dir_resultados = self.dir_principal + "Resultados" self.dir_plots = self.dir_principal + "Plots"
def _proxy(self, name=''): """Ensure generation of named static COM proxy upon dispatch.""" f = io.StringIO() with contextlib.redirect_stdout(f): sys.argv = ['', '-i', name] makepy.main() exec('\n'.join( line.replace(' >>> ', '') for line in f.getvalue().splitlines() if line.startswith(' >>> ')))
def run(): CYBOS_PLUS_DIR = r"c:\daishin\CYBOSPLUS" DLL_FILES = [ 'cpdib.dll', 'CpForeDib.dll', 'CpForeTrade.dll', 'CpForeUtil.dll', 'CpGmaxDib.dll', 'CpIndexes.dll', 'CpintTrade.dll', 'CpNanoSysDib.dll', 'CpPrivDib.dll', 'CpSysDib.dll', 'cptrade.dll', 'cputil.dll' ] for i, f in enumerate(DLL_FILES): DLL_FILES[i] = os.path.join(CYBOS_PLUS_DIR, f) sys.argv = ['makepy'] sys.argv.extend(DLL_FILES) makepy.main()
def __init__(self, dssFileName): """ Compile OpenDSS model and initialize variables.""" self.dssFileName = dssFileName if self.dssFileName == "": print("Need to add the file path of the run file") # These variables provide direct interface into OpenDSS sys.argv = ["makepy", r"OpenDSSEngine.DSS"] makepy.main() # ensures early binding and improves speed # Create a new instance of the DSS self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") # Start the DSS if self.dssObj.Start(0) == False: print("DSS Failed to Start") else: #Assign a variable to each of the interfaces for easier access self.dssText = self.dssObj.Text self.dssCircuit = self.dssObj.ActiveCircuit self.dssSolution = self.dssCircuit.Solution self.dssCktElement = self.dssCircuit.ActiveCktElement self.dssBus = self.dssCircuit.ActiveBus self.dssMeters = self.dssCircuit.Meters self.dssPDElement = self.dssCircuit.PDElements self.dssLoads = self.dssCircuit.Loads self.dssLines = self.dssCircuit.Lines self.dssTransformers = self.dssCircuit.Transformers # Always a good idea to clear the DSS when loading a new circuit self.dssObj.ClearAll() # Loads the given circuit master file into OpenDSS self.dssText.Command = "compile " + dssFileName # Lists self.transformersNames = [] self.busesNames = [] self.consumersNames = [] self.transformersNames_ltc = [] self.busesNames_ltc = [] self.consumersNames_ltc = []
def __init__(self, dssFileName): # Create a new instance of the DSS sys.argv = ["makepy", "OpenDSSEngine.DSS"] makepy.main() self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") # Start the DSS if self.dssObj.Start(0) == False: print("DSS Failed to Start") else: self.dssFileName = dssFileName # Assign a variable to each of the interfaces for easier access self.dssText = self.dssObj.Text self.dssCircuit = self.dssObj.ActiveCircuit self.dssSolution = self.dssCircuit.Solution self.dssCktElement = self.dssCircuit.ActiveCktElement self.dssBus = self.dssCircuit.ActiveBus self.dssTransformer = self.dssCircuit.Transformers
def FinalTests(self): """Ensure a static proxy exists""" try: c.xlDown except: from win32com.client import makepy sys.argv = ["makepy", r"C:\Program Files (x86)\Microsoft Office\Office14\Excel.exe"] with Capturing() as printoutput: makepy.main() if len(printoutput): if printoutput[0].startswith("Could not locate a type library matching"): sys.argv = ["makepy", r"C:\Program Files (x86)\Microsoft Office\Office16\Excel.exe"] with Capturing() as printoutput: makepy.main() if len(printoutput): if printoutput[0].startswith("Could not locate a type library matching"): sys.argv= [""] print "Choose: Microsoft Excel 14.0 Object Library (1.7), or Excel 16.0 Object Library (1.9)" with Capturing() as printoutput: makepy.main() if len(printoutput): if printoutput[0].startswith("Could not locate a type library matching"): print "Could not create a win32 proxy for Excel. Stopping now." time.sleep(5) sys.exit()
def DSSStartup(): # Function for starting up the DSS # In Python we need to import all the libraries besides the standard library before we use their functions. # "win32com" is one possible library to use a COM object from Python import win32com.client #from comtypes import client as cc # Early binding import sys from win32com.client import makepy sys.argv = ["makepy", "OpenDSSEngine.DSS"] makepy.main() # instantiate the DSS Object Obj = win32com.client.Dispatch('OpenDSSEngine.DSS') #Obj = cc.CreateObject('OpenDSSEngine.DSS') # Start the DSS. Only needs to be executed the first time within a Python session Start = Obj.Start(0) # Define the text interface Text = Obj.Text # In Python the output(s) of the functions need to be explicitely returned when the function finishes return Start, Obj, Text
''' Created on May 26, 2020 @author: spate181 ''' import sys import win32com.client #pywin32 from win32com.client import makepy sys.argv = ["makepy", r"OpenDSSEngine.DSS"] makepy.main() # ensures early binding and improves speed # Create a new instance of the DSS print("Initiating opendss engine") dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") if dssObj.Start(0) == False: print("DSS Failed to Start") else: print("Python-dss interface successful")
"""################ SCRIPT ##################""" # Create time set Time_sim = np.array(range1(Time_start, Time_end, Time_sim_interval)) # Time set for simulations """ CREATE THE OpenDSS CIRCUIT This will be handy for getting some extra network data Applicaitons: Using OPF as benchmark for a ANM solution implemented in OpenDSS """ # Create OpenDSS object # The COM module has a variety of interfaces, and creating variables to access them directly is handy. sys.argv = ["makepy", "OpenDSSEngine.DSS"] makepy.main() dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") dssText = dssObj.Text # to excecute OpenDSS text commands dssCircuit = dssObj.ActiveCircuit # Use it to access the elements in the circuit (e.g., capacitors, buses, etc.) dssSolution = dssCircuit.Solution dssElem = dssCircuit.ActiveCktElement dssBus = dssCircuit.ActiveBus # This is the datapath were the dss file is. Results will also be saved here. dssText.Command = 'set datapath=' + Main_path dssText.Command = 'Clear' # clear any existing circuit in the engine dssText.Command = 'Set DefaultBaseFrequency=50' # Vsource dssText.Command = 'Redirect ' + Main_path + '/Network_data/Network_model/OpenDSS_NewCircuit.txt' # Transformer
def generate(): sys.argv = ['', '-o', mseLib[0], mseLib[1]] makepy.main() sys.argv = ['', '-o', msoLib[0], msoLib[1]] makepy.main()
if __name__ == "__main__": setup(name='MS Office pyCOM', version='0.1', description='A python wrapper for MS Excel VBA WinCOM32 API', long_description=readme(), url='https://github.com/Top-Dog/MS-COM', author="Sean D. O'Connor", author_email='*****@*****.**', license='MIT', packages=['MSOffice', 'MSOffice.Excel', 'MSOffice.Excel.Charts', 'MSOffice.Excel.Worksheets', 'MSOffice.Excel.PivotTables'], install_requires=['six', 'wheel', 'virtualenv', 'numpy', 'pypiwin32', 'pyodbc'], # Try 'pywin32' if pypiwin32 fails dependency_links=[], zip_safe=False, #packages=find_packages() ) from win32com.client import makepy # For Excel (fill the cache so we can use constatns with late binding) sys.argv = ["makepy", r"C:\Program Files (x86)\Microsoft Office\Office14\Excel.exe"] with Capturing() as printoutput: makepy.main() if len(printoutput): if printoutput[0].startswith("Could not locate a type library matching"): sys.argv = ["makepy", r"C:\Program Files (x86)\Microsoft Office\Office16\Excel.exe"] with Capturing() as printoutput: makepy.main() if len(printoutput): if printoutput[0].startswith("Could not locate a type library matching"): sys.argv= [""] print "Choose: Microsoft Excel 14.0 Object Library (1.7), or Excel 16.0 Object Library (1.9)" makepy.main()
def __init__(self, dssFileName): # Create a new instance of the DSS sys.argv = ["makepy", "OpenDSSEngine.DSS"] makepy.main() self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") # Start the DSS if self.dssObj.Start(0) == False: print "DSS Failed to Start" else: #Assign a variable to each of the interfaces for easier access self.dssText = self.dssObj.Text self.dssCircuit = self.dssObj.ActiveCircuit self.dssSolution = self.dssCircuit.Solution self.dssCktElement = self.dssCircuit.ActiveCktElement self.dssBus = self.dssCircuit.ActiveBus self.dssTransformer = self.dssCircuit.Transformers # Always a good idea to clear the DSS when loading a new circuit self.dssObj.ClearAll() # Load the given circuit master file into OpenDSS self.dssText.Command = "compile " + dssFileName #OpenDSS folder self.OpenDSS_folder_path = os.path.dirname(dssFileName) self.results_path = self.OpenDSS_folder_path + "/CorrectedLoadShape/results" self.dssText.Command = "set DataPath=" + self.results_path loadmult = [1, 1.15, 1.3] pv_penetracao = [0, 0.1, 0.2, 0.3] for i in range(len(loadmult)): for j in range(len(pv_penetracao)): self.dssText.Command = "set case=" + "LM_" + str( loadmult[i]) + "_PEN_" + str(pv_penetracao[j]) self.ajuste_param(loadmult[i], pv_penetracao[j]) self.dssText.Command = "get loadmult" print self.dssText.Result self.dssText.Command = "? PVSystem.PV_1.Pmpp" print self.dssText.Result # Solve settings self.solve_settings() # self.dssSolution.Number = 2 * self.dssSolution.Number #Resolve dois dias (esperar controles entrarem em regime) self.dssSolution.Solve() #Solve two days self.dssText.Command = "export monitors Substationtap" self.dssText.Command = "export monitors Reg2a" self.dssText.Command = "export monitors Reg3a" self.dssText.Command = "export monitors Reg4a" self.dssText.Command = "export monitors Reg4b" self.dssText.Command = "export monitors Reg3c" self.dssText.Command = "export monitors Reg4c" self.dssText.Command = "export monitors medidor_trafo_conexao_tensao" self.dssText.Command = "export monitors medidor_trafo_conexao_potencia" self.dssText.Command = "export monitors medidor_PV1" self.dssText.Command = "export monitors SubstationtapV" self.dssText.Command = "export monitors Reg2aV" self.dssText.Command = "export monitors Reg3aV" self.dssText.Command = "export monitors Reg4aV" self.dssText.Command = "export monitors Reg4bV" self.dssText.Command = "export monitors Reg3cV" self.dssText.Command = "export monitors Reg4cV"
def __init__(self, dssFileName): # Cria uma nova instância do OpenDSS utilizando Ligações Prematuras (Early Bindings) sys.argv = ["makepy", "OpenDSSEngine.DSS"] makepy.main() self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") # Inicializa o OpenDSS if self.dssObj.Start(0) == False: print "DSS Failed to Start" else: #Atribui uma variável às interfaces comumentes utilizadas para fácil acesso self.dssText = self.dssObj.Text self.dssCircuit = self.dssObj.ActiveCircuit self.dssSolution = self.dssCircuit.Solution self.dssCktElement = self.dssCircuit.ActiveCktElement self.dssBus = self.dssCircuit.ActiveBus self.dssTransformer = self.dssCircuit.Transformers self.dssPV = self.dssCircuit.PVSystems #Parâmetros Fixos loadmult = 1.3 pv_penetracao = 0.3 minutos = [2, 4, 10] for i in range(len(minutos)): if i == 0: self.min = 2 # duração da janela da média móvel elif i == 1: self.min = 4 elif i == 2: self.min = 10 # Limpa a memória do OpenDSS self.dssObj.ClearAll() # Carrega o circuito Master self.dssText.Command = "compile " + dssFileName # Salva o diretório atual e acrecenta uma pasta para resultados self.OpenDSS_folder_path = os.path.dirname(dssFileName) self.results_path = self.OpenDSS_folder_path + "/resultados_teste_perdas_somente_eff/resultsStorage_" + str( self.min) + "_min" # Seta um novo caso para fácil identificação de resultados self.dssText.Command = "set case=" + "LM_" + str( loadmult) + "_PEN_" + str(pv_penetracao) self.ajuste_param(loadmult, pv_penetracao) # Resolver o resto passo a passo # Primeiramente, adicionar os dados da bateria self.dssText.Command = "Redirect Storage.DSS" self.dssText.Command = "set DataPath=" + self.results_path # Ajusta as configurações da solução self.solve_settings() OriginalSteps = self.dssSolution.Number self.dssSolution.Number = 1 for stepNumber in range(OriginalSteps): control_iter = 1 self.dssSolution.InitSnap() # Inicializa Contadores while not self.dssSolution.ControlActionsDone: self.dssSolution.SolveNoControl( ) # Resolve o fluxo de potência sem controles. # Nesse instante, já tenho acesso à nova potência injetada pelo PV. Portanto, posso atualizar a potência injetada pelas baterias. if control_iter == 1 and self.dssSolution.Hour >= 29 and self.dssSolution.Hour <= 43: #Considerar os PVs só no segundo dia. Menor tempo de simulação self.atualiza_Pbaterias() self.dssSolution.SolveNoControl() self.dssSolution.SampleControlDevices( ) # Amostra os controles e popula a Control Queue com ações dos controladores do OpenDSS if self.dssCircuit.CtrlQueue == 0: break #Sai do While se não há mais ações de controle para realizar self.dssSolution.DoControlActions( ) # Empurra pra fora da Control Queue a primeira ação da lista de controle.. quem decide # se a ação é realizada ou não é o elemento de controle quem decide control_iter += 1 if control_iter >= self.dssSolution.MaxControlIterations: print "Numero maximo de iteracoes de controle excedido" iteracao = "Maximo excedido" break self.dssSolution.FinishTimeStep( ) #atualiza monitores, elementos que integram e incrementa o passo de tempo self.rastreia_solucao( ) #só para ter uma ideia de quanto tempo vai demorar self.dssText.Command = "export monitors Substationtap" self.dssText.Command = "export monitors Reg2a" self.dssText.Command = "export monitors Reg3a" self.dssText.Command = "export monitors Reg4a" self.dssText.Command = "export monitors Reg4b" self.dssText.Command = "export monitors Reg3c" self.dssText.Command = "export monitors Reg4c" self.dssText.Command = "export monitors medidor_trafo_conexao_tensao" self.dssText.Command = "export monitors medidor_trafo_conexao_potencia" self.dssText.Command = "export monitors Monitor_Baterias_states" self.dssText.Command = "export monitors Monitor_Baterias_P" self.dssText.Command = "export monitors medidor_PV1" self.dssText.Command = "export monitors SubstationtapV" self.dssText.Command = "export monitors Reg2aV" self.dssText.Command = "export monitors Reg3aV" self.dssText.Command = "export monitors Reg4aV" self.dssText.Command = "export monitors Reg4bV" self.dssText.Command = "export monitors Reg3cV" self.dssText.Command = "export monitors Reg4cV"
def __init__(self, dssFileName): sys.argv = ["makepy", r"OpenDSSEngine.DSS"] makepy.main() # ensures early binding and improves speed # Create a new instance of the DSS print("Initiating opendss engine") self.dssObj = win32com.client.Dispatch("OpenDSSEngine.DSS") if self.dssObj.Start(0) == False: print("DSS Failed to Start") else: #Assign a variable to each of the interfaces for easier access self.dssText = self.dssObj.Text self.dssCircuit = self.dssObj.ActiveCircuit self.dssSolution = self.dssCircuit.Solution self.dssCktElement = self.dssCircuit.ActiveCktElement self.dssBus = self.dssCircuit.ActiveBus self.dssMeters = self.dssCircuit.Meters self.dssPDElement = self.dssCircuit.PDElements self.dssLoads = self.dssCircuit.Loads self.dssLines = self.dssCircuit.Lines self.dssTransformers = self.dssCircuit.Transformers self.dssFileName = dssFileName self.dssPVs = self.dssCircuit.PVSystems self.loadnodes = [] self.l53flow = [] # Always a good idea to clear the DSS when loading a new circuit self.dssObj.ClearAll() # Loads the given circuit master file into OpenDSS self.dssText.Command = "compile " + dssFileName # Lists self.busesNames = self.dssCircuit.AllBusNames self.consumersNames = self.dssLoads.AllNames self.transformersNames = self.dssTransformers.AllNames self.busesNames_ltc = [] self.consumersNames_ltc = [] self.PVlines = [] self.lines = self.dssLines.AllNames self.capacitors = self.dssCircuit.Capacitors.AllNames self.capcontrols = self.dssCircuit.CapControls.AllNames self.regcontrols = self.dssCircuit.RegControls.AllNames self.loadoff = [] self.pvs = self.dssPVs.AllNames self.loads = self.dssLoads.AllNames self.bess_soc = {} self.tieline = {} self.tap_position = {} self.der_output = {} self.derIDs = {} self.vsource = [] self.simulinkresults = {} self.events = [{ "ID": 0, "Type": "Set Fault", "StartTime": 1.1, "Bus": "650" }, { "ID": 1, "Type": "Remove Fault", "StartTime": 1.15, "Bus": "650" }] #self.events=[{"ID":0, "Type":"None", "StartTime":1.1, "Bus":"650"},{"ID":1, "Type":"None", "StartTime":1.15, "Bus":"650"}] #self.events=[] self.derIDs = [ "DER1", "DER2", "DER3", "DER4", "DER5", "DER6", "DER7", "DER8", "DER9", "DER10", "DER11", "DER12", "DER13", "DER14", "DER15", "DER16", "DER17", "DER18", "DER19", "DER20", "DER21", "DER22", "DER23", "DER24", "DER25" ] self.der_parameterlist = [ "Time", "Vfeederhead", "Pfeederhead", "Qfeederhead", "P2grid", "Vpcc_a_dss", "Vpcc_b_dss", "Vpcc_c_dss", "angle_a_dss", "angle_b_dss", "angle_c_dss", "pflow_dss", "qflow_dss" ] self.pvlines = [ "line1", "line2", "line3", "line4", "line5", "line6", "line7", "line8", "line9", "line10", "line11", "line12", "line13", "line14", "line15", "line16", "line17", "line18", "lin19", "line20", "line21", "line22", "line23", "line24", "line25" ] self.pvpcc = [ "650", "651", "652", "653", "654", "655", "656", "657", "658", "659", "660", "661", "662", "663", "664", "665", "666", "667", "668", "669", "670", "671", "672", "673", "674" ] self.dynamics_mode = "Balanced"