def test_valuefederate_test_double(): broker = createBroker() vFed, fedinfo = createValueFederate() defaultValue = 1.0 testValue = 2.0 pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.HELICS_DATA_TYPE_DOUBLE, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "") h.helicsInputSetDefaultDouble(subid, defaultValue) h.helicsFederateEnterExecutingMode(vFed) # publish string1 at time=0.0 h.helicsPublicationPublishDouble(pubid, testValue) value = h.helicsInputGetDouble(subid) assert value == defaultValue grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 value = h.helicsInputGetDouble(subid) assert value == testValue # publish string1 at time=0.0 h.helicsPublicationPublishDouble(pubid, testValue + 1) grantedtime = h.helicsFederateRequestTime(vFed, 2.0) assert grantedtime == 0.02 value = h.helicsInputGetDouble(subid) assert value == testValue + 1 destroyFederate(vFed, fedinfo) destroyBroker(broker)
def test_iteration_execution_iteration_test(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") # register the publications pubid = h.helicsFederateRegisterGlobalPublication( vFed1, "pub1", h.HELICS_DATA_TYPE_DOUBLE, "") subid = h.helicsFederateRegisterSubscription(vFed1, "pub1", "") h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_DELTA, 1.0) h.helicsFederateEnterInitializingMode(vFed1) h.helicsPublicationPublishDouble(pubid, 27.0) comp = h.helicsFederateEnterExecutingModeIterative( vFed1, h.HELICS_ITERATION_REQUEST_ITERATE_IF_NEEDED) assert comp == h.HELICS_ITERATION_RESULT_ITERATING val = h.helicsInputGetDouble(subid) assert val == 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 h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
def test_value_federate_runFederateTestDouble(vFed): defaultValue = 1.0 testValue = 2.0 pubid = h.helicsFederateRegisterGlobalPublication( vFed, "pub1", h.helics_data_type_double, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "") h.helicsInputSetDefaultDouble(subid, defaultValue) h.helicsFederateEnterExecutingMode(vFed) # publish string1 at time=0.0; h.helicsPublicationPublishDouble(pubid, testValue) value = h.helicsInputGetDouble(subid) assert value == defaultValue grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 value = h.helicsInputGetDouble(subid) assert value == testValue # publish string1 at time=0.0; h.helicsPublicationPublishDouble(pubid, testValue + 1) grantedtime = h.helicsFederateRequestTime(vFed, 2.0) assert grantedtime == 0.02 value = h.helicsInputGetDouble(subid) assert value == testValue + 1
def _get_input_based_on_type(self, in_put): """ Get input based on type :param in_put: :return: """ val = None sub_id = in_put['sub_id'] try: if in_put['type'] == 'integer': val = h.helicsInputGetInteger(sub_id) elif in_put['type'] == 'double': val = h.helicsInputGetDouble(sub_id) elif in_put['type'] == 'string': val = h.helicsInputGetString(sub_id) elif in_put['type'] == 'complex': real, imag = h.helicsInputGetComplex(sub_id) val = [real, imag] elif in_put['type'] == 'vector': val = h.helicsInputGetVector(sub_id) elif in_put['type'] == 'boolean': val = h.helicsInputGetBoolean(sub_id) else: _log.error("Unknown datatype: {}".format(in_put['type'])) except h._helics.HelicsException as e: _log.exception("Error getting input from HELICS {}".format(e)) return val
def subscribe(self): for sub_tag, sub_data in self.subscriptions.iteritems(): sub_data['value'] = h.helicsInputGetDouble( sub_data['subscription']) self.logger.debug('pyPSSE: Data recieved {} for tag {}'.format( sub_data['value'], sub_tag)) return self.subscriptions
def pub_and_sub_calc(sub_voltage, pub_load, iters): # get the supply voltage supply_voltage = h.helicsInputGetDouble(sub_voltage) # print("reiteration {} with supply voltage {}".format(iters, supply_voltage)) logging.debug(f"reiteration {iters} with supply voltage {supply_voltage}") # calculate load based on supply voltage feeder_load = 1000 + supply_voltage / iters # publish feeder load h.helicsPublicationPublishDouble(pub_load, feeder_load) return supply_voltage, feeder_load
def update_subscriptions(self): for subName, subList in self.Subscriptions.items(): for subInfo in subList: sub = subInfo["subscriptionObj"] if subInfo["dType"].lower() == "complex": value = h.helicsInputGetComplex(sub) elif subInfo["dType"].lower() == 'real': value = h.helicsInputGetDouble(sub) elif subInfo["dType"].lower() == 'text': value = h.helicsInputGetString(sub) elif subInfo["dType"].lower() == "number": value = h.helicsInputGetInteger(sub) else: value = h.helicsInputGetDouble(sub) if value: value = value * subInfo["mult"] X1 = subInfo["elementObj"].GetValue(subInfo["property"]) if value < 10000.0 and value > -100000.0: subInfo["elementObj"].SetValue(value, subInfo["property"]) #X2 = subInfo["elementObj"].GetValue(subInfo["property"]) self.__Logger.debug( f"{subInfo['class']}.{subInfo['name']}.{subInfo['property']} updated to {value}" ) if self.settings['helics']['coiter_mode']: if self.c_seconds != self.c_seconds_old: subInfo["dStates"] = [self.init_state ] * self.n_states else: subInfo["dStates"].insert(0, subInfo["dStates"].pop()) subInfo["dStates"][0] = value #self.cympy.study.Save() return
def updateHelicsSubscriptions(self): for element_name, sub_info in self._subscriptions.items(): if 'Subscription' in sub_info: value = None if sub_info['Data type'].lower() == 'double': value = helics.helicsInputGetDouble( sub_info['Subscription']) elif sub_info['Data type'].lower() == 'vector': value = helics.helicsInputGetVector( sub_info['Subscription']) elif sub_info['Data type'].lower() == 'string': value = helics.helicsInputGetString( sub_info['Subscription']) elif sub_info['Data type'].lower() == 'boolean': value = helics.helicsInputGetBoolean( sub_info['Subscription']) elif sub_info['Data type'].lower() == 'integer': value = helics.helicsInputGetInteger( sub_info['Subscription']) if value and value != 0: value = value * sub_info['Multiplier'] dssElement = self._objects_by_element[element_name] dssElement.SetParameter(sub_info['Property'], value) self._logger.info( 'Value for "{}.{}" changed to "{}"'.format( element_name, sub_info['Property'], value * sub_info['Multiplier'])) if self._settings.helics.iterative_mode: if self.c_seconds != self.c_seconds_old: self._subscription_dState[element_name] = [ self.init_state ] * self.n_states else: self._subscription_dState[element_name].insert( 0, self._subscription_dState[element_name].pop()) self._subscription_dState[element_name][0] = value else: self._logger.warning( '{} will not be used to update element for "{}.{}" '. format(value, element_name, sub_info['Property'])) self.c_seconds_old = self.c_seconds
def pub_and_sub_calc(supply_voltage, last_loads, sub_loads, pub_voltages): # calculate the voltage fed to feeders below feeder_voltage = [ supply_voltage * 0.999 - max((fl - 1000) / 100, 0) for fl in last_loads ] n_feeders = len(last_loads) new_loads = [0.0 for _ in range(0, n_feeders)] load_diff = [0.0 for _ in range(0, n_feeders)] # publish feeder supply voltages for i in range(0, n_feeders): h.helicsPublicationPublishDouble(pub_voltages[i], feeder_voltage[i]) # subscribe to all feeder loads and check for convergence for i in range(0, n_feeders): new_loads[i] = h.helicsInputGetDouble(sub_loads[i]) logger.debug( f"Circuit {feeders[i]} active power demand: {new_loads[i]} at voltage: {feeder_voltage[i]}" ) load_diff[i] = abs(last_loads[i] - new_loads[i]) logger.debug(f"total load difference: {load_diff}") return new_loads
# -*- 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()
# Create value federate print("PI RECEIVER: Creating Value Federate") vfed = h.helicsCreateValueFederate("TestB Federate", fedinfo) print("PI RECEIVER: Value federate created") # Subscribe to PI SENDER's publication sub = h.helicsFederateRegisterSubscription(vfed, "testA", "") print("PI RECEIVER: Subscription registered") h.helicsFederateEnterExecutingMode(vfed) print("PI RECEIVER: Entering execution mode") value = 0.0 prevtime = 0 currenttime = -1 while currenttime <= 100: currenttime = h.helicsFederateRequestTime(vfed, 100) value = h.helicsInputGetDouble(sub) print("PI RECEIVER: Received value = {} at time {} from PI SENDER".format( value, currenttime)) h.helicsFederateFinalize(vfed) h.helicsFederateFree(vfed) h.helicsCloseLibrary() print("PI RECEIVER: Federate finalized")
else: currenttime, iteration_state = h.helicsFederateRequestTimeIterative( vfed, time_requested, h.helics_iteration_request_force_iteration #helics_iteration_request_force_iteration, helics_iteration_request_iterate_if_needed ) A = 200 + random.random() * X B = 100 + random.random() * X C = 400 + random.random() * X D = 350 + random.random() * X h.helicsPublicationPublishDouble(pubA, A) h.helicsPublicationPublishDouble(pubB, B) h.helicsPublicationPublishDouble(pubC, C) h.helicsPublicationPublishDouble(pubD, D) print(f"Powers published: {A}, {B}, {C}, {D}") value1 = h.helicsInputGetDouble(sub1) value2 = h.helicsInputGetDouble(sub2) print("PSS/E voltages: bus 153 {} p.u., bus 154 {} p.u.".format(value1, value2)) print(f"Current time: {time_requested}, Granted time: {currenttime}") #i+=1 h.helicsFederateFinalize(vfed) print("PI SENDER: Federate finalized") while h.helicsBrokerIsConnected(broker): time.sleep(1) h.helicsFederateFree(vfed) h.helicsCloseLibrary()
n = 5 a = Federate() a.create_federate("Manager federate") a.publish("manager", "double") for i in range(n): a.subscribe(str("worker" + str(i))) a.start() print("Manager: Entering execution mode") currenttime = -1 for time_s in range(11): currenttime = h.helicsFederateRequestTime(a.vfed, time_s) val = time_s + 1 h.helicsPublicationPublishDouble(a.pub[0], val) print("Manager: Sending value =", val, "at time =", currenttime, " to Workers") print("Manager waiting for workers to send value back") currenttime = check_values_returned(n, a) for i in range(n): val = h.helicsInputGetDouble(a.sub[i]) print("Manager: Received value =", val, " at time =", currenttime, " from Worker", i) print( "---------------------------------------------------------------------------" ) a.destroy() print("federates finalized") h.helicsCloseLibrary()
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)
# -*- coding: utf-8 -*- import helics as h import time import struct fed = h.helicsCreateCombinationFederateFromConfig("receiver.json") sub = h.helicsFederateGetSubscription(fed, "data") h.helicsFederateEnterExecutingMode(fed) for request_time in range(1, 10): granted_time = h.helicsFederateRequestTime(fed, request_time) data = h.helicsInputGetDouble(sub) print("Message : {}".format(data)) h.helicsFederateFinalize(fed) h.helicsFederateFree(fed) h.helicsCloseLibrary()
soc = {} # As long as granted time is in the time range to be simulated... while grantedtime < total_interval: # Time request for the next physical interval to be simulated requested_time = (grantedtime+update_interval) logger.debug(f'Requesting time {requested_time}\n') grantedtime = h.helicsFederateRequestTime (fed, requested_time) logger.debug(f'Granted time {grantedtime}') for j in range(0,sub_count): logger.debug(f'Battery {j+1} time {grantedtime}') # Get the applied charging voltage from the EV charging_voltage = h.helicsInputGetDouble((subid[j])) logger.debug(f'\tReceived voltage {charging_voltage:.2f} from input' f' {h.helicsSubscriptionGetTarget(subid[j])}') # EV is fully charged and a new EV is moving in # This is indicated by the charging removing voltage when it # thinks the EV is full if charging_voltage == 0: new_batt = get_new_battery(1) batt_list[j] = new_batt[0] current_soc[j] = (np.random.randint(0,80))/100 charging_current = 0 # Calculate charging current and update SOC R = np.interp(current_soc[j], socs, effective_R) logger.debug(f'\tEffective R (ohms): {R:.2f}')
def run_p1u_federate(fed_name, broker_address, feeders): fedinitstring = "--federates=1" if broker_address is not None: fedinitstring = f"{fedinitstring} --broker_address=tcp://{broker_address}" deltat = 0.01 print(f"{fed_name}: Helics version = {h.helicsGetVersion()}") # Create Federate Info object that describes the federate properties fedinfo = h.helicsCreateFederateInfo() # Set Federate name h.helicsFederateInfoSetCoreName(fedinfo, fed_name) # Set core type from string h.helicsFederateInfoSetCoreTypeFromString(fedinfo, "zmq") # Federate init string h.helicsFederateInfoSetCoreInitString(fedinfo, fedinitstring) # Set one second message interval h.helicsFederateInfoSetTimeProperty(fedinfo, h.helics_property_time_delta, deltat) # Create value federate vfed = h.helicsCreateValueFederate(fed_name, fedinfo) print("Value federate created") # Register the publications pub_load = h.helicsFederateRegisterGlobalTypePublication( vfed, "Circuit.full_network.TotalPower.E", "double", "kW" ) pub_voltages = [] for feeder in feeders: pub_name = f"Circuit.feeder_p1u.{feeder}.p1ux.voltage" pub_voltages.append( h.helicsFederateRegisterGlobalTypePublication( vfed, pub_name, "double", "pu" ) ) print(f"{fed_name}: publication {pub_name} registered") # Register subscriptions # subscribe to voltage supplied sub_voltage = h.helicsFederateRegisterSubscription( vfed, "full_network.voltage", "pu" ) h.helicsInputSetDefaultDouble(sub_voltage, 1.0) # subscribe to loads below sub_loads = [] for feeder in feeders: sub_name = f"Circuit.feeder_p1u.{feeder}.p1ux.TotalPower.E" sub_loads.append(h.helicsFederateRegisterSubscription(vfed, sub_name, "kW")) print(f"{fed_name}: subscription {sub_name} registered") h.helicsFederateSetIntegerProperty(vfed, h.helics_property_int_max_iterations, 10) # Enter execution mode h.helicsFederateEnterExecutingMode(vfed) print(f"{fed_name} Entering executing mode") # start execution loop n_feeders = len(feeders) desiredtime = 0.0 t = 0.0 end_time = 24 * 3600 while desiredtime <= end_time: # check time desiredtime = t * 15 * 60 currenttime = h.helicsFederateRequestTime(vfed, desiredtime) if currenttime >= desiredtime: last_loads = [0 for i in range(0, n_feeders)] # reiterate between supply voltage and loads for up to __ iterations # get supply voltage iters = 1 supply_voltage = h.helicsInputGetDouble(sub_voltage) iteration_state = h.helics_iteration_result_iterating while iteration_state == h.helics_iteration_result_iterating: # if there is an iteration going on, publish and subscribe again new_loads = pub_and_sub_calc( supply_voltage, last_loads, sub_loads, pub_voltages ) currenttime, iteration_state = h.helicsFederateRequestTimeIterative( vfed, desiredtime, h.helics_iteration_request_iterate_if_needed ) # find change in load and determine if you need to continue iterating load_diff = 0 for i in range(n_feeders): load_diff = load_diff + abs(new_loads[i] - last_loads[i]) if load_diff / n_feeders < 1e-3: iteration_state = 0 last_loads = new_loads iters += 1 h.helicsPublicationPublishDouble(pub_load, sum(last_loads)) logger.info( "feeder loads {last_loads} at time {currenttime} after {iters} iters" ) t += 1 # all other federates should have finished, so now you can close h.helicsFederateFinalize(vfed) print(f"{fed_name}: Test Federate finalized") h.helicsFederateDestroy(vfed) print(f"{fed_name}: test federate destroyed") h.helicsFederateFree(vfed) print(f"{fed_name}: federate freed") h.helicsCloseLibrary() print(f"{fed_name}: library closed")
def test_valuefederate_default_value_tests(): broker = createBroker() vFed1, fedinfo = createValueFederate(1, "fed0") inp_raw1 = h.helicsFederateRegisterInput(vFed1, "key1", h.HELICS_DATA_TYPE_RAW, "raw") inp_raw2 = h.helicsFederateRegisterInput(vFed1, "key2", h.HELICS_DATA_TYPE_RAW, "raw") inp_bool = h.helicsFederateRegisterInput(vFed1, "key3", h.HELICS_DATA_TYPE_BOOLEAN, "") inp_time = h.helicsFederateRegisterInput(vFed1, "key4", h.HELICS_DATA_TYPE_TIME, "") inp_char = h.helicsFederateRegisterInput(vFed1, "key5", h.HELICS_DATA_TYPE_STRING, "") inp_vect = h.helicsFederateRegisterInput(vFed1, "key6", h.HELICS_DATA_TYPE_VECTOR, "V") inp_double = h.helicsFederateRegisterInput(vFed1, "key7", h.HELICS_DATA_TYPE_DOUBLE, "kW") inp_double2 = h.helicsFederateRegisterInput(vFed1, "key8", h.HELICS_DATA_TYPE_DOUBLE, "") inp_np = h.helicsFederateRegisterInput(vFed1, "key9", h.HELICS_DATA_TYPE_NAMED_POINT, "") h.helicsInputSetMinimumChange(inp_double, 1100.0) h.helicsInputSetDefaultDouble(inp_double, 10000.0) h.helicsInputSetOption(inp_double2, h.HELICS_HANDLE_OPTION_CONNECTION_REQUIRED, True) pub = h.helicsFederateRegisterPublication(vFed1, "", h.HELICS_DATA_TYPE_INT, "MW") h.helicsPublicationSetOption(pub, h.HELICS_HANDLE_OPTION_CONNECTION_REQUIRED, True) h.helicsPublicationAddTarget(pub, "Testfed0/key7") h.helicsPublicationAddTarget(pub, "Testfed0/key8") h.helicsInputSetDefaultRaw(inp_raw1, "") data = "this is a string" h.helicsInputSetDefaultRaw(inp_raw2, data) h.helicsInputSetDefaultBoolean(inp_bool, True) h.helicsInputSetDefaultTime(inp_time, 12.3) h.helicsInputSetDefaultChar(inp_char, "q") h.helicsInputSetDefaultVector(inp_vect, []) h.helicsInputSetDefaultNamedPoint(inp_np, data, 15.7) h.helicsFederateEnterExecutingMode(vFed1) assert h.helicsInputGetInjectionUnits(inp_double) == "MW" assert h.helicsInputGetInjectionUnits(inp_double2) == "MW" assert h.helicsInputGetType(inp_double) == "double" assert h.helicsInputGetPublicationType(inp_double) == "int64" c2 = h.helicsInputGetChar(inp_char) assert c2 == "q" h.helicsInputGetVector(inp_vect) optset = h.helicsInputGetOption(inp_double2, h.HELICS_HANDLE_OPTION_CONNECTION_REQUIRED) assert optset == 1 optset = h.helicsPublicationGetOption(pub, h.HELICS_HANDLE_OPTION_CONNECTION_REQUIRED) assert optset == 1 h.helicsPublicationPublishInteger(pub, 12) h.helicsFederateRequestNextStep(vFed1) assert h.helicsInputGetDouble(inp_double) == 12000.0 assert h.helicsInputGetDouble(inp_double2) == 12.0 h.helicsPublicationPublishInteger(pub, 13) h.helicsFederateRequestNextStep(vFed1) assert h.helicsInputIsUpdated(inp_double) is False assert h.helicsInputIsUpdated(inp_double2) is True assert h.helicsInputGetDouble(inp_double) == 12000.0 assert h.helicsInputGetDouble(inp_double2) == 13.0 h.helicsPublicationPublishInteger(pub, 15) h.helicsFederateRequestNextStep(vFed1) assert h.helicsInputIsUpdated(inp_double) is True assert h.helicsInputIsUpdated(inp_double2) is True h.helicsInputClearUpdate(inp_double) h.helicsInputClearUpdate(inp_double2) assert h.helicsInputIsUpdated(inp_double) is False assert h.helicsInputIsUpdated(inp_double2) is False _, rval = h.helicsInputGetNamedPoint(inp_np) assert rval == 15.7 out, rval = h.helicsInputGetNamedPoint(inp_np) assert out == "this is a string" assert rval == 15.7 h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
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 run_sub_trans(feeders, broker_address): fedinitstring = "--federates=1" if broker_address is not None: fedinitstring = f"{fedinitstring} --broker_address=tcp://{broker_address}" deltat = 0.01 print(f"{fed_name}: Helics version = {h.helicsGetVersion()}") # Create Federate Info object that describes the federate properties # fedinfo = h.helicsCreateFederateInfo() # Set Federate name # h.helicsFederateInfoSetCoreName(fedinfo, fed_name) # Set core type from string # h.helicsFederateInfoSetCoreTypeFromString(fedinfo, "zmq") # Federate init string # h.helicsFederateInfoSetCoreInitString(fedinfo, fedinitstring) # Set the message interval (timedelta) for federate. Note th# # HELICS minimum message time interval is 1 ns and by default # it uses a time delta of 1 second. What is provided to the # setTimedelta routine is a multiplier for the default timedelta. # Set one second message interval # h.helicsFederateInfoSetTimeProperty(fedinfo, h.helics_property_time_delta, deltat) # Create value federate # vfed = h.helicsCreateValueFederate(fed_name, fedinfo) print("Value federate created") # Register the publication # print(f"{fed_name}: Publication registered") pubs = [] subs = [] for feeder in feeders: pub_name = f"{feeder}.voltage" pubs.append( h.helicsFederateRegisterGlobalTypePublication( vfed, pub_name, "double", "pu" ) ) print(f"{fed_name}: publication {pub_name} registered") sub_name = "Circuit.{feeder}.TotalPower.E" subs.append(h.helicsFederateRegisterSubscription(vfed, sub_name, "kW")) print(f"{fed_name}: subscription {sub_name} registered") # Enter execution mode h.helicsFederateEnterExecutingMode(vfed) print(f"{fed_name} Entering executing mode") # start execution loop n_feeders = len(feeders) currenttime = 0 desiredtime = 0.0 t = 0.0 end_time = 24 * 3600 while desiredtime <= end_time: # publish desiredtime = t * 15 * 60 currenttime = h.helicsFederateRequestTime(vfed, desiredtime) if currenttime >= desiredtime: for p in pubs: h.helicsPublicationPublishDouble(p, 1.01) for i in range(n_feeders): value = h.helicsInputGetDouble(subs[i]) print( f"Circuit {feeders[i]} active power demand: {value} kW at time: {currenttime}." ) t += 1 # all other federates should have finished, so now you can close the broker h.helicsFederateFinalize(vfed) print(f"{fed_name}: Test Federate finalized") h.helicsFederateDestroy(vfed) print(f"{fed_name}: test federate destroyed") h.helicsFederateFree(vfed) print("federate freed") h.helicsCloseLibrary() print("library closed")
# As long as granted time is in the time range to be simulated... while grantedtime < total_interval: # Time request for the next physical interval to be simulated requested_time = (grantedtime + update_interval) logger.debug(f'Requesting time {requested_time}') grantedtime = h.helicsFederateRequestTime(fed, requested_time) logger.debug(f'Granted time {grantedtime}') for j in range(0, end_count): logger.debug(f'EV {j+1} time {grantedtime}') # Model the physics of the battery charging. This happens # every time step whether a message comes in or not and always # uses the latest value provided by the battery model. charging_current = h.helicsInputGetDouble((subid[j])) logger.debug(f'\tCharging current: {charging_current:.2f} from ' f'input {h.helicsSubscriptionGetKey(subid[j])}') # New EV is in place after removing charge from old EV, # as indicated by the zero current draw. if charging_current == 0: _, _, _, newEVtype = get_new_EV(1) EVlist[j] = newEVtype[0] charge_V = calc_charging_voltage(newEVtype) charging_voltage[j] = charge_V[0] currentsoc[j] = 0 # Initial SOC estimate logger.debug(f'\t New EV, SOC estimate: {currentsoc[j]:.4f}') logger.debug(f'\t New EV, charging voltage:' f' {charging_voltage[j]}')
for i in range(n): h.helicsFederateEnterExecutingModeComplete(fed[i].vfed) # print(i, "started") currenttime = [0] * n for i in range(n): currenttime[i] = h.helicsFederateRequestTime(fed[i].vfed, 0) it = 0 num_it = 0 while not it == 11: currenttime = check_values_updated(n, fed) for i in range(n): value = h.helicsInputGetDouble(fed[i].sub[0]) print("Worker", i, ": Received value =", value ,"at time =", currenttime[i],"from Manager") value = value * (i+2) time.sleep(random.randrange(2)) h.helicsPublicationPublishDouble(fed[i].pub[0], value) print("Worker", i, ": Sending value =", value, "at time =", currenttime[i],"to Manager") print("-----------------------------------------------------------") if i == n - 1: it = it + 1 for i in fed: i.destroy() print("federates finalized") h.helicsCloseLibrary()