def start(log_file, feeder_mrid, model_api_topic):
    global logfile
    logfile = log_file

    global G, measid_lbs, loadbreaksw, undirected_graph  

    print("\nTOPOLOGY_VALIDATOR starting!!!------------------------------------------------------------")
    print("\nTOPOLOGY_VALIDATOR starting!!!------------------------------------------------------------", file=logfile)

    gapps = GridAPPSD()
    # NOTE: Use of modelType as STATIC or OPERATIONAL will change the response
    message = {"modelId": feeder_mrid,
                   "requestType": "LOOPS",
                   "modelType": "OPERATIONAL",
                   "resultFormat": "JSON"}
    out_topic = "/topic/goss.gridappsd.model-validator.topology.out"
    gapps.subscribe(out_topic, on_message)

    in_topic = "/topic/goss.gridappsd.model-validator.topology.in"
    gapps.send(in_topic, message)
    print("TOPOLOGY_VALIDATOR sent request to microservice; waiting for response\n", flush=True)
    print("TOPOLOGY_VALIDATOR sent request to microservice; waiting for response\n", file=logfile)
    
    global exit_flag
    exit_flag = False

    while not exit_flag:
        time.sleep(0.1)
Beispiel #2
0
def _main():
    _log.debug("Starting application")
    print(
        "Application starting!!!-------------------------------------------------------"
    )
    global message_period

    # arguments to be passed
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "simulation_id",
        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request", help="Simulation Request")
    parser.add_argument(
        "--message_period",
        help="How often the sample app will send open/close capacitor message.",
        default=DEFAULT_MESSAGE_PERIOD)
    opts = parser.parse_args()
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    message_period = int(opts.message_period)
    sim_request = json.loads(opts.request.replace("\'", ""))
    model_mrid = sim_request["power_system_config"]["Line_name"]
    _log.debug("Model mrid is: {}".format(model_mrid))

    # Interaction with the web-based GridAPPSD interface
    gapps = GridAPPSD(opts.simulation_id,
                      address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(),
                      password=utils.get_gridappsd_pass())

    # the three lines (uncommented) below are from Shiva
    '''
    The Powergrid Model Data Manager API allows you to query the powergrid model data store.
    
    Query request should be sent on following queue: 
    goss.gridappsd.process.request.data.powergridmodel
    
    i.e. if I want any powergrid component data then the query above has to be addressed
    '''
    topic = "goss.gridappsd.process.request.data.powergridmodel"

    # returns the MRID for AC lines and switch
    ACline, obj_msr_loadsw, obj_msr_reg, switches, regulators = get_meas_mrid(
        gapps, model_mrid, topic)

    # print("\n ************ ACLine ********* \n")
    # print(ACline)

    # print("\n ************ obj_msr_loadsw ********* \n")
    # print(obj_msr_loadsw)
    # print(sh)

    # toggling the switch ON and OFF
    toggler = NodalVoltage(opts.simulation_id, gapps, ACline, obj_msr_loadsw,
                           obj_msr_reg, switches, regulators)

    # gapps.subscribe calls the on_message function
    gapps.subscribe(listening_to_topic, toggler)
    while True:
        time.sleep(0.1)
Beispiel #3
0
def _main():
    parser = argparse.ArgumentParser()
    parser.add_argument("simulation_id",
                        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request",
                        help="Simulation Request")
    # These are now set through the docker container interface via env variables or defaulted to
    # proper values.
    #
    # parser.add_argument("-u", "--user", default="system",
    #                     help="The username to authenticate with the message bus.")
    # parser.add_argument("-p", "--password", default="manager",
    #                     help="The password to authenticate with the message bus.")
    # parser.add_argument("-a", "--address", default="127.0.0.1",
    #                     help="tcp address of the mesage bus.")
    # parser.add_argument("--port", default=61613, type=int,
    #                     help="the stomp port on the message bus.")
    #
    opts = parser.parse_args()
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    #TODO: read this from simulation request as below 
    # message_interval = sim_request["service_config"]["voltage-violation"]["message_interval"]
    message_interval = 5
    sim_request = json.loads(opts.request.replace("\'",""))
    model_mrid = sim_request["power_system_config"]["Line_name"]
    gapps = GridAPPSD(opts.simulation_id, address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(), password=utils.get_gridappsd_pass())
    nominal_voltage_dict = get_nominal_voltage(gapps, model_mrid)
    subscriber = SimulationSubscriber(opts.simulation_id, gapps, nominal_voltage_dict, message_interval)
    gapps.subscribe(listening_to_topic, subscriber)
    while True:
        time.sleep(0.1)
def _main():
    _log.debug("Starting application")
    print(
        "Application starting!!!-------------------------------------------------------"
    )
    global message_period
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "simulation_id",
        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request", help="Simulation Request")
    parser.add_argument(
        "--message_period",
        help="How often the sample app will send open/close capacitor message.",
        default=DEFAULT_MESSAGE_PERIOD)
    opts = parser.parse_args()
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    message_period = int(opts.message_period)
    sim_request = json.loads(opts.request.replace("\'", ""))
    model_mrid = sim_request["power_system_config"]["Line_name"]
    _log.debug("Model mrid is: {}".format(model_mrid))
    gapps = GridAPPSD(opts.simulation_id,
                      address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(),
                      password=utils.get_gridappsd_pass())
    topic = "goss.gridappsd.process.request.data.powergridmodel"

    # Run several query to extract the model information
    ACline, obj_msr_loadsw = get_meas_mrid(gapps, model_mrid, topic)

    # Subscribe to simulation output and interface to platform
    toggler = LearnPlatform(opts.simulation_id, gapps, ACline, obj_msr_loadsw)
    gapps.subscribe(listening_to_topic, toggler)
    while True:
        time.sleep(0.1)
Beispiel #5
0
    def __init__(self, gad: GridAPPSD, sim_id: str, sim_start_ts: int,
                 log_interval=60):
        """Initialize attributes, subscribe to the simulation log.

        :param gad: Initialized gridappsd.GridAPPSD object.
        :param sim_id: Simulation ID of the simulation to track.
        :param sim_start_ts: Simulation start timestamp in seconds since
            the epoch.
        :param log_interval: How many simulation seconds in between
            logging the current simulation time.
        """
        # Setup logging.
        self.log = logging.getLogger(self.__class__.__name__)

        # Simply set the simulation starting time as an attribute.
        self.sim_start_ts = sim_start_ts
        self.log_interval = log_interval

        # Use attributes for tracking the simulation time and current
        # time (as indicated by the most recent message).
        self.sim_time = None
        self.time_step = None
        self.msg_time = None
        self.last_log_time = None

        # Compile a regular expression for extracting the time from the
        # message.
        self.regexp = re.compile('(?:incrementing to )([0-9]+)')

        # Subscribe to the simulation log.
        gad.subscribe(topic=topics.simulation_log_topic(sim_id),
                      callback=self._on_message)

        self.log.info('SimulationClock configured and initialized.')
Beispiel #6
0
def _main():
    _log.debug("Starting application")
    print(
        "Application starting-------------------------------------------------------"
    )
    global message_period
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "simulation_id",
        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request", help="Simulation Request")
    parser.add_argument(
        "--message_period",
        help="How often the sample app will send open/close capacitor message.",
        default=DEFAULT_MESSAGE_PERIOD)
    # These are now set through the docker container interface via env variables or defaulted to
    # proper values.
    #
    # parser.add_argument("-u", "--user", default="system",
    #                     help="The username to authenticate with the message bus.")
    # parser.add_argument("-p", "--password", default="manager",
    #                     help="The password to authenticate with the message bus.")
    # parser.add_argument("-a", "--address", default="127.0.0.1",
    #                     help="tcp address of the mesage bus.")
    # parser.add_argument("--port", default=61613, type=int,
    #                     help="the stomp port on the message bus.")
    #
    opts = parser.parse_args()
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    print(listening_to_topic)
    message_period = int(opts.message_period)
    sim_request = json.loads(opts.request.replace("\'", ""))
    model_mrid = sim_request["power_system_config"]["Line_name"]
    print("\n \n The model running is IEEE 123 node with MRID:")
    print(model_mrid)

    _log.debug("Model mrid is: {}".format(model_mrid))
    gapps = GridAPPSD(opts.simulation_id,
                      address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(),
                      password=utils.get_gridappsd_pass())

    # Get measurement MRIDS for primary nodes in the feeder
    topic = "goss.gridappsd.process.request.data.powergridmodel"
    message = {
        "modelId": model_mrid,
        "requestType": "QUERY_OBJECT_MEASUREMENTS",
        "resultFormat": "JSON",
        "objectType": "ACLineSegment"
    }
    obj_msr_loads = gapps.get_response(topic, message, timeout=90)
    # print(obj_msr_loads)
    with open('measid.json', 'w') as json_file:
        json.dump(obj_msr_loads, json_file)

    toggler = SwitchingActions(opts.simulation_id, gapps, obj_msr_loads)
    print("Now subscribing")
    gapps.subscribe(listening_to_topic, toggler)
    while True:
        time.sleep(0.1)
Beispiel #7
0
def _main():
    from gridappsd import utils
    _log.info("Starting application")
    _log.info(str(sys.argv))
    _log.info("Args ")
    for arg in sys.argv[1:]:
        _log.info(type(arg))
        _log.info(arg)

    # _log.info("Run local only -JEFF")
    # exit(0)
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "simulation_id",
        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request", help="Simulation Request")
    parser.add_argument("opt", help="opt")
    opts = parser.parse_args()
    _log.info(opts)
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    print(opts.request)
    sim_request = json.loads(opts.request.replace("\'", ""))
    model_mrid = sim_request['power_system_config']['Line_name']
    start_time = sim_request['simulation_config']['start_time']
    app_config = sim_request["application_config"]["applications"]
    print(app_config)

    # app_config = [json.loads(app['config_string']) for app in app_config if app['name'] == 'solar_forecasting_app'][0]
    app = [
        app for app in app_config if app['name'] == 'solar_forecasting_app'
    ][0]
    print(app)
    if app['config_string']:
        # app_config = json.loads(app['config_string'])
        app_config = json.loads(app['config_string'].replace(u'\u0027', '"'))
    else:
        app_config = {'run_freq': 60, 'run_on_host': False}

    ## Run the docker container. WOOT!
    if 'run_on_host' in app_config and app_config['run_on_host']:
        exit(0)

    _log.info("Model mrid is: {}".format(model_mrid))
    gapps = GridAPPSD(opts.simulation_id,
                      address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(),
                      password=utils.get_gridappsd_pass())

    print(listening_to_topic)
    # gapps = GridAPPSD(opts.simulation_id)
    solar_forecast = Solar_Forecast(opts.simulation_id, gapps, model_mrid,
                                    start_time, app_config)
    gapps.subscribe(listening_to_topic, solar_forecast)
    # gapps.subscribe(ghi_weather_topic, solar_forecast)

    # ls_output = subprocess.Popen(["python solar_forecasting/util/post_goss_ghi.py","1357048800","720" , "10"], stdout=subprocess.PIPE)

    while True:
        time.sleep(0.1)
Beispiel #8
0
class GridAPPSDVolttron(Agent):
    """
    Document agent constructor here.
    """
    def __init__(self, setting1=1, setting2="some/random/topic", **kwargs):
        super(GridAPPSDVolttron, self).__init__(**kwargs)
        self._gapps = None
        self._publish_event = None
        self._test_topic = "/topic/data"
        self._receiver_thread = None

    def receiver_thread(self, arg):
        self._receiver_thread = gevent.threading.Thread(group=None, target=arg)
        self._receiver_thread.daemon = True  # Don't let thread prevent termination
        self._receiver_thread.start()
        return self._receiver_thread

    def publish_next(self):
        _log.debug("Publishing next")
        if self._publish_event is not None:
            self._publish_event.cancel()
        self._gapps.send(self._test_topic, "foo bar")
        if self._gapps.connected:
            self._gapps.send("/queue/test", "foo bar")
        else:
            print("Not connected")
        now = get_aware_utc_now()
        print(utils.get_utc_seconds_from_epoch(now))
        next_update_time = now + datetime.timedelta(seconds=5)
        _log.debug(f'Scheduling nex time {next_update_time}')
        self._publish_event = self.core.schedule(next_update_time,
                                                 self.publish_next)
        _log.debug(f'After scheduling next time {next_update_time}')
        gevent.sleep(0.1)

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):
        self._gapps = GridAPPSD(override_threading=self.receiver_thread)

        # goss_log_level=logging.DEBUG)
        # stomp_log_level=logging.DEBUG)

        def message_published(headers, body):
            _log.debug(f"Received from gridappsd {headers}, body: {body}")
            self.vip.pubsub.publish('pubsub',
                                    "data/foo",
                                    headers=headers,
                                    message=body)

        self._gapps.subscribe(self._test_topic, message_published)
        gevent.sleep(0.1)
        self.publish_next()

    @Core.receiver("onstop")
    def onstop(self, sender, **kwargs):
        print("Stopping data!")

        # self._gapps.disconnect()
        print("After disconnect")
