Example #1
0
def test_federate_tests_federateGeneratedGlobalError():

    brk = h.helicsCreateBroker("inproc", "gbrokerc", "--root")
    cr = h.helicsCreateCore("inproc", "gcore", "--broker=gbrokerc")

    argv = ["", "--corename=gcore"]

    fi = h.helicsCreateFederateInfo()
    h.helicsFederateInfoLoadFromArgs(fi, argv)

    fed1 = h.helicsCreateValueFederate("fed0", fi)

    h.helicsFederateInfoFree(fi)
    h.helicsFederateEnterExecutingMode(fed1)

    h.helicsFederateRequestTime(fed1, 2.0)
    h.helicsFederateGlobalError(fed1, 9827, "user generated global error")

    with pt.raises(h.HelicsException):
        h.helicsFederateRequestTime(fed1, 3.0)

    h.helicsFederateDestroy(fed1)
    h.helicsCoreDisconnect(cr)
    h.helicsBrokerDisconnect(brk)
    h.helicsCloseLibrary()
Example #2
0
def init_worker(config_file_name, manager_name):
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)

    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    fed_name = h.helicsFederateGetName(fed)

    dest = manager_name + "/data"
    pid = os.getpid()
    h.helicsFederateEnterExecutingMode(fed)

    current_time = h.helicsFederateRequestTime(fed, maxtime)
    simulation_time_data = h.helicsEndpointGetMessage(my_epid)
    sleep_time = float(simulation_time_data.data)

    current_time = -1
    while current_time < maxtime:
        current_time = h.helicsFederateRequestTime(fed, maxtime)
        if h.helicsEndpointHasMessage(my_epid):
            message = h.helicsEndpointGetMessage(my_epid)
            data = str(fed_name) + "(" + str(pid) + "): " + str(message.data)
            #			time.sleep(random.randrange(4))
            time.sleep(float(sleep_time))
            h.helicsEndpointSendMessageRaw(my_epid, str(dest), data)

    h.helicsFederateFinalize(fed)
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Example #3
0
def init_logger(config_file_name):
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)
    my_epid = h.helicsFederateGetEndpoint(fed, "logger")

    fed_name = h.helicsFederateGetName(fed)
    print(fed_name)
    pid = os.getpid()
    print("Logger Pid {}".format(pid))
    currenttime = -1

    output = ""

    log.basicConfig(filename='./log/logger.log',
                    filemode='w',
                    format='%(message)s',
                    level=log.INFO)

    h.helicsFederateEnterExecutingMode(fed)
    while (currenttime < maxtime):
        currenttime = h.helicsFederateRequestTime(fed, maxtime)
        if h.helicsEndpointHasMessage(my_epid):
            count = h.helicsEndpointPendingMessages(my_epid)
            for i in range(count):
                message = h.helicsEndpointGetMessage(my_epid)
                output = output + str(message.data) + "\n"
    log.info("Current Time : {}".format(currenttime))
    log.info(output)
    h.helicsFederateFinalize(fed)
    print(fed_name, " : Federate finalized")
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Example #4
0
def test_filter_types_tests_core_fitler_registration():

    core1 = h.helicsCreateCore("inproc", "core1", "--autobroker")

    core2 = h.helicsCoreClone(core1)

    core1IdentifierString = h.helicsCoreGetIdentifier(core1)

    assert core1IdentifierString == "core1"

    sourceFilter1 = h.helicsCoreRegisterFilter(core1,
                                               h.HELICS_FILTER_TYPE_DELAY,
                                               "core1SourceFilter")

    h.helicsFilterAddSourceTarget(sourceFilter1, "ep1")
    destinationFilter1 = h.helicsCoreRegisterFilter(core1,
                                                    h.HELICS_FILTER_TYPE_DELAY,
                                                    "core1DestinationFilter")

    h.helicsFilterAddDestinationTarget(destinationFilter1, "ep2")
    cloningFilter1 = h.helicsCoreRegisterCloningFilter(core1, "ep3")

    h.helicsFilterRemoveDeliveryEndpoint(cloningFilter1, "ep3")
    core1IsConnected = h.helicsCoreIsConnected(core1)
    assert core1IsConnected != 0
    h.helicsCoreSetReadyToInit(core1)
    h.helicsCoreDisconnect(core1)
    h.helicsCoreDisconnect(core2)
    h.helicsCoreFree(core1)
    h.helicsCoreFree(core2)
    h.helicsCloseLibrary()
