def test_value_federate_runFederateTestComplex(vFed):
    rDefaultValue = 1.0
    iDefaultValue = 1.0
    rTestValue = 2.0
    iTestValue = 2.0
    pubid = h.helicsFederateRegisterGlobalPublication(
        vFed, "pub1", h.helics_data_type_complex, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "")
    h.helicsInputSetDefaultComplex(subid, rDefaultValue, iDefaultValue)

    h.helicsFederateEnterExecutingMode(vFed)

    # publish string1 at time=0.0;
    h.helicsPublicationPublishComplex(pubid, rTestValue, iTestValue)

    value1, value2 = h.helicsInputGetComplex(subid)
    assert value1 == rDefaultValue
    assert value2 == iDefaultValue

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

    value1, value2 = h.helicsInputGetComplex(subid)
    assert value1 == rTestValue
    assert value2 == iTestValue
Example #2
0
    def update_publications(self):
        for pubName, pubInfo in self.Publications.items():
            device = pubInfo["elementObj"]
            pub = pubInfo["publicationObj"]
            if pubInfo["isKeyword"]:
                res = self.cympy.study.QueryInfoDevice(pubInfo["property"],
                                                       device.DeviceNumber,
                                                       device.DeviceType)
            else:
                res = pubInfo["elementObj"].GetValue(pubInfo["property"])

            print(pubInfo["property"], res, type(res), pubInfo["dType"],
                  pubInfo["unit"])

            if pubInfo["dType"].lower() == "complex":
                h.helicsPublicationPublishComplex(pub,
                                                  complex(res).real,
                                                  complex(res).imag)
            elif pubInfo["dType"].lower() == 'real':
                h.helicsPublicationPublishDouble(pub, float(res))
            elif pubInfo["dType"].lower() == 'text':
                h.helicsPublicationPublishString(pub, str(res))
            elif pubInfo["dType"].lower() == "number":
                h.helicsPublicationPublishInteger(pub, int(res))

        return
Example #3
0
def test_value_federate_runFederateTestComplex(vFed):
    rDefaultValue = 1.0
    iDefaultValue = 1.0
    rTestValue = 2.0
    iTestValue = 2.0
    pubid = h.helicsFederateRegisterGlobalTypePublication(
        vFed, "pub1", h.HELICS_DATA_TYPE_COMPLEX, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "double", "")
    h.helicsSubscriptionSetDefaultComplex(subid, rDefaultValue, iDefaultValue)

    h.helicsFederateEnterExecutionMode(vFed)

    # publish string1 at time=0.0;
    h.helicsPublicationPublishComplex(pubid, rTestValue, iTestValue)

    status, value1, value2 = h.helicsSubscriptionGetComplex(subid)
    assert value1 == rDefaultValue
    assert value2 == iDefaultValue

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

    status, value1, value2 = h.helicsSubscriptionGetComplex(subid)
    assert value1 == rTestValue
    assert value2 == iTestValue
Example #4
0
def test_valuefederate_test_complex():
    broker = createBroker()
    vFed, fedinfo = createValueFederate()

    rDefaultValue = 1.0
    iDefaultValue = 1.0
    rTestValue = 2.0
    iTestValue = 2.0
    pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.HELICS_DATA_TYPE_COMPLEX, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "")
    h.helicsInputSetDefaultComplex(subid, complex(rDefaultValue, iDefaultValue))

    h.helicsFederateEnterExecutingMode(vFed)

    # publish string1 at time=0.0
    h.helicsPublicationPublishComplex(pubid, complex(rTestValue, iTestValue))

    assert (rDefaultValue, iDefaultValue) == h.helicsInputGetComplex(subid)

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

    assert (rTestValue, iTestValue) == h.helicsInputGetComplex(subid)

    destroyFederate(vFed, fedinfo)
    destroyBroker(broker)
Example #5
0
 def _publish_based_on_type(self, output):
     """
     Publish message based on type
     :param output:
     :return:
     """
     try:
         if output['type'] == 'integer':
             h.helicsPublicationPublishInteger(output['pub_id'],
                                               output['value'])
         elif output['type'] == 'double':
             h.helicsPublicationPublishDouble(output['pub_id'],
                                              output['value'])
         elif output['type'] == 'string':
             h.helicsPublicationPublishString(output['pub_id'],
                                              output['value'])
         elif output['type'] == 'complex':
             h.helicsPublicationPublishComplex(output['pub_id'],
                                               output['value'])
         elif output['type'] == 'vector':
             h.helicsPublicationPublishVector(output['pub_id'],
                                              output['value'])
         elif output['type'] == 'boolean':
             h.helicsPublicationPublishBoolean(output['pub_id'],
                                               output['value'])
         else:
             _log.error("Unknown datatype: {}".format(output['type']))
     except h._helics.HelicsException as e:
         _log.exception("Error sending publication to  HELICS {}".format(e))
