Example #1
0
    def __init__(self, SimulationSettings, Logger):
        self.Logger = Logger
        self.Network_Modifications = []
        self.__SimulationOptions = SimulationSettings
        self.__dssInstance = dss
        Logger.Log(1, 'Compiling: ' + SimulationSettings['DSS File'])
        self.__dssInstance.Basic.ClearAll()
        self.__dssInstance.utils.run_command('Log=NO')
        run_command('Clear')
        print('creating PyDSS')
        hasComplied = run_command('compile ' + SimulationSettings['DSS File'])
        print(hasComplied)
        if 'Not Found' in hasComplied:
            Logger.Log(3, 'OpenDSS file not found.')
            self.hasComplied = False
            return
        else:
            self.hasComplied = True
            Logger.Log(1, 'Project compilation successful.')

        self.__dssCircuit = dss.Circuit
        self.__dssElement = dss.Element
        self.__dssBus = dss.Bus
        self.__dssClass = dss.ActiveClass
        self.__dssCommand = run_command
        self.__dssSolution = dss.Solution

        run_command('Solve')
        self.createGraph()

        self.dssSolver = SolveMode.GetSolver(self.__SimulationOptions,
                                             self.__dssInstance, Logger)
        Logger.Log(1, 'pyDSS instance created successfully.')
        return
Example #2
0
    def _CompileModel(self):
        self._dssInstance.Basic.ClearAll()
        self._dssInstance.utils.run_command('Log=NO')
        run_command('Clear')
        self._Logger.info('Loading OpenDSS model')
        reply = ""
        try:
            orig_dir = os.getcwd()
            reply = run_command('compile ' + str(self._dssPath['dssFilePath']))
        finally:
            os.chdir(orig_dir)

        self._Logger.info('OpenDSS:  ' + reply)
        if reply != "":
            raise OpenDssModelError(f"Error compiling OpenDSS model: {reply}")
