Create and Add Custom Checks - Basic Examples

ToSee
Add a customized check to a Model Advisor By Product > Demo subfolder.Add Custom Check to by Product Folder

Create a Model Advisor pass/fail check.

Create Customized Pass/Fail Check

Create a Model Advisor pass/fail check with a fix action.

Create Customized Pass/Fail Check with Fix Action
Create a Model Advisor pass/fail check with detailed result collections Create Customized Pass/Fail Check with Detailed Result Collections

Add Custom Check to by Product Folder

This example shows how to add a custom check to a Model Advisor By Product > Demo subfolder. In this example, the customized check does not check model elements.

  1. In your working folder, create the sl_customization.m file. This file registers and creates the check registration function defineModelAdvisorChecks, which in turn registers the check callback function SimpleCallback. The function defineModelAdvisorChecks uses a ModelAdvisor.Root object to define the check interface.

    function sl_customization(cm)
    
    % --- register custom checks
    cm.addModelAdvisorCheckFcn(@defineModelAdvisorChecks);
    
    % --- defineModelAdvisorChecks function
    function defineModelAdvisorChecks
    mdladvRoot = ModelAdvisor.Root;
    rec = ModelAdvisor.Check('exampleCheck');
    rec.Title = 'Example of a customized check';
    rec.TitleTips = 'Added customized check to Product Folder';
    rec.setCallbackFcn(@SimpleCallback,'None','StyleOne');
    mdladvRoot.publish(rec, 'Demo'); 
    
    % --- creates SimpleCallback function
    function result = SimpleCallback(system);
    result={};

  2. Close the Model Advisor and your model if either are open.

  3. In the Command Window, enter:

    Advisor.Manager.refresh_customizations
  4. From the MATLAB® window, select New > Simulink Model to open a new Simulink® model window.

  5. In the Modeling tab, select Model Advisor. A System Selector ― Model Advisor dialog box opens. Click OK. The Model Advisor opens.

  6. In the left pane, expand the By Product folder to display the subfolders. The customized check Example of a customized check appears in the By Product > Demo subfolder.

    Note

    If the By Product folder is not displayed in the Model Advisor window, select SettingsPreferencesShow By Product Folder.

    The following commands in the sl_customization.m file create the right pane of the Model Advisor.

    rec.Title = 'Example of a customized check';
    rec.TitleTips = 'Added customized check to Product Folder';
    

Create Customized Pass/Fail Check