Example #6
0
def main():
    # broker = create_broker() # Broker already created from 1st terminal
    fed = create_federate()

    # Register publication
    pubid = h.helicsFederateRegisterGlobalPublication(
        fed, "TransmissionSim/B2Voltage", h.helics_data_type_complex, "")

    # Register subscription
    subid = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B2_G_1/totalLoad", "")

    # Register endpoint
    epid = h.helicsFederateRegisterEndpoint(fed, "ep1", None)

    # h.helicsSubscriptionSetDefaultComplex(subid, 0, 0)

    # Enter execution mode
    h.helicsFederateEnterExecutingMode(fed)

    hours = 1
    seconds = int(60 * 60 * hours)
    grantedtime = -1
    random.seed(0)
    for t in range(0, seconds, 60 * 5):
        c = complex(132790.562, 0) * (1 + (random.random() - 0.5) / 2)
        logger.info("Voltage value = {} kV".format(abs(c) / 1000))
        status = h.helicsPublicationPublishComplex(pubid, c.real, c.imag)
        # status = h.helicsEndpointSendEventRaw(epid, "fixed_price", 10, t)
        while grantedtime < t:
            grantedtime = h.helicsFederateRequestTime(fed, t)
        time.sleep(1)
        rValue, iValue = h.helicsInputGetComplex(subid)
        logger.info("Python Federate grantedtime = {}".format(grantedtime))
        logger.info("Load value = {} MVA".format(
            complex(rValue, iValue) / 1000))

    t = 60 * 60 * 24
    while grantedtime < t:
        grantedtime = h.helicsFederateRequestTime(fed, t)
    logger.info("Destroying federate")
    destroy_federate(fed)
Example #7
0
def main():

    # broker = create_broker()
    fed = create_federate()

    pubid = h.helicsFederateRegisterGlobalTypePublication(
        fed, "TransmissionSim/B2Voltage", h.HELICS_DATA_TYPE_COMPLEX, "")
    subid = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B2_G_1/totalLoad", "complex", "")
    epid = h.helicsFederateRegisterEndpoint(fed, "ep1", None)

    h.helicsSubscriptionSetDefaultComplex(subid, 0, 0)

    h.helicsFederateEnterExecutionMode(fed)

    hours = 1
    seconds = int(60 * 60 * hours)
    grantedtime = -1
    random.seed(0)
    for t in range(0, seconds, 60 * 5):
        c = complex(132790.562, 0) * (1 + (random.random() - 0.5) / 2)
        logger.info("Voltage value = {} kV".format(abs(c) / 1000))
        status = h.helicsPublicationPublishComplex(pubid, c.real, c.imag)
        # status = h.helicsEndpointSendEventRaw(epid, "fixed_price", 10, t)
        while grantedtime < t:
            status, grantedtime = h.helicsFederateRequestTime(fed, t)
        time.sleep(1)
        status, rValue, iValue = h.helicsSubscriptionGetComplex(subid)
        logger.info("Python Federate grantedtime = {}".format(grantedtime))
        logger.info("Load value = {} MW".format(
            complex(rValue, iValue) / 1000))

    t = 60 * 60 * 24
    while grantedtime < t:
        status, grantedtime = h.helicsFederateRequestTime(fed, t)
    logger.info("Destroying federate")
    destroy_federate(fed)
    x = 0
    k = 0
    voltage_cosim_bus = (ppc['bus'][cosim_bus, 7] *
                         ppc['bus'][cosim_bus, 9]) * 1.043

    #########################################   Starting Co-simulation  ####################################################

    for t in range(0, total_inteval, pf_interval):

        ############################   Publishing Voltage to GridLAB-D #######################################################

        voltage_gld = complex(voltage_cosim_bus * 1000)
        logger.info("Voltage value = {} kV".format(abs(voltage_gld) / 1000))
        for i in range(0, pubkeys_count):
            pub = pubid["m{}".format(i)]
            status = h.helicsPublicationPublishComplex(pub, voltage_gld.real,
                                                       voltage_gld.imag)
        # status = h.helicsEndpointSendEventRaw(epid, "fixed_price", 10, t)

        while grantedtime < t:
            grantedtime = h.helicsFederateRequestTime(fed, t)
        time.sleep(0.1)

        #############################   Subscribing to Feeder Load from to GridLAB-D ##############################################

        for i in range(0, subkeys_count):
            sub = subid["m{}".format(i)]
            rload, iload = h.helicsInputGetComplex(sub)
        logger.info("Python Federate grantedtime = {}".format(grantedtime))
        logger.info("Load value = {} kW".format(complex(rload, iload) / 1000))
        #print(voltage_plot,real_demand)
