Esempio n. 1
0
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 test_combination_federate():

    broker = createBroker()

    cfed = h.helicsCreateCombinationFederateFromConfig(
        os.path.join(CURRENT_DIRECTORY, "combinationfederate.json"))

    assert h.helicsFederateIsValid(cfed)

    assert h.helicsFederateGetEndpointCount(cfed) == 2
    assert h.helicsFederateGetFilterCount(cfed) == 0
    assert h.helicsFederateGetInputCount(cfed) == 2

    ept = h.helicsFederateGetEndpointByIndex(cfed, 0)

    assert h.helicsEndpointGetName(ept) == "ept1"

    ipt = h.helicsFederateGetInputByIndex(cfed, 1)
    assert h.helicsInputGetExtractionUnits(ipt) == ""
    assert h.helicsSubscriptionGetKey(ipt) == "comboFed/pub2"

    h.helicsEndpointClearMessages(ept)

    h.helicsFederateDestroy(cfed)
    h.helicsFederateFree(cfed)
    h.helicsBrokerDestroy(broker)
    h.helicsCloseLibrary()
Esempio n. 3
0
    logger.info(f'\tNumber of publications: {pub_count}')
    print(f'Created federate {federate_name}')
    print(f'\tNumber of endpoints: {end_count}')
    print(f'\tNumber of subscriptions: {sub_count}')
    print(f'\tNumber of publications: {pub_count}')

    # Diagnostics to confirm JSON config correctly added the required
    #   endpoints, publications, and subscriptions.
    endid = {}
    for i in range(0, end_count):
        endid[i] = h.helicsFederateGetEndpointByIndex(fed, i)
        end_name = h.helicsEndpointGetName(endid[i])
        logger.debug(f'\tRegistered Endpoint ---> {end_name}')
    subid = {}
    for i in range(0, sub_count):
        subid[i] = h.helicsFederateGetInputByIndex(fed, i)
        sub_name = h.helicsSubscriptionGetKey(subid[i])
        logger.debug(f'\tRegistered subscription---> {sub_name}')

    pubid = {}
    for i in range(0, pub_count):
        pubid[i] = h.helicsFederateGetPublicationByIndex(fed, i)
        pub_name = h.helicsPublicationGetKey(pubid[i])
        logger.debug(f'\tRegistered publication---> {pub_name}')

    ##############  Entering Execution Mode  ##################################
    h.helicsFederateEnterExecutingMode(fed)
    logger.info('Entered HELICS execution mode')

    # Definition of charging power level (in kW) for level 1, 2, 3 chargers
    charge_rate = [1.8, 7.2, 50]
    fed = h.helicsCreateValueFederateFromConfig('Transmission_json.json')
    status = h.helicsFederateRegisterInterfaces(fed, 'Transmission_json.json')
    federate_name = h.helicsFederateGetName(fed)[-1]
    print(" Federate {} has been registered".format(federate_name))
    pubkeys_count = h.helicsFederateGetPublicationCount(fed)
    subkeys_count = h.helicsFederateGetInputCount(fed)
    print(subkeys_count)
    ######################   Reference to Publications and Subscription form index  #############################
    pubid = {}
    subid = {}
    for i in range(0, pubkeys_count):
        pubid["m{}".format(i)] = h.helicsFederateGetPublicationByIndex(fed, i)
        pubtype = h.helicsPublicationGetType(pubid["m{}".format(i)])
        print(pubtype)
    for i in range(0, subkeys_count):
        subid["m{}".format(i)] = h.helicsFederateGetInputByIndex(fed, i)
        status = h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0)
        sub_key = h.helicsSubscriptionGetKey(subid["m{}".format(i)])
        print('Registered Subscription ---> {}'.format(sub_key))

######################   Entereing Execution Mode  ##########################################################
    status = h.helicsFederateEnterInitializingMode(fed)
    status = h.helicsFederateEnterExecutingMode(fed)

    #Pypower Processing (inputs)
    hours = 24
    total_inteval = int(60 * 60 * hours)
    grantedtime = -1
    pf_interval = 5 * 60  # in seconds (minimim_resolution)
    acopf_interval = 15 * 60  # in seconds (minimim_resolution)
    random.seed(0)
