Documentation

Create Callback Functions and Results

About Callback Functions

A callback function specifies the actions that the Model Advisor performs on a model or subsystem, based on the check or action that the user runs. You must create a callback function for each custom check and action so that the Model Advisor can execute the function when a user runs the check. There are several types of callback functions:

All types of callback functions provide one or more return arguments for displaying the results after executing the check or action. In some cases, return arguments are strings or cell arrays of strings that support embedded HTML tags for text formatting. Use the Model Advisor Result Template API to format check results, as described in Format Model Advisor Results. Limit HTML tags to be compatible with alternate output formats.

Common Utilities for Authoring Checks

When you create a check, there are common Simulink® utilities that you can use to make the check perform different actions. Following is a list of utilities and when to use them. In the Utility column, click the link for more information about the utility.

UtilityUsed for...
find_system

Getting handle or path to:

  • Blocks

  • Lines

  • Annotations

When getting the object, you can:

  • Specify a search depth

  • Search under masks and libraries

get_param / set_paramGetting and setting system and block parameter values.
inspectGetting object properties. First you must get a handle to the object.
evalinWorking in the base workspace.
Simulink Identifier (SID)Identifying Simulink blocks, model annotations or Stateflow® objects. The SID is a unique number within the model, assigned by Simulink.
Stateflow APIProgrammatic access to Stateflow objects.

Simple Check Callback Function

Use a simple check callback function with results formatted using the Result Template API to indicate whether the model passed or failed the check, or to recommend fixing an issue. The keyword for this callback function is StyleOne. The check definition requires this keyword (see Define Custom Checks).

The check callback function takes the following arguments.

ArgumentI/O TypeDescription
systemInputPath to the model or subsystem analyzed by the Model Advisor.
resultOutputMATLAB® string that supports Model Advisor Formatting API calls or embedded HTML tags for text formatting.

For code examples see:

Detailed Check Callback Function

Use the detailed check callback function to return and organize results as strings in a layered, hierarchical fashion. The function provides two output arguments so you can associate text descriptions with one or more paragraphs of detailed information. The keyword for the detailed callback function is StyleTwo. The check definition requires this keyword (see Define Custom Checks).

The detailed callback function takes the following arguments.

ArgumentI/O TypeDescription
systemInputPath to the model or system analyzed by the Model Advisor.
ResultDescriptionOutputCell array of MATLAB strings that supports Model Advisor Formatting API calls or embedded HTML tags for text formatting. The Model Advisor concatenates the ResultDescription string with the corresponding array of ResultDetails strings.
ResultDetailsOutputCell array of cell arrays, each of which contains one or more strings.

    Note:   The ResultDetails cell array must be the same length as the ResultDescription cell array.

Here is an example of a detailed check callback function that checks optimization settings for simulation and code generation.

function [ResultDescription, ResultDetails] = SampleStyleTwoCallback(system)
ResultDescription ={};
ResultDetails ={};

model = bdroot(system);
mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system); % get object
mdladvObj.setCheckResultStatus(true);  % init result status to pass

% Check Simulation optimization setting
ResultDescription{end+1} = ModelAdvisor.Paragraph(['Check Simulation '...
    'optimization settings:']);
if strcmp(get_param(model,'BlockReduction'),'off');
    ResultDetails{end+1}     = {ModelAdvisor.Text(['It is recommended to '...
        'turn on Block reduction optimization option.'],{'italic'})};
    mdladvObj.setCheckResultStatus(false); % set to fail
    mdladvObj.setActionEnable(true);
else
    ResultDetails{end+1}     = {ModelAdvisor.Text('Passed',{'pass'})};
end

% Check code generation optimization setting
ResultDescription{end+1} = ModelAdvisor.Paragraph(['Check code generation '...
    'optimization settings:']);
ResultDetails{end+1}  = {};
if strcmp(get_param(model,'LocalBlockOutputs'),'off');
    ResultDetails{end}{end+1}     = ModelAdvisor.Text(['It is recommended to'...
        ' turn on Enable local block outputs option.'],{'italic'});
    ResultDetails{end}{end+1}     = ModelAdvisor.LineBreak;
    mdladvObj.setCheckResultStatus(false); % set to fail
    mdladvObj.setActionEnable(true);
