Main Content

Math Function Code Replacement

This example shows how to develop a code replacement library to optimize the performance of math functions by providing information on how to define code replacement for a sin function. To develop a code replacement library use either the interactive or programmatic approach. For more information, see Develop a Code Replacement Library.

Interactively Develop a Code Replacement Library

  1. Open the Code Replacement Tool (crtool), from the MATLAB command line with the following command:

    >>crtool
  2. Create a table.

    1. From the crtool context menu, select File > New Table.

    2. In the right pane, name the table crl_table_sin. Click Apply.

  3. Create an entry. From the crtool context menu, select File > New entry > Function.

  4. Create entry parameters. In the Function drop-down list, select sin. Algorithm information appears in the crtool. For this example, leave the parameter unspecified.

  5. Create the conceptual representation. The conceptual representation describes the signature of the function that you want to replace. In the Conceptual function subsection of the crtool, specify the return argument, y1, and the input argument, u1, with the Data Type of double and the Argument Type of Scalar.

  6. Create the implementation representation. The implementation representation describes the signature of the optimization function. For this example, to specify that the implementation arguments have the same order and properties as the conceptual arguments, select the Make conceptual and implementation argument types the same check box.

  7. Specify build information. Click the Build Information tab to open the build requirements pane. Specify the files (source, header, object) that the code generator requires for code replacement. For this example, you do not need to specify build information.

  8. Validate and save the table. Click the Mapping Information tab and verify the fields are filled in as shown. Click Validate entry. In the crtool context menu, select File > Save table > Save.

  9. Register a code replacement library. Registration creates a library composed of the tables that you specify. Select File > Generate registration file. In the Generate registration file dialog box, fill out these fields:

    To use your code replacement library, refresh your current MATLAB session with the command:

    >>sl_refresh_customizations

  10. Verify the code replacement library. From the MATLAB command line, open the library by using the Code Replacement Viewer and verify that the table and entry are correctly specified. For more information, see Verify Code Replacement Library. Configure your model to use the code replacement library, generate code, and verify that replacement occurs as expected. If unexpected behavior occurs, examine the hit and miss logs to troubleshoot the issues.

