Malcolm Lidierth – Undocumented Matlab https://undocumentedmatlab.com/blog_old Charting Matlab's unsupported hidden underbelly Tue, 29 Oct 2019 15:26:09 +0000 en-US hourly 1 https://wordpress.org/?v=4.4.1 Solving an mput (FTP) hang problemhttps://undocumentedmatlab.com/blog_old/solving-an-mput-ftp-hang-problem https://undocumentedmatlab.com/blog_old/solving-an-mput-ftp-hang-problem#comments Wed, 19 Aug 2015 20:10:17 +0000 https://undocumentedmatlab.com/?p=5974 Related posts:
  1. More undocumented timing features There are several undocumented ways in Matlab to get CPU and clock data...
  2. Uitable customization report Matlab's uitable can be customized in many different ways. A detailed report explains how. ...
  3. Waiting for asynchronous events The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. ...
  4. uisplittool & uitogglesplittool callbacks Matlab's undocumented uisplittool and uitogglesplittool are powerful toolbar controls - this article explains how to customize their behavior...
]]>
Matlab includes a variety of builtin utility functions that enable easy access to FTP. These functions are basically methods of an FTP object using Matlab’s old class system (for example, the mput function is implemented as mput.m in the %matlabroot%\toolbox\matlab\iofun\@ftp\ folder). These are pretty old files that haven’t changed much in years.

FTPI recently needed to upload files from Matlab onto an FTP server, and discovered that calling mput simply hang Matlab to the point that I needed to kill and restart the Matlab process. The problem was not in the FTP server, since it could be accessed normally using FTP clients such as FileZilla and WinSCP. So it had to be something internal to Matlab. My initial workaround was to create an automation script (using WinSCP in my case) for the file upload. But this kludge is both non-robust as well as slow. A fix to the Matlab problem would be much better.

Some online research yielded others who have complained about similar issues over the years, but I saw no concrete answer. I saw many references online to problems that relate to the combination of passive FTP with Windows 7 / firewall / Java 7, that suggested several fixes (example 1, example 2, example 3, example 4). However, none of them solved the problem: calling mput (or dir etc.) continued to freeze Matlab, forcing either a hard process kill or waiting several minutes for the timeout.

Today, Malcolm Lidierth, author of the Waterloo graphics package, told me that he also saw a similar situation on Mac. Fortunately, Malcolm discovered a much better solution to the problem than my external scripts workaround. It seems that simply setting the Java object underlying Matlab’s FTP object to use passive mode fixes the problem (possibly in addition to the other fixes mentioned above).

This can be done in two manners:

The easiest is to add the following highlighted line in mput.m, on or about line 69 (the exact line may change based on your Matlab release):

...
% Upload this file.
fis = java.io.FileInputStream(fileObject);
h.jobject.enterLocalPassiveMode();  % Use passive modestatus = h.jobject.storeFile(name,fis);
fis.close;
...

This works but has several limitations:

  1. it does not solve the problems of other passive FTP commands such as dir, although they can be solved in a similar manner
  2. it creates a counter-problem when connecting to non-passive FTP servers – users might wish to make this a parameter of the ftp constructor function
  3. and of course it requires changing Matlab’s installation files which is problematic in many aspects, as well as non-portable if you ever use your program on another machine or Matlab release.

Here’s a much simpler, portable and flexible solution: simply set the underlying Java object’s passive mode after connecting to the server (using the ftp constructor function) but before using mput or dir or any other command that uses passive FTP mode:

f = ftp('myftpserver.com',username,password);
cd(f);  sf=struct(f);  sf.jobject.enterLocalPassiveMode();mput(f,filename);
dir(f);
close(f);

Note that we need to connect first, then get the underlying Java reference using the struct hack (since direct access to f.jobject is prevented), then we enter local passive mode, and only then we call mput to upload the file. If we omit the highlighted line in the script above, then mput (and dir etc.) will hang.

This way, we can programmatically control when to use passive mode, and no changes to the Matlab install files is required: our Matlab script should now work on all platforms and Matlab releases.

Note the seemingly unnecessary call to cd(f) – this is done to ensure a valid connection before setting the passive mode. We should ensure to do this before each call to mput/dir etc., since otherwise, if the connection drops for any reason (e.g., timeout or some other disconnection), then the mput/dir command would reconnect without passive mode (causing a hang). By calling cd(f) we ensure that the connection is done and passive mode is re-entered before mput/dir are called.

As an interesting related note, ftp accepts an undocumented set of optional input parameters following its first 3 documented inputs (hostname, username and password). We can pass one or more of the following parameters in P-V (param name, param value) pairs format: System, LenientFutureDates, DefaultDateFormatStr, RecentDateFormatStr, ServerLanguageCode, ServerTimeZoneId, ShortMonthNames. All of these parameters expect string (char) values, except LenientFutureDates that expects a logical value (true/false). All the parameters have a default value of empty. An explanation of these parameters can be found in Apache’s documentation of the FTPClientConfig class (Matlab’s ftp uses a plain Apache FTPClient object, where you can also find an explanation of the enterLocalPassiveMode method that was used above).

Italy visit, Aug 26 – Sep 1, 2015

I will be traveling to north Italy between Aug 26 – Sep 1, 2015. If you happen to be in the area at that time, I will be happy to meet you to discuss how I could bring value to your work. Please email me (altmany at gmail) if you are interested.

Due to my travel, this blog will take a short summer vacation, and will return in early September. Stay tuned!

]]>
https://undocumentedmatlab.com/blog_old/solving-an-mput-ftp-hang-problem/feed 3
Waterloo graphics animation and web deploymenthttps://undocumentedmatlab.com/blog_old/waterloo-graphics-animation-web-deployment https://undocumentedmatlab.com/blog_old/waterloo-graphics-animation-web-deployment#comments Wed, 03 Jul 2013 18:00:38 +0000 https://undocumentedmatlab.com/?p=3944 Related posts:
  1. Waterloo graphics Waterloo is an open-source library that can significantly improve Matlab GUI. ...
  2. Waterloo graphics beta The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...
  3. Waterloo graphics examples Some Matlab usage examples for the open-source Waterloo graphics package. ...
  4. Inactive Control Tooltips & Event Chaining Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....
]]>
Once again I’d like to welcome guest blogger Malcolm Lidierth of King’s College London. Last week Malcolm wrote about integrating the Waterloo graphing library in Matlab figures. Today, Malcolm discusses advanced features in this library.

Readers who are interested in high-quality plotting in Matlab may also be interested in the JFreeChart and MTEX open-source packages. JFreeChart provides chart types that are unavailable in Matlab, while MTEX builds upon existing Matlab plots using sophisticated data analysis and visualization. Unlike JFreeChart, I haven’t mentioned MTEX here before. MTEX is definitely worth a good mention, perhaps I’ll write about it someday. If you are using any other good charting packages for Matlab, please add a comment below.

A feature request received from several of Yair’s readers for the Waterloo graphics project was for fast updating and animation of plots. This week, I’ll describe features supporting this. As those need to be illustrated here on a web page, I’ll also describe Waterloo’s new deploy-to-web feature.

Waterloo animated plot

Waterloo animated plot


Updating Waterloo plots

Recall that Waterloo provides a Matlab OOP class called GXPlot, which wraps the underlying Waterloo plot type and can be retrieved using the getObject() method. For a GXPlot named p, the data can easily be updated from Matlab by passing it a new data array of values:

p.getObject().getXData().setDataBufferData(XData);
p.getObject().getYData().setDataBufferData(YData);

This will be fast enough for most purposes, although the exchange of arrays between Matlab and Java is done by copying the data rather than by reference (a limitation imposed by the Java Native Interface rather than Matlab).

If only a few data points are to be changed at any one time, an alternative approach is available of setting individual data points (referenced by their index, 0 being the first):

p.getObject().getXData().setEntry(index, value);
p.getObject().getYData().setEntry(index, value);

These methods will update the plot p, as well as all other plots that share its underlying data buffer.