def test_combination_federate():

    broker = createBroker()

    cfed = h.helicsCreateCombinationFederateFromConfig(
        os.path.join(CURRENT_DIRECTORY, "combinationfederate.json"))

    assert h.helicsFederateIsValid(cfed)

    assert h.helicsFederateGetEndpointCount(cfed) == 2
    assert h.helicsFederateGetFilterCount(cfed) == 0
    assert h.helicsFederateGetInputCount(cfed) == 2

    ept = h.helicsFederateGetEndpointByIndex(cfed, 0)

    assert h.helicsEndpointGetName(ept) == "ept1"

    ipt = h.helicsFederateGetInputByIndex(cfed, 1)
    assert h.helicsInputGetExtractionUnits(ipt) == ""
    assert h.helicsSubscriptionGetKey(ipt) == "comboFed/pub2"

    h.helicsEndpointClearMessages(ept)

    h.helicsFederateDestroy(cfed)
    h.helicsFederateFree(cfed)
    h.helicsBrokerDestroy(broker)
    h.helicsCloseLibrary()
Example #6
0
def destroy_federate(fed):
    """
    fed: federate to destroy
    """
    h.helicsFederateFinalize(fed)
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Example #7
0
 def close(self, ID=5):
     try:
         h.helicsFederateFree(self.vf)
         h.helicsCloseLibrary()
         self.pyGldWorker.close(ID=ID)
     except:
         PrintException()
Example #8
0
def init_worker(config_file_name, manager_name, individual_simulation_time):
    print("worker in")
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)
    print("worker passed config")
    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    fed_name = h.helicsFederateGetName(fed)

    dest = manager_name + "/data"
    pid = os.getpid()
    print(fed_name, " about to Started")
    h.helicsFederateEnterExecutingMode(fed)

    print(fed_name, " Started")
    current_time = -1
    while current_time < maxtime:
        current_time = h.helicsFederateRequestTime(fed, maxtime)
        if h.helicsEndpointHasMessage(my_epid):
            message = h.helicsEndpointGetMessage(my_epid)
            data = str(fed_name) + "(" + str(pid) + "): " + str(message.data)
            #			time.sleep(random.randrange(4))
            time.sleep(individual_simulation_time)
            h.helicsEndpointSendMessageRaw(my_epid, str(dest), data)

    h.helicsFederateFinalize(fed)
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Example #9
0
def test_core_api():

    core1 = h.helicsCreateCore("inproc", "core1", "--autobroker")
    assert h.helicsCoreIsValid(core1) is True
    core2 = h.helicsCoreClone(core1)
    assert "core1" in h.helicsCoreGetIdentifier(core1)

    assert h.helicsCoreIsConnected(core1) == 0

    sourceFilter1 = h.helicsCoreRegisterFilter(core1,
                                               h.HELICS_FILTER_TYPE_DELAY,
                                               "core1SourceFilter")
    h.helicsFilterAddSourceTarget(sourceFilter1, "ep1")
    destinationFilter1 = h.helicsCoreRegisterFilter(core1,
                                                    h.HELICS_FILTER_TYPE_DELAY,
                                                    "core1DestinationFilter")
    h.helicsFilterAddDestinationTarget(destinationFilter1, "ep2")
    cloningFilter1 = h.helicsCoreRegisterCloningFilter(core1, "ep3")
    h.helicsFilterRemoveDeliveryEndpoint(cloningFilter1, "ep3")

    h.helicsCoreSetReadyToInit(core1)
    h.helicsCoreDisconnect(core1)
    h.helicsCoreDisconnect(core2)
    h.helicsCoreFree(core1)
    h.helicsCoreFree(core2)
    h.helicsCloseLibrary()
