示例#1
0
 def test_staticInitalize(self):
     model = PSSEModel()
     model.setup()
     GlobalData.data['DNet']['Nodes'] = {11: {}}
     targetS, Vpcc = model.staticInitialize()
     self.assertIsNotNone(Vpcc[11])
     self.assertIsNotNone(targetS[11])
示例#2
0
 def test_dynamicInitalize(self):
     GlobalData.data['dynamic'] = {}
     model = PSSEModel()
     model.setup()
     GlobalData.data['DNet']['Nodes'] = {11: {'solarPenetration': 0.1}}
     GlobalData.data['DNet']['ReductionPercent'] = 0.1
     targetS, Vpcc = model.dynamicInitialize()
     self.assertIsNotNone(Vpcc[11])
     self.assertIsNotNone(targetS[11])
示例#3
0
 def test_setLoad(self):
     model = PSSEModel()
     model.setup()
     GlobalData.data['DNet']['Nodes'] = {11: {}}
     S = {11: {'P': 0.0, 'Q': 0.0}}
     targetS, Vpcc = model.staticInitialize()
     model.setLoad(S)
     model.runPFLOW()
     Vpcc2 = model.getVoltage()
     for node in Vpcc:
         self.assertNotEqual(Vpcc[node], Vpcc2[node])
示例#4
0
 def test_shunt(self):
     GlobalData.data['dynamic'] = {}
     model = PSSEModel()
     model.setup()
     GlobalData.data['DNet']['Nodes'] = {11: {'solarPenetration': 0.1}}
     GlobalData.data['DNet']['ReductionPercent'] = 0.1
     targetS, Vpcc = model.dynamicInitialize()
     power = {11: {'P': 10.0, 'Q': 10.0}}
     model.shunt(targetS, Vpcc, power)
     model.runPFLOW()
     Vpcc2 = model.getVoltage()
     for node in Vpcc:
         self.assertEqual(Vpcc[node], Vpcc2[node])
示例#5
0
 def test_getVoltage(self):
     model = PSSEModel()
     model.setup()
     GlobalData.data['DNet']['Nodes'] = {11: {}}
     targetS, Vpcc = model.staticInitialize()
     Vpcc2 = model.getVoltage()
     for node in Vpcc:
         self.assertEqual(Vpcc[node], Vpcc2[node])
示例#6
0
 def test_init(self):
     model = PSSEModel()
     self.assertIsInstance(model, PSSEModel)
示例#7
0
 def test_setup(self):
     model = PSSEModel()
     model.setup()
     self.assertNotEqual(GlobalData.data['TNet']['TotalRealPowerLoad'], 0)
class DefaultStaticProcedure(DefaultProcedure):
    def __init__(self):
        self._tnet_model = PSSEModel()
        self._dnet_model = OpenDSSModel()
    def setup(self):
        self._tnet_model.setup()
        self._dnet_model.setup()        
    def initialize(self):        
        targetS, Vpcc = self._tnet_model.staticInitialize()        
        power = self._dnet_model.initialize(targetS, Vpcc)        
        self._tnet_model.shunt(targetS, Vpcc, power)
    def run(self):        
        GlobalData.data['static'] = {}
        maxIter = 20
        tol=10**-4
        count = 0
        loadShape = GlobalData.config['simulationConfig']['staticConfig']['loadShape']
        GlobalData.data['monitorData']={}
        for scale in loadShape:
            GlobalData.data['static'][count] = {}
            f=lambda x:[x[entry] for entry in x]
            iteration=0
            scaleData={}
            Vpcc = self._tnet_model.getVoltage()
            Vcheck=np.random.random((len(Vpcc),2))
            for nodeID in Vpcc:
                scaleData[nodeID]=scale
            self._dnet_model.scaleLoad(scaleData)# now scale distribution feeder load

            while np.any(np.abs(Vcheck[:,0]-Vcheck[:,1])>tol) and iteration<maxIter:
                self._tnet_model.runPFLOW()# run power flow
                Vpcc = self._tnet_model.getVoltage()
                self._dnet_model.setVoltage(Vpcc)#set voltage based on previous guess
                S = self._dnet_model.getLoad()# get complex power injection
                self._tnet_model.setLoad(S)# set complex power injection as seen from T side
                Vcheck[:,0]=Vcheck[:,1]#iterate for tight coupling
                Vcheck[:,1]=np.array(f(Vpcc))
                iteration+=1

            # collect data and store
            msg={}
            msg['varName']={}
            for node in Vpcc:
                msg['varName'][node]=['voltage']
            GlobalData.data['monitorData'][count]=self._dnet_model.monitor(msg)

            GlobalData.data['static'][count]['V'] = Vpcc
            GlobalData.data['static'][count]['S'] = S
            GlobalData.data['static'][count]['Scale'] = scale
            count = count + 1
 def __init__(self):
     self._tnet_model = PSSEModel()
     self._dnet_model = OpenDSSModel()
