Пример #1
0
def main(delay=None):

    broker = create_broker()
    fed = create_value_federate(broker)

    pubid = h.helicsFederateRegisterGlobalTypePublication(
        fed, "federate1-to-federate2", h.HELICS_DATA_TYPE_STRING, "")
    subid = h.helicsFederateRegisterSubscription(fed, "federate2-to-federate1",
                                                 "double", "")
    epid = h.helicsFederateRegisterGlobalEndpoint(fed, "endpoint1", "")

    if delay is not None:
        fid = h.helicsFederateRegisterSourceFilter(fed, h.helics_delay_filter,
                                                   "endpoint2", "filter-name")

    h.helicsSubscriptionSetDefaultDouble(subid, 0)

    print("Entering execution mode")
    h.helicsFederateEnterExecutionMode(fed)

    if delay is not None:
        h.helicsFilterSet(fid, "delay", 2.0)

    grantedtime = -1
    while True:
        try:
            stop_at_time, value_to_send = get_input(grantedtime)
        except KeyboardInterrupt:
            print("")
            break
        while grantedtime < stop_at_time:
            print(">>>>>>>> Requesting time = {}".format(stop_at_time))
            status, grantedtime = h.helicsFederateRequestTime(
                fed, stop_at_time)
            assert status == 0
            if grantedtime != stop_at_time:
                status, value = h.helicsSubscriptionGetString(subid)
                assert status == 0
                print("Interrupt value '{}' from Federate 2".format(value))
            print("<<<<<<<< Granted Time = {}".format(grantedtime))
        assert grantedtime == stop_at_time, "stop_at_time = {}, grantedtime = {}".format(
            stop_at_time, grantedtime)
        if value_to_send is not None and value_to_send != '':
            print("Sending '{}' to Federate 2".format(value_to_send))
            status = h.helicsPublicationPublishString(pubid,
                                                      str(value_to_send))
            assert status == 0
            status = h.helicsEndpointSendMessageRaw(epid, "endpoint2",
                                                    str(value_to_send))
            assert status == 0
        status, value = h.helicsSubscriptionGetString(subid)
        assert status == 0
        print("Received value '{}' from Federate 2".format(value))
        while h.helicsEndpointHasMessage(epid):
            value = h.helicsEndpointGetMessage(epid)
            print("Received message '{}' at time {} from Federate 2".format(
                value.data, value.time))
        print("----------------------------------")

    destroy_value_federate(fed, broker)
Пример #2
0
def test_value_federate_runFederateTestString(vFed):
    defaultValue = "String1"
    testValue = "String2"
    pubid = h.helicsFederateRegisterGlobalTypePublication(
        vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "string", "")
    h.helicsSubscriptionSetDefaultString(subid, defaultValue)

    h.helicsFederateEnterExecutionMode(vFed)

    # TODO: Fix error with the following function
    h.helicsPublicationPublishString(pubid, testValue)

    status, value = h.helicsSubscriptionGetString(subid)
    assert value == defaultValue

    status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0)
    assert grantedtime == 0.01

    status, value = h.helicsSubscriptionGetString(subid)
    assert value == testValue
Пример #3
0
def test_value_federate_single_transfer(vFed):

    pubid = h.helicsFederateRegisterGlobalTypePublication(
        vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "string", "")

    h.helicsFederateEnterExecutionMode(vFed)

    h.helicsPublicationPublishString(pubid, "string1")

    status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0)

    assert grantedtime == 0.01

    status, s = h.helicsSubscriptionGetString(subid)

    assert status == 0
    assert s == "string1"