All that is then needed is to update the display. This means:

  1. Optionally, checking and rescaling the axes as needed
  2. Calling repaint on the graph or its container

The best way will often be to make the container a listener on the relevant data object (the container houses the axes, so these will then be repainted if the scale changes). For example, for the YData:

% get a reference to the plot's graph container
container = p.getObject().getParentGraph().getGraphContainer();
 
% attach the graph as a listener to the ydata buffer 
dataObject = p.getObject().getYData();
dataObject.addPropertyChangeListener(p.getObject().getParentGraph());

Now any change to the YData object will fire a property change event causing the display to update.

A simple example

Waterloo animated bar plot

Waterloo animated bar plot

f = GXFigure();
set(gcf, 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4], 'Name','TestUpdate1');
 
% Create some data and plot a bar chart
Y = hist(randn(1,100), 50);
 
container = gxgca();
p = bar(container, -1:0.0408:1, Y, 'BarWidth',0.0408, 'Fill','LIGHTCORAL');
container.getView().setAxesBounds(-1,0,2,225);
container.getView().setBackground(kcl.waterloo.defaults.Colors.getColor('WHEAT'));
container.getView().setBackgroundPainted(true);
refresh();
 
% Attach the graph as a listener to the ydata buffer 
p.getObject().getYData().addPropertyChangeListener(p.getObject().getParentGraph());
 
% Now update the ydata in a loop - pausing for 0.1s on each iteration.
% The listener attached above will cause a repaint
for k = 1 : 50
    Y = hist(randn(1,100),50);
    Y = Y + p.getObject().getYData().getRawDataValues().';
    p.getObject().getYData().setDataBufferData(Y);
    pause(0.1);
end

Note that the repaints will be done on the Event Dispatch Thread (EDT). The call to the Matlab pause above causes EDT to be flushed so a full repaint is done for each iteration of the loop. Using a timer, as in the example below, can avoid this and allows the Swing repaint mechanisms to collapse multiple repaint calls into a single rendering operation. This will almost always be faster: use drawnow and pause sparingly with Waterloo code.

Improving speed

Refreshing the display as above requires that

  1. the graph container is repainted together with the axes – using internal axes that are rendered as part of step [2] will speed this up
  2. the graph is repainted including grids and internal axes – speed this up by turning off, or reducing the number of, grid lines. Switch off background painting – the container’s background will suffice (this is the default).
  3. the plot displays are updated – to speed this up:
    • Use objects that are easily translated into a square pixel-grid on screen. e.g. use squares instead of circles in a scatter plot
    • Use solid lines, not dashed or dotted ones
    • Turn off anti-aliasing of the plot

As painting is done on the EDT it will not block the Matlab thread. The time taken to update a plot will be variable, but it typically takes 5-20 msecs.

Fast plot updates

In the beta release, new methods have been added to the plots: plotRedraw() and plotUpdate() both redraw a plot without refreshing the background, grids or axes.

In the default implementation, plotUpdate simply calls plotRedraw: there actions are identical. plotUpdate is intended to be overridden in custom user subclasses to paint only points that have been added to end of a plot since the last update and the logic to do that needs to be added to the plot methods in those subclasses.

This logic can also be synthesized on-the-fly (e.g. in Matlab, as in the example below) by adding NaNs in the data objects – Waterloo ignores these values. In the example below, a timer is used to update the plot.

function update2(thisDelay)
 
    if nargin == 0
        DELAY = 0.01;
    else
        DELAY = thisDelay;
    end
 
    % Set up and create some data
    f = GXFigure();
    set(gcf, 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4], 'Name','TestAnimation');
    x = linspace(-pi*4, pi*4, 50);
    y = cos(x);
 
    % Now  the plot
    gr1 = subplot(f, 1,1, 1);
    p1 = line(gxgca, [], [], 'LineSpec', '-og');
    gr1.getObject().getView().setAxesBounds(-pi*4,-2.5,pi*8,5);
 
    % We'll draw 2 points only in each timer call below (2 points needed for interconnecting line)
    % This plot will therefore show only these points when the normal paint mechanism is
    % used unless all the data are added at the end: which the timer callback below does
    p1.getObject().setXData(x(1:2));
    p1.getObject().setYData(y(1:2)*2);
 
    p1.getObject().getParentGraph().setLeftAxisPainted(false);
    p1.getObject().getParentGraph().setRightAxisPainted(false);
    p1.getObject().getParentGraph().setTopAxisPainted(false);
    p1.getObject().getParentGraph().setBottomAxisPainted(false);
    p1.getObject().getParentGraph().setInnerAxisPainted(true);
    p1.getObject().getParentGraph().setInnerAxisLabelled(true);
 
    p1.getObject().getParentGraph().getGraphContainer().repaint();
    drawnow();
 
    t = timer('ExecutionMode','fixedSpacing', 'Period',DELAY, 'TimerFcn', {@localTimer, p1.getObject(), x, y});
    start(t);
 
    function localTimer(t, EventData, p1, x, y)
        k = get(t,'TasksExecuted');
        if k > numel(x)
            % Finished
            stop(t);
            p1.setXData(x);
            p1.setYData(y*2);
            p1.plotRedraw();
        elseif k > 1
            % Add 2 new data points to the plot
            p1.setXData(x(k-1:k));
            p1.setYData(y(k-1:k)*2);
            p1.plotRedraw();
        end
    end  % localTimer
 
end  % update2

Calls to plotRedraw and plotUpdate are extremely fast, typically 1-2 msecs. Each call to plotRedraw() adds two new data points to the existing plot. The result is the animated plot shown at the very top of this article.

Notes:

  • this example used the same timer callback to update both data and display; it will often be best to do this is separate callbacks – the refresh rates for data update and display animation can then be set independently.
  • readers who need plot animation may find interest in the related Matlab functions comet and comet3, or this week’s POTW multicomet.
  • plot animation in standard Matlab typically relies on the EraseMode property. In the upcoming HG2, this mechanism will no longer work, at least as seen in the HG2 prequel that is available today. So if your code uses any plot animation, you should expect it to break when HG2 is released (2014?), and you will need to convert your code to use HG2’s new animation functionality. Waterloo graphs and animation, being independent Java-based, are not expected to be affected, and will run the same way in both HG1 and HG2.

Deploying graphics to the web

Waterloo enables export of static graphics to a variety of vector and bit-mapped formats (PNG, PDF, SVG etc.) that can be included in web pages. In the beta version, deployment to web is also supported directly, with automatic generation of the graphics files together with accompanying HTML files and optional CSS styling sheets and supporting Javascript. These are available from the Graph Editor, which is activated by double-clicking a graph and selecting the world (Waterloo world icon) button.

Two formats are presently supported:

  • Scalable Vector Graphics (SVG). By default, the generated files provide conversion of the SVG to HTML5 canvas commands when loaded into a browser via the canvg.js JavaScript by Gabe Lerner. Use of canvg provides better cross-browser consistency in the rendering of the graphics, particularly for text. Note that only static graphics are presently supported with SVG.
  • Through the Processing script language for visual arts and processing.js JavaScript.

Processing script output supports animations using a new class developed for Waterloo (PDEGraphics2D), which also supports an AWT/Swing container. The generated script files can be loaded and customized using the Process.app file available at the web site above.

In addition, experimental (and presently quirky) support for generating animated GIFs is included. The animations for this blog were generated using this. Animated GIFs are to be preferred when vector graphics are not required because GIFs

  • are universally and consistently supported in browsers
  • are smaller and less computationally intensive. They therefore consume less power and are environmentally friendlier. Visitors to a website, especially those using battery-powered devices, are likely to stay longer on the site.

For the present, only static graphics are supported through the GUIs, so animations need to be created programmatically. A “record” button will be added to the GUIs in future Waterloo releases.