Example #10
0
def test_system_tests_federate_logging():

    lfile = "log.txt"
    rm(lfile, force=True)
    core = h.helicsCreateCore("inproc", "clogf",
                              "--autobroker --log_level=trace")

    fi = h.helicsCreateFederateInfo()
    h.helicsFederateInfoSetBrokerKey(fi, "key")
    h.helicsFederateInfoSetCoreName(fi, "clogf")
    fed = h.helicsCreateValueFederate("f1", fi)
    h.helicsFederateSetLogFile(fed, lfile)
    h.helicsFederateLogLevelMessage(fed, 7, "hello")
    h.helicsFederateLogErrorMessage(fed, "hello")
    h.helicsFederateLogDebugMessage(fed, "hello")
    h.helicsFederateLogWarningMessage(fed, "hello")
    h.helicsFederateClearMessages(fed)
    h.helicsCoreSetLogFile(core, lfile)
    h.helicsCoreDisconnect(core)
    h.helicsFederateFinalize(fed)
    h.helicsFederateInfoFree(fi)
    h.helicsCloseLibrary()

    assert isfile(lfile)
    rm(lfile, force=True)
Example #11
0
def destroy_federate(fed, broker=None):
    status = h.helicsFederateFinalize(fed)
    state = h.helicsFederateGetState(fed)
    assert state == 3
    while (h.helicsBrokerIsConnected(broker)):
        time.sleep(1)
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Example #12
0
def destroy_value_federate(fed):
    h.helicsFederateFinalize(fed)

    state = h.helicsFederateGetState(fed)

    h.helicsFederateFree(fed)

    h.helicsCloseLibrary()
Example #13
0
def destroy_federate(fed):
    status = h.helicsFederateFinalize(fed)
    #while h.helicsBrokerIsConnected(broker):
    #    print('broker is still connected')
    #    time.sleep(1)

    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Example #14
0
def destroy_value_federate(fed):
    status = h.helicsFederateFinalize(fed)

    status, state = h.helicsFederateGetState(fed)
    assert state == 3

    h.helicsFederateFree(fed)

    h.helicsCloseLibrary()
Example #15
0
def test_system_tests_broker_logging():
    lfile = "log.txt"
    rm(lfile, force=True)
    broker = h.helicsCreateBroker("inproc", "blog", "--log_level=trace")
    h.helicsBrokerSetLogFile(broker, lfile)
    h.helicsBrokerDisconnect(broker)
    h.helicsCloseLibrary()
    assert isfile(lfile)
    rm(lfile, force=True)
Example #16
0
def test_system_tests_core_logging():
    lfile = "log.txt"
    rm(lfile, force=True)
    core = h.helicsCreateCore("inproc", "clog",
                              "--autobroker --log_level=trace")
    h.helicsCoreSetLogFile(core, lfile)
    h.helicsCoreDisconnect(core)
    h.helicsCloseLibrary()
    assert isfile(lfile)
    rm(lfile, force=True)