def _main_local():
    simulation_id =1543123248
    listening_to_topic = simulation_output_topic(simulation_id)

    model_mrid = '_E407CBB6-8C8D-9BC9-589C-AB83FBF0826D'

    gapps = GridAPPSD(simulation_id)
    # __GRIDAPPSD_URI__ = os.environ.get("GRIDAPPSD_URI", "localhost:61613")
    # gapps = GridAPPSD(simulation_id, address=__GRIDAPPSD_URI__)
    solar_forecast = Solar_Forecast(simulation_id, gapps, model_mrid, 1357048800)
    gapps.subscribe(ghi_weather_topic, solar_forecast)

    while True:
        time.sleep(0.1)
Beispiel #10
0
class GOSSListener(object):
    def __init__(self, simID, measDict, appName):
        """Initialize a GOSSListener."""
        # Set properties from inputs
        self.measDict = measDict
        self.simID = simID
        self.appName = appName

        # Create a GridAPPSD object and subscribe to simulation output.
        self.gossObj = GridAPPSD(simulation_id=self.simID,
                                 source=self.appName,
                                 base_simulation_status_topic=SIM_LOG)
        self.gossObj.subscribe(SIM_OUT, self)

        # Initialize dictionary for storing simulation data
        # TODO: we probably shouldn't stack this up in memory... recipe for
        # disaster.
        self.data = {}

    def on_message(self, headers, msg):
        """Forward relevant information along."""
        # Get the message as a dictionary.
        msg = json.loads(msg)

        # Grabe the timestamp
        t = int(msg['timestamp'])

        # Ensure we don't have this timestamp already.
        try:
            self.data[t]
        except KeyError:
            # Good, we don't have the key. Create it.
            self.data[t] = {}
        else:
            # This key already exists? We're in trouble...
            raise UserWarning("We already have data for time {}".format)

        # Get the simulation output as a dictionary.
        # May need to wrap this in a try-catch, TBD
        simOut = json.loads(msg['output'])

        # Loop over our measurements, extract info from the sim output
        for k in self.measDict:
            self.data[t][k] = simOut[self.simID][k]
            print(simOut[self.simID][k])
Beispiel #11
0
def _main():
    _log.debug("Starting application"
               )  # display of log messages while the simulation is running
    # th elogs are displayed on the web based simulation (you can check this while running the simulation)
    print(
        "Application starting!!!-------------------------------------------------------"
    )
    global message_period
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "simulation_id",
        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request", help="Simulation Request")
    parser.add_argument(
        "--message_period",
        help="How often the sample app will send open/close capacitor message.",
        default=DEFAULT_MESSAGE_PERIOD)
    # These are now set through the docker container interface via env variables or defaulted to
    # proper values.
    #
    # parser.add_argument("-u", "--user", default="system",
    #                     help="The username to authenticate with the message bus.")
    # parser.add_argument("-p", "--password", default="manager",
    #                     help="The password to authenticate with the message bus.")
    # parser.add_argument("-a", "--address", default="127.0.0.1",
    #                     help="tcp address of the mesage bus.")
    # parser.add_argument("--port", default=61613, type=int,
    #                     help="the stomp port on the message bus.")
    #
    opts = parser.parse_args()
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    message_period = int(opts.message_period)
    sim_request = json.loads(opts.request.replace("\'", ""))
    model_mrid = sim_request["power_system_config"]["Line_name"]
    _log.debug("Model mrid is: {}".format(model_mrid))  # object MRID
    gapps = GridAPPSD(opts.simulation_id,
                      address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(),
                      password=utils.get_gridappsd_pass())

    capacitors = get_capacitor_mrids(gapps, model_mrid)
    toggler = CapacitorToggler(opts.simulation_id, gapps, capacitors)
    gapps.subscribe(listening_to_topic, toggler)
    while True:
        time.sleep(0.1)
def start(log_file, feeder_mrid, model_api_topic):
    global logfp
    logfp = log_file

    global xfm_df, load_df, der_df
    
    print("\nTRANSFORMER_CAPACITY starting!!!------------------------------------------------")
    print("\nTRANSFORMER_CAPACITY starting!!!------------------------------------------------", file=logfp)

    SPARQLManager = getattr(importlib.import_module('shared.sparql'), 'SPARQLManager')

    gapps = GridAPPSD()

    sparql_mgr = SPARQLManager(gapps, feeder_mrid, model_api_topic)

    # Get transformer data
    xfm_df = sparql_mgr.query_transformers()
    print('TRANSFORMER_CAPACITY transformer data obtained', flush=True)
    print('TRANSFORMER_CAPACITY transformer data obtained', file=logfp)
    
    load_df = sparql_mgr.query_energyconsumer()
    der_df = sparql_mgr.query_der()
    print('TRANSFORMER_CAPACITY load and DER data obtained', flush=True)
    print('TRANSFORMER_CAPACITY load and DER data obtained', file=logfp)

    # Subscribe to microservice for getting the graph information
    message = {"modelId": feeder_mrid,
                   "requestType": "GRAPH",
                   "modelType": "STATIC",
                   "resultFormat": "JSON"}
    out_topic = "/topic/goss.gridappsd.model-validator.graph.out"
    gapps.subscribe(out_topic, callback)

    in_topic = "/topic/goss.gridappsd.model-validator.graph.in"
    gapps.send(in_topic, message)
    print("TRANSFORMER_CAPACITY sent request to microservice; waiting for response\n", flush=True)
    print("TRANSFORMER_CAPACITY sent request to microservice; waiting for response\n", file=logfp)

    global exit_flag
    exit_flag = False

    while not exit_flag:
        time.sleep(0.1)
Beispiel #13
0
class GridAPPSDVolttron(Agent):
    """
    Document agent constructor here.
    """
    def __init__(self, setting1=1, setting2="some/random/topic", **kwargs):
        super(GridAPPSDVolttron, self).__init__(**kwargs)
        self._gapps = GridAPPSD(override_threading=gevent.spawn)
        self._publish_event = None

    def publish_next(self):
        if self._publish_event is not None:
            self._publish_event.cancel()
        if self._gapps.connected:
            self._gapps.send("/queue/test", "foo bar")
        else:
            print("Not connected")
        now = get_aware_utc_now()
        print(utils.get_utc_seconds_from_epoch(now))
        next_update_time = now + datetime.timedelta(seconds=5)
        self._publish_event = self.core.schedule(next_update_time,
                                                 self.publish_next)
        gevent.sleep(0.1)

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):
        def message_published(headers, body):
            self.vip.pubsub.publish('pubsub',
                                    "data/foo",
                                    headers=headers,
                                    message=body)

        self._gapps.subscribe('/queue/test', message_published)
        gevent.sleep(0.1)
        self.publish_next()

    @Core.receiver("onstop")
    def onstop(self, sender, **kwargs):
        print("Stopping data!")

        # self._gapps.disconnect()
        print("After disconnect")
Beispiel #14
0
def check_topology(feeder_mrid, model_api_topic, simulation_id):
    global measid_lbs, loadbreaksw, undirected_graph, openSW, openSW_CIM, sourcebus
    global lock_flag, feeder_id

    feeder_id = feeder_mrid
    openSW = []

    SPARQLManager = getattr(importlib.import_module('shared.sparql'),
                            'SPARQLManager')

    gapps = GridAPPSD()

    sparql_mgr = SPARQLManager(gapps, feeder_mrid, model_api_topic)

    # Get graph connectivity
    undirected_graph = sparql_mgr.graph_query()
    sourcebus, sourcevang = sparql_mgr.sourcebus_query()
    sourcebus = sourcebus.upper()
    openSW_CIM = sparql_mgr.opensw()
    print('MICROSERVICES conectivity information obtained', flush=True)
    print('MICROSERVICES conectivity information obtained',
          file=logfile,
          flush=True)

    loadbreaksw = sparql_mgr.switch_query()
    measid_lbs = sparql_mgr.switch_meas_query()
    find_all_cycles()

    lock_flag = True
    print("MICROSERVICES setting initial lock", flush=True)
    print("MICROSERVICES setting initial lock", file=logfile, flush=True)
    sim_output_topic = simulation_output_topic(simulation_id)
    gapps.subscribe(sim_output_topic, on_message)

    in_topic = "/topic/goss.gridappsd.model-validator.graph.in"
    gapps.subscribe(in_topic, handle_request)

    in_topic = "/topic/goss.gridappsd.model-validator.topology.in"
    gapps.subscribe(in_topic, handle_request)

    global exit_flag
    exit_flag = False

    while not exit_flag:
        time.sleep(0.1)