Example #9
0
def test_bad_input_type_publication_2_tests():
    broker = createBroker(1)
    vFed1, fedinfo = createValueFederate(1, "test")

    pubid = h.helicsFederateRegisterGlobalTypePublication(
        vFed1, "pub1", "string", "")
    with pt.raises(h.HelicsException):
        # @test_throws h.HELICSErrorRegistrationFailure
        pubid2 = h.helicsFederateRegisterGlobalTypePublication(
            vFed1, "pub1", "string", "")

    with pt.raises(h.HelicsException):
        # @test_throws h.HELICSErrorInvalidArgument
        h.helicsFederateRegisterFromPublicationJSON(vFed1, "unknownfile.json")

    with pt.raises(h.HelicsException):
        # @test_throws h.HELICSErrorExternalArgument
        h.helicsFederateRegisterInterfaces(vFed1, "unknownfile.json")

    subid = h.helicsFederateRegisterTypeInput(vFed1, "inp1", "string", "")
    # @test_throws h.HELICSErrorRegistrationFailure
    with pt.raises(h.HelicsException):
        subid2 = h.helicsFederateRegisterTypeInput(vFed1, "inp1", "string", "")

    h.helicsInputAddTarget(subid, "pub1")

    h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0)

    h.helicsFederateEnterExecutingModeIterativeAsync(
        vFed1, h.HELICS_ITERATION_REQUEST_NO_ITERATION)
    res = h.helicsFederateEnterExecutingModeIterativeComplete(vFed1)
    assert res == h.HELICS_ITERATION_RESULT_NEXT_STEP

    h.helicsPublicationPublishTime(pubid, 27.0)

    # @test_throws h.HELICSErrorInvalidArgument
    with pt.raises(h.HelicsException):
        h.helicsFederatePublishJSON(vFed1, "unknownfile.json")

    h.helicsFederateRequestNextStep(vFed1)
    string = h.helicsInputGetString(subid)
    assert string[0] == "2"
    assert string[1] == "7"
    h.helicsFederateClearUpdates(vFed1)

    h.helicsFederateFinalize(vFed1)

    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishRaw(pubid, string.encode())
    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishString(pubid, string)
    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishInteger(pubid, 5)
    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishBoolean(pubid, True)
    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishDouble(pubid, 39.2)
    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishTime(pubid, 19.2)
    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishChar(pubid, "a")

    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishComplex(pubid, 2.5 + -9.8j)

    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishVector(pubid, [1.3, 2.9])

    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsPublicationPublishNamedPoint(pubid, "hello world", 2.0)

    destroyFederate(vFed1, fedinfo)
    destroyBroker(broker)
