Exemple #1
0
    def setup_simulation(self, scenario='default'):
        """Setup a simulation."""

        self.events_list = []
        self.grid_list = []
        self.DER_model_list = []
        self.sim_list = []
        self.results_list = []

        self.n_instances = self.return_settings(scenario=scenario,
                                                parameter='n_DER',
                                                settings_type='setup')

        power_rating = self.return_settings(scenario=scenario,
                                            parameter='power_rating',
                                            settings_type='setup')
        SinglePhase = self.return_settings(scenario=scenario,
                                           parameter='SinglePhase',
                                           settings_type='setup')
        SteadyState = self.return_settings(scenario=scenario,
                                           parameter='SteadyState',
                                           settings_type='setup')

        for i in range(self.n_instances):

            self.events_list.append(SimulationEvents())
            self.grid_list.append(Grid(events=self.events_list[-1]))

            if SinglePhase:
                self.DER_model_list.append(
                    SolarPV_DER_SinglePhase(
                        grid_model=self.grid_list[-1],
                        events=self.events_list[-1],
                        standAlone=True,
                        Sinverter_rated=power_rating,
                        STEADY_STATE_INITIALIZATION=SteadyState))
            else:
                self.DER_model_list.append(
                    SolarPV_DER_ThreePhase(
                        grid_model=self.grid_list[-1],
                        events=self.events_list[-1],
                        standAlone=True,
                        Sinverter_rated=power_rating,
                        STEADY_STATE_INITIALIZATION=SteadyState))

            self.sim_list.append(
                DynamicSimulation(grid_model=self.grid_list[-1],
                                  PV_model=self.DER_model_list[-1],
                                  events=self.events_list[-1],
                                  LOOP_MODE=False,
                                  COLLECT_SOLUTION=True))
            self.sim_list[
                -1].jacFlag = False  #Provide analytical Jacobian to ODE solver
            self.sim_list[
                -1].DEBUG_SOLVER = False  #Check whether solver is failing to converge at any step

            self.results_list.append(
                SimulationResults(simulation=self.sim_list[-1], PER_UNIT=True))
Exemple #2
0
    def test_run_simulation(self):
        """Test run simulation method."""

        events = SimulationEvents()

        PVDER = SolarPVDERThreePhase(events=events,
                                     configFile=config_file,
                                     **{
                                         **self.flag_arguments,
                                         **self.ratings_arguments,
                                         **self.voltage_arguments
                                     })

        sim = DynamicSimulation(PV_model=PVDER,
                                events=events,
                                jacFlag=True,
                                verbosity='DEBUG',
                                solverType='odeint')

        sim.tStop = 10.0
        sim.tInc = 1 / 120.
        sim.run_simulation()

        self.assertEqual(sim.t[-1], sim.tStop)
        self.assertTrue(sim.SOLVER_CONVERGENCE)
Exemple #3
0
 def test_init(self):
     """Test Dynamic Simulation initialization."""          
                     
     events = SimulationEvents()
             
     PVDER = SolarPV_DER_ThreePhase(events = events,
                                    Sinverter_rated = self.power_rating,Vrms_rated = self.Vrms, #175
                                    gridVoltagePhaseA = self.Va,
                                    gridVoltagePhaseB = self.Vb,
                                    gridVoltagePhaseC = self.Vc,
                                    gridFrequency = self.wgrid,
                                    standAlone = False,STEADY_STATE_INITIALIZATION=True,verbosity = 'DEBUG')
 
     sim = DynamicSimulation(PV_model=PVDER,events = events,jacFlag = True,verbosity = 'DEBUG',solver_type='odeint')
     
     self.assertIsInstance(sim, DynamicSimulation)
     self.assertTrue(sim.jacFlag)      
    def create_DER_simulation_instances(self, n_instances):
        """Create specified number of DER instances."""

        assert n_instances >= 1, 'Number of simulation instances should be greater than or equal to one!'

        self.events_list = []
        self.grid_list = []
        self.DER_list = []
        self.sim_list = []

        print('{} DER model instances will be created.'.format(n_instances))

        for instance in range(n_instances):
            print('Creating Instance:', instance + 1)

            self.events_list.append(SimulationEvents())
            self.grid_list.append(
                Grid(events=self.events_list[instance],
                     unbalance_ratio_b=1.0,
                     unbalance_ratio_c=1.0))

            if self._SINGLE_PHASE:
                self.DER_list.append(
                    SolarPV_DER_SinglePhase(
                        grid_model=self.grid_list[instance],
                        events=self.events_list[instance],
                        Sinverter_rated=self._rating,
                        standAlone=True,
                        STEADY_STATE_INITIALIZATION=True,
                        verbosity='INFO'))

            else:
                self.DER_list.append(
                    SolarPV_DER_ThreePhase(grid_model=self.grid_list[instance],
                                           events=self.events_list[instance],
                                           Sinverter_rated=self._rating,
                                           standAlone=True,
                                           STEADY_STATE_INITIALIZATION=True,
                                           verbosity='INFO'))

            self.sim_list.append(
                DynamicSimulation(grid_model=self.grid_list[instance],
                                  PV_model=self.DER_list[instance],
                                  events=self.events_list[instance]))