def start(log_file, feeder_mrid, model_api_topic, simulation_id):
    global logfile
    logfile = log_file

    SPARQLManager = getattr(importlib.import_module('shared.sparql'), 'SPARQLManager')

    gapps = GridAPPSD()

    sparql_mgr = SPARQLManager(gapps, feeder_mrid, model_api_topic)

    #ysparse,nodelist = sparql_mgr.ybus_export()

    #idx = 1
    #nodes = {}
    #for obj in nodelist:
    #    nodes[idx] = obj.strip('\"')
    #    idx += 1
    ##print(nodes)

    #Ybus = {}
    #for obj in ysparse:
    #    items = obj.split(',')
    #    if items[0] == 'Row':
    #        continue
    #    if nodes[int(items[0])] not in Ybus:
    #        Ybus[nodes[int(items[0])]] = {}
    #    Ybus[nodes[int(items[0])]][nodes[int(items[1])]] = complex(float(items[2]), float(items[3]))
    ##print(Ybus)

    Ysys = {}
    Unsupported = {}

    mod_import = importlib.import_module('line_model_validator.line_model_validator')
    start_func = getattr(mod_import, 'start')
    start_func(log_file, feeder_mrid, model_api_topic, False, Ysys, Unsupported)
    #print('line_model_validator Ysys...')
    #print(Ysys)
    #line_count = 0
    #for bus1 in Ysys:
    #    line_count += len(Ysys[bus1])
    #print('\nLine_model # entries: ' + str(line_count) + '\n', flush=True)
    #print('\nLine_model # entries: ' + str(line_count) + '\n', file=logfile)

    mod_import = importlib.import_module('power_transformer_validator.power_transformer_validator')
    start_func = getattr(mod_import, 'start')
    start_func(log_file, feeder_mrid, model_api_topic, False, Ysys, Unsupported)
    #print('power_transformer_validator Ysys...')
    #print(Ysys)
    #count = 0
    #for bus1 in Ysys:
    #    count += len(Ysys[bus1])
    #xfmr_count = count - line_count
    #print('Power_transformer # entries: ' + str(xfmr_count) + '\n', flush=True)
    #print('Power_transformer # entries: ' + str(xfmr_count) + '\n', file=logfile)

    mod_import = importlib.import_module('switching_equipment_validator.switching_equipment_validator')
    start_func = getattr(mod_import, 'start')
    start_func(log_file, feeder_mrid, model_api_topic, False, Ysys, Unsupported)
    #print('switching_equipment_validator (final) Ysys...')
    #print(Ysys)
    #count = 0
    #for bus1 in Ysys:
    #    count += len(Ysys[bus1])
    #switch_count = count - line_count - xfmr_count
    #print('Switching_equipment # entries: ' + str(switch_count) + '\n', flush=True)
    #print('Switching_equipment # entries: ' + str(switch_count) + '\n', file=logfile)

    #print('\n*** Full Ysys:\n')
    #for bus1 in Ysys:
    #    for bus2 in Ysys[bus1]:
    #        print(bus1 + ',' + bus2 + ',' + str(Ysys[bus1][bus2].real) + ',' + str(Ysys[bus1][bus2].imag))

    ysysCount = 0
    for bus1 in Ysys:
        ysysCount += len(Ysys[bus1])
    #print('Total computed # entries: ' + str(ysysCount) + '\n', flush=True)
    #print('Total computed # entries: ' + str(ysysCount) + '\n', file=logfile)

    # build the Numpy matrix from the full Ysys before we start deleting
    # entries to check Ysys vs. Ybus
    # first, create a node index dictionary
    Node2idx = {}
    N = 0
    for bus1 in list(Ysys):
        if bus1 not in Node2idx:
            Node2idx[bus1] = N
            N += 1
        for bus2 in list(Ysys[bus1]):
            if bus2 not in Node2idx:
                Node2idx[bus2] = N
                N += 1
    print('Node2idx size: ' + str(N))
    print('Node2idx dictionary:')
    print(Node2idx)

    sourcebus, sourcevang = sparql_mgr.sourcebus_query()
    sourcebus = sourcebus.upper()
    #print('\nquery results sourcebus: ' + sourcebus)
    #print('query results sourcevang: ' + str(sourcevang))

    bindings = sparql_mgr.nomv_query()
    #print('\nnomv query results:')
    #print(bindings)

    sqrt3 = math.sqrt(3.0)
    Vmag = {}

    for obj in bindings:
        busname = obj['busname']['value'].upper()
        nomv = float(obj['nomv']['value'])
        Vmag[busname] = nomv/sqrt3

    Vang = {}
    Vang['1'] = math.radians(0.0)
    Vang['2'] = math.radians(-120.0)
    Vang['3'] = math.radians(120.0)

    # calculate CandidateVnom
    CandidateVnom = {}
    CandidateVnomPolar = {}
    for node in Node2idx:
        bus = node[:node.find('.')]
        phase = node[node.find('.')+1:]

        # source bus is a special case for the angle
        if node.startswith(sourcebus+'.'):
            CandidateVnom[node] = pol2cart(Vmag[bus], sourcevang+Vang[phase])
            CandidateVnomPolar[node] = (Vmag[bus], math.degrees(sourcevang+Vang[phase]))
        else:
            if bus in Vmag:
                CandidateVnom[node] = pol2cart(Vmag[bus], Vang[phase])
                CandidateVnomPolar[node] = (Vmag[bus], math.degrees(Vang[phase]))
            else:
                print('*** WARNING:  no nomv value for bus: ' + bus + ' for node: ' + node)

    #print('\nCandidateVnom dictionary:')
    #print(CandidateVnom)

    src_idxs = []
    if sourcebus+'.1' in Node2idx:
        src_idxs.append(Node2idx[sourcebus+'.1'])
    if sourcebus+'.2' in Node2idx:
        src_idxs.append(Node2idx[sourcebus+'.2'])
    if sourcebus+'.3' in Node2idx:
        src_idxs.append(Node2idx[sourcebus+'.3'])
    print('\nsrc_idxs: ' + str(src_idxs))

    YsysMatrix = np.zeros((N,N), dtype=complex)
    # next, remap into a numpy array
    for bus1 in list(Ysys):
        for bus2 in list(Ysys[bus1]):
            YsysMatrix[Node2idx[bus2],Node2idx[bus1]] = YsysMatrix[Node2idx[bus1],Node2idx[bus2]] = Ysys[bus1][bus2]
    # dump YsysMatrix for MATLAB comparison
    #print('\nYsysMatrix for MATLAB:')
    #for row in range(N):
    #    for col in range(N):
    #        print(str(row+1) + ',' + str(col+1) + ',' + str(YsysMatrix[row,col].real) + ',' + str(YsysMatrix[row,col].imag))

    np.set_printoptions(threshold=sys.maxsize)
    #print('\nYsys numpy array:')
    #print(YsysMatrix)

    # create the CandidateVnom numpy vector for computations below
    CandidateVnomVec = np.zeros((N), dtype=complex)
    for node in Node2idx:
        if node in CandidateVnom:
            print('CandidateVnomVec node: ' + node + ', index: ' + str(Node2idx[node]) + ', cartesian value: ' + str(CandidateVnom[node]) + ', polar value: ' + str(CandidateVnomPolar[node]))
            CandidateVnomVec[Node2idx[node]] = CandidateVnom[node]
        else:
            print('*** WARNING: no CandidateVnom value for populating node: ' + node + ', index: ' + str(Node2idx[node]))
    #print('\nCandidateVnom:')
    #print(CandidateVnomVec)
    # dump CandidateVnomVec to CSV file for MATLAB comparison
    #print('\nCandidateVnom for MATLAB:')
    #for row in range(N):
    #    print(str(CandidateVnomVec[row].real) + ',' + str(CandidateVnomVec[row].imag))

    # time to get the source injection terms
    # first, get the dictionary of regulator ids
    bindings = sparql_mgr.regid_query()
    Rids = []
    for obj in bindings:
        Rids.append(obj['rid']['value'])
    print('\nRegulator IDs: ' + str(Rids))

    # second, subscribe to simulation output so we can start setting tap
    # positions to 0
    simSetRap = SimSetWrapper(gapps, simulation_id, Rids)
    conn_id = gapps.subscribe(simulation_output_topic(simulation_id), simSetRap)

    while simSetRap.keepLooping():
        #print('Sleeping....', flush=True)
        time.sleep(0.1)

    gapps.unsubscribe(conn_id)

    bindings = sparql_mgr.query_energyconsumer_lf()
    #print(bindings)

    phaseIdx = {'A': '.1', 'B': '.2', 'C': '.3', 's1': '.1', 's2': '.2'}
    DeltaList = []
    #print("\nDelta connected load EnergyConsumer query:")
    for obj in bindings:
        #name = obj['name']['value'].upper()
        bus = obj['bus']['value'].upper()
        conn = obj['conn']['value']
        phases = obj['phases']['value']
        #print('bus: ' + bus + ', conn: ' + conn + ', phases: ' + phases)
        if conn == 'D':
           if phases == '':
               DeltaList.append(bus+'.1')
               DeltaList.append(bus+'.2')
               DeltaList.append(bus+'.3')
           else:
               DeltaList.append(bus+phaseIdx[phases])

    PNVmag = np.zeros((N), dtype=float)

    # third, verify all tap positions are 0
    config_api_topic = 'goss.gridappsd.process.request.config'
    message = {
        'configurationType': 'CIM Dictionary',
        'parameters': {'model_id': feeder_mrid}
        }
    cim_dict = gapps.get_response(config_api_topic, message, timeout=10)
    #print('\nCIM Dictionary:')
    #print(cim_dict)
    # get list of regulator mRIDs
    RegMRIDs = []
    CondMRIDs = []
    PNVmRIDs = []
    PNVdict = {}
    condTypes = set(['EnergyConsumer', 'LinearShuntCompensator', 'PowerElectronicsConnection', 'SynchronousMachine'])
    phaseIdx2 = {'A': '.2', 'B': '.3', 'C': '.1'}

    for feeder in cim_dict['data']['feeders']:
        for measurement in feeder['measurements']:
            if measurement['name'].startswith('RatioTapChanger') and measurement['measurementType']=='Pos':
                RegMRIDs.append(measurement['mRID'])

            elif measurement['measurementType']=='VA' and (measurement['ConductingEquipment_type'] in condTypes):
                node = measurement['ConnectivityNode'].upper() + phaseIdx[measurement['phases']]
                if node in DeltaList:
                    node2 = measurement['ConnectivityNode'].upper() + phaseIdx2[measurement['phases']]
                    #print('Appending CondMRID tuple: (' + measurement['mRID'] + ', ' + measurement['ConductingEquipment_type'] + ', ' + str(Node2idx[node]) + ', ' + str(Node2idx[node2]) + ') for node: ' + node, flush=True)
                    CondMRIDs.append((measurement['mRID'], measurement['ConductingEquipment_type'], Node2idx[node], Node2idx[node2]))
                else:
                    #print('Appending CondMRID tuple: (' + measurement['mRID'] + ', ' + measurement['ConductingEquipment_type'] + ', ' + str(Node2idx[node]) + ', None) for node: ' + node, flush=True)
                    CondMRIDs.append((measurement['mRID'], measurement['ConductingEquipment_type'], Node2idx[node], None))

            elif measurement['measurementType'] == 'PNV':
                # save PNV measurements in Andy's mixing bowl for later
                node = measurement['ConnectivityNode'].upper() + phaseIdx[measurement['phases']]
                #print('Appending PNVmRID tuple: (' + measurement['mRID'] + ', ' + measurement['ConductingEquipment_type'] + ', ' + str(Node2idx[node]) + ') for node: ' + node, flush=True)
                PNVmRIDs.append((measurement['mRID'], Node2idx[node]))
                PNVdict[Node2idx[node]] = measurement['mRID']

    print('Found RatioTapChanger mRIDs: ' + str(RegMRIDs), flush=True)
    print('Found ConductingEquipment mRIDs: ' + str(CondMRIDs), flush=True)
    print('Found PNV dictionary: ' + str(PNVdict), flush=True)
    print('PNV dictionary size: ' + str(len(PNVdict)), flush=True)

    # fourth, verify tap ratios are all 0 and then set Sinj values for the
    # conducting equipment mRIDs by listening to simulation output

    # start with Sinj as zero vector and we will come back to this later
    Sinj = np.zeros((N), dtype=complex)
    Sinj[src_idxs] = complex(0.0,1.0)
    print('\nInitial Sinj:')
    print(Sinj)

    # subscribe to simulation output so we can start checking tap positions
    # and then setting Sinj
    simCheckRap = SimCheckWrapper(Sinj, PNVmag, RegMRIDs, CondMRIDs, PNVmRIDs, PNVdict)
    conn_id = gapps.subscribe(simulation_output_topic(simulation_id), simCheckRap)

    while simCheckRap.keepLooping():
        #print('Sleeping....', flush=True)
        time.sleep(0.1)

    gapps.unsubscribe(conn_id)

    print('\nFinal Sinj:')
    #print(Sinj)
    for key,value in Node2idx.items():
        print(key + ': ' + str(Sinj[value]))

    vsrc = np.zeros((3), dtype=complex)
    vsrc = CandidateVnomVec[src_idxs]
    #print('\nvsrc:')
    #print(vsrc)

    Iinj_nom = np.conj(Sinj/CandidateVnomVec)
    #print('\nIinj_nom:')
    #print(Iinj_nom)

    Yinj_nom = -Iinj_nom/CandidateVnomVec
    #print('\nYinj_nom:')
    #print(Yinj_nom)

    Yaug = YsysMatrix + np.diag(Yinj_nom)
    #print('\nYaug:')
    #print(Yaug)

    Zaug = np.linalg.inv(Yaug)
    #print('\nZaug:')
    #print(Zaug)

    tolerance = 0.01
    Nfpi = 10
    Nfpi = 15
    Isrc_vec = np.zeros((N), dtype=complex)
    Vfpi = np.zeros((N,Nfpi), dtype=complex)

    # start with the CandidateVnom for Vfpi
    Vfpi[:,0] = CandidateVnomVec
    #print('\nVfpi:')
    #print(Vfpi)

    k = 1
    maxdiff = 1.0

    while k<Nfpi and maxdiff>tolerance:
        Iload_tot = np.conj(Sinj / Vfpi[:,k-1])
        Iload_z = -Yinj_nom * Vfpi[:,k-1]
        Iload_comp = Iload_tot - Iload_z
        #print('\nIload_comp numpy matrix:')
        #print(Iload_comp)

        term1 = np.linalg.inv(Zaug[np.ix_(src_idxs,src_idxs)])
        term2 = vsrc - np.matmul(Zaug[np.ix_(src_idxs,list(range(N)))], Iload_comp)
        Isrc_vec[src_idxs] = np.matmul(term1, term2)
        #print("\nIsrc_vec:")
        #print(Isrc_vec)

        Icomp = Isrc_vec + Iload_comp
        Vfpi[:,k] = np.matmul(Zaug, Icomp)
        #print("\nVfpi:")
        #print(Vfpi)
        #print(Vfpi[:,k])

        maxlist = abs(abs(Vfpi[:,k]) - abs(Vfpi[:,k-1]))
        print("\nmaxlist:")
        for i in range(41):
          print(str(i) + ": " + str(maxlist[i]))

        maxdiff = max(abs(abs(Vfpi[:,k]) - abs(Vfpi[:,k-1])))
        print("\nk: " + str(k) + ", maxdiff: " + str(maxdiff))
        k += 1

    if k == Nfpi:
        print("\nDid not converge with k: " + str(k))
        return

    # set the final Vpfi index
    k -= 1
    print("\nconverged k: " + str(k))
    print("\nVfpi:")
    for key, value in Node2idx.items():
        rho, phi = cart2pol(Vfpi[value,k])
        print(key + ': rho: ' + str(rho) + ', phi: ' + str(math.degrees(phi)))
        print('index: ' + str(value) + ', sim mag: ' + str(PNVmag[value]))

    print("\nVfpi rho to sim magnitude CSV:")
    for key, value in Node2idx.items():
        mag = PNVmag[value]
        if mag != 0.0:
            rho, phi = cart2pol(Vfpi[value,k])
            print(str(value) + ',' + key + ',' + str(rho) + ',' + str(mag))

    return
Beispiel #16
0
}

#Start the simulation....

gapps_sim = GridAPPSD()
simulation = Simulation(gapps_sim, run_config_13)
simulation.start_simulation()

simulation_id = simulation.simulation_id
print(simulation_id)

#Test the callback function
sim_output_topic = simulation_output_topic(simulation_id)
f = open('csvwritertest.csv', 'w')

gapps.subscribe(sim_output_topic, callback)
sim_log_topic = simulation_log_topic(simulation_id)
gapps.subscribe(sim_log_topic, callback2)


def _main():
    global end_program
    print('test')
    while not end_program:
        time.sleep(0.1)
    if end_program:
        f.close()
        print('bye')
        quit()

Beispiel #17
0
    # print("Alka3")
    #print(gapps.query_data( query,database_type=POWERGRID_MODEL, timeout=30 ))
    # # with open("power2.json", 'r') as g:
    # #     print(gapps.get_response(request_topic, json.load(g), timeout=30))
    # print("Alka4")
    # print(gapps.query_object_dictionary('_0f6f3735-b297-46aa-8861-547d3cd0dee9', object_type='http://iec.ch/TC57/CIM100#ACLineSegment', object_id=None))

    # with open("./weather_data.json", 'r') as g:
    #     print(gapps.get_response(t.TIMESERIES, json.load(g), timeout=30))
    #
    # with open("./query.json", 'r') as f:
    #     query = json.load(f)
    #     query["queryFilter"]["simulation_id"] = opts.simulation_id
    #     print(query["queryFilter"]["simulation_id"])
    #     print("Alka")
    #     print(gapps.get_response(t.TIMESERIES, query, timeout=30))

    # For testing Alarms topic uncomment the below lines
    # alarms_topic = t.service_output_topic('gridappsd-alarms', simulation_id)
    # print(alarms_topic)
    # print(simulation_id)
    # print("Alka")
    # print(gapps.subscribe(alarms_topic, Subscribe.on_message))
    # print(gapps.query_model_names(model_id=None))

    #For testing the  Logging API uncomment the below line
    print(gapps.subscribe(simulation_log_topic(simulation_id), Subscribe.on_message))

    while True:
        time.sleep(30)