Esempio n. 5
0
def test_valuefederate_subscription_and_publication_registration():

    broker = createBroker()
    vFed, fedinfo = createValueFederate(1, "fed0")

    pubid = h.helicsFederateRegisterPublication(vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "")
    pubid2 = h.helicsFederateRegisterGlobalPublication(vFed, "pub2", h.HELICS_DATA_TYPE_INT, "volts")
    pubid3 = h.helicsFederateRegisterTypePublication(vFed, "pub3", "double", "V")

    subid1 = h.helicsFederateRegisterSubscription(vFed, "sub1", "")
    subid2 = h.helicsFederateRegisterSubscription(vFed, "sub2", "")
    subid3 = h.helicsFederateRegisterSubscription(vFed, "sub3", "V")

    h.helicsFederateEnterExecutingMode(vFed)

    publication_type = h.helicsPublicationGetType(pubid3)
    assert publication_type == "double"

    sub_key = h.helicsSubscriptionGetKey(subid1)
    assert sub_key == "sub1"
    sub_type = h.helicsInputGetType(subid1)
    assert sub_type == ""
    sub_key = h.helicsSubscriptionGetKey(subid2)
    assert sub_key == "sub2"
    sub_key = h.helicsSubscriptionGetKey(subid3)
    assert sub_key == "sub3"
    sub_type = h.helicsInputGetType(subid3)
    assert sub_type == ""
    sub_units = h.helicsInputGetUnits(subid3)
    assert sub_units == "V"
    sub_type = h.helicsInputGetType(subid2)
    assert sub_type == ""

    subid_b = h.helicsFederateGetSubscription(vFed, "sub1")
    tmp = h.helicsSubscriptionGetKey(subid_b)
    assert tmp == "sub1"
    # check the getSubscriptionByIndex function
    subid_c = h.helicsFederateGetInputByIndex(vFed, 2)
    tmp = h.helicsInputGetUnits(subid_c)
    assert tmp == "V"
    # check publications

    sv = h.helicsPublicationGetKey(pubid)
    sv2 = h.helicsPublicationGetKey(pubid2)
    assert sv == "Testfed0/pub1"
    assert sv2 == "pub2"
    pub3name = h.helicsPublicationGetKey(pubid3)
    assert pub3name == "Testfed0/pub3"

    type = h.helicsPublicationGetType(pubid3)
    assert type == "double"
    units = h.helicsPublicationGetUnits(pubid3)
    assert units == "V"

    # check the getSubscription function

    pubid_b = h.helicsFederateGetPublication(vFed, "Testfed0/pub1")
    tmp = h.helicsPublicationGetType(pubid_b)
    assert tmp == "string"
    # check the getSubscriptionByIndex function
    pubid_c = h.helicsFederateGetPublicationByIndex(vFed, 1)
    tmp = h.helicsPublicationGetUnits(pubid_c)
    assert tmp == "volts"

    # this one should be invalid
    # @test_throws h.HELICSErrorInvalidArgument pubid_d = h.helicsFederateGetPublicationByIndex(vFed, 5)

    h.helicsFederateFinalize(vFed)

    state = h.helicsFederateGetState(vFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(vFed, fedinfo)
    destroyBroker(broker)
Esempio n. 6
0
def federate_example(config_path):
    # Registering  federate from json

    try:
        fed = h.helicsCreateCombinationFederateFromConfig(config_path)
    except h._helics.HelicsException as exc:
        print("Exception occured".format(exc))
        exit(-1)
    federate_name = h.helicsFederateGetName(fed)
    print(federate_name)
    endpoint_count = h.helicsFederateGetEndpointCount(fed)
    subkeys_count = h.helicsFederateGetInputCount(fed)
    pubkeys_count = h.helicsFederateGetPublicationCount(fed)

    # Reference to Publications and Subscription form index
    endid = {}
    subid = {}
    pubid = {}
    for i in range(0,endpoint_count):
        endid["m{}".format(i)] = h.helicsFederateGetEndpointByIndex(fed, i)
        end_name = h.helicsEndpointGetName(endid["m{}".format(i)])
        logger.info( 'Registered Endpoint ---> {}'.format(end_name))

    for i in range(0, subkeys_count):
        idx = h.helicsFederateGetInputByIndex(fed, i)
        subid["m{}".format(i)] = idx
        status = h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0)
        sub_key = h.helicsSubscriptionGetKey(idx)
        logger.info( 'Registered Subscription ---> {}'.format(sub_key))

    for i in range(0, pubkeys_count):
        idx = h.helicsFederateGetPublicationByIndex(fed, i)
        pubid["m{}".format(i)] = idx
        pub_key = h.helicsPublicationGetKey(idx)
        logger.info( 'Registered Publications ---> {}'.format(pub_key))

    print('###############################################################################################')
    print('########################   Entering Execution Mode  ##########################################')
    # Entering Execution Mode
    h.helicsFederateEnterExecutingMode(fed)
    print('###############################################################################################')

    hours = 0.1
    total_inteval = int(60 * 60 * hours)
    grantedtime = -1
    update_interval = 1 # 5*60
    k = 0
    data ={}
    time.sleep(5)
    time_sim = []
    real = 0
    for t in range(0, total_inteval, update_interval):
        while grantedtime < t:
            grantedtime = h.helicsFederateRequestTime (fed, t)
        time.sleep(0.1)
        print('########################   Time interval {}  ##########################################'.format(t))
        print('########################   Publishing to topics  ######################################')
        real = real + 1
        for i in range(0, pubkeys_count):
            idx = pubid["m{}".format(i)]
            h.helicsPublicationPublishComplex(idx, real*i, 78)

        print( '########################   Get input from subscribed topics  #########################')
        for i in range(0, subkeys_count):
            idx = subid["m{}".format(i)]
            value = h.helicsInputGetDouble(idx)
            key = h.helicsSubscriptionGetKey(idx)
            print("Value for key: {} is {}".format(key, value))

        print('########################   Get from Endpoint  #########################################')
        idx = endid["m{}".format(0)]
        while h.helicsEndpointHasMessage(idx):            
            msg = h.helicsEndpointGetMessage(idx)
            end_name = h.helicsEndpointGetName(idx)
            print("Value from endpoint name: {} is {}".format(end_name, msg.data))

        print('########################   Send to VOLTTRON Endpoint  #################################')
        for i in range(0, endpoint_count):
            idx = endid["m{}".format(i)]
            value = i + random.randint(1, 101) + 89.7
            end_name = h.helicsEndpointGetName(idx)
            print("Sending Value:{0} for endpoint: {1}".format(value, end_name))
            h.helicsEndpointSendEventRaw(idx, '', str(value), t)
            end_name = h.helicsEndpointGetName(idx)

    logger.info("Destroying federate")
    destroy_federate(fed)