Exemple #5
0
    def test_init(self):
        """Test Dynamic Simulation initialization."""

        events = SimulationEvents()

        PVDER = SolarPVDERThreePhase(events=events,
                                     configFile=config_file,
                                     **{
                                         **self.flag_arguments,
                                         **self.ratings_arguments,
                                         **self.voltage_arguments
                                     })

        sim = DynamicSimulation(PV_model=PVDER,
                                events=events,
                                jacFlag=True,
                                verbosity='DEBUG',
                                solverType='odeint')

        self.assertIsInstance(sim, DynamicSimulation)
        self.assertTrue(sim.jacFlag)
Exemple #6
0
    def setup_PVDER_simulation(self, model_type='model_2'):
        """Setup simulation environment."""

        self.max_sim_time = self.max_sim_time_user

        events = SimulationEvents(events_spec=self.env_events_spec,
                                  verbosity='INFO')
        grid_model = Grid(events=events)

        PVDER_model = DERModel(
            modelType=self.env_model_spec[model_type]['DERModelType'],
            events=events,
            configFile=self.env_model_spec[model_type]['configFile'],
            gridModel=grid_model,
            derId=self.env_model_spec[model_type]['derId'],
            standAlone=True,
            steadyStateInitialization=True)

        PVDER_model.DER_model.LVRT_ENABLE = False  #Disconnects PV-DER using ride through settings during voltage anomaly
        PVDER_model.DER_model.DO_EXTRA_CALCULATIONS = True
        #PV_model.Vdc_EXTERNAL = True
        self.sim = DynamicSimulation(gridModel=grid_model,
                                     PV_model=PVDER_model.DER_model,
                                     events=events,
                                     verbosity='INFO',
                                     solverType='odeint',
                                     LOOP_MODE=False)  #'odeint','ode-vode-bdf'
        self.sim.jacFlag = True  #Provide analytical Jacobian to ODE solver
        self.sim.DEBUG_SOLVER = False  #Give information on solver convergence

        self.results = SimulationResults(simulation=self.sim)
        self.results.PER_UNIT = False
        self.results.font_size = 18

        self.generate_simulation_events()
        PVDER_model.Qref_EXTERNAL = True  #Enable VAR reference manipulation through outside program
        self.sim.DEBUG_SOLVER = False  #Give information on solver convergence
        self.sim.tInc = self.env_sim_spec[
            'sim_time_step']  #1/60.0 #self.time_taken_per_step #
Exemple #7
0
 def test_run_simulation(self):
     """Test run simulation method.""" 
     
     events = SimulationEvents()
             
     PVDER = SolarPV_DER_ThreePhase(events = events,
                                    Sinverter_rated = self.power_rating,Vrms_rated = self.Vrms, #175
                                    gridVoltagePhaseA = self.Va,
                                    gridVoltagePhaseB = self.Vb,
                                    gridVoltagePhaseC = self.Vc,
                                    gridFrequency = self.wgrid,
                                    standAlone = False,STEADY_STATE_INITIALIZATION=True,verbosity = 'DEBUG')
 
     sim = DynamicSimulation(PV_model=PVDER,events = events,
                             jacFlag = True,verbosity = 'DEBUG',solver_type='odeint')
     
     sim.tStop = 10.0
     sim.tInc = 1/120.
     sim.run_simulation()
     
     self.assertEqual(sim.t[-1],sim.tStop)
     self.assertTrue(sim.SOLVER_CONVERGENCE)  