Example #3
0
    def __init__(self, settings: SimulationSettingsModel):
        self._dssInstance = dss
        self._TempResultList = []
        self._dssBuses = {}
        self._dssObjects = {}
        self._dssObjectsByClass = {}
        self._DelFlag = 0
        self._pyPlotObjects = {}
        self.BokehSessionID = None
        self._settings = settings
        self._convergenceErrors = 0
        self._convergenceErrorsOpenDSS = 0
        self._maxConvergenceErrorCount = None
        self._maxConvergenceError = 0.0
        self._controller_iteration_counts = {}
        self._simulation_range = SimulationFilteredTimeRange.from_settings(
            settings)

        root_path = settings.project.project_path
        active_project_path = root_path / settings.project.active_project
        import_path = active_project_path / 'Scenarios'
        active_scenario_path = import_path / settings.project.active_scenario
        self._ActiveProject = settings.project.active_project

        self._dssPath = {
            'root':
            root_path,
            'Import':
            import_path,
            'pyPlots':
            active_scenario_path / 'pyPlotList',
            'ExportLists':
            active_scenario_path / 'ExportLists',
            'pyControllers':
            active_scenario_path / 'pyControllerList',
            'Export':
            active_project_path / 'Exports',
            'Log':
            active_project_path / 'Logs',
            'dssFiles':
            active_project_path / 'DSSfiles',
            'dssFilePath':
            active_project_path / 'DSSfiles' / settings.project.dss_file,
        }

        if settings.project.dss_file_absolute_path:
            self._dssPath['dssFilePath'] = Path(settings.project.dss_file)

        if not self._dssPath['dssFilePath'].exists():
            raise InvalidConfiguration(
                f"DSS file {self._dssPath['dssFilePath']} does not exist")

        LoggerTag = pyLogger.getLoggerTag(settings)
        self._Logger = logging.getLogger(__name__)
        self._reportsLogger = pyLogger.getReportLogger(LoggerTag,
                                                       self._dssPath["Log"],
                                                       settings.logging)
        self._Logger.info('An instance of OpenDSS version ' +
                          self._dssInstance.__version__ + ' has been created.')

        for key, path in self._dssPath.items():
            if path.name == "pyControllerList" and not path.exists():
                # This will happen if a zipped project with no controllers is unzipped and then run.
                path.mkdir()
            else:
                assert path.exists(), '{} path: {} does not exist!'.format(
                    key, path)

        self._CompileModel()

        #run_command('Set DefaultBaseFrequency={}'.format(settings.frequency.fundamental_frequency))
        self._Logger.info('OpenDSS fundamental frequency set to :  ' +
                          str(settings.frequency.fundamental_frequency) +
                          ' Hz')

        #run_command('Set %SeriesRL={}'.format(settings.frequency.percentage_load_in_series))
        if settings.frequency.neglect_shunt_admittance:
            run_command('Set NeglectLoadY=Yes')

        active_scenario = self._GetActiveScenario()
        if active_scenario.snapshot_time_point_selection_config.mode != SnapshotTimePointSelectionMode.NONE:
            self._SetSnapshotTimePoint(active_scenario)

        self._dssCircuit = self._dssInstance.Circuit
        self._dssElement = self._dssInstance.Element
        self._dssBus = self._dssInstance.Bus
        self._dssClass = self._dssInstance.ActiveClass
        self._dssCommand = run_command
        self._dssSolution = self._dssInstance.Solution
        self._dssSolver = SolveMode.GetSolver(settings=settings,
                                              dssInstance=self._dssInstance)
        self._Modifier = Modifier(self._dssInstance, run_command, settings)
        self._dssBuses = self.CreateBusObjects()
        self._dssObjects, self._dssObjectsByClass = self.CreateDssObjects(
            self._dssBuses)
        self._dssSolver.reSolve()

        if settings.profiles.use_profile_manager:
            #TODO: disable internal profiles
            self._Logger.info(
                'Disabling internal yearly and duty-cycle profiles.')
            for m in ["Loads", "PVSystem", "Generator", "Storage"]:
                run_command(f'BatchEdit {m}..* yearly=NONE duty=None')
            profileSettings = self._settings.profiles.settings
            profileSettings["objects"] = self._dssObjects
            self.profileStore = ProfileInterface.Create(
                self._dssInstance, self._dssSolver, self._settings,
                self._Logger, **profileSettings)

        self.ResultContainer = ResultData(settings, self._dssPath,
                                          self._dssObjects,
                                          self._dssObjectsByClass,
                                          self._dssBuses, self._dssSolver,
                                          self._dssCommand, self._dssInstance)

        if settings.project.use_controller_registry:
            ControllerList = read_controller_settings_from_registry(
                self._dssPath['pyControllers'])
        else:
            pyCtrlReader = pcr(self._dssPath['pyControllers'])
            ControllerList = pyCtrlReader.pyControllers

        if ControllerList is not None:
            self._CreateControllers(ControllerList)

        if settings.plots.create_dynamic_plots:
            pyPlotReader = ppr(self._dssPath['pyPlots'])
            PlotList = pyPlotReader.pyPlots
            self._CreatePlots(PlotList)
            for Plot in self._pyPlotObjects:
                self.BokehSessionID = self._pyPlotObjects[Plot].GetSessionID()
                if settings.plots.open_plots_in_browser:
                    self._pyPlotObjects[Plot].session.show()
                break
        self._increment_flag = True
        if settings.helics.co_simulation_mode:
            self._HI = HI.helics_interface(self._dssSolver, self._dssObjects,
                                           self._dssObjectsByClass, settings,
                                           self._dssPath)
        self._Logger.info("Simulation initialization complete")
        return