Users can edit the default settings for deployment using the preferences editor, now available from the Graph Editor using the key (Waterloo key icon) button. For SVG, the options are shown below: allowing a choice of whether SVG is to be embedded in the generated HTML file; whether canvg.js should be used and selection of a styling sheet. Customize the file addresses relative to the target folder for the HTML file or use a URL. The “httpd.py” file here is a Python 2.7 script that will set up a local server and display the HTML file in your system browser – it is needed only if the security rules for your browser prevent the files being loaded directly from the local file system.

Waterloo preferences window

Waterloo preferences window

By default, the deploy tool uses a template index.html file that is embedded in the distribution. You can specify your own instead, although I have not yet added that to the Preferences GUI.

]]>
https://undocumentedmatlab.com/blog_old/waterloo-graphics-animation-web-deployment/feed 12
Waterloo graphics betahttps://undocumentedmatlab.com/blog_old/waterloo-graphics-beta https://undocumentedmatlab.com/blog_old/waterloo-graphics-beta#comments Wed, 26 Jun 2013 18:00:20 +0000 https://undocumentedmatlab.com/?p=3907 Related posts:
  1. Waterloo graphics Waterloo is an open-source library that can significantly improve Matlab GUI. ...
  2. Inactive Control Tooltips & Event Chaining Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....
  3. Matlab and the Event Dispatch Thread (EDT) The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  4. Waterloo graphics examples Some Matlab usage examples for the open-source Waterloo graphics package. ...
]]>
Once again I’d like to welcome guest blogger Malcolm Lidierth of King’s College London. Malcolm has written several articles here, including a couple of articles on his Waterloo graphing library. Today, Malcolm discusses new features in this library, as it matures into an official beta phase.

Waterloo contour plot of Matlab's penny image

Waterloo contour plot of Matlab's penny image

Last year, Yair kindly allowed me space for a couple of guest blogs on the Waterloo graphics open-source project. Waterloo has recently transitioned to a ‘beta’ release status, with several new features – many of them in response to suggestions from readers of this blog. Many thanks to all who made those.

One of the motivations in writing Waterloo was to get better, less pixellated graphs in Matlab. By using Java 2D, the core library is not tied to Matlab. Waterloo graphics can be used wherever there is access to a Java Virtual Machine: R, ScilLab etc. MathWorks obviously feel the need for better graphics too: Yair recently blogged about the next generation Matlab graphics (HG2). The Waterloo beta release provides support for mixing both Waterloo graphs and Matlab HG2 graphs in a single figure (as well as current HG1 graphics of course).

The new features in the Waterloo beta can be summarized as:

  1. Introducing new plot types: contours, bars, polar and area charts
  2. Mouse-selectable regions of interest
  3. Support for fast-plot updates without redrawing the entire graph
  4. Support for web-deployment of the graphs using SVG or Processing and ProcessingJS

Today I will concentrate on [1] and [2], illustrated with some Matlab examples; I will discuss [3] and [4] next week.

Installation of Waterloo in Matlab

For those readers who have not yet installed Waterloo in Matlab, the process is very simple: download the latest zip file and extract it. All the sub-folders in the waterloo folder are needed but only the Waterloo_MATLAB_Library subfolder (not its subfolders) should be added to the Matlab path. Once installed, just type waterloo at the Matlab prompt in each Matlab session.

A Matlab script file that will do it all is available here (Waterloo_installer.m). The script is harmless to run if you already have Waterloo installed, but if not then it will automatically find the latest zip file on SourceForge, download and install it, and then configure the Matlab path appropriately.

Contour plots

I ended my last guest article with an example of work-in-progress: filled contours. The beta release now fully supports these.

Recall from the previous articles that GXFigure creates a Waterloo-compatible Matlab figure window. gxgca() returns a reference to the container for the graph as a Matlab GXGraph object, much as Matlab’s built-in gca returns an axes reference.

Here is Matlab’s Lincoln penny demo in Waterloo:

% Get some pre-defined colors
colors = [kcl.waterloo.defaults.Colors.getColor(0)];
for k = 1 : 17
    colors = horzcat(colors,kcl.waterloo.defaults.Colors.getColor(k));
end
 
f = GXFigure();
set(gcf, 'Name','Filled Contour', 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4])
 
load penny;
ax = subplot(f,1,1,1);
ax.getObject().setAspectRatio(1);
p2 = contourf(ax, flipud(P), 18, 'LineStyle','-', 'LineWidth',0.4);
p2.getObject().setFillClipping(false);
p2.getObject().setFill(colors);
drawnow();

(resulting in the contour plot above)

To transform Abe Lincoln to a logarithmic world, just double-click the graph and select the log transform. The result is shown on the right here:

Transformed Matlab penny image

Transformed Matlab penny image

All plots in Waterloo share a common data model, including contour plots. For a scatter plot, x, y pairs in a set represent the offsets to display a marker e.g. a circle or square that is generally of fixed size. For a contour plot, the marker is the contour line and the values for that incorporate the offsets. The xdata and ydata are added during plotting; while these will normally be zero, this makes it trivial to construct montages of contour plots simply by using non-zero values.

Plainly, this needs some extra work to support the common model: circles for a scatter plot are still painted as fixed diameter circles when the plot is rescaled or transformed but the pixel values for a contour line, bar plot etc will need to be recalculated. To achieve this:

  • the data model incorporates an extra object to do the work
  • such plots implement a new interface – GJTransformUpdateInterface – that specifies a transformUpdate() method that refreshes the pixel-coordinates. End-users will not normally need to concern themselves with this, as transformUpdate method will be called by the listeners as required.

Categorical data

Waterloo always uses numeric data to position markers, bars etc in a plot. However, categorical data can be used to supplement those data. Here is an example using the new bar plot:

Categorized Waterloo bar plot Categorized Waterloo bar plot

Categorized Waterloo bar plots

f = GXFigure();
set(gcf, 'Name','TestBar4', 'Units','normalized', 'Position',[0.1 0.1 0.8 0.8]);
m = {'Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'};
gr1 = subplot(f, 2, 2, 1);
a = bar(gr1, 1:12, 1:12);
for k = 1 : 12
   a.getObject().getDataModel().getXData().setCategory(k, m{k});
end
gr1.getObject().setTitleText('Label using the XData categories');
gr1.getObject().getView().autoScale();

Support for categorical labels on the axes is supported for all plots via the common data model. For bar charts, the extra object associated with the plot also supports adding labels to the bars themselves:

f = GXFigure();
set(gcf, 'Name','Categorized Bars', 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4]);
m = {'Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'};
gr = subplot(f, 1, 1, 1);
c = barh(gr, 1:10, 1:10,'stacked');
c.getObject().setFill([java.awt.Color.yellow, java.awt.Color.blue]);
c.getObject().getDataModel().getExtraObject().setFontForeground([java.awt.Color.BLACK, java.awt.Color.WHITE]);
for k = 1 : 12
   c.getObject().getDataModel().getExtraObject().getLabels().add(k-1, m{k});
end
gr.getObject().getView().autoScale();

Note that the standard method setFill, is used to set the bar colors and as two colors are supplied the data are assumed to contain a pair of multiplexed series. This is common to all plots.

To customize the labels, we need to set a property in the extra object which is retrieved with a call to c.getObject().getDataModel().getExtraObject().

The same principles apply to pie charts:

Labelled Waterloo pie chart

Labelled Waterloo pie chart

f = GXFigure();
set(gcf, 'Name','TestPie1', 'Units','normalized', 'Position',[0.1 0.1 0.8 0.8]);
colors = [kcl.waterloo.defaults.Colors.getColor(0)];
y = ones(1,18)*100/18;
gr = subplot(f, 1, 1, 1);
colors = [kcl.waterloo.defaults.Colors.getColor(1),...
    kcl.waterloo.defaults.Colors.getColor(17),...
    kcl.waterloo.defaults.Colors.getColor(2),...
    kcl.waterloo.defaults.Colors.getColor(16),...
    kcl.waterloo.defaults.Colors.getColor(3),...
    kcl.waterloo.defaults.Colors.getColor(15),...
    kcl.waterloo.defaults.Colors.getColor(4),...
    kcl.waterloo.defaults.Colors.getColor(14)];