示例#10
0
	def __init__(self):
		try:
			self._tnet_model = PSSEModel()
			self._dnet_model = OpenDSSModel()
		except:
			GlobalData.log()
示例#11
0
class DefaultStaticProcedure(DefaultProcedure):
#===================================================================================================
	def __init__(self):
		try:
			self._tnet_model = PSSEModel()
			self._dnet_model = OpenDSSModel()
		except:
			GlobalData.log()

#===================================================================================================
	def setup(self):
		try:
			self._tnet_model.setup()
			self._dnet_model.setup()
		except:
			GlobalData.log()

#===================================================================================================
	def initialize(self):
		try:
			targetS, Vpcc = self._tnet_model.staticInitialize()
			GlobalData.log(20,'Attaching substaion to following buses: {}'.format(Vpcc.keys()))
			power = self._dnet_model.initialize(targetS, Vpcc)
		except:
			GlobalData.log()

#===================================================================================================
	def run(self):
		try:
			GlobalData.data['static'] = {}
			maxIter = 20
			tol=10**-4
			count = 0
			loadShape = GlobalData.config['simulationConfig']['staticConfig']['loadShape']
			GlobalData.data['monitorData']={}
			updateBins=20

			for scale in loadShape:
				GlobalData.log(20,'Running dispatch with loadshape {}'.format(scale))
				GlobalData.data['static'][count] = {}
				f=lambda x:[x[entry] for entry in x]
				iteration=0
				scaleData={}
				Vpcc = self._tnet_model.getVoltage()
				Vcheck=np.random.random((len(Vpcc),2))
				for nodeID in Vpcc:
					scaleData[nodeID]=scale
				self._dnet_model.scaleLoad(scaleData)# now scale distribution feeder load

				while np.any(np.abs(Vcheck[:,0]-Vcheck[:,1])>tol) and iteration<maxIter:
					self._tnet_model.runPFLOW()# run power flow
					Vpcc = self._tnet_model.getVoltage()
					self._dnet_model.setVoltage(Vpcc)#set voltage based on previous guess
					S = self._dnet_model.getLoad()# get complex power injection
					self._tnet_model.setLoad(S)# set complex power injection as seen from T side
					Vcheck[:,0]=Vcheck[:,1]#iterate for tight coupling
					Vcheck[:,1]=np.array(f(Vpcc))
					iteration+=1
				
				print('Simulation Progress : ='+'='*int((updateBins-1)*(count/len(loadShape)))+'>'+\
				' {}%({} dispatches/{} dispatches)'.format(((count+1)/len(loadShape))*100,count+1,len(loadShape)),end='\r')
				GlobalData.log(20,'Loadshape {} Converged in {} iterations with mismatch {}'.format(scale,iteration,max(abs(np.abs(Vcheck[:,0]-Vcheck[:,1])))))

				# collect data and store
				msg={}
				msg['varName']={}
				for node in Vpcc:
					msg['varName'][node]=['voltage']
				GlobalData.data['monitorData'][count]=self._dnet_model.monitor(msg)

				GlobalData.data['static'][count]['V'] = Vpcc
				GlobalData.data['static'][count]['S'] = S
				GlobalData.data['static'][count]['Scale'] = scale
				count+=1

			# close
			print('')# for newline
			ack=self._dnet_model.close()
			GlobalData.log(level=20,msg=json.dumps(ack))
			ierr=self._tnet_model._psspy.pssehalt_2(); assert ierr==0
		except:
			GlobalData.log()
