Example #1
0
    def _main_loop(self, vFed):
        """The main loop for running the HELICS functions.

        Args:
            vFed (helics federate object) - The value federate.

        Returns:
            (null)
        """
        cnt = 0
        txstring = "{:<100000}{:<100}".format(self.index_, "1")
        tbuffer = chr(256)
        itr = 5000
        self.vFed = vFed
        logging.info("echo leaf - starting the helics functions")
        while cnt <= itr + 1:
            h.helicsFederateRequestTimeAsync(self.vFed, 1.0)
            while h.helicsFederateIsAsyncOperationCompleted(self.vFed) == 0:
                pass
            h.helicsFederateRequestTimeComplete(self.vFed)
            if cnt <= itr:
                h.helicsPublicationPublishString(self.pub, txstring)
            if h.helicsInputIsUpdated(self.sub):
                actLen = 0
                h.helicsInputGetString(self.sub, tbuffer, 256, actLen)
                if str(tbuffer) != txstring:
                    logging.error("incorrect string\n")
                    break
            cnt += 1
        h.helicsFederateFinalizeAsync(self.vFed)
        while h.helicsFederateIsAsyncOperationCompleted(self.vFed) == 0:
            pass
        h.helicsFederateFinalizeComplete(self.vFed)
        logging.info("echo leaf - the helics functions have been completed")
Example #2
0
    def _main_loop(self, vFed):
        """The main loop for running the HELICS functions.

        Args:
            vFed (helics federate object) - The value federate.

        Returns:
            (null)
        """
        self.vFed = vFed
        buffer = chr(256)
        cTime = h.helics_time_zero
        logging.info("echo hub - starting the helics functions")
        while cTime <= self.finalTime:
            i = 0
            for c in range(0, self.cnt_):
                if h.helicsInputIsUpdated(self.subs[i]):
                    actLen = 0
                    h.helicsInputGetString(self.subs[i], buffer, 256, actLen)
                    h.helicsPublicationPublishRaw(self.pub[i], buffer, actLen)
            h.helicsFederateRequestTimeAsync(self.vFed, self.finalTime + 0.05)
            while h.helicsFederateIsAsyncOperationCompleted(self.vFed) == 0:
                pass
            cTime = h.helicsFederateRequestTimeComplete(self.vFed)
        h.helicsFederateFinalizeAsync(self.vFed)
        while h.helicsFederateIsAsyncOperationCompleted(self.vFed) == 0:
            pass
        h.helicsFederateFinalizeComplete(self.vFed)
        logging.info("echo hub - the helics functions have been completed")
Example #3
0
def test_valuefederate_test_string():
    broker = createBroker()
    vFed, fedinfo = createValueFederate()

    defaultValue = "String1"
    testValue = "String2"
    pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "")
    h.helicsInputSetDefaultString(subid, defaultValue)

    h.helicsFederateEnterExecutingMode(vFed)

    h.helicsPublicationPublishString(pubid, testValue)

    value = h.helicsInputGetString(subid)
    assert value == defaultValue

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

    value = h.helicsInputGetString(subid)
    assert value == testValue

    destroyFederate(vFed, fedinfo)
    destroyBroker(broker)
Example #4
0
def test_valuefederate_test_single_transfer():
    broker = createBroker()
    vFed, fedinfo = createValueFederate()

    s = "n2"

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

    h.helicsFederateEnterExecutingMode(vFed)

    h.helicsPublicationPublishString(pubid, "string1")

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

    s = h.helicsInputGetString(subid)

    assert s == "string1"

    t = h.helicsInputLastUpdateTime(subid)
    assert t == 0.01

    h.helicsPublicationPublishString(pubid, "string2")

    destroyFederate(vFed, fedinfo)
    destroyBroker(broker)
Example #5
0
 def _get_input_based_on_type(self, in_put):
     """
     Get input based on type
     :param in_put:
     :return:
     """
     val = None
     sub_id = in_put['sub_id']
     try:
         if in_put['type'] == 'integer':
             val = h.helicsInputGetInteger(sub_id)
         elif in_put['type'] == 'double':
             val = h.helicsInputGetDouble(sub_id)
         elif in_put['type'] == 'string':
             val = h.helicsInputGetString(sub_id)
         elif in_put['type'] == 'complex':
             real, imag = h.helicsInputGetComplex(sub_id)
             val = [real, imag]
         elif in_put['type'] == 'vector':
             val = h.helicsInputGetVector(sub_id)
         elif in_put['type'] == 'boolean':
             val = h.helicsInputGetBoolean(sub_id)
         else:
             _log.error("Unknown datatype: {}".format(in_put['type']))
     except h._helics.HelicsException as e:
         _log.exception("Error getting input from  HELICS {}".format(e))
     return val