end
if strcmp(get_param(model,'BufferReuse'),'off');
    ResultDetails{end}{end+1}     = ModelAdvisor.Text(['It is recommended to'...
        ' turn on Reuse block outputs option.'],{'italic'});
    mdladvObj.setCheckResultStatus(false); % set to fail
    mdladvObj.setActionEnable(true);
end
if isempty(ResultDetails{end})
    ResultDetails{end}{end+1}     = ModelAdvisor.Text('Passed',{'pass'});
end

Check Callback Function with Hyperlinked Results

This callback function automatically displays hyperlinks for every object returned by the check so that you can easily locate problem areas in your model or subsystem. The keyword for this type of callback function is StyleThree. The check definition requires this keyword (see Define Custom Checks).

This callback function takes the following arguments.

ArgumentI/O TypeDescription
systemInputPath to the model or system analyzed by the Model Advisor.
ResultDescriptionOutputCell array of MATLAB strings that supports the Model Advisor Formatting API calls or embedded HTML tags for text formatting.
ResultDetailsOutputCell array of cell arrays, each of which contains one or more Simulink objects such as blocks, ports, lines, and Stateflow charts. The objects must be in the form of a handle or Simulink path.

    Note:   The ResultDetails cell array must be the same length as the ResultDescription cell array.

The Model Advisor automatically concatenates each string from ResultDescription with the corresponding array of objects from ResultDetails. The Model Advisor displays the contents of ResultDetails as a set of hyperlinks, one for each object returned in the cell arrays. When you click a hyperlink, the Model Advisor displays the target object highlighted in your Simulink model.

The following is an example of a check callback function with hyperlinked results. This example checks a model for consistent use of font type and font size in its blocks. It also contains input parameters, actions, and a call to the Model Advisor Result Explorer, which are described in later sections.

function [ResultDescription, ResultDetails] = SampleStyleThreeCallback(system)
ResultDescription ={};
ResultDetails ={};

mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
mdladvObj.setCheckResultStatus(true);
needEnableAction = false;
% get input parameters
inputParams = mdladvObj.getInputParameters;
skipFontCheck = inputParams{1}.Value;
regularFontSize = inputParams{2}.Value;
regularFontName = inputParams{3}.Value;
if skipFontCheck
    ResultDescription{end+1} = ModelAdvisor.Paragraph('Skipped.');
    ResultDetails{end+1}     = {};
    return
end
regularFontSize = str2double(regularFontSize);
if regularFontSize<1 || regularFontSize>=99
    mdladvObj.setCheckResultStatus(false);
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['Invalid font size. '...
        'Please enter a value between 1 and 99']);
    ResultDetails{end+1}     = {};
end

% find all blocks inside current system
allBlks = find_system(system);

% block diagram doesn't have font property
% get blocks inside current system that have font property
allBlks = setdiff(allBlks, {system});

% find regular font name blocks
regularBlks = find_system(allBlks,'FontName',regularFontName);

% look for different font blocks in the system
searchResult = setdiff(allBlks, regularBlks);
if ~isempty(searchResult)
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['It is recommended to '...
        'use same font for blocks for a uniform appearance in the model. '...
        'The following blocks use a font other than ' regularFontName ': ']);
    ResultDetails{end+1}     = searchResult;
    mdladvObj.setCheckResultStatus(false);
    myLVParam = ModelAdvisor.ListViewParameter;
    myLVParam.Name = 'Invalid font blocks'; % pull down filter name
    myLVParam.Data = get_param(searchResult,'object')';
    myLVParam.Attributes = {'FontName'}; % name is default property
    mdladvObj.setListViewParameters({myLVParam});
    needEnableAction = true;
else
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['All block font names '...
        'are identical.']);
    ResultDetails{end+1}     = {};
end