Example #17
0
def init_manager(config_file_name, worker_name_list):
    print("manager in")
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)
    print("manager passed config")
    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    log_id = h.helicsFederateGetEndpoint(fed, "logger")
    log_dest = h.helicsEndpointGetDefaultDestination(log_id)

    currenttime = -1
    print("Manager about to Started")
    h.helicsFederateEnterExecutingMode(fed)
    print("Manager Started")
    for t in range(1, 11):
        h.helicsEndpointSendMessageRaw(log_id, log_dest,
                                       "Timestep {}".format(t))

        message = "Hello World " + str(t)
        while currenttime < t:
            currenttime = h.helicsFederateRequestTime(fed, t)

        log_msg = ""

        ################### START TIMING ###############
        start_time = time.time_ns() / (10**9)
        ##############################################

        for worker_name in worker_name_list:
            h.helicsEndpointSendMessageRaw(my_epid, worker_name + "/data",
                                           message)

        while not (h.helicsEndpointPendingMessages(my_epid)
                   == len(worker_name_list)):
            currenttime = h.helicsFederateRequestTime(fed, 0)

        for i in range(len(worker_name_list)):
            if h.helicsEndpointHasMessage(my_epid):
                new_message = h.helicsEndpointGetMessage(my_epid)
                log_msg = log_msg + "From: {}  Msg: {}  Time: {}\n".format(
                    new_message.source, new_message.data, new_message.time)

        ################### END TIMING ##################
        end_time = time.time_ns() / (10**9)
        ###############################################

        time_taken = "Time taken for iteration " + str(t) + ": " + str(
            end_time - start_time) + "\n"

        h.helicsEndpointSendMessageRaw(log_id, log_dest, log_msg)
        h.helicsEndpointSendMessageRaw(log_id, log_dest, time_taken)

    fed_name = h.helicsFederateGetName(fed)
    h.helicsFederateFinalize(fed)
    #	print("{}: Federate finalized".format(fed_name))
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
def vFed():

    initstring = "-f 1 --name=mainbroker"
    fedinitstring = "--broker=mainbroker --federates=1"
    deltat = 0.01
    #TODO: should add an assert here about helicsGetVersion
    h.helicsGetVersion()

    # Create broker #
    broker = h.helicsCreateBroker("zmq", "", initstring)

    isconnected = h.helicsBrokerIsConnected(broker)

    if isconnected == 1:
        pass

    # Create Federate Info object that describes the federate properties #
    fedinfo = h.helicsCreateFederateInfo()

    # Set Federate name #
    h.helicsFederateInfoSetCoreName(fedinfo, "TestA Core")

    # Set core type from string #
    h.helicsFederateInfoSetCoreTypeFromString(fedinfo, "zmq")

    # Federate init string #
    h.helicsFederateInfoSetCoreInitString(fedinfo, fedinitstring)

    # Set the message interval (timedelta) for federate. Note th#
    # HELICS minimum message time interval is 1 ns and by default
    # it uses a time delta of 1 second. What is provided to the
    # setTimedelta routine is a multiplier for the default timedelta.

    # Set one second message interval #
    h.helicsFederateInfoSetTimeProperty(fedinfo, h.helics_property_time_delta,
                                        deltat)

    h.helicsFederateInfoSetIntegerProperty(fedinfo,
                                           h.helics_property_int_log_level, 1)

    vFed = h.helicsCreateValueFederate("TestA Federate", fedinfo)

    yield vFed

    h.helicsFederateFinalize(vFed)

    state = h.helicsFederateGetState(vFed)
    assert state == 3

    while (h.helicsBrokerIsConnected(broker)):
        time.sleep(1)

    h.helicsFederateInfoFree(fedinfo)
    h.helicsFederateFree(vFed)
    h.helicsCloseLibrary()
Example #19
0
def test_filter_test_file_load():

    filename = os.path.join(CURRENT_DIRECTORY, "filters.json")
    mFed = h.helicsCreateMessageFederateFromConfig(filename)

    name = h.helicsFederateGetName(mFed)
    assert name == "filterFed"

    assert h.helicsFederateGetEndpointCount(mFed) == 3
    h.helicsFederateFinalize(mFed)
    h.helicsCloseLibrary()
def destroy_value_federate(fed, broker):
    h.helicsFederateFinalize(fed)

    state = h.helicsFederateGetState(fed)

    while h.helicsBrokerIsConnected(broker):
        time.sleep(1)

    h.helicsFederateFree(fed)

    h.helicsCloseLibrary()
Example #21
0
def destroy_federate(fed):
    h.helicsFederateFinalize(fed)

    #    status, state = h.helicsFederateGetState(fed)
    #    assert state == 3

    while h.helicsBrokerIsConnected(broker):
        time.sleep(1)

    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Example #22
0
 def stop_simulation(self, *args, **kwargs):
     """
     Disconnect the federate from helics core and close the library
     :return:
     """
     try:
         h.helicsFederateFinalize(self.fed)
         h.helicsFederateFree(self.fed)
         h.helicsCloseLibrary()
     except h._helics.HelicsException as e:
         _log.exception("Error stopping HELICS federate {}".format(e))