Example #10
0
def test_misc_api():
    fedInfo1 = h.helicsCreateFederateInfo()
    h.helicsFederateInfoSetCoreInitString(fedInfo1, "-f 1")
    h.helicsFederateInfoSetCoreName(fedInfo1, "core3")
    h.helicsFederateInfoSetCoreType(fedInfo1, 3)
    h.helicsFederateInfoSetCoreTypeFromString(fedInfo1, "zmq")
    h.helicsFederateInfoSetFlagOption(fedInfo1, 1, True)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_INPUT_DELAY,
                                        1.0)
    h.helicsFederateInfoSetIntegerProperty(fedInfo1,
                                           h.HELICS_PROPERTY_INT_LOG_LEVEL, 1)
    h.helicsFederateInfoSetIntegerProperty(
        fedInfo1, h.HELICS_PROPERTY_INT_MAX_ITERATIONS, 100)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_OUTPUT_DELAY,
                                        1.0)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_PERIOD, 1.0)
    h.helicsFederateInfoSetTimeProperty(fedInfo1, h.HELICS_PROPERTY_TIME_DELTA,
                                        1.0)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_OFFSET, 0.1)
    h.helicsFederateInfoFree(fedInfo1)

    broker3 = h.helicsCreateBroker("zmq", "broker3",
                                   "--federates 1 --loglevel 1")
    fedInfo2 = h.helicsCreateFederateInfo()
    coreInitString = "--federates 1"
    h.helicsFederateInfoSetCoreInitString(fedInfo2, coreInitString)
    h.helicsFederateInfoSetCoreTypeFromString(fedInfo2, "zmq")
    h.helicsFederateInfoSetIntegerProperty(fedInfo2,
                                           h.HELICS_PROPERTY_INT_LOG_LEVEL, 1)
    h.helicsFederateInfoSetTimeProperty(fedInfo2, h.HELICS_PROPERTY_TIME_DELTA,
                                        1.0)
    fed1 = h.helicsCreateCombinationFederate("fed1", fedInfo2)
    fed2 = h.helicsFederateClone(fed1)
    _ = h.helicsGetFederateByName("fed1")
    h.helicsFederateSetFlagOption(fed2, 1, False)

    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_INPUT_DELAY,
                                    1.0)
    h.helicsFederateSetIntegerProperty(fed1, h.HELICS_PROPERTY_INT_LOG_LEVEL,
                                       1)
    h.helicsFederateSetIntegerProperty(fed2,
                                       h.HELICS_PROPERTY_INT_MAX_ITERATIONS,
                                       100)
    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_OUTPUT_DELAY,
                                    1.0)
    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_PERIOD, 0.0)
    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_DELTA, 1.0)

    _ = h.helicsFederateRegisterCloningFilter(fed1, "fed1/Ep1")
    fed1DestinationFilter = h.helicsFederateRegisterFilter(
        fed1, h.HELICS_FILTER_TYPE_DELAY, "fed1DestinationFilter")
    h.helicsFilterAddDestinationTarget(fed1DestinationFilter, "Ep2")

    ep1 = h.helicsFederateRegisterEndpoint(fed1, "Ep1", "string")
    ep2 = h.helicsFederateRegisterGlobalEndpoint(fed1, "Ep2", "string")
    pub1 = h.helicsFederateRegisterGlobalPublication(fed1, "pub1",
                                                     h.HELICS_DATA_TYPE_DOUBLE,
                                                     "")
    pub2 = h.helicsFederateRegisterGlobalTypePublication(
        fed1, "pub2", "complex", "")

    sub1 = h.helicsFederateRegisterSubscription(fed1, "pub1")
    sub2 = h.helicsFederateRegisterSubscription(fed1, "pub2")
    h.helicsInputAddTarget(sub2, "Ep2")
    pub3 = h.helicsFederateRegisterPublication(fed1, "pub3",
                                               h.HELICS_DATA_TYPE_STRING, "")

    pub1KeyString = h.helicsPublicationGetKey(pub1)
    pub1TypeString = h.helicsPublicationGetType(pub1)
    pub1UnitsString = h.helicsPublicationGetUnits(pub1)
    sub1KeyString = h.helicsSubscriptionGetKey(sub1)
    sub1UnitsString = h.helicsInputGetUnits(sub1)
    assert "pub1" == pub1KeyString
    assert "double" == pub1TypeString
    assert "" == pub1UnitsString
    assert "pub1" == sub1KeyString
    assert "" == sub1UnitsString

    fed1SourceFilter = h.helicsFederateRegisterFilter(
        fed1, h.HELICS_FILTER_TYPE_DELAY, "fed1SourceFilter")
    h.helicsFilterAddSourceTarget(fed1SourceFilter, "Ep2")
    h.helicsFilterAddDestinationTarget(fed1SourceFilter, "fed1/Ep1")
    h.helicsFilterRemoveTarget(fed1SourceFilter, "fed1/Ep1")
    h.helicsFilterAddSourceTarget(fed1SourceFilter, "Ep2")
    h.helicsFilterRemoveTarget(fed1SourceFilter, "Ep2")

    fed1SourceFilterNameString = h.helicsFilterGetName(fed1SourceFilter)
    assert fed1SourceFilterNameString == "fed1/fed1SourceFilter"

    sub3 = h.helicsFederateRegisterSubscription(fed1, "fed1/pub3", "")
    pub4 = h.helicsFederateRegisterTypePublication(fed1, "pub4", "int", "")

    sub4 = h.helicsFederateRegisterSubscription(fed1, "fed1/pub4", "")
    pub5 = h.helicsFederateRegisterGlobalTypePublication(
        fed1, "pub5", "boolean", "")

    sub5 = h.helicsFederateRegisterSubscription(fed1, "pub5", "")
    pub6 = h.helicsFederateRegisterGlobalPublication(fed1, "pub6",
                                                     h.HELICS_DATA_TYPE_VECTOR,
                                                     "")
    sub6 = h.helicsFederateRegisterSubscription(fed1, "pub6", "")
    pub7 = h.helicsFederateRegisterGlobalPublication(
        fed1, "pub7", h.HELICS_DATA_TYPE_NAMED_POINT, "")
    sub7 = h.helicsFederateRegisterSubscription(fed1, "pub7", "")

    assert """helics.HelicsPublication(name = "pub1", type = "double", units = "", info = "")""" in repr(
        pub1)
    assert """helics.HelicsPublication(name = "pub2", type = "complex", units = "", info = "")""" in repr(
        pub2)
    assert """helics.HelicsPublication(name = "fed1/pub3", type = "string", units = "", info = "")""" in repr(
        pub3)
    assert """helics.HelicsPublication(name = "fed1/pub4", type = "int", units = "", info = "")""" in repr(
        pub4)
    assert """helics.HelicsPublication(name = "pub5", type = "boolean", units = "", info = "")""" in repr(
        pub5)
    assert """helics.HelicsPublication(name = "pub6", type = "double_vector", units = "", info = "")""" in repr(
        pub6)
    assert """helics.HelicsPublication(name = "pub7", type = "named_point", units = "", info = "")""" in repr(
        pub7)
    assert (
        """helics.HelicsInput(name = "_input_18", units = "", injection_units = "", publication_type = "", type = "", target = "pub7", info = "")"""
        in repr(sub7))

    h.helicsInputSetDefaultBoolean(sub5, False)
    h.helicsInputSetDefaultComplex(sub2, -9.9 + 2.5j)
    h.helicsInputSetDefaultDouble(sub1, 3.4)
    h.helicsInputSetDefaultInteger(sub4, 6)
    h.helicsInputSetDefaultNamedPoint(sub7, "hollow", 20.0)
    h.helicsInputSetDefaultString(sub3, "default")
    sub6Default = [3.4, 90.9, 4.5]
    h.helicsInputSetDefaultVector(sub6, sub6Default)
    h.helicsEndpointSubscribe(ep2, "fed1/pub3")
    h.helicsFederateEnterInitializingModeAsync(fed1)
    rs = h.helicsFederateIsAsyncOperationCompleted(fed1)
    if rs == 0:
        time.sleep(0.500)
        rs = h.helicsFederateIsAsyncOperationCompleted(fed1)
        if rs == 0:
            time.sleep(0.500)
            rs = h.helicsFederateIsAsyncOperationCompleted(fed1)
            if rs == 0:
                assert True is False
    h.helicsFederateEnterInitializingModeComplete(fed1)
    h.helicsFederateEnterExecutingModeAsync(fed1)
    h.helicsFederateEnterExecutingModeComplete(fed1)

    assert (
        """helics.HelicsInput(name = "_input_18", units = "", injection_units = "", publication_type = "named_point", type = "", target = "pub7", info = "")"""
        in repr(sub7))

    mesg1 = h.helicsFederateCreateMessage(fed1)
    h.helicsMessageSetString(mesg1, "Hello")
    h.helicsMessageSetSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetOriginalSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetDestination(mesg1, "Ep2")
    h.helicsMessageSetOriginalDestination(mesg1, "Ep2")

    h.helicsEndpointSendMessage(ep1, mesg1)
    mesg1 = h.helicsFederateCreateMessage(fed1)
    h.helicsMessageSetString(mesg1, "There")
    h.helicsMessageSetSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetOriginalSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetDestination(mesg1, "Ep2")
    h.helicsMessageSetOriginalDestination(mesg1, "Ep2")
    h.helicsEndpointSendMessage(ep1, mesg1)
    h.helicsEndpointSetDefaultDestination(ep2, "fed1/Ep1")

    ep1NameString = h.helicsEndpointGetName(ep1)
    ep1TypeString = h.helicsEndpointGetType(ep1)

    assert ep1NameString == "fed1/Ep1"
    assert ep1TypeString == "string"

    _ = h.helicsFederateGetCoreObject(fed1)

    fed1Time = h.helicsFederateGetCurrentTime(fed1)
    assert fed1Time == 0.0
    fed1EndpointCount = h.helicsFederateGetEndpointCount(fed1)
    assert fed1EndpointCount == 2

    fed1NameString = h.helicsFederateGetName(fed1)
    assert fed1NameString == "fed1"

    fed1State = h.helicsFederateGetState(fed1)
    assert fed1State == 2
    fed1PubCount = h.helicsFederateGetPublicationCount(fed1)
    assert fed1PubCount == 7
    fed1SubCount = h.helicsFederateGetInputCount(fed1)
    assert fed1SubCount == 7

    h.helicsPublicationPublishBoolean(pub5, True)
    h.helicsPublicationPublishComplex(pub2, 5.6 + -0.67j)
    h.helicsPublicationPublishDouble(pub1, 457.234)
    h.helicsPublicationPublishInteger(pub4, 1)
    h.helicsPublicationPublishNamedPoint(pub7, "Blah Blah", 20.0)
    h.helicsPublicationPublishString(pub3, "Mayhem")
    pub6Vector = [4.5, 56.5]
    h.helicsPublicationPublishVector(pub6, pub6Vector)
    time.sleep(0.500)
    h.helicsFederateRequestTimeAsync(fed1, 1.0)

    returnTime = h.helicsFederateRequestTimeComplete(fed1)
    assert returnTime == 1.0
    ep2MsgCount = h.helicsEndpointPendingMessages(ep2)
    assert ep2MsgCount == 2
    ep2HasMsg = h.helicsEndpointHasMessage(ep2)
    assert ep2HasMsg == 1

    msg2 = h.helicsEndpointGetMessage(ep2)
    assert h.helicsMessageGetTime(msg2) == 1.0
    assert h.helicsMessageGetString(msg2) == "Hello"
    assert h.helicsMessageGetOriginalSource(msg2) == "fed1/Ep1"
    assert h.helicsMessageGetSource(msg2) == "fed1/Ep1"
    assert h.helicsMessageGetDestination(msg2) == "Ep2"
    assert h.helicsMessageGetOriginalDestination(msg2) == "Ep2"

    fed1MsgCount = h.helicsFederatePendingMessages(fed1)
    assert fed1MsgCount == 1

    assert h.helicsFederateHasMessage(fed1) == 1

    msg3 = h.helicsFederateGetMessage(fed1)
    assert h.helicsMessageGetTime(msg3) == 1.0
    assert h.helicsMessageGetString(msg3) == "There"
    assert h.helicsMessageGetOriginalSource(msg3) == "fed1/Ep1"
    assert h.helicsMessageGetSource(msg3) == "fed1/Ep1"
    assert h.helicsMessageGetDestination(msg3) == "Ep2"
    assert h.helicsMessageGetOriginalDestination(msg3) == "Ep2"

    sub1Updated = h.helicsInputIsUpdated(sub1)
    # TODO: figure out why this test is broken
    assert sub1Updated is False

    # TODO: figure out why this test is broken
    assert h.helicsInputLastUpdateTime(sub2) == 0.0

    # assert h.helicsInputGetComplex(sub2) == 5.6 - 0.67j

    # assert h.helicsInputGetDouble(sub1) == 457.234
    # assert h.helicsInputGetInteger(sub4) == 1
    sub7PointString, sub7DoubleValue = h.helicsInputGetNamedPoint(sub7)
    # assert sub7PointString == "Blah Blah"
    assert sub7DoubleValue == 20.0
    # assert h.helicsInputGetBoolean(sub5) == True
    # assert h.helicsInputGetString(sub3) == "Mayhem"

    sub3ValueSize = h.helicsInputGetRawValueSize(sub3)
    # assert sub3ValueSize == 6

    # assert h.helicsInputGetVector(sub6) == [4.5, 56.5]

    h.helicsFederateFinalize(fed1)
    h.helicsFederateFinalize(fed2)
    h.helicsFederateFree(fed1)
    h.helicsFederateFinalize(fed2)
    h.helicsFederateFree(fed2)
    h.helicsFederateInfoFree(fedInfo2)
    h.helicsBrokerDisconnect(broker3)

    h.helicsBrokerFree(broker3)

    h.helicsCleanupLibrary()
    h.helicsCloseLibrary()