Exemple #8
0
    def setup(self, nodeid):
        try:
            VpuInitial = 1.0
            SinglePhase = False

            if 'myconfig' in OpenDSSData.config and 'DERParameters' in OpenDSSData.config[
                    'myconfig']:
                if 'DERParameters' in OpenDSSData.config['myconfig']:
                    pvderConfig = OpenDSSData.config['myconfig'][
                        'DERParameters']
                    power_rating = OpenDSSData.config['myconfig'][
                        'DERParameters']['power_rating'] * 1e3
                    voltage_rating = OpenDSSData.config['myconfig'][
                        'DERParameters']['voltage_rating']
                    SteadyState = OpenDSSData.config['myconfig'][
                        'DERParameters']['SteadyState']

                if 'nodenumber' in OpenDSSData.config['myconfig']:
                    DER_location = str(os.getpid()) + '-' + 'bus_' + str(
                        OpenDSSData.config['myconfig']
                        ['nodenumber']) + '-' + 'node_' + nodeid
                else:
                    DER_location = str(os.getpid()) + '-' + 'node_' + nodeid

            else:
                print(
                    'DERParameters not found in `OpenDSSData` object - using default ratings and parameters!'
                )
                pvderConfig = None
                SteadyState = True
                DER_location = 'node_' + nodeid

                if SinglePhase:
                    power_rating = 10.0e3
                else:
                    power_rating = 50.0e3

            Va = (.50 + 0j) * Grid.Vbase
            Vb = (-.25 - .43301270j) * Grid.Vbase
            Vc = (-.25 + .43301270j) * Grid.Vbase

            events = SimulationEvents()

            if SinglePhase:
                self.PV_model = PV_model = SolarPV_DER_SinglePhase(
                    events=events,
                    Sinverter_rated=power_rating,
                    Vrms_rated=voltage_rating,
                    gridVoltagePhaseA=Va * VpuInitial,
                    gridVoltagePhaseB=Vb * VpuInitial,
                    gridVoltagePhaseC=Vc * VpuInitial,
                    gridFrequency=2 * math.pi * 60.0,
                    standAlone=False,
                    STEADY_STATE_INITIALIZATION=SteadyState,
                    pvderConfig=pvderConfig,
                    identifier=DER_location)
            else:
                self.PV_model = PV_model = SolarPV_DER_ThreePhase(
                    events=events,
                    Sinverter_rated=power_rating,
                    Vrms_rated=voltage_rating,
                    gridVoltagePhaseA=Va * VpuInitial,
                    gridVoltagePhaseB=Vb * VpuInitial,
                    gridVoltagePhaseC=Vc * VpuInitial,
                    gridFrequency=2 * math.pi * 60.0,
                    standAlone=False,
                    STEADY_STATE_INITIALIZATION=SteadyState,
                    pvderConfig=pvderConfig,
                    identifier=DER_location)

            self.PV_model.LVRT_ENABLE = True  #Disconnects PV-DER based on ride through settings in case of voltage anomaly
            self.sim = DynamicSimulation(PV_model=PV_model,
                                         events=events,
                                         LOOP_MODE=True,
                                         COLLECT_SOLUTION=True)
            self.sim.jacFlag = True  #Provide analytical Jacobian to ODE solver
            self.sim.DEBUG_SOLVER = False  #Check whether solver is failing to converge at any step

            self.results = SimulationResults(simulation=self.sim,
                                             PER_UNIT=True)

            self.lastSol = copy.deepcopy(self.sim.y0)  # mutable,make copy
            self.lastT = 0
        except Exception as e:
            OpenDSSData.log("Failed Setup PVDER at node:{}!".format(nodeid))