Example #6
0
def test_value_federate_runFederateTestString(vFed):
    defaultValue = "String1"
    testValue = "String2"
    pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.helics_data_type_string, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "")
    h.helicsInputSetDefaultString(subid, defaultValue)

    h.helicsFederateEnterExecutingMode(vFed)

    h.helicsPublicationPublishString(pubid, testValue)

    value = h.helicsInputGetString(subid)
    assert value == defaultValue

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

    value = h.helicsInputGetString(subid)
    assert value == testValue
Example #7
0
def test_value_federate_single_transfer(vFed):

    pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.helics_data_type_string, "")
    subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "")

    h.helicsFederateEnterExecutingMode(vFed)

    h.helicsPublicationPublishString(pubid, "string1")

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

    s = h.helicsInputGetString(subid)
    assert s == "string1"
Example #8
0
    def updateHelicsSubscriptions(self):

        for element_name, sub_info in self._subscriptions.items():
            if 'Subscription' in sub_info:
                value = None
                if sub_info['Data type'].lower() == 'double':
                    value = helics.helicsInputGetDouble(
                        sub_info['Subscription'])
                elif sub_info['Data type'].lower() == 'vector':
                    value = helics.helicsInputGetVector(
                        sub_info['Subscription'])
                elif sub_info['Data type'].lower() == 'string':
                    value = helics.helicsInputGetString(
                        sub_info['Subscription'])
                elif sub_info['Data type'].lower() == 'boolean':
                    value = helics.helicsInputGetBoolean(
                        sub_info['Subscription'])
                elif sub_info['Data type'].lower() == 'integer':
                    value = helics.helicsInputGetInteger(
                        sub_info['Subscription'])

                if value and value != 0:
                    value = value * sub_info['Multiplier']

                    dssElement = self._objects_by_element[element_name]
                    dssElement.SetParameter(sub_info['Property'], value)

                    self._logger.info(
                        'Value for "{}.{}" changed to "{}"'.format(
                            element_name, sub_info['Property'],
                            value * sub_info['Multiplier']))

                    if self._settings.helics.iterative_mode:
                        if self.c_seconds != self.c_seconds_old:
                            self._subscription_dState[element_name] = [
                                self.init_state
                            ] * self.n_states
                        else:
                            self._subscription_dState[element_name].insert(
                                0,
                                self._subscription_dState[element_name].pop())
                        self._subscription_dState[element_name][0] = value
                else:
                    self._logger.warning(
                        '{} will not be used to update element for "{}.{}" '.
                        format(value, element_name, sub_info['Property']))
        self.c_seconds_old = self.c_seconds
Example #9
0
def test_bad_input_duplicate_publication_and_input_pathways():

    broker = createBroker(1)
    vFed1, fedinfo = createValueFederate(1, "fed0")

    pubid = h.helicsFederateRegisterTypePublication(vFed1, "pub1", "string",
                                                    "")

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

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

    # @test_throws h.HELICSErrorInvalidObject ept = h.helicsFederateRegisterEndpoint(vFed1, "ept1", "")

    h.helicsInputAddTarget(subid, "Testfed0/pub1")

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

    h.helicsFederateEnterExecutingMode(vFed1)

    h.helicsPublicationPublishDouble(pubid, 27.0)
    h.helicsFederateRequestNextStep(vFed1)
    str = h.helicsInputGetString(subid)
    assert str[0] == "2"
    assert str[1] == "7"

    messages = h.helicsFederatePendingMessages(vFed1)
    assert messages == 0

    h.helicsFederateFinalize(vFed1)

    destroyFederate(vFed1, fedinfo)
    destroyBroker(broker)