c = pie(gr, [10 20 45 42 22 26 42 20], logical([0 0 1]), 'FaceColor',colors);

Polar charts

Polar bar and compass charts are also now supported:

Waterloo polar bar chart (click for details)Waterloo compass chart (click for details)

Waterloo polar bar and compass charts (click for details)

f = GXFigure();
set(gcf, 'Name','TestPie1', 'Units','normalized', 'Position',[0.1 0.1 0.8 0.8]);
load sunspot.dat  % Contains a 2-column vector named sunspot
colors = [kcl.waterloo.defaults.Colors.getColor(0)];
for k = 1 : 17
    colors = horzcat(colors,kcl.waterloo.defaults.Colors.getColor(k));
end
gr1 = subplot(f, 1,2, 1);
a = polarbar(gr1, sunspot(1:48,2), 'FaceColor',colors, 'EdgeWidth',0.5);
 
[a,b] = hist(sunspot(:,2),12);
gr2 = subplot(f, 1,2, 2);
b = polarbar(gr2, a, 'FaceColor',colors);
 
Z = eig(randn(20,20));
a = compass(gr1, real(Z), imag(Z), 'LineColor','r');

Area plots

Area plots are supported through a new plot class and also by having all plots implement a new Java interface. To illustrate, create two line plots:

Waterloo area-fill chart

Waterloo area-fill chart

f = GXFigure();
set(gcf, 'Name','TestAreaFill', 'Units','normalized', 'Position',[0.4 0.1 0.5 0.4]);
x = 0.5 : 0.5 : 10;
y = sin(x);
gr1 = gxgca();
a1 = line(gr1, x, y, 'LineSpec','-ob');
b1 = line(gr1, x, y*2, 'LineSpec','-sg');
gr1.getObject().getView().autoScale();
 
% Filling the area between the two plots requires one extra line and a refresh call to paint the result:
a1.getObject().setAreaFill(b1.getObject());
refresh();

All the work is done in the Java code because plots now implement the GJFillable interface. All that is required is to call the setAreaFill() method on a class implementing GJFillable, specifying another GJFillable as input.

A new java class, GJFill, also implements GJFillable and can be used to fill an area relative to a scalar constant or an arbitrary shape. I have also written a Matlab wrapper class for this (GXFill, see below) but I shall use a Java-based example here.

Whether the fill is made horizontally (from the plot) or vertically (from the axes) can be selected by setting the orientation property of the GJFill instance. This can also be set to arbitrary, in which case we can create a custom fillable area sythesized from java.geom shapes:

Waterloo full area fill chart Waterloo custom area fill chart

Waterloo full (above) & custom (below) area fill charts

f = GXFigure();
set(gcf, 'Name','Constant Fill', 'Units','normalized', 'Position',[0.3 0.3 0.4 0.4]);
x = 0.5 : 0.5 : 10;
y = sin(x);
gr1 = subplot(f, 1, 1, 1);
a1 = line(gxgca, x+1, y+3, 'LineSpec','-sg');
 
% Now create a GJFill instance, using a constant as the reference (1.5 in this case), and use this as this area's fill
v = kcl.waterloo.graphics.plots2D.GJFill(a1.getObject(), 1.5);
a1.getObject().setAreaFill(v);
 
%% Start complex
   % Alternately, we can use an arbitrary fill shape:
   v.setOrientation(javaMethod('valueOf', 'kcl.waterloo.graphics.plots2D.GJFill$ORIENTATION', 'ARBITRARY'));
   a1.getObject().setAreaFill(v);
 
   % Create a shape (which can be complex)
   area = java.awt.geom.Area(javaObject('java.awt.geom.Rectangle2D$Double',1,1,5,5));
   area.add(java.awt.geom.Area(javaObject('java.awt.geom.Rectangle2D$Double',8,1,2,5)));
 
   % Add the shape to the GJFill instance
   v.setArbitraryArea(java.awt.geom.Area(area));
%% End complex
 
% Customize the fill color
v.setAreaPaint(java.awt.Color(0,1,0,0.5));
 
% Manually rescale and refresh the plot
gr1.getObject().getView().setAxesBounds(0,0,12,5);
refresh();

To make this simpler from Matlab, a new Matlab class GXFill is provided. This constructs and adds a fill in a single step:

fill = GXFill(plot_reference, value, orientation);

where value is a scalar or a Java Shape object, and orientation is a string e.g. ‘horizontal’. Note that the coordinates are specified in axes units and they will rescale and be transformed as needed when the axes are changed.

Specifying/selecting ROIs

Finally, regions of interest (ROIs) can be selected both programmatically and with the mouse. One of these can be set as the “current” ROI and that is the one that is mouse selectable: set the current ROI using shift-left mouse drag, set the region and rescale to display only that region using shift-right mouse drag.

To create an ROI that can be dragged and resized, add a GJRoi instance to the graph, e.g. with an existing current ROI selected:

gr = gxgca;
gr = gr.getObject().getView();
gr.add(kcl.waterloo.graphics.GJRoi.createInstance(gr, gr.getCurrentROI()));

Waterloo and Matlab’s Java support

Note: It appears that HG2, like HG1, creates an offscreen bitmap that is then blitted onto a Java Canvas within a Matlab figure. Matlab warns that the JavaFrame property will (no longer may) be discontinued in some future release, but it is my guess that this will not be the case when HG2 is released. A new set of uicontrols may indeed be included using a C-based library like wxWidgets or Qt. However, it seems unlikely that Java support will be dropped completely – too much of Matlab’s GUI uses Java (for example, the new desktop introduced in R2012b is entirely Java-based). So the Waterloo Matlab library should work, even if a switch is needed to using JFrames instead of Matlab figures for output.

For the adventurous, Waterloo graphs can also be deployed using JavaFX via the SwingNode class – but that requires installation of the latest Java 8 (currently in early release status). Noting that Matlab is still (as of R2013a) using Java 6, this may indeed be a big jump (note last week’s article on upgrading Matlab to use Java 7).

Naturally, Waterloo’s graphs and classes can also be used in stand-alone Java applications, entirely outside Matlab, even on a $30 ARM6 Raspberry Pi.

Next week, I will look at methods for animating plots (e.g. using Matlab timers) and deploying vector graphics to web pages using the in-built GUIs.

]]>
https://undocumentedmatlab.com/blog_old/waterloo-graphics-beta/feed 11
Waterloo graphics exampleshttps://undocumentedmatlab.com/blog_old/waterloo-graphics-examples https://undocumentedmatlab.com/blog_old/waterloo-graphics-examples#comments Wed, 05 Dec 2012 18:00:50 +0000 https://undocumentedmatlab.com/?p=3374 Related posts:
  1. Waterloo graphics Waterloo is an open-source library that can significantly improve Matlab GUI. ...
  2. Inactive Control Tooltips & Event Chaining Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....
  3. Matlab and the Event Dispatch Thread (EDT) The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  4. Waterloo graphics beta The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...
]]>
Last week, guest blogger Malcolm Lidierth wrote about the open-source Waterloo graphics package and how it can be used in Matlab. Today, Malcolm continues the discussion of Waterloo with a set of examples in Matlab code.

Note: I highly recommend checking out Malcolm’s other open-source submissions/utilities on the Matlab File Exchange.

 
The Waterloo graphics routines provide three potential APIs for MATLAB-users:

  • A Java API for the core code provides a simple and consistent mechanism for creating plots using the same data model for each of them, from line and scatter through quiver and contour plots.
  • A Groovy API that can be used to call the Java API via some static methods that use Groovy’s dynamic typing mechanisms and so allows the same code to be called with different classes on input from different environments – a cell array from MATLAB for example.
  • A Matlab API that mimics the standard MATLAB graphics routines and variously calls the Java-API and Groovy API as required.

I will concentrate here on the Matlab API, which is likely to be of more interest to the majority of readers. This uses Matlab OOP wrappers for the underlying Java objects and all provide access to them by using the getObject() method on the wrappers, so Matlab and Java code can be easily mixed.