Example #23
0
def test_system_test_federate_global_value():

    brk = h.helicsCreateBroker("inproc", "gbrokerc", "--root")
    cr = h.helicsCreateCore("inproc", "gcore", "--broker=gbrokerc")

    argv = ["", "--corename=gcore"]

    fi = h.helicsCreateFederateInfo()
    h.helicsFederateInfoLoadFromArgs(fi, argv)

    fed = h.helicsCreateValueFederate("fed0", fi)

    fi2 = h.helicsFederateInfoClone(fi)

    h.helicsFederateInfoFree(fi2)
    h.helicsFederateInfoFree(fi)

    globalVal = "this is a string constant that functions as a global"
    globalVal2 = "this is a second string constant that functions as a global"
    h.helicsFederateSetGlobal(fed, "testglobal", globalVal)
    q = h.helicsCreateQuery("global", "testglobal")
    res = h.helicsQueryExecute(q, fed)
    assert res == globalVal
    h.helicsFederateSetGlobal(fed, "testglobal2", globalVal2)
    h.helicsQueryFree(q)
    q = h.helicsCreateQuery("global", "testglobal2")
    h.helicsQueryExecuteAsync(q, fed)
    while h.helicsQueryIsCompleted(q) is False:
        time.sleep(0.20)
    res = h.helicsQueryExecuteComplete(q)
    assert res == globalVal2

    q2 = h.helicsCreateQuery("", "isinit")
    h.helicsQueryExecuteAsync(q2, fed)
    while h.helicsQueryIsCompleted(q2) is False:
        time.sleep(0.20)
    res = h.helicsQueryExecuteComplete(q2)
    assert str(res).lower() == "false"

    h.helicsFederateFinalize(fed)

    h.helicsCoreDisconnect(cr)
    h.helicsBrokerDisconnect(brk)

    h.helicsQueryFree(q)
    h.helicsQueryFree(q2)
    assert h.helicsBrokerIsConnected(brk) is False

    h.helicsBrokerDisconnect(brk)
    h.helicsCoreDisconnect(cr)

    assert h.helicsBrokerIsConnected(brk) is False
    h.helicsCloseLibrary()
def mFed():
    import helics as h

    initstring = "1 --name=mainbroker"
    fedinitstring = "--broker=mainbroker --federates=1"
    deltat = 0.01

    helicsversion = h.helicsGetVersion()

    # Create broker #
    broker = h.helicsCreateBroker("zmq", "", initstring)

    isconnected = h.helicsBrokerIsConnected(broker)

    if isconnected == 1:
        pass

    # Create Federate Info object that describes the federate properties #
    fedinfo = h.helicsFederateInfoCreate()

    # Set Federate name #
    status = h.helicsFederateInfoSetFederateName(fedinfo, "TestA Federate")

    # Set core type from string #
    status = h.helicsFederateInfoSetCoreTypeFromString(fedinfo, "zmq")

    # Federate init string #
    status = h.helicsFederateInfoSetCoreInitString(fedinfo, fedinitstring)

    # Set the message interval (timedelta) for federate. Note th#
    # HELICS minimum message time interval is 1 ns and by default
    # it uses a time delta of 1 second. What is provided to the
    # setTimedelta routine is a multiplier for the default timedelta.

    # Set one second message interval #
    status = h.helicsFederateInfoSetTimeDelta(fedinfo, deltat)

    status = h.helicsFederateInfoSetLoggingLevel(fedinfo, 1)

    mFed = h.helicsCreateMessageFederate(fedinfo)

    yield mFed

    status = h.helicsFederateFinalize(mFed)

    status, state = h.helicsFederateGetState(mFed)
    assert state == 3

    while (h.helicsBrokerIsConnected(broker)):
        time.sleep(1)

    h.helicsFederateFree(mFed)
    h.helicsCloseLibrary()
Example #25
0
def mFed():
    initstring = "-f 1 --name=mainbroker"
    fedinitstring = "--broker=mainbroker --federates=1"
    deltat = 0.01

    h.helicsGetVersion()

    # Create broker #
    broker = h.helicsCreateBroker("zmq", "", initstring)

    isconnected = h.helicsBrokerIsConnected(broker)

    if isconnected == 1:
        pass

    # Create Federate Info object that describes the federate properties #
    fedinfo = h.helicsCreateFederateInfo()

    # Set Federate name #
    h.helicsFederateInfoSetCoreName(fedinfo, "CoreA Federate")

    # Set core type from string #
    h.helicsFederateInfoSetCoreTypeFromString(fedinfo, "zmq")

    # Federate init string #
    h.helicsFederateInfoSetCoreInitString(fedinfo, fedinitstring)

    # Set the message interval (timedelta) for federate. Note th#
    # HELICS minimum message time interval is 1 ns and by default
    # it uses a time delta of 1 second. What is provided to the
    # setTimedelta routine is a multiplier for the default timedelta.

    # Set one second message interval #
    h.helicsFederateInfoSetTimeProperty(fedinfo, h.HELICS_PROPERTY_TIME_DELTA,
                                        deltat)

    h.helicsFederateInfoSetIntegerProperty(fedinfo,
                                           h.HELICS_PROPERTY_INT_LOG_LEVEL, 1)

    mFed = h.helicsCreateMessageFederate("TestA Federate", fedinfo)

    yield mFed

    h.helicsFederateFinalize(mFed)
    state = h.helicsFederateGetState(mFed)
    assert state == 3
    while h.helicsBrokerIsConnected(broker):
        time.sleep(1)

    h.helicsFederateInfoFree(fedinfo)
    h.helicsFederateFree(mFed)
    h.helicsCloseLibrary()
