def test_query_broker_tests(): broker = createBroker(2) vFed1, fedinfo1 = createValueFederate(1, "fed0") vFed2, fedinfo2 = createValueFederate(1, "fed1") core = h.helicsFederateGetCoreObject(vFed1) q1 = h.helicsCreateQuery("root", "federates") res = h.helicsQueryCoreExecute(q1, core) name1 = h.helicsFederateGetName(vFed1) name2 = h.helicsFederateGetName(vFed2) try: assert f"[{name1};{name2}]" == res except AssertionError: assert [name1, name2] == res res = h.helicsQueryExecute(q1, vFed1) try: assert f"[{name1};{name2}]" == res except AssertionError: assert [name1, name2] == res h.helicsFederateEnterInitializingModeAsync(vFed1) h.helicsFederateEnterInitializingMode(vFed2) h.helicsFederateEnterInitializingModeComplete(vFed1) h.helicsQueryFree(q1) h.helicsCoreFree(core) h.helicsFederateFinalizeAsync(vFed1) h.helicsFederateFinalize(vFed2) h.helicsFederateFinalizeComplete(vFed1) destroyFederate(vFed1, fedinfo1) destroyFederate(vFed2, fedinfo2) destroyBroker(broker)
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()
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()
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()
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 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 configure_federate(): fed = h.helicsCreateMessageFederateFromConfig("FilterConfig.json") federate_name = h.helicsFederateGetName(fed) logger.info(f'Created federate {federate_name}') # Diagnostics to confirm JSON config correctly added the required # endpoints end_count = h.helicsFederateGetEndpointCount(fed) logger.debug(f'\tNumber of endpoints: {end_count}') endid = h.helicsFederateGetEndpointByIndex(fed, 0) end_name = h.helicsEndpointGetName(endid) logger.debug("Registered Endpoint ---> {}".format(end_name)) return fed, endid
def test_bad_inputs_core_link(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") # register the publications h.helicsFederateRegisterGlobalTypePublication(vFed1, "pub1", "custom1", "") h.helicsFederateRegisterTypeInput(vFed1, "inp1", "custom2", "") fed2 = h.helicsGetFederateByName(h.helicsFederateGetName(vFed1)) assert h.helicsFederateGetName(fed2) == h.helicsFederateGetName(vFed1) # @test_throws h.HELICSErrorInvalidArgument with pt.raises(h.HelicsException): fed3 = h.helicsGetFederateByName("fed_unknown") cr = h.helicsFederateGetCoreObject(vFed1) h.helicsCoreDataLink(cr, "pub1", "fed0/inp1") # @test_throws h.HELICSErrorInvalidArgument with pt.raises(h.HelicsException): h.helicsCoreMakeConnections(cr, "unknownfile.json") # TODO: This test should throw an error # @test_throws h.HELICSErrorInvalidArgument h.helicsCoreDataLink(cr, "pub1", "") # @test_broken False cr2 = h.helicsCoreClone(cr) assert h.helicsCoreGetAddress(cr2) == h.helicsCoreGetAddress(cr) # TODO: this should error as well # h.helicsFederateEnterExecutingMode(vFed1) # @test_broken False h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
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()
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()
def init_logger(config_file_name, log_out_file_name, total_simulation_time, individual_simulation_time): print("logger in") fed = h.helicsCreateMessageFederateFromConfig(config_file_name) print("logger passed config") 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/{}".format(log_out_file_name), filemode='w', format='%(message)s', level=log.INFO) print(fed_name, " about to Started") h.helicsFederateEnterExecutingMode(fed) print(fed_name, "Started") 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) # log.log(str(message.messageID)) output = output + str(message.data) + "message id: " + "\n" log.info(output) h.helicsFederateFinalize(fed) print(fed_name, " : Federate finalized") h.helicsFederateFree(fed) h.helicsCloseLibrary()
mu = 0 sigma = 0.2 noise = np.random.normal(mu, sigma) measured_A = charging_A + noise measured_R = charging_V / measured_A SOC_estimate = np.interp(measured_R, effective_R, socs) return SOC_estimate if __name__ == "__main__": np.random.seed(1490) ############## Registering federate from json ########################## fed = h.helicsCreateCombinationFederateFromConfig("ChargerConfig.json") federate_name = h.helicsFederateGetName(fed) logger.info(f'Created federate {federate_name}') end_count = h.helicsFederateGetEndpointCount(fed) logger.info(f'\tNumber of endpoints: {end_count}') sub_count = h.helicsFederateGetInputCount(fed) logger.info(f'\tNumber of subscriptions: {sub_count}') pub_count = h.helicsFederateGetPublicationCount(fed) logger.info(f'\tNumber of publications: {pub_count}') print(f'Created federate {federate_name}') print(f'\tNumber of endpoints: {end_count}') print(f'\tNumber of subscriptions: {sub_count}') print(f'\tNumber of publications: {pub_count}') # Diagnostics to confirm JSON config correctly added the required # endpoints, publications, and subscriptions. endid = {}
def test_bad_inputs_input_tests(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") # register the publications pubid = h.helicsFederateRegisterGlobalPublication( vFed1, "pub1", h.HELICS_DATA_TYPE_DOUBLE, "") subid = h.helicsFederateRegisterInput(vFed1, "inp1", h.HELICS_DATA_TYPE_DOUBLE, "") # @test_throws h.HELICSErrorRegistrationFailure with pt.raises(h.HelicsException): subid2 = h.helicsFederateRegisterInput(vFed1, "inp1", h.HELICS_DATA_TYPE_DOUBLE, "") h.helicsInputAddTarget(subid, "pub1") vf2 = h.helicsFederateClone(vFed1) assert h.helicsFederateGetName(vFed1) == h.helicsFederateGetName(vf2) h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0) # @test_throws h.HELICSErrorInvalidObject with pt.raises(h.HelicsException): ept = h.helicsFederateRegisterEndpoint(vFed1, "ept1", "") h.helicsFederateEnterInitializingMode(vFed1) h.helicsPublicationPublishDouble(pubid, 27.0) comp = h.helicsFederateEnterExecutingModeIterative( vFed1, h.HELICS_ITERATION_REQUEST_FORCE_ITERATION) assert comp == h.HELICS_ITERATION_RESULT_ITERATING val = h.helicsInputGetDouble(subid) assert val == 27.0 valt = h.helicsInputGetTime(subid) assert valt == 27.0 comp = h.helicsFederateEnterExecutingModeIterative( vFed1, h.HELICS_ITERATION_REQUEST_ITERATE_IF_NEEDED) assert comp == h.HELICS_ITERATION_RESULT_NEXT_STEP val2 = h.helicsInputGetDouble(subid) assert val2 == val # expect error entering initializing Mode again # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsFederateEnterInitializingMode(vFed1) # expect error entering initializing Mode again # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsFederateEnterInitializingModeAsync(vFed1) # expect error entering initializing Mode again # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsFederateEnterInitializingModeComplete(vFed1) h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
def test_misc_api(): fedInfo1 = h.helicsCreateFederateInfo() h.helicsFederateInfoSetCoreInitString(fedInfo1, "-f 1") h.helicsFederateInfoSetCoreName(fedInfo1, "core3") h.helicsFederateInfoSetCoreType(fedInfo1, 3) h.helicsFederateInfoSetCoreTypeFromString(fedInfo1, "zmq") h.helicsFederateInfoSetFlagOption(fedInfo1, 1, True) h.helicsFederateInfoSetTimeProperty(fedInfo1, h.HELICS_PROPERTY_TIME_INPUT_DELAY, 1.0) h.helicsFederateInfoSetIntegerProperty(fedInfo1, h.HELICS_PROPERTY_INT_LOG_LEVEL, 1) h.helicsFederateInfoSetIntegerProperty( fedInfo1, h.HELICS_PROPERTY_INT_MAX_ITERATIONS, 100) h.helicsFederateInfoSetTimeProperty(fedInfo1, h.HELICS_PROPERTY_TIME_OUTPUT_DELAY, 1.0) h.helicsFederateInfoSetTimeProperty(fedInfo1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0) h.helicsFederateInfoSetTimeProperty(fedInfo1, h.HELICS_PROPERTY_TIME_DELTA, 1.0) h.helicsFederateInfoSetTimeProperty(fedInfo1, h.HELICS_PROPERTY_TIME_OFFSET, 0.1) h.helicsFederateInfoFree(fedInfo1) broker3 = h.helicsCreateBroker("zmq", "broker3", "--federates 1 --loglevel 1") fedInfo2 = h.helicsCreateFederateInfo() coreInitString = "--federates 1" h.helicsFederateInfoSetCoreInitString(fedInfo2, coreInitString) h.helicsFederateInfoSetCoreTypeFromString(fedInfo2, "zmq") h.helicsFederateInfoSetIntegerProperty(fedInfo2, h.HELICS_PROPERTY_INT_LOG_LEVEL, 1) h.helicsFederateInfoSetTimeProperty(fedInfo2, h.HELICS_PROPERTY_TIME_DELTA, 1.0) fed1 = h.helicsCreateCombinationFederate("fed1", fedInfo2) fed2 = h.helicsFederateClone(fed1) _ = h.helicsGetFederateByName("fed1") h.helicsFederateSetFlagOption(fed2, 1, False) h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_INPUT_DELAY, 1.0) h.helicsFederateSetIntegerProperty(fed1, h.HELICS_PROPERTY_INT_LOG_LEVEL, 1) h.helicsFederateSetIntegerProperty(fed2, h.HELICS_PROPERTY_INT_MAX_ITERATIONS, 100) h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_OUTPUT_DELAY, 1.0) h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_PERIOD, 0.0) h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_DELTA, 1.0) _ = h.helicsFederateRegisterCloningFilter(fed1, "fed1/Ep1") fed1DestinationFilter = h.helicsFederateRegisterFilter( fed1, h.HELICS_FILTER_TYPE_DELAY, "fed1DestinationFilter") h.helicsFilterAddDestinationTarget(fed1DestinationFilter, "Ep2") ep1 = h.helicsFederateRegisterEndpoint(fed1, "Ep1", "string") ep2 = h.helicsFederateRegisterGlobalEndpoint(fed1, "Ep2", "string") pub1 = h.helicsFederateRegisterGlobalPublication(fed1, "pub1", h.HELICS_DATA_TYPE_DOUBLE, "") pub2 = h.helicsFederateRegisterGlobalTypePublication( fed1, "pub2", "complex", "") sub1 = h.helicsFederateRegisterSubscription(fed1, "pub1") sub2 = h.helicsFederateRegisterSubscription(fed1, "pub2") h.helicsInputAddTarget(sub2, "Ep2") pub3 = h.helicsFederateRegisterPublication(fed1, "pub3", h.HELICS_DATA_TYPE_STRING, "") pub1KeyString = h.helicsPublicationGetKey(pub1) pub1TypeString = h.helicsPublicationGetType(pub1) pub1UnitsString = h.helicsPublicationGetUnits(pub1) sub1KeyString = h.helicsSubscriptionGetKey(sub1) sub1UnitsString = h.helicsInputGetUnits(sub1) assert "pub1" == pub1KeyString assert "double" == pub1TypeString assert "" == pub1UnitsString assert "pub1" == sub1KeyString assert "" == sub1UnitsString fed1SourceFilter = h.helicsFederateRegisterFilter( fed1, h.HELICS_FILTER_TYPE_DELAY, "fed1SourceFilter") h.helicsFilterAddSourceTarget(fed1SourceFilter, "Ep2") h.helicsFilterAddDestinationTarget(fed1SourceFilter, "fed1/Ep1") h.helicsFilterRemoveTarget(fed1SourceFilter, "fed1/Ep1") h.helicsFilterAddSourceTarget(fed1SourceFilter, "Ep2") h.helicsFilterRemoveTarget(fed1SourceFilter, "Ep2") fed1SourceFilterNameString = h.helicsFilterGetName(fed1SourceFilter) assert fed1SourceFilterNameString == "fed1/fed1SourceFilter" sub3 = h.helicsFederateRegisterSubscription(fed1, "fed1/pub3", "") pub4 = h.helicsFederateRegisterTypePublication(fed1, "pub4", "int", "") sub4 = h.helicsFederateRegisterSubscription(fed1, "fed1/pub4", "") pub5 = h.helicsFederateRegisterGlobalTypePublication( fed1, "pub5", "boolean", "") sub5 = h.helicsFederateRegisterSubscription(fed1, "pub5", "") pub6 = h.helicsFederateRegisterGlobalPublication(fed1, "pub6", h.HELICS_DATA_TYPE_VECTOR, "") sub6 = h.helicsFederateRegisterSubscription(fed1, "pub6", "") pub7 = h.helicsFederateRegisterGlobalPublication( fed1, "pub7", h.HELICS_DATA_TYPE_NAMED_POINT, "") sub7 = h.helicsFederateRegisterSubscription(fed1, "pub7", "") assert """helics.HelicsPublication(name = "pub1", type = "double", units = "", info = "")""" in repr( pub1) assert """helics.HelicsPublication(name = "pub2", type = "complex", units = "", info = "")""" in repr( pub2) assert """helics.HelicsPublication(name = "fed1/pub3", type = "string", units = "", info = "")""" in repr( pub3) assert """helics.HelicsPublication(name = "fed1/pub4", type = "int", units = "", info = "")""" in repr( pub4) assert """helics.HelicsPublication(name = "pub5", type = "boolean", units = "", info = "")""" in repr( pub5) assert """helics.HelicsPublication(name = "pub6", type = "double_vector", units = "", info = "")""" in repr( pub6) assert """helics.HelicsPublication(name = "pub7", type = "named_point", units = "", info = "")""" in repr( pub7) assert ( """helics.HelicsInput(name = "_input_18", units = "", injection_units = "", publication_type = "", type = "", target = "pub7", info = "")""" in repr(sub7)) h.helicsInputSetDefaultBoolean(sub5, False) h.helicsInputSetDefaultComplex(sub2, -9.9 + 2.5j) h.helicsInputSetDefaultDouble(sub1, 3.4) h.helicsInputSetDefaultInteger(sub4, 6) h.helicsInputSetDefaultNamedPoint(sub7, "hollow", 20.0) h.helicsInputSetDefaultString(sub3, "default") sub6Default = [3.4, 90.9, 4.5] h.helicsInputSetDefaultVector(sub6, sub6Default) h.helicsEndpointSubscribe(ep2, "fed1/pub3") h.helicsFederateEnterInitializingModeAsync(fed1) rs = h.helicsFederateIsAsyncOperationCompleted(fed1) if rs == 0: time.sleep(0.500) rs = h.helicsFederateIsAsyncOperationCompleted(fed1) if rs == 0: time.sleep(0.500) rs = h.helicsFederateIsAsyncOperationCompleted(fed1) if rs == 0: assert True is False h.helicsFederateEnterInitializingModeComplete(fed1) h.helicsFederateEnterExecutingModeAsync(fed1) h.helicsFederateEnterExecutingModeComplete(fed1) assert ( """helics.HelicsInput(name = "_input_18", units = "", injection_units = "", publication_type = "named_point", type = "", target = "pub7", info = "")""" in repr(sub7)) mesg1 = h.helicsFederateCreateMessage(fed1) h.helicsMessageSetString(mesg1, "Hello") h.helicsMessageSetSource(mesg1, "fed1/Ep1") h.helicsMessageSetOriginalSource(mesg1, "fed1/Ep1") h.helicsMessageSetDestination(mesg1, "Ep2") h.helicsMessageSetOriginalDestination(mesg1, "Ep2") h.helicsEndpointSendMessage(ep1, mesg1) mesg1 = h.helicsFederateCreateMessage(fed1) h.helicsMessageSetString(mesg1, "There") h.helicsMessageSetSource(mesg1, "fed1/Ep1") h.helicsMessageSetOriginalSource(mesg1, "fed1/Ep1") h.helicsMessageSetDestination(mesg1, "Ep2") h.helicsMessageSetOriginalDestination(mesg1, "Ep2") h.helicsEndpointSendMessage(ep1, mesg1) h.helicsEndpointSetDefaultDestination(ep2, "fed1/Ep1") ep1NameString = h.helicsEndpointGetName(ep1) ep1TypeString = h.helicsEndpointGetType(ep1) assert ep1NameString == "fed1/Ep1" assert ep1TypeString == "string" _ = h.helicsFederateGetCoreObject(fed1) fed1Time = h.helicsFederateGetCurrentTime(fed1) assert fed1Time == 0.0 fed1EndpointCount = h.helicsFederateGetEndpointCount(fed1) assert fed1EndpointCount == 2 fed1NameString = h.helicsFederateGetName(fed1) assert fed1NameString == "fed1" fed1State = h.helicsFederateGetState(fed1) assert fed1State == 2 fed1PubCount = h.helicsFederateGetPublicationCount(fed1) assert fed1PubCount == 7 fed1SubCount = h.helicsFederateGetInputCount(fed1) assert fed1SubCount == 7 h.helicsPublicationPublishBoolean(pub5, True) h.helicsPublicationPublishComplex(pub2, 5.6 + -0.67j) h.helicsPublicationPublishDouble(pub1, 457.234) h.helicsPublicationPublishInteger(pub4, 1) h.helicsPublicationPublishNamedPoint(pub7, "Blah Blah", 20.0) h.helicsPublicationPublishString(pub3, "Mayhem") pub6Vector = [4.5, 56.5] h.helicsPublicationPublishVector(pub6, pub6Vector) time.sleep(0.500) h.helicsFederateRequestTimeAsync(fed1, 1.0) returnTime = h.helicsFederateRequestTimeComplete(fed1) assert returnTime == 1.0 ep2MsgCount = h.helicsEndpointPendingMessages(ep2) assert ep2MsgCount == 2 ep2HasMsg = h.helicsEndpointHasMessage(ep2) assert ep2HasMsg == 1 msg2 = h.helicsEndpointGetMessage(ep2) assert h.helicsMessageGetTime(msg2) == 1.0 assert h.helicsMessageGetString(msg2) == "Hello" assert h.helicsMessageGetOriginalSource(msg2) == "fed1/Ep1" assert h.helicsMessageGetSource(msg2) == "fed1/Ep1" assert h.helicsMessageGetDestination(msg2) == "Ep2" assert h.helicsMessageGetOriginalDestination(msg2) == "Ep2" fed1MsgCount = h.helicsFederatePendingMessages(fed1) assert fed1MsgCount == 1 assert h.helicsFederateHasMessage(fed1) == 1 msg3 = h.helicsFederateGetMessage(fed1) assert h.helicsMessageGetTime(msg3) == 1.0 assert h.helicsMessageGetString(msg3) == "There" assert h.helicsMessageGetOriginalSource(msg3) == "fed1/Ep1" assert h.helicsMessageGetSource(msg3) == "fed1/Ep1" assert h.helicsMessageGetDestination(msg3) == "Ep2" assert h.helicsMessageGetOriginalDestination(msg3) == "Ep2" sub1Updated = h.helicsInputIsUpdated(sub1) # TODO: figure out why this test is broken assert sub1Updated is False # TODO: figure out why this test is broken assert h.helicsInputLastUpdateTime(sub2) == 0.0 # assert h.helicsInputGetComplex(sub2) == 5.6 - 0.67j # assert h.helicsInputGetDouble(sub1) == 457.234 # assert h.helicsInputGetInteger(sub4) == 1 sub7PointString, sub7DoubleValue = h.helicsInputGetNamedPoint(sub7) # assert sub7PointString == "Blah Blah" assert sub7DoubleValue == 20.0 # assert h.helicsInputGetBoolean(sub5) == True # assert h.helicsInputGetString(sub3) == "Mayhem" sub3ValueSize = h.helicsInputGetRawValueSize(sub3) # assert sub3ValueSize == 6 # assert h.helicsInputGetVector(sub6) == [4.5, 56.5] h.helicsFederateFinalize(fed1) h.helicsFederateFinalize(fed2) h.helicsFederateFree(fed1) h.helicsFederateFinalize(fed2) h.helicsFederateFree(fed2) h.helicsFederateInfoFree(fedInfo2) h.helicsBrokerDisconnect(broker3) h.helicsBrokerFree(broker3) h.helicsCleanupLibrary() h.helicsCloseLibrary()
def federate_example(config_path): # Registering federate from json try: fed = h.helicsCreateCombinationFederateFromConfig(config_path) except h._helics.HelicsException as exc: print("Exception occured".format(exc)) exit(-1) federate_name = h.helicsFederateGetName(fed) print(federate_name) endpoint_count = h.helicsFederateGetEndpointCount(fed) subkeys_count = h.helicsFederateGetInputCount(fed) pubkeys_count = h.helicsFederateGetPublicationCount(fed) # Reference to Publications and Subscription form index endid = {} subid = {} pubid = {} for i in range(0,endpoint_count): endid["m{}".format(i)] = h.helicsFederateGetEndpointByIndex(fed, i) end_name = h.helicsEndpointGetName(endid["m{}".format(i)]) logger.info( 'Registered Endpoint ---> {}'.format(end_name)) for i in range(0, subkeys_count): idx = h.helicsFederateGetInputByIndex(fed, i) subid["m{}".format(i)] = idx status = h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0) sub_key = h.helicsSubscriptionGetKey(idx) logger.info( 'Registered Subscription ---> {}'.format(sub_key)) for i in range(0, pubkeys_count): idx = h.helicsFederateGetPublicationByIndex(fed, i) pubid["m{}".format(i)] = idx pub_key = h.helicsPublicationGetKey(idx) logger.info( 'Registered Publications ---> {}'.format(pub_key)) print('###############################################################################################') print('######################## Entering Execution Mode ##########################################') # Entering Execution Mode h.helicsFederateEnterExecutingMode(fed) print('###############################################################################################') hours = 0.1 total_inteval = int(60 * 60 * hours) grantedtime = -1 update_interval = 1 # 5*60 k = 0 data ={} time.sleep(5) time_sim = [] real = 0 for t in range(0, total_inteval, update_interval): while grantedtime < t: grantedtime = h.helicsFederateRequestTime (fed, t) time.sleep(0.1) print('######################## Time interval {} ##########################################'.format(t)) print('######################## Publishing to topics ######################################') real = real + 1 for i in range(0, pubkeys_count): idx = pubid["m{}".format(i)] h.helicsPublicationPublishComplex(idx, real*i, 78) print( '######################## Get input from subscribed topics #########################') for i in range(0, subkeys_count): idx = subid["m{}".format(i)] value = h.helicsInputGetDouble(idx) key = h.helicsSubscriptionGetKey(idx) print("Value for key: {} is {}".format(key, value)) print('######################## Get from Endpoint #########################################') idx = endid["m{}".format(0)] while h.helicsEndpointHasMessage(idx): msg = h.helicsEndpointGetMessage(idx) end_name = h.helicsEndpointGetName(idx) print("Value from endpoint name: {} is {}".format(end_name, msg.data)) print('######################## Send to VOLTTRON Endpoint #################################') for i in range(0, endpoint_count): idx = endid["m{}".format(i)] value = i + random.randint(1, 101) + 89.7 end_name = h.helicsEndpointGetName(idx) print("Sending Value:{0} for endpoint: {1}".format(value, end_name)) h.helicsEndpointSendEventRaw(idx, '', str(value), t) end_name = h.helicsEndpointGetName(idx) logger.info("Destroying federate") destroy_federate(fed)
def register_inputs(self, config=None, callback=None, **kwargs): """ Register configuration parameters with HELICS. The config parameters may include but not limited to: 1. Name of the federate 2. simulation length 2. Type of core to use (zmq/tcp/udp etc) 3. list (and type) of subscriptions 4. list (and type) of publications 5. broker address (if not default) :param config: config parameters :param callback: Register agent callback method :return: """ self._work_callback = callback # Build HELICS config from agent config helics_config = deepcopy(config) properties = helics_config.pop('properties', {}) if not properties: raise RuntimeError( "Invalid configuration. Missing properties dictionary") self._simulation_delta = properties.pop('timeDelta', 1.0) # seconds self._simulation_length = properties.pop('simulation_length', 3600) # seconds for key, value in properties.items(): helics_config[key] = value subscriptions = helics_config.pop('outputs', []) for sub in subscriptions: volttron_topic = sub.pop('volttron_topic', None) if volttron_topic is not None: self.helics_to_volttron_publish[sub.get( 'key')] = volttron_topic sub['key'] = sub.pop('sim_topic') # Replace 'outputs' key with 'subscriptions' key if subscriptions: helics_config['subscriptions'] = subscriptions publications = helics_config.pop('inputs', []) for pub in publications: volttron_topic = pub.pop('volttron_topic', None) pub['key'] = pub.pop('sim_topic') # Replace 'inputs' key with 'publications' key if publications: helics_config['publications'] = publications _log.debug("new config: {}".format(helics_config)) # Create a temporary json file tmp_file = os.path.join(os.getcwd(), 'fed_cfg.json') _log.debug("tmp file: {}".format(tmp_file)) with open(tmp_file, 'w') as fout: fout.write(jsonapi.dumps(helics_config)) _log.debug("Create Combination Federate") # Create federate from provided config parameters try: self.fed = h.helicsCreateCombinationFederateFromConfig(tmp_file) except h._helics.HelicsException as e: _log.exception("Error parsing HELICS config {}".format(e)) # Check if HELICS broker correctly registered inputs federate_name = h.helicsFederateGetName(self.fed) _log.debug("Federate name: {}".format(federate_name)) endpoint_count = h.helicsFederateGetEndpointCount(self.fed) _log.debug("Endpoint count: {}".format(endpoint_count)) subkeys_count = h.helicsFederateGetInputCount(self.fed) _log.debug("Subscription key count: {}".format(subkeys_count)) pubkeys_count = h.helicsFederateGetPublicationCount(self.fed) _log.debug("Publication key count: {}".format(endpoint_count)) for i in range(0, endpoint_count): try: endpt_idx = h.helicsFederateGetEndpointByIndex(self.fed, i) endpt_name = h.helicsEndpointGetName(endpt_idx) self.endpoints[endpt_name] = endpt_idx except h._helics.HelicsException as e: _log.exception( "Error getting helics endpoint index: {}".format(e)) for i in range(0, subkeys_count): inputs = dict() try: idx = h.helicsFederateGetInputByIndex(self.fed, i) inputs['sub_id'] = idx inputs['type'] = h.helicsInputGetType(idx) inputs['key'] = h.helicsSubscriptionGetKey(idx) self.inputs.append(inputs) data = dict(type=inputs['type'], value=None) except h._helics.HelicsException as e: _log.exception( "Error getting helics input index: {}".format(e)) for i in range(0, pubkeys_count): outputs = dict() try: idx = h.helicsFederateGetPublicationByIndex(self.fed, i) outputs['pub_id'] = idx outputs['type'] = h.helicsPublicationGetType(idx) pub_key = h.helicsPublicationGetKey(idx) _log.debug("Publication: {}".format(pub_key)) self.outputs[pub_key] = outputs data = dict(type=outputs['type'], value=None) except h._helics.HelicsException as e: _log.exception( "Error getting helics publication index: {}".format(e))