Exemple #9
0
class PVDERModel:
    def __init__(self):
        self._pvModel = {}
        self._sim = {}
        self._lastSol = {}
        self._lastT = 0

    def setup(self, nodeid):
        try:
            VpuInitial = 1.0
            SinglePhase = False

            if 'myconfig' in OpenDSSData.config and 'DERParameters' in OpenDSSData.config[
                    'myconfig']:
                if 'DERParameters' in OpenDSSData.config['myconfig']:
                    pvderConfig = OpenDSSData.config['myconfig'][
                        'DERParameters']
                    power_rating = OpenDSSData.config['myconfig'][
                        'DERParameters']['power_rating'] * 1e3
                    voltage_rating = OpenDSSData.config['myconfig'][
                        'DERParameters']['voltage_rating']
                    SteadyState = OpenDSSData.config['myconfig'][
                        'DERParameters']['SteadyState']

                if 'nodenumber' in OpenDSSData.config['myconfig']:
                    DER_location = str(os.getpid()) + '-' + 'bus_' + str(
                        OpenDSSData.config['myconfig']
                        ['nodenumber']) + '-' + 'node_' + nodeid
                else:
                    DER_location = str(os.getpid()) + '-' + 'node_' + nodeid

            else:
                print(
                    'DERParameters not found in `OpenDSSData` object - using default ratings and parameters!'
                )
                pvderConfig = None
                SteadyState = True
                DER_location = 'node_' + nodeid

                if SinglePhase:
                    power_rating = 10.0e3
                else:
                    power_rating = 50.0e3

            Va = (.50 + 0j) * Grid.Vbase
            Vb = (-.25 - .43301270j) * Grid.Vbase
            Vc = (-.25 + .43301270j) * Grid.Vbase

            events = SimulationEvents()

            if SinglePhase:
                self.PV_model = PV_model = SolarPV_DER_SinglePhase(
                    events=events,
                    Sinverter_rated=power_rating,
                    Vrms_rated=voltage_rating,
                    gridVoltagePhaseA=Va * VpuInitial,
                    gridVoltagePhaseB=Vb * VpuInitial,
                    gridVoltagePhaseC=Vc * VpuInitial,
                    gridFrequency=2 * math.pi * 60.0,
                    standAlone=False,
                    STEADY_STATE_INITIALIZATION=SteadyState,
                    pvderConfig=pvderConfig,
                    identifier=DER_location)
            else:
                self.PV_model = PV_model = SolarPV_DER_ThreePhase(
                    events=events,
                    Sinverter_rated=power_rating,
                    Vrms_rated=voltage_rating,
                    gridVoltagePhaseA=Va * VpuInitial,
                    gridVoltagePhaseB=Vb * VpuInitial,
                    gridVoltagePhaseC=Vc * VpuInitial,
                    gridFrequency=2 * math.pi * 60.0,
                    standAlone=False,
                    STEADY_STATE_INITIALIZATION=SteadyState,
                    pvderConfig=pvderConfig,
                    identifier=DER_location)

            self.PV_model.LVRT_ENABLE = True  #Disconnects PV-DER based on ride through settings in case of voltage anomaly
            self.sim = DynamicSimulation(PV_model=PV_model,
                                         events=events,
                                         LOOP_MODE=True,
                                         COLLECT_SOLUTION=True)
            self.sim.jacFlag = True  #Provide analytical Jacobian to ODE solver
            self.sim.DEBUG_SOLVER = False  #Check whether solver is failing to converge at any step

            self.results = SimulationResults(simulation=self.sim,
                                             PER_UNIT=True)

            self.lastSol = copy.deepcopy(self.sim.y0)  # mutable,make copy
            self.lastT = 0
        except Exception as e:
            OpenDSSData.log("Failed Setup PVDER at node:{}!".format(nodeid))

    def prerun(self, gridVoltagePhaseA, gridVoltagePhaseB, gridVoltagePhaseC):
        """Prerun will set the required data in pvder model. This method should be run before
        running the integrator."""
        try:
            # set grid voltage. This value will be kept constant during the run
            # as opendss will sync will grid_simulation only once during the run call.
            # opendss will solve power flow and will set gridVoltagePhase value.
            self.PV_model.gridVoltagePhaseA = gridVoltagePhaseA * math.sqrt(
                2) / Grid.Vbase
            self.PV_model.gridVoltagePhaseB = gridVoltagePhaseB * math.sqrt(
                2) / Grid.Vbase
            self.PV_model.gridVoltagePhaseC = gridVoltagePhaseC * math.sqrt(
                2) / Grid.Vbase
            self.sim.t = self.lastT + 1 / 120.0

            return None
        except Exception as e:
            OpenDSSData.log("Failed prerun in the pvder model")

    def postrun(self, sol, t, KVAbase=50):
        """Postrun will gather results. This method should be run after running the integrator."""
        try:
            if self.sim.COLLECT_SOLUTION:
                self.sim.collect_solution(sol, t)

            #np array is mutable, hence make a copy
            self.lastSol = copy.deepcopy(sol[-1])
            self.lastT = t[-1]

            # get S
            S = self._getS()

            return S * KVAbase
        except Exception as e:
            OpenDSSData.log("Failed postrun in the pvder model")

    def _run(self,
             gridVoltagePhaseA,
             gridVoltagePhaseB,
             gridVoltagePhaseC,
             KVAbase=50):
        #t = [self.lastT, self.lastT + OpenDSSData.data['DNet']['DER']['DERParameters']['dt']]
        t = [self.lastT, self.lastT + 1 / 120.0]

        try:
            # set grid voltage. This value will be kept constant during the run
            # as opendss will sync will grid_simulation only once during the run call.
            # opendss will solve power flow and will set gridVoltagePhase value.
            self.PV_model.gridVoltagePhaseA = gridVoltagePhaseA * math.sqrt(
                2) / Grid.Vbase
            self.PV_model.gridVoltagePhaseB = gridVoltagePhaseB * math.sqrt(
                2) / Grid.Vbase
            self.PV_model.gridVoltagePhaseC = gridVoltagePhaseC * math.sqrt(
                2) / Grid.Vbase
            self.sim.t = t

            sol, info, ConvergeFlag = self.sim.call_ODE_solver(
                self.sim.ODE_model, self.sim.jac_ODE_model, self.lastSol, t)

            if self.sim.COLLECT_SOLUTION:
                self.sim.collect_solution(sol, t)

            #sol,info=odeint(odeFunc,y0,t,Dfun=jac_odeFunc,full_output=1,printmessg=True,hmax = 1/120.,mxstep=50,atol=1e-4,rtol=1e-4)
            #sol,info=odeint(odeFunc,y0,t,full_output=1,printmessg=True,hmax = 1/120.,mxstep=50,atol=1e-4,rtol=1e-4)

            #np array is mutable, hence make a copy
            self.lastSol = copy.deepcopy(sol[-1])
            self.lastT = t[-1]

            # get S
            S = self._getS()

            return S * KVAbase
        except Exception as e:
            #OpenDSSData.log("Failed run in the pvder model")
            OpenDSSData.log(
                "{}:ODE solver failed between {:.4f} s and {:.4f} s!".format(
                    self.PV_model.name, t[0], t[-1]))

        S = 0
        return S

    def _getS(self):
        try:
            return self.sim.PV_model.S_PCC  # value at end of PV-DER simulation
        except Exception as e:
            OpenDSSData.log("Failed getS in the pvder model")
    def setup_simulation(self, scenario='default'):
        """Setup a simulation."""

        self.events_list = []
        self.grid_list = []
        self.DER_model_list = []
        self.sim_list = []
        self.results_list = []

        self.n_instances = self.return_settings(scenario=scenario,
                                                parameter='n_DER',
                                                settings_type='setup')

        flag_arguments = {
            'standAlone':
            True,
            'steadyStateInitialization':
            self.return_settings(scenario=scenario,
                                 parameter='steadyStateInitialization',
                                 settings_type='setup'),
            'verbosity':
            'DEBUG'
        }
        ratings_arguments = {
            'powerRating':
            self.return_settings(scenario=scenario,
                                 parameter='powerRating',
                                 settings_type='setup')
        }

        SinglePhase = self.return_settings(scenario=scenario,
                                           parameter='SinglePhase',
                                           settings_type='setup')

        for i in range(self.n_instances):

            self.events_list.append(SimulationEvents())
            self.grid_list.append(Grid(events=self.events_list[-1]))

            if SinglePhase:
                self.DER_model_list.append(
                    SolarPVDERSinglePhase(events=self.events_list[-1],
                                          configFile=config_file,
                                          **{
                                              "gridModel": self.grid_list[-1],
                                              "identifier": scenario,
                                              **flag_arguments,
                                              **ratings_arguments
                                          }))
            else:
                self.DER_model_list.append(
                    SolarPVDERThreePhase(events=self.events_list[-1],
                                         configFile=config_file,
                                         **{
                                             "gridModel": self.grid_list[-1],
                                             "identifier": scenario,
                                             **flag_arguments,
                                             **ratings_arguments
                                         }))

            self.sim_list.append(
                DynamicSimulation(gridModel=self.grid_list[-1],
                                  PV_model=self.DER_model_list[-1],
                                  events=self.events_list[-1],
                                  LOOP_MODE=False,
                                  COLLECT_SOLUTION=True))
            self.sim_list[
                -1].jacFlag = False  #Provide analytical Jacobian to ODE solver
            self.sim_list[
                -1].DEBUG_SOLVER = False  #Check whether solver is failing to converge at any step

            self.results_list.append(
                SimulationResults(simulation=self.sim_list[-1], PER_UNIT=True))