Simple Waterloo plots

To create a Matlab figure that can accept Waterloo graphics call GXFigure instead of figure e.g.

f = GXFigure(10);

creates figure 10 and enables it for Waterloo.

In Matlab, you might use gca to create a figure and a set of axes – for Waterloo use gxgca instead. The graph reference also needs to be provided as input to force Matlab to use the Waterloo plotting methods. So

 scatter(1:10,1:10,'^r')

in Matlab becomes:

scatter(gxgca, 1:10,1:10,'^r')

Here are the outputs:

Simple Matlab plot
Simple Waterloo plot

Simple Matlab and Waterloo plots


Note that gxgca returns gca if the current axes are not Waterloo-enabled (so its use above would have produced a Matlab scatter plot in that case). If there is no current axes object, it creates a Waterloo GXGraph and returns a reference to it (just as gca creates Matlab axes when there are none).

However, Waterloo does not attempt to completely mimic Matlab: the markers above were specified as ‘^r’. A full LineSpec (e.g., ‘-^r’) would produce an error when given to the scatter function in Matlab, but Waterloo does not care – if a property is specified that is inappropriate it will be ignored. That is because the Matlab properties are translated into a set of Java properties that all plots have in common, but not all plots use. Note also, that hold is effectively ‘on’ for Waterloo, markers are filled and grids are drawn by default (but all the defaults are user-editable).

Combining Waterloo plots

Waterloo plots can be added together. To draw a line through a set of scatter points, a line plot is added to it. Similarly, an error bar plot can be added to that. The Waterloo Matlab-API has an errorbar function that does that. As the plots are additive the process can be continued to create a series of such compound plots:

f = GXFigure();
ax = subplot(f,1,1,1);
set(gcf, 'Units', 'normalized', 'Position', [0.1 0.1 0.8 0.8], 'Name', 'TestError');
x = 0.5 : 0.5 : 10;
y = log(x);
a1 = errorbar(ax, x, y, y/3.5, 'LineSpec', '-ob');
errorbar(a1, [], y*2, y/3.5*2,'LineSpec', '-sg');
errorbar(a1, [], y*5, y/3.5*5, 'LineSpec', '-dr');
Y = errorbar(a1, [], y*10, y/3.5*10, 'LineSpec', '-^m');
ax.getObject().getView().autoScale();

Here I have created a GXFigure, used its subplot method to create a graph, plotted the first errorbar series to it and parented the remaining plots from the first. As they share their x-data, that is specified as empty for the last three plots.

Combining Waterloo plots

Combining Waterloo plots

The final line above looks less Matlab-like. For

ax.getObject().getView().autoScale();
  • ax is the Matlab OOP wrapper created by subplot – it’s a GXGraph.
  • ax.getObject() returns the Java Swing container which has a “view” (which is the graph)
  • ax.getObject().getView() returns the graph

ax.getObject().getView().autoScale() just causes the graph to be auto-scaled to fit in all the graphics. The axes can be moved, expanded and shrunk using the mouse and double-clicking displays a GUI editor as shown last week. Clicking on a plot causes the plot to become the current Waterloo graphic object, which can then be accessed with gxgco instead of gco (just as gxgca was used in place of gca).

Combining Matlab and Waterloo sub-plots

I have shown only single-axes plots till now. The subplot function can, as in Matlab, create multiple axes and these can be used to mix Waterloo and Matlab graphics in a single figure as here (upper-left and lower-right are Matlab):

Mixing Matlab and Waterloo subplots

Mixing Matlab and Waterloo subplots

Some additional examples

Here then are a few more plot examples:

f = GXFigure();
set(f.Parent, 'Units', 'normalized', 'Position', [.2 .2 .6 .6], 'Name', 'TestQuiver');
[X,Y] = meshgrid(-2:.2:2);
Z = X.*exp(-X.^2 - Y.^2);
[DX,DY] = gradient(Z,.2,.2);
ax = subplot(gxgcf,1,1,1);
q1 = quiver(ax,X,Y,DX,DY, 0.9);

Waterloo quiver plot

Waterloo quiver plot

f = GXFigure();
set(gcf, 'Units', 'normalized', 'Position', [0.1 0.1 0.8 0.8], 'Name', 'TestStairs');
x = linspace(-2*pi,2*pi,40);
y = sin(x);
ax = subplot(f, 1, 2, 1);
a1 = stairs(gxgca, x, y, 'LineColor', 'r');
b1 = stairs(gxgca, x, y*2,'LineColor', 'g');
c1 = stairs(gxgca, x, y*5,'LineColor', 'm');
d1 = stairs(gxgca, x, y*10,'LineColor', 'b');

Waterloo stairs plot

Waterloo stairs plot

load penny;
f = GXFigure();
ax = subplot(f,1,1,1);
ax.getObject().setAspectRatio(1);  % This sets the aspect ratio of the view in the container
p2 = contour(ax, flipud(P), 30);

Waterloo contour plot

Waterloo contour plot

I have added labels and titles here using the GUI editor – they can of course also be set programmatically.

Future work

Waterloo is far from finished and more plot types are being added. Here is a taster of a filled contour plot which will be available in the next update (see the development version GIT repository):

f = GXFigure();
set(gcf, 'Name', 'TestContour', 'Units', 'normalized', 'Position', [0.2 0.2 0.7 0.5])
ax = subplot(f,1,1,1);
ax.getObject().setAspectRatio(1);
p1 = contourf(ax, peaks(100), 20);
p1.getObject().setAlpha(0.3);

Waterloo filled contour plot

Waterloo filled contour plot

If you have any comments or feedback on Waterloo, please feel free to join its open-source development effort, or simply leave a comment below.

]]>
https://undocumentedmatlab.com/blog_old/waterloo-graphics-examples/feed 48
Waterloo graphicshttps://undocumentedmatlab.com/blog_old/waterloo-graphics https://undocumentedmatlab.com/blog_old/waterloo-graphics#comments Wed, 28 Nov 2012 18:00:35 +0000 https://undocumentedmatlab.com/?p=3361 Related posts:
  1. Waterloo graphics examples Some Matlab usage examples for the open-source Waterloo graphics package. ...
  2. Inactive Control Tooltips & Event Chaining Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....
  3. Matlab and the Event Dispatch Thread (EDT) The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  4. Waterloo graphics beta The Waterloo graphics library extends Matlab graphics with numerous customizable plots that can be embedded in Matlab figures. ...
]]>
Once again I would like to welcome guest blogger Malcolm Lidierth of King’s College London, who has already written here in the past. Today Malcolm will describe the Waterloo open-source project and its usage in Matlab.

The Waterloo graphics project

One of Matlab’s limitations is the quality of its 2D graphics. Plots are more pixellated and less interactive than some might expect in a modern programming environment.

A recent addition to the open-source Waterloo graphics library addresses this by providing a pure Java library of 2D graphics functions that can easily be integrated in Matlab. An accompanying Matlab library provides support for these objects in Matlab OOP wrappers. While these do not quite provide a drop-in replacement for Matlab graphics code, in most instances they require very few code line changes to try out the library using existing Matlab code. Here is a taster of some of the plots presently supported:

Figure 1: Some Waterloo graphs showing a selection of some of the plots available. The list of available plots will grow in time. Click for details

Figure 1: Some Waterloo graphs showing a selection of some of the plots available. The list of available plots will grow in time. Click for details

Waterloo is a free, open-source project and it draws upon resources from many other open-source resources: notably the JXGraph class that is part of the SwingLabs SwingX project and was originally developed for the “Filthy Rich Clients” book by Chet Haase and Romain Guy. JXGraph formed the basis for some of the core graphics classes in Waterloo.

Main features

