Ejemplo n.º 1
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()
Ejemplo n.º 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()
Ejemplo n.º 3
0
def test_filter_type_tests_message_filter_function():

    broker = createBroker(2)
    fFed, fedinfo1 = createMessageFederate(1, "filter")
    mFed, fedinfo2 = createMessageFederate(1, "message")

    h.helicsFederateSetFlagOption(mFed,
                                  h.HELICS_FLAG_IGNORE_TIME_MISMATCH_WARNINGS,
                                  True)
    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "")

    f1 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    h.helicsFilterSet(f1, "delay", 2.5)

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsFederateHasMessage(mFed) is False

    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False

    h.helicsFederateRequestTimeAsync(fFed, 3.0)
    h.helicsFederateRequestTime(mFed, 3.0)

    assert h.helicsEndpointHasMessage(p2) is True

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    h.helicsFederateRequestTime(mFed, 3.0)
    h.helicsFederateRequestTimeComplete(fFed)
    h.helicsFederateFinalizeAsync(mFed)
    h.helicsFederateFinalize(fFed)
    h.helicsFederateFinalizeComplete(mFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(fFed, fedinfo1)
    destroyFederate(mFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 4
0
def test_messagefilter_function():
    broker = createBroker(2)

    fFed, ffedinfo = createMessageFederate(1, "filter")
    mFed, mfedinfo = createMessageFederate(1, "message")

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "random")

    f1 = h.helicsFederateRegisterGlobalFilter(fFed,
                                              h.HELICS_FILTER_TYPE_CUSTOM,
                                              "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    f2 = h.helicsFederateRegisterGlobalFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                              "filter2")
    h.helicsFilterAddSourceTarget(f2, "port1")
    h.helicsFederateRegisterEndpoint(fFed, "fout", "")
    f3 = h.helicsFederateRegisterFilter(fFed,
                                        h.HELICS_FILTER_TYPE_RANDOM_DELAY,
                                        "filter3")
    h.helicsFilterAddSourceTarget(f3, "filter/fout")

    h.helicsFilterSet(f2, "delay", 2.5)
    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)
    state = h.helicsFederateGetState(fFed)
    assert state == 2
    data = "hello world"

    filt_key = h.helicsFilterGetName(f1)
    assert filt_key == "filter1"

    filt_key = h.helicsFilterGetName(f2)
    assert filt_key == "filter2"

    h.helicsEndpointSendMessageRaw(p1, "port2", data.encode())
    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    grantedtime = h.helicsFederateRequestTime(fFed, 1.0)
    assert grantedtime == 1.0
    grantedtime = h.helicsFederateRequestTimeComplete(mFed)
    assert grantedtime == 1.0
    res = h.helicsFederateHasMessage(mFed)
    assert res == 0
    res = h.helicsEndpointHasMessage(p2)
    assert res == 0
    # grantedtime = h.helicsFederateRequestTime(fFed, 3.0)
    # assert res==h.helics_true

    h.helicsFederateFinalize(mFed)
    h.helicsFederateFinalize(fFed)
    # f2 = h.helicsFederateRegisterDestinationFilter(fFed, h.helics_custom_filter, "filter2", "port2")
    # ep1 = h.helicsFederateRegisterEndpoint(fFed, "fout", "")
    # f3 = h.helicsFederateRegisterSourceFilter(fFed, h.helics_custom_filter, "", "filter0/fout")

    destroyFederate(fFed, ffedinfo)
    destroyFederate(mFed, mfedinfo)
    time.sleep(1.0)
    destroyBroker(broker)
Ejemplo n.º 5
0
def main(delay=None):

    broker = create_broker()
    fed = create_value_federate(broker)

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

    if delay is not None:
        fid = h.helicsFederateRegisterGlobalFilter(fed,
                                                   h.helics_filter_type_delay,
                                                   "filter-name")
        h.helicsFilterAddSourceTarget(fid, "endpoint1")

    h.helicsInputSetDefaultNamedPoint(subid, "", 0)

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

    if delay is not None:
        h.helicsFilterSet(fid, "delay", delay)
    grantedtime = -1
    while True:
        try:
            stop_at_time, value_to_send = get_input(grantedtime)
            print(stop_at_time)
        except KeyboardInterrupt:
            print("")
            break
        while grantedtime < stop_at_time:
            print(">>>>>>>> Requesting time = {}".format(stop_at_time))
            grantedtime = h.helicsFederateRequestTime(fed, stop_at_time)
            grantedtime = int(grantedtime)
            if grantedtime != stop_at_time:
                value = h.helicsSubscriptionGetKey(subid)
                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))
            h.helicsPublicationPublishString(pubid, str(value_to_send))
            h.helicsEndpointSendMessageRaw(epid, "endpoint2",
                                           str(value_to_send))
        value = h.helicsSubscriptionGetKey(subid)
        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)
Ejemplo n.º 6
0
def test_message_filter_function(broker):

    fFed, ffedinfo = AddFederate(broker, "zmq", 1, 1, "filter")
    mFed, mfedinfo = AddFederate(broker, "zmq", 1, 1, "message")

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "random")

    f1 = h.helicsFederateRegisterGlobalFilter(fFed,
                                              h.helics_filter_type_custom,
                                              "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    f2 = h.helicsFederateRegisterGlobalFilter(fFed, h.helics_filter_type_delay,
                                              "filter2")
    h.helicsFilterAddSourceTarget(f2, "port1")
    h.helicsFederateRegisterEndpoint(fFed, 'fout', '')
    f3 = h.helicsFederateRegisterFilter(fFed,
                                        h.helics_filter_type_random_delay,
                                        'filter3')
    h.helicsFilterAddSourceTarget(f3, 'filter/fout')

    h.helicsFilterSet(f2, "delay", 2.5)
    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)
    state = h.helicsFederateGetState(fFed)
    assert state == 2
    data = "hello world"

    filt_key = h.helicsFilterGetName(f1)
    assert filt_key == 'filter1'

    filt_key = h.helicsFilterGetName(f2)
    assert filt_key == 'filter2'

    h.helicsEndpointSendMessageRaw(p1, "port2", data)
    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    grantedtime = h.helicsFederateRequestTime(fFed, 1.0)
    assert grantedtime == 1.0
    grantedtime = h.helicsFederateRequestTimeComplete(mFed)
    assert grantedtime == 1.0
    res = h.helicsFederateHasMessage(mFed)
    assert res == 0
    res = h.helicsEndpointHasMessage(p2)
    assert res == 0
    #grantedtime = h.helicsFederateRequestTime(fFed, 3.0)
    #assert res==h.helics_true

    h.helicsFederateFinalize(mFed)
    h.helicsFederateFinalize(fFed)
    #f2 = h.helicsFederateRegisterDestinationFilter (fFed, h.helics_custom_filter, "filter2", "port2")
    #ep1 = h.helicsFederateRegisterEndpoint (fFed, "fout", "")
    #f3 = h.helicsFederateRegisterSourceFilter (fFed, h.helics_custom_filter, "", "filter0/fout")

    FreeFederate(fFed, ffedinfo)
    FreeFederate(mFed, mfedinfo)
    time.sleep(1.0)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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()
