def test_bad_input_init_error(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") # register the publications # the types here don't match which causes an error when initializing the federation h.helicsFederateRegisterGlobalTypePublication(vFed1, "pub1", "custom1", "") subid = h.helicsFederateRegisterTypeInput(vFed1, "inp1", "custom2", "") k1 = h.helicsInputGetKey(subid) # check some other calls inp2 = h.helicsFederateGetInput(vFed1, "inp1") k2 = h.helicsInputGetKey(inp2) assert k1 == k2 inp3 = h.helicsFederateGetInputByIndex(vFed1, 0) k3 = h.helicsInputGetKey(inp3) assert k1 == k3 h.helicsInputAddTarget(subid, "pub1") h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0) # unknown publication with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorInvalidArgument pub3 = h.helicsFederateGetPublication(vFed1, "unknown") # error in this call from the mismatch with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorConnectionFailure h.helicsFederateEnterInitializingMode(vFed1) with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorInvalidFunctionCall h.helicsFederateRequestTimeAdvance(vFed1, 0.1) # unknown input with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorInvalidArgument inp4 = h.helicsFederateGetInput(vFed1, "unknown") # invalid input index # TODO: does this test segfault some times? with pt.raises(h.HelicsException): # @test_throws h.HELICSErrorInvalidArgument inp5 = h.helicsFederateGetInputByIndex(vFed1, 4) h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
def main(delay=None, verbose=False): if verbose is not False: logger.setLevel(logging.DEBUG) logger.info("Creating MockFederate for FESTIV") fed = create_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, "") h.helicsFederateEnterExecutionMode(fed) time_granted = -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', ]: for interval in range(0, int(24 * 60 / 5)): 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) logger.info( "time granted = {}".format(time_granted)) destroy_federate(fed)
def test_valuefederate_test_info_filed(): broker = createBroker() vFed, fedinfo = createValueFederate(1, "fed0") h.helicsFederateSetFlagOption(vFed, h.HELICS_HANDLE_OPTION_CONNECTION_OPTIONAL, True) # register the publications/subscriptions subid1 = h.helicsFederateRegisterSubscription(vFed, "sub1", "") pubid1 = h.helicsFederateRegisterTypePublication(vFed, "pub1", "string", "") pubid2 = h.helicsFederateRegisterGlobalTypePublication(vFed, "pub2", "string", "") # Set info fields h.helicsInputSetInfo(subid1, "sub1_test") h.helicsPublicationSetInfo(pubid1, "pub1_test") h.helicsPublicationSetInfo(pubid2, "pub2_test") h.helicsFederateEnterExecutingMode(vFed) assert h.helicsInputGetInfo(subid1) == "sub1_test" assert h.helicsPublicationGetInfo(pubid1) == "pub1_test" assert h.helicsPublicationGetInfo(pubid2) == "pub2_test" cr = h.helicsFederateGetCoreObject(vFed) h.helicsFederateFinalize(vFed) wait = h.helicsCoreWaitForDisconnect(cr, 70) if wait is False: wait = h.helicsCoreWaitForDisconnect(cr, 500) assert wait is True destroyFederate(vFed, fedinfo) destroyBroker(broker)
def test_value_federate_runFederateTestComplex(vFed): rDefaultValue = 1.0 iDefaultValue = 1.0 rTestValue = 2.0 iTestValue = 2.0 pubid = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub1", h.HELICS_DATA_TYPE_COMPLEX, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "double", "") h.helicsSubscriptionSetDefaultComplex(subid, rDefaultValue, iDefaultValue) h.helicsFederateEnterExecutionMode(vFed) # publish string1 at time=0.0; h.helicsPublicationPublishComplex(pubid, rTestValue, iTestValue) status, value1, value2 = h.helicsSubscriptionGetComplex(subid) assert value1 == rDefaultValue assert value2 == iDefaultValue status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 status, value1, value2 = h.helicsSubscriptionGetComplex(subid) assert value1 == rTestValue assert value2 == iTestValue
def _registerFederatePublications(self, pubs): if pubs is not None: publicationList= pubs else: self._file_reader = pyExportReader( os.path.join( self._system_paths ["ExportLists"], "ExportMode-byClass.toml", ), ) publicationList = self._file_reader.publicationList self._publications = {} for valid_publication in publicationList: obj_class, obj_property = valid_publication.split(' ') objects = self._objects_by_class[obj_class] for obj_X, obj in objects.items(): name = '{}.{}.{}'.format(self._options['Helics']['Federate name'], obj_X, obj_property) self._publications[name] = helics.helicsFederateRegisterGlobalTypePublication( self._PyDSSfederate, name, self.type_info[obj_property], '' ) self._logger.info(f'Publication registered: {name}') return
def test_value_federate_runFederateTestInteger(vFed): defaultValue = 1 testValue = 2 pubid = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub1", h.HELICS_DATA_TYPE_INT, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "int", "") h.helicsSubscriptionSetDefaultInteger(subid, defaultValue) h.helicsFederateEnterExecutionMode(vFed) h.helicsPublicationPublishInteger(pubid, testValue) status, value = h.helicsSubscriptionGetInteger(subid) assert value == defaultValue status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 status, value = h.helicsSubscriptionGetInteger(subid) assert value == testValue h.helicsPublicationPublishInteger(pubid, testValue + 1) status, grantedtime = h.helicsFederateRequestTime(vFed, 2.0) assert grantedtime == 0.02 status, value = h.helicsSubscriptionGetInteger(subid) assert value == testValue + 1
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 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 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_publisher_registration(vFed): pubid1 = h.helicsFederateRegisterTypePublication(vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "") pubid2 = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub2", h.HELICS_DATA_TYPE_INT, "") pubid3 = h.helicsFederateRegisterTypePublication(vFed, "pub3", h.HELICS_DATA_TYPE_DOUBLE, "V") h.helicsFederateEnterExecutionMode(vFed)
def test_query_federate_tests(): broker = createBroker(2) vFed1, fedinfo1 = createValueFederate(1, "fed0") vFed2, fedinfo2 = createValueFederate(1, "fed1") h.helicsFederateRegisterGlobalTypePublication(vFed1, "pub1", "double", "") h.helicsFederateRegisterTypePublication(vFed1, "pub2", "double", "") h.helicsFederateRegisterTypePublication(vFed2, "pub3", "double", "") h.helicsFederateEnterInitializingModeAsync(vFed1) h.helicsFederateEnterInitializingMode(vFed2) h.helicsFederateEnterInitializingModeComplete(vFed1) core = h.helicsFederateGetCoreObject(vFed1) q1 = h.helicsCreateQuery("Testfed0", "publications") res = h.helicsQueryCoreExecute(q1, core) try: assert res == "[pub1;Testfed0/pub2]" except: assert res == ["pub1", "Testfed0/pub2"] # res = h.helicsQueryExecute(q1, vFed2) # assert res == "[pub1;Testfed0/pub2]" h.helicsQueryFree(q1) # q1 = h.helicsCreateQuery("Testfed1", "isinit") # res = h.helicsQueryExecute(q1, vFed1) # assert res, "True" # h.helicsQueryFree(q1) # q1 = h.helicsCreateQuery("Testfed1", "publications") # res = h.helicsQueryExecute(q1, vFed1) # assert res == "[Testfed1/pub3]" # h.helicsQueryFree(q1) h.helicsCoreFree(core) h.helicsFederateFinalizeAsync(vFed1) h.helicsFederateFinalize(vFed2) h.helicsFederateFinalizeComplete(vFed1) destroyFederate(vFed1, fedinfo1) destroyFederate(vFed2, fedinfo2) destroyBroker(broker)
def test_bad_inputs_core_link(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") # register the publications h.helicsFederateRegisterGlobalTypePublication(vFed1, "pub1", "custom1", "") h.helicsFederateRegisterTypeInput(vFed1, "inp1", "custom2", "") fed2 = h.helicsGetFederateByName(h.helicsFederateGetName(vFed1)) assert h.helicsFederateGetName(fed2) == h.helicsFederateGetName(vFed1) # @test_throws h.HELICSErrorInvalidArgument with pt.raises(h.HelicsException): fed3 = h.helicsGetFederateByName("fed_unknown") cr = h.helicsFederateGetCoreObject(vFed1) h.helicsCoreDataLink(cr, "pub1", "fed0/inp1") # @test_throws h.HELICSErrorInvalidArgument with pt.raises(h.HelicsException): h.helicsCoreMakeConnections(cr, "unknownfile.json") # TODO: This test should throw an error # @test_throws h.HELICSErrorInvalidArgument h.helicsCoreDataLink(cr, "pub1", "") # @test_broken False cr2 = h.helicsCoreClone(cr) assert h.helicsCoreGetAddress(cr2) == h.helicsCoreGetAddress(cr) # TODO: this should error as well # h.helicsFederateEnterExecutingMode(vFed1) # @test_broken False h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
def test_bad_inputs_init_error_5(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") # register the publications h.helicsFederateInfoSetSeparator(fedinfo, "-") h.helicsFederateSetSeparator(vFed1, "-") h.helicsFederateRegisterGlobalTypePublication(vFed1, "pub1", "custom1", "") subid = h.helicsFederateRegisterTypeInput(vFed1, "inp1", "custom2", "") h.helicsInputAddTarget(subid, "pub1") h.helicsFederateSetTimeProperty(vFed1, h.HELICS_PROPERTY_TIME_PERIOD, 1.0) # @test_throws h.HELICSErrorConnectionFailure with pt.raises(h.HelicsException): resIt = h.helicsFederateEnterExecutingModeIterative( vFed1, h.HELICS_ITERATION_REQUEST_NO_ITERATION) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): h.helicsFederateRequestTimeIterativeAsync( vFed1, 1.0, h.HELICS_ITERATION_REQUEST_NO_ITERATION) # @test_throws h.HELICSErrorInvalidFunctionCall with pt.raises(h.HelicsException): res = h.helicsFederateRequestTimeIterativeComplete(vFed1) h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) destroyBroker(broker)
def test_bad_inputs_broker_link(): broker = createBroker(1) vFed1, fedinfo = createValueFederate(1, "fed0") # register the publications h.helicsFederateRegisterGlobalTypePublication(vFed1, "pub1", "custom1", "") h.helicsFederateRegisterTypeInput(vFed1, "inp1", "custom2", "") br = h.helicsBrokerClone(broker) h.helicsBrokerDataLink(br, "pub1", "Testfed0/inp1") # TODO: This test should throw an error # @test_throws h.HELICSErrorInvalidArgument # with pt.raises(h.HelicsException): # h.helicsBrokerDataLink(br, "pub1", "") # @test_broken False # @test_throws h.HELICSErrorInvalidArgument with pt.raises(h.HelicsException): h.helicsBrokerMakeConnections(br, "unknownfile.json") # @test_throws h.HELICSErrorConnectionFailure with pt.raises(h.HelicsException): h.helicsFederateEnterExecutingMode(vFed1) h.helicsFederateFinalize(vFed1) destroyFederate(vFed1, fedinfo) h.helicsBrokerWaitForDisconnect(broker, 200) destroyBroker(broker)
def create_publication(self, pubInfo, device, cName, eName): self.__Logger.info("Creating publications") for propertyX in pubInfo["properties"]: keyword = self.cympy.app.GetKeyword(propertyX) if keyword is None: found, units, defaultValue, cType = self.isProperty( device, propertyX) if not found: raise Exception( f"{propertyX} is neither a valid keyword not a valid property of object type {cName}" ) res = device.GetValue(propertyX) else: res = self.cympy.study.QueryInfoDevice(propertyX, device.DeviceNumber, device.DeviceType) pubname = f"{self.fedName}.{cName}.{eName}.{propertyX}" T = self.type_info[keyword.Type.lower( )] if keyword is not None else self.type_info[cType] if res: self.Publications[pubname] = { "elementObj": device, "publicationObj": h.helicsFederateRegisterGlobalTypePublication( self.cymeFederate, pubname, T, keyword.Unit if keyword is not None else units), "class": cName, "name": eName, "property": propertyX, "unit": keyword.Unit if keyword is not None else units, "dType": keyword.Type if keyword is not None else cType, "isKeyword": True if keyword is not None else False } self.__Logger.debug( f"Publication {pubname} of type {T} registered successfully." ) else: self.__Logger.warning( f"Property {propertyX} for publication {pubname} not valid" ) return
def test_value_federate_publication_registration(vFed): pubid1 = h.helicsFederateRegisterTypePublication(vFed, "pub1", "string", "") pubid2 = h.helicsFederateRegisterGlobalTypePublication(vFed, "pub2", "int", "") pubid3 = h.helicsFederateRegisterTypePublication(vFed, "pub3", "double", "V") h.helicsFederateEnterExecutingMode(vFed) publication_key = h.helicsPublicationGetKey(pubid1) assert publication_key == "TestA Federate/pub1" publication_key = h.helicsPublicationGetKey(pubid2) assert publication_key == "pub2" publication_key = h.helicsPublicationGetKey(pubid3) assert publication_key == "TestA Federate/pub3" publication_type = h.helicsPublicationGetType(pubid3) assert publication_type == "double" publication_units = h.helicsPublicationGetUnits(pubid3) assert publication_units == "V"
def register_publications(self, bus_subsystems): self.publications = {} for bus_subsystem_id in self.settings['bus_subsystems'][ "publish_subsystems"]: if bus_subsystem_id in bus_subsystems: buses = bus_subsystems[bus_subsystem_id] for bus_id in buses: self.publications[bus_id] = {} for bus_p in self.bus_pubs: pub = "{}.bus-{}.{}".format( self.settings['Federate name'], bus_id, bus_p) self.publications[bus_id][ pub] = h.helicsFederateRegisterGlobalTypePublication( self.PSSEfederate, pub, 'double', '') self.logger.debug( "Publication registered: {}".format(pub)) return
def test_value_federate_subscription_and_publication_registration(vFed): pubid1 = h.helicsFederateRegisterTypePublication(vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "") pubid2 = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub2", h.HELICS_DATA_TYPE_INT, "") pubid3 = h.helicsFederateRegisterPublication(vFed, "pub3", "double", "V") subid1 = h.helicsFederateRegisterOptionalSubscription( vFed, "sub1", "double", "V") subid2 = h.helicsFederateRegisterOptionalTypeSubscription( vFed, "sub2", h.HELICS_DATA_TYPE_INT, "") subid3 = h.helicsFederateRegisterOptionalSubscription( vFed, "sub3", "double", "V")
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_valuefederate_publication_registration(): broker = createBroker() vFed, fedinfo = createValueFederate() pubid1 = h.helicsFederateRegisterTypePublication(vFed, "pub1", "string", "") pubid2 = h.helicsFederateRegisterGlobalTypePublication(vFed, "pub2", "int", "") pubid3 = h.helicsFederateRegisterTypePublication(vFed, "pub3", "double", "V") h.helicsFederateEnterExecutingMode(vFed) assert h.helicsPublicationGetKey(pubid1) == "TestA Federate/pub1" assert h.helicsPublicationGetKey(pubid2) == "pub2" assert h.helicsPublicationGetKey(pubid3) == "TestA Federate/pub3" assert h.helicsPublicationGetType(pubid3) == "double" assert h.helicsPublicationGetUnits(pubid3) == "V" destroyFederate(vFed, fedinfo) destroyBroker(broker)
def test_value_federate_runFederateTestVectorD(vFed): defaultValue = [0, 1, 2] testValue = [3, 4, 5] pubid = h.helicsFederateRegisterGlobalTypePublication( vFed, "pub1", h.HELICS_DATA_TYPE_VECTOR, "") subid = h.helicsFederateRegisterSubscription(vFed, "pub1", "vector", "") h.helicsSubscriptionSetDefaultVector(subid, defaultValue) h.helicsFederateEnterExecutionMode(vFed) # TODO: Fix error with the following function h.helicsPublicationPublishVector(pubid, testValue) status, value = h.helicsSubscriptionGetVector(subid) assert value == [0, 1, 2] status, grantedtime = h.helicsFederateRequestTime(vFed, 1.0) assert grantedtime == 0.01 status, value = h.helicsSubscriptionGetVector(subid) assert value == [3, 4, 5]
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(): # broker = create_broker() fed = create_federate() pubid = h.helicsFederateRegisterGlobalTypePublication( fed, "TransmissionSim/B2Voltage", h.HELICS_DATA_TYPE_COMPLEX, "") subid = h.helicsFederateRegisterSubscription( fed, "DistributionSim_B2_G_1/totalLoad", "complex", "") epid = h.helicsFederateRegisterEndpoint(fed, "ep1", None) h.helicsSubscriptionSetDefaultComplex(subid, 0, 0) h.helicsFederateEnterExecutionMode(fed) hours = 1 seconds = int(60 * 60 * hours) grantedtime = -1 random.seed(0) for t in range(0, seconds, 60 * 5): c = complex(132790.562, 0) * (1 + (random.random() - 0.5) / 2) logger.info("Voltage value = {} kV".format(abs(c) / 1000)) status = h.helicsPublicationPublishComplex(pubid, c.real, c.imag) # status = h.helicsEndpointSendEventRaw(epid, "fixed_price", 10, t) while grantedtime < t: status, grantedtime = h.helicsFederateRequestTime(fed, t) time.sleep(1) status, rValue, iValue = h.helicsSubscriptionGetComplex(subid) logger.info("Python Federate grantedtime = {}".format(grantedtime)) logger.info("Load value = {} MW".format( complex(rValue, iValue) / 1000)) t = 60 * 60 * 24 while grantedtime < t: status, grantedtime = h.helicsFederateRequestTime(fed, t) logger.info("Destroying federate") destroy_federate(fed)
federate_name = f"SenderFederate{sys.argv[1]}" print(f"{federate_name}: Helics version = {h.helicsGetVersion()}") fedinfo = h.helicsCreateFederateInfo() h.helicsFederateInfoSetCoreName(fedinfo, federate_name + "Core") h.helicsFederateInfoSetCoreTypeFromString(fedinfo, "zmq") h.helicsFederateInfoSetCoreInitString(fedinfo, "--federates=1") h.helicsFederateInfoSetTimeProperty(fedinfo, h.helics_property_time_delta, 0.01) vfed = h.helicsCreateValueFederate(federate_name, fedinfo) print(f"{federate_name}: Value federate created") 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
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("TestA Federate", fedinfo) print("PI SENDER: Value federate created") # Register the publication # pub = h.helicsFederateRegisterGlobalTypePublication(vfed, "testA", "double", "") 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.helicsFederateInfoSetCoreInitString(fedinfo, federateinitstring) # 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("TestA Federate", fedinfo) print("PI SENDER: Value federate created") # Register the publication # pub = h.helicsFederateRegisterGlobalTypePublication(vfed, "testA", "double", "") 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)
# 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) #h.helicsFederateInfoSetIntegerProperty(fedinfo, h.helics_property_int_log_level, 20) # Create value federate # vfed = h.helicsCreateValueFederate("Test Federate", fedinfo) print("PI SENDER: Value federate created") pubA = h.helicsFederateRegisterGlobalTypePublication( vfed, "test.feederhead.voltageA", "double", "kVLN") pubB = h.helicsFederateRegisterGlobalTypePublication( vfed, "test.feederhead.voltageB", "double", "kVLN") pubC = h.helicsFederateRegisterGlobalTypePublication( vfed, "test.feederhead.voltageC", "double", "kVLN") print("PI SENDER: Publication registered") sub1 = h.helicsFederateRegisterSubscription( vfed, "CYME.Source.DEMO-STATION-S1.KWTOT", "") sub1 = h.helicsFederateRegisterSubscription( vfed, "CYME.Source.DEMO-STATION-S1.KVARTOT", "") #h.helicsInputSetMinimumChange(sub1, 0.1) # Enter execution mode # h.helicsFederateEnterExecutingMode(vfed) basevolt = 4.16
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 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))
# 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, 60 * 60) #h.helicsFederateInfoSetIntegerProperty(fedinfo, h.helics_property_int_log_level, 20) # Create value federate # vfed = h.helicsCreateValueFederate("Test Federate", fedinfo) print("PI SENDER: Value federate created") pubA = h.helicsFederateRegisterGlobalTypePublication(vfed, "test.load1.P", "double", "") pubB = h.helicsFederateRegisterGlobalTypePublication(vfed, "test.load1.Q", "double", "") pubC = h.helicsFederateRegisterGlobalTypePublication(vfed, "test.load2.P", "double", "") pubD = h.helicsFederateRegisterGlobalTypePublication(vfed, "test.load2.Q", "double", "") print("PI SENDER: Publication registered") sub1 = h.helicsFederateRegisterSubscription(vfed, "psse.Buses.153.PU", "") sub2 = h.helicsFederateRegisterSubscription(vfed, "psse.Buses.154.PU", "") #h.helicsInputSetMinimumChange(sub1, 0.1) # Enter execution mode # h.helicsFederateEnterExecutingMode(vfed) basevolt = 2.40 X = 20.0 currenttime = 0 for t in range(0, 25):
############## Registering federate and configuring with API ########################## fedinitstring = " --federates=1" name = "Charger" period = 60 fed = create_value_federate(fedinitstring, name, period) logger.info(f'Created federate {name}') print(f'Created federate {name}') num_EVs = 5 pub_count = num_EVs pubid = {} for i in range(0, pub_count): # "key":"Battery/EV1_current", pub_name = f'Charger/EV{i+1}_voltage' pubid[i] = h.helicsFederateRegisterGlobalTypePublication( fed, pub_name, 'double', 'V') logger.debug(f'\tRegistered publication---> {pub_name}') sub_count = num_EVs subid = {} for i in range(0, sub_count): sub_name = f'Battery/EV{i+1}_current' subid[i] = h.helicsFederateRegisterSubscription(fed, sub_name, 'A') logger.debug(f'\tRegistered subscription---> {sub_name[i]}') sub_count = h.helicsFederateGetInputCount(fed) logger.debug(f'\tNumber of subscriptions: {sub_count}') pub_count = h.helicsFederateGetPublicationCount(fed) logger.debug(f'\tNumber of publications: {pub_count}') ############## Entering Execution Mode ##################################