Highlights of the project include:

  • Platform-independent, pure Java library callable from any environment that supports a Java Virtual Machine (JVM). So far, I have tested it with Groovy, Java, Matlab, the R statistical environment, Scala and SciLab.
  • High-speed rendering if you activate the appropriate graphics pipeline – e.g. DirectX for Windows and Quartz for Mac.
  • Anti-aliased graphics and text together with full support for transparency supported at color, plot and graph levels.
  • Graphics can be annotated with lines, arrows, text etc that are Java Graphics 2D–based, but also, because the graphs are Swing-based, with other Swing components such as JLabels, JTextFields etc.
  • As Waterloo graphs are also Swing components, they too can be added to other Swing components (a Matlab figure for example) as well as to other graphs, for example to create graphical insets.
  • Multi-layered graphs, with each layer having independent axes.
  • Figure 2: A multi-layered graph. Each plot has its own graph layer with independent axes.

    Figure 2: A multi-layered graph. Each plot has its own graph layer with independent axes.

  • Built-in mouse interactivity and GUIs for interactive plot editing.
  • Figure 3: A plot editor for a single-layered graph. Java programmers might note here the use of a few custom-designed Swing widgets: a dial that subclasses JSlider and supports multiple-turns, and a color chooser that uses standard names for web colors. Click for details

    Figure 3: A plot editor for a single-layered graph. Java programmers might note here the use of a few custom-designed Swing widgets: a dial that subclasses JSlider and supports multiple-turns, and a color chooser that uses standard names for web colors. Click for details

  • Linear and log axes implemented via Java objects that also format the axes labeling etc.: so for a log axis you have a choice of base 10, 2 and e as well as -log10. Polar plotting is partially implemented and will be improved in later releases.
  • User-selectable preference settings with a GUI to change them (and save them across sessions).
  • Waterloo preferences

    Waterloo preferences

  • Export to PDF and SVG files – and also to the clipboard with preservation of vector graphics quality if your platform supports it. In designing the Java Graphics 2D methods, care has been taken to optimize the grouping of graphics objects to facilitate editing in vector-graphics based packages such as Adobe Illustrator and the open-source InkScape editor. Support is included also for bitmap graphics output to both file and clipboard.
  • Graphics can be saved to portable XML files. These use the standard java.util.bean.XMLCoder, which is a built-in feature of all JVMs so the files are fully portable. Full serialization/de-serialization is supported so the full state of the graph when it was saved is restored on reloading. Writing and reading of these files has built-in support for gzip compression and decompression of the XML data stream.
  • An interactive GUI-based “Graph Explorer” that can be run as a stand-alone Java executable to view the generated graphs, or be run from a console session (including from the Matlab desktop; note that until I find a fix, Unix-based platforms will need Matlab R2012a or later for this). You can share XML files with others: they can view and edit them without Matlab.
  • Tested so far on Windows XP/7 (Oracle JRE 6 &anp; 7), Mac OS Snow Leopard (Apple JRE 6 & OpenJDK 7) and Ubuntu Linux 12.10 (IcedTea OpenJDK JRE 6 & 7).

Benefits for Matlab users

For Matlab-users, we can add:

  • Runs “out-of-the-box”. Unzip the distribution and add the Waterloo Matlab Library folder to your path. Running waterloo.m then adds everything needed to the path and sets up the Java dynamic class path for the current Matlab session – so Waterloo is only installed when needed. However, for all JRE 6-based Matlab versions, I would recommend upgrading to the latest JRE 6 release (update 37 at the time of writing): you will get better and faster graphics performance and recent security fixes (including some relevant to the use of XML files as in Waterloo). For best performance on Windows, also edit or create a “java.opts” file to activate DirectX graphics pipeline (then restart Matlab: you cannot alter this setting for the current JVM session). Use: -Dsun.java2d.noddraw=false
  • Integration of the Waterloo and Matlab graphics via Matlab OOP wrappers. You can mix-and-match Waterloo and standard Matlab graphics in a single Matlab figure.
  • Mixed Matlab and Waterloo graphics are treated specially for serialization. Waterloo creates a folder instead of a single file containing [1] a Matlab .fig file, [2] a Waterloo XML file, and [3] a set of image files – one for each Matlab axes object. In Matlab, the folder can be re-loaded and both Matlab and Waterloo graphics will be fully de-serialized. Outside of Matlab, e.g. in the Waterloo Graph Explorer, the image files will be used to display Matlab graphs. By default, these images are saved as PNG files but you can install a custom function to generate other formats including SVG (Graph Explorer provides an SVG viewer using Apache Batik).
  • The Graph Explorer embeds a copy of the Groovy Console so users can pass variables between the host workspace and the console and use it to run Groovy scripts from Matlab, R, SciLab etc.
  • Tested variously on Matlab R2008a through R2012b on Mac, Windows and Ubuntu Linux. Although the Matlab OOP uses R2008+ classes, the base Java library could probably be invoked directly from earlier Matlab versions.
  • Ability to attach Matlab callbacks to the underlying Java objects. That includes property change callbacks for data objects, individual plots and graphs and for their Swing containers.

Sample Matlab usage

I will finish with a simple example of mixing Matlab and Waterloo graphics:

% Create some data
t = 0 : .035 : 2*pi; 
[x,y] = pol2cart(t, sin(2*t).*cos(2*t));
 
% Now do the plotting
hFig = GXFigure(); % Create Waterloo-enabled Matlab figure 
ax1 = subplot(1,  2, 1); % Create Matlab axes
ax2 = subplot(hFig, 1, 2, 2); % Create Waterloo "axes"
scatter(ax1, x, y); % Matlab scatter plot
scatter(ax2, x, y); % Waterloo scatter plot
 
set(gcf, 'Units', 'normalized', 'Position', [0.1 0.1 0.8 0.8]);

Here is the output:

Figure 5: Mixed Matlab and Waterloo graphics in a single Matlab figure. Click for details

Figure 5: Mixed Matlab and Waterloo graphics in a single Matlab figure. Click for details

Next week, I will give more Matlab code examples.

]]>
https://undocumentedmatlab.com/blog_old/waterloo-graphics/feed 39
Using Groovy in Matlabhttps://undocumentedmatlab.com/blog_old/using-groovy-in-matlab https://undocumentedmatlab.com/blog_old/using-groovy-in-matlab#comments Wed, 04 Jul 2012 19:14:02 +0000 https://undocumentedmatlab.com/?p=2988 Related posts:
  1. GUI automation utilities This article explains a couple of Matlab utilities that use Java's Robot class to programmatically control mouse and keyboard actions...
  2. JBoost – Integrating an external Java library in Matlab This article shows how an external Java library can be integrated in Matlab...
  3. Controlling callback re-entrancy Callback reentrancy is a major problem for frequently-fired events. Luckily, it can easily be solved....
  4. Waterloo graphics Waterloo is an open-source library that can significantly improve Matlab GUI. ...
]]>
Once again I would like to welcome guest blogger Malcolm Lidierth of King’s College London, who has already written here in the past. Today Malcolm will explain the basics of using Groovy code within Matlab.

Readers of this blog are likely to be familiar with calling Java from within Matlab code and/or writing custom Java code for Matlab use. But, Java is only one of many programming languages that can use the Java Virtual Machine. Here, I’d like to draw Matlab-users’ attention to another: Groovy.

Groovy logo Groovy is a superset of Java that compiles to Java byte-code and seamlessly integrates with existing Java code. So seamlessly, in fact, that you can mix-and-match Java and Groovy syntax in a single file or method. This means that you can call Groovy classes from Matlab just as though they were Java classes: Matlab will see no difference.

Most IDEs support Groovy and include the necessary files – IntelliJ seems particularly good for Groovy development. Groovy is also available separately at http://groovy.codehaus.org/Download. Use Groovy 1.8.6 or earlier, not the latest 2.0 version (* see below).

All that is needed to run Groovy in Matlab is to include its jar files on your Matlab javaclasspath, by using Matlab’s javaaddpath function to add to the dynamic classpath, or by adding the jar locations to the classpath.txt file (the static classpath, which is generally better).

To illustrate a few of its features, below is a rough-and-ready static method in Groovy to return a factorial:

package Examples
class StaticLib {
   static factorial(n){
      def fact=1.0
      for (def k=1; k< =n; k++)
         fact*=k
      return fact
   }
}

Java programmers will note there are no public keywords: in Groovy public is the default. Next the method declaration has no return type. Neither does the input n. In Groovy, typing is optional. This is exploited on the next line, where fact is declared using the def keyword. Groovy will determine its type at runtime much as Matlab does for variables. The same is true for the loop control variable k.

To run the code at the Matlab command prompt, use commands as you would for Java e.g:

>> import Examples.StaticLib
>> StaticLib.factorial(40)
>> StaticLib.factorial(int64(40))
>> StaticLib.factorial(java.math.BigInteger(40))

all produce:

ans =
815915283247897734345611269596115894272000000000.0

This is an exact, and correct, result because Groovy instantiated fact as a java.math.BigDecimal when it was initialized with a floating-point value. Note also, that Groovy’s dynamic typing meant only one method was needed– not one for every possible class of input. With Groovy, you need to write much less code. (Caution: running this code with very large n will work, but slowly, and potentially take up all available memory to store the result).

The small typing change below makes a substantial difference to the code’s operation:

package Examples
   class NewLib {
      def factorial = {n ->
      def fact = 1.0
      for (def k = 1; k < = n; k++)
         fact *= k
      return fact
   }
}

Here, factorial is a property, not a method, of the class and its contents are the code – in Groovy this is a closure (in Matlab it would be called an anonymous function).

Create an instance of the NewLib class in Matlab, call the get method on the factorial property and run the code in Matlab as follows:

>> myObj=Examples.NewLib();
>> func=myObj.getFactorial();
>> func.call(40)
ans =
815915283247897734345611269596115894272000000000.0

Using Groovy saved a lot of work: there was no need to write a no argument constructor or a getFactorial() method. Groovy did that automatically.

Here is another code snippet where Groovy’s dynamic typing makes it look much more like Matlab than Java:

for (obj in props) {
   switch (obj.key) {case "Alpha":
      case "EdgeColor":
      case "LineColor":
      case "XData":
      case "YData":
      case "ZData":
      plot.("set" + obj.key)(props.(obj.key))
      break}
}

props is a LinkedHashMap. We start by running through each of the entries in this map in a loop using:

for (obj in props)

Each entry is assigned to obj in turn. Again, we let Groovy determine the class of obj dynamically – it will be of class java.util.LinkedHashMap$Entry, but we do not need to worry about that detail.

For each entry we retrieve the key and use that as the variable for the switch block. In this case, the keys are all strings and, in Groovy, strings can be used in case statements (Java 7 would be needed for that if the code were written in Java; note that Java 7 is still not integrated in Matlab as of this date).

Within the switch block, the code invokes a setter on an object called plot. Rather than write separate lines for each possible property in the key list, one line is enough:

plot.("set" + obj.key)(props.(obj.key))

The key string is pre-pended with “set” and the corresponding method is invoked passing the value from the LinkedHashMap entry as input – so a particular iteration of the loop, this might equate for example to plot.setAlpha(0.5)

For a Matlab programmer who is put off from delving into Java because of the tedious boiler-plate code it requires, Groovy may be an attractive alternative. Groovy also has many powerful features for handling regular expressions, a set of builder classes (for example a thread-safe SwingBuilder class), writing domain specific languages and for meta-object programming including run-time injection of new methods. There is also a growing set of Groovy plugin modules.

Not all Java programmers like Groovy. The dynamic features inevitably create run-time overheads and mean that type-mismatches that would be detected at compile-time in Java may produce run-time exceptions with Groovy, but Groovy 2.0 addresses some of these issues by introducing new compiler annotations. My own use of it has been limited, partly because of these issues: I have used it to create a static library to link Matlab, R, SciLab etc to a graphics package written in Java. The dynamic features of Groovy have been useful there to reduce the work involved.


* Note: Groovy 2.0 was released 28.06.2012. Initial experiments suggest it does not work within Matlab, perhaps because of version clashes with jars on the Matlab static class path.

—————————-

Note: in 21-23 August 2012, I (Yair) will present advanced Matlab training courses in Geneva, Switzerland. The planned topics are:

Anyone interested please email me (altmany at gmail dot com) for more details.

]]>
https://undocumentedmatlab.com/blog_old/using-groovy-in-matlab/feed 8
Controlling callback re-entrancyhttps://undocumentedmatlab.com/blog_old/controlling-callback-re-entrancy https://undocumentedmatlab.com/blog_old/controlling-callback-re-entrancy#comments Wed, 10 Aug 2011 18:00:57 +0000 https://undocumentedmatlab.com/?p=2403 Related posts:
  1. Matlab-Java interface using a static control The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....
  2. copyobj behavior change in HG2 the behavior of Matlab's copyobj function changed in R2014b (HG2), and callbacks are no longer copied. ...
  3. Matlab and the Event Dispatch Thread (EDT) The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....
  4. Advanced JIDE Property Grids JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks...
]]>
I’d like to welcome guest blogger Malcolm Lidierth of King’s College London. Malcolm is well known in the Matlab-Java community for his jcontrol utility. Some months ago, I mentioned his work on another File Exchange contribution, MUtilities when I discussed transparent Matlab figure windows. Today, Malcolm discusses one of his lesser-known but extremely important isMultipleCall utility.

Every now and again, a very simple bit of code turns out to be more useful than the author initially imagined. Something I have repeatedly used is the isMultipleCall function which I posted to MATLAB Central’s File Exchange a year or so ago.

The isMultipleCall function uses fully-documented pure-MATLAB to extend the control that can be achieved over callbacks.

Here was the problem: I had a modular system built in MATLAB which allowed third-party developers to add their own plugins. I wanted a mechanism to force the dismissal (“bail-out”) of a callback even when the Interruptible property of the parent object was set to ‘on’. Such callback re-entrancy issues are common for rapidly-firing events, and debugging and fixing them is usually not easy.

The callback’s dismissal code would need to be fast because it might be called many dozens of times, e.g. in a WindowButtonMotion callback. An obvious approach was to check the function call stack using MATLAB’s dbstack function. Although, at first, this seemed likely to be too slow, profiling showed it was not – taking < 40µsec per call – and within a WindowButtonMotion callback in a real GUI, I could not perceive any slowing of the code.

Here is the function:

function flag=isMultipleCall()
  flag = false; 
  % Get the stack
  s = dbstack();
  if numel(s)< =2
    % Stack too short for a multiple call
    return
  end
 
  % How many calls to the calling function are in the stack?
  names = {s(:).name};
  TF = strcmp(s(2).name,names);
  count = sum(TF);
  if count>1
    % More than 1
    flag = true; 
  end
end

With isMultipleCall invoked from another function (see note below), dbstack will return a structure with a minimum of 2 elements – the first relating to isMultipleCall itself and the second to the calling function. So with numel(s) <= 2, there can be no multiple calls and we can return false immediately thus saving time in doing any further testing. For numel(s) > 2 we simply check to see whether the calling functions referenced in s(2) appears anywhere else on the stack. If it does, then we return true; otherwise false.

Then, in our callback code we simply use:

if isMultipleCall();  return;  end

If this line is placed first in the callback function code, it essentially mimics the behavior that you might expect after setting the Interruptible property of the event firing object to ‘off’. Adding a drawnow() at the end of the callback will ensure that any waiting callbacks in the queue are dismissed:

function MyCallback(hObj, EventData)
  % Quick bail-out if callback code is called before another has ended
  if isMultipleCall();  return;  end
 
  ...  % do some actual callback work here
  drawnow();
end

There are several ways in which isMultipleCall can extend the standard MALAB functionality. First, by moving isMultipleCall reference from the first line of the callback we can create both an interruptible and an uninteruptible code block, e.g.

function MyCallback(hObj, EventData)
 
  %Code Block 1
  ...
 
  if isMultipleCall();  return;  end
 
  %Code Block 2
  ...
 
  drawnow();
end