This example shows how to create a Model Advisor pass/fail check. In this example, the Model Advisor checks Constant blocks. If a Constant blocks value is numeric, the check fails.

  1. In your working folder, update the sl_customization.m file. This file registers and creates the check registration function defineModelAdvisorChecks, which also registers the check callback function SimpleCallback. The function SimpleCallback creates a check that finds Constant blocks that have numeric values. SimpleCallback uses the Model Advisor format template.

    function sl_customization(cm)
    
    % --- register custom checks
    cm.addModelAdvisorCheckFcn(@defineModelAdvisorChecks);
    
    % --- defineModelAdvisorChecks function
    function defineModelAdvisorChecks
    mdladvRoot = ModelAdvisor.Root;
    rec = ModelAdvisor.Check('exampleCheck');
    rec.Title = 'Check Constant block usage';
    rec.TitleTips = ['Fail if Constant block value is a number; Pass if' ...
        ' Constant block value is a letter'];
    rec.setCallbackFcn(@SimpleCallback,'None','StyleOne') 
    
    mdladvRoot.publish(rec, 'Demo');
    
    % --- SimpleCallback function that checks constant blocks
    function result = SimpleCallback(system)
    mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
    result    = {};
    
    all_constant_blk=find_system(system,'LookUnderMasks','all',...
        'FollowLinks','on','BlockType','Constant');
    blk_with_value=find_system(all_constant_blk,'RegExp','On','Value','^[0-9]');
    
    ft = ModelAdvisor.FormatTemplate('ListTemplate');
    ft.setInformation(['This check looks for constant blocks that'...
        ' use numeric values']);
    if ~isempty(blk_with_value)
        ft.setSubResultStatusText(['Check has failed. The following '...
            'Constant blocks have numeric values:']);
        ft.setListObj(blk_with_value);
        ft.setSubResultStatus('warn');
        ft.setRecAction('Parameterize the constant block');
        mdladvObj.setCheckResultStatus(false); 
    else
        ft.setSubResultStatusText(['Check has passed. No constant blocks'...
            ' with numeric values were found.']);
        ft.setSubResultStatus('pass');
        mdladvObj.setCheckResultStatus(true); 
    end
    ft.setSubBar(0);
    result{end+1} = ft;

  2. Close the Model Advisor and your model if either are open.

  3. In the Command Window, enter:

    Advisor.Manager.refresh_customizations
  4. From the MATLAB window, select New > Simulink Model to open a new Simulink model window.

  5. In the Simulink model window, create two Constant blocks named Const_one and Const_1. Right-click on a block, choose Block Parameters, and assign the Constant value as follows:

    • For Const_one, set the value to one.

    • For Const_1, set the value to 1.

  6. Save your model as example2_qs

  7. In the Modeling tab, select Model Advisor. A System Selector ― Model Advisor dialog box opens. Click OK. The Model Advisor opens.

  8. In the left pane, select By Product > Demo > Check Constant block usage.

    Note

    If the By Product folder is not displayed in the Model Advisor window, select SettingsPreferencesShow By Product Folder.

  9. Select Run This Check. The Model Advisor check fails for the Const_1 block and displays a Recommended Action.

    The following commands in the sl_customization.m file create the right pane in the Model Advisor.

    Check Constant block usage

    rec.Title = 'Check Constant block usage';
    rec.TitleTips = ['Fail if Constant block value is a number; Pass if' ...
        ' Constant block value is a letter'];
    
    Recommended Action
    ft.setInformation(['This check looks for constant blocks that'...
        ' use numeric values']);
    ft.setSubResultStatusText(['Check has failed. The following '...
            'Constant blocks have numeric values:']);
    ft.setListObj(blk_with_value);
    ft.setSubResultStatus('warn');
    ft.setRecAction('Parameterize the constant block');
    

  10. Follow the Recommended Action for fixing the failed Constant block. In the Model Advisor dialog box:

    • Double-click the example2_qs/Const_1 hyperlink.

    • Change the Constant value to two, or a nonnumeric value.

    • Rerun the Model Advisor check. Both Constant blocks now pass the check.

Create Customized Pass/Fail Check with Fix Action