% find regular font size blocks
regularBlks = find_system(allBlks,'FontSize',regularFontSize);
% look for different font size blocks in the system
searchResult = setdiff(allBlks, regularBlks);
if ~isempty(searchResult)
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['It is recommended to '...
        'use same font size for blocks for a uniform appearance in the model. '...
        'The following blocks use a font size other than ' ...
        num2str(regularFontSize) ': ']);
    ResultDetails{end+1}     = searchResult;
    mdladvObj.setCheckResultStatus(false);
    myLVParam = ModelAdvisor.ListViewParameter;
    myLVParam.Name = 'Invalid font size blocks'; % pull down filter name
    myLVParam.Data = get_param(searchResult,'object')';
    myLVParam.Attributes = {'FontSize'}; % name is default property
    mdladvObj.setListViewParameters...
        ({mdladvObj.getListViewParameters{:}, myLVParam});
    needEnableAction = true;
else
    ResultDescription{end+1} = ModelAdvisor.Paragraph(['All block font sizes '...
        'are identical.']);
    ResultDetails{end+1}     = {};
end

mdladvObj.setActionEnable(needEnableAction);
mdladvObj.setCheckErrorSeverity(1);

In the Model Advisor, if you run Example task with input parameter and auto-fix ability for the slvnvdemo_mdladv model, you can view the hyperlinked results. Clicking the first hyperlink, slvnvdemo_mdladv/Input, displays the Simulink model with the Input block highlighted.

Action Callback Function

An action callback function specifies the actions that the Model Advisor performs on a model or subsystem when the user clicks the action button. You must create one callback function for the action that you want to take.

The action callback function takes the following arguments.

ArgumentI/O TypeDescription
taskobjInputThe ModelAdvisor.Task object for the check that includes an action definition.
resultOutputMATLAB string that supports Model Advisor Formatting API calls or embedded HTML tags for text formatting.

For a code example, see Action Callback Function

Action Callback Function with Result Details

The following is an example of an action callback function that contains result details.

    % Get Simulink.ModelAdvisor object
    mdladvObj = taskobj.MAObj;
    % get result of 'MyCheck'
    myResult = mdladvObj.getCheckResult('MyCheck');
    % if the check is in style three
    [ResultDescription, ResultDetails] = myResult;

Format Model Advisor Results

Overview of Displaying Results

You can make the analysis results of your custom checks appear similar to each other with minimal scripting using the Model Advisor ModelAdvisor.FormatTemplate class, as described in ModelAdvisor.FormatTemplate. For examples of callback functions using the ModelAdvisor.FormatTemplate class, see Simple Check Callback Function.

If this format template does not meet your needs, or if you want to format action results, use the Model Advisor Formatting API, as described in the following sections.

Format Model Advisor Results

Use the Model Advisor Formatting API to produce formatted outputs in the Model Advisor. The following constructors of the ModelAdvisor class provide the ability to format the output. For more information on each constructor and associated methods, in the Constructor column, click the link.

ConstructorDescription
ModelAdvisor.TextFormats element text.
ModelAdvisor.ParagraphCombines elements into paragraphs.
ModelAdvisor.ListCreates a list of elements.
ModelAdvisor.LineBreakAdds a line break between elements.
ModelAdvisor.TableCreates a table.
ModelAdvisor.ImageAdds an image to the output.

Format Text

Text is the simplest form of output. You can format text in many different ways. The default text formatting is:

  • Empty

  • Default color (black)

  • Unformatted (not bold, italicized, underlined, linked, subscripted, or superscripted)

To change text formatting, use the ModelAdvisor.Text constructor. When you want one type of formatting for all text, use this syntax:

ModelAdvisor.Text(content, {attributes})
When you want multiple types of formatting, you must build the text.
t1 = ModelAdvisor.Text('It is ');
t2 = ModelAdvisor.Text('recommended', {'italic'});
t3 = ModelAdvisor.Text(' to use same font for ');
t4 = ModelAdvisor.Text('blocks', {'bold'});
t5 = ModelAdvisor.Text(' for a uniform appearance in the model.');