Beispiel #18
0
from time import sleep
from gridappsd import GridAPPSD

g = GridAPPSD()


def cb(header, msg):
    print(f"header: {header} message: {msg}")


g.subscribe("/topic/data", cb)

houses = g.get_houses()
hs = houses.get_houses_for_feeder('_503D6E20-F499-4CC7-8051-971E23D0BF79')
print(hs)

while True:
    sleep(0.1)
def start(log_file, feeder_mrid, model_api_topic, simulation_id):
    global logfile
    logfile = log_file

    print(
        "\nAC_LINE_AMPACITY starting!!!----------------------------------------------------"
    )
    print(
        "\nAC_LINE_AMPACITY starting!!!----------------------------------------------------",
        file=logfile)

    SPARQLManager = getattr(importlib.import_module('shared.sparql'),
                            'SPARQLManager')

    gapps = GridAPPSD()

    sparql_mgr = SPARQLManager(gapps, feeder_mrid, model_api_topic)

    # AC Line segement rating check
    global df_acline_measA
    df_acline_measA = sparql_mgr.acline_measurements(logfile)
    # Combine measurement mrids for 'A' and rating together
    df_acline_rating = sparql_mgr.acline_rating_query()
    if df_acline_measA is not None:
        print('AC_LINE_AMPACITY ACLineSegment measurements obtained',
              flush=True)
        print('AC_LINE_AMPACITY ACLineSegment measurements obtained',
              file=logfile)
        df_acline_measA = df_acline_measA.assign(
            flow=np.zeros(df_acline_measA.shape[0]))
        for r in df_acline_rating.itertuples(index=False):
            index = df_acline_measA.index[df_acline_measA['eqname'] ==
                                          r.eqname].tolist()
            rating = r.val
            for k in index:
                df_acline_measA.loc[df_acline_measA.index == k,
                                    'rating'] = rating
        print('AC_LINE_AMPACITY ACLineSegment rating obtained', flush=True)
        print('AC_LINE_AMPACITY ACLineSegment rating obtained', file=logfile)
        print('AC_LINE_AMPACITY df_acline_measA: ' + str(df_acline_measA),
              flush=True)
        print('AC_LINE_AMPACITY df_acline_measA: ' + str(df_acline_measA),
              file=logfile)
    else:
        return

    sim_output_topic = simulation_output_topic(simulation_id)
    sim_log_topic = simulation_log_topic(simulation_id)
    print('AC_LINE_AMPACITY simulation output topic from function: ' +
          sim_output_topic,
          flush=True)
    print('AC_LINE_AMPACITY simulation output topic from function: ' +
          sim_output_topic,
          file=logfile)
    print('AC_LINE_AMPACITY simulation log topic from function: ' +
          sim_log_topic,
          flush=True)
    print('AC_LINE_AMPACITY simulation log topic from function: ' +
          sim_log_topic,
          file=logfile)

    gapps.subscribe(topic=sim_output_topic, callback=on_message)
    gapps.subscribe(topic=sim_log_topic, callback=on_message)
    print(
        'AC_LINE_AMPACITY subscribed to both output and log topics, waiting for messages',
        flush=True)
    print(
        'AC_LINE_AMPACITY subscribed to both output and log topics, waiting for messages',
        file=logfile)

    global exit_flag
    exit_flag = False

    while not exit_flag:
        time.sleep(0.1)
class GridAPPSDSimIntegration(BaseSimIntegration):
    """
    The class is responsible for integration with GridAPPSD co-simulation platform.
    It provides integration support to register configuration, start, stop, publish,
    receive messages, pause and resume simulation
    """
    def __init__(self, config, pubsub):
        super(GridAPPSDSimIntegration, self).__init__(config)
        self._work_callback = None
        self.config = config
        self.gridappsd = None
        self.sim = None
        self.event_callbacks = {}
        self.topic_callbacks = {}
        self.sim_id = None
        self.username = None
        self.password = None

    def register_inputs(self, config=None, callback=None, **kwargs):
        """
        Register configuration parameters with GridAppsD.
        The config parameters may include but not limited to:
        - power_system_config
        - application_config
        - simulation_config
        - test_config
        - service_configs
        : Register agent callback method
        :return:
        """
        self.config = config
        self.username = self.config.pop('username', 'system')
        self.password = self.config.pop('password', 'manager')
        self._work_callback = callback

    def register_event_callbacks(self, callbacks={}):
        """
        Register for event callbacks for event notifications such as
        - on measurement change
        - on timestep change
        - on finish
        """
        _log.debug("Registering for event callbacks")
        self.event_callbacks = callbacks

    def register_topic_callbacks(self, callbacks={}):
        """
        Register for any simulation topic callbacks
        """
        _log.debug("Registering for topic callbacks")
        self.topic_callbacks = callbacks

    def start_simulation(self, *args, **kwargs):
        """
        Simulation start activities involve:
        - Creating GridAppsD connection gevent thread
        - Registering for event callbacks (if specified)
        - Registering for topic callbacks if specified
        - Starting simulation based on the input config
        :return:
        """
        try:
            self.gridappsd = GridAPPSD(override_threading=self.receiver_thread,
                                       username=self.username,
                                       password=self.password)

            _log.debug('Gridappsd connected')

            _log.debug(f"connection config is: {self.config}")
            self.sim = Simulation(self.gridappsd, self.config)

            _log.debug('Gridappsd adding onstart callback')
            # Register for onstart callback to know if simulation has started
            self.sim.add_onstart_callback(self.sim_on_start)
            # Register event callbacks - on measurement, on timestep, on finish
            for name, cb in self.event_callbacks.items():
                if name == 'MEASUREMENT':
                    _log.debug('Gridappsd adding measurement callback')
                    self.sim.add_onmesurement_callback(cb)
                elif name == 'TIMESTEP':
                    _log.debug('Gridappsd adding timestep callback')
                    self.sim.add_ontimestep_callback(cb)
                elif name == 'FINISH':
                    _log.debug('Gridappsd adding finish callback')
                    self.sim.add_oncomplete_callback(cb)

            # Register/Subscribe for simulation topics
            for topic, cb in self.topic_callbacks:
                _log.debug('Gridappsd subscribing to topics callback')
                self.gridappsd.subscribe(topic, cb)

            # Starting GridAppsD simulation
            self.sim.start_simulation()
            _log.debug(f"Gridappsd simulation id: {self.sim.simulation_id}")
        except stomp.exception.NotConnectedException as ex:
            _log.error("Unable to connect to GridAPPSD: {}".format(ex))
            raise ex

    def sim_on_start(self, sim):
        """
        Simulation on start callback to get notified when simulation starts
        """
        _log.debug(
            f"GridAppsD simulation id inside sim_on_start(): {sim.simulation_id}"
        )
        self.sim_id = sim.simulation_id

    def receiver_thread(self, arg):
        """
        GridAPPSD connection thread
        """
        self._receiver_thread = gevent.threading.Thread(group=None, target=arg)
        self._receiver_thread.daemon = True  # Don't let thread prevent termination
        self._receiver_thread.start()
        _log.debug('Gridappsd receiver_thread started!')
        return self._receiver_thread

    def publish_to_simulation(self, topic, message, **kwargs):
        """
        Publish message to GridAppsD
        :param topic: GridAppsD publication topic
        :param message: message
        :return:
        """
        self.gridappsd.send(topic, message)

    def pause_simulation(self, timeout=None, **kwargs):
        """
        Pause the GridAppsD simulation
        """
        if timeout is None:
            self.sim.pause()
        else:
            self.sim.pause(timeout)

    def resume_simulation(self, *args, **kwargs):
        """
        Resume the GridAppsD simulation
        """
        self.sim.resume()

    def is_sim_installed(self, **kwargs):
        """
        Flag to indicate if GridAppsD is installed
        """
        return HAS_GAPPSD

    def stop_simulation(self, *args, **kwargs):
        """
        Stop the simulation if running and disconnect from GridAppsD server
        :return:
        """
        _log.debug('Stopping the simulation')
        try:
            if self.sim_id is not None:
                self.sim.stop()
            _log.debug('Disconnect GridAppsd')
            if self.gridappsd is not None:
                self.gridappsd.disconnect()
        except Exception:
            _log.error("Error stop GridAPPSD simulation")
Beispiel #21
0
def _main():
    _log.debug("Starting application")
    print(
        "Application starting-------------------------------------------------------"
    )
    global message_period
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "simulation_id",
        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request", help="Simulation Request")
    parser.add_argument(
        "--message_period",
        help="How often the sample app will send open/close capacitor message.",
        default=DEFAULT_MESSAGE_PERIOD)

    #
    opts = parser.parse_args()
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    print(listening_to_topic)
    message_period = int(opts.message_period)
    sim_request = json.loads(opts.request.replace("\'", ""))
    model_mrid = sim_request["power_system_config"]["Line_name"]
    print("\n \n The model running is 9500 node with MRID:")
    # print(model_mrid)

    _log.debug("Model mrid is: {}".format(model_mrid))
    gapps = GridAPPSD(opts.simulation_id,
                      address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(),
                      password=utils.get_gridappsd_pass())

    # # Get measurement MRIDS for regulators in the feeder
    topic = "goss.gridappsd.process.request.data.powergridmodel"

    # Run queries to get model information
    print('Get Model Information..... \n')
    query = MODEL_EQ(gapps, model_mrid, topic)
    obj_msr_loadsw, obj_msr_demand, obj_msr_reg, obj_msr_cap, obj_msr_inv, obj_msr_node = query.meas_mrids(
    )
    # print('Get Object MRIDS.... \n')
    switches = query.get_switches_mrids()
    regulator = query.get_regulators_mrids()
    # print('regultor is printed')
    capacitor = query.get_capacitors_mrids()
    # print('capacitor is printed')
    LoadData, xfmr = query.distLoad()

    obj_msr_inv = obj_msr_inv['data']
    # print(obj_msr_inv)
    obj_msr_inv = [
        d for d in obj_msr_inv if d['type'] != 'PNV' and 'pv' in d['eqname']
    ]
    # print(obj_msr_inv[0])
    obj_inv = query.Inverters()
    # print(obj_inv[0])

    for inv in obj_msr_inv:
        for sinv in obj_inv:
            if sinv['mrid'] == inv['eqid']:
                inv['Srated'] = sinv['ratedS']

    sP = 0.
    sQ = 0.
    for l in LoadData:
        sP += float(l['kW'])
        sQ += float(l['kVaR'])

        # Load Line parameters
    with open('LineData.json', 'r') as read_file:
        line = json.load(read_file)

    print("Initialize..... \n")

    toggler = SwitchingActions(opts.simulation_id, gapps, regulator, capacitor,
                               LoadData, line, xfmr, obj_msr_demand,
                               obj_msr_cap, obj_msr_reg, obj_msr_loadsw,
                               switches, obj_msr_inv, obj_msr_node)
    print("Now subscribing")
    gapps.subscribe(listening_to_topic, toggler)
    while True:
        time.sleep(0.1)
