def test_valuefederate_test_single_transfer(): broker = createBroker() vFed, fedinfo = createValueFederate() s = "n2" pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "") h.helicsFederateEnterExecutingMode(vFed) h.helicsPublicationPublishString(pubid, "string1") grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 s = h.helicsInputGetString(subid) assert s == "string1" t = h.helicsInputLastUpdateTime(subid) assert t == 0.01 h.helicsPublicationPublishString(pubid, "string2") destroyFederate(vFed, fedinfo) destroyBroker(broker)
def _main_loop(self, vFed): """The main loop for running the HELICS functions. Args: vFed (helics federate object) - The value federate. Returns: (null) """ cnt = 0 txstring = "{:<100000}{:<100}".format(self.index_, "1") tbuffer = chr(256) itr = 5000 self.vFed = vFed logging.info("echo leaf - starting the helics functions") while cnt <= itr + 1: h.helicsFederateRequestTimeAsync(self.vFed, 1.0) while h.helicsFederateIsAsyncOperationCompleted(self.vFed) == 0: pass h.helicsFederateRequestTimeComplete(self.vFed) if cnt <= itr: h.helicsPublicationPublishString(self.pub, txstring) if h.helicsInputIsUpdated(self.sub): actLen = 0 h.helicsInputGetString(self.sub, tbuffer, 256, actLen) if str(tbuffer) != txstring: logging.error("incorrect string\n") break cnt += 1 h.helicsFederateFinalizeAsync(self.vFed) while h.helicsFederateIsAsyncOperationCompleted(self.vFed) == 0: pass h.helicsFederateFinalizeComplete(self.vFed) logging.info("echo leaf - the helics functions have been completed")
def test_valuefederate_test_string(): broker = createBroker() vFed, fedinfo = createValueFederate() defaultValue = "String1" testValue = "String2" pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "") h.helicsInputSetDefaultString(subid, defaultValue) h.helicsFederateEnterExecutingMode(vFed) h.helicsPublicationPublishString(pubid, testValue) value = h.helicsInputGetString(subid) assert value == defaultValue grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 value = h.helicsInputGetString(subid) assert value == testValue 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 _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 main(delay=None): broker = create_broker() fed = create_value_federate(broker) pubid = h.helicsFederateRegisterGlobalTypePublication( fed, "federate1-to-federate2", "string", "") subid = h.helicsFederateRegisterSubscription(fed, "federate2-to-federate1", "") epid = h.helicsFederateRegisterGlobalEndpoint(fed, "endpoint1", "") if delay is not None: fid = h.helicsFederateRegisterGlobalFilter(fed, h.helics_filter_type_delay, "filter-name") h.helicsFilterAddSourceTarget(fid, "endpoint1") h.helicsInputSetDefaultNamedPoint(subid, "", 0) print("Entering execution mode") h.helicsFederateEnterExecutingMode(fed) if delay is not None: h.helicsFilterSet(fid, "delay", delay) grantedtime = -1 while True: try: stop_at_time, value_to_send = get_input(grantedtime) print(stop_at_time) except KeyboardInterrupt: print("") break while grantedtime < stop_at_time: print(">>>>>>>> Requesting time = {}".format(stop_at_time)) grantedtime = h.helicsFederateRequestTime(fed, stop_at_time) grantedtime = int(grantedtime) if grantedtime != stop_at_time: value = h.helicsSubscriptionGetKey(subid) print("Interrupt value '{}' from Federate 2".format(value)) print("<<<<<<<< Granted Time = {}".format(grantedtime)) assert (grantedtime == stop_at_time ), "stop_at_time = {}, grantedtime = {}".format( stop_at_time, grantedtime) if value_to_send is not None and value_to_send != "": print("Sending '{}' to Federate 2".format(value_to_send)) h.helicsPublicationPublishString(pubid, str(value_to_send)) h.helicsEndpointSendMessageRaw(epid, "endpoint2", str(value_to_send)) value = h.helicsSubscriptionGetKey(subid) print("Received value '{}' from Federate 2".format(value)) while h.helicsEndpointHasMessage(epid): value = h.helicsEndpointGetMessage(epid) print("Received message '{}' at time {} from Federate 2".format( value.data, value.time)) print("----------------------------------") destroy_value_federate(fed, broker)
def test_value_federate_single_transfer(vFed): pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.helics_data_type_string, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "") h.helicsFederateEnterExecutingMode(vFed) h.helicsPublicationPublishString(pubid, "string1") grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 s = h.helicsInputGetString(subid) assert s == "string1"
def main(delay=None): broker = create_broker() fed = create_value_federate(broker) pubid = h.helicsFederateRegisterGlobalTypePublication( fed, "federate1-to-federate2", h.HELICS_DATA_TYPE_STRING, "") subid = h.helicsFederateRegisterSubscription(fed, "federate2-to-federate1", "double", "") epid = h.helicsFederateRegisterGlobalEndpoint(fed, "endpoint1", "") if delay is not None: fid = h.helicsFederateRegisterSourceFilter(fed, h.helics_delay_filter, "endpoint2", "filter-name") h.helicsSubscriptionSetDefaultDouble(subid, 0) print("Entering execution mode") h.helicsFederateEnterExecutionMode(fed) if delay is not None: h.helicsFilterSet(fid, "delay", 2.0) grantedtime = -1 while True: try: stop_at_time, value_to_send = get_input(grantedtime) except KeyboardInterrupt: print("") break while grantedtime < stop_at_time: print(">>>>>>>> Requesting time = {}".format(stop_at_time)) status, grantedtime = h.helicsFederateRequestTime( fed, stop_at_time) assert status == 0 if grantedtime != stop_at_time: status, value = h.helicsSubscriptionGetString(subid) assert status == 0 print("Interrupt value '{}' from Federate 2".format(value)) print("<<<<<<<< Granted Time = {}".format(grantedtime)) assert grantedtime == stop_at_time, "stop_at_time = {}, grantedtime = {}".format( stop_at_time, grantedtime) if value_to_send is not None and value_to_send != '': print("Sending '{}' to Federate 2".format(value_to_send)) status = h.helicsPublicationPublishString(pubid, str(value_to_send)) assert status == 0 status = h.helicsEndpointSendMessageRaw(epid, "endpoint2", str(value_to_send)) assert status == 0 status, value = h.helicsSubscriptionGetString(subid) assert status == 0 print("Received value '{}' from Federate 2".format(value)) while h.helicsEndpointHasMessage(epid): value = h.helicsEndpointGetMessage(epid) print("Received message '{}' at time {} from Federate 2".format( value.data, value.time)) print("----------------------------------") destroy_value_federate(fed, broker)
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_value_federate_single_transfer(vFed): pubid = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "string", "") h.helicsFederateEnterExecutionMode(vFed) h.helicsPublicationPublishString(pubid, "string1") status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 status, s = h.helicsSubscriptionGetString(subid) assert status == 0 assert s == "string1"
def test_value_federate_runFederateTestString(vFed): defaultValue = "String1" testValue = "String2" pubid = h.helicsFederateRegisterGlobalPublication(vFed, "pub1", h.helics_data_type_string, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "") h.helicsInputSetDefaultString(subid, defaultValue) h.helicsFederateEnterExecutingMode(vFed) h.helicsPublicationPublishString(pubid, testValue) value = h.helicsInputGetString(subid) assert value == defaultValue grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 value = h.helicsInputGetString(subid) assert value == testValue
def test_value_federate_runFederateTestString(vFed): defaultValue = "String1" testValue = "String2" pubid = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "string", "") h.helicsSubscriptionSetDefaultString(subid, defaultValue) h.helicsFederateEnterExecutionMode(vFed) # TODO: Fix error with the following function h.helicsPublicationPublishString(pubid, testValue) status, value = h.helicsSubscriptionGetString(subid) assert value == defaultValue status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 status, value = h.helicsSubscriptionGetString(subid) assert value == testValue
def main(): fed = create_federate() pubid = h.helicsFederateRegisterGlobalPublication( fed, "loadshed/sw_status", h.helics_data_type_string, "") subid = h.helicsFederateRegisterSubscription( fed, "gridlabdSimulator1/totalLoad", "") h.helicsFederateEnterExecutingMode(fed) switchings = [[0, 1], [1800, 0], [5400, 1], [16200, 0], [19800, 1]] hours = 6 seconds = int(60 * 60 * hours) grantedtime = -1 for swt in switchings: t = swt[0] val = swt[1] while grantedtime < t: grantedtime = h.helicsFederateRequestTime(fed, t) logger.info('Switching to ' + str(val) + ' at ' + str(t)) status = h.helicsPublicationPublishString(pubid, str(val)) logger.info("Destroying federate") destroy_federate(fed)
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)
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 run(self,dt=300.0,ID=5,\ scale={5:0.0000009, 7:0.000001, 9:0.00000125},monitor=False,\ inv_nominalV={5:480.0, 7:480.0, 9:480.0},msgSize=1024): try: Res = [] res = {} simTime = 0.0 comm_end = 0 while comm_end == 0: grantedTime = h.helicsFederateRequestTime(self.vf, simTime) status, msg = h.helicsSubscriptionGetString( self.sub) # receive from pyPflow simTime += dt if 'setpoint' in msg: msg = eval(msg) if ID in msg['setpoint']: propVal = [] for entry in msg['setpoint'][ID]: propVal.append(entry[0]) propVal.append(entry[1]) objName = ['solar_inv'] * 8 propName = [ 'V1', 'Q1', 'V2', 'Q2', 'V3', 'Q3', 'V4', 'Q4' ] self.pyGldWorker.objVal(ID, objName, propName, propVal, flg='send') # set new QV curve self.pyGldWorker.objVal(ID, objName, propName, ['none'] * len(propVal), flg='recv') # set new QV curve status = h.helicsPublicationPublishString( self.pub, 'Received QV curve') grantedTime = h.helicsFederateRequestTime( self.vf, simTime) # sync at this point simTime += dt else: msg = eval(msg) if 'comm_end' in msg: if msg['comm_end'] == 1: comm_end = 1 if len(res) > 0: Res.append(res) if comm_end == 0: # set load if requested if 'set' in msg['mpc'].keys(): if 'loadShape' in msg['mpc']['set'].keys(): self.pyGldWorker.setLoad( msg['mpc']['set']['loadShape'], ID=ID) self.pyGldWorker.setSolar( msg['mpc']['set']['solarShape'], ID=ID) if len(res) > 0: Res.append(res) Vpu = 0 for entry in msg['mpc']['get']['V']: if entry[0] == ID: Vpu = entry[1] Pd = 0 Qd = 0 if Vpu != 0: Sinj, res, convergence_flg = self.pyGldWorker.run( Vpu, ID=ID, monitor=monitor) # will call gridlabd server if convergence_flg == 1: Pd = Sinj.real * scale[ID] Qd = Sinj.imag * scale[ID] msg = {} msg['mpc'] = {} msg['mpc']['set'] = {} msg['mpc']['get'] = {} if Pd != 0 and Qd != 0: msg['mpc']['set']['Pd'] = [[ ID, 1, math.ceil(Pd * 10**6) * 10**-6 ]] msg['mpc']['set']['Qd'] = [[ ID, 1, math.ceil(Qd * 10**6) * 10**-6 ]] msg['mpc']['get']['V'] = [[ID, 0, 0]] msg['mpc']['set']['solar_V']=math.ceil(min([\ res[ID]['solar_meter']['measured_voltage_A_mag']/inv_nominalV[ID]*math.sqrt(3),\ res[ID]['solar_meter']['measured_voltage_B_mag']/inv_nominalV[ID]*math.sqrt(3),\ res[ID]['solar_meter']['measured_voltage_C_mag']/inv_nominalV[ID]*math.sqrt(3)\ ])*10**4)*10**-4 msg['mpc']['set']['solar_Q']=\ math.ceil(-res[ID]['solar_meter']['measured_reactive_power']/\ (res[ID]['solar_inv']['rated_power']*3)*10**2)*10**-2 # rated power is per phase # send status = h.helicsPublicationPublishString( self.pub, str(msg)) # publish Sinj as fedName grantedTime = h.helicsFederateRequestTime( self.vf, simTime) # sync at this point simTime += dt if monitor == True: json.dump( Res, open(dirName + '/results/res_' + str(ID) + '.json', 'w')) except: PrintException()
def run(self,dt=300.0,nDis=5,tol=10**-3,\ pflowFname=dirName+'/results/pflowRes.json',adaptive=False,iterMax=10,\ msgSize=1024): try: simTime = 0.0 comm_end = 0 pflowRes = [] setPoint = {} sensitivity_info = {} sensitivity_info['inv'] = {5: 0.025, 7: 0.025, 9: 0.025} sensitivity_info['pcc'] = {5: 0.01, 7: 0.01, 9: 0.01} iteration = 0 dispatchNo = 1 while comm_end == 0: #send (set V at distribution side) self.msgFromPflow['mpc'].pop('set') self.msgFromPflow['mpc']['set'] = {} if iteration == 0: #set load at iteration 0 self.__setDcopfData(self.msgFromPflow, dispatchNo, 'gld') boundaryConditionCheck = np.zeros(shape=(len(self.ID), 2)) if adaptive and 'flg' in setPoint and setPoint[ 'flg'] == 1: # change QV curve if needed setPoint.pop('flg') temp_setpoint = {} temp_setpoint['setpoint'] = setPoint temp_setpoint = str(temp_setpoint).replace(' ', '') setPoint = {} status = h.helicsPublicationPublishString( self.pub, temp_setpoint) grantedTime = h.helicsFederateRequestTime(self.vf, simTime) simTime += dt grantedTime = h.helicsFederateRequestTime(self.vf, simTime) for ID in self.ID: # receive from GLD errFlg, temp = h.helicsSubscriptionGetString( self.sub['pyGld_' + str(ID)]) temp = eval(temp) simTime += dt else: status = h.helicsPublicationPublishString( self.pub, str(self.msgFromPflow) ) # will send msg i.e. Vpcc to all # distribution feeders that are subscribers of publisher called pyPflow grantedTime = h.helicsFederateRequestTime(self.vf, simTime) simTime += dt #recv (getS from distribution side) grantedTime = h.helicsFederateRequestTime(self.vf, simTime) msgFromGld = {} msgFromGld['mpc'] = {} msgFromGld['mpc']['set'] = {} msgFromGld['mpc']['get'] = {} setData = msgFromGld['mpc']['set'] getData = msgFromGld['mpc']['get'] setData['Pd'] = [] setData['Qd'] = [] getData['V'] = [] inv_volt = {} inv_Q = {} for ID in self.ID: errFlg, temp = h.helicsSubscriptionGetString( self.sub['pyGld_' + str(ID)]) temp = eval(temp) setData['Pd'].append(temp['mpc']['set']['Pd'][0]) setData['Qd'].append(temp['mpc']['set']['Qd'][0]) getData['V'].append(temp['mpc']['get']['V'][0]) inv_volt[ID] = temp['mpc']['set']['solar_V'] inv_Q[ID] = temp['mpc']['set']['solar_Q'] simTime += dt # run PFLOW (setS and getV from transmission side) if iteration == 0: #set load at iteration 0 self.__setDcopfData(msgFromGld, dispatchNo, 'pflow') self.socket.send_string( json.dumps(msgFromGld)) # send instructions to pflow self.msgFromPflow = eval( self.socket.recv()) # receive data from pflow iteration += 1 # check boundary condition V = np.array(self.msgFromPflow['mpc']['get']['V']) pcc_volt = {} for ID in self.ID: pcc_volt[ID] = V[V[:, 0] == ID, 1][0] count = 0 for ID in self.ID: boundaryConditionCheck[ count, 1] = boundaryConditionCheck[count, 0] boundaryConditionCheck[count, 0] = V[V[:, 0] == ID, 1][0] count += 1 if np.all( abs(boundaryConditionCheck[:, 0] - boundaryConditionCheck[:, 1]) < tol): # check for QV setting if adaptive: setPoint = self.setQvCurve(pcc_volt, inv_volt, inv_Q, sensitivity_info) else: setPoint = {} setPoint['flg'] = 0 # implies no adaptive changes are required or max iterations have been exceeded if setPoint['flg'] == 0 or iteration > iterMax: six.print_("Completed Dispath Number: ", dispatchNo) pflowRes.append([self.msgFromPflow, msgFromGld]) # store pflow result iteration = 0 # reset iteration for the new dispatch if dispatchNo == nDis: comm_end = 1 commEndMsg = {} commEndMsg['comm_end'] = 1 status = h.helicsPublicationPublishString( self.pub, str(commEndMsg)) # send shutdown signal grantedTime = h.helicsFederateRequestTime( self.vf, simTime) self.socket.send_string("COMM_END") msgFromPflow = self.socket.recv() else: dispatchNo += 1 # save results json.dump(pflowRes, open(pflowFname, 'w')) except: PrintException()