Пример #4
0
    def run(self,dt=300.0,ID=5,\
    scale={5:0.0000009, 7:0.000001, 9:0.00000125},monitor=False,\
    inv_nominalV={5:480.0, 7:480.0, 9:480.0},msgSize=1024):
        try:
            Res = []
            res = {}
            simTime = 0.0
            comm_end = 0
            while comm_end == 0:
                grantedTime = h.helicsFederateRequestTime(self.vf, simTime)
                status, msg = h.helicsSubscriptionGetString(
                    self.sub)  # receive from pyPflow
                simTime += dt

                if 'setpoint' in msg:
                    msg = eval(msg)

                    if ID in msg['setpoint']:
                        propVal = []
                        for entry in msg['setpoint'][ID]:
                            propVal.append(entry[0])
                            propVal.append(entry[1])

                        objName = ['solar_inv'] * 8
                        propName = [
                            'V1', 'Q1', 'V2', 'Q2', 'V3', 'Q3', 'V4', 'Q4'
                        ]
                        self.pyGldWorker.objVal(ID,
                                                objName,
                                                propName,
                                                propVal,
                                                flg='send')  # set new QV curve
                        self.pyGldWorker.objVal(ID,
                                                objName,
                                                propName,
                                                ['none'] * len(propVal),
                                                flg='recv')  # set new QV curve

                    status = h.helicsPublicationPublishString(
                        self.pub, 'Received QV curve')
                    grantedTime = h.helicsFederateRequestTime(
                        self.vf, simTime)  # sync at this point
                    simTime += dt
                else:
                    msg = eval(msg)
                    if 'comm_end' in msg:
                        if msg['comm_end'] == 1:
                            comm_end = 1
                            if len(res) > 0:
                                Res.append(res)

                    if comm_end == 0:
                        # set load if requested
                        if 'set' in msg['mpc'].keys():
                            if 'loadShape' in msg['mpc']['set'].keys():
                                self.pyGldWorker.setLoad(
                                    msg['mpc']['set']['loadShape'], ID=ID)
                                self.pyGldWorker.setSolar(
                                    msg['mpc']['set']['solarShape'], ID=ID)
                                if len(res) > 0:
                                    Res.append(res)

                        Vpu = 0
                        for entry in msg['mpc']['get']['V']:
                            if entry[0] == ID:
                                Vpu = entry[1]

                        Pd = 0
                        Qd = 0
                        if Vpu != 0:
                            Sinj, res, convergence_flg = self.pyGldWorker.run(
                                Vpu, ID=ID,
                                monitor=monitor)  # will call gridlabd server
                            if convergence_flg == 1:
                                Pd = Sinj.real * scale[ID]
                                Qd = Sinj.imag * scale[ID]

                        msg = {}
                        msg['mpc'] = {}
                        msg['mpc']['set'] = {}
                        msg['mpc']['get'] = {}
                        if Pd != 0 and Qd != 0:
                            msg['mpc']['set']['Pd'] = [[
                                ID, 1, math.ceil(Pd * 10**6) * 10**-6
                            ]]
                            msg['mpc']['set']['Qd'] = [[
                                ID, 1, math.ceil(Qd * 10**6) * 10**-6
                            ]]
                            msg['mpc']['get']['V'] = [[ID, 0, 0]]
                            msg['mpc']['set']['solar_V']=math.ceil(min([\
                            res[ID]['solar_meter']['measured_voltage_A_mag']/inv_nominalV[ID]*math.sqrt(3),\
                            res[ID]['solar_meter']['measured_voltage_B_mag']/inv_nominalV[ID]*math.sqrt(3),\
                            res[ID]['solar_meter']['measured_voltage_C_mag']/inv_nominalV[ID]*math.sqrt(3)\
                            ])*10**4)*10**-4
                            msg['mpc']['set']['solar_Q']=\
                            math.ceil(-res[ID]['solar_meter']['measured_reactive_power']/\
                            (res[ID]['solar_inv']['rated_power']*3)*10**2)*10**-2 # rated power is per phase

                        # send
                        status = h.helicsPublicationPublishString(
                            self.pub, str(msg))  # publish Sinj as fedName
                        grantedTime = h.helicsFederateRequestTime(
                            self.vf, simTime)  # sync at this point
                        simTime += dt
            if monitor == True:
                json.dump(
                    Res,
                    open(dirName + '/results/res_' + str(ID) + '.json', 'w'))
        except:
            PrintException()