Example #4
0
    def __init__(self, params):
        self._TempResultList = []
        self._dssInstance = dss
        self._dssBuses = {}
        self._dssObjects = {}
        self._dssObjectsByClass = {}
        self._DelFlag = 0
        self._pyPlotObjects = {}
        self.BokehSessionID = None
        self._Options = params

        rootPath = params['Project']['Project Path']
        self._ActiveProject = params['Project']['Active Project']
        importPath = os.path.join(rootPath,
                                  params['Project']['Active Project'],
                                  'Scenarios')

        self._dssPath = {
            'root':
            rootPath,
            'Import':
            importPath,
            'pyPlots':
            os.path.join(importPath, params['Project']['Active Scenario'],
                         'pyPlotList'),
            'ExportLists':
            os.path.join(importPath, params['Project']['Active Scenario'],
                         'ExportLists'),
            'pyControllers':
            os.path.join(importPath, params['Project']['Active Scenario'],
                         'pyControllerList'),
            'Export':
            os.path.join(rootPath, params['Project']['Active Project'],
                         'Exports'),
            'Log':
            os.path.join(rootPath, params['Project']['Active Project'],
                         'Logs'),
            'dssFiles':
            os.path.join(rootPath, params['Project']['Active Project'],
                         'DSSfiles'),
            'dssFilePath':
            os.path.join(rootPath, params['Project']['Active Project'],
                         'DSSfiles', params['Project']['DSS File']),
        }

        if params['Project']['DSS File Absolute Path']:
            self._dssPath['dssFilePath'] = params['Project']['DSS File']
        else:
            self._dssPath['dssFilePath'] = os.path.join(
                rootPath, params['Project']['Active Project'], 'DSSfiles',
                params['Project']['DSS File'])

        if params["Logging"]["Pre-configured logging"]:
            self._Logger = logging.getLogger(__name__)
        else:
            LoggerTag = pyLogger.getLoggerTag(params)
            self._Logger = pyLogger.getLogger(LoggerTag,
                                              self._dssPath['Log'],
                                              LoggerOptions=params["Logging"])
        self._Logger.info('An instance of OpenDSS version ' + dss.__version__ +
                          ' has been created.')

        for key, path in self._dssPath.items():
            assert (
                os.path.exists(path)), '{} path: {} does not exist!'.format(
                    key, path)

        self._dssInstance.Basic.ClearAll()
        self._dssInstance.utils.run_command('Log=NO')
        run_command('Clear')
        self._Logger.info('Loading OpenDSS model')
        try:
            orig_dir = os.getcwd()
            reply = run_command('compile ' + self._dssPath['dssFilePath'])
        finally:
            os.chdir(orig_dir)
        self._Logger.info('OpenDSS:  ' + reply)

        assert ('error ' not in reply.lower()
                ), 'Error compiling OpenDSS model.\n{}'.format(reply)
        run_command('Set DefaultBaseFrequency={}'.format(
            params['Frequency']['Fundamental frequency']))
        self._Logger.info('OpenDSS fundamental frequency set to :  ' +
                          str(params['Frequency']['Fundamental frequency']) +
                          ' Hz')

        run_command('Set %SeriesRL={}'.format(
            params['Frequency']['Percentage load in series']))
        if params['Frequency']['Neglect shunt admittance']:
            run_command('Set NeglectLoadY=Yes')

        self._dssCircuit = dss.Circuit
        self._dssElement = dss.Element
        self._dssBus = dss.Bus
        self._dssClass = dss.ActiveClass
        self._dssCommand = run_command
        self._dssSolution = dss.Solution
        self._dssSolver = SolveMode.GetSolver(SimulationSettings=params,
                                              dssInstance=self._dssInstance)

        self._Modifier = Modifier(dss, run_command, params)
        self._UpdateDictionary()
        self._CreateBusObjects()
        self._dssSolver.reSolve()

        if params and params['Exports']['Log Results']:
            if params['Exports']['Result Container'] == 'ResultContainer':
                self.ResultContainer = RC(params, self._dssPath,
                                          self._dssObjects,
                                          self._dssObjectsByClass,
                                          self._dssBuses, self._dssSolver,
                                          self._dssCommand)
            else:
                self.ResultContainer = ResultData(
                    params, self._dssPath, self._dssObjects,
                    self._dssObjectsByClass, self._dssBuses, self._dssSolver,
                    self._dssCommand, self._dssInstance)
        else:
            self.ResultContainer = None

        if params['Project']['Use Controller Registry']:
            ControllerList = read_controller_settings_from_registry(
                self._dssPath['pyControllers'])
        else:
            pyCtrlReader = pcr(self._dssPath['pyControllers'])
            ControllerList = pyCtrlReader.pyControllers

        if ControllerList is not None:
            self._CreateControllers(ControllerList)

        if params['Plots']['Create dynamic plots']:
            pyPlotReader = ppr(self._dssPath['pyPlots'])
            PlotList = pyPlotReader.pyPlots
            self._CreatePlots(PlotList)
            for Plot in self._pyPlotObjects:
                self.BokehSessionID = self._pyPlotObjects[Plot].GetSessionID()
                if params['Plots']['Open plots in browser']:
                    self._pyPlotObjects[Plot].session.show()
                break
        self._increment_flag = True
        if params['Helics']["Co-simulation Mode"]:
            self._HI = HI.helics_interface(self._dssSolver, self._dssObjects,
                                           self._dssObjectsByClass, params,
                                           self._dssPath)
        return