Main Content

addObserver

Add observer to scenario simulation

Since R2022a

    Description

    An observer is a type of actor that you can create and add to the MATLAB® cosimulation client in addition to the main actors participating in a scenario. Observers can only read simulation states without modifying them in any way during simulation. The purpose of observers is to allow for custom computations, for example, visualization and runtime analysis of simulation data. For instance, an observer can notice if a vehicle is too close to another vehicle.

    observer = addObserver(ScenarioSim,ObserverName,FileName) adds an observer named ObserverName represented by a MATLAB System object™, or a Simulink® model in the file FileName, to the scenario simulation ScenarioSim. If the command is successful, then the function returns logical 1 (true). Otherwise, the function returns logical 0 (false).

    example

    Examples

    collapse all

    1. At the MATLAB Command Window, specify the path to your local RoadRunner installation folder. This code snippet uses the default installation path of the RoadRunner application on Windows®. You can change the path to match the location of your RoadRunner installation folder.

      RRInstallationFolder = "C:\Program Files\RoadRunner " ...
        + matlabRelease.Release + "\bin\win64";
    2. Set the project location to the path of your RoadRunner project folder.

      rrProjectLocation = "C:\Observer_proj";
      
    3. Create a roadrunner (RoadRunner) object to launch the RoadRunner application, and open the project at the specified project location.

      rrApp = roadrunner(rrProjectLocation,"InstallationFolder",...
        RRInstallationFolder);
      
    4. Open the scene FourWaySignal, which is in the Scenes folder of your project.

      openScene(rrApp,"FourWaySignal");
      
    5. Open the scenario CutInAndSlow, which is in the Scenarios folder of your project.

      openScenario(rrApp,"CutInAndSlow");
      
    6. Connect to the RoadRunner Scenario server to enable cosimulation by using the createSimulation (RoadRunner Scenario) function.

      ss = createSimulation(rrApp);
      
    7. Create the class mySysObserver that inherits from matlab.System base class. The file containing mySysObserver must share the same name as the class.

      In the setupImpl method, get the list of actors in the scenario simulation. In the stepImpl method, increment a counter variable to get the number of vehicles driving above the velocity threshold in each time step. In the releaseImpl method, assign the array containing this statistic for all time steps to a workspace variable named NumberofVehiclesOverThreshold.

      classdef mySysObserver < matlab.System
      
          properties(Access=private)
               mScenarioSimObj;
               mScenarioSimActorList = [];
               velThreshold = 15;  % Set threshold velocity
               y = [];
          end
      
          methods(Access = protected)             
             
             function setupImpl(obj)
                 obj.mScenarioSimObj = Simulink.ScenarioSimulation.find("ScenarioSimulation", ...
                 "SystemObject", obj);
                 obj.mScenarioSimActorList = obj.mScenarioSimObj.get("ActorSimulation");
                 % Get list of all actors
             end
      
             function stepImpl(obj)
                 count = 0;
                 for i = 1:length(obj.mScenarioSimActorList)
                     vel = norm(getAttribute(obj.mScenarioSimActorList{i},"Velocity"));
                     if(vel > obj.velThreshold)
                       count = count + 1;  
                       % Number of vehicles driving above threshold velocity
                         in every time step 
                     end 
                 end
                 obj.y = [obj.y,count]; 
                 % Array with count value across all time steps                              
             end
      
             function releaseImpl(obj)
                 assignin('base','NumberofVehiclesOverThreshold', obj.y);
                 % Final array assigned to workspace variable
             end
          end
      end
    8. Add the System object in the file mySysObserver as an observer named velThreshold to the simulation ss.

      observer = addObserver(ss,"velThreshold","mysysObserver")

    9. Start the simulation.

      set(ss,"SimulationCommand","Start");
      
    10. Check the NumberofVehiclesOverThreshold variable in the base workspace to view the number of vehicles that crossed the velocity threshold across different time steps.

    11. After you finish viewing, or working with the variable, delete it from your workspace.

      clearvars NumberofVehiclesOverThreshold;

    Create and add a Simulink model as an observer of a RoadRunner Scenario simulation.

    This Simulink model observes the number of vehicles that drive at a velocity above a certain threshold value, in every time step of the scenario simulation. The velocity threshold value is configurable from the model.

    The example workflows on this page assume that:

    Explore a Simulink Observer Model

    Open the Simulink model Velocity_Threshold.

    modelname = "Velocity_Threshold"; 
    open_system(modelname);

    Snapshot of the Simulink model representing an observer for a scenario simulation.

    In the model, a RoadRunner Scenario Reader block is connected to a Queue block. The RoadRunner Scenario Reader block reads actor information dispatched by a simulation through the buses loaded in the workspace by the load model callback function.

    In the Block Parameters dialog box of the RoadRunner Scenario Reader block, Topic Category is set to Actor, Actor Type is set to All Types, and Topic is set to Actor Pose. These parameter settings enable the RoadRunner Scenario Reader block to output the Actor ID, Pose, Velocity, and Angular Velocity of vehicles in the scenario.

    The Queue block is connected to a MATLAB System block. The Queue block allows you to receive and manage information from multiple vehicles in RoadRunner Scenario in the form of messages.

    The MATLAB System block executes the behavior implemented in the MATLAB System object file ReadActorVel. The System object file contains these primary functions:

    • getInterfaceImpl — Defines the interface to the MATLAB System block, including the input and output signal types. The MATLAB System block receives messages through one input port and sends a signal through one output port.

    • stepImpl — Implements the code that calculates the number of vehicles that drive at a velocity above a certain threshold value, in every time step.

    To configure the velocity threshold from the model, double-click the MATLAB System block to open the Block Parameters dialog box. Enter the desired value in the Velocity Threshold box, and click OK. Save the model.

    The connected Scope block then plots a graph of the number of vehicles that drive at a velocity above a certain threshold value, at every time step.

    Note: Any Simulink model representing an observer must not have a RoadRunner Scenario Writer block.

    Add Simulink Observer Model to Scenario

    1. Specify the path to your local RoadRunner installation folder. This code snippet uses the default installation path of the RoadRunner application on Windows. You can change the path to match the location of your RoadRunner installation folder.

    RRInstallationFolder = "C:\Program Files\RoadRunner " + matlabRelease.Release + "\bin\win64";

    2. Set the project location to the path of your RoadRunner project folder.

    rrProjectLocation = "C:\Observer_proj";

    3. Create a roadrunner object to launch the RoadRunner application, and open the project at the specified project location.

    rrApp = roadrunner(rrProjectLocation,"InstallationFolder",RRInstallationFolder);

    4. Open the scene FourWaySignal, which is in the Scenes folder of your project.

    openScene(rrApp,"FourWaySignal");

    5. Open the scenario CutInAndSlow, which is in the Scenarios folder of your project.

    openScenario(rrApp,"CutInAndSlow");

    6. Connect to the RoadRunner Scenario server to enable cosimulation by using the createSimulation function.

    ss = rrApp.createSimulation();

    7. Add the model Velocity_Threshold to the scenario as an observer named sysobs.

    addObserver(ss,"sysobs","Velocity_Threshold");

    8. Start the simulation.

    set(ss,"SimulationCommand","Start");

    After the scenario plays, check the Scope block from the opened Simulink model to view the number of vehicles that crossed the velocity threshold across different time steps.

    Scope window with the number of vehicle crossing velocity threshold plotted for each time step.

    Copyright 2024 The MathWorks, Inc.

    Input Arguments

    collapse all

    RoadRunner Scenario simulation, specified as a ScenarioSimulation object.

    Example: ScenarioSim

    Name of the observer, specified as a string or character vector. Choose a unique and meaningful name for the observer.

    Example: "RedCarObserver"

    Name of the System object file, or name of the Simulink file containing the observer code, or an observer model, respectively. Specified as a string or character vector.

    You may use a MATLAB System object or a Simulink model, depending on how you choose to implement the observer.

    To create and add an observer from MATLAB, see Use MATLAB System Object Representing Observer to View Number of Vehicles Crossing Threshold Velocity.

    To create and add an observer from Simulink, see Use Simulink Model Representing Observer to View Number of Vehicles Crossing Threshold Velocity.

    Example: "mySysObserver.m"

    Example: "blueTruckObserver.slx"

    Version History

    Introduced in R2022a

    expand all