Example #26
0
def test_python_api3():
    core1 = h.helicsCreateCore("inproc", "core1", "--autobroker")

    assert """HelicsCore(identifier = "core1", address = "core1")""" in repr(
        core1)

    core2 = core1.clone()

    assert core1.identifier == "core1"

    source_filter1 = core1.register_filter(h.HELICS_FILTER_TYPE_DELAY,
                                           "core1SourceFilter")

    source_filter1.add_source_target("ep1")

    assert (
        """<{ 'CONNECTION_REQUIRED' = 0, 'CONNECTION_OPTIONAL' = 0, 'SINGLE_CONNECTION_ONLY' = 0, 'MULTIPLE_CONNECTIONS_ALLOWED' = 0, 'BUFFER_DATA' = 0, 'STRICT_TYPE_CHECKING' = 0, 'IGNORE_UNIT_MISMATCH' = 0, 'ONLY_TRANSMIT_ON_CHANGE' = 0, 'ONLY_UPDATE_ON_CHANGE' = 0, 'IGNORE_INTERRUPTS' = 0, 'MULTI_INPUT_HANDLING_METHOD' = 0, 'INPUT_PRIORITY_LOCATION' = 0, 'CLEAR_PRIORITY_LIST' = 0, 'CONNECTIONS' = 0 }>"""
        in repr(source_filter1.option))

    source_filter1.option["CONNECTION_REQUIRED"] = 1
    assert source_filter1.option["CONNECTION_REQUIRED"] == 1

    source_filter1.add_source_target("hello")
    source_filter1.add_destination_target("world")
    source_filter1.remove_destination_target("world")

    source_filter1.info = "hello world"
    assert source_filter1.info == "hello world"

    source_filter1.set("hello", 1)

    destination_filter1 = core1.register_filter(h.HELICS_FILTER_TYPE_DELAY,
                                                "core1DestinationFilter")

    destination_filter1.add_destination_target("ep2")
    cloning_filter1 = core1.register_cloning_filter("ep3")

    cloning_filter1.remove_delivery_endpoint("ep3")
    cloning_filter1.add_delivery_endpoint("ep3")

    assert core1.is_valid()
    assert core1.is_connected()
    core1.set_ready_to_init()

    core1.disconnect()
    core2.disconnect()

    del core1
    del core2

    h.helicsCloseLibrary()
Example #27
0
def test_valuefederate_test_file_load():

    filename = os.path.join(CURRENT_DIRECTORY, "valuefederate.json")
    vFed = h.helicsCreateValueFederateFromConfig(filename)

    name = h.helicsFederateGetName(vFed)
    assert name == "valueFed"

    assert h.helicsFederateGetInputCount(vFed) == 3
    assert h.helicsFederateGetPublicationCount(vFed) == 2

    h.helicsFederateFinalize(vFed)
    h.helicsFederateFree(vFed)
    h.helicsCloseLibrary()
Example #28
0
def destroy_federate(fed):
    '''
    As part of ending a HELICS co-simulation it is good housekeeping to
    formally destroy a federate. Doing so informs the rest of the
    federation that it is no longer a part of the co-simulation and they
    should proceed without it (if applicable). Generally this is done
    when the co-simulation is complete and all federates end execution
    at more or less the same wall-clock time.

    :param fed: Federate to be destroyed
    :return: (none)
    '''
    status = h.helicsFederateFinalize(fed)
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
    logger.info('Federate finalized')
