Stop A GUI in a middle of process in MATLAB - matlab

I'm designing a GUI using GUIDE in MATLAB R2014b. My program has a long loop (takes 2~5h to process). I want have a button in my GUI that the user stop the process every time he/she want (The GUI is updating graphs and texts continuously based on result of loops). Something like pressing Control+C not after ending a loop. How can I implement this?
PS.
I don't want MATLAB remove my workspace. The user can continue the process with previous loaded data and workspace by changing some options in GUI.

Here is a trick that should work: Somewhere in the GUI, like in its OpeningFcn for instance, initialize a flag named for example StopNow to false and store it in the handles structure of the GUI. Then in the loop that takes long to execute, put an if statement with a call to return whenever the flag is set to true. That will stop the execution of the loop and you will have access to your data. You can make a pushbutton to change the flag value.
Sample code: I made a simple GUI that starts enumerating digits in a for loop and printing them in a text box. When you press the STOP button, the flag is set to true and the loop stops. If something is unclear please tell me.
function StopGUI
clear
clc
close all
%// Create figure and uielements
handles.fig = figure('Position',[440 500 400 150]);
handles.CalcButton = uicontrol('Style','Pushbutton','Position',[60 70 80 40],'String','Calculate','Callback',#CalculateCallback);
handles.StopButton = uicontrol('Style','Pushbutton','Position',[250 70 80 40],'String','STOP','Callback',#StopCallback);
%// Initialize flag
handles.StopNow = false;
handles.Val1Text = uicontrol('Style','Text','Position',[150 100 60 20],'String','Value 1');
handles.Val1Edit = uicontrol('Style','Edit','Position',[150 70 60 20],'String','');
guidata(handles.fig,handles); %// Save handles structure of GUI. IMPORTANT
function CalculateCallback(~,~)
%// Retrieve elements from handles structure.
handles = guidata(handles.fig);
for k = 1:1000
if handles.StopNow == false
set(handles.Val1Edit,'String',num2str(k));
pause(.5) %// The pause is just so we see the numbers changing in the text box.
else
msgbox('Process stopped');
return
end
end
guidata(handles.fig,handles); %// Save handles structure of GUI.
end
function StopCallback(~,~)
%// Retrieve elements from handles structure.
handles = guidata(handles.fig);
handles.StopNow = true;
guidata(handles.fig,handles); %// Save handles structure of GUI.
end
end
Screenshot after pressing the STOP button:
Hope that helps!

Best solution would be to use separate threads (one for the user interface and one for the processing) maybe using parallel toolbox. Anyhow this would be then quite complex to synchronise both.
So, here is a simple solution that only relies on anonymous functions (to delegate interface refreshing outside the processing block) and on drawnow function (to force the graphical interface to process its messages).
Sample application
The sample application to work with is very basic. It contains:
A settings panel (with only one setting, the number of iterations for the processing block)
A progress bar
A Go/Cancel button
NB: Source code is quite long (about 250 lines, mainly due to gui creation), so I dropped it here.
GUI creation is not important. The most important parts are the processing block, the anonymous functions to instrument the code and the callbacks to react to the GUI events. I will thus detail theses only.
The processing block
Processing block is a simple routine:
function [] = processing(count, instrumentation)
%[
for ki = 1:count,
instrumentation.CheckCancel();
instrumentation.Progress((ki-1)/count);
if (ki > 1), pause(1); end
instrumentation.CheckCancel();
instrumentation.Progress(ki/count);
end
%]
end
The only special thing about it is that it takes an additional instrumentation structure. This structure has two fields that points to two anonymous functions defined by the caller (i.e. the graphical interface). We'll see shortly how.
CheckCancel is a function in charge of raising an error if the user wants to stop the processing.
Progress is a function on which to delegate progression report.
Here is how the anonymous functions are connected to the graphical interface (see doProcessing sub-function in the code):
% Connect instrumentation callbacks with the gui
instrumentation.CheckCancel = #(ratio)onCheckCancel(dlg);
instrumentation.Progress = #(ratio)onProgress(dlg, ratio);
% Perform the processing
processing(settings.NumberOfIterations, instrumentation);
Progress and CheckCancel handlers
Here is the handler defined by the GUI for Progress:
function [] = onProgress(dlg, ratio)
%[
% Update the progress bar value
data = guidata(dlg);
uiprogress(data.handles.pbProgress, ratio);
% Force interface to refresh
drawnow();
%]
end
This is simple, it just updates progressbar control and forces the GUI to refresh (remind that matlab is single-threaded and is currently executing the processing block, so we need to force GUI refreshing).
Here is the handler for CheckCancel:
function [] = onCheckCancel(dlg)
%[
% Force interface to process its events
drawnow();
% Check 'UserData' has not been modified during events processing
guiState = get(dlg, 'UserData');
if (~isempty(guiState) && ....
strcmp(guiState, 'CancelRequested') || strcmp(guiState, 'CloseRequested'))
error('System:OperationCanceledException', 'Operation canceled');
end
%]
end
Again, this is quite simple. We force the GUI to process events (buttons clicks, etc...) and then we read if UserData was modified to some expected value. If so, we raise an exception to stop the processing. Remind again that currently executing code is the processing block.
GUI events handlers
The GUI has only two interesting events. Either the user clicks the close button, either he/she clicks the Go/Cancel button.
NB: Remind that even if matlab is locked in executing the processing block, GUI events are still processed because processing block is calling drawnow from time to time (by the mean of the instrumentation delegates).
Here is the code for the close button:
function [] = onCloseRequest(dlg)
%[
% If already in computation mode
if (~isempty(get(dlg, 'UserData')))
% Just indicate close is requested and leave immediatly
set(dlg, 'UserData', 'CloseRequested');
data = guidata(dlg);
set(data.handles.btnGoCancel, 'Enable', 'off', 'String', 'Cancelling...');
return;
end
% Immediate close
delete(dlg);
%]
end
This is simple, if we are in running mode, we just signal we want to stop, else we close the dialog immediately.
Here is the code for the go/cancel button:
function [] = onGoCancelClick(dlg)
%[
% If already in computation mode
if (~isempty(get(dlg, 'UserData')))
% Just indicate cancel is requested and leave immediatly
set(dlg, 'UserData', 'CancelRequested');
data = guidata(dlg);
set(data.handles.btnGoCancel, 'Enable', 'off', 'String', 'Cancelling...');
return;
end
% Go into computation mode
[settings, err] = tryReadSettings(dlg);
if (~isempty(err))
waitfor(msgbox(err.message, 'Invalid settings', 'Error', 'Modal'));
else
enterComputationMode(dlg);
err = doProcessing(dlg, settings);
leaveComputationMode(dlg, err);
end
%]
end
It's a little longer, anyhow this is the same. If we're in running mode, we just indicate we want to stop; else, the interface is in normal mode, and we start the processing.
Functions tryReadSettings, enterComputationMode and leaveComputationMode are just glue to update controls in the interface and nicely report for errors or cancellation.
Conclusion
We have designed a responsive graphical interface relying only on drawnow and anonymous functions. This is of course just a trick and a better solution would be to use multitasking.
The graphical interface was created here programmatically. Principle is the same if build with GUIDE or with the help of the GUI Layout toolbox.
Instrumentation callbacks can further be improved, for instance, by adding a Log field to report processing details in a textbox or to some back-end similar to Log4Net (with just a message level and message value). Or by adding callback for intermediate results.
Interface can also be improved or modified, for instance why not to run processing whenever a setting is modified (i.e. just stopping any current run and without the need to manually click on a 'Go/Cancel' button each time).
There are a lot of possibilities. Here, just providing some ground application to start with (or not ...).

Related

Moving control out of a loop when user presses a specific key? [duplicate]

This question already has answers here:
Detect Keyboard Input Matlab
(4 answers)
Closed 6 years ago.
I am using an infinite loop in my code.
while 1
% many statements/computation...
...
...
end
I want my control to come out of the loop when a user presses a specific key, say Spacebar.
I've tried the solution given here but no luck. Figure window does not open.
You have two routes you can take.
1) You can take even-driven approach and register KeyPressFcn callback for the current figure. The catch is that Matlab is single threaded*, so as long as your loop continuously executes some code, event will not be handled. A workaround would be to insert either drawnow or pause statements within your loop. That will halt the main thread execution and would process outside events, such as our key press. In the callback you would need to change the state of some flag, e.g. an object property / appdata of some graphics handle, or even a global variable (which I would advise against). You would then be able to query from within the loop and break if you see the flag changing.
function test()
hFig = figure();
setappdata(hFig, 'space_pressed', false);
set(hFig, 'KeyPressFcn', #keyPressedFcn);
while true
A = randn(10000); % doing some stuff
pause(0.01);
flag = getappdata(hFig, 'space_pressed');
if flag
break;
end
fprintf('Still running...\n');
end
fprintf('Finished!\n');
end
function keyPressedFcn(hFig, event)
fprintf('Pressed character: "%s"...\n', event.Character);
if strcmp(event.Character, ' ')
setappdata(hFig, 'space_pressed', true);
end
end
Sample output:
>> test
Still running...
Still running...
Pressed character: "h"...
Still running...
Still running...
Pressed character: " "...
Finished!
2) Second approach would be to poll for CurrentCharacter. Note that it also requires you to halt execution by using pause / drawnow for the character stroke to be processed. A side-effect of this approach is that after a key press the focus moves to command window, and the character also appears there.
function test()
hFig = figure();
set(hFig, 'CurrentCharacter', '^'); % some other character
drawnow();
while true
A = randn(10000); % doing some stuff
pause(0.01);
char = get(hFig, 'CurrentCharacter');
if strcmp(char, ' ')
break;
end
fprintf('Still running...\n');
end
fprintf('Finished!\n');
end
EDIT elaborating on the threading in Matlab:
Matlab GUI components actually run on EDT thread, which is separate to the one where the main execution is happening (unless you create java GUI objects explicitly without using javaObjectEDT, which you should avoid) - this is what allows GUI components to visually react on some actions you take which do not require synchronization with the main execution thread, like visually changing button state when clicking on it. But to actually get the callback to run and change the state of your workspace inside the execution thread, you need to let Matlab synchronize the two threads. This is what pause/drawnow helps to do - it halts whatever you've been doing on the execution thread which allows your GUI callbacks to execute in the meantime. drawnow would clear the whole pending queue before returning execution to your original code block, while pause will potentially only process some of the callbacks until the time runs out. You may observe this if you set pause argument to a tiny fraction of a second and make lots of actions - not all will be processed.
You may notice some slight changes in behavior between different Matlab releases - the two threads seem to become slightly more independent over time. There is surprisingly little official information available on this - most of it is based on experience and various answers scattered across Matlab central, like this and that, and obviously fantastic articles on the UndocumentMatlab, like the one linked above.
Why not something like that:
ended = false
while !ended
if pressed_spacebar
ended = true
If you can't change your loop condition, you can use the break instruction but it's not a good programming practise :)

