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()
effective_R = np.array([8, 150]) 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.
#while (h.helicsBrokerIsConnected(broker)): #time.sleep(1) h.helicsFederateFree(fed) h.helicsCloseLibrary() if __name__ == "__main__": # broker = create_broker() #fed = create_federate() ################################# 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))
# -*- coding: utf-8 -*- import os import helics as h fed = h.helicsCreateCombinationFederateFromConfig( os.path.join(os.path.dirname(__file__), "receiver.json") ) topicA = h.helicsFederateGetSubscription(fed, "topicA") h.helicsFederateEnterExecutingMode(fed) currenttime = 0 for t in range(5, 10 + 1): while currenttime < t: currenttime = h.helicsFederateRequestTime(fed, t) a = h.helicsInputGetDouble(topicA) print(f"Received a = {a} at time = {currenttime}") h.helicsFederateFinalize(fed) h.helicsFederateFree(fed) h.helicsCloseLibrary()
import helics as h import time import struct initstring = "-f 2 --name=mainbroker" broker = h.helicsCreateBroker("zmq", "", initstring) isconnected = h.helicsBrokerIsConnected(broker) if isconnected == 1: 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)
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))
lvl3 = 0.3 listOfEVs = np.random.choice([1, 2, 3], numEVs, p=[lvl1, lvl2, lvl3]).tolist() numLvl1 = listOfEVs.count(1) numLvl2 = listOfEVs.count(2) numLvl3 = listOfEVs.count(3) return numLvl1, numLvl2, numLvl3, listOfEVs if __name__ == "__main__": np.random.seed(1) ############## Registering federate from json ########################## name = "EV_federate" fed = h.helicsCreateCombinationFederateFromConfig("EVconfig.json") federate_name = h.helicsFederateGetName(fed) logging.info(f'Created federate {federate_name}') end_count = h.helicsFederateGetEndpointCount(fed) logging.info(f'\tNumber of endpoints: {end_count}') sub_count = h.helicsFederateGetInputCount(fed) logging.info(f'\tNumber of subscriptions: {sub_count}') pub_count = h.helicsFederateGetPublicationCount(fed) logging.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.