Example #11
0
	
	#get the specified bus voltage
	ibusno = 225 #specify the bus to communicate with gridlabd is bus 225
	print("\nFinding bus number 225!")
	targetbus = pslf.queries.find_bus_by_number(ibusno)
	print(targetbus)
	busvolt_mag = targetbus._volt.vm #get bus voltage magnitude, unit per unit value, need to multiply by 132790.562 when passing to gridlabd
	busvolt_ang = targetbus._volt.va #get bus voltage angle, unit rads.
	
	busvolt_real = busvolt_mag*132790.562*math.cos(busvolt_ang*180/math.pi) #covert the voltage in complex format - real part
	busvolt_imag = busvolt_mag*132790.562*math.sin(busvolt_ang*180/math.pi) #covert the voltage in complex format - imag part
	print('bus 225 voltage magnitude: ' + str(busvolt_mag) + ' V , angle: ' + str(busvolt_ang) + ' degree')
	
	#The busvolt is the value that need to be published to the gridlabd
	
	status = h.helicsPublicationPublishComplex(pubid, busvolt_real, busvolt_imag)
	
	
	while grantedtime < itimestep:
		status, grantedtime = h.helicsFederateRequestTime (fed, itimestep)
	status, grantedtime = h.helicsFederateRequestTime (fed, itimestep)
	print ('grantedtime from HELICS is: ' + str(grantedtime))  #renke add.
	time.sleep(1)
	#The following code subscribes total load values from gridlabd, and write this load value to the load at bus 225
	status, rValue, iValue = h.helicsSubscriptionGetComplex(subid)
	
	#logger.info("Python Federate grantedtime = {}".format(grantedtime))
	#logger.info("Load value = {} MW".format(complex(rValue, iValue)/1000))
    #modify the load at bus8:
	loadscalor = 8000
	loadp = rValue/loadscalor  # I am not sure about what the scale should be, if the rValue are at the level of 1.23E+06 to 8E+06
