def test_combination_federate(): broker = createBroker() cfed = h.helicsCreateCombinationFederateFromConfig( os.path.join(CURRENT_DIRECTORY, "combinationfederate.json")) assert h.helicsFederateIsValid(cfed) assert h.helicsFederateGetEndpointCount(cfed) == 2 assert h.helicsFederateGetFilterCount(cfed) == 0 assert h.helicsFederateGetInputCount(cfed) == 2 ept = h.helicsFederateGetEndpointByIndex(cfed, 0) assert h.helicsEndpointGetName(ept) == "ept1" ipt = h.helicsFederateGetInputByIndex(cfed, 1) assert h.helicsInputGetExtractionUnits(ipt) == "" assert h.helicsSubscriptionGetKey(ipt) == "comboFed/pub2" h.helicsEndpointClearMessages(ept) h.helicsFederateDestroy(cfed) h.helicsFederateFree(cfed) h.helicsBrokerDestroy(broker) h.helicsCloseLibrary()
def test_messagefederate_test_message_federate_endpoint_registration(mFed): epid1 = h.helicsFederateRegisterEndpoint(mFed, "ep1", "") epid2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "ep2", "random") h.helicsFederateEnterExecutingMode(mFed) assert h.HELICS_STATE_EXECUTION == h.helicsFederateGetState(mFed) endpoint_name = h.helicsEndpointGetName(epid1) assert endpoint_name == "TestA Federate/ep1" endpoint_name = h.helicsEndpointGetName(epid2) assert endpoint_name == "ep2" endpoint_name = h.helicsEndpointGetType(epid1) assert endpoint_name == "" endpoint_name = h.helicsEndpointGetType(epid2) assert endpoint_name == "random" epid_b = h.helicsFederateGetEndpoint(mFed, "ep2") type = h.helicsEndpointGetType(epid_b) assert type == "random" epid_c = h.helicsFederateGetEndpointByIndex(mFed, 0) name = h.helicsEndpointGetName(epid_c) assert name == "TestA Federate/ep1"
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
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 = {} for i in range(0, end_count): endid[i] = h.helicsFederateGetEndpointByIndex(fed, i) end_name = h.helicsEndpointGetName(endid[i]) logger.debug(f'\tRegistered Endpoint ---> {end_name}') subid = {} for i in range(0, sub_count): subid[i] = h.helicsFederateGetInputByIndex(fed, i) sub_name = h.helicsSubscriptionGetKey(subid[i]) logger.debug(f'\tRegistered subscription---> {sub_name}') pubid = {} for i in range(0, pub_count): pubid[i] = h.helicsFederateGetPublicationByIndex(fed, i) pub_name = h.helicsPublicationGetKey(pubid[i]) logger.debug(f'\tRegistered publication---> {pub_name}') ############## Entering Execution Mode ##################################
import time 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()
################################# Registering federate from json ######################################## fed = h.helicsCreateCombinationFederateFromConfig('Control.json') #status = h.helicsFederateRegisterInterfaces(fed, 'Control.json') federate_name = h.helicsFederateGetName(fed) print(federate_name) #print(" Federate {} has been registered".format(federate_name)) endpoint_count = h.helicsFederateGetEndpointCount(fed) subkeys_count = h.helicsFederateGetInputCount(fed) print(subkeys_count) print(endpoint_count) ###################### Reference to Publications and Subscription form index ############################# endid = {} subid = {} for i in range(0, endpoint_count): endid["m{}".format(i)] = h.helicsFederateGetEndpointByIndex(fed, i) end_name = h.helicsEndpointGetName(endid["m{}".format(i)]) print('Registered Endpoint ---> {}'.format(end_name)) for i in range(0, subkeys_count): subid["m{}".format(i)] = h.helicsFederateGetInputByIndex(fed, i) status = h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0) sub_key = h.helicsSubscriptionGetKey(subid["m{}".format(i)]) print('Registered Subscription ---> {}'.format(sub_key)) print( '###############################################################################################' ) print( '######################## Entering Execution Mode ##########################################' )
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))