Esempio n. 7
0
    def register_inputs(self, config=None, callback=None, **kwargs):
        """
        Register configuration parameters with HELICS. The config parameters may include
        but not limited to:
        1. Name of the federate
        2. simulation length
        2. Type of core to use (zmq/tcp/udp etc)
        3. list (and type) of subscriptions
        4. list (and type) of publications
        5. broker address (if not default)
        :param config: config parameters
        :param callback: Register agent callback method
        :return:
        """
        self._work_callback = callback
        # Build HELICS config from agent config
        helics_config = deepcopy(config)

        properties = helics_config.pop('properties', {})
        if not properties:
            raise RuntimeError(
                "Invalid configuration. Missing properties dictionary")
        self._simulation_delta = properties.pop('timeDelta', 1.0)  # seconds
        self._simulation_length = properties.pop('simulation_length',
                                                 3600)  # seconds

        for key, value in properties.items():
            helics_config[key] = value
        subscriptions = helics_config.pop('outputs', [])
        for sub in subscriptions:
            volttron_topic = sub.pop('volttron_topic', None)
            if volttron_topic is not None:
                self.helics_to_volttron_publish[sub.get(
                    'key')] = volttron_topic
            sub['key'] = sub.pop('sim_topic')
        # Replace 'outputs' key with 'subscriptions' key
        if subscriptions:
            helics_config['subscriptions'] = subscriptions

        publications = helics_config.pop('inputs', [])
        for pub in publications:
            volttron_topic = pub.pop('volttron_topic', None)
            pub['key'] = pub.pop('sim_topic')
        # Replace 'inputs' key with 'publications' key
        if publications:
            helics_config['publications'] = publications
        _log.debug("new config: {}".format(helics_config))

        # Create a temporary json file
        tmp_file = os.path.join(os.getcwd(), 'fed_cfg.json')
        _log.debug("tmp file: {}".format(tmp_file))
        with open(tmp_file, 'w') as fout:
            fout.write(jsonapi.dumps(helics_config))

        _log.debug("Create Combination Federate")
        # Create federate from provided config parameters
        try:
            self.fed = h.helicsCreateCombinationFederateFromConfig(tmp_file)
        except h._helics.HelicsException as e:
            _log.exception("Error parsing HELICS config {}".format(e))

        # Check if HELICS broker correctly registered inputs
        federate_name = h.helicsFederateGetName(self.fed)
        _log.debug("Federate name: {}".format(federate_name))
        endpoint_count = h.helicsFederateGetEndpointCount(self.fed)
        _log.debug("Endpoint count: {}".format(endpoint_count))
        subkeys_count = h.helicsFederateGetInputCount(self.fed)
        _log.debug("Subscription key count: {}".format(subkeys_count))
        pubkeys_count = h.helicsFederateGetPublicationCount(self.fed)
        _log.debug("Publication key count: {}".format(endpoint_count))

        for i in range(0, endpoint_count):
            try:
                endpt_idx = h.helicsFederateGetEndpointByIndex(self.fed, i)
                endpt_name = h.helicsEndpointGetName(endpt_idx)
                self.endpoints[endpt_name] = endpt_idx
            except h._helics.HelicsException as e:
                _log.exception(
                    "Error getting helics endpoint index: {}".format(e))

        for i in range(0, subkeys_count):
            inputs = dict()
            try:
                idx = h.helicsFederateGetInputByIndex(self.fed, i)
                inputs['sub_id'] = idx
                inputs['type'] = h.helicsInputGetType(idx)
                inputs['key'] = h.helicsSubscriptionGetKey(idx)
                self.inputs.append(inputs)
                data = dict(type=inputs['type'], value=None)
            except h._helics.HelicsException as e:
                _log.exception(
                    "Error getting helics input index: {}".format(e))

        for i in range(0, pubkeys_count):
            outputs = dict()
            try:
                idx = h.helicsFederateGetPublicationByIndex(self.fed, i)
                outputs['pub_id'] = idx
                outputs['type'] = h.helicsPublicationGetType(idx)
                pub_key = h.helicsPublicationGetKey(idx)
                _log.debug("Publication: {}".format(pub_key))
                self.outputs[pub_key] = outputs
                data = dict(type=outputs['type'], value=None)
            except h._helics.HelicsException as e:
                _log.exception(
                    "Error getting helics publication index: {}".format(e))