def test_bad_input_tests_raw_tests(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "test") pubid = h.helicsFederateRegisterPublication(vFed1, "pub1", h.HELICS_DATA_TYPE_RAW, "") subid = h.helicsFederateRegisterGlobalInput(vFed1, "inp1", h.HELICS_DATA_TYPE_RAW, "") h.helicsPublicationAddTarget(pubid, "inp1") h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0) h.helicsFederateEnterExecutingMode(vFed1) h.helicsPublicationPublishRaw(pubid, b"hello world") h.helicsFederateRequestNextStep(vFed1) s = h.helicsInputGetRawValue(subid) assert s == b"hello world" h.helicsPublicationPublishDouble(pubid, 27) h.helicsFederateRequestNextStep(vFed1) s = h.helicsInputGetComplex(subid) assert complex(*s) != 27 + 0j h.helicsFederateFinalize(vFed1) t, res = h.helicsFederateRequestTimeIterative( vFed1, 1.0, h.HELICS_ITERATION_REQUEST_NO_ITERATION) assert res == h.HELICS_ITERATION_RESULT_HALTED destroyFederate(vFed1, fedinfo) destroyBroker(broker)
def _publish_based_on_type(self, output): """ Publish message based on type :param output: :return: """ try: if output['type'] == 'integer': h.helicsPublicationPublishInteger(output['pub_id'], output['value']) elif output['type'] == 'double': h.helicsPublicationPublishDouble(output['pub_id'], output['value']) elif output['type'] == 'string': h.helicsPublicationPublishString(output['pub_id'], output['value']) elif output['type'] == 'complex': h.helicsPublicationPublishComplex(output['pub_id'], output['value']) elif output['type'] == 'vector': h.helicsPublicationPublishVector(output['pub_id'], output['value']) elif output['type'] == 'boolean': h.helicsPublicationPublishBoolean(output['pub_id'], output['value']) else: _log.error("Unknown datatype: {}".format(output['type'])) except h._helics.HelicsException as e: _log.exception("Error sending publication to HELICS {}".format(e))
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 update_publications(self): for pubName, pubInfo in self.Publications.items(): device = pubInfo["elementObj"] pub = pubInfo["publicationObj"] if pubInfo["isKeyword"]: res = self.cympy.study.QueryInfoDevice(pubInfo["property"], device.DeviceNumber, device.DeviceType) else: res = pubInfo["elementObj"].GetValue(pubInfo["property"]) print(pubInfo["property"], res, type(res), pubInfo["dType"], pubInfo["unit"]) if pubInfo["dType"].lower() == "complex": h.helicsPublicationPublishComplex(pub, complex(res).real, complex(res).imag) elif pubInfo["dType"].lower() == 'real': h.helicsPublicationPublishDouble(pub, float(res)) elif pubInfo["dType"].lower() == 'text': h.helicsPublicationPublishString(pub, str(res)) elif pubInfo["dType"].lower() == "number": h.helicsPublicationPublishInteger(pub, int(res)) return
def test_value_federate_runFederateTestDouble(vFed): defaultValue = 1.0 testValue = 2.0 pubid = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub1", h.HELICS_DATA_TYPE_DOUBLE, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "double", "") h.helicsSubscriptionSetDefaultDouble(subid, defaultValue) h.helicsFederateEnterExecutionMode(vFed) # publish string1 at time=0.0; h.helicsPublicationPublishDouble(pubid, testValue) status, value = h.helicsSubscriptionGetDouble(subid) assert value == defaultValue status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 status, value = h.helicsSubscriptionGetDouble(subid) assert value == testValue # publish string1 at time=0.0; h.helicsPublicationPublishDouble(pubid, testValue + 1) status, grantedtime = h.helicsFederateRequestTime(vFed, 2.0) assert grantedtime == 0.02 status, value = h.helicsSubscriptionGetDouble(subid) assert value == testValue + 1
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 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 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 publish(self, all_bus_data): all_bus_data = pd.DataFrame(all_bus_data, columns=self.bus_pubs) for r in all_bus_data.index: bus_data = all_bus_data.loc[r] bus_id = bus_data['bus_id'] for c in bus_data.index: data = bus_data[c] bus_property_names = self.publications[bus_id].keys() check = [True if c in x else False for x in bus_property_names] pub_id = check.index(True) pub_id = bus_property_names[pub_id] pub = self.publications[bus_id][pub_id] h.helicsPublicationPublishDouble(pub, data) self.logger.debug('pyPSSE: published "{}" for tag: {}'.format( data, pub_id)) return
def updateHelicsPublications(self): for element, pub in self._publications.items(): fed_name, class_name, object_name, ppty_name = element.split('.') obj_name = '{}.{}'.format(class_name, object_name) obj = self._objects_by_element[obj_name] value = obj.GetValue(ppty_name) if isinstance(value, list): helics.helicsPublicationPublishVector(pub, value) elif isinstance(value, float): helics.helicsPublicationPublishDouble(pub, value) elif isinstance(value, str): helics.helicsPublicationPublishString(pub, value) elif isinstance(value, bool): helics.helicsPublicationPublishBoolean(pub, value) elif isinstance(value, int): helics.helicsPublicationPublishInteger(pub, value) return
def test_bad_input_duplicate_publication_and_input_pathways(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") pubid = h.helicsFederateRegisterTypePublication(vFed1, "pub1", "string", "") # @test_throws h.HELICSErrorRegistrationFailure with pt.raises(h.HelicsException): pubid2 = h.helicsFederateRegisterTypePublication( vFed1, "pub1", "string", "") subid = h.helicsFederateRegisterGlobalTypeInput(vFed1, "inp1", "string", "") # @test_throws h.HELICSErrorRegistrationFailure with pt.raises(h.HelicsException): subid2 = h.helicsFederateRegisterGlobalTypeInput( vFed1, "inp1", "string", "") # @test_throws h.HELICSErrorInvalidObject ept = h.helicsFederateRegisterEndpoint(vFed1, "ept1", "") h.helicsInputAddTarget(subid, "Testfed0/pub1") h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0) h.helicsFederateEnterExecutingMode(vFed1) h.helicsPublicationPublishDouble(pubid, 27.0) h.helicsFederateRequestNextStep(vFed1) str = h.helicsInputGetString(subid) assert str[0] == "2" assert str[1] == "7" messages = h.helicsFederatePendingMessages(vFed1) assert messages == 0 h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
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
pub = h.helicsFederateRegisterGlobalTypePublication( vfed, f"globaltopic{sys.argv[1]}", "double", "" ) pub = h.helicsFederateRegisterTypePublication( vfed, f"localtopic{sys.argv[1]}", "double", "" ) print(f"{federate_name}: Publication registered") h.helicsFederateEnterExecutingMode(vfed) print(f"{federate_name}: Entering execution mode") this_time = 0.0 value = pi for t in range(5, 10): val = value currenttime = h.helicsFederateRequestTime(vfed, t) h.helicsPublicationPublishDouble(pub, val) print(f"{federate_name}: Sending value pi = {val} at time {currenttime}") time.sleep(1) h.helicsFederateFinalize(vfed) print(f"{federate_name}: Federate finalized") h.helicsFederateFree(vfed) h.helicsCloseLibrary()
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")
print("PI SENDER: Publication registered") # Enter execution mode # h.helicsFederateEnterExecutingMode(vfed) print("PI SENDER: Entering execution mode") # This federate will be publishing deltat*pi for numsteps steps # this_time = 0.0 value = pi for t in range(5, 10): val = value currenttime = h.helicsFederateRequestTime(vfed, t) h.helicsPublicationPublishDouble(pub, val) print( "PI SENDER: Sending value pi = {} at time {} to PI RECEIVER".format( val, currenttime ) ) time.sleep(1) h.helicsFederateFinalize(vfed) print("PI SENDER: Federate finalized") while h.helicsBrokerIsConnected(broker): time.sleep(1) h.helicsFederateFree(vfed)
iteration_state = h.helics_iteration_result_iterating for i in range(5): if i == 0: while currenttime < time_requested: currenttime = h.helicsFederateRequestTime(vfed, time_requested) 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")
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))
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()
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()
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 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)
print("PI SENDER: Publication registered") # Enter execution mode # status = h.helicsFederateEnterExecutionMode(vfed) print("PI SENDER: Entering execution mode") # This federate will be publishing deltat*pi for numsteps steps # this_time = 0.0 value = pi for t in range(5, 10): val = value currenttime = h.helicsFederateRequestTime(vfed, t) status = h.helicsPublicationPublishDouble(pub, val) print("PI SENDER: Sending value pi = {} at time {} to PI RECEIVER".format( val, currenttime[-1])) time.sleep(1) status = h.helicsFederateFinalize(vfed) print("PI SENDER: Federate finalized") while (h.helicsBrokerIsConnected(broker)): time.sleep(1) h.helicsFederateFree(vfed) h.helicsCloseLibrary() print("PI SENDER: Broker disconnected")
def test_bad_input_type_publication_2_tests(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "test") pubid = h.helicsFederateRegisterGlobalTypePublication( vFed1, "pub1", "string", "") with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorRegistrationFailure pubid2 = h.helicsFederateRegisterGlobalTypePublication( vFed1, "pub1", "string", "") with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorInvalidArgument h.helicsFederateRegisterFromPublicationJSON(vFed1, "unknownfile.json") with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorExternalArgument h.helicsFederateRegisterInterfaces(vFed1, "unknownfile.json") subid = h.helicsFederateRegisterTypeInput(vFed1, "inp1", "string", "") # @test_throws h.HELICSErrorRegistrationFailure with pt.raises(h.HelicsException): subid2 = h.helicsFederateRegisterTypeInput(vFed1, "inp1", "string", "") h.helicsInputAddTarget(subid, "pub1") h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0) h.helicsFederateEnterExecutingModeIterativeAsync( vFed1, h.HELICS_ITERATION_REQUEST_NO_ITERATION) res = h.helicsFederateEnterExecutingModeIterativeComplete(vFed1) assert res == h.HELICS_ITERATION_RESULT_NEXT_STEP h.helicsPublicationPublishTime(pubid, 27.0) # @test_throws h.HELICSErrorInvalidArgument with pt.raises(h.HelicsException): h.helicsFederatePublishJSON(vFed1, "unknownfile.json") h.helicsFederateRequestNextStep(vFed1) string = h.helicsInputGetString(subid) assert string[0] == "2" assert string[1] == "7" h.helicsFederateClearUpdates(vFed1) h.helicsFederateFinalize(vFed1) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishRaw(pubid, string.encode()) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishString(pubid, string) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishInteger(pubid, 5) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishBoolean(pubid, True) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishDouble(pubid, 39.2) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishTime(pubid, 19.2) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishChar(pubid, "a") # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishComplex(pubid, 2.5 + -9.8j) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishVector(pubid, [1.3, 2.9]) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsPublicationPublishNamedPoint(pubid, "hello world", 2.0) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
sub1 = h.helicsFederateRegisterSubscription( vfed, "PyDSS.PVSystem.pvgnem_mpx000635970.Powers", "kW") #h.helicsInputSetMinimumChange(sub1, 0.1) # Enter execution mode # h.helicsFederateEnterExecutingMode(vfed) for t in range(1, 5): time_requested = t * 15 * 60 #while time_requested < r_seconds: currenttime = h.helicsFederateRequestTime(vfed, time_requested) iteration_state = h.helics_iteration_result_iterating for i in range(20): currenttime, iteration_state = h.helicsFederateRequestTimeIterative( vfed, time_requested, h.helics_iteration_request_iterate_if_needed) h.helicsPublicationPublishDouble(pub1, 5.0 + 1. / (1.0 + i)) print("Published: {}".format((5.0 + 1. / (1.0 + i)))) h.helicsPublicationPublishDouble(pub2, 1.0) value = h.helicsInputGetString(sub1) print("Circuit active power demand: {} kW @ time: {}".format( value, currenttime)) #time.sleep(0.01) #i+=1 time.sleep(0.1) h.helicsFederateFinalize(vfed) print("PI SENDER: Federate finalized") while h.helicsBrokerIsConnected(broker): time.sleep(1)
# Calculate charging current and update SOC R = np.interp(current_soc[j], socs, effective_R) logger.debug(f'\tEffective R (ohms): {R:.2f}') charging_current = charging_voltage / R logger.debug(f'\tCharging current (A): {charging_current:.2f}') added_energy = (charging_current * charging_voltage * \ update_interval/3600) / 1000 logger.debug(f'\tAdded energy (kWh): {added_energy:.4f}') current_soc[j] = current_soc[j] + added_energy / batt_list[j] logger.debug(f'\tSOC: {current_soc[j]:.4f}') # Publish out charging current h.helicsPublicationPublishDouble(pubid[j], charging_current) logger.debug(f'\tPublished {pub_name[j]} with value ' f'{charging_current:.2f}') # Store SOC for later analysis/graphing if subid[j] not in soc: soc[subid[j]] = [] soc[subid[j]].append(float(current_soc[j])) # Data collection vectors time_sim.append(grantedtime) current.append(charging_current) # Cleaning up HELICS stuff once we've finished the co-simulation.
# -*- coding: utf-8 -*- import helics as h import time import struct import math initstring = "-f 2 --name=mainbroker" broker = h.helicsCreateBroker("zmq", "", initstring) fed = h.helicsCreateCombinationFederateFromConfig("sender.json") pub = h.helicsFederateGetPublication(fed, "data") h.helicsFederateEnterExecutingMode(fed) for request_time in range(1, 10): h.helicsFederateRequestTime(fed, request_time) h.helicsPublicationPublishDouble(pub, math.pi) h.helicsFederateFinalize(fed) h.helicsFederateFree(fed) h.helicsCloseLibrary()
charging_voltage = calc_charging_voltage(EVlist) currentsoc = {} # 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}') grantedtime = h.helicsFederateRequestTime(fed, initial_time) logger.debug(f'Granted time {grantedtime}') # Apply initial charging voltage for j in range(0, pub_count): h.helicsPublicationPublishDouble(pubid[j], charging_voltage[j]) logger.debug(f'\tPublishing charging voltage of {charging_voltage[j]} ' f' at time {grantedtime}') # 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()) # ########## Main co-simulation loop ######################################## # As long as granted time is in the time range to be simulated... while grantedtime < total_interval:
# Enter execution mode # h.helicsFederateEnterExecutingMode(vfed) basevolt = 4.16 for t in range(1, 1440): time_requested = t * 60 #while time_requested < r_seconds: currenttime = h.helicsFederateRequestTime(vfed, time_requested) iteration_state = h.helics_iteration_result_iterating for i in range(20): currenttime, iteration_state = h.helicsFederateRequestTimeIterative( vfed, time_requested, h.helics_iteration_request_iterate_if_needed) print(iteration_state) h.helicsPublicationPublishDouble(pubA, basevolt + random.random() / 30) h.helicsPublicationPublishDouble(pubB, basevolt + random.random() / 30) h.helicsPublicationPublishDouble(pubC, basevolt + random.random() / 30) value = h.helicsInputGetVector(sub1) print("PyDSS.Circuit.heco19021.TotalPower: {} kW @ time: {}".format( value, currenttime)) #i+=1 h.helicsFederateFinalize(vfed) print("PI SENDER: Federate finalized") while h.helicsBrokerIsConnected(broker): time.sleep(1) h.helicsFederateFree(vfed) h.helicsCloseLibrary()
assert h.helicsBrokerIsConnected(broker) is True fedinfo = h.helicsCreateFederateInfo() h.helicsFederateInfoSetCoreType(fedinfo, h.helics_core_type_zmq) h.helicsFederateInfoSetCoreInitString(fedinfo, "--loglevel=7") h.helicsFederateInfoSetTimeProperty(fedinfo, h.helics_property_time_delta, 1.0) fed = h.helicsCreateCombinationFederate("sender", fedinfo,) topicA = h.helicsFederateRegisterGlobalPublication( fed, "topicA", h.helics_data_type_double, "" ) h.helicsFederateEnterExecutingMode(fed) currenttime = 0 for t in range(5, 10 + 1): while currenttime < t: currenttime = h.helicsFederateRequestTime(fed, t) print(f"Sending value = {pi} at time = {currenttime}") h.helicsPublicationPublishDouble(topicA, pi) h.helicsFederateFinalize(fed) h.helicsFederateFree(fed) while h.helicsBrokerIsConnected(broker) is True: time.sleep(1) h.helicsBrokerDisconnect(broker) h.helicsCloseLibrary()
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")