Beispiel #22
0
def _startTest(username,password,gossServer='localhost',stompPort='61613', simulationID=1234, rulePort=5000, topic="input"):

    req_template = {"power_system_config": {"SubGeographicalRegion_name": "_1CD7D2EE-3C91-3248-5662-A43EFEFAC224",
                                            "GeographicalRegion_name": "_24809814-4EC6-29D2-B509-7F8BFB646437",
                                            "Line_name": "_C1C3E687-6FFD-C753-582B-632A27E28507"},
                    "simulation_config": {"power_flow_solver_method": "NR",
                                          "duration": 120,
                                          "simulation_name": "ieee123",
                                          "simulator": "GridLAB-D",
                                          "start_time": 1248156000,
                                          "run_realtime": True,
                                          "timestep_frequency": "1000",
                                          "timestep_increment": "1000",
                                          "model_creation_config": {"load_scaling_factor": 1.0, "triplex": "y",
                                                                    "encoding": "u", "system_frequency": 60,
                                                                    "voltage_multiplier": 1.0,
                                                                    "power_unit_conversion": 1.0, "unique_names": "y",
                                                                    "schedule_name": "ieeezipload", "z_fraction": "0",
                                                                    "i_fraction": "1", "p_fraction": "0",
                                                                    "randomize_zipload_fractions": False,
                                                                    "use_houses": False},
                                          "simulation_broker_port": 52798, "simulation_broker_location": "127.0.0.1"},
                    "application_config": {"applications": [{"name": "der_dispatch_app", "config_string": "{}"}]},
                    "simulation_request_type": "NEW", "test_config": {"events": []}}
 #138236b0
    xxx =  {"power_system_config":
                {"GeographicalRegion_name":"_73C512BD-7249-4F50-50DA-D93849B89C43",
                 "SubGeographicalRegion_name":"_A1170111-942A-6ABD-D325-C64886DC4D7D",
                 "Line_name":"_AAE94E4A-2465-6F5E-37B1-3E72183A4E44"},
                "application_config":{"applications":[]},
            "simulation_config":{
                "start_time":"1572040521",
                "duration":"120",
                "simulator":"GridLAB-D",
                "timestep_frequency":"1000",
                "timestep_increment":"1000",
                "run_realtime":True,
                "simulation_name":"test9500new",
                "power_flow_solver_method":"NR",
                "model_creation_config":{"load_scaling_factor":"1",
                                         "schedule_name":"ieeezipload",
                                         "z_fraction":"0",
                                         "i_fraction":"1",
                                         "p_fraction":"0",
                                         "randomize_zipload_fractions":False,
                                         "use_houses":False}
            },
            "test_config":{"events":[],"appId":""},"service_configs":[]}

    sw5_event = {
            "message": {
                "forward_differences": [
                    {
                        "object": "_60208A8D-E4EA-DA37-C758-428756C84F0D",
                        "attribute": "Switch.open",
                        "value": 1
                    }
                ],
                "reverse_differences": [
                    {
                        "object": "_60208A8D-E4EA-DA37-C758-428756C84F0D",
                        "attribute": "Switch.open",
                        "value": 0
                    }
                ]
            },
            "event_type": "ScheduledCommandEvent",
            "occuredDateTime": 1374510750,
            "stopDateTime": 1374510960
        }

    sw3_event = {
            "message": {
                "forward_differences": [
                    {
                        "object": "_4AA2369A-BF4B-F677-1229-CF5FB9A3A07E",
                        "attribute": "Switch.open",
                        "value": 1
                    }
                ],
                "reverse_differences": [
                    {
                        "object": "_4AA2369A-BF4B-F677-1229-CF5FB9A3A07E",
                        "attribute": "Switch.open",
                        "value": 0
                    }
                ]
            },
            "event_type": "ScheduledCommandEvent",
            "occuredDateTime": 1374258660 + (4*60),
            "stopDateTime": 1374258660 + (8*60)
        }
    event_l114 =  {"PhaseConnectedFaultKind": "lineToLineToGround",
                "FaultImpedance": {
                    "xGround": 0.36,
                    "rGround": 0.36,
                    "xLineToLine": 0.36,
                    "rLineToLine": 0.36
                },
                "ObjectMRID": ["_81CF3E64-ABA9-EF74-EE81-B86439ED61D5"], #  _ACA88F2A-96E3-B942-B09B-274CDD213CA6 PV no switches
                "phases": "ABC",
                "event_type": "Fault",
                "occuredDateTime": 1374258600 + (4*60),
                "stopDateTime":  1374258600 + (8*60)
    }
    event_1_v2019_10_0 = {
        "message": {
            "forward_differences": [
                {
                    "object": "_1B6A5DFD-9ADA-404A-83DF-C9AC89D9323C", # l9191_48332_sw
                    "attribute": "Switch.open",
                    "value": 1
                }
            ],
            "reverse_differences": [
                {
                    "object": "_1B6A5DFD-9ADA-404A-83DF-C9AC89D9323C",
                    "attribute": "Switch.open",
                    "value": 0
                }
            ]
        },
        "event_type": "ScheduledCommandEvent",
        "occuredDateTime": 1248174120,  # 2009-07-21 11:02:00 AM
        "stopDateTime": 1248174240      # 2009-07-21 11:04:00 AM
    }
    event_1 = {'message': {'forward_differences': [{'object': '_302E3119-B3ED-46A1-87D5-EBC8496357DF', 'attribute': 'Switch.open', 'value': 1}],
                           'reverse_differences': [{'object': '_302E3119-B3ED-46A1-87D5-EBC8496357DF', 'attribute': 'Switch.open', 'value': 0}]},
               'event_type': 'ScheduledCommandEvent',
               'occuredDateTime': 1248177660,
               'stopDateTime': 1248177780}

    restore_event_1 = {
      "message": {
        "forward_differences": [
          {
            "object": "_D287FFEF-4813-44C4-8F30-CBF836D58DF7",
            "attribute": "Switch.open",
            "value": 1
          },
          {
            "object": "_E976600E-B276-4B9A-A65F-DEEF65A7F080",
            "attribute": "Switch.open",
            "value": 1
          },
          {
            "object": "_57574CED-ACDC-4B14-AD36-D8BE9B6DD42C",
            "attribute": "Switch.open",
            "value": 0
          },
          {
            "object": "_37619299-61AC-40B4-BB3E-6B7C2A5D5719",
            "attribute": "Switch.open",
            "value": 0
          }
        ],
        "reverse_differences": [
          {
            "object": "_D287FFEF-4813-44C4-8F30-CBF836D58DF7",
            "attribute": "Switch.open",
            "value": 0
          },
          {
            "object": "_E976600E-B276-4B9A-A65F-DEEF65A7F080",
            "attribute": "Switch.open",
            "value": 0
          },
          {
            "object": "_57574CED-ACDC-4B14-AD36-D8BE9B6DD42C",
            "attribute": "Switch.open",
            "value": 1
          },
          {
            "object": "_37619299-61AC-40B4-BB3E-6B7C2A5D5719",
            "attribute": "Switch.open",
            "value": 1
          }
        ]
      },
      "event_type": "ScheduledCommandEvent",
      "occuredDateTime": 1248177690.0,
      "stopDateTime": 1248177810.0
    }

    event_3_v2019_10_0 = {"message": {
        "forward_differences": [
          {
            "object": "_2455DC96-1030-44F6-81E9-000A3702E157",
            "attribute": "Switch.open",
            "value": 1
          },
          {
            "object": "_A7AAF230-5237-4ABC-9F0B-845DD245CC1E",
            "attribute": "Switch.open",
            "value": 1
          }
        ],
        "reverse_differences": [
          {
            "object": "_2455DC96-1030-44F6-81E9-000A3702E157",
            "attribute": "Switch.open",
            "value": 0
          },
          {
            "object": "_A7AAF230-5237-4ABC-9F0B-845DD245CC1E",
            "attribute": "Switch.open",
            "value": 0
          }
        ]
      },
      "event_type": "ScheduledCommandEvent",
      "occuredDateTime": 1563796860,
      "stopDateTime": 1563796980
    }



    # 2009-07-21 05:00:00 AM
    # ##### event_1
    # Line LINE.LN5593236-6
    # node m1047515

    # "dg_84": "_233D4DC1-66EA-DF3C-D859-D10438ECCBDF", "dg_90": "_60E702BC-A8E7-6AB8-F5EB-D038283E4D3E"
    # Meas "_facde6ab-95e2-471b-b151-1b7125d863f0","_888e15c8-380d-4dcf-9876-ccf8949d45b1"

    # sx2991914c.1
    # new Line.2002200004991174_sw phases=3 bus1=d6290228-6_int.1.2.3 bus2=q16642.1.2.3 switch=y // CIM LoadBreakSwitch
    # ~ normamps=400.00 emergamps=600.00
    #   close Line.2002200004991174_sw 1
    # {'command': 'update', 'input': {'simulation_id': 966953393, 'message': {'timestamp': 1571850450, 'difference_mrid': 'caf85954-d594-42ec-b3d1-644a32941a4a', 'reverse_differences': [{'object': '_CB845255-3CD8-4E25-9B48-3CB74EE59F63', 'attribute': 'Switch.open', 'value': 1}], 'forward_differences': [{'object': '_CB845255-3CD8-4E25-9B48-3CB74EE59F63', 'attribute': 'Switch.open', 'value': 0}]}}}

    pv_84_90_event = {
        "allOutputOutage": False,
        "allInputOutage": False,
        "inputOutageList": [{"objectMRID": "_233D4DC1-66EA-DF3C-D859-D10438ECCBDF", "attribute": "PowerElectronicsConnection.p"},
                            {"objectMRID": "_233D4DC1-66EA-DF3C-D859-D10438ECCBDF", "attribute": "PowerElectronicsConnection.q"},
                            {"objectMRID": "_60E702BC-A8E7-6AB8-F5EB-D038283E4D3E", "attribute": "PowerElectronicsConnection.p"},
                            {"objectMRID": "_60E702BC-A8E7-6AB8-F5EB-D038283E4D3E", "attribute": "PowerElectronicsConnection.q"},
                            ],
        "outputOutageList": ['_a5107987-1609-47b2-8f5b-f91f99658390', '_2c4e0cb2-4bf0-4a2f-be94-83ee9b87d1e5'],
        "event_type": "CommOutage",
        "occuredDateTime": 1374510600 + (5*60),
        "stopDateTime": 1374510600 + (10*60)
    }

    # _EAE0584D-6B67-2F23-FC02-E3F2C8C6A48D"
    # _73E7B579-37DB-B7F2-EBC6-D083E8BBA1F3
    # 104.3 dg_84 _b8442bbd-4d3e-4b2e-884e-96639bb207bc
    # 113.1 dg_90 _b005322e-7dba-48d3-b6ce-f6fe57c4dd61

    pv_84_90_event = {
        "allOutputOutage": False,
        "allInputOutage": False,
        "inputOutageList": [{"objectMRID": "_EAE0584D-6B67-2F23-FC02-E3F2C8C6A48D", "attribute": "PowerElectronicsConnection.p"},
                            {"objectMRID": "_EAE0584D-6B67-2F23-FC02-E3F2C8C6A48D", "attribute": "PowerElectronicsConnection.q"},
                            {"objectMRID": "_73E7B579-37DB-B7F2-EBC6-D083E8BBA1F3", "attribute": "PowerElectronicsConnection.p"},
                            {"objectMRID": "_73E7B579-37DB-B7F2-EBC6-D083E8BBA1F3", "attribute": "PowerElectronicsConnection.q"},
                            ],
        "outputOutageList": ['_b8442bbd-4d3e-4b2e-884e-96639bb207bc', '_b005322e-7dba-48d3-b6ce-f6fe57c4dd61'],
        "event_type": "CommOutage",
        "occuredDateTime": 1374510600 + (5*60),
        "stopDateTime": 1374510600 + (10*60)
    }


    # {"applications": [{"name": "der_dispatch_app", "config_string": ""}]}
    req_template['simulation_config']['model_creation_config']['load_scaling_factor'] = 1
    req_template['simulation_config']['run_realtime'] = False
    req_template['simulation_config']['duration'] = 60 * 60 * 1
    req_template['simulation_config']['duration'] = 60 * 20

    req_template['simulation_config']['start_time'] = 1538510000
    req_template['simulation_config']['start_time'] = 1374498000  # GMT: Monday, July 22, 2013 1:00:00 PM What I was doing
    req_template['simulation_config']['start_time'] = 1374510600  # GMT: Monday, July 22, 2013 4:30:00 PM MST 10:30:00 AM
    # req_template['simulation_config']['start_time'] = 1374517800   # GMT: Monday, July 22, 2013 6:30:00 PM
    # req_template['simulation_config']['start_time'] = 1374510720  # GMT: Monday, July 22, 2013 4:30:00 PM PLUS 2 minutes!!
    # July 22, 2013 4:32:00 GMT
    # July 22, 2013 10:32:00 2013-07-22 10:32:00
    # req_template['simulation_config']['start_time'] = 1374514200  # GMT: Monday, July 22, 2013 5:30:00 PM

    # req_template['simulation_config']['start_time'] = 1374519600  # (GMT): Monday, July 22, 2013 7:00:00 PM
    # req_template['simulation_config']['start_time'] = 1374530400  # (GMT): Monday, July 22, 2013 10:00:00 PM Cause
    # req_template['simulation_config']['start_time'] = 1374454800  # (GMT): Monday, July 22, 2013 1:00:00 AM
    # req_template['simulation_config']['start_time'] = 1374411600  # 7/21/2013 7AM
    req_template['simulation_config']['start_time'] = 1374256800  # (GMT): Friday, July 19, 2013 6:00:00 PM
    req_template['simulation_config']['start_time'] = 1374217200  # July 19 07:00 AM GMT / 1:00 AM MST
    req_template['simulation_config']['start_time'] = 1374228000  # July 19 10:00 AM GMT / 4:00 AM MST
    req_template['simulation_config']['start_time'] = 1374233400  # July 19 11:30 AM GMT / 5:30 AM MST
    req_template['simulation_config']['start_time'] = 1374240600  # July 19 13:30 AM GMT / 7:30 AM MST
    req_template['simulation_config']['start_time'] = 1374213600  # July 19 06:00 AM GMT / 00:00 AM MST
    req_template['simulation_config']['start_time'] = 1374235200  # July 19 12:00 PM GMT / 06:00 AM MST
    req_template['simulation_config']['start_time'] = 1248156000  # Tuesday, July 21, 2009 6:00:00 AM
    req_template['simulation_config']['start_time'] = 1248192000  # Tuesday, July 21, 2009 4:00:00 PM / 10:00:00 AM
    req_template['simulation_config']['start_time'] = 1248199200  # Tuesday, July 21, 2009 6:00:00 PM / 12:00:00 PM
    req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 13:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 12:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    req_template['simulation_config']['start_time'] = timegm(strptime('2019-07-22 11:01:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))

    req_template['simulation_config']['start_time'] = timegm(strptime('2019-07-23 14:50:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    req_template['simulation_config']['start_time'] = timegm(strptime('2013-07-22 12:01:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    #2013-07-14 08:00:00

    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 10:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 09:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 18:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 20:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 21:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 18:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = 1374249600  #  July 19, 2013 4:00:00 PM
    # req_template['simulation_config']['start_time'] = 1374258600  # July 19, 2013 6:30:00 PM  - 2013-07-19 18:30:00 / 12:30 PM MST  # MAX PV!!!
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-19 12:30:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))  # July 19, 2013 6:30:00 PM  - 2013-07-19 18:30:00 / 12:30 PM MST  # MAX PV!!!
    # dg_42 _2B5D7749-6C18-D77E-B848-3F4C31ADC3E6 p=146621.68181873375 q=-179.94738632961975
    # 2013-07-19 18:32:00
    # 2013-07-19 18:35:00

    # pv_84_90_event["occuredDateTime"] = req_template['simulation_config']['start_time'] + (5*60)
    # pv_84_90_event["stopDateTime"]    = req_template['simulation_config']['start_time'] + (10*60)
    # req_template["test_config"]["events"].append(pv_84_90_event)

    # req_template["test_config"]["events"].append(sw3_event)
    # req_template["test_config"]["events"].append(event_l114)

    # event_1_v2019_10_0["occuredDateTime"] = req_template['simulation_config']['start_time'] + (1*60)
    # event_1_v2019_10_0["stopDateTime"]    = req_template['simulation_config']['start_time'] + (3*60)
    # req_template["test_config"]["events"].append(event_1_v2019_10_0)

    # event_1["occuredDateTime"] = req_template['simulation_config']['start_time'] + (1*60)
    # event_1["stopDateTime"]    = req_template['simulation_config']['start_time'] + (3*60)
    # req_template["test_config"]["events"].append(event_1)

    #event_3_v2019_10_0
    event_3_v2019_10_0["occuredDateTime"] = req_template['simulation_config']['start_time'] + (1*60)
    event_3_v2019_10_0["stopDateTime"]    = req_template['simulation_config']['start_time'] + (3*60)
    # req_template["test_config"]["events"].append(event_3_v2019_10_0)

    # event_3["occuredDateTime"] = req_template['simulation_config']['start_time'] + (1*60)
    # event_3["stopDateTime"]    = req_template['simulation_config']['start_time'] + (3*60)
    # req_template["test_config"]["events"].append(event_3)

    app_config = {'OPF': 1, 'run_freq': 15, 'run_on_host': True}
    app_config['run_realtime'] = req_template['simulation_config']['run_realtime']
    app_config['stepsize_xp'] = 0.2
    app_config['stepsize_xq'] = 2
    # app_config['coeff_p'] = 0.1
    # app_config['coeff_q'] = 0.00005
    app_config['coeff_p'] = 0.005
    app_config['coeff_q'] = 0.0005
    app_config['Vupper'] = 1.025
    app_config['Vlower'] = 0.95
    app_config['stepsize_mu'] = 50000
    app_config['optimizer_num_iterations'] = 10
    print(json.dumps(app_config,indent=2))
    # exit(0)

    #TODO stepsize_mu = 50000 lower this! 500 or 50
    req_template["application_config"]["applications"] = [{"name": "der_dispatch_app", "config_string": json.dumps(app_config)}]

    # GMT: Tuesday, October 2, 2018 4:50:00 PM
    # Your time zone: Tuesday, October 2, 2018 10:50:00 AM GMT-06:00 DST
    req_template['power_system_config']['Line_name'] = '_E407CBB6-8C8D-9BC9-589C-AB83FBF0826D'  # Mine 123pv'
    # req_template['power_system_config']['Line_name'] = '_EBDB5A4A-543C-9025-243E-8CAD24307380'  # 123 with reg
    # req_template['power_system_config']['Line_name'] = '_88B3A3D8-51CD-7466-5E29-B692F21723CB' # Mine with feet conv
    req_template['power_system_config']['Line_name'] = '_DA00D94F-4683-FD19-15D9-8FF002220115'  # mine with house

    # req_template['power_system_config']['Line_name'] = '_49AD8E07-3BF9-A4E2-CB8F-C3722F837B62'  # 13
    req_template['power_system_config']['Line_name'] = '_AAE94E4A-2465-6F5E-37B1-3E72183A4E44'  # New 8500 9500
    # req_template['power_system_config']['Line_name'] = '_C1C3E687-6FFD-C753-582B-632A27E28507'

    # req_template['power_system_config']['Line_name'] = '_4F76A5F9-271D-9EB8-5E31-AA362D86F2C3'
    # req_template["application_config"]["applications"][0]['name'] = 'sample_app'
    req_template["application_config"]["applications"][0]['name'] = 'der_dispatch_app'

    req_template['power_system_config']['Line_name'] = '_49AD8E07-3BF9-A4E2-CB8F-C3722F837B62'
    # req_template['power_system_config']['Line_name'] = '_E407CBB6-8C8D-9BC9-589C-AB83FBF0826D'
    req_template['power_system_config']['Line_name'] = '_AAE94E4A-2465-6F5E-37B1-3E72183A4E44'

    ## TOD test with 13 8/24/2020

    simCfg13pv = json.dumps(req_template)
    print(simCfg13pv)

    goss = GOSS()
    goss.connect()

    simulation_id = goss.get_response(goss_sim, simCfg13pv, timeout=220) # 180 Maybe?
    simulation_id = int(simulation_id['simulationId'])
    print(simulation_id)
    print('sent simulation request')
    time.sleep(1)

    if app_config['run_on_host']:
        from main_app_new import DER_Dispatch
        listening_to_topic = simulation_output_topic(simulation_id)
        print(listening_to_topic)
        log_topic = simulation_log_topic(simulation_id)
        model_mrid = req_template['power_system_config']['Line_name']
        start_time = req_template['simulation_config']['start_time']
        app_configs = req_template["application_config"]["applications"]
        app_config = [json.loads(app['config_string']) for app in app_configs if app['name'] == 'der_dispatch_app'][0]

        # gapps = GridAPPSD(simulation_id)
        from gridappsd import utils
        gapps = GridAPPSD(simulation_id, address=utils.get_gridappsd_address(),
                          username=utils.get_gridappsd_user(), password=utils.get_gridappsd_pass())
        load_scale = req_template['simulation_config']['model_creation_config']['load_scaling_factor']
        der_0 = DER_Dispatch(simulation_id, gapps, model_mrid, './FeederInfo', start_time, app_config, load_scale)
        der_0.setup()
        gapps.subscribe(listening_to_topic, der_0)
        gapps.subscribe(log_topic, der_0)

        while der_0.running():
            time.sleep(0.1)
        raise SystemExit

    read_topic = simulation_output_topic(opts.simulation_id)
    write_topic = service_output_topic("sensors", opts.simulation_id)

    gapp = GridAPPSD(username=opts.username,
                     password=opts.password,
                     stomp_address=opts.stomp_address,
                     stomp_port=opts.stomp_port)

    sensor = Sensor(
        gapp,
        seed=opts.random_seed,
        nominal=opts.
        nominal,  # TODO (Craig, Tom, Andy F): these 4 parameters will need to be different for each sensor instance
        perunit_confidence95=opts.perunit_confidence,
        perunit_dropping=opts.perunit_dropping,
        interval=opts.interval,
        output_topic=write_topic)

    gapp.subscribe(read_topic, sensor.on_simulation_message)

    while True:
        time.sleep(0.1)

#
#    Subscribe to all messages on /topic/goss.gridappsd.simulation.output.<simulation_id>
#    Add 1% error from a uniform distribution to every numerical value received. One way of doing this, using Numpy, would be: import numpy as np; val_out = np.random.uniform (0.99 * val_in, 1.01 * val_in)
#    Publish each val_out on /topic/goss.gridappsd.simulation.sensors.<simulation_id>
#    Have an option to drop 1% of the publications from step 3. xmit = np.random.uniform (0, 1) and then publish if xmit <= 0.99:
    # print(gapps.query_object_types(model_id=None))
    # print("Alka3")
    #print(gapps.query_data( query,database_type=POWERGRID_MODEL, timeout=30 ))
    # # with open("power2.json", 'r') as g:
    # #     print(gapps.get_response(request_topic, json.load(g), timeout=30))
    # print("Alka4")
    # print(gapps.query_object_dictionary('_0f6f3735-b297-46aa-8861-547d3cd0dee9', object_type='http://iec.ch/TC57/CIM100#ACLineSegment', object_id=None))

    # with open("./weather_data.json", 'r') as g:
    #     print(gapps.get_response(t.TIMESERIES, json.load(g), timeout=30))
    #
    # with open("./query.json", 'r') as f:
    #     query = json.load(f)
    #     query["queryFilter"]["simulation_id"] = opts.simulation_id
    #     print(query["queryFilter"]["simulation_id"])
    #     print("Alka")
    #     print(gapps.get_response(t.TIMESERIES, query, timeout=30))

    # For testing Alarms topic uncomment the below lines
    alarms_topic = t.service_output_topic('gridappsd-alarms', simulation_id)
    print(alarms_topic)
    print(simulation_id)
    print("Alka")
    print(gapps.subscribe(alarms_topic, Subscribe.on_message))
    print(gapps.query_model_names(model_id=None))

    #For testing the  Logging API uncomment the below line
    #print(gapps.subscribe(simulation_log_topic(simulation_id), Subscribe.on_message))

    while True:
        time.sleep(30)
Beispiel #25
0
        print("Received: headers: {}\nmessage: {}".format(headers, message))

    # Handle python 3 not having input_raw function.
    try:
        get_input = raw_input
    except NameError:
        get_input = input

    print("Creating GridAPPSD object")
    gapps = GridAPPSD(stomp_address="127.0.0.1",
                      stomp_port=61613,
                      username='******',
                      password='******')

    print("Subscribing to /topic/foo")
    gapps.subscribe('/topic/foo', on_message)
    result = get_input(
        "Press enter to send json.dumps(dict(bim='bash')) to topic /topic/foo")
    print("Sending data")
    gapps.send('/topic/foo', json.dumps(dict(bim='bash')))
    sleep(1)

    get_input("Press enter to receive platform status")
    resp = gapps.get_platform_status()
    pprint(resp)

    get_input("Press enter to query model info")
    resp = gapps.query_model_info()
    pprint(resp)

    get_input("Press enter to query model names")
Beispiel #26
0
def _main():
    parser = argparse.ArgumentParser()
    parser.add_argument("simulation_id",
                        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request",
                        help="Simulation Request")
    # These are now set through the docker container interface via env variables or defaulted to
    # proper values.
    #
    # parser.add_argument("-u", "--user", default="system",
    #                     help="The username to authenticate with the message bus.")
    # parser.add_argument("-p", "--password", default="manager",
    #                     help="The password to authenticate with the message bus.")
    # parser.add_argument("-a", "--address", default="127.0.0.1",
    #                     help="tcp address of the mesage bus.")
    # parser.add_argument("--port", default=61613, type=int,
    #                     help="the stomp port on the message bus.")
    #
    opts = parser.parse_args()
    sim_output_topic = simulation_output_topic(opts.simulation_id)
    sim_input_topic = simulation_input_topic(opts.simulation_id)
    sim_request = json.loads(opts.request.replace("\'",""))
    model_mrid = sim_request["power_system_config"]["Line_name"]
    gapps = GridAPPSD(opts.simulation_id, address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(), password=utils.get_gridappsd_pass())
    capacitors_dict = {}
    switches_dict = {}
    capacitors_meas_dict = {}
    switches_meas_dict = {}

    request = {
        "modelId": model_mrid,
        "requestType": "QUERY_OBJECT_DICT",
        "resultFormat": "JSON",
        "objectType": "LinearShuntCompensator"
        }

    response = gapps.get_response("goss.gridappsd.process.request.data.powergridmodel",request)
    for capacitor in response["data"]:
        capacitors_dict[capacitor["id"]] = capacitor

    request = {
        "modelId": model_mrid,
        "requestType": "QUERY_OBJECT_DICT",
        "resultFormat": "JSON",
        "objectType": "LoadBreakSwitch"
        }

    response = gapps.get_response("goss.gridappsd.process.request.data.powergridmodel",request)
    for switch in response["data"]:
        switches_dict[switch["id"]] = switch

    #print(capacitors_dict)
    #print(switches_dict)
    
    request = {"modelId": model_mrid,
               "requestType": "QUERY_OBJECT_MEASUREMENTS",
               "resultFormat": "JSON",
               "objectType": "LinearShuntCompensator"
               }
    
    response = gapps.get_response("goss.gridappsd.process.request.data.powergridmodel",request)
    for measurement in response["data"]:
        capacitors_meas_dict[measurement["measid"]] = measurement
        
    request = {"modelId": model_mrid,
               "requestType": "QUERY_OBJECT_MEASUREMENTS",
               "resultFormat": "JSON",
               "objectType": "LoadBreakSwitch"
               }
    
    response = gapps.get_response("goss.gridappsd.process.request.data.powergridmodel",request)
    for measurement in response["data"]:
        switches_meas_dict[measurement["measid"]] = measurement

    #print(capacitors_meas_dict)
    #print(switches_meas_dict)

    #capacitors_dict = get_capacitor_measurements(gapps, model_mrid)
    #switches_dict = get_switch_measurements(gapps, model_mrid)
    subscriber = SimulationSubscriber(opts.simulation_id, gapps, capacitors_dict, switches_dict, capacitors_meas_dict, switches_meas_dict)
    gapps.subscribe(sim_input_topic, subscriber)
    gapps.subscribe(sim_output_topic, subscriber)
    while True:
        time.sleep(0.1)
Beispiel #27
0
def _startTest(username,
               password,
               gossServer='localhost',
               stompPort='61613',
               simulationID=1234,
               rulePort=5000,
               topic="input"):
    req_template = {
        "power_system_config": {
            "SubGeographicalRegion_name":
            "_1CD7D2EE-3C91-3248-5662-A43EFEFAC224",
            "GeographicalRegion_name": "_24809814-4EC6-29D2-B509-7F8BFB646437",
            "Line_name": "_C1C3E687-6FFD-C753-582B-632A27E28507"
        },
        "simulation_config": {
            "power_flow_solver_method": "NR",
            "duration": 120,
            "simulation_name": "ieee123",
            "simulator": "GridLAB-D",
            "start_time": 1248156000,
            "run_realtime": True,
            "timestep_frequency": "1000",
            "timestep_increment": "1000",
            "model_creation_config": {
                "load_scaling_factor": 1.0,
                "triplex": "y",
                "encoding": "u",
                "system_frequency": 60,
                "voltage_multiplier": 1.0,
                "power_unit_conversion": 1.0,
                "unique_names": "y",
                "schedule_name": "ieeezipload",
                "z_fraction": "0",
                "i_fraction": "0",
                "p_fraction": "1",
                "randomize_zipload_fractions": False,
                "use_houses": False
            },
            "simulation_broker_port": 52798,
            "simulation_broker_location": "127.0.0.1"
        },
        "application_config": {
            "applications": [{
                "name": "der_dispatch_app",
                "config_string": "{}"
            }]
        },
        "simulation_request_type": "NEW",
        "test_config": {
            "events": []
        }
    }

    # _B221C5F6-E08A-BC62-91DE-ADC1E2F8FF96
    sw3_event = {
        "message": {
            "forward_differences": [{
                "object": "_B221C5F6-E08A-BC62-91DE-ADC1E2F8FF96",
                "attribute": "Switch.open",
                "value": 1
            }],
            "reverse_differences": [{
                "object": "_B221C5F6-E08A-BC62-91DE-ADC1E2F8FF96",
                "attribute": "Switch.open",
                "value": 0
            }]
        },
        "event_type": "ScheduledCommandEvent",
        "occuredDateTime": 1374258660 + (4 * 60),
        "stopDateTime": 1374258660 + (8 * 60)
    }
    pv_84_90_event = {
        "allOutputOutage":
        False,
        "allInputOutage":
        False,
        "inputOutageList": [
            {
                "objectMRID": "_233D4DC1-66EA-DF3C-D859-D10438ECCBDF",
                "attribute": "PowerElectronicsConnection.p"
            },
            {
                "objectMRID": "_233D4DC1-66EA-DF3C-D859-D10438ECCBDF",
                "attribute": "PowerElectronicsConnection.q"
            },
            {
                "objectMRID": "_60E702BC-A8E7-6AB8-F5EB-D038283E4D3E",
                "attribute": "PowerElectronicsConnection.p"
            },
            {
                "objectMRID": "_60E702BC-A8E7-6AB8-F5EB-D038283E4D3E",
                "attribute": "PowerElectronicsConnection.q"
            },
        ],
        "outputOutageList": [
            '_a5107987-1609-47b2-8f5b-f91f99658390',
            '_2c4e0cb2-4bf0-4a2f-be94-83ee9b87d1e5'
        ],
        "event_type":
        "CommOutage",
        "occuredDateTime":
        1374510600 + (5 * 60),
        "stopDateTime":
        1374510600 + (10 * 60)
    }

    pv_84_90_event = {
        "allOutputOutage":
        False,
        "allInputOutage":
        False,
        "inputOutageList": [
            {
                "objectMRID": "_EAE0584D-6B67-2F23-FC02-E3F2C8C6A48D",
                "attribute": "PowerElectronicsConnection.p"
            },
            {
                "objectMRID": "_EAE0584D-6B67-2F23-FC02-E3F2C8C6A48D",
                "attribute": "PowerElectronicsConnection.q"
            },
            {
                "objectMRID": "_73E7B579-37DB-B7F2-EBC6-D083E8BBA1F3",
                "attribute": "PowerElectronicsConnection.p"
            },
            {
                "objectMRID": "_73E7B579-37DB-B7F2-EBC6-D083E8BBA1F3",
                "attribute": "PowerElectronicsConnection.q"
            },
        ],
        "outputOutageList": [
            '_b8442bbd-4d3e-4b2e-884e-96639bb207bc',
            '_b005322e-7dba-48d3-b6ce-f6fe57c4dd61'
        ],
        "event_type":
        "CommOutage",
        "occuredDateTime":
        1374510600 + (5 * 60),
        "stopDateTime":
        1374510600 + (10 * 60)
    }

    # {"applications": [{"name": "der_dispatch_app", "config_string": ""}]}
    req_template['simulation_config']['model_creation_config'][
        'load_scaling_factor'] = 1
    req_template['simulation_config']['run_realtime'] = False
    req_template['simulation_config']['duration'] = 60 * 15

    req_template['simulation_config']['start_time'] = 1538510000
    req_template['simulation_config'][
        'start_time'] = 1374498000  # 7/22/2013 What I was doing
    req_template['simulation_config'][
        'start_time'] = 1374510600  # GMT: Monday, July 22, 2013 4:30:00 PM
    req_template['simulation_config']['start_time'] = 1374483600  # 3:00 am
    # req_template['simulation_config']['start_time'] = 1374519600  # (GMT): Monday, July 22, 2013 7:00:00 PM
    req_template['simulation_config'][
        'start_time'] = 1374530400  # (GMT): Monday, July 22, 2013 10:00:00 PM Cause
    req_template['simulation_config'][
        'start_time'] = 1374240600  # July 19 13:30 AM GMT / 7:30 AM MST
    # req_template['simulation_config']['start_time'] = 1374249600  #  July 19, 2013 4:00:00 PM
    req_template['simulation_config'][
        'start_time'] = 1374258600  # July 19, 2013 6:30:00 PM  - 2013-07-19 18:30:00 / 12:30 PM MST  # MAX PV!!!
    req_template['simulation_config'][
        'start_time'] = 1248156000  # Tuesday, July 21, 2009 6:00:00 AM
    req_template['simulation_config'][
        'start_time'] = 1248192000  # Tuesday, July 21, 2009 4:00:00 PM / 10:00:00 AM
    req_template['simulation_config']['start_time'] = timegm(
        strptime('2009-07-21 15:03:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))

    req_template['simulation_config']['start_time'] = timegm(
        strptime('2009-07-21 00:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 08:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    # req_template['simulation_config']['start_time'] = timegm(strptime('2009-07-21 12:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    req_template['simulation_config']['start_time'] = timegm(
        strptime('2019-07-22 12:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))
    req_template['simulation_config']['start_time'] = timegm(
        strptime('2019-07-23 14:50:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))

    pv_84_90_event["occuredDateTime"] = req_template['simulation_config'][
        'start_time'] + (2 * 60)
    pv_84_90_event["stopDateTime"] = req_template['simulation_config'][
        'start_time'] + (4 * 60)
    req_template["test_config"]["events"].append(pv_84_90_event)

    # sw3_event
    sw3_event["occuredDateTime"] = req_template['simulation_config'][
        'start_time'] + (7 * 60)
    sw3_event["stopDateTime"] = req_template['simulation_config'][
        'start_time'] + (9 * 60)
    # req_template["test_config"]["events"].append(sw3_event)

    app_config = {
        'OPF': 0,
        'run_freq': 60,
        'run_on_host': True,
        'run_realtime': req_template['simulation_config']['run_realtime'],
        'historical_run': 875592221
    }  #30
    app_config['historical_run'] = 0  # Turn Off
    req_template["application_config"]["applications"] = [{
        "name":
        "grid_forecasting_app",
        "config_string":
        json.dumps(app_config)
    }]

    # GMT: Tuesday, October 2, 2018 4:50:00 PM
    # Your time zone: Tuesday, October 2, 2018 10:50:00 AM GMT-06:00 DST
    req_template['power_system_config'][
        'Line_name'] = '_C1C3E687-6FFD-C753-582B-632A27E28507'
    req_template['power_system_config'][
        'Line_name'] = '_E407CBB6-8C8D-9BC9-589C-AB83FBF0826D'  # Mine 123pv
    # req_template['power_system_config']['Line_name'] = '_EBDB5A4A-543C-9025-243E-8CAD24307380'  # 123 with reg

    req_template['power_system_config'][
        'Line_name'] = '_DA00D94F-4683-FD19-15D9-8FF002220115'  # mine with house
    # req_template['power_system_config']['Line_name'] = '_88B3A3D8-51CD-7466-5E29-B692F21723CB' # Mine with feet conv
    # req_template['power_system_config']['Line_name'] = '_49AD8E07-3BF9-A4E2-CB8F-C3722F837B62'  # 13
    # req_template['power_system_config']['Line_name'] = '_C1C3E687-6FFD-C753-582B-632A27E28507'  # 123
    # req_template['power_system_config']['Line_name'] = '_AAE94E4A-2465-6F5E-37B1-3E72183A4E44'  # New 8500
    # req_template['power_system_config']['Line_name'] = '_AAE94E4A-Jeff'

    # req_template['power_system_config']['Line_name'] = '_4F76A5F9-271D-9EB8-5E31-AA362D86F2C3'
    req_template["application_config"]["applications"][0][
        'name'] = 'grid_forecasting_app'

    simCfg13pv = json.dumps(req_template)
    print(simCfg13pv)
    # exit(0)
    goss = GOSS()
    goss.connect()

    simulation_id = goss.get_response(goss_sim, simCfg13pv, timeout=200)
    simulation_id = int(simulation_id['simulationId'])
    print(simulation_id)
    print('sent simulation request')
    time.sleep(1)

    if app_config['run_on_host']:
        listening_to_topic = simulation_output_topic(simulation_id)
        log_topic = simulation_log_topic(simulation_id)
        model_mrid = req_template['power_system_config']['Line_name']
        start_time = req_template['simulation_config']['start_time']
        app_configs = req_template["application_config"]["applications"]
        app_config = [
            json.loads(app['config_string']) for app in app_configs
            if app['name'] == 'grid_forecasting_app'
        ][0]

        gapps = GridAPPSD(simulation_id)
        load_scale = req_template['simulation_config'][
            'model_creation_config']['load_scaling_factor']
        app = Grid_Forecast(simulation_id, gapps, model_mrid, start_time,
                            app_config, load_scale)
        app.setup()
        gapps.subscribe(listening_to_topic, app)
        # gapps.subscribe(log_topic, app)

        while True:
            time.sleep(0.1)
def _startTest(username,
               password,
               gossServer='localhost',
               stompPort='61613',
               simulationID=1234,
               rulePort=5000,
               topic="input"):
    req_template = {
        "power_system_config": {
            "SubGeographicalRegion_name":
            "_1CD7D2EE-3C91-3248-5662-A43EFEFAC224",
            "GeographicalRegion_name": "_24809814-4EC6-29D2-B509-7F8BFB646437",
            "Line_name": "_C1C3E687-6FFD-C753-582B-632A27E28507"
        },
        "simulation_config": {
            "power_flow_solver_method": "NR",
            "duration": 120,
            "simulation_name": "ieee123",
            "simulator": "GridLAB-D",
            "start_time": 1248156000,
            "run_realtime": True,
            "timestep_frequency": "1000",
            "timestep_increment": "1000",
            "model_creation_config": {
                "load_scaling_factor": 1.0,
                "triplex": "y",
                "encoding": "u",
                "system_frequency": 60,
                "voltage_multiplier": 1.0,
                "power_unit_conversion": 1.0,
                "unique_names": "y",
                "schedule_name": "ieeezipload",
                "z_fraction": 0.0,
                "i_fraction": 1.0,
                "p_fraction": 0.0,
                "randomize_zipload_fractions": False,
                "use_houses": False
            },
            "simulation_broker_port": 52798,
            "simulation_broker_location": "127.0.0.1"
        },
        "application_config": {
            "applications": [{
                "name": "der_dispatch_app",
                "config_string": "{}"
            }]
        },
        "simulation_request_type": "NEW"
    }

    req_template['simulation_config']['model_creation_config'][
        'load_scaling_factor'] = 1
    req_template['simulation_config']['run_realtime'] = True
    # req_template['simulation_config']['duration'] = 60 * 60 * 4
    req_template['simulation_config']['duration'] = 60 * 15
    req_template['simulation_config']['start_time'] = 1374510600
    req_template['power_system_config'][
        'Line_name'] = '_C1C3E687-6FFD-C753-582B-632A27E28507'
    # req_template['power_system_config']['Line_name'] = '_E407CBB6-8C8D-9BC9-589C-AB83FBF0826D'  # Mine 123pv
    # req_template['power_system_config']['Line_name'] = '_EBDB5A4A-543C-9025-243E-8CAD24307380'  # 123 with reg
    # # req_template['power_system_config']['Line_name'] = '_49AD8E07-3BF9-A4E2-CB8F-C3722F837B62'  # 13
    # req_template['power_system_config']['Line_name'] = '_AAE94E4A-2465-6F5E-37B1-3E72183A4E44'  # New 8500
    req_template["application_config"]["applications"][0][
        'name'] = 'solar_forecasting_app'
    req_template['simulation_config']['start_time'] = timegm(
        strptime('2013-07-22 08:00:00 GMT', '%Y-%m-%d %H:%M:%S %Z'))

    app_config = {'run_freq': 60, 'run_on_host': False}
    app_config['run_realtime'] = req_template['simulation_config'][
        'run_realtime']
    print(app_config)

    req_template["application_config"]["applications"] = [{
        "name":
        "solar_forecasting_app",
        "config_string":
        json.dumps(app_config)
    }]

    print(req_template)
    # req_template['power_system_config']['Line_name'] = '_67AB291F-DCCD-31B7-B499-338206B9828F' # J1

    simCfg13pv = json.dumps(req_template)
    print(simCfg13pv)
    goss = GOSS()
    goss.connect()

    simulation_id = goss.get_response(goss_sim, simCfg13pv, timeout=10)
    simulation_id = int(simulation_id['simulationId'])
    print(simulation_id)
    print('sent simulation request')
    time.sleep(1)

    if app_config['run_on_host']:
        listening_to_topic = simulation_output_topic(simulation_id)
        model_mrid = req_template['power_system_config']['Line_name']
        gapps = GridAPPSD(simulation_id)
        solar_forecast = Solar_Forecast(simulation_id, gapps, model_mrid,
                                        1538484951, app_config)
        gapps.subscribe(listening_to_topic, solar_forecast)

        while True:
            time.sleep(0.1)
class FncsBridge(object):

    def __init__(self, simulation_id,
                 fncs_broker_location='tcp://localhost:5570',
                 base_input_topic='/topic/goss.gridappsd.simulation.input',
                 base_output_topic="/topic/goss.gridappsd.simulation.output",
                 connect_now=True):

        if not base_input_topic.endswith('.'):
            base_input_topic += '.'

        if not base_output_topic.endswith('.'):
            base_output_topic += '.'

        self.fncs_broker_location = fncs_broker_location
        self.simulation_input_topic = base_input_topic + str(simulation_id)
        self.simulation_output_topic = base_output_topic + str(simulation_id)
        self.simulation_id = str(simulation_id)

        self._gridappsd = None
        self._gridappsd_listener = None

        if connect_now:
            self.start_bridge()

    def timestep_complete(self, current_time):
        """tell the fncs_broker to move to the next time step.

            Function arguments:
                current_time -- Type: integer. Description: the current time in seconds.
                    It must not be none.
            Function returns:
                None.
            Function exceptions:
                RuntimeError()
                ValueError()
            """
        try:
            message_str = 'In done with timestep ' + str(current_time)
            self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)
            if current_time or type(current_time) != int:
                raise ValueError(
                    'current_time must be an integer.\n'
                    + 'current_time = {0}'.format(current_time))
            time_request = current_time + 1
            message_str = 'calling time_request ' + str(time_request)
            self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)
            time_approved = fncs.time_request(time_request)
            message_str = 'time approved ' + str(time_approved)
            self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)
            if time_approved != time_request:
                raise RuntimeError(
                    'The time approved from fncs_broker is not the time requested.\n'
                    + 'time_request = {0}.\ntime_approved = {1}'.format(time_request,
                                                                        time_approved))
        except Exception as e:
            message_str = 'Error in fncs timestep ' + str(e)
            self._gridappsd.send_simulation_status('ERROR', message_str, ERROR)

    def publish_to_fncs(self, goss_message):
        """publish a message received from the GOSS bus to the FNCS bus.

        Function arguments:
            simulation_id -- Type: string. Description: The simulation id.
                It must not be an empty string. Default: None.
            goss_message -- Type: string. Description: The message from the GOSS bus
                as a json string. It must not be an empty string. Default: None.
        Function returns:
            None.
        Function exceptions:
            RuntimeError()
            ValueError()
        """
        message_str = 'publish to fncs bus {} {}'.format(self.simulation_id, goss_message)
        self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)

        if not self.simulation_id or type(self.simulation_id) != str:
            raise ValueError(
                'simulation_id must be a nonempty string.\n'
                + 'simulation_id = {0}'.format(self.simulation_id))
        if not goss_message or type(goss_message) != str:
            raise ValueError(
                'goss_message must be a nonempty string.\n'
                + 'goss_message = {0}'.format(goss_message))
        if not fncs.is_initialized():
            raise RuntimeError(
                'Cannot publish message as there is no connection'
                + ' to the FNCS message bus.')
        try:
            test_goss_message_format = yaml.safe_load(goss_message)
            if type(test_goss_message_format) != dict:
                raise ValueError(
                    'goss_message is not a json formatted string.'
                    + '\ngoss_message = {0}'.format(goss_message))
        except ValueError as ve:
            raise ValueError(ve)
        except:
            raise RuntimeError(
                'Unexpected error occured while executing yaml.safe_load(goss_message'
                + '{0}'.format(sys.exc_info()[0]))
        fncs_input_topic = '{0}/fncs_input'.format(self.simulation_id)
        message_str = 'fncs input topic ' + fncs_input_topic
        self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)
        fncs.publish_anon(fncs_input_topic, goss_message)

    def get_messages_from_fncs(self):
        """publish a message received from the GOSS bus to the FNCS bus.

            Function arguments:
                simulation_id -- Type: string. Description: The simulation id.
                    It must not be an empty string. Default: None.
            Function returns:
                fncs_output -- Type: string. Description: The json structured output
                    from the simulation. If no output was sent from the simulation then
                    it returns None.
            Function exceptions:
                ValueError()
            """
        try:
            fncs_output = None
            if not self.simulation_id or type(self.simulation_id) != str:
                raise ValueError(
                    'self.simulation_id must be a nonempty string.\n'
                    + 'simulation_id = {0}'.format(self.simulation_id))
            message_str = 'about to get fncs events'
            self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)
            message_events = fncs.get_events()
            message_str = 'fncs events ' + str(message_events)
            self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)
            if self.simulation_id in message_events:
                fncs_output = fncs.get_value(self.simulation_id)
            message_str = 'fncs_output ' + str(fncs_output)
            self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG)
            return fncs_output
        except Exception as e:
            message_str = 'Error on get FncsBusMessages for ' + str(self.simulation_id) + ' ' + str(e)
            self._gridappsd.send_simulation_status('ERROR', message_str, ERROR)

    def start_bridge(self):
        """Register with the fncs_broker and return.

            Function arguments:
                broker_location -- Type: string. Description: The ip location and port
                    for the fncs_broker. It must not be an empty string.
                    Default: 'tcp://localhost:5570'.
            Function returns:
                None.
            Function exceptions:
                RuntimeError()
                ValueError()
            """
        global is_initialized

        # First connect with goos via the GridAPPSD interface
        self._gridappsd = GridAPPSD(self.simulation_id, id=2,
                                    base_simulation_status_topic=BASE_SIMULATION_STATUS_TOPIC)
        self._gridappsd_listener = GridAPPSDListener(self, self._gridappsd)

        self._gridappsd.subscribe(self.simulation_input_topic,
                                  callback=self._gridappsd_listener)
        self._gridappsd.send_simulation_status("STARTING",
                                               "Starting Bridge for simulation id: {}".format(self.simulation_id))

        configuration_zpl = ''
        try:

            message_str = 'Registering with FNCS broker ' + str(self.simulation_id) + ' and broker ' + self.fncs_broker_location
            self._gridappsd.send_simulation_status("STARTED", message_str)

            message_str = 'connected to goss {}'.format(self._gridappsd.connected)
            self._gridappsd.send_simulation_status("STARTED", message_str)
            if not self.simulation_id or type(self.simulation_id) != str:
                raise ValueError(
                    'simulation_id must be a nonempty string.\n'
                    + 'simulation_id = {0}'.format(self.simulation_id))

            if not self.fncs_broker_location or type(self.fncs_broker_location) != str:
                raise ValueError(
                    'broker_location must be a nonempty string.\n'
                    + 'broker_location = {0}'.format(self.fncs_broker_location))
            fncs_configuration = {
                'name': 'FNCS_GOSS_Bridge_' + self.simulation_id,
                'time_delta': '1s',
                'broker': self.fncs_broker_location,
                'values': {
                    self.simulation_id: {
                        'topic': self.simulation_id + '/fncs_output',
                        'default': '{}',
                        'type': 'JSON',
                        'list': 'false'
                    }
                }
            }

            configuration_zpl = ('name = {0}\n'.format(fncs_configuration['name'])
                                 + 'time_delta = {0}\n'.format(fncs_configuration['time_delta'])
                                 + 'broker = {0}\nvalues'.format(fncs_configuration['broker']))
            for x in fncs_configuration['values'].keys():
                configuration_zpl += '\n    {0}'.format(x)
                configuration_zpl += '\n        topic = {0}'.format(
                    fncs_configuration['values'][x]['topic'])
                configuration_zpl += '\n        default = {0}'.format(
                    fncs_configuration['values'][x]['default'])
                configuration_zpl += '\n        type = {0}'.format(
                    fncs_configuration['values'][x]['type'])
                configuration_zpl += '\n        list = {0}'.format(
                    fncs_configuration['values'][x]['list'])
            fncs.initialize(configuration_zpl)

            is_initialized = fncs.is_initialized()
            if is_initialized:
                message_str = 'Registered with fncs ' + str(is_initialized)
                self._gridappsd.send_simulation_status("RUNNING", message_str)

        except Exception as e:
            message_str = 'Error while registering with fncs broker ' + str(e)
            self._gridappsd.send_simulation_status('ERROR', message_str, 'ERROR')
            if fncs.is_initialized():
                fncs.die()

        if not fncs.is_initialized():
            message_str = 'fncs.initialize(configuration_zpl) failed!\n' + 'configuration_zpl = {0}'.format(
                configuration_zpl)
            self._gridappsd.send_simulation_status('ERROR', message_str, 'ERROR')
            if fncs.is_initialized():
                fncs.die()
            raise RuntimeError(
                'fncs.initialize(configuration_zpl) failed!\n'
                + 'configuration_zpl = {0}'.format(configuration_zpl))
Beispiel #30
0
def _main():
    _log.debug("Starting application")
    print("Application starting-------------------------------------------------------")
    global message_period
    parser = argparse.ArgumentParser()
    parser.add_argument("simulation_id",
                        help="Simulation id to use for responses on the message bus.")
    parser.add_argument("request",
                        help="Simulation Request")
    parser.add_argument("--message_period",
                        help="How often the sample app will send open/close capacitor message.",
                        default=DEFAULT_MESSAGE_PERIOD)
    opts = parser.parse_args()
    listening_to_topic = simulation_output_topic(opts.simulation_id)
    message_period = int(opts.message_period)
    sim_request = json.loads(opts.request.replace("\'",""))
    model_mrid = sim_request['power_system_config']['Line_name']
    print("\n \n The model running is IEEE 9500-node with MRID:", model_mrid)
    
    _log.debug("Model mrid is: {}".format(model_mrid))
    gapps = GridAPPSD(opts.simulation_id, address=utils.get_gridappsd_address(),
                      username=utils.get_gridappsd_user(), password=utils.get_gridappsd_pass())

    # Get measurement MRIDS for Loadbreakswitches in the feeder
    print('Get Measurement MRIDS for Loadbreakswitches.....')
    topic = "goss.gridappsd.process.request.data.powergridmodel"
    message = {
        "modelId": model_mrid,
        "requestType": "QUERY_OBJECT_MEASUREMENTS",
        "resultFormat": "JSON",
        "objectType": "LoadBreakSwitch"}     
    obj_msr_loadsw = gapps.get_response(topic, message, timeout=180)
    with open('measid_LoadbreakSwitch.json', 'w') as json_file:
        json.dump(obj_msr_loadsw, json_file)    

    # Get measurement MRIDS for kW consumptions at each node
    print('Get Measurement MRIDS for EnergyConsumers.....')
    message = {
        "modelId": model_mrid,
        "requestType": "QUERY_OBJECT_MEASUREMENTS",
        "resultFormat": "JSON",
        "objectType": "EnergyConsumer"}     
    obj_msr_demand = gapps.get_response(topic, message, timeout=180)

    # Get Eq. MRIDs of Loadbreakswitches
    print('Get Switches Information.....')    
    switches = get_switches_mrids(gapps, model_mrid)

    # Load demand and lineparameters
    with open('Demand9500.json', 'r') as read_file:
        demand = json.load(read_file)
    with open('LineData.json', 'r') as read_file:
        line = json.load(read_file)

    print("Initialize.....")
    toggler = SwitchingActions(opts.simulation_id, gapps, switches, \
    obj_msr_loadsw, obj_msr_demand, demand, line)
    print("Now subscribing....")
    gapps.subscribe(listening_to_topic, toggler)
    while True:
        time.sleep(0.1)