Exemple #11
0
    def setup(self, nodeid, V0):
        try:
            VpuInitial = 1.0
            SinglePhase = False

            if 'myconfig' in OpenDSSData.config and 'DERParameters' in OpenDSSData.config[
                    'myconfig']:
                #pvderConfig = copy.deepcopy(OpenDSSData.config['myconfig']['DERParameters'])

                DERFilePath = OpenDSSData.config['myconfig']['DERFilePath']
                DERModelType = OpenDSSData.config['myconfig']['DERModelType']
                DERSetting = OpenDSSData.config['myconfig']['DERSetting']

                DERParameters = OpenDSSData.config['myconfig']['DERParameters']

                if DERSetting == 'default':
                    pvderConfig = self.get_derconfig(DERParameters['default'])
                    DERArguments = self.get_derarguments(
                        DERParameters['default'])

                elif DERSetting == 'PVPlacement':  # for manual feeder config based on PVPlacement
                    if nodeid in DERParameters['PVPlacement']:
                        pvderConfig = self.get_derconfig(
                            DERParameters['PVPlacement'][nodeid])
                        DERArguments = self.get_derarguments(
                            DERParameters['PVPlacement'][nodeid])
                    else:
                        raise ValueError(
                            'Distribution node {} not found in config file!'.
                            format(nodeid))
                else:
                    raise ValueError(
                        '{} is not a valid DER setting in config file!'.format(
                            DERSetting))

                if 'nodenumber' in OpenDSSData.config['myconfig']:
                    DERLocation = str(os.getpid()) + '-' + 'bus_' + str(
                        OpenDSSData.config['myconfig']
                        ['nodenumber']) + '-' + 'node_' + nodeid
                else:
                    DERLocation = str(os.getpid()) + '-' + 'node_' + nodeid

            else:
                print(
                    'DERParameters not found in `OpenDSSData` object - using default ratings and parameters!'
                )
                DERArguments = {}
                pvderConfig = {}
                SteadyState = True
                if SinglePhase:
                    powerRating = 10.0e3
                else:
                    powerRating = 50.0e3
                DERLocation = 'node_' + nodeid

                DERArguments.update({'pvderConfig': pvderConfig})
                DERArguments.update({'powerRating': powerRating})
                DERArguments.update({'SteadyState': SteadyState})

            #Va = cmath.rect(DERArguments['VrmsRating']*math.sqrt(2),0.0)
            #Vb = utility_functions.Ub_calc(Va)
            #Vc = utility_functions.Uc_calc(Va)
            a = utility_functions.Urms_calc(
                V0['a'], V0['b'], V0['c']) / DERArguments['VrmsRating']
            Va = (V0['a'] / a)  #Convert node voltage at HV side to LV
            Vb = (V0['b'] / a)
            Vc = (V0['c'] / a)

            DERArguments.update({'identifier': DERLocation})
            DERArguments.update({'derConfig': pvderConfig})
            DERArguments.update({'standAlone': False})

            DERArguments.update({'gridFrequency': 2 * math.pi * 60.0})
            DERArguments.update({'gridVoltagePhaseA': Va})
            DERArguments.update({'gridVoltagePhaseB': Vb})
            DERArguments.update({'gridVoltagePhaseC': Vc})

            logging.debug(
                'Creating DER instance of {} model for {} node.'.format(
                    DERModelType, DERLocation))
            print('Creating DER instance of {} model for {} node.'.format(
                DERModelType, DERLocation))
            events = SimulationEvents()

            PVDER_model = DERModel(modelType=DERModelType,
                                   events=events,
                                   configFile=DERFilePath,
                                   **DERArguments)
            self.PV_model = PVDER_model.DER_model

            self.PV_model.LVRT_ENABLE = True  #Disconnects PV-DER based on ride through settings in case of voltage anomaly
            self.sim = DynamicSimulation(PV_model=self.PV_model,
                                         events=events,
                                         LOOP_MODE=True,
                                         COLLECT_SOLUTION=True)
            if DERModelType in self.sim.jac_list:
                self.sim.jacFlag = True  #Provide analytical Jacobian to ODE solver
            else:
                self.sim.jacFlag = False
            self.sim.DEBUG_SOLVER = False  #Check whether solver is failing to converge at any step
            self.results = SimulationResults(simulation=self.sim,
                                             PER_UNIT=True)

            self.lastSol = copy.deepcopy(self.sim.y0)  # mutable,make copy
            self.lastT = 0
        except Exception as e:
            OpenDSSData.log("Failed Setup PVDER at node:{}!".format(nodeid))
