rapid development tools in matlab1 - university of...
TRANSCRIPT
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Rapid Development Tools in MATLAB1
W. Steven Rosenthal
wrosenthal at math.arizona.edu
University of ArizonaGIDP in Applied Mathematics
March 6, 2013
1Best, searchable documentation athttp://www.mathworks.com/help/index.html
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Abstract
Rapid Development Tools in MATLAB
This presentation introduces and develops tools that can be used with MATLAB forrapid prototyping. While MATLAB is not a computational workhorse, its programdevelopment environment is quick and efficient for small- to medium-scale projects. Ithelps organize and analyze implementation, provides powerful graphical analysis tools,and facilitates rapid sharing of results. One can speed up research tasks even furtherby taking advantage of the structure of MATLAB’s graphical output and libraryroutines. For custom codes, after using the code analyzer to optimize runtime,MATLAB furnishes automated tools to publish the routine in more common or lowerlevel languages. The specific tasks explored within include:
Resizing of all text and graphics in a figure with a single parameter;
Controlling hgobject properties to improve data visualization;
Expanding the utility and reliability of MATLAB library routines with customhandle classes;
Outsourcing intensive computations to C/C++ via automated publishing;
Ensuring reliable code sharing by using MATLAB libraries.
Sample codes for most tasks, and copies of this presentation, can be found on the UAMath Department Software Interest Group (SWIG) website:
http://math.arizona.edu/~swig/
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Outline
1 Graphical objects and control
2 Using properties to control graphics
3 Built-in functions and control
4 Outsourcing slow computation to C/C++
5 Organizing utility libraries
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Table of Contents
1 Graphical objects and controlObject anatomy of a typical plotMATLAB handle graphics object hierarchyFinding and using hgobjectsExample: controlling legend entriesGlobal queries and changesExample: group plot formattingThe ‘UserData’ propertyOne-parameter resizing
2 Using properties to control graphics
3 Built-in functions and control
4 Outsourcing slow computation to C/C++
5 Organizing utility libraries
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Object anatomy of a typical plot
Every plot is a collection of“hgobjects” (handle graphics)
figure window
axes box (with ticks/labels)
title and axes labels
legend box, lines, and labels
“hidden” annotations
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
MATLAB handle graphics object hierarchy
Objects defined by properties
‘Type’
‘Parent’/‘Children’
‘Visible’
‘Position’
‘UserData’
Data/formatting (most)
Examples of objects:
Core: axes, line, text, patch, surface,textPlot: (groups of objects) lineseries,contourgorup, quivergroup, surfaceplotGroup: (group by user) hggroup,hgtransform
Some object properties can affectother objects;
Scope controlled by a hierarchy →Parents ↑Children ↓
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Finding and using hgobjects
Methods: functions which query properties, change their value, or use thevalue.
Commands for querying/modifying properties:
gcf, gca, gco - currently selected figure, axes, or object
get - the value of a property from an object
set - the value of a property of an object
delete - an object (all children fall out of scope)
Objects identified by handles
Name is a “randomly” generated floating point number
A handle usually is outputed when the object is created
h = figure, h = axes, h = line
Can find handles later by using the handle from its parent or child
hc = get(axes handle,’children’)
The MATLAB root (session) has handle 0
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Example: controlling legend entries
hSLines = plot(t,sin(m),’Color’,’b’);
hSGroup = hggroup; % declare hggroup object
set(hSLines,’Parent’,hSGroup) % parent of sine lines
set(get(get(hSGroup,’Annotation’),’LegendInformation’),...
’IconDisplayStyle’,’on’); % hggroup legend icon->on
legend(’Sine’,’Cosine’,’Location’,’SouthEast’)
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Global queries and changes
Commands to search parts/all of a hgobject tree
target_handles = findobj(handle,’property’,value)
ignores hidden objects, finicky with scope
target_handles = findall(handle,’property’,value)
finds all subobjects with given properties
Refine with boolean switches
...,‘property’,value,‘-and’,‘property’,valuealso ‘-or’,‘-xor’, ‘-not’
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Example: group plot formatting
Unify fonts in all objects of all plots in a directory:
fs = 16; % <-- specify fontsize
s = dir(’*.fig’); % build structure of fig files
for j = 1:length(s)
hf = open(s(j).name);
htext = findall(hf,’type’,’text’,’-or’,’type’,’axes’);
% vector of objects containing printed text
set(htext,’fontsize’,fs) % set all fontsizes
[~,filename,~] = fileparts(s(j).name); % remove .fig suffix
print(hf,’-dpng’,’-r150’,filename) % save as .png
close(hf); % without saving reformatting
end
Caveat:1 Often have multiple plot sizes in paper/presentation
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
The ‘UserData’ property
All hgobjects have a ’UserData’ propertyBest practices: when using a program with automated plot output, check ifit uses this property and in which objects.
1 Write a function2 to save figures and include a “printsize” in UserData.
function fig(figure_handle,filename,printsize)
2 Consider a subfunction to associate “printsize” with ideal fontsize
% Assumes fontunits = point, ensures positive integer
% printsize = 5 <=> fontsize = 24 point (half size)
% printsize = 10 <=> fontsize = 16 point (full size)
fontsize = @(printsize) max(ceil( 24-8/5*(printsize-5) ),1);
3 Can write a similar subfunction to control line width and marker size
4 Write another function2 to save figures according to specified “printsize”
function png(figure_handle,filename,printsize)
2Sample code on SWIG site
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
One-parameter resizing
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Table of Contents
1 Graphical objects and control
2 Using properties to control graphicsUngrouping objects for legendsLinking axes of corresponding subplots
3 Built-in functions and control
4 Outsourcing slow computation to C/C++
5 Organizing utility libraries
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Ungrouping objects for legends3
[mC hC] = contour(X,Y,Z,’linewidth’,2);% Undo grouping by letting children
% have legend entries
set(get(get(hC,’Annotation’),...
’LegendInformation’),...
’IconDisplayStyle’,’Children’);
% Label each line with its contour height
hLines = get(hC,’Children’);
k = 1; ind = 1;
while k < size(mC,2),
set(hLines(ind),’DisplayName’,...
num2str(mC(1,k)))
k = k+mC(2,k)+1; ind = ind+1;
end
legend(’show’)
3See http://www.mathworks.com/help/releases/R2012a/techdoc/creating_
plots/braliom.html
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Linking axes of corresponding subplots
Subplots often have corresponding x- or y - axes
linkaxes(axes handle vector,’x’) - x-axis limits synced
Can link ’y’ axis limits or ’xy’ both4
linkprop - generalized to linking any property
4Seehttp://www.mathworks.com/help/releases/R2012a/techdoc/ref/linkaxes.html
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Overlapping axes in plots
The plotyy function5 graphs two lineswith different ordinate scales
Each line is child to a different axesobjectWhen axes are coincident, difficultadd y-axis labels (also children ofaxes) with the graphical interfaceplotyy outputs hgobject handles foreach axes and line. Use these tocoordinate y-axis labels, colors, tickmarks, and legend entriesUse syntaxplotyy(x1, y1, x2, y2,@plotfun)to extend double y-axes functionalityto “plotfun”
5Seehttp://www.mathworks.com/help/releases/R2012a/techdoc/ref/plotyy.html
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Table of Contents
1 Graphical objects and control
2 Using properties to control graphics
3 Built-in functions and controlBlack-box methods in MATLABFunctions as objectsProblems with scopeExpanding the scope of a functionUsing a wrapped function handle
4 Outsourcing slow computation to C/C++
5 Organizing utility libraries
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Black-box methods in MATLAB
Encounter during common tasks:
Numerically solve nonlinear ODEs
[tout,yout] = ode45(odefun,tspan,y0,options)
Optimize nonlinear functionals
[x,fval] = fminsearch(fun,x0,options)
Advantages:
Many problems can be described with the function object inputodefun or fun
Can specify options (odeset or optimset), including runtimeoutput/plot functions6
6See http://www.mathworks.com/help/optim/ug/optimization-options-reference.html
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Black-box methods in MATLAB
Disadvantages:
1 Some problems may require previous model states, e.g.
Processes with time correlationStopping conditions with long-term comparisonsAny problems using time- or iteration-averaged parametersLarge-scale problems: upscaling output in runtime reduces storage
2 Escaping destroys all data as black-box method goes out of scope
Uncaught error thrownctrl+c due to e.g. uncontrolled inf/NaN or slow convergence
→ Would be nice to collect, protect, and/or process data in runtime.
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Functions as objects
→ Think of functions as objects with their own properties and methods.
Recall: e.g. hgobjects have lots of properties, and methods like get andset and findall which draw from and/or manipulate the properties.
The simplest function is the anonymous function, e.g.
% Lorenz-63 model
lorenz63 = @(x,y,z,si,rh,be) [ si*(y-x) ; ...
x.*(rh-z)-y ; ...
x.*y-be*z ];
dudt = @(t,u) lorenz63(u(1),u(2),u(3),10,28,8/3);
Anonymous functions are simple objects
No properties
Just an evaluation method, “feval” (that may take extra arguments)
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Functions as objects
For calculations needing internal storage, there is the function block, e.g.
% Lorenz-63 model
function out = dudt(t,u)
si = 10; rh = 28; be = 8/3;
out = zeros(3,1);
out(1) = si*( u(2)-u(1) );
out(2) = u(1)*( rh-u(3) )-u(2);
out(3) = u(1)*u(2)-be*u(3);
end
Think of function blocks as objects as well:
Properties (i.e. variables) can be defined within the block
They also have an evaluation method: “feval”
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Problems with scope
Problem: The properties/variables in a function block only exist whenthe function (or one of its subfunctions) has control
1 Calling “feval” on a function passes control to it
2 Returning a value passes control back to whatever called “feval”
3 Without control, the function block object falls out of scope, and itsproperties no longer can be reached
Persistent properties/variables are retained in memory for subsequentfunction calls, but are invisible outside the black-box routine
Global properties/variables are given maximum scope and can be seenanywhere in the MATLAB root. Not a good practice in general. Can bechanged inadvertantly, or cause a name conflict with properties/variablesoutside the function, including those in the black-box!
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Expanding the scope of a function
Solution: Expand the scope of the function to outside the black-box
Make it an object in scope outside the black-box routine
Define an evaluation method so black-box routines still canmanipulate its properties
Include properties which store iterations of the black-box routine
Black-box routine
Function
Black-box routine
Wrapper object
(Properties) Function →
→ Write a MATLAB classdef file7 defining “wrapper objects”,properties, evaluation method, and overload the desired built-in routines
wrapped_rhs = wrapper(@Lorenz63); % Wrap function with storage
[t,y] = ode45(wrapped_rhs,tspan,y0); % Pass wrapper to black-box
7RHS wrapper for MATLAB ODE solvers available on SWIG website
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Using a wrapped function handle"model" acts like a function handle with storage
odelib.rhswrap handlePackage: odelib
Properties:h_rhs: @odelib.Lorenz63
t_backup: []y_backup: []
Attempt to integrate "model" with an ode solver...
Unexpected error halts the integration of Lorenz63MException
Properties:identifier: ’Lorenz63:error’
message: ’Oops! Output lost?’cause: 0x1 cellstack: [6x1 struct]
"model.t_backup" & "model.u_backup" now hold resultsodelib.rhswrap handlePackage: odelib
Properties:h_rhs: @odelib.Lorenz63
t_backup: [621x1 double]y_backup: [621x3 double]
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Table of Contents
1 Graphical objects and control
2 Using properties to control graphics
3 Built-in functions and control
4 Outsourcing slow computation to C/C++Developing in MATLAB ↔ Executing in C/C++Intentions and prerequisitesGeneral workflow in C/C++ ACG
5 Organizing utility libraries
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Developing in MATLAB ↔ Executing in C/C++
Advantages of MATLAB1 Simple, high-level syntax2 Development environment3 Vectorized memory management4 Comprehensive graphics library5 Code optimization reporting6 HTML/LaTeX results compiler7 Support (MathWorks
docs/demos,MatlabCentral)
Disadvantages of MATLAB1 Slow for large-scale applications2 Hides many compiling/
computation details3 No 0 index4 Convoluted handle graphics system5 Little integration with open source
projects6 Commercial product
Speed-up Solution: Automated C/C++ code generation (ACG)
Outsource intensive computations
Deploy to non-MATLAB systems
350+ MATLAB toolbox functions adapted for C/C++ ACG
Testing and development remains in MATLAB environment
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Intentions and prerequisites
Intentions:
Make sure all functions called in the MATLAB code are supportedfor code generation8
Code generation primarily is used for computation. Functions whichmake use of handle graphics may not translate.
Prerequisites:
MATLAB
MATLAB Coder
A supported C compiler (MATLAB provides one, though qualifies itis inefficient)
Tutorials available: Step-by-step instructions for command lineimplementation9
8See http:
//www.mathworks.com/help/releases/R2012a/toolbox/eml/ug/bq1h2z8-12.html
for list9Step-by-step instructions also at http://www.mathworks.com/help/releases/
R2012a/toolbox/coder/gs/bsc7jt3.html#bsc7zyq-2
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
General workflow in C/C++ ACG10
1 Eliminate unsupported constructs from the MATLAB function
Placing %#codegen below function declaration tells the MATLAB codeanalyzer (green/orange/red square in upper right of compiler) to checkfor translation conflicts, e.g. cell array indexing
2 The codegen function will identify other mistranslations at runtime
If automated translation will succeed, codegen returns a .mex functionfor sample executionOtherwise, codegen generates an error reportC uses static typing, so must specify class and size of all function inputs
3 Generate standalone C library using codegen
Add -config:lib to generate C library for the translated functionA .c-file with the same name as the translated MATLAB file containsthe highest level functionInclude the library in intended C program and call as desiredBest practices: use -report to generate hyperlink to debugging report
10Good demonstration video at http://www.mathworks.com/videos/
generating-c-code-from-matlab-code-68964.html
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Table of Contents
1 Graphical objects and control
2 Using properties to control graphics
3 Built-in functions and control
4 Outsourcing slow computation to C/C++
5 Organizing utility librariesThe “+[library name]” prefixExample
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
The “+[library name]” prefix
For protecting/sharing collections of related/interdependent functions:
Similar utilites, functions with subfunctions, or combinations of each
Keeps dependencies supported when sharing functions in the library
Place library directory in the MATLAB path or the current directory;attaching the prefix “library name.” to the front of a function orscript from the library restricts the namespace to the library
In other words, now “plot” and “library name.plot” are two differentfunctions, and “library name.plot” can be called from the currentdirectory or anywhere along the MATLAB path, like the original“plot” function
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Example
1 Suppose one has the formatting utilities (fig.m,png.m) and a plotdemonstration (a typical plot.m) which calls one of theformatting utilities
2 Place the functions in a library directory e.g. “+plotlib”, and addthe library directory to the MATLAB path (or ensure it is a subfolderof the current directory
3 Note that the current directory cannot be the library directory, evenwhen running scripts located in the library directory
4 Open a typical plot.m and make sure it refers to the otherutilities as “library name.fig(...)” or “library name.png(...)”
5 To run the plot demonstration script, press F5 while insidea typical plot.m or type “plotlib.a typical plot.m” into thecommand line and press “Enter”
6 Note that the plots will be saved in the current directory, and not inthe library directory
Graphical objects Controlling graphics Built-in functions Outsourcing to C/C++ Organizing libraries
Enjoy MATLAB
Questions, comments, typos? Feel free to e-mail the author at:
wrosenthal at math.arizona.edu