Пример #5
0
    def run(self,dt=300.0,nDis=5,tol=10**-3,\
    pflowFname=dirName+'/results/pflowRes.json',adaptive=False,iterMax=10,\
    msgSize=1024):
        try:
            simTime = 0.0
            comm_end = 0
            pflowRes = []
            setPoint = {}
            sensitivity_info = {}
            sensitivity_info['inv'] = {5: 0.025, 7: 0.025, 9: 0.025}
            sensitivity_info['pcc'] = {5: 0.01, 7: 0.01, 9: 0.01}
            iteration = 0
            dispatchNo = 1

            while comm_end == 0:
                #send (set V at distribution side)
                self.msgFromPflow['mpc'].pop('set')
                self.msgFromPflow['mpc']['set'] = {}

                if iteration == 0:  #set load at iteration 0
                    self.__setDcopfData(self.msgFromPflow, dispatchNo, 'gld')
                    boundaryConditionCheck = np.zeros(shape=(len(self.ID), 2))

                if adaptive and 'flg' in setPoint and setPoint[
                        'flg'] == 1:  # change QV curve if needed
                    setPoint.pop('flg')
                    temp_setpoint = {}
                    temp_setpoint['setpoint'] = setPoint
                    temp_setpoint = str(temp_setpoint).replace(' ', '')
                    setPoint = {}

                    status = h.helicsPublicationPublishString(
                        self.pub, temp_setpoint)
                    grantedTime = h.helicsFederateRequestTime(self.vf, simTime)
                    simTime += dt
                    grantedTime = h.helicsFederateRequestTime(self.vf, simTime)

                    for ID in self.ID:  # receive from GLD
                        errFlg, temp = h.helicsSubscriptionGetString(
                            self.sub['pyGld_' + str(ID)])
                        temp = eval(temp)
                    simTime += dt
                else:
                    status = h.helicsPublicationPublishString(
                        self.pub, str(self.msgFromPflow)
                    )  # will send msg i.e. Vpcc to all
                    # distribution feeders that are subscribers of publisher called pyPflow
                    grantedTime = h.helicsFederateRequestTime(self.vf, simTime)
                    simTime += dt

                    #recv (getS from distribution side)
                    grantedTime = h.helicsFederateRequestTime(self.vf, simTime)

                    msgFromGld = {}
                    msgFromGld['mpc'] = {}
                    msgFromGld['mpc']['set'] = {}
                    msgFromGld['mpc']['get'] = {}
                    setData = msgFromGld['mpc']['set']
                    getData = msgFromGld['mpc']['get']
                    setData['Pd'] = []
                    setData['Qd'] = []
                    getData['V'] = []

                    inv_volt = {}
                    inv_Q = {}
                    for ID in self.ID:
                        errFlg, temp = h.helicsSubscriptionGetString(
                            self.sub['pyGld_' + str(ID)])
                        temp = eval(temp)

                        setData['Pd'].append(temp['mpc']['set']['Pd'][0])
                        setData['Qd'].append(temp['mpc']['set']['Qd'][0])
                        getData['V'].append(temp['mpc']['get']['V'][0])
                        inv_volt[ID] = temp['mpc']['set']['solar_V']
                        inv_Q[ID] = temp['mpc']['set']['solar_Q']
                    simTime += dt

                    # run PFLOW (setS and getV from transmission side)
                    if iteration == 0:  #set load at iteration 0
                        self.__setDcopfData(msgFromGld, dispatchNo, 'pflow')

                    self.socket.send_string(
                        json.dumps(msgFromGld))  # send instructions to pflow
                    self.msgFromPflow = eval(
                        self.socket.recv())  # receive data from pflow
                    iteration += 1

                    # check boundary condition
                    V = np.array(self.msgFromPflow['mpc']['get']['V'])

                    pcc_volt = {}
                    for ID in self.ID:
                        pcc_volt[ID] = V[V[:, 0] == ID, 1][0]

                    count = 0
                    for ID in self.ID:
                        boundaryConditionCheck[
                            count, 1] = boundaryConditionCheck[count, 0]
                        boundaryConditionCheck[count, 0] = V[V[:, 0] == ID,
                                                             1][0]
                        count += 1

                    if np.all(
                            abs(boundaryConditionCheck[:, 0] -
                                boundaryConditionCheck[:, 1]) < tol):
                        # check for QV setting
                        if adaptive:
                            setPoint = self.setQvCurve(pcc_volt, inv_volt,
                                                       inv_Q, sensitivity_info)
                        else:
                            setPoint = {}
                            setPoint['flg'] = 0

                        # implies no adaptive changes are required or max iterations have been exceeded
                        if setPoint['flg'] == 0 or iteration > iterMax:
                            six.print_("Completed Dispath Number: ",
                                       dispatchNo)
                            pflowRes.append([self.msgFromPflow,
                                             msgFromGld])  # store pflow result
                            iteration = 0  # reset iteration for the new dispatch
                            if dispatchNo == nDis:
                                comm_end = 1
                                commEndMsg = {}
                                commEndMsg['comm_end'] = 1
                                status = h.helicsPublicationPublishString(
                                    self.pub,
                                    str(commEndMsg))  # send shutdown signal
                                grantedTime = h.helicsFederateRequestTime(
                                    self.vf, simTime)
                                self.socket.send_string("COMM_END")
                                msgFromPflow = self.socket.recv()
                            else:
                                dispatchNo += 1

            # save results
            json.dump(pflowRes, open(pflowFname, 'w'))
        except:
            PrintException()