Second, as isMultipleCall controls the callbacks – not the objects that trigger them – we can individually control the callbacks of objects which fire multiple events. That is particularly useful with Java components, which gives a third extension – isMultipleCall can be used in any function: not just the callbacks of standard MATLAB components, but also of Java or COM components.

Finally, as the callback, not the object is being controlled, we can control a callback that may be shared between multiple objects e.g. a menu component and a toolbar button.

Not bad for 13 lines of code.

Note: isMultipleCall must be called from a function, not from a string in the callback property.

Do you have any other favorite mechanism for controlling callback re-entrancy? If so, please post a comment.

]]>
https://undocumentedmatlab.com/blog_old/controlling-callback-re-entrancy/feed 16
Transparent Matlab figure windowhttps://undocumentedmatlab.com/blog_old/transparent-matlab-figure-window https://undocumentedmatlab.com/blog_old/transparent-matlab-figure-window#comments Wed, 13 Apr 2011 23:22:38 +0000 https://undocumentedmatlab.com/?p=2246 Related posts:
  1. Detecting window focus events Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....
  2. Enable/disable entire figure window Disabling/enabling an entire figure window is impossible with pure Matlab, but is very simple using the underlying Java. This article explains how....
  3. Minimize/maximize figure window Matlab figure windows can easily be maximized, minimized and restored using a bit of undocumented magic powder...
  4. Setting status-bar text The Matlab desktop and figure windows have a usable statusbar which can only be set using undocumented methods. This post shows how to set the status-bar text....
]]>
Every now and then, a user asks whether it is possible to make an entire Matlab window transparent (example). This could be used, for example, for window fade-in/fade-out effects. The short answer is that there is no supported way of doing this with pure documented Matlab, but it is trivially easy to achieve using just a bit of Java magic powder (surprise, surprise).

Matlab figure window transparency

Following an idea I got from Malcolm Lidierth’s MUtilities submission on the Matlab File Exchange, the solution for setting Matlab figure window transparency is quite simple: Get the figure’s underlying Java window reference handle, as in last week’s article. Then use Java’s setWindowOpacity method to set the window’s transparency value. Actually, setWindowOpacity sets the opacity level, rather than transparency, but they are obviously complementary and I personally find “transparency” to be more easily understandable.

By default, windows are created with an opacity of 1.0 (= not transparent). They can be set to any floating-point value between 0.0-1.0, where an opacity of 0.0 means full transparency, and any value in between means partial transparency (i.e., translucency):

jFigPeer = get(handle(gcf),'JavaFrame');
jWindow = jFigPeer.fFigureClient.getWindow;
com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,0.7)

Semi-transparent (translucent) Matlab figure (click to enlarge)

Semi-transparent (translucent) Matlab figure (click to enlarge)

Similarly, you can set the entire Matlab Desktop’s transparency/opacity value:

jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance.getMainFrame;
com.sun.awt.AWTUtilities.setWindowOpacity(jDesktop, 0.8);

Note that the com.sun.awt.AWTUtilities class also enables other GUI effects that would make a Matlab GUI developer’s mouth to start drooling: shaped windows, per-pixel transparency values, mirroring/reflection, window shadows, gradients etc. Perhaps I’ll explore their adaptation for Matlab figures someday.

Fade-in / fade-out

Window fade-in/fade-out effects can easily be achieved using transparency: Simply invoke the setWindowOpacity method several times, with progressively higher or lower values. This is easily done in a simple blocking loop. For example, to fade-out a window:

for stepIdx = 1 : 5
   newAlpha = 1.0 - 0.2*stepIdx;
   com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,newAlpha);
   jWindow.repaint;
   pause(0.2);  % seconds
end

Gradual window fade-out

Gradual window fade-out

A more general example dynamically computes the opacity step size/duration and also enables non-blocking fade effects using an asynchronous timer:

% Compute the required opacity-setting steps
fadeDuration = 1.5;  % seconds
oldAlpha = com.sun.awt.AWTUtilities.getWindowOpacity(jWindow);
newAlpha = 0.0;
deltaAlpha = newAlpha - oldAlpha;
maxStepAlpha = 0.03;
steps = fix(abs(deltaAlpha) / maxStepAlpha) + 1;
stepAlpha = deltaAlpha / steps;
stepDuration = fadeDuration / (steps-1);
 
% If blocking, do the fade effect immediately
if blockingFlag || steps==1
   for stepIdx = 1 : steps
      newAlpha = oldAlpha + stepAlpha*stepIdx;
      com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,newAlpha);
      jWindow.repaint;
      if stepIdx < steps,  pause(stepDuration);  end
   end
else
   % non-blocking: fade in/out asynchronously using a dedicated timer
   start(timer('ExecutionMode','fixedRate', 'Period',0.1, 'TasksToExecute',steps, ...
               'TimerFcn', {@timerFcn,jWindow,oldAlpha,stepAlpha}));
end
 
% Timer function for non-blocking fade-in/fade-out effect
function timerFcn(hTimer,eventData,jFrame,currentAlpha,stepAlpha)  %#ok<INUSL> eventData
  stepIdx = hTimer.TasksExecuted;
  newAlpha = currentAlpha + stepAlpha*stepIdx;
  com.sun.awt.AWTUtilities.setWindowOpacity(jFrame,newAlpha);
  jFrame.repaint;
  if stepIdx == hTimer.TasksToExecute
      stop(hTimer);
      delete(hTimer);
  end
end  % timerFcn

Of course, you can also fade-in/out to intermediate values such as 0.3 or 0.8. If you fade-out completely (i.e., to a value of 0.0), it might be a good idea to actually close the figure window once it gets the totally-transparent value of 0.0.

I’ve prepared a Matlab utility that contains all these options, including optional blocking/non-blocking fade effects, in my setFigTransparency utility, which is available for download on the Matlab File Exchange. You may also wish to use Malcolm Lidierth’s MUtilities, which also has similar functionalities (plus some other goodies).

Limitations

Setting a figure window’s transparency requires using Java Run-time Engine (JRE) 1.6.0_10 (also called “Java 6 update 10”) or higher. This means that it’s supported on Matlab release 7.9 (R2009b) and higher by default, and on earlier releases using a JRE retrofit.

If you are using an earlier Matlab release, consider a retrofit of JRE 1.6.0_10 or any later version (e.g., the latest available version today is 1.6 update 24). The JRE can be downloaded from here, and you can configure Matlab to use it according to the instructions here. As noted, Matlab R2009b (7.9) and onward, at least on Microsoft Windows, pre-bundle a JRE version that does support transparency/opacity and so do not require a retrofit.

You can check your current Java version in Matlab as follows:

>> version -java
ans =
Java 1.6.0_17-b04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode

Unfortunately, Matlab plot axes cannot be made transparent. If you have any axes in your GUI, the axes area will simply appear as a shaded axes, whose intensity depends on the selected alpha (transparency) value; the contents beneath the window will not be merged in the axes area as it is in the non-axes areas.

Finally, note that com.sun.awt.AWTUtilities is itself an undocumented Java class. It is bundled with the standard Java release since 2008 (1.6.0_10), and yet is not part of the official release because its API has not yet settled. In fact, in the upcoming Java 7 release, which is expected in a few months, and which I expect to be available in Matlab sometime in 2012, the set of transparency/opacity methods have migrated to the fully-documented java.awt.Window class.

Blurred figure window

So here’s a riddle for you: using figure window transparency, can you guess how to make a Matlab figure appear blurred for disabled figures (see the screenshot there)? There are several possible ways to do this – can you find the simplest? The first one to post a comment with a correct answer gets a smiley… My answer will appear in next week’s article.

Upgraded website

Also, did you notice my new website design? It’s supposed to be much more readable (yes – also on Android…). It now also runs on a multi-server cloud, which means more stability and faster response times. Do you like the new design? hate it? I would love to hear your feedback via comment or email.

]]>
https://undocumentedmatlab.com/blog_old/transparent-matlab-figure-window/feed 18