Exemple #12
0
class PVDERModel:
    def __init__(self):
        self._pvModel = {}
        self._sim = {}
        self._lastSol = {}
        self._lastT = 0

    def setup(self, nodeid, V0):
        try:
            VpuInitial = 1.0
            SinglePhase = False

            if 'myconfig' in OpenDSSData.config and 'DERParameters' in OpenDSSData.config[
                    'myconfig']:
                #pvderConfig = copy.deepcopy(OpenDSSData.config['myconfig']['DERParameters'])

                DERFilePath = OpenDSSData.config['myconfig']['DERFilePath']
                DERModelType = OpenDSSData.config['myconfig']['DERModelType']
                DERSetting = OpenDSSData.config['myconfig']['DERSetting']

                DERParameters = OpenDSSData.config['myconfig']['DERParameters']

                if DERSetting == 'default':
                    pvderConfig = self.get_derconfig(DERParameters['default'])
                    DERArguments = self.get_derarguments(
                        DERParameters['default'])

                elif DERSetting == 'PVPlacement':  # for manual feeder config based on PVPlacement
                    if nodeid in DERParameters['PVPlacement']:
                        pvderConfig = self.get_derconfig(
                            DERParameters['PVPlacement'][nodeid])
                        DERArguments = self.get_derarguments(
                            DERParameters['PVPlacement'][nodeid])
                    else:
                        raise ValueError(
                            'Distribution node {} not found in config file!'.
                            format(nodeid))
                else:
                    raise ValueError(
                        '{} is not a valid DER setting in config file!'.format(
                            DERSetting))

                if 'nodenumber' in OpenDSSData.config['myconfig']:
                    DERLocation = str(os.getpid()) + '-' + 'bus_' + str(
                        OpenDSSData.config['myconfig']
                        ['nodenumber']) + '-' + 'node_' + nodeid
                else:
                    DERLocation = str(os.getpid()) + '-' + 'node_' + nodeid

            else:
                print(
                    'DERParameters not found in `OpenDSSData` object - using default ratings and parameters!'
                )
                DERArguments = {}
                pvderConfig = {}
                SteadyState = True
                if SinglePhase:
                    powerRating = 10.0e3
                else:
                    powerRating = 50.0e3
                DERLocation = 'node_' + nodeid

                DERArguments.update({'pvderConfig': pvderConfig})
                DERArguments.update({'powerRating': powerRating})
                DERArguments.update({'SteadyState': SteadyState})

            #Va = cmath.rect(DERArguments['VrmsRating']*math.sqrt(2),0.0)
            #Vb = utility_functions.Ub_calc(Va)
            #Vc = utility_functions.Uc_calc(Va)
            a = utility_functions.Urms_calc(
                V0['a'], V0['b'], V0['c']) / DERArguments['VrmsRating']
            Va = (V0['a'] / a)  #Convert node voltage at HV side to LV
            Vb = (V0['b'] / a)
            Vc = (V0['c'] / a)

            DERArguments.update({'identifier': DERLocation})
            DERArguments.update({'derConfig': pvderConfig})
            DERArguments.update({'standAlone': False})

            DERArguments.update({'gridFrequency': 2 * math.pi * 60.0})
            DERArguments.update({'gridVoltagePhaseA': Va})
            DERArguments.update({'gridVoltagePhaseB': Vb})
            DERArguments.update({'gridVoltagePhaseC': Vc})

            logging.debug(
                'Creating DER instance of {} model for {} node.'.format(
                    DERModelType, DERLocation))
            print('Creating DER instance of {} model for {} node.'.format(
                DERModelType, DERLocation))
            events = SimulationEvents()

            PVDER_model = DERModel(modelType=DERModelType,
                                   events=events,
                                   configFile=DERFilePath,
                                   **DERArguments)
            self.PV_model = PVDER_model.DER_model

            self.PV_model.LVRT_ENABLE = True  #Disconnects PV-DER based on ride through settings in case of voltage anomaly
            self.sim = DynamicSimulation(PV_model=self.PV_model,
                                         events=events,
                                         LOOP_MODE=True,
                                         COLLECT_SOLUTION=True)
            if DERModelType in self.sim.jac_list:
                self.sim.jacFlag = True  #Provide analytical Jacobian to ODE solver
            else:
                self.sim.jacFlag = False
            self.sim.DEBUG_SOLVER = False  #Check whether solver is failing to converge at any step
            self.results = SimulationResults(simulation=self.sim,
                                             PER_UNIT=True)

            self.lastSol = copy.deepcopy(self.sim.y0)  # mutable,make copy
            self.lastT = 0
        except Exception as e:
            OpenDSSData.log("Failed Setup PVDER at node:{}!".format(nodeid))

    def get_derconfig(self, DERParameters):
        """DER config."""

        derConfig = {}

        for entry in DERParameters:
            if entry in templates.VRT_config_template.keys():
                derConfig.update({entry: DERParameters[entry]})

        return derConfig

    def get_derarguments(self, DERParameters):
        """DER config."""

        DERArguments = {}

        for entry in specifications.DER_argument_spec:
            if entry in DERParameters:
                DERArguments.update({entry: DERParameters[entry]})

        if 'powerRating' in DERArguments:
            DERArguments.update(
                {'powerRating': DERArguments['powerRating'] * 1e3})

        return DERArguments

    def prerun(self, gridVoltagePhaseA, gridVoltagePhaseB, gridVoltagePhaseC):
        """Prerun will set the required data in pvder model. This method should be run before
        running the integrator."""
        try:
            # set grid voltage. This value will be kept constant during the run
            # as opendss will sync will grid_simulation only once during the run call.
            # opendss will solve power flow and will set gridVoltagePhase value.
            self.PV_model.gridVoltagePhaseA = gridVoltagePhaseA * math.sqrt(
                2) / Grid.Vbase
            if templates.DER_design_template[
                    self.PV_model.DER_model_type]['basic_specs']['unbalanced']:
                self.PV_model.gridVoltagePhaseB = gridVoltagePhaseB * math.sqrt(
                    2) / Grid.Vbase
                self.PV_model.gridVoltagePhaseC = gridVoltagePhaseC * math.sqrt(
                    2) / Grid.Vbase
            self.sim.t = self.lastT + 1 / 120.0

            return None
        except Exception as e:
            OpenDSSData.log("Failed prerun in the pvder model")

    def postrun(self, sol, t, KVAbase=50):
        """Postrun will gather results. This method should be run after running the integrator."""
        try:
            if self.sim.COLLECT_SOLUTION:
                self.sim.collect_solution(sol, t)

            #np array is mutable, hence make a copy
            self.lastSol = copy.deepcopy(sol[-1])
            self.lastT = t[-1]

            # get S
            S = self._getS()

            return S * KVAbase
        except Exception as e:
            OpenDSSData.log("Failed postrun in the pvder model")

    def _run(self,
             gridVoltagePhaseA,
             gridVoltagePhaseB,
             gridVoltagePhaseC,
             KVAbase=50):
        #t = [self.lastT, self.lastT + OpenDSSData.data['DNet']['DER']['DERParameters']['dt']]
        t = [self.lastT, self.lastT + 1 / 120.0]

        try:
            # set grid voltage. This value will be kept constant during the run
            # as opendss will sync will grid_simulation only once during the run call.
            # opendss will solve power flow and will set gridVoltagePhase value.
            self.PV_model.gridVoltagePhaseA = gridVoltagePhaseA * math.sqrt(
                2) / Grid.Vbase
            self.PV_model.gridVoltagePhaseB = gridVoltagePhaseB * math.sqrt(
                2) / Grid.Vbase
            self.PV_model.gridVoltagePhaseC = gridVoltagePhaseC * math.sqrt(
                2) / Grid.Vbase
            self.sim.t = t

            sol, info, ConvergeFlag = self.sim.call_ODE_solver(
                self.sim.ODE_model, self.sim.jac_ODE_model, self.lastSol, t)

            if self.sim.COLLECT_SOLUTION:
                self.sim.collect_solution(sol, t)

            #sol,info=odeint(odeFunc,y0,t,Dfun=jac_odeFunc,full_output=1,printmessg=True,hmax = 1/120.,mxstep=50,atol=1e-4,rtol=1e-4)
            #sol,info=odeint(odeFunc,y0,t,full_output=1,printmessg=True,hmax = 1/120.,mxstep=50,atol=1e-4,rtol=1e-4)

            #np array is mutable, hence make a copy
            self.lastSol = copy.deepcopy(sol[-1])
            self.lastT = t[-1]

            # get S
            S = self._getS()

            return S * KVAbase
        except Exception as e:
            #OpenDSSData.log("Failed run in the pvder model")
            OpenDSSData.log(
                "{}:ODE solver failed between {:.4f} s and {:.4f} s!".format(
                    self.PV_model.name, t[0], t[-1]))

        S = 0
        return S

    def _getS(self):
        try:
            return self.sim.PV_model.S_PCC  # value at end of PV-DER simulation
        except Exception as e:
            OpenDSSData.log("Failed getS in the pvder model")