This example shows how to create a Model Advisor pass/fail check with a fix action. In this example, the Model Advisor checks Constant blocks. If a Constant block value is numeric, the check fails. The Model Advisor is also customized to create a fix action for the failed checks.

  1. In your working folder, update the sl_customization.m file. This file contains three functions, each of which use the Model Advisor format template:

    • defineModelAdvisorChecks — Defines the check, creates input parameters, and defines the fix action.

    • simpleCallback — Creates the check callback function that finds Constant blocks with numeric values.

    • simpleActionCallback — Creates the fix for Constant blocks that fail the check.

    function sl_customization(cm)
    
    % --- register custom checks
    cm.addModelAdvisorCheckFcn(@defineModelAdvisorChecks);
    
    % --- defineModelAdvisorChecks function
    function defineModelAdvisorChecks
    mdladvRoot = ModelAdvisor.Root;
    rec = ModelAdvisor.Check('exampleCheck');
    rec.Title = 'Check Constant block usage';
    rec.TitleTips = ['Fail if Constant block value is a number; Pass if '...
        'Constant block value is a letter'];
    rec.setCallbackFcn(@SimpleCallback,'None','StyleOne') 
    
    % --- input parameters 
    rec.setInputParametersLayoutGrid([1 1]);
    inputParam1 = ModelAdvisor.InputParameter;
    inputParam1.Name = 'Text entry example';
    inputParam1.Value='VarNm';
    inputParam1.Type='String';
    inputParam1.Description='sample tooltip';
    inputParam1.setRowSpan([1 1]);
    inputParam1.setColSpan([1 1]);
    rec.setInputParameters({inputParam1});
    
    % -- set fix operation
    myAction = ModelAdvisor.Action;
    myAction.setCallbackFcn(@simpleActionCallback);
    myAction.Name='Fix Constant blocks';
    myAction.Description=['Click the button to update all blocks with'...
        ' Text entry example'];
    rec.setAction(myAction);
    
    mdladvRoot.publish(rec, 'Demo'); 
    
    % --- SimpleCallback function that checks constant blocks
    function result = SimpleCallback(system)
    mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system);
    result    = {};
    
    all_constant_blk=find_system(system,'LookUnderMasks','all',...
        'FollowLinks','on','BlockType','Constant');
    blk_with_value=find_system(all_constant_blk,'RegExp','On','Value','^[0-9]');
    
    ft = ModelAdvisor.FormatTemplate('ListTemplate');
    ft.setInformation(['This check looks for constant blocks that'...
        ' use numeric values']);
    if ~isempty(blk_with_value)
        ft.setSubResultStatusText(['Check has failed. The following '...
            'Constant blocks have numeric values:']);
        ft.setListObj(blk_with_value);
        ft.setSubResultStatus('warn');
        ft.setRecAction('Parameterize the constant block');
        mdladvObj.setCheckResultStatus(false);
        mdladvObj.setActionEnable(true);
    else
        ft.setSubResultStatusText(['Check has passed. No constant blocks'...
            'with numeric values were found.']);
        ft.setSubResultStatus('pass');
        mdladvObj.setCheckResultStatus(true);
    end
    ft.setSubBar(0);
    result{end+1} = ft;
    
    % --- creates SimpleActionCallback function that fixes failed check
    function result = simpleActionCallback(taskobj)
    mdladvObj = taskobj.MAObj;
    result    = {};
    
    system = getfullname(mdladvObj.System);
    
    % Get the string from the input parameter box.
    inputParams = mdladvObj.getInputParameters;
    textEntryEx = inputParams{1}.Value;
    
    all_constant_blk=find_system(system,'LookUnderMasks','all',...
        'FollowLinks','on','BlockType','Constant');
    blk_with_value=find_system(all_constant_blk,'RegExp','On','Value','^[0-9]');
    ft = ModelAdvisor.FormatTemplate('TableTemplate');
    % Define table col titles
    ft.setColTitles({'Block','Old Value','New Value'})
    for inx=1:size(blk_with_value)
       oldVal = get_param(blk_with_value{inx},'Value');
       ft.addRow({blk_with_value{inx},oldVal,textEntryEx});
       set_param(blk_with_value{inx},'Value',textEntryEx);    
    end
    
    ft.setSubBar(0);
    result = ft;
    mdladvObj.setActionEnable(false);

  2. Close the Model Advisor and your model if either are open.

  3. At the command prompt, enter:

    Advisor.Manager.refresh_customizations
  4. From the Command Window, select New > Simulink Model to open a new model.

  5. In the Simulink model window, create two Constant blocks named Const_one and Const_1. Right-click on a block, choose Block Parameters, and assign the Constant value as follows:

    • For Const_one, set the value to one.

    • For Const_1, set the value to 1.

  6. Save your model as example3_qs.

  7. In the Modeling tab, select Model Advisor. A System Selector ― Model Advisor dialog box opens. Click OK. The Model Advisor opens.

  8. In the left pane, select By Product > Demo > Check Constant block usage.

  9. Note

    If the By Product folder is not displayed in the Model Advisor window, select SettingsPreferencesShow By Product Folder.

  10. Select Run This Check. The Model Advisor check fails for the Const_1 block.

    The following commands in the sl_customization.m file create the right pane in the Model Advisor.

    Check Constant block usage

    rec.Title = 'Check Constant block usage';
    rec.TitleTips = ['Fail if Constant block value is a number; Pass if '...
        'Constant block value is a letter'];
    rec.setInputParametersLayoutGrid([1 1]);
    inputParam1 = ModelAdvisor.InputParameter;
    inputParam1.Name = 'Text entry example';
    inputParam1.Value='VarNm';
    inputParam1.Type='String';
    inputParam1.Description='sample tooltip';
    inputParam1.setRowSpan([1 1]);
    inputParam1.setColSpan([1 1]);
    rec.setInputParameters({inputParam1});
    
    Action
    myAction.Name='Fix Constant blocks';
    myAction.Description=['Click the button to update all blocks with'...
        'Text entry example'];
    

    The Model Advisor box has a Fix Constant blocks button in the Action section of the Model Advisor dialog box.

  11. In the Model Advisor dialog box, enter a nonnumeric value in the Text entry example parameter field in. In this example, the value is VarNm.

  12. Click Fix Constant blocks. The Const_1 Constant block value changes from 1 to the nonnumeric value that you entered. The Result section of the dialog box lists the Old Value and New Value of the Const_1 block.

    The following commands in the sl_customization.m file create the right pane in the Model Advisor.

    Action

    ft = ModelAdvisor.FormatTemplate('TableTemplate');
    
    ft.setColTitles({'Block','Old Value','New Value'})
    for inx=1:size(blk_with_value)
       oldVal = get_param(blk_with_value{inx},'Value');
       ft.addRow({blk_with_value{inx},oldVal,textEntryEx});
       set_param(blk_with_value{inx},'Value',textEntryEx);    
    end
    

  13. In the Model Advisor dialog box, click Run This Check. Both constant blocks now pass the check.

