how to generate c code for a tracker -凯发k8网页登录
this example shows how to generate c code for a matlab function that processes detections and outputs tracks. the function contains a trackergnn
, but any tracker can be used instead.
automatic generation of code from matlab code has two key benefits:
prototypes can be developed and debugged in the matlab environment. once the matlab work is done, automatic c code generation makes the algorithms deployable to various targets. additionally, the c code can be further tested by running the compiled mex file in a matlab environment using the same visualization and analysis tools that were available during the prototyping phase.
after generating c code, you can generate executable code, which in many cases runs faster than the matlab code. the improved run time can be used to develop and deploy real-time sensor fusion and tracking systems. it also provides a better way to batch test the tracking systems on a large number of data sets.
the example explains how to modify the matlab code in the air traffic control example to support code generation. this example requires a matlab coder license for generating c code.
modify and run matlab code
to generate c code, matlab coder requires matlab code to be in the form of a function. furthermore, the arguments of the function cannot be matlab classes.
in this example, the code for the air traffic control (atc) example has been restructured such that the trackergnn
that performs sensor fusion and tracking resides in a separate file, called . review this file for important information about memory allocation for code generation.
to preserve the state of the trackergnn
between calls to tracker_kernel.m
, the tracker is defined as a variable.
this function takes a cell array of objectdetection
objects, generated by the fusionradarsensor
object, and time as input arguments.
similarly, the outputs from a function that supports code generation cannot be objects. the outputs from tracker_kernel.m
are:
confirmed tracks - a
struct
array that contains a variable number of tracks.number of tracks - an integer scalar.
information about the tracker processing at the current update.
by restructuring the code this way, you can reuse the same display tools used in the atc example. these tools still run in matlab and do not require code generation.
% if a previous tracker is defined, clear it. clear tracker_kernel % create the atc scene with radar and platforms. [scenario,tower,radar] = helpercreateatcscenario; % create a display to show the true, measured, and tracked positions of the % airliners. [theater,fig] = helpertrackercgexample('create display',scenario); helpertrackercgexample('update display',theater,scenario,tower);
now run the example by calling the tracker_kernel
function in matlab. this initial run provides a baseline to compare the results and enables you to collect some metrics about the performance of the tracker when it runs in matlab or as a mex file.
simulate and track airliners
the following loop advances the platform positions until the end of the scenario. for each step forward in the scenario, the radar generates detections from targets in its field of view. the tracker is updated with these detections after the radar has completed a 360 degree scan in azimuth.
% set simulation to advance at the update rate of the radar. scenario.updaterate = radar.updaterate; % create a buffer to collect the detections from a full scan of the radar. scanbuffer = {}; % initialize the track array. tracks = []; % set random seed for repeatable results. rng(2020) % allocate memory for number of tracks and time measurement in matlab. numsteps = 12; numtracks = zeros(1, numsteps); runtimes = zeros(1, numsteps); index = 0; while advance(scenario) && ishghandle(fig) % generate detections on targets in the radar's current field of view. [dets,config] = detect(scenario); scanbuffer = [scanbuffer;dets]; %#okallow the buffer to grow. % update tracks when a 360 degree scan is complete. if config.isscandone % update tracker index = index 1; tic [tracks, numtracks(index), info] = tracker_kernel(scanbuffer,scenario.simulationtime); runtimes(index) = toc; % gather matlab run time data % clear scan buffer for next scan. scanbuffer = {}; end % update display with current beam position, buffered detections, and % track positions. helpertrackercgexample('update display',theater,scenario,tower,scanbuffer,tracks); end
compile the matlab function into a mex file
use the codegen
function to compile the tracker_kernel
function into a mex file. you can specify the -report
option to generate a compilation report that shows the original matlab code and the associated files that were created during c code generation. consider creating a temporary directory where matlab coder can store generated files. note that unless you use the -o
option to specify the name of the executable, the generated mex file has the same name as the original matlab file with _mex
appended.
matlab coder requires that you specify the properties of all the input arguments. the inputs are used by the tracker to create the correct data types and sizes for objects used in the tracking. the data types and sizes must not change between data frames. one easy way to do this is to define the input properties by example at the command line using the -args
option. for more information, see (matlab coder).
% define the properties of the input. first define the detections buffer as % a variable-sized cell array that contains objectdetection objects. then % define the second argument as simtime, which is a scalar double. dets = coder.typeof(scanbuffer(1), [inf 1], [1 0]); compinputs = {dets scenario.simulationtime}; % code generation may take some time. h = msgbox({'generating code. this may take a few minutes...';'this message box will close when done.'},'codegen message'); % generate code. try codegen tracker_kernel -args compinputs; close(h) catch me close(h) throw(me) end
code generation successful.
run the generated code
now that the code has been generated, run the exact same scenario with the generated mex file tracker_kernel_mex
. everything else remains the same.
% if a previous tracker is defined, clear it. clear tracker_kernel_mex % allocate memory for number of tracks and time measurement numtracksmex = zeros(1, numsteps); runtimesmex = zeros(1, numsteps); % reset the scenario, data counter, plotters, scanbuffer, tracks, and rng. index = 0; restart(scenario) scanbuffer = {}; clearplotterdata(theater); tracks = []; rng(2020) while advance(scenario) && ishghandle(fig) % generate detections on targets in the radar's current field of view. [dets,config] = detect(scenario); scanbuffer = [scanbuffer;dets]; %#okallow the buffer to grow. % update tracks when a 360 degree scan is complete. if config.isscandone % update tracker. index = index 1; tic [tracks, numtracksmex(index), info] = tracker_kernel_mex(scanbuffer,scenario.simulationtime); runtimesmex(index) = toc; % gather mex run time data % clear scan buffer for next scan. scanbuffer = {}; end % update display with current beam position, buffered detections, and % track positions. helpertrackercgexample('update display',theater,scenario,tower,scanbuffer,tracks); end
compare the results of the two runs
compare the results and the performance of the generated code vs. the matlab code. the following plots compare the number of tracks maintained by the trackers at each time step. they also show the amount of time it took to process each call to the function.
figure(2) subplot(2,1,1) plot(2:numsteps, numtracks(2:numsteps), 's:', 2:numsteps, numtracksmex(2:numsteps), 'x-.') title('number of tracks at each step'); legend('matlab', 'mex') grid subplot(2,1,2) plot(2:numsteps, runtimesmex(2:numsteps)*1e3); title('mex processing time at each step') grid xlabel('time step') ylabel('mex processing time [ms]')
the top plot shows that the number of tracks that were maintained by each tracker are the same. it measures the size of the tracking problem in terms of number of tracks. even though there were 3 confirmed tracks throughout the tracking example, the total number of all tracks maintained by the tracker varies based on the number of tentative tracks, that were created by false detections.
the bottom plot shows the time required for the generated code function to process each step. the first step was excluded from the plot, because it takes a disproportionately longer time to instantiate all the tracks on the first step.
the results show the number of milliseconds required by the mex code to perform each update step on your computer. in this example, the time required for the mex code to run an update step is measured in a few milliseconds.
summary
this example showed how to generate c code from matlab code for sensor fusion and tracking.
the main benefits of automatic code generation are the ability to prototype in the matlab environment, and generate a mex file that can run in the matlab environment. the generated c code can be deployed to a target. in most cases, the generated code is faster than the matlab code, and can be used for batch testing of algorithms and generating real-time tracking systems.