示例#12
0
class DefaultDynamicProcedure(DefaultProcedure):
    def __init__(self):
        self._tnet_model = PSSEModel()
        self._dnet_model = OpenDSSModel()

    def setup(self):
        self._tnet_model.setup()
        self._dnet_model.setup()

    def initialize(self):
        GlobalData.data['dynamic'] = {}
        targetS, Vpcc = self._tnet_model.dynamicInitialize()
        power = self._dnet_model.initialize(targetS, Vpcc)
        self._tnet_model.shunt(targetS, Vpcc, power)

    def run(self):

        GlobalData.data['monitorData'] = {}
        GlobalData.data['TNet']['Dynamic'] = {}
        dt = 0.0083333
        maxIter = 1
        tol = 10**-4
        if GlobalData.config['simulationConfig']['protocol'].lower(
        ) != 'loose_coupling':
            maxIter = GlobalData.config['simulationConfig']['protocol'][
                'maxiteration']
        eventData = GlobalData.config['simulationConfig']['dynamicConfig'][
            'events']
        events = eventData.keys()
        events.sort()

        memory_threshold = GlobalData.config['simulationConfig'][
            'memoryThreshold']

        t = 0

        stepCount = 0
        stepThreshold = 1e6
        lastWriteInd = 0
        nPart = 0

        for event in events:
            while t < eventData[event]['time']:
                iteration = 0
                mismatch = 100.
                if t <= eventData[event]['time'] and t + dt >= eventData[
                        event]['time']:
                    if eventData[event]['type'] == 'faultOn':
                        self._tnet_model.faultOn(
                            eventData[event]['faultBus'],
                            eventData[event]['faultImpedance'])
                    elif eventData[event]['type'] == 'faultOff':
                        self._tnet_model.faultOff(eventData[event]['faultBus'])
                while mismatch > tol and iteration < maxIter:
                    try:
                        t = t + dt
                        iteration += 1
                        self._tnet_model.runDynamic(t)
                        print("Sim time: " + str(t))
                        Vpcc = self._tnet_model.getVoltage()
                        self._dnet_model.setVoltage(Vpcc)
                        S = self._dnet_model.getLoad()
                        self._tnet_model.setLoad(S)

                        # collect data and store
                        msg = {}
                        msg['varName'] = {}
                        for node in Vpcc:
                            msg['varName'][node] = ['voltage', 'der']
                        GlobalData.data['monitorData'][
                            t] = self._dnet_model.monitor(msg)

                        GlobalData.data['TNet']['Dynamic'][t] = {
                            'V': Vpcc,
                            'S': S
                        }

                        # write to disk if running low on memory based on memory threshold
                        try:
                            if stepCount == 0:
                                currentMemUsage = psutil.Process(
                                ).memory_full_info().uss * 1e-6
                                print("Current Memory: " +
                                      str(currentMemUsage))
                            elif stepCount == 1:
                                memUseRate = psutil.Process().memory_full_info(
                                ).uss * 1e-6 - currentMemUsage
                                stepThreshold = int(memory_threshold /
                                                    memUseRate)
                                print("Step Threshhold: " + str(stepThreshold))
                            elif stepCount > 1 and stepCount % stepThreshold == 0:
                                ffullpath = str(
                                    GlobalData.config["outputPath"] +
                                    "\\report{}.xlsx".format(nPart))
                                stype = str(
                                    GlobalData.config['simulationConfig']
                                    ['simType'])
                                generateReport(GlobalData,
                                               fname=ffullpath,
                                               sim=stype)
                                print("generated report part" + str(nPart))
                                GlobalData.data['monitorData'] = {
                                }  # empty data
                                GlobalData.data['TNet']['Dynamic'] = {
                                }  # empty data
                                nPart += 1
                                lastWriteInd = stepCount
                            stepCount += 1
                        except:
                            print(
                                "Failed write the data on the file to protect the memory"
                            )
                            print("Unexpected error:", sys.exc_info()[0])

                        #mismatch=Vprev-V ##TODO: Need to update mismatch
                        #TODO: tight_coupling isn't implemented
                        if GlobalData.config['simulationConfig'][
                                'protocol'].lower(
                                ) == 'tight_coupling' and mismatch > tol:
                            print("Tight Couping is not implemented")

                    except Exception as e:
                        print('failed to run dynamic simulation')
                        GlobalData.data['TNet']['Dynamic'][t] = {
                            'V': Vpcc,
                            'S': S
                        }
                        DSSconvergenceFlg = True
                        for busID in GlobalData.data['TNet']['LoadBusNumber']:
                            if busID in GlobalData.data['DNet']['Nodes']:
                                if S[busID]['convergenceFlg'] is False:
                                    DSSconvergenceFlg = False
                                    break
                        if DSSconvergenceFlg is False:
                            print('OpenDSS Convergence Failed')
示例#13
0
class DefaultDynamicProcedure(DefaultProcedure):
    #===================================================================================================
    def __init__(self):
        try:
            self._tnet_model = PSSEModel()
            self._dnet_model = OpenDSSModel()
        except:
            GlobalData.log()

#===================================================================================================

    def setup(self):
        try:
            self._tnet_model.setup()
            self._dnet_model.setup()
        except:
            GlobalData.log()