Create Customized Pass/Fail Check with Detailed Result Collections

This example shows how to create a Model Advisor check whose results are collected into a group, such as blocks in a subsystem that violate a check. When a check is not violated, the results contain the check description and result status. When a check is violated, the results contain the check description, result status, and the recommended action to fix the issue. This method is recommended when creating custom Model Advisor checks.

You can review results in the Model Advisor by selecting:

  • View By > Recommended Action ─ When a check is violated, this view shows a list of model elements that violate the check. When there is no violation, this view provides a brief description stating that the check was not violated.

  • View By > Subsystem ─ This view shows a table of model elements that violate the check, organized by model or subsystem (when applicable).

  • View By > Block ─ This view provides a list of check violations for each block.

When a check does not pass, results include a hyperlink to each model element that violates the check. Use these hyperlinks to easily locate areas in your model or subsystem.

To create a customized check with detailed result presented as a collection:

  1. In your working folder, update the sl_customization.m file as shows in the example. This file contains three functions specific for creating a check whose results are presented on the Model Advisor as a collection:

    • defineModelAdvisorChecks ─ Defines the check and fix actions. In this function, the callback style is 'DetailStyle', which is the Model Advisor format template that presents the results as a collection in the Model Advisor.

    • SampleNewCheckStyleCallback ─ Creates the check callback function that finds blocks whose name is not located below the block. The function uses name and value pairs to gather the results into collections. See Check Callback Function for Detailed Result Collections.

    • sampleActionCB0 ─ Creates the fix for blocks whose name is not located below the block. In this example, it moves the name below the block. See Action Callback Function for Detailed Result Collections.

    function sl_customization(cm)
    
    % -----------------------------
    % Register custom checks
    cm.addModelAdvisorCheckFcn(@defineModelAdvisorChecks);
    
    % -----------------------------
    % Define Model Advisor check "Check whether block names appear 
    % below blocks".
    function defineModelAdvisorChecks
    mdladvRoot = ModelAdvisor.Root;
    rec = ModelAdvisor.Check('com.mathworks.sample.Check0');
    rec.Title = 'Check whether block names appear below blocks 
        (recommended check style)';
    rec.TitleTips = 'Example new style callback (recommended 
        check style)';
    rec.setCallbackFcn(@SampleNewCheckStyleCallback,'None',
        'DetailStyle');
    % set fix operation
    myAction0 = ModelAdvisor.Action;
    myAction0.setCallbackFcn(@sampleActionCB0);
    myAction0.Name='Make block names appear below blocks';
    myAction0.Description='Click the button to place block     
        names below blocks';
    rec.setAction(myAction0);
    mdladvRoot.publish(rec, 'Demo'); % publish check into Demo group.
    
    % -----------------------------
    % Callback function for check "Check whether block names appear     
    % below blocks".
    function SampleNewCheckStyleCallback(system, CheckObj)
    mdladvObj = Simulink.ModelAdvisor.getModelAdvisor(system); % get object
    % find all blocks whose name does not appear below blocks
    violationBlks = find_system(system, 'Type','block',...
                               'NamePlacement','alternate',...
                               'ShowName', 'on');
    if isempty(violationBlks)
        ElementResults = ModelAdvisor.ResultDetail;
        ElementResults.IsInformer = true;
        ElementResults.Description = 'Identify blocks where the name is 
            not displayed below the block.';
        ElementResults.Status = 'All blocks have names displayed below     
            the block.';                
        mdladvObj.setCheckResultStatus(true);  
    else
        ElementResults(1,numel(violationBlks))=ModelAdvisor.ResultDetail;
        for i=1:numel(ElementResults)
            ElementResults(i).setData(violationBlks{i});
            ElementResults(i).Description = 'Identify blocks where the 
                name is not displayed below the block.';
            ElementResults(i).Status = 'The following blocks have names     
                that do not display below the blocks:';
            ElementResults(i).RecAction =  'Change the location such that     
                the block name is below the block.';
        end                        
        mdladvObj.setCheckResultStatus(false);  
        mdladvObj.setActionEnable(true);
    end
    CheckObj.setResultDetails(ElementResults);
    
    % -----------------------------
    % Action callback function for check "Check whether block names 
    % appear below blocks". 
    function result = sampleActionCB0(taskobj)
    mdladvObj = taskobj.MAObj;
    checkObj = taskobj.Check;
    resultDetailObjs = checkObj.ResultDetails;
    for i=1:numel(resultDetailObjs)
        % take some action for each of them
        block=Simulink.ID.getHandle(resultDetailObjs(i).Data);
        set_param(block,'NamePlacement','normal');
    end
    result = ModelAdvisor.Text('Changed the location such that the 
    block name is below the block.');
    mdladvObj.setActionEnable(false);
  2. Close the Model Advisor and your model if either are open.

  3. In the MATLAB command window, enter:

    Advisor.Manager.refresh_customizations
  4. From the MATLAB window, open model sldemo_fuelsys.

  5. In the Simulink model window:

    • In the top model, right-click the Engine Speed block and select Rotate & Flip > Flip Block Name.

    • Open the fuel_rate_control subsystem. Right-click the validate_sample_time block and select Rotate & Flip > Flip Block Name.

    Return to the top model and save as example_sldemo_fuelsys.

  6. In the Modeling tab, select Model Advisor. A System Selector ― Model Advisor dialog box opens. Click OK. The Model Advisor opens.

  7. In the left pane, select By Product > Demo > Check whether block names appear below blocks.

    Note

    If the By Product folder is not displayed in the Model Advisor window, select SettingsPreferencesShow By Product Folder.

  8. Select Run This Check. The Model Advisor check fails for the blocks.

  9. Review the results by selecting one of the View by options.

    The report provides a recommended action for each check. You can click the hyperlink path to open the violating block in the model editor. For example,

    The following commands in the sl_customization.m file create the right pane in the Model Advisor.

    Check title and subtitle

    rec.Title = 'Check whether block names appear below blocks 
        (recommended check style)';
    rec.TitleTips = 'Example new style callback (recommended 
        check style)';
    
    Result
    ElementResults(i).Description = 'Identify blocks where the name is
        not displayed below the block.';
    ElementResults(i).Status = 'The following blocks have names that do   
        not display below the blocks:';
    ElementResults(i).RecAction =  'Change the location such that the block
        name is below the block.';
    
    Action
    myAction0.Name='Make block names appear below blocks';
    myAction0.Description='Click the button to place block names 
        below blocks';
    

  10. Follow the recommended action for fixing the violating blocks by using one of these methods:

    • Update each violation individually by double-clicking the hyperlink to open the block. Right-click the block and select Rotate & Flip > Flip Block Name.

    • Select the Make block names appear below blocks button. The Model Advisor automatically fixes the issues in the model. Notice that the button is greyed out after the violations are fixed.

  11. Save the model and rerun the Model Advisor check. The check passes.

    The following commands in the sl_customization.m file create the right pane in the Model Advisor.

    Result

    ElementResults.Description = 'Identify blocks where the name is not 
        displayed below the block.';
    ElementResults.Status = 'All blocks have names displayed below the block.';
    

See Also

| | |

Related Topics