Example #12
0
def federate_example(config_path):
    # Registering  federate from json

    try:
        fed = h.helicsCreateCombinationFederateFromConfig(config_path)
    except h._helics.HelicsException as exc:
        print("Exception occured".format(exc))
        exit(-1)
    federate_name = h.helicsFederateGetName(fed)
    print(federate_name)
    endpoint_count = h.helicsFederateGetEndpointCount(fed)
    subkeys_count = h.helicsFederateGetInputCount(fed)
    pubkeys_count = h.helicsFederateGetPublicationCount(fed)

    # Reference to Publications and Subscription form index
    endid = {}
    subid = {}
    pubid = {}
    for i in range(0,endpoint_count):
        endid["m{}".format(i)] = h.helicsFederateGetEndpointByIndex(fed, i)
        end_name = h.helicsEndpointGetName(endid["m{}".format(i)])
        logger.info( 'Registered Endpoint ---> {}'.format(end_name))

    for i in range(0, subkeys_count):
        idx = h.helicsFederateGetInputByIndex(fed, i)
        subid["m{}".format(i)] = idx
        status = h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0)
        sub_key = h.helicsSubscriptionGetKey(idx)
        logger.info( 'Registered Subscription ---> {}'.format(sub_key))

    for i in range(0, pubkeys_count):
        idx = h.helicsFederateGetPublicationByIndex(fed, i)
        pubid["m{}".format(i)] = idx
        pub_key = h.helicsPublicationGetKey(idx)
        logger.info( 'Registered Publications ---> {}'.format(pub_key))

    print('###############################################################################################')
    print('########################   Entering Execution Mode  ##########################################')
    # Entering Execution Mode
    h.helicsFederateEnterExecutingMode(fed)
    print('###############################################################################################')

    hours = 0.1
    total_inteval = int(60 * 60 * hours)
    grantedtime = -1
    update_interval = 1 # 5*60
    k = 0
    data ={}
    time.sleep(5)
    time_sim = []
    real = 0
    for t in range(0, total_inteval, update_interval):
        while grantedtime < t:
            grantedtime = h.helicsFederateRequestTime (fed, t)
        time.sleep(0.1)
        print('########################   Time interval {}  ##########################################'.format(t))
        print('########################   Publishing to topics  ######################################')
        real = real + 1
        for i in range(0, pubkeys_count):
            idx = pubid["m{}".format(i)]
            h.helicsPublicationPublishComplex(idx, real*i, 78)

        print( '########################   Get input from subscribed topics  #########################')
        for i in range(0, subkeys_count):
            idx = subid["m{}".format(i)]
            value = h.helicsInputGetDouble(idx)
            key = h.helicsSubscriptionGetKey(idx)
            print("Value for key: {} is {}".format(key, value))

        print('########################   Get from Endpoint  #########################################')
        idx = endid["m{}".format(0)]
        while h.helicsEndpointHasMessage(idx):            
            msg = h.helicsEndpointGetMessage(idx)
            end_name = h.helicsEndpointGetName(idx)
            print("Value from endpoint name: {} is {}".format(end_name, msg.data))

        print('########################   Send to VOLTTRON Endpoint  #################################')
        for i in range(0, endpoint_count):
            idx = endid["m{}".format(i)]
            value = i + random.randint(1, 101) + 89.7
            end_name = h.helicsEndpointGetName(idx)
            print("Sending Value:{0} for endpoint: {1}".format(value, end_name))
            h.helicsEndpointSendEventRaw(idx, '', str(value), t)
            end_name = h.helicsEndpointGetName(idx)

    logger.info("Destroying federate")
    destroy_federate(fed)