Ejemplo n.º 9
0
def test_message_filter_function(broker):

    fFed = AddFederate(broker, "zmq", 1, 1, "filter")
    mFed = AddFederate(broker, "zmq", 1, 1, "message")

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "")

    f1 = h.helicsFederateRegisterSourceFilter(fFed, h.helics_delay_filter,
                                              "port1", "filter1")
    status = h.helicsFilterSet(f1, "delay", 2.5)
    assert status == 0
    status = h.helicsFederateEnterExecutionModeAsync(fFed)
    assert status == 0
    status = h.helicsFederateEnterExecutionMode(mFed)
    assert status == 0
    status = h.helicsFederateEnterExecutionModeComplete(fFed)
    assert status == 0
    status, state = h.helicsFederateGetState(fFed)
    assert status == 0
    assert state == 2
    data = "hello world"
    h.helicsEndpointSendMessageRaw(p1, "port2", data)
    grantedtime = h.helicsFederateRequestTimeAsync(mFed, 1.0)
    assert grantedtime == 0
    status, grantedtime = h.helicsFederateRequestTime(fFed, 1.0)
    assert status == 0
    assert grantedtime == 1.0
    status, grantedtime = h.helicsFederateRequestTimeComplete(mFed)
    assert status == 0
    assert grantedtime == 1.0

    h.helicsFederateFinalize(mFed)
    h.helicsFederateFinalize(fFed)
    #f2 = h.helicsFederateRegisterDestinationFilter (fFed, h.helics_custom_filter, "filter2", "port2")
    #ep1 = h.helicsFederateRegisterEndpoint (fFed, "fout", "")
    #f3 = h.helicsFederateRegisterSourceFilter (fFed, h.helics_custom_filter, "", "filter0/fout")

    FreeFederate(fFed)
    FreeFederate(mFed)
    time.sleep(1.0)
Ejemplo n.º 10
0
def test_messagefederate_send_receive_2fed_multisend():

    broker = createBroker(2)
    mFed1, fedinfo1 = createMessageFederate(1, "A Federate")
    mFed2, fedinfo2 = createMessageFederate(1, "B Federate")

    epid1 = h.helicsFederateRegisterEndpoint(mFed1, "ep1", "")
    epid2 = h.helicsFederateRegisterGlobalEndpoint(mFed2, "ep2", "random")

    h.helicsEndpointSetOption(epid1, h.HELICS_HANDLE_OPTION_IGNORE_INTERRUPTS,
                              True)

    h.helicsFederateSetTimeProperty(mFed1, h.HELICS_PROPERTY_TIME_DELTA, 1.0)
    h.helicsFederateSetTimeProperty(mFed2, h.HELICS_PROPERTY_TIME_DELTA, 1.0)

    h.helicsFederateEnterExecutingModeAsync(mFed1)
    h.helicsFederateEnterExecutingMode(mFed2)
    h.helicsFederateEnterExecutingModeComplete(mFed1)

    assert h.HELICS_STATE_EXECUTION == h.helicsFederateGetState(mFed1)
    assert h.HELICS_STATE_EXECUTION == h.helicsFederateGetState(mFed2)

    h.helicsEndpointSetDefaultDestination(epid1, "ep2")

    h.helicsEndpointSendMessageRaw(epid1, "", "a".encode())
    h.helicsEndpointSendMessageRaw(epid1, "", "a".encode())
    h.helicsEndpointSendMessageRaw(epid1, "", "a".encode())

    h.helicsFederateRequestTimeAsync(mFed1, 1.0)
    granted_time = h.helicsFederateRequestTime(mFed2, 1.0)
    complete_time = h.helicsFederateRequestTimeComplete(mFed1)

    assert granted_time == 1.0
    assert complete_time == 1.0

    res = h.helicsEndpointPendingMessages(epid2)
    assert res == 3

    res = h.helicsFederatePendingMessages(mFed2)
    assert res == 3

    assert h.helicsEndpointGetDefaultDestination(epid1) == "ep2"

    # FIXME: Someday this will be implemented.
    # @test_broken h.helicsEndpointGetOption(epid1, h.HELICS_HANDLE_OPTION_IGNORE_INTERRUPTS) is True

    destroyFederate(mFed1, fedinfo1)
    destroyFederate(mFed2, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 11
0
def init_manager(config_file_name, worker_name_list):
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)

    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    log_id = h.helicsFederateGetEndpoint(fed, "logger")
    log_dest = h.helicsEndpointGetDefaultDestination(log_id)

    currenttime = -1
    h.helicsFederateEnterExecutingMode(fed)

    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)

        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)
        log_msg = ""
        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)

        h.helicsEndpointSendMessageRaw(log_id, log_dest, log_msg)

    fed_name = h.helicsFederateGetName(fed)
    h.helicsFederateFinalize(fed)

    #	print("{}: Federate finalized".format(fed_name))

    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Ejemplo n.º 12