#===================================================================================================

    def initialize(self):
        try:
            GlobalData.data['dynamic'] = {}
            targetS, Vpcc = self._tnet_model.dynamicInitialize()
            power = self._dnet_model.initialize(targetS, Vpcc)
            self._tnet_model.shunt(targetS, Vpcc, power)
        except:
            GlobalData.log()

#===================================================================================================

    def run(self):
        try:
            GlobalData.data['monitorData'] = {}
            GlobalData.data['TNet']['Dynamic'] = {}
            maxIter = 1
            tol = 10**-4
            if GlobalData.config['simulationConfig']['protocol'].lower(
            ) != 'loose_coupling':
                maxIter = GlobalData.config['simulationConfig']['protocol'][
                    'maxiteration']
            eventData = GlobalData.config['simulationConfig']['dynamicConfig'][
                'events']
            events = eventData.keys()
            if six.PY3:
                events = list(events)
            events.sort()

            memory_threshold = GlobalData.config['simulationConfig'][
                'memoryThreshold']
            t = 0.0
            dt = dt_default = 1 / 120.
            eps = 1e-4
            stepCount = 0
            stepThreshold = 1e6
            lastWriteInd = 0
            nPart = 0
            simEnd = eventData[events[-1]]['time']
            updateBins = 20
            eventFlag = False
            resetFlag = False

            # t0
            Vpcc = self._tnet_model.getVoltage()
            self._dnet_model.setVoltage(Vpcc)
            S = self._dnet_model.getLoad(t=t, dt=dt)

            msg = {'varName': {}}
            for node in Vpcc:
                msg['varName'][node] = ['voltage_der', 'der']

            GlobalData.data['monitorData'][t] = self._dnet_model.monitor(msg)
            GlobalData.data['TNet']['Dynamic'][t] = {'V': Vpcc, 'S': S}

            for event in events:
                while t < eventData[event]['time']:
                    iteration = 0
                    mismatch = 100.
                    while mismatch > tol and iteration < maxIter:
                        if t + dt - eps < eventData[event][
                                'time'] < t + dt + eps:
                            eventFlag = True
                            dt = dt_default - eps
                        t += dt

                        iteration += 1
                        self._tnet_model.runDynamic(t)
                        print('Simulation Progress : ='+'='*int((updateBins-1)*(t/simEnd))+'>'+\
                        ' {}%({}s/{}s)'.format((t/simEnd)*100,t,simEnd),end='\r')
                        GlobalData.log(level=10, msg="Sim time: " + str(t))
                        Vpcc = self._tnet_model.getVoltage()
                        self._dnet_model.setVoltage(Vpcc)
                        S = self._dnet_model.getLoad(t=t, dt=dt)
                        self._tnet_model.setLoad(S)

                        # collect data and store
                        msg = {'varName': {}}
                        for node in Vpcc:
                            msg['varName'][node] = ['voltage_der', 'der']

                        GlobalData.data['monitorData'][
                            t] = self._dnet_model.monitor(msg)
                        GlobalData.data['TNet']['Dynamic'][t] = {
                            'V': Vpcc,
                            'S': S
                        }

                        # write to disk if running low on memory based on memory threshold
                        if stepCount == 0:
                            currentMemUsage = psutil.Process(
                            ).memory_full_info().uss * 1e-6
                            GlobalData.log(level=10,
                                           msg="Current Memory: " +
                                           str(currentMemUsage))
                        elif stepCount == 1:
                            memUseRate = psutil.Process().memory_full_info(
                            ).uss * 1e-6 - currentMemUsage
                            if memUseRate == 0:
                                memUseRate = 1
                            stepThreshold = int(memory_threshold / memUseRate)
                            GlobalData.log(level=10,
                                           msg="Step Threshhold: " +
                                           str(stepThreshold))
                        elif stepCount > 1 and stepCount % stepThreshold == 0:
                            ffullpath = str(GlobalData.config["outputPath"]+\
                            "\\report{}.xlsx".format(nPart))
                            stype = str(GlobalData.config['simulationConfig']
                                        ['simType'])
                            generate_excel_report(GlobalData,
                                                  fname=ffullpath,
                                                  sim=stype)
                            GlobalData.log(level=10,
                                           msg="generated report part" +
                                           str(nPart))
                            GlobalData.data['monitorData'] = {}  # empty data
                            GlobalData.data['TNet']['Dynamic'] = {
                            }  # empty data
                            nPart += 1
                            lastWriteInd = stepCount
                        stepCount += 1

                        #mismatch=Vprev-V ##TODO: Need to update mismatch
                        #TODO: tight_coupling isn't implemented
                        if GlobalData.config['simulationConfig']['protocol'].lower()==\
                        'tight_coupling' and mismatch>tol:
                            GlobalData.log(
                                level=50,
                                msg="Tight Couping is not implemented")

                        # check for DSS convergence
                        DSSconvergenceFlg = True
                        for busID in GlobalData.data['TNet']['LoadBusNumber']:
                            if busID in GlobalData.data['DNet']['Nodes']:
                                if S[busID]['convergenceFlg'] is False:
                                    DSSconvergenceFlg = False
                                    break
                        if DSSconvergenceFlg is False:
                            GlobalData.log(msg='OpenDSS Convergence Failed')

                        if resetFlag:
                            dt = dt_default - 2 * eps
                            resetFlag = False
                        elif eventFlag:
                            if eventData[event]['type'] == 'faultOn':
                                self._tnet_model.faultOn(
                                    eventData[event]['faultBus'],
                                    eventData[event]['faultImpedance'])
                            elif eventData[event]['type'] == 'faultOff':
                                self._tnet_model.faultOff(
                                    eventData[event]['faultBus'])
                            eventFlag = False
                            dt = 3 * eps
                            resetFlag = True
                        else:
                            dt = dt_default
            # close
            print('')  # for newline
            ack = self._dnet_model.close()
            GlobalData.log(level=20, msg=json.dumps(ack))
            ierr = self._tnet_model._psspy.pssehalt_2()
            assert ierr == 0
        except:
            GlobalData.log()