Programmatically Develop a Code Replacement Library

  1. Open the programmatic interface from the MATLAB menu by selecting New > Function.

  2. Create a table.

    1. Create a function with the name of your code replacement library table that does not have arguments and returns a table object. You can use this function to call your code replacement library table.

    2. Create a table object by calling RTW.TflTable.

    function hTable = crl_table_sin
    % Create a function to call the code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
  3. Create an entry. Because this example replaces a function, create a code replacement entry in your table by calling the entry function RTW.TflCFunctionEntry.

    function hTable = crl_table_sin
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = rtw.TflCFunctionEntry;
    
  4. Create entry parameters. Because this examples replaces a function, create entry parameters by calling the function setTflCFunctionEntryParameters.

    function hTable = crl_table_sin()
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry 
    hEntry = RTW.TflCFunctionEntry;
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters(...
            'Key',                         'sin', ...
            'Priority',                    30, ...
            'ImplementationName',          'mySin', ...
            'ImplementationHeaderFile',    'basicMath.h', ...
            'ImplementationSourceFile',    'basicMath.c');
  5. Create the conceptual representation. The conceptual representation describes the signature of the function that you want to replace. To explicitly specify argument properties, call the function createAndAddConceptualArg.

    function hTable = crl_table_sin()
    % Create a code replacement library table
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry 
    hEntry = RTW.TflCFunctionEntry;
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters(...
            'Key',                         'sin', ...
            'Priority',                    30, ...
            'ImplementationName',          'mySin', ...
            'ImplementationHeaderFile',    'basicMath.h', ...
            'ImplementationSourceFile',    'basicMath.c');
    
    %% Create the conceptual representation
    hEntry.createAndAddConceptualArg(...
            'RTW.TflArgNumeric',      ...
            'Name',                   'y1',...
            'IOType',                 'RTW_IO_OUTPUT',...
            'DataTypeMode',           'double');
    
    hEntry.createAndAddConceptualArg(...
            'RTW.TflArgNumeric',      ...
            'Name',                   'u1', ...
            'IOType',                 'RTW_IO_INPUT',...
            'DataTypeMode',           'double');
    
  6. Create the implementation representation. The implementation representation describes the signature of the optimization function. To specify that the implementation arguments have the same order and properties as the conceptual arguments, call the function copyConceptualArgsToImplementation. Add the complete entry to the table by calling the function addEntry.

    function hTable = crl_table_sin()
    % Create a code replacement library table
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry 
    hEntry = RTW.TflCFunctionEntry;
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters(...
            'Key',                         'sin', ...
            'Priority',                    30, ...
            'ImplementationName',          'mySin', ...
            'ImplementationHeaderFile',    'basicMath.h', ...
            'ImplementationSourceFile',    'basicMath.c');
    
    %% Create the conceptual representation
    hEntry.createAndAddConceptualArg(...
            'RTW.TflArgNumeric',      ...
            'Name',                   'y1',...
            'IOType',                 'RTW_IO_OUTPUT',...
            'DataTypeMode',           'double');
    
    hEntry.createAndAddConceptualArg(...
            'RTW.TflArgNumeric',      ...
            'Name',                   'u1', ...
            'IOType',                 'RTW_IO_INPUT',...
            'DataTypeMode',           'double');
    
    %% Create the Implementation Representation
    copyConceptualArgsToImplementation(hEntry);
    
    %% Add the entry to the table
    hTable.addEntry(hEntry);
    
  7. Specify build information. In the entry parameters, specify files (header, source, object) that the code generator needs for code replacement. For this example, build information is not required.

  8. Validate and save the customization file. From the MATLAB menu, save this customization file by selecting File > Save. From the command line, validate the code replacement library table by calling it:

    >> hTable = crl_table_sin
  9. Register the code replacement library. Registration creates a code replacement library by defining the library name, code replacement tables, and other information. Create a registration file (a new function file) with these specifications:

    function rtwTargetInfo(cm)
     
    cm.registerTargetInfo(@loc_register_crl);
    end
     
    function this = loc_register_crl 
     
    this(1) = RTW.TflRegistry; 
    this(1).Name = 'CRL for sin function replacement’;
    this(1).TableList = {'crl_table_sin.m'}; % table created in this example
    this(1).TargetHWDeviceType = {'*'};
    this(1).Description = 'Example code replacement library';
    
    end
    

    To use your code replacement library, refresh your current MATLAB session with the command:

    >>sl_refresh_customizations

  10. Verify the code replacement library. From the MATLAB command line, open the library by using the Code Replacement Viewer and verify that the table and entry are correctly specified. For more information, see Verify Code Replacement Library. Configure your model to use the code replacement library, generate code, and verify that replacement occurs as expected. If unexpected behavior occurs, examine the hit and miss logs to troubleshoot the issues.

Generate Code by Using Math Code Replacement Library

In this section, you generate code using the code replacement library that you created in the first two sections of this example. A math function sin is replaced with a call to a custom function in the generated code. This example does not provide an implementation function. Write your own implementation.

Example Model

Open the model crl_mathfunction for configuring the code replacement library.

open_system('crl_mathfunction');

copyfile mathFnRtwTargetInfo.txt rtwTargetInfo.m

Run the MATLAB customization file to create a code replacement table and register the file. The customization file has already been executed. Run the sl_refresh_customizations function to register the library.

sl_refresh_customizations;

Enable Code Replacement Library

  1. Open the Configuration Parameters dialog box.

  2. On the Interface pane, set Code Replacement Library by clicking Select and adding CRL for sin function replacement to the Selected code replacement libraries - prioritized list pane. Alternatively, use the command-line API to enable the code replacement:

set_param('crl_mathfunction', 'CodeReplacementLibrary', 'CRL for sin function replacement');

Generate code from the model:

evalc('rtwbuild(''crl_mathfunction'')');

View the generated code. Here is a portion of crl_mathfunction.c.

cfile = fullfile('crl_mathfunction_ert_rtw','crl_mathfunction.c');
rtwdemodbtype(cfile,'/* Model step function ','/* Model initialize function',1, 1);
/* Model step function */
void crl_mathfunction_step(void)
{
  /* Outport: '<Root>/Y1' incorporates:
   *  Inport: '<Root>/U1'
   *  Trigonometry: '<Root>/Trigonometric Function'
   */
  crl_mathfunction_Y.Y1 = mySin(crl_mathfunction_U.U1);
}

The sin function is replaced with a custom mysin function.

Close the model and code generation report.

delete ./rtwTargetInfo.m
bdclose('crl_mathfunction');
rtwdemoclean;

Related Topics