How to determine the last time a user interacted with the matlab GUI?

In a Matlab function, I would like to know the last time a user interacted with the Matlab GUI. By matlab GUI, I mean basically, a user typing in the command window, or in the editor.
The algorithm I wish to implement is essentially:
If it's been a while, the function will not grab focus, but operate in the background.
If the user has recently interacted, presumably he/she is interested "right now" in the results, and the function will grab focus.
This is a tough one ! Here is a proposition to do what you want with the command window only, based on this undocumented code and persitent variables.
I used two functions: CW_listen and CW_callback. A call to CW_listen (or CW_listen(true)) starts to listen to the command window, while a call to CW_listen(false) stops listening. While listening is on, any action performed on the command window trigs a call toCW_callback.
Here are the two functions:
function CW_listen(b)
% Default value
if ~exist('b', 'var'), b = true; end
% Get the reference handle to the Command Window text area
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
try
cmdWin = jDesktop.getClient('Command Window');
jTextArea = cmdWin.getComponent(0).getViewport.getComponent(0);
catch
commandwindow;
jTextArea = jDesktop.getMainFrame.getFocusOwner;
end
% Instrument the text area's callback
if b
set(jTextArea,'CaretUpdateCallback',#CW_callback);
else
set(jTextArea,'CaretUpdateCallback',[]);
end
and
function CW_callback(varargin)
% Define a persistent variable
persistent last_call;
if isempty(last_call)
last_call = clock;
else
ts = clock;
Dt = etime(ts, last_call);
% Update the status bar
dt = javaMethod('getInstance', 'com.mathworks.mde.desk.MLDesktop');
if dt.hasMainFrame
dt.setStatusText(['Ellapsed time: ' num2str(Dt) 's']);
end
if Dt>5
fprintf('So long !\n');
last_call = ts;
else
% Do nothing
end
end
I also dislayed the ellapsed time in the status bar, it was useful for developping the code and adds a quite cool feature.
You can replace the time in seconds (here 5s) and the fprintf('So long !\n'); by any action of your choice. Be aware that inserting any kind of display outside of this if statement will result in an infinite display loop ...
For the moment I don't see how one could transpose this to the editor, but if you search in Undocumented Matlab you may find how to do it ;)

Showing data on Matlab GUI which is continuously being updated in a separate Matlab function

I have a function in Matlab which is getting continuous sensor values from a hardware. It gives a flag when new values are available and we can update the variables holding these values. Following is a dummy function to mimic what this function is doing.
function example( )
% Example function to describe functionality of NatNetOptiTrack
% Hardware initialization,
% Retriving real time information continuously
for i = 1:100 %in real time this loop runs for ever
data = rand(3,6);
% Send the updated data to gui in each iteration
end
end
i have made a gui using guide as shown in the figure:
So the data to be displayed is a 3x6 matrix with columns corresponding to X Y Z Roll Pitch and Yaw values while rows correspond to Objects.
I want to show the continuously updated values from this function on the gui. Is there a way i can initialize gui inside my example function and update the output value by using the handles inside my loop. I tried copying the gui code inside the example function as a script, it was able to initialize but was not recognizing the handles.
Also i want to show the current values on command window when i press the button.
Thanks
If you launch the GUI and then run the function, you should be able to get the handles to the controls on the GUI provided that you make the GUI figure handle visible and set its tag/name to something appropriate. In GUIDE, open the Property Inspector for the GUI and set the HandleVisibility property to on, and the Tag property to MyGui (or some other name). Then in your example.m file do the following
function example( )
% Example function to describe functionality of NatNetOptiTrack
% get the handle of the GUI
hGui = findobj('Tag','MyGui');
if ~isempty(hGui)
% get the handles to the controls of the GUI
handles = guidata(hGui);
else
handles = [];
end
% Hardware initialization,
% Retriving real time information continuously
for i = 1:100 %in real time this loop runs for ever
data = rand(3,6);
% update the GUI controls
if ~isempty(handles)
% update the controls
% set(handles.yaw,…);
% etc.
end
% make sure that the GUI is refreshed with new content
drawnow();
end
end
An alternative is to copy the example function code into your GUI - the hardware initializations could occur in the _OpeningFcn of your GUI and you could create a (periodic) timer to communicate with the hardware and get the data to display on the GUI.
As for displaying the current data when pressing the GUI button, you can easily do this by writing the contents of the GUI controls to the command line/window with fprintf. You will though need to make your example function interruptible so that the push button can interrupt that continuously running loop. You can do this by either adding a pause call (for a certain number of milliseconds) that gets executed at the end of each iteration of your loop, or just make use of the drawnow call from above (that is why I placed it outside of the if statement - so that it will be called on each iteration of your loop.
Try the above and see what happens!

pass value between two callback function in matlab GUI

I have 2 pushbutton. If i press one infinte loop will be running and if i press other loop must break. please some help in code.
Thanks in advance
Are you using GUIDE or a "programmatic" gui? The following is a little example for a programmatic gui; similar concepts may apply for GUIDE. (I personally like the added flexibility of the programmatic gui route, plus I always end up irrevocably breaking any GUIDE gui's I create...)
Anyway, a few things to note in this example:
use of the gui's figure handle UserData field to store "global" information. This is a way to pass data between callbacks.
the pause statement within the "infinite" loop is needed so that the interrupt from cb_button2 is processed. From Matlab help: "If the Interruptible property of the object whose callback is executing is on , the callback can be interrupted. However, it is interrupted only when it, or a function it triggers, calls drawnow, figure, getframe, pause, or waitfor."
function my_gui(varargin)
mainfig = figure;
out.h_button1 = uicontrol(mainfig,...
'Style','pushbutton',...
'Units','Normalized',...
'Position',[0,0.5,1,0.5],...
'String','Button 1',...
'Callback',#cb_button1);
out.h_button2 = uicontrol(mainfig,...
'Style','pushbutton',...
'Units','Normalized',...
'Position',[0,0,1,0.5],...
'String','Button 2',...
'Callback',#cb_button2);
out.button2_flag = 0; %flag indicating whether button 2 has been pressed yet
set(mainfig,'UserData',out);%store "global" data in mainfig's UserData (for use by callbacks)
function cb_button1(varargin)
out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
while ~out.button2_flag
disp('Aaaahhh, infinite loop! Quick press Button 2!');
out = get(gcbf,'UserData'); %reload "global" data
pause(0.1); %need this so this callback may be interrupted by cb_button2
end
disp('Thanks! I thought that would never end!');
function cb_button2(varargin)
out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
out.button2_flag = 1;
set(gcbf,'UserData',out); %save changes to "global" data

Matlab gui WindowButtonMotionFcn crashes when called too often?

I've set WindowButtonMotionFcn to my callback which plots three plots, with the data depending on mouse position. However this seems to be too much for MATLAB to handle, because after moving my mouse around a bit, the GUI stops responding.
I use this code (copied parts from someone):
set(handles.figure1, 'windowbuttonmotionfcn', #hover_Callback);
function hover_Callback(hObject, handles, eventdata)
inside = false;
pos = get(handles.axes1, 'currentpoint');
xlim = get(handles.axes1, 'XLim');
ylim = get(handles.axes1, 'YLim');
if (pos(1,1) > max(xlim(1), 1) && ...
pos(1,1) < xlim(2) && ...
pos(1,2) > ylim(1) && ...
pos(1,2) < ylim(2))
inside = true;
end
if ~inside
return
end
ix = round(pos(1,1));
iy = round(pos(2,2));
axes(handles.axes2); cla; plot(squeeze(t2(ix,iy,:)), squeeze(d2(ix,iy,:)));
axes(handles.axes3); cla; plot(squeeze(t3(ix,iy,:)), squeeze(d3(ix,iy,:)));
axes(handles.axes4); cla; plot(squeeze(t4(ix,iy,:)), squeeze(d4(ix,iy,:)));
This causes my GUI to stop responding, without error codes. If I then quit it and start it again the whole of MATLAB stops responding. Anyone knows what could be happening and how I can fix this? Maybe I'm somehow clogging my memory?
When a callback is called with high frequency, there is the danger that it will be called again before another call has finished executing (i.e. re-entrancy). With WindowButtonMotionFcn, there's a pretty darn good chance that this will happen.
You can prevent callback re-entrancy by inspecting the function call stack (the output of dbstack) for multiple calls to the responsible callback. A very straightforward, but clever implementation of such a check called isMultipleCall is presented in a post on undocumentedmatlab.com. The idea is to count the number of times the callback function name appears on the stack. Take the actual function directly from undocumentedmatlab.com, but it distills to the following:
function flag=isMultipleCall()
s = dbstack();
% s(1) corresponds to isMultipleCall
if numel(s)<=2, flag=false; return; end
% compare all functions on stack to name of caller
count = sum(strcmp(s(2).name,{s(:).name}));
% is caller re-entrant?
if count>1, flag=true; else flag=false; end
The usage of isMultipleCall is very simple. Put run it at the top of the callback (in this case, hover_Callback), and bail out if it indicates that multiple calls are in progress:
function hover_Callback(hObject, eventdata, handles)
if isMultipleCall(); return; end
...
end
This prevents the callback from executing fully again until previous calls have terminated. Only the check will be run, skipping the intensive graphics object operations (i.e. axes, plot, etc.)
An alternative approach is to use a listener for the WindowButtonMotionEvent:
handles.motion = handle.listener(gcf,'WindowButtonMotionEvent',#hover_callback2);
Then in the callback, check the eventdata.CurrentPoint property instead of currentpoint. Check for re-entrancy as above.
If you are NOT using GUIDE and do not have a handles structure managed by guidata, then call the listener something like motionListener and use setappdata to store the listener. For example,
setappdata(hFigure,'mouseMotion',motionListener);
Just use the known handle of any object in the GUI so the listener persists. You could also use UserData instead of setappdata, or any other way of managing GUI data.
As an aside, note that the axes command is rather slow, and can be avoided by passing the axis handle to plot directly:
plot(handles.axes2, squeeze(t2(ix,iy,:)), squeeze(d2(ix,iy,:)));