示例#14
0
class DefaultDynamicProcedure(DefaultProcedure):
    def __init__(self):
        self._tnet_model = PSSEModel()
        self._dnet_model = OpenDSSModel()

    def setup(self):
        self._tnet_model.setup()
        self._dnet_model.setup()

    def initialize(self):
        GlobalData.data['dynamic'] = {}
        targetS, Vpcc = self._tnet_model.dynamicInitialize()
        power = self._dnet_model.initialize(targetS, Vpcc)
        self._tnet_model.shunt(targetS, Vpcc, power)

    def run(self):

        GlobalData.data['monitorData'] = {}
        GlobalData.data['TNet']['Dynamic'] = {}
        dt = 0.0083333
        maxIter = 1
        tol = 10**-4
        if GlobalData.config['simulationConfig']['protocol'].lower(
        ) != 'loose_coupling':
            maxIter = GlobalData.config['simulationConfig']['protocol'][
                'maxiteration']
        eventData = GlobalData.config['simulationConfig']['dynamicConfig'][
            'events']
        events = eventData.keys()
        events.sort()
        t = 0
        for event in events:
            while t < eventData[event]['time']:
                iteration = 0
                mismatch = 100.
                if t <= eventData[event]['time'] and t + dt >= eventData[
                        event]['time']:
                    if eventData[event]['type'] == 'faultOn':
                        self._tnet_model.faultOn(
                            eventData[event]['faultBus'],
                            eventData[event]['faultImpedance'])
                    elif eventData[event]['type'] == 'faultOff':
                        self._tnet_model.faultOff()
                while mismatch > tol and iteration < maxIter:
                    try:
                        self._tnet_model.runDynamic(t + dt)
                        t = t + dt
                        print("Sim time: " + str(t))
                        Vpcc = self._tnet_model.getVoltage()
                        self._dnet_model.setVoltage(Vpcc)
                        S = self._dnet_model.getLoad()
                        self._tnet_model.setLoad(S)

                        # collect data and store
                        msg = {}
                        msg['varName'] = {}
                        for node in Vpcc:
                            msg['varName'][node] = ['voltage', 'der']
                        GlobalData.data['monitorData'][
                            t] = self._dnet_model.monitor(msg)

                        GlobalData.data['TNet']['Dynamic'][t] = {
                            'V': Vpcc,
                            'S': S
                        }
                        #mismatch=Vprev-V ##TODO: Need to update mismatch
                        #TODO: tight_coupling isn't implemented
                        if GlobalData.config['simulationConfig'][
                                'protocol'].lower(
                                ) == 'tight_coupling' and mismatch > tol:
                            print("Tight Couping is not implemented")
                        iteration += 1
                    except Exception as e:
                        print('failed to run dynamic simulation')
                        GlobalData.data['TNet']['Dynamic'][t] = {
                            'V': Vpcc,
                            'S': S
                        }
                        DSSconvergenceFlg = True
                        for busID in GlobalData.data['TNet']['LoadBusNumber']:
                            if busID in GlobalData.data['DNet']['Nodes']:
                                if S[busID]['convergenceFlg'] is False:
                                    DSSconvergenceFlg = False
                                    break
                        if DSSconvergenceFlg is False:
                            print('OpenDSS Convergence Failed')