Example #10
0
    def update_subscriptions(self):
        for subName, subList in self.Subscriptions.items():
            for subInfo in subList:
                sub = subInfo["subscriptionObj"]
                if subInfo["dType"].lower() == "complex":
                    value = h.helicsInputGetComplex(sub)
                elif subInfo["dType"].lower() == 'real':
                    value = h.helicsInputGetDouble(sub)
                elif subInfo["dType"].lower() == 'text':
                    value = h.helicsInputGetString(sub)
                elif subInfo["dType"].lower() == "number":
                    value = h.helicsInputGetInteger(sub)
                else:
                    value = h.helicsInputGetDouble(sub)

                if value:
                    value = value * subInfo["mult"]
                    X1 = subInfo["elementObj"].GetValue(subInfo["property"])

                    if value < 10000.0 and value > -100000.0:
                        subInfo["elementObj"].SetValue(value,
                                                       subInfo["property"])
                        #X2 = subInfo["elementObj"].GetValue(subInfo["property"])
                        self.__Logger.debug(
                            f"{subInfo['class']}.{subInfo['name']}.{subInfo['property']} updated to {value}"
                        )
                    if self.settings['helics']['coiter_mode']:
                        if self.c_seconds != self.c_seconds_old:
                            subInfo["dStates"] = [self.init_state
                                                  ] * self.n_states
                        else:
                            subInfo["dStates"].insert(0,
                                                      subInfo["dStates"].pop())
                        subInfo["dStates"][0] = value
            #self.cympy.study.Save()
        return
Example #11
0
h.helicsFederateInfoSetCoreInitString(fedinfo, "--federates=1")
h.helicsFederateInfoSetTimeProperty(fedinfo, h.helics_property_time_delta,
                                    0.01)

vfed = h.helicsCreateValueFederate(federate_name, fedinfo)
print(f"{federate_name}: Value federate created")

sub = h.helicsFederateRegisterSubscription(vfed, f"globaltopic{sys.argv[1]}",
                                           "")

h.helicsFederateEnterExecutingMode(vfed)
print(f"{federate_name}: Entering execution mode")

value = 0.0
prevtime = 0

currenttime = -1

while currenttime <= 100:

    currenttime = h.helicsFederateRequestTime(vfed, 100)

    value = h.helicsInputGetString(sub)
    print(f"{federate_name}: Received value = {value} at time {currenttime}")

h.helicsFederateFinalize(vfed)

h.helicsFederateFree(vfed)
h.helicsCloseLibrary()
print(f"{federate_name}: Federate finalized")
Example #12
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)
    cfed, "BeamFederate/chargingPlugIn", "string")
subs_chargingPlugOut = h.helicsFederateRegisterSubscription(
    cfed, "BeamFederate/chargingPlugOut", "string")

print("Waiting Execution Mode...")
h.helicsFederateEnterInitializingMode(cfed)
h.helicsFederateEnterExecutingMode(cfed)

# start execution loop #
timebin = 300
currenttime = 0
for t in range(timebin, timebin * 360 + 1, timebin):
    while currenttime < t:
        currenttime = h.helicsFederateRequestTime(cfed, t)
    if h.helicsInputIsUpdated(subs_chargingPlugIn) == 1:
        chargingPlugIn = h.helicsInputGetString(subs_chargingPlugIn)
        arr = chargingPlugIn.split(',')
        print("vehId:{}, Joules:{}, lat:{}, lng:{}\n".format(
            arr[0], arr[1], arr[2], arr[3]))
    if h.helicsInputIsUpdated(subs_chargingPlugOut) == 1:
        chargingPlugOut = h.helicsInputGetString(subs_chargingPlugOut)
        arr = chargingPlugOut.split(',')
        print("vehId:{}, Joules:{}, lat:{}, lng:{}\n".format(
            arr[0], arr[1], arr[2], arr[3]))

h.helicsFederateFinalize(cfed)
h.helicsFederateDestroy(cfed)
h.helicsFederateFree(cfed)
# don't wait more than half an hour for all other federates to finalize and write
second = 0
while h.helicsBrokerIsConnected(broker) == 1 and second < 1800:
Example #14
0
vfed = h.helicsCreateValueFederate("TestB Federate", fedinfo)
print("PI RECEIVER: Value federate created")

# Subscribe to PI SENDER's publication
sub = h.helicsFederateRegisterSubscription(vfed, "testA", "")
print("PI RECEIVER: Subscription registered")

h.helicsFederateEnterExecutingMode(vfed)
print("PI RECEIVER: Entering execution mode")

value = 0.0
prevtime = 0

currenttime = -1

while currenttime <= 100:

    currenttime = h.helicsFederateRequestTime(vfed, 100)

    value = h.helicsInputGetString(sub)
    print(
        "PI RECEIVER: Received value = {} at time {} from PI SENDER".format(
            value, currenttime
        )
    )

h.helicsFederateFinalize(vfed)

h.helicsFederateFree(vfed)
h.helicsCloseLibrary()
print("PI RECEIVER: Federate finalized")