result = [t1, t2, t3, t4, t5];
Add ASCII and Extended ASCII characters using the MATLAB char command. For more information, see the ModelAdvisor.Text class page.

Format Lists

You can create two types of lists: numbered and bulleted. The default list formatting is bulleted. Use the ModelAdvisor.List constructor to create and format lists (see ModelAdvisor.List). You can create lists with indented subsections, formatted as either numbered or bulleted.

subList = ModelAdvisor.List();
subList.setType('numbered')
subList.addItem(ModelAdvisor.Text('Sub entry 1', {'pass','bold'}));
subList.addItem(ModelAdvisor.Text('Sub entry 2', {'pass','bold'}));

topList = ModelAdvisor.List();
topList.addItem([ModelAdvisor.Text('Entry level 1',{'keyword','bold'}), subList]);
topList.addItem([ModelAdvisor.Text('Entry level 2',{'keyword','bold'}), subList]);

Format Tables

The default table formatting is:

  • Default color (black)

  • Left justified

  • Bold title, row, and column headings

Change table formatting using the ModelAdvisor.Table constructor.

The following example code creates a subtable within a table.

table1 = ModelAdvisor.Table(1,1);
table2 = ModelAdvisor.Table(2,3);
table2.setHeading('Table 2');
table2.setHeadingAlign('center');
table2.setColHeading(1, 'Header 1');
table2.setColHeading(2, 'Header 2');
table2.setColHeading(3, 'Header 3');
table1.setHeading('Table 1');
table1.setEntry(1,1,table2);

The following example code creates a table with five rows and five columns containing randomly generated numbers. Use the MATLAB code in a callback function to create the table. The Model Advisor displays table1 in the results.

% ModelAdvisor.Table example

matrixData = rand(5,5) * 10^5;

% initialize a table with 5 rows and 5 columns (heading rows not counting)
table1 = ModelAdvisor.Table(5,5);

% set column headings
for n=1:5
    table1.setColHeading(n, ['Column ', num2str(n)]);
end

% set alignment of second column heading
table1.setColHeadingAlign(2, 'center');

% set column width of second column
table1.setColWidth(2, 3);

% set row headings
for n=1:5
    table1.setRowHeading(n, ['Row ', num2str(n)]);
end

% set Table content
for rowIndex=1:5
    for colIndex=1:5
        table1.setEntry(rowIndex, colIndex, ...
            num2str(matrixData(rowIndex, colIndex)));

        % set alignment of entries in second row
        if colIndex == 2
            table1.setEntryAlign(rowIndex, colIndex, 'center');
        end
    end
end

% overwrite content of cell 3,3 with a ModelAdvisor.Text
text = ModelAdvisor.Text('Example Text');
table1.setEntry(3,3, text)

Format Paragraphs

You must handle paragraphs explicitly because most markup languages do not support line breaks. The default paragraph formatting is:

  • Empty

  • Default color (black)

  • Unformatted, (not bold, italicized, underlined, linked, subscripted, or superscripted)

  • Aligned left

If you want to change paragraph formatting, use the ModelAdvisor.Paragraph class.

Formatted Output

The following is the example from Simple Check Callback Function, reformatted using the Model Advisor Formatting API.

function result = SampleStyleOneCallback(system)
mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
if strcmp(get_param(bdroot(system), 'ScreenColor'),'white')
   result = ModelAdvisor.Text('Passed',{'pass'});
   mdladvObj.setCheckResultStatus(true);
else
   msg1 = ModelAdvisor.Text(...
       ['It is recommended to select a Simulink window screen color'...
       ' of white for a readable and printable model. Click ']);
   msg2 = ModelAdvisor.Text('here');
   msg2.setHyperlink('matlab: set_param(bdroot,''ScreenColor'',''white'')');
   msg3 = ModelAdvisor.Text(' to change screen color to white.');
   result = [msg1, msg2, msg3];
   mdladvObj.setCheckResultStatus(false);
end
Was this topic helpful?