Example #13
0
def main():

    fed = create_federate()

    pubid1 = h.helicsFederateRegisterGlobalTypePublication(
        fed, "GenOutput/Alta", h.HELICS_DATA_TYPE_COMPLEX, "")
    pubid2 = h.helicsFederateRegisterGlobalTypePublication(
        fed, "GenOutput/Brighton", h.HELICS_DATA_TYPE_COMPLEX, "")
    pubid3 = h.helicsFederateRegisterGlobalTypePublication(
        fed, "GenOutput/ParkCity", h.HELICS_DATA_TYPE_COMPLEX, "")
    pubid4 = h.helicsFederateRegisterGlobalTypePublication(
        fed, "GenOutput/Solitude", h.HELICS_DATA_TYPE_COMPLEX, "")
    pubid5 = h.helicsFederateRegisterGlobalTypePublication(
        fed, "GenOutput/Sundance", h.HELICS_DATA_TYPE_COMPLEX, "")

    subid1 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B4_G_1/totalLoad", "complex", "")
    subid2 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B4_R_1_2/totalLoad", "complex", "")
    subid3 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B4_R_1_1/totalLoad", "complex", "")
    subid4 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B3_R_3_4/totalLoad", "complex", "")
    subid5 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B3_R_3_3/totalLoad", "complex", "")
    subid6 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B3_R_3_2/totalLoad", "complex", "")
    subid7 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B3_R_3_1/totalLoad", "complex", "")
    subid8 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B2_G_1/totalLoad", "complex", "")
    subid9 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B2_R_2_3/totalLoad", "complex", "")
    subid10 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B2_R_2_2/totalLoad", "complex", "")
    subid11 = h.helicsFederateRegisterSubscription(
        fed, "DistributionSim_B2_R_2_1/totalLoad", "complex", "")

    subid12 = h.helicsFederateRegisterSubscription(
        fed, "MarketSim/AGCGenDispatch/Alta", "double", "")
    subid13 = h.helicsFederateRegisterSubscription(
        fed, "MarketSim/AGCGenDispatch/Brighton", "double", "")
    subid14 = h.helicsFederateRegisterSubscription(
        fed, "MarketSim/AGCGenDispatch/ParkCity", "double", "")
    subid15 = h.helicsFederateRegisterSubscription(
        fed, "MarketSim/AGCGenDispatch/Solitude", "double", "")
    subid16 = h.helicsFederateRegisterSubscription(
        fed, "MarketSim/AGCGenDispatch/Sundance", "double", "")

    h.helicsFederateEnterExecutionMode(fed)

    hours = 1
    seconds = int(60 * 60 * hours)
    grantedtime = -1
    random.seed(0)
    for t in range(0, seconds, 60 * 5):
        status, value = h.helicsSubscriptionGetDouble(subid12)
        c = complex(value, 0)
        status = h.helicsPublicationPublishComplex(pubid1, c.real, c.imag)
        status, value = h.helicsSubscriptionGetDouble(subid13)
        c = complex(value, 0)
        status = h.helicsPublicationPublishComplex(pubid2, c.real, c.imag)
        status, value = h.helicsSubscriptionGetDouble(subid14)
        c = complex(value, 0)
        status = h.helicsPublicationPublishComplex(pubid3, c.real, c.imag)
        status, value = h.helicsSubscriptionGetDouble(subid15)
        c = complex(value, 0)
        status = h.helicsPublicationPublishComplex(pubid4, c.real, c.imag)
        status, value = h.helicsSubscriptionGetDouble(subid16)
        c = complex(value, 0)
        status = h.helicsPublicationPublishComplex(pubid5, c.real, c.imag)
        # status = h.helicsEndpointSendEventRaw(epid, "fixed_price", 10, t)
        while grantedtime < t:
            status, grantedtime = h.helicsFederateRequestTime(fed, t)
        time.sleep(1)
        logger.info("Python Federate grantedtime = {}".format(grantedtime))

    t = 60 * 60 * 24
    while grantedtime < t:
        status, grantedtime = h.helicsFederateRequestTime(fed, t)
    logger.info("Destroying federate")
    destroy_federate(fed)