Example #29
0
def test_python_api0():
    broker = h.helicsCreateBroker("zmq", "", "-f 1 --name=mainbroker")
    fedinfo = h.helicsCreateFederateInfo()
    assert "HelicsFederateInfo()" in repr(fedinfo)
    fedinfo.core_name = "TestFederate"
    fedinfo.core_type = "zmq"
    fedinfo.core_init = "-f 1 --broker=mainbroker"
    mFed = h.helicsCreateCombinationFederate("TestFederate", fedinfo)

    assert (
        """HelicsCombinationFederate(name = "TestFederate", state = HelicsFederateState.STARTUP, current_time = -9223372036.854776, n_publications = 0, n_subscriptions = 0, n_endpoints = 0, n_filters = 0, n_pending_messages = 0)"""
        in repr(mFed))

    _ = mFed.register_endpoint("ep1")
    _ = mFed.register_global_endpoint("ep2")

    pub = mFed.register_publication("publication", h.HELICS_DATA_TYPE_STRING,
                                    "custom-units")
    assert """HelicsPublication(name = "TestFederate/publication", type = "string", units = "custom-units", info = "")""" in repr(
        pub)

    sub = mFed.register_subscription("subscription", "custom-units")
    assert (
        """HelicsInput(name = "_input_3", units = "custom-units", injection_units = "", publication_type = "", type = "", target = "subscription", info = "")"""
        in repr(sub))
    assert (
        """{ 'CONNECTION_REQUIRED' = 0, 'CONNECTION_OPTIONAL' = 0, 'SINGLE_CONNECTION_ONLY' = 0, 'MULTIPLE_CONNECTIONS_ALLOWED' = 1, 'BUFFER_DATA' = 0, 'STRICT_TYPE_CHECKING' = 0, 'IGNORE_UNIT_MISMATCH' = 0, 'ONLY_TRANSMIT_ON_CHANGE' = 0, 'ONLY_UPDATE_ON_CHANGE' = 0, 'IGNORE_INTERRUPTS' = 0, 'MULTI_INPUT_HANDLING_METHOD' = 0, 'INPUT_PRIORITY_LOCATION' = -1, 'CLEAR_PRIORITY_LIST' = 1, 'CONNECTIONS' = 0 }"""
        in repr(sub.option))
    sub.option["CONNECTION_REQUIRED"] = 1
    sub.option[h.HELICS_HANDLE_OPTION_CONNECTION_REQUIRED] = 1
    assert sub.option["CONNECTION_REQUIRED"] == 1

    sub.add_target("")

    mFed.property[h.HELICS_PROPERTY_TIME_DELTA] = 1.0
    assert mFed.property[h.HELICS_PROPERTY_TIME_DELTA] == 1.0

    mFed.property["TIME_DELTA"] = 1.0
    assert mFed.property["TIME_DELTA"] == 1.0

    with pt.raises(h.HelicsException):
        mFed.enter_executing_mode()

    h.helicsCloseLibrary()

    del mFed
    del broker
Example #30
0
def helicsBroker():
    initstring = "-f 1 --name=mainbroker"
    # TODO: should add an assert here about helicsGetVersion
    h.helicsGetVersion()

    # Create broker #
    broker = h.helicsCreateBroker("zmq", "", initstring)

    isconnected = h.helicsBrokerIsConnected(broker)

    if isconnected == 1:
        pass

    yield broker

    h.helicsBrokerFree(broker)
    h.helicsCloseLibrary()
Example #31
0
h.helicsFederateEnterExecutingMode(vfed)
print("PI SENDER: Entering execution mode")

# This federate will be publishing deltat*pi for numsteps steps #
this_time = 0.0
value = pi

for t in range(5, 10):
    val = value

    currenttime = h.helicsFederateRequestTime(vfed, t)

    h.helicsPublicationPublishDouble(pub, val)
    print(
        "PI SENDER: Sending value pi = {} at time {} to PI RECEIVER".format(
            val, currenttime
        )
    )

    time.sleep(1)

h.helicsFederateFinalize(vfed)
print("PI SENDER: Federate finalized")

while h.helicsBrokerIsConnected(broker):
    time.sleep(1)

h.helicsFederateFree(vfed)
h.helicsCloseLibrary()

print("PI SENDER: Broker disconnected")