0
    # Data collection lists
    time_sim = []
    power = []

    # Blocking call for a time request at simulation time 0
    initial_time = 60
    logger.debug(f'Requesting initial time {initial_time}')
    t = h.helicsFederateRequestTime(fed, initial_time)
    logger.debug(f'Granted time {t}')

    # Once granted an initial time, send the initial SOCs to the EV
    #   Controller
    for j in range(0, end_count):
        destination_name = str(h.helicsEndpointGetDefaultDestination(endid[j]))
        h.helicsEndpointSendMessageRaw(endid[j], "",
                                       str(currentsoc[j]).encode())  #

    # As long as granted time is in the time range to be simulated...
    while t < total_interval:

        # Time request for the next physical interval to be simulated
        requested_time = (t + update_interval)
        logger.debug(f'Requesting time {requested_time}')
        grantedtime = h.helicsFederateRequestTime(fed, requested_time)
        logger.debug(f'Granted time {grantedtime}')

        t = grantedtime

        for j in range(0, end_count):

            # Model the physics of the battery charging. This happens
Ejemplo n.º 13
0
def test_filter_test_types_clone_test_broker_dest_connections():

    broker = createBroker(3)
    sFed, fedinfo1 = createMessageFederate(1, "source", 1.0)
    dFed, fedinfo2 = createMessageFederate(1, "dest", 1.0)
    dcFed, fedinfo3 = createMessageFederate(1, "dest_clone", 1.0)

    p1 = h.helicsFederateRegisterGlobalEndpoint(sFed, "src", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(dFed, "dest", "")
    p3 = h.helicsFederateRegisterGlobalEndpoint(dcFed, "cm", "")

    f1 = h.helicsFederateRegisterGlobalCloningFilter(dcFed, "filt1")
    h.helicsFilterAddDeliveryEndpoint(f1, "cm")
    h.helicsBrokerAddDestinationFilterToEndpoint(broker, "filt1", "dest")

    h.helicsBrokerAddDestinationFilterToEndpoint(broker, "", "dest")

    h.helicsFederateEnterExecutingModeAsync(sFed)
    h.helicsFederateEnterExecutingModeAsync(dcFed)
    h.helicsFederateEnterExecutingMode(dFed)
    h.helicsFederateEnterExecutingModeComplete(sFed)
    h.helicsFederateEnterExecutingModeComplete(dcFed)

    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "dest", data)

    h.helicsFederateRequestTimeAsync(sFed, 1.0)
    h.helicsFederateRequestTimeAsync(dcFed, 1.0)
    h.helicsFederateRequestTime(dFed, 1.0)
    h.helicsFederateRequestTimeComplete(sFed)
    h.helicsFederateRequestTimeComplete(dcFed)

    assert h.helicsFederateHasMessage(dFed) is True

    m2 = h.helicsEndpointGetMessage(p2)

    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    h.helicsFederateFinalizeAsync(sFed)
    h.helicsFederateFinalizeAsync(dFed)

    # TODO: figure out why this test fails on CI
    # @test_broken False
    # assert h.helicsFederateHasMessage(dcFed) is False

    # h.helicsFederateRequestTime(dcFed, 2.0)

    # assert h.helicsFederateHasMessage(dcFed) is True

    # m2 = h.helicsEndpointGetMessage(p3)
    # assert h.helicsMessageGetSource(m2) == "src"
    # assert h.helicsMessageGetOriginalSource(m2) == "src"
    # assert h.helicsMessageGetDestination(m2) == "cm"
    # assert h.helicsMessageGetOriginalDestination(m2) == "dest"
    # assert h.helicsMessageGetRawDataSize(m2) == len(data)

    # _ = h.helicsFederateHasMessage(dcFed)

    h.helicsFederateFinalize(dcFed)
    h.helicsFederateFinalizeComplete(sFed)
    h.helicsFederateFinalizeComplete(dFed)
    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(sFed, fedinfo1)
    destroyFederate(dFed, fedinfo2)
    destroyFederate(dcFed, fedinfo3)
    destroyBroker(broker)
Ejemplo n.º 14
0
def test_filter_callback_test():

    broker = createBroker(2)

    assert """helics.HelicsBroker(identifier = "mainbroker", address = "tcp://127.0.0.1:23404")""" in repr(
        broker)

    fFed, fedinfo1 = createMessageFederate(1, "filter", 1.0)
    mFed, fedinfo2 = createMessageFederate(1, "message", 1.0)

    h.helicsFederateSetFlagOption(mFed,
                                  h.HELICS_FLAG_IGNORE_TIME_MISMATCH_WARNINGS,
                                  True)

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "")

    assert (
        """helics.HelicsEndpoint(name = "port1", type = "", info = "", is_valid = True, default_destination = "", n_pending_messages = 0)"""
        in repr(p1))
    assert (
        """helics.HelicsEndpoint(name = "port2", type = "", info = "", is_valid = True, default_destination = "", n_pending_messages = 0)"""
        in repr(p2))

    f1 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_CUSTOM,
                                        "filter1")
    f2 = h.helicsFederateRegisterFilter(mFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "dfilter")

    h.helicsFilterAddSourceTarget(f1, "port1")

    assert 'name = "Testfilter/filter1"' in repr(f1)

    userdata = UserData(5)

    handle = h.ffi.new_handle(userdata)
    h.helicsFilterSetCustomCallback(f1, filterFunc1, handle)

    with pt.raises(h.HelicsException):
        h.helicsFilterSetCustomCallback(f2, filterFunc1, handle)

    assert (
        """helics.HelicsMessageFederate(name = "Testfilter", state = HelicsFederateState.STARTUP, current_time = -9223372036.854776, n_publications = 0, n_subscriptions = 0, n_endpoints = 0, n_filters = 1, n_pending_messages = 0)"""
        in repr(fFed))
    assert (
        """helics.HelicsMessageFederate(name = "Testmessage", state = HelicsFederateState.STARTUP, current_time = -9223372036.854776, n_publications = 0, n_subscriptions = 0, n_endpoints = 2, n_filters = 1, n_pending_messages = 0)"""
        in repr(mFed))

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    assert (
        """helics.HelicsMessageFederate(name = "Testfilter", state = HelicsFederateState.EXECUTION, current_time = 0.0, n_publications = 0, n_subscriptions = 0, n_endpoints = 0, n_filters = 1, n_pending_messages = 0)"""
        in repr(fFed))
    assert (
        """helics.HelicsMessageFederate(name = "Testmessage", state = HelicsFederateState.EXECUTION, current_time = 0.0, n_publications = 0, n_subscriptions = 0, n_endpoints = 2, n_filters = 1, n_pending_messages = 0)"""
        in repr(mFed))

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsFederateHasMessage(mFed) is False

    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False

    h.helicsFederateRequestTimeAsync(fFed, 3.0)
    h.helicsFederateRequestTime(mFed, 3.0)

    assert h.helicsEndpointHasMessage(p2)

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    h.helicsFederateRequestTime(mFed, 3.0)
    h.helicsFederateRequestTimeComplete(fFed)
    h.helicsFederateFinalizeAsync(mFed)
    h.helicsFederateFinalize(fFed)
    h.helicsFederateFinalizeComplete(mFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(fFed, fedinfo1)
    destroyFederate(mFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 15
0
def test_filter_test_types_clone_test_dest_connections():
    broker = createBroker(3)
    sFed, fedinfo1 = createMessageFederate(1, "source", 1.0)
    dFed, fedinfo2 = createMessageFederate(1, "dest", 1.0)
    dcFed, fedinfo3 = createMessageFederate(1, "dest_clone", 2.0)

    p1 = h.helicsFederateRegisterGlobalEndpoint(sFed, "src", "")
    _ = h.helicsFederateRegisterGlobalEndpoint(dFed, "dest", "")
    _ = h.helicsFederateRegisterGlobalEndpoint(dcFed, "cm", "")

    f1 = h.helicsFederateRegisterGlobalCloningFilter(dcFed, "filt1")
    h.helicsFilterAddDeliveryEndpoint(f1, "cm")

    cr = h.helicsFederateGetCoreObject(sFed)

    h.helicsCoreAddDestinationFilterToEndpoint(cr, "filt1", "dest")

    h.helicsCoreAddDestinationFilterToEndpoint(cr, "", "dest")

    h.helicsCoreFree(cr)

    h.helicsFederateEnterExecutingModeAsync(sFed)
    h.helicsFederateEnterExecutingModeAsync(dcFed)
    h.helicsFederateEnterExecutingMode(dFed)
    h.helicsFederateEnterExecutingModeComplete(sFed)
    h.helicsFederateEnterExecutingModeComplete(dcFed)

    q = h.helicsCreateQuery("", "filtered_endpoints")
    filteredEndpoints = h.helicsQueryExecute(q, dFed)
    assert "cloningdestFilter" in str(filteredEndpoints)
    h.helicsQueryFree(q)

    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "dest", data)

    h.helicsFederateFinalize(sFed)

    # TODO: implement threading

    # auto dFedExec = [&]() {
    #     h.helicsFederateRequestTime(dFed, 1.0)
    #     m2 = h.helicsEndpointGetMessage(p2)
    #     h.helicsFederateFinalize(dFed, "")
    # }

    # h.helics_message m3
    # auto dcFedExec = [&]() {
    #     h.helicsFederateRequestTime(dcFed, 2.0)
    #     auto res = h.helicsFederateHasMessage(dcFed)
    #     if (res == h.helics_False) {
    #         std::this_thread::sleep_for(std::chrono::milliseconds(50))
    #         h.helicsFederateRequestTime(dcFed, 4.0)
    #     }
    #     m3 = h.helicsEndpointGetMessage(p3)
    #     h.helicsFederateFinalize(dcFed)
    # }

    # auto threaddFed = std::thread(dFedExec)
    # auto threaddcFed = std::thread(dcFedExec)

    # threaddFed.join()
    # (m2.source, "src")
    # (m2.original_source, "src")
    # (m2.dest, "dest")
    # (m2.length, static_cast<int64_t>(data.size()))

    # threaddcFed.join()

    # (m3.source, "src")
    # (m3.original_source, "src")
    # (m3.dest, "cm")
    # (m3.original_dest, "dest")
    # (m3.length, static_cast<int64_t>(data.size()))

    # (state = h.helicsFederateGetState(sFed))
    # (state == h.helics_state_finalize)

    destroyFederate(sFed, fedinfo1)
    destroyFederate(dFed, fedinfo2)
    destroyFederate(dcFed, fedinfo3)
    destroyBroker(broker)
Ejemplo n.º 16
0
def test_filter_test_types_clone_test_connections():

    broker = createBroker(3)
    sFed, fedinfo1 = createMessageFederate(
        1,
        "source",
        1.0,
    )
    dFed, fedinfo2 = createMessageFederate(1, "dest", 1.0)
    dcFed, fedinfo3 = createMessageFederate(1, "dest_clone", 1.0)

    p1 = h.helicsFederateRegisterGlobalEndpoint(sFed, "src", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(dFed, "dest", "")
    p3 = h.helicsFederateRegisterGlobalEndpoint(dcFed, "cm", "")

    f1 = h.helicsFederateRegisterGlobalCloningFilter(dcFed, "filt1")
    h.helicsFilterAddDeliveryEndpoint(f1, "cm")
    cr = h.helicsFederateGetCoreObject(sFed)

    h.helicsCoreAddSourceFilterToEndpoint(cr, "filt1", "src")
    h.helicsCoreAddSourceFilterToEndpoint(cr, "", "src")

    h.helicsFederateEnterExecutingModeAsync(sFed)
    h.helicsFederateEnterExecutingModeAsync(dcFed)
    h.helicsFederateEnterExecutingMode(dFed)
    h.helicsFederateEnterExecutingModeComplete(sFed)
    h.helicsFederateEnterExecutingModeComplete(dcFed)

    q = h.helicsCreateQuery("", "filtered_endpoints")
    filteredEndpoints = h.helicsQueryExecute(q, sFed)
    assert "srcFilters" in str(filteredEndpoints)
    assert "(cloning)" in str(filteredEndpoints)
    h.helicsQueryFree(q)

    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "dest", data)

    h.helicsFederateRequestTimeAsync(sFed, 1.0)
    h.helicsFederateRequestTimeAsync(dcFed, 1.0)
    h.helicsFederateRequestTime(dFed, 1.0)
    h.helicsFederateRequestTimeComplete(sFed)
    h.helicsFederateRequestTimeComplete(dcFed)

    assert h.helicsFederateHasMessage(dFed) is True

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    assert h.helicsFederateHasMessage(dcFed) is True

    m2 = h.helicsEndpointGetMessage(p3)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "cm"
    assert h.helicsMessageGetOriginalDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    h.helicsFederateFinalizeAsync(sFed)
    h.helicsFederateFinalizeAsync(dFed)
    h.helicsFederateFinalize(dcFed)
    h.helicsFederateFinalizeComplete(sFed)
    h.helicsFederateFinalizeComplete(dFed)
    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(sFed, fedinfo1)
    destroyFederate(dFed, fedinfo2)
    destroyFederate(dcFed, fedinfo3)
    destroyBroker(broker)
Ejemplo n.º 17
0
            source = h.helicsMessageGetOriginalSource(msg)
            logger.debug(f'Received message from endpoint {source}'
                         f' at time {t}'
                         f' with SOC {currentsoc}')

            # Send back charging command based on current SOC
            #   Our very basic protocol:
            #       If the SOC is less than soc_full keep charging (send "1")
            #       Otherwise, stop charging (send "0")
            soc_full = 0.9
            if float(currentsoc) <= soc_full:
                instructions = 1
            else:
                instructions = 0
            message = str(instructions)
            h.helicsEndpointSendMessageRaw(endid, source, message)
            logger.debug(f'Sent message to endpoint {source}'
                         f' at time {t}'
                         f' with payload {instructions}')

            # Store SOC for later analysis/graphing
            if source not in soc:
                soc[source] = []
            soc[source].append(float(currentsoc))

        time_sim.append(t)

        # Since we've dealt with all the messages that are queued, there's
        #   nothing else for the federate to do until/unless another
        #   message comes in. Request a time very far into the future
        #   and take a break until/unless a new message arrives.
Ejemplo n.º 18
0
            else:
                logger.debug(f'\tNo messages at endpoint {endpoint_name} '
                             f'recieved at '
                             f'time {grantedtime}')

            # Publish updated charging voltage
            h.helicsPublicationPublishDouble(pubid[j], charging_voltage[j])
            logger.debug(
                f'\tPublishing charging voltage of {charging_voltage[j]} '
                f' at time {grantedtime}')

            # Send message to Controller with SOC every 15 minutes
            if grantedtime % 900 == 0:
                destination_name = str(
                    h.helicsEndpointGetDefaultDestination(endid[j]))
                h.helicsEndpointSendMessageRaw(
                    endid[j], "", f'{currentsoc[j]:4f}'.encode())  #
                logger.debug(f'Sent message from endpoint {endpoint_name}'
                             f' at time {grantedtime}'
                             f' with payload SOC {currentsoc[j]:4f}')

        # Calculate the total power required by all chargers. This is the
        #   primary metric of interest, to understand the power profile
        #   and capacity requirements required for this charging garage.
        total_power = 0
        for j in range(0, end_count):
            total_power += charge_rate[(EVlist[j] - 1)]

        # Data collection vectors
        time_sim.append(grantedtime)
        power.append(total_power)
Ejemplo n.º 19
0
def test_filter_test_types_function2():

    broker = createBroker(2)
    fFed, fedinfo1 = createMessageFederate(1, "filter")
    mFed, fedinfo2 = createMessageFederate(1, "message")

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "")

    f1 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    h.helicsFilterSet(f1, "delay", 2.5)

    f2 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "filter2")
    h.helicsFilterAddSourceTarget(f2, "port2")
    h.helicsFilterSet(f2, "delay", 2.5)
    # this is expected to fail since a regular filter doesn't have a delivery endpoint
    # @test_throws h.HELICSErrorInvalidObject h.helicsFilterAddDeliveryEndpoint(f2, "port1")

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION

    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    res = h.helicsFederateHasMessage(mFed)
    assert res is False

    h.helicsEndpointSendMessageRaw(p2, "port1", data)
    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False
    # there may be something wrong here yet but this test isn't the one to find it and
    # this may prevent spurious errors for now.
    # std::this_thread::yield()
    h.helicsFederateRequestTime(mFed, 3.0)

    assert h.helicsEndpointHasMessage(p2) is True

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    assert h.helicsEndpointHasMessage(p1) is False

    h.helicsFederateRequestTime(mFed, 4.0)
    assert h.helicsEndpointHasMessage(p1) is True
    h.helicsFederateFinalizeAsync(mFed)
    h.helicsFederateFinalize(fFed)
    h.helicsFederateFinalizeComplete(mFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(fFed, fedinfo1)
    destroyFederate(mFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 20
0
        logger.info('Total Feeder Load is {} + {} j'.format(
            Real_feeder_load, Imag_feeder_load))

        if (Real_feeder_load > feeder_limit_upper):
            logger.info('Total Feeder Load is over the Feeder Upper Limit')
            logger.info('Warning ----> Feeder OverLimit --->  Turn off EV')

            if (k < endpoint_count):
                end = endid["m{}".format(k)]
                end_name = str(h.helicsEndpointGetName(end))
                print(end_name)
                destination_name = (end_name.replace(federate_name,
                                                     distribution_fed_name))
                print('Endpoint Destination {}'.format(destination_name))
                status = h.helicsEndpointSendMessageRaw(
                    end, destination_name, str('0 + 0 j'))
                #status = h.helicsEndpointSendMessageRaw(end, 'NULL', str('0 + 0 j'))
                logger.info('Turning off {}'.format(end_name))
                k = k + 1
            else:
                logger.info('All EVs are Turned off')

        if (Real_feeder_load < feeder_limit_lower):
            logger.info('Total Feeder Load is under the Feeder Lower Limit')
            logger.info('Feeder Can Support EVs ------>  Turn on EV')
            if (k > 0):
                k = k - 1
                end = endid["m{}".format(k)]
                end_name = h.helicsEndpointGetName(end)
                destination_name = (end_name.replace(federate_name,
                                                     distribution_fed_name))
Ejemplo n.º 21
0
    print("Broker created and connected")

fed = h.helicsCreateCombinationFederateFromConfig("sender.json")
my_epid = h.helicsFederateGetEndpoint(fed, "data")

h.helicsFederateEnterExecutingMode(fed)

l = []
for i in range(64, 79):
    l.append(i)
l.append(255)
message = bytes(l)

print(message)

current_time = 0
for i in range(1, 5):
    current_time = h.helicsFederateRequestTime(fed, i)
    print("current time : ", current_time)

    h.helicsEndpointSendMessageRaw(my_epid, "receiver/data", message)
    time.sleep(0.5)

h.helicsFederateFinalize(fed)

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

h.helicsFederateFree(fed)
h.helicsCloseLibrary()
Ejemplo n.º 22
0
def main(delay=None, verbose=False):
    if verbose is not False:
        logger.setLevel(logging.DEBUG)

    mapping = create_mapping()

    logger.info("Creating CombinationFederate for FESTIV")
    fed = create_value_federate()

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

    logger.info("Registering endpoint")
    epid = h.helicsFederateRegisterGlobalEndpoint(fed, "festiv-fixed-price",
                                                  "")
    if delay is not None:
        fedfilter = h.helicsFederateRegisterSourceFilter(
            fed, 1, "festiv-fixed-price", "delay_filter")
        status = h.helicsFilterSet(fedfilter, "delay", int(delay))

    h.helicsFederateEnterExecutionMode(fed)

    time_granted = -1
    last_second = -1
    ticker = 0

    for day in [
            '2020-08-03',
            '2020-08-04',
            '2020-08-05',
            '2020-08-06',
            '2020-08-07',
            '2020-08-08',
            '2020-08-09',
    ]:

        logger.info("Running DAM for day={day}".format(day=day))
        df = get_load(day)
        dam_s = df.loc[day, 'LOAD'].resample('1H').mean()

        dam_m = build_DAM_model(day, dam_s)
        dam_m.solve('cbc', verbose=False)

        rtm_s = df.loc[day, 'LOAD'].resample('5T').mean()

        for interval in range(0, int(24 * 60 / 5)):
            hour = int(interval * 5 / 60)
            logger.info(
                "Running RTM for day={day} for minute={m} (hour={hour})".
                format(day=day, m=interval * 5, hour=hour))
            commitment = dam_m.results.unit_commitment.loc[hour:hour, :]
            rtm_m = build_RTM_model(day, rtm_s.iloc[interval], commitment)
            rtm_m.solve('cbc', verbose=False)
            logger.debug("LMP = {lmp} \t Power Generated = {pg}".format(
                lmp=rtm_m.results.lmp, pg=rtm_m.results.power_generated))

            for minute in range(0, 5):

                for second in range(0, 60):
                    ticker = ticker + 1

                    if int(second % 6) == 0:
                        stop_at_time = ticker
                        while time_granted < stop_at_time:
                            status, time_granted = h.helicsFederateRequestTime(
                                fed, stop_at_time)

                        b2, b3, b4 = rtm_m.results.lmp[['B2', 'B3',
                                                        'B4']].values[0]
                        for name in mapping["B2"]:
                            status = h.helicsEndpointSendMessageRaw(
                                epid, "{}/fixed_price".format(name), str(b2))
                        for name in mapping["B3"]:
                            status = h.helicsEndpointSendMessageRaw(
                                epid, "{}/fixed_price".format(name), str(b3))
                        for name in mapping["B4"]:
                            status = h.helicsEndpointSendMessageRaw(
                                epid, "{}/fixed_price".format(name), str(b4))

                        pg = rtm_m.results.power_generated.loc[0].to_dict()

                        status = h.helicsPublicationPublishDouble(
                            pubid1, pg["ALTA"])
                        status = h.helicsPublicationPublishDouble(
                            pubid2, pg["BRIGHTON"])
                        status = h.helicsPublicationPublishDouble(
                            pubid3, pg["PARKCITY"])
                        status = h.helicsPublicationPublishDouble(
                            pubid4, pg["SOLITUDE"])
                        status = h.helicsPublicationPublishDouble(
                            pubid5, pg["SUNDANCE"])

                        logger.info("Publishing lmp B2={}".format(b2))
                        logger.info("Publishing lmp B3={}".format(b2))
                        logger.info("Publishing lmp B4={}".format(b2))

                        logger.info("Publishing pg = {}".format(pg))
                        logger.info("Current time = {minutes} ".format(
                            minutes=ticker / 60))
Ejemplo n.º 23
0
    while t < total_interval:

        for j in range(0, len(enddest_EVsoc)):
            # 1. Receive SOC
            # print('endpt name: ',h.helicsEndpointGetName(end_EVsoc[j]))
            if h.helicsEndpointHasMessage(end_EVsoc[j]):
                msg = h.helicsEndpointGetMessageObject(end_EVsoc[j])
                currentsoc = h.helicsMessageGetString(msg)
                # print('currentsoc: ',currentsoc)
                # 2. Send instructions
                # destination_name = str(h.helicsEndpointGetDefaultDestination(end_EVsoc[j]))
                print(t / 3600, currentsoc)
                if float(currentsoc) <= 0.9:
                    instructions = 1
                else:
                    instructions = 0
                message = str(instructions)
                h.helicsEndpointSendMessageRaw(end_EVsoc[j], "", message)  #
                # print('Sent instructions: {}'.format(instructions))
            else:
                print("NO MESSAGE RECEIVED AT TIME ", t / 3600)

        grantedtime = h.helicsFederateRequestTime(fed, (t + update_interval))
        # print('EV time: ',grantedtime/3600)

        t = grantedtime

    # logger.info("Destroying federate")
    destroy_federate(fed)
    # logger.info("Done!")
Ejemplo n.º 24
0
        logger.info("Total Feeder Load is {} + {} j".format(Real_feeder_load, Imag_feeder_load))

        if Real_feeder_load > feeder_limit_upper:
            logger.info("Total Feeder Load is over the Feeder Upper Limit")
            logger.info("Warning ----> Feeder OverLimit --->  Turn off EV")

            if k < endpoint_count:
                end = endid["m{}".format(k)]
                logger.info("endid: {}".format(endid))
                end_name = str(h.helicsEndpointGetName(end))
                logger.info("Sending endpoint name: {}".format(end_name))
                destination_name = end_name.replace(federate_name, distribution_fed_name)
                logger.info(
                    "Endpoint destination: {}".format(h.helicsEndpointGetDefaultDestination(end))
                )
                status = h.helicsEndpointSendMessageRaw(end, "", str("0 + 0 j"))  #
                logger.info("Endpoint sending status: {}".format(status))
                logger.info("Turning off {}".format(end_name))
                k = k + 1
            else:
                logger.info("All EVs are Turned off")

        if Real_feeder_load < feeder_limit_lower:
            logger.info("Total Feeder Load is under the Feeder Lower Limit")
            logger.info("Feeder Can Support EVs ------>  Turn on EV")
            if k > 0:
                k = k - 1
                end = endid["m{}".format(k)]
                end_name = h.helicsEndpointGetName(end)
                destination_name = end_name.replace(federate_name, distribution_fed_name)
                print("Endpoint Destination {}".format(destination_name))
Ejemplo n.º 25
0
def run_cosim(fed, endid):

    # The event queue ("eq") is the master list of events that the filter
    #   federates works on. In this simple filter federate, each event
    #   will be a dictionary with a few parameters:
    #       'dest' - destination of message
    #       'time' - time when the message should be sent on to its
    #               intended destination
    #       'payload' - content of the message being sent
    #
    #   When eq is empty, there are no messages being
    #   filtered by the federate. When there are events in the queue it
    #   indicates the filter federate has messages it is holding onto
    #   that it needs to forward on (at the indicated time).
    #
    eq = []

    h.helicsFederateEnterExecutingMode(fed)
    logger.info('Entered HELICS execution mode')

    hours = 24 * 7  # one week
    total_interval = int(60 * 60 * hours)

    # Blocking call for a time request at max simulation time
    fake_max_time = int(h.HELICS_TIME_MAXTIME / 1000)
    starttime = fake_max_time
    logger.debug(f'Requesting initial time {starttime}')
    grantedtime = h.helicsFederateRequestTime(fed, starttime)
    logger.debug(f'Granted time {grantedtime}')

    while grantedtime < total_interval:
        # In HELICS, when multiple messages arrive at an endpoint they
        # queue up and are popped off one-by-one with the
        #   "helicsEndpointHasMessage" API call. When that API doesn't
        #   return a message, you've processed them all.
        while h.helicsEndpointHasMessage(endid):
            msg = h.helicsEndpointGetMessage(endid)
            msg_str = h.helicsMessageGetString(msg)
            source = h.helicsMessageGetOriginalSource(msg)
            dest = h.helicsMessageGetOriginalDestination(msg)
            time = h.helicsMessageGetTime(msg)
            logger.debug(f'Received message from endpoint {source}'
                         f' to endpoint {dest}'
                         f' at time {grantedtime}'
                         f' with message {msg_str}')
            event = {
                "payload": msg_str,
                "source": source,
                "dest": dest,
                "time": time
            }
            eq = filter_message(eq, event, 'delay')
            if source == 'EVController_federate/endpoint':
                eq = filter_message(eq, event, 'hack')

        # Sort event queue to get it back in order
        eq = sorted(eq, key=itemgetter('time'))

        # Acting on any events that need to be dequeued
        # Running interference filter. This filter has the ability to
        #   remove events from eq. We may not have any messages to send
        #   after interference runs
        event = eq[0]
        eq = filter_message(eq, event, 'interfere')

        # After filtering, send all messages whose time has come (or past;
        #   in which case something has gone wrong)
        while eq and eq[0]['time'] <= grantedtime:
            h.helicsEndpointSendMessageRaw(endid, eq[0]['dest'],
                                           eq[0]['payload'].encode())
            logger.debug(f'Sent message from endpoint {endid}'
                         f' to endpoint {eq[0]["dest"]}'
                         f' at time {grantedtime}'
                         f' with message {eq[0]["payload"]}')
            del eq[0]

        if eq:
            # Event queue not empty, need to schedule filter federate to
            #   run again when its time to deliver the next message in the
            #   queue
            requested_time = eq[0]['time']
        else:
            # If no events in queue, schedule run for end of simulation.
            #   Filter federate will be granted an earlier time if a
            #   message is rerouted to the filter federate.
            requested_time = fake_max_time
        logger.debug(f'Requesting time {requested_time}')
        grantedtime = h.helicsFederateRequestTime(fed, requested_time)
        logger.debug(f'Granted time {grantedtime}')
Ejemplo n.º 26
0
            source = h.helicsMessageGetOriginalSource(msg)
            logger.debug(f'Received message from endpoint {source}'
                         f' at time {grantedtime}'
                         f' with SOC {currentsoc}')

            # Send back charging command based on current SOC
            #   Our very basic protocol:
            #       If the SOC is less than soc_full keep charging (send "1")
            #       Otherwise, stop charging (send "0")
            soc_full = 0.95
            if float(currentsoc) <= soc_full:
                instructions = 1
            else:
                instructions = 0
            message = str(instructions)
            h.helicsEndpointSendMessageRaw(endid, source, message.encode())
            logger.debug(f'Sent message to endpoint {source}'
                         f' at time {grantedtime}'
                         f' with payload {instructions}')

            # Store SOC for later analysis/graphing
            if source not in soc:
                soc[source] = []
            soc[source].append(float(currentsoc))

        time_sim.append(grantedtime)

        # Since we've dealt with all the messages that are queued, there's
        #   nothing else for the federate to do until/unless another
        #   message comes in. Request a time very far into the future
        #   and take a break until/unless a new message arrives.
Ejemplo n.º 27
0
import helics as h
from math import pi

print("about to read file")
fed = h.helicsCreateMessageFederateFromConfig("config1.json")
print("read file")

epid = h.helicsFederateGetEndpointByIndex(fed, 0)
ep_name = h.helicsEndpointGetName(epid)
print(ep_name)

h.helicsFederateEnterExecutingMode(fed)

this_time = 0.0
value = pi

for t in range(1, 11):
    val = value * t
    currenttime = h.helicsFederateRequestTime(fed, t)
    h.helicsEndpointSendMessageRaw(epid, "end2", str(val))
    print("PI SENDER: Sending value pi = {} at time {} to PI RECEIVER".format(
        val, currenttime))

#h.helicsFederateRequestTime(fed, 10000)

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

h.helicsFederateFree(fed)
h.helicsCloseLibrary()
Ejemplo n.º 28
0
def test_filter_test_types_message_filter_function3():

    broker = createBroker(2)
    fFed, fedinfo1 = createMessageFederate(1, "filter", 1)
    mFed, fedinfo2 = createMessageFederate(1, "message", 1)

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "random")

    f1 = h.helicsFederateRegisterGlobalFilter(fFed,
                                              h.HELICS_FILTER_TYPE_CUSTOM,
                                              "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    f2 = h.helicsFederateRegisterGlobalFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                              "filter2")
    h.helicsFilterAddSourceTarget(f2, "port1")

    h.helicsFederateRegisterEndpoint(fFed, "fout", "")
    f3 = h.helicsFederateRegisterFilter(fFed,
                                        h.HELICS_FILTER_TYPE_RANDOM_DELAY,
                                        "filter3")
    h.helicsFilterAddSourceTarget(f3, "filter0/fout")

    h.helicsFilterSet(f2, "delay", 2.5)

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION

    data = "hello world".encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsFederateHasMessage(mFed) is False

    h.helicsEndpointSendMessageRaw(p2, "port1", data)
    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False
    # there may be something wrong here yet but this test isn't the one to find it and
    # this may prevent spurious errors for now.
    # std::this_thread::yield()
    h.helicsFederateRequestTimeAsync(mFed, 3.0)
    h.helicsFederateRequestTime(fFed, 3.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsEndpointHasMessage(p2)

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    assert h.helicsEndpointHasMessage(p1) is True
    h.helicsFederateFinalize(mFed)
    h.helicsFederateFinalize(fFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(mFed, fedinfo1)
    destroyFederate(fFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 29
0
        logger.info('Total Feeder Load is {} + {} j'.format(
            Real_feeder_load, Imag_feeder_load))

        if (Real_feeder_load > feeder_limit_upper):
            logger.info('Total Feeder Load is over the Feeder Upper Limit')
            logger.info('Warning ----> Feeder OverLimit --->  Turn off EV')

            if (k < endpoint_count):
                end = endid["m{}".format(k)]
                end_name = str(h.helicsEndpointGetName(end))
                print(end_name)
                destination_name = (end_name.replace(federate_name,
                                                     distribution_fed_name))
                print('Endpoint Destination {}'.format(destination_name))
                #status = h.helicsEndpointSendMessageRaw(end, destination_name, str('0 + 0 j'))
                status = h.helicsEndpointSendMessageRaw(
                    end, 'NULL', str('0 + 0 j'))
                logger.info('Turning off {}'.format(end_name))
                k = k + 1
            else:
                logger.info('All EVs are Turned off')

        if (Real_feeder_load < feeder_limit_lower):
            logger.info('Total Feeder Load is under the Feeder Lower Limit')
            logger.info('Feeder Can Support EVs ------>  Turn on EV')
            if (k > 0):
                k = k - 1
                end = endid["m{}".format(k)]
                end_name = h.helicsEndpointGetName(end)
                destination_name = (end_name.replace(federate_name,
                                                     distribution_fed_name))
                print('Endpoint Destination {}'.format(destination_name))
Ejemplo n.º 30
0
def test_filter_test_types_clone_test():

    broker = createBroker(3)
    sFed, fedinfo1 = createMessageFederate(1, "source", 1)
    dFed, fedinfo2 = createMessageFederate(1, "dest", 1)
    dcFed, fedinfo3 = createMessageFederate(1, "dest_clone", 1)

    p1 = h.helicsFederateRegisterGlobalEndpoint(sFed, "src", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(dFed, "dest", "")
    p3 = h.helicsFederateRegisterGlobalEndpoint(dcFed, "cm", "")

    f1 = h.helicsFederateRegisterCloningFilter(dcFed, "")
    h.helicsFilterAddDeliveryEndpoint(f1, "cm")
    h.helicsFilterAddSourceTarget(f1, "src")

    h.helicsFederateEnterExecutingModeAsync(sFed)
    h.helicsFederateEnterExecutingModeAsync(dcFed)
    h.helicsFederateEnterExecutingMode(dFed)
    h.helicsFederateEnterExecutingModeComplete(sFed)
    h.helicsFederateEnterExecutingModeComplete(dcFed)

    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_EXECUTION
    state = h.helicsFederateGetState(dcFed)
    assert state == h.HELICS_STATE_EXECUTION
    state = h.helicsFederateGetState(dFed)
    assert state == h.HELICS_STATE_EXECUTION

    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "dest", data)

    h.helicsFederateRequestTimeAsync(sFed, 1.0)
    h.helicsFederateRequestTimeAsync(dcFed, 1.0)
    h.helicsFederateRequestTime(dFed, 1.0)
    h.helicsFederateRequestTimeComplete(sFed)
    h.helicsFederateRequestTimeComplete(dcFed)

    assert h.helicsFederateHasMessage(dFed)

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    assert h.helicsFederateHasMessage(dcFed)

    m2 = h.helicsEndpointGetMessage(p3)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "cm"
    assert h.helicsMessageGetOriginalDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    h.helicsFederateFinalizeAsync(sFed)
    h.helicsFederateFinalizeAsync(dFed)
    h.helicsFederateFinalize(dcFed)
    h.helicsFederateFinalizeComplete(sFed)
    h.helicsFederateFinalizeComplete(dFed)
    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(sFed, fedinfo1)
    destroyFederate(dFed, fedinfo2)
    destroyFederate(dcFed, fedinfo3)
    destroyBroker(broker)