Code covered by the BSD License  

Highlights from
Model Replay

image thumbnail
from Model Replay by Ben Spivey
Performs state or parameter estimation of process models using the APMonitor executable.

ModelReplayGUI2(varargin)
function varargout = ModelReplayGUI2(varargin)
%MODELREPLAYGUI2 M-file for ModelReplayGUI2.fig
%
% ModelReplayGUI2 beta, Developed by Benjamin Spivey, 2/3/2009
%
% ----------------------------------------------------------------------- %
%      MODELREPLAYGUI2, by itself, creates a new MODELREPLAYGUI2 or raises the existing
%      singleton*.
%
%      H = MODELREPLAYGUI2 returns the handle to a new MODELREPLAYGUI2 or the handle to
%      the existing singleton*.
%
%      MODELREPLAYGUI2('Property','Value',...) creates a new MODELREPLAYGUI2 using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to ModelReplayGUI2_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      MODELREPLAYGUI2('CALLBACK') and MODELREPLAYGUI2('CALLBACK',hObject,...) call the
%      local function named CALLBACK in MODELREPLAYGUI2.M with the given input
%      arguments.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help ModelReplayGUI2

% Last Modified by GUIDE v2.5 31-Jan-2009 22:26:06
% ----------------------------------------------------------------------- %

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ModelReplayGUI2_OpeningFcn, ...
                   'gui_OutputFcn',  @ModelReplayGUI2_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% ----------------------------------------------------------------------- %

% --- Executes just before ModelReplayGUI2 is made visible.
function ModelReplayGUI2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for ModelReplayGUI2
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% This is the tag that all tab push buttons share.  If you have multiple
% sets of tab push buttons, each group should have unique tag.
group_name = 'tab_group';

% This is a list of the UserData values used to link tab push buttons and
% the components on their linked panels.  To add a new tab panel to the group
%  Add the button using GUIDE
%  Assign the Tag based on the group name - in this case tab_group
%  Give the UserData a unique name - e.g. another_tab_panel
%  Add components to GUIDE for the new panel
%  Give the new components the same UserData as teh tab button
%  Add the new UserData name to the below cell array
%  Modify the get_outputs function so information on the new panel
%  is returned to the calling function.
panel_names = {'settings','variable_plots'};

% tabpanelfcn('makegroups',...) adds new fields to the handles structure,
% one for each panel name and another called 'group_name_all'.  These fields
% are used by the tabpanefcn when tab_group_handler is called.
handles = tabpanelfcn('make_groups',group_name, panel_names, handles, 1);

% Update handles structure
guidata(hObject, handles);

hAboutMenu      =   uimenu(...       % About menu
                        'Parent',hObject,...
                        'HandleVisibility','callback', ...
                        'Label','About', ...
                        'Callback',@About_Callback);
% Since this window blocks MATLAB execution with UIWAIT, it is simplist 
% to make it modal.  Set the window style to 'normal' for debugging.
% set(handles.figure1, 'WindowStyle', 'modal')

% Wait to close the figure in the output function so we can access the
% updated handles structure there.
% UIWAIT makes tabpanel wait for user response (see UIRESUME)
uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = ModelReplayGUI2_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
% varargout{1} = handles.output;

% close the figure
% if ishandle(handles.figure1)
%     delete(handles.figure1);
% end

% ----------------------------------------------------------------------- %
% ----------------------------------------------------------------------- %
%            Functions of buttons in graphical user interface             %
% ----------------------------------------------------------------------- %
% ----------------------------------------------------------------------- %

% --- Executes on button press in tab_group.
function tab_group_Callback(hObject, eventdata, handles)
% hObject    handle to tab_group (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Call the tab_group_handler.  This updates visiblity of components as needed to
% hide the components from the previous tab and show components on this tab.
% This also updates the last_tab field in the handles structure to keep track
% of which panel was hidden.
handles = tabpanelfcn('tab_group_handler',hObject, handles, get(hObject, 'Tag'));

% Update handles structure
guidata(hObject, handles);


% --- Executes on button press in orientation_group.
function orientation_group_Callback(hObject, eventdata, handles)
% hObject    handle to orientation_group (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% deselect other radio buttons in this group
% setdiff extracts a specific entry from a vector.
set(setdiff(handles.orientation_group, hObject), ...
    'Value', 0, ...
    'Enable', 'on')

% deactivate this control
set(hObject,'Enable','inactive')


% --- Executes during object creation, after setting all properties.
function pt_papertype_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pt_papertype (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% On the PC, listboxes typically have a white background.  On unix they
% typically use the system background color.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Error trapping - if a callback failed, the figure will still be there but
% no longer in a UIWAIT.  Make sure the window closes nicely if that is the
% case.
if ~strcmpi(get(hObject,'waitstatus'),'waiting')
    delete(hObject);
    return;
end

% get_outputs updates the output field in the handles structure
% based on the state of various elements in the GUI
handles = get_outputs(handles, 'Cancel');

% Update handles structure
guidata(hObject, handles);

% Use uiresume instead of delete so we can get the updated handles
% structure in the output function.
uiresume(hObject);

function gui_hFigure = local_openfig(name, singleton)
if nargin('openfig') == 3 
    gui_hFigure = openfig(name, singleton, 'auto');
else
    % OPENFIG did not accept 3rd input argument until R13,
    % toggle default figure visible to prevent the figure
    % from showing up too soon.
    gui_OldDefaultVisible = get(0,'defaultFigureVisible');
    set(0,'defaultFigureVisible','off');
    gui_hFigure = openfig(name, singleton);
    set(0,'defaultFigureVisible',gui_OldDefaultVisible);
end

% --- Executes on button press in RunButton.
function RunButton_Callback(hObject, eventdata, handles)
% hObject    handle to RunButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% modelReplay.m
% Parameter Estimation Data Replay
% Summary: Main script for performing parameter estimation with APMonitor on past
% data. User may provide past measured MV values, and code will use APM to
% estimate past parameters.
%
% -- Introductory Comments ---------------------------------------------- %
% 1) Measurements_in.dat and Calculations_out.dat need to be exported into csv format
% but saved as .dat text files.  The last line of text before data should
% be the variable tags in MV(..), SV(..), or FV(..) format. Measurement
% data may be in any decimal format.
% 2) DBS File comments: NLC.DIAGLEVEL must be equal to 1 to produce est.t0, 
% est.meas, and est.dxdt files. DBSREAD = 1, DBSWRITE = 1.
% 3) Files Needed to Run: (model).apm, apmonitor.exe, (model).dbs, Calculations_out.dat,
% Measurements_in.dat, (model).info, cellwrite.m, ModelReplayGUI2.fig,
% tabpanel.fig, tabpanel.m, tabpanelfcn.m
% 4) Troubleshooting - Common Errors: 
%    a) ??? Reference to non-existent field 'colheaders'. This is commonly
%    caused by improper formatting of Measurements_in.dat or
%    Calculations_out.dat files.  Change format of files to .csv and
%    inspect file in excel.
%    b) ??? Error using ==> textscan. Mismatch between file and format string.
%    Occurs sometimes when startrun.txt is modified.
%    Need to delete startrun.txt file and create a new one starting from 1.
% 5) Output Files: output.dat, Calculations_out2.dat

% -- Initial Operations ------------------------------------------------- %
% Specify how many of the most recent run folders to keep. Minimum is one.
keep_folders = str2num(get(handles.keepfolders,'String'));

% Load measurement data 
meas_data = importdata('Measurements_in.dat',',');
meas_tags = strtrim(meas_data.colheaders); % tags should be in the form of MV(..), SV(..), or FV(..)
number_meas = length(meas_data.data);
number_tags = length(meas_tags);

% Calculations_out.xls file information
calc_data = importdata('Calculations_out.dat',',');
calc_tags = strtrim(calc_data.colheaders); % tags should be in the form of MV(..) or SV(..)
number_ctags = length(calc_tags);

% Variable names extracted from the Calculations_out.xls file
temp = strtrim(calc_data.textdata);
temp = temp{1,1};
calc_vars = textscan(temp, '%s', 'delimiter', ',');
calc_vars %TS

% Save initial directory
initial_dir = pwd;

% Obtain the starting run from the user and set the current run
temp = get(handles.startrun,'String');
set(handles.currentrun,'String',temp);
start_run = str2num(temp);
next_run = start_run;
clear temp
% next_run = dlmread('nextrun.txt');

% Find name of the .apm model filename
[handles, model_file] = get_modelname(handles);
dbs_file_initial = strcat(model_file,'.dbs');

% Update the APMonitor NLC settings
[handles, adv_settings] = get_adv_settings(handles);
fid = fopen(dbs_file_initial);

dbs_read = textscan(fid,'%s %s %s %s %s');
tag_column = dbs_read{1};

for i=1:6
    % Identify row of measurement to update in dbs file
    identifier = strcat('NLC.',adv_settings(i).tag);
    matching_row = strmatch(identifier,tag_column,'exact');
    % Update NLC settings in dbs file
    updated_value = num2str(adv_settings(i).value);
    updated_value = {[strcat(updated_value,',')]};
    dbs_read{3}(matching_row) = updated_value;
    dbs_matrix = [dbs_read{1},dbs_read{2},dbs_read{3},dbs_read{4},dbs_read{5}];
end
status = fclose(fid);
cellwrite(dbs_file_initial,dbs_matrix);

% Read the user-chosen plot variables
[handles, plot_vars] = get_plot_vars(handles);
number_plotvars = length(plot_vars);

% Display the .apm model filename on the user interface
handles = display_modelname(handles, model_file);

% Update handles structure
guidata(hObject, handles);

% Progress Bar
position = [25 10 200 10]; % Position of progressbar in pixels.
H = progressbar(position);

fprintf('\n\nModelReplay is running ...\n\n')

% -- Primary Loop ------------------------------------------------------- %
for iter=start_run:number_meas
    % -- Directory and File Management (runs within main directory) ----- %
    % Create new run directory with sequential naming
    temp = get(handles.currentrun,'String');
    next_run = str2num(temp);
    clear temp
    nextrun_count = num2str(next_run);
    folder_name = strcat('run_',nextrun_count);
    if isdir('Run Directory') == 0
        mkdir('Run Directory');
    end
    mkdir('Run Directory',folder_name);
    current_dir = strcat('./Run Directory/',folder_name);
    last_run = next_run - 1;

    % Copy coldstart apmonitor files to new run directory
    files = dir;
    num_contents = length(files);
    for i=1:num_contents
        if isdir(files(i).name) == 0 & ~strcmp(files(i).name,'nextrun.txt')
            copyfile(files(i).name, current_dir);
        end
    end
    
    % Copy output files from last run into new run directory
    if last_run > 0
        % Find name of last run directory
        lastrun_count = num2str(last_run);
        last_folder_name = strcat('run_',lastrun_count);
        last_dir = strcat('./Run Directory/',last_folder_name,'/');
        % Copy files if in mode 5, mhe
        t0_file = strcat(last_dir,'est.t0');
        status = copyfile(t0_file,current_dir);
        meas_file = strcat(last_dir,'est.meas');
        status = copyfile(meas_file,current_dir);
        dxdt_file = strcat(last_dir,'est.dxdt');
        status = copyfile(dxdt_file,current_dir);
        dbs_file = strcat(last_dir,dbs_file_initial);
        status = copyfile(dbs_file,current_dir);
        calc_file = strcat(last_dir,'Calculations_out2.dat');
        status = copyfile(calc_file,current_dir);
    end

    % Delete the oldest run directory
    if next_run > keep_folders
        delete_run = next_run - keep_folders;
        deleterun_count = num2str(delete_run);
        delete_folder = strcat('./Run Directory/','run_',deleterun_count);
        rmdir(delete_folder,'s');
    end

    % -- Run APMonitor with latest measurements (runs in run_i directory) %
    cd(current_dir);
    % Update APM DBS file with latest measurements
    current_meas = meas_data.data(next_run,:);
    fid = fopen(dbs_file_initial);

    dbs_read = textscan(fid,'%s %s %s %s %s');
    tag_column = dbs_read{1};

    for i=1:number_tags
        % Identify row of measurement to update in dbs file
        identifier = strcat(meas_tags(i),'.MEAS');
        matching_row = strmatch(identifier,tag_column,'exact');
        identifier2 = strcat(meas_tags(i),'.NEWVAL');
        matching_row2 = strmatch(identifier2,tag_column,'exact');
        identifier3 = strcat(meas_tags(i),'.LSTVAL');
        matching_row3 = strmatch(identifier3,tag_column,'exact');
        identifier4 = strcat(meas_tags(i),'.NXTVAL');
        matching_row4 = strmatch(identifier4,tag_column,'exact');
        if next_run > 1
            identifier5 = 'NLC.COLDSTART';
            matching_row5 = strmatch(identifier5,tag_column,'exact');
        end
        % Correct meas format to apmonitor format (0.000D+00,)
        current_meas_str = num2str(current_meas(i),'%17.16E');
        len_str = length(current_meas_str);
        temp1 = current_meas_str(1:(len_str-3));
        temp2 = current_meas_str((len_str-1):len_str);
        current_meas_str2 = strcat(temp1,temp2);
        updated_current_meas = strrep(current_meas_str2,'E','D');
        updated_current_meas = {[strcat(updated_current_meas,',')]};
        % Replace old meas with new meas in dbs file
        dbs_read{3}(matching_row) = updated_current_meas;
        dbs_read{3}(matching_row2) = updated_current_meas;
        dbs_read{3}(matching_row3) = updated_current_meas;
        dbs_read{3}(matching_row4) = updated_current_meas;
        if next_run > 1
            dbs_read{3}(matching_row5) = {['0,']};
        end
        dbs_matrix = [dbs_read{1},dbs_read{2},dbs_read{3},dbs_read{4},dbs_read{5}];
    end
    status = fclose(fid);
    cellwrite(dbs_file_initial,dbs_matrix);

    % Run APMonitor
    run_cmd = strcat('apmonitor_',model_file); % combines the command line text into one string (i.e. 'apmonitor l8pcp')
    run_cmd = strrep(run_cmd,'_',' ');
    [status output] = system(run_cmd);
    dlmwrite('output.dat',output,'delimiter','');

    % -- Write output to Calculations_out2.dat file ---------------------- %
    fid = fopen(dbs_file_initial);
    dbs_read = textscan(fid,'%s %s %s %s %s');
    clear tag_column
    tag_column = dbs_read{1};
    for i=1:number_ctags
        % Identify row of calculation to find in dbs file depending if SV or MV
        tag_type_temp = calc_tags(i);
        tag_type = tag_type_temp{:}(1:2);
        if strcmp(tag_type,'SV')
            identifier = strcat(calc_tags(i),'.MODEL');
        elseif strcmp(tag_type,'MV')
            identifier = strcat(calc_tags(i),'.NEWVAL');
        else
            identifier = '';
        end
        meas_identifier = strcat(calc_tags(i),'.MEAS');
        output_matching_row(1) = strmatch(identifier,tag_column,'exact');
        output_matching_row(2) = strmatch(meas_identifier,tag_column,'exact');
        % Extract MODEL from dbs file and remove comma from data
        for j=1:2
            temp = dbs_read{3}(output_matching_row(j));
            temp = sprintf('%s',temp{1}(:));
            len_data = length(temp);
            newval = temp(1:len_data);
            newval_array(j,i) = str2num(newval);
        end
        % Save the NEWVAL for plotted variables
        %  plotvars_indicator = 1 : calc_tags(i) is a plotted variable
        %  plotvars_indicator = 0 : calc_tags(i) is not a plotted variable
        if number_plotvars > 0
            plotvars_index = strmatch(calc_tags(i),plot_vars,'exact');
            plotvars_indicator = length(plotvars_index);
            if plotvars_indicator ~= 0
                plotvars_newval_array(iter,plotvars_index) = newval_array(1,i);
                plotvars_meas_array(iter,plotvars_index) = newval_array(2,i);
                plotvars_ctags_index(1,plotvars_index) = i;
            end
        end
    end
    % Write NEWVAL to Calculations_out2.dat file
    next_run_row = next_run;
    dlmwrite('Calculations_out2.dat',newval_array(1,:), '-append', 'roffset',1,'delimiter', ' ');

    % -- Preparation for next run (runs in main directory ) ------------- %
    % Notify user of percent complete
    percent_comp = next_run/number_meas*100;
    fprintf('*** Percent Complete = %0.3g%% \n\n', percent_comp)

    status = fclose(fid);
    delete('*.exe'); % Delete apmonitor.exe to reduce storage needed
    cd(initial_dir);
    next_run = next_run + 1;
    temp = num2str(next_run);
    set(handles.currentrun,'String',temp);
%     dlmwrite('nextrun.txt',next_run);
    
    % -- Plot variables ------------------------------------------------- %
    plotvars_ctags_index(1,:) %TS
    plotvars_newval_array(:,:)
    for i=1:number_plotvars
        % Plot on GUI
        sphandle = subplot(number_plotvars,1,i,'Parent',handles.EMVPlots);
        plot(plotvars_newval_array(:,i),'--')
        hold on
        plot(plotvars_meas_array(:,i))
        hold off
        
        ylabel_index = plotvars_ctags_index(1,i);
        ylabel_text = strrep(calc_vars{:}(ylabel_index),'_',' ');
        ylabel(ylabel_text)
    end
    
    for i=1:number_plotvars
        % Plot new figure
        figure(i)
        plot(plotvars_newval_array(:,i),'--')
        hold on
        plot(plotvars_meas_array(:,i))
        hold off

        ylabel_index = plotvars_ctags_index(1,i);
        ylabel_text = strrep(calc_vars{:}(ylabel_index),'_',' ');
        ylabel(ylabel_text)
        figure(handles.figure1)
    end      
    
    
    % -- Progress Bar --------------------------------------------------- %
    progressbar(H,(iter - start_run + 1)/(number_meas - start_run + 1));
    drawnow
end
fprintf('ModelReplay has successfully finished execution.\n\n')
fprintf('Results files for each run are stored in Run Directory:\n')
fprintf('*** Calculations_out2.dat: state and parameter results\n')
fprintf('*** output.dat: APMonitor output\n\n')

% --- Executes on button press in DeleteRunFoldersButton.
function DeleteRunFoldersButton_Callback(hObject, eventdata, handles)
% hObject    handle to DeleteRunFoldersButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
disp('DeleteRunFolders is called')

if exist('Run Directory')
    [dstatus, dmessage, dmessageid] = rmdir('Run Directory','s');
    if dstatus == 1
        fprintf('The Run Directory was successfully deleted.')
    else
        fprintf('The Run Directory could not be deleted.\n')
        fprintf('*** A process, such as MATLAB or APMonitor, may have locked files in the Run Directory.\n')
        fprintf('*** You may be able to unlock the files by killing a process or ensuring that a process\n')
        fprintf('*** is not using the Run Directory.')
    end
    fprintf('\n\n')
else
    fprintf('The Run Directory does not exist in the current folder\n\n')
end


function About_Callback(hObject, eventdata, handles)
% hObject    handle to keepfolders (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of keepfolders as text
%        str2double(get(hObject,'String')) returns contents of keepfolders
%        as a double

message{1,:} = 'ModelReplay beta'
message{2,:} = 'Developed by Benjamin Spivey, 2009';
title = 'About'
msgbox(message,title)

% ----------------------------------------------------------------------- %
% ----------------------------------------------------------------------- %
%                       Subroutines used in the m-file                    %
% ----------------------------------------------------------------------- %
% ----------------------------------------------------------------------- %

function [handles, model_file] = get_modelname(handles)
% First check whether the user has entered a model name
model_file=get(handles.modelname,'String');
model_file = strcat(model_file);
% If the user has left the field blank, search for an apm file
if length(model_file) == 0
    model_file = dir('*.apm');
    if length(model_file) > 1
        disp('*** Error: More than one apm file is present in the current directory ***')
        return
    end
    model_file = model_file.name;
    temp = textscan(model_file, '%[^.]');
    temp2 = temp{1};
    model_file = sprintf('%s',temp2{1}(:));
end

function [handles] = display_modelname(handles, model_file)
    set(handles.modelname,'String',model_file);
    
function [handles, adv_settings] = get_adv_settings(handles)
% Retrieve values from GUI text boxes
diaglevel = get(handles.DIAGLEVEL,'String');
diaglevel = strcat(diaglevel);
ev_type = get(handles.EV_TYPE,'String');
ev_type = strcat(ev_type);
max_iter = get(handles.MAX_ITER,'String');
max_iter = strcat(max_iter);
mv_step_hor = get(handles.MV_STEP_HOR,'String');
mv_step_hor = strcat(mv_step_hor);
solver = get(handles.SOLVER,'String');
solver = strcat(solver);
nodes = get(handles.NODES,'String');
nodes = strcat(nodes);
% Populate adv_settings structure
adv_settings(1).tag = 'DIAGLEVEL';
adv_settings(2).tag = 'EV_TYPE';
adv_settings(3).tag = 'MAX_ITER';
adv_settings(4).tag = 'MV_STEP_HOR';
adv_settings(5).tag = 'SOLVER';
adv_settings(6).tag = 'NODES';
adv_settings(1).value = diaglevel;
adv_settings(2).value = ev_type;
adv_settings(3).value = max_iter;
adv_settings(4).value = mv_step_hor;
adv_settings(5).value = solver;
adv_settings(6).value = nodes;

function [handles, plot_vars] = get_plot_vars(handles);
plot_variables = get(handles.plot_variables,'String');
plot_variables = strrep(plot_variables,' ','');
i = 1;
if isempty(plot_variables)
    disp('*** Warning: No plot variables were selected ***')
    plot_vars = null(1,1);
    return
end
while true
   [curvar, plot_variables] = strtok(plot_variables, ',');
   if isempty(curvar),  break;  end
   plot_vars{i,1} = curvar;
   i=i+1;
end
    
function h = progressbar(varargin)
% progressbar: A waitbar that can be embedded in a GUI figure.
% Syntax:
% POSITION = [20 20 200 20]; % Position of progressbar in pixels.
% H = progressbar(POSITION);
% for i = 1:100
% progressbar(H,i/100)
% end
 
if ishandle(varargin{1})
    ax = varargin{1};
    value = varargin{2};
    p = get(ax,'Child');
    x = get(p,'XData');
    x(3:4) = value;
    set(p,'XData',x)
    return
end

pos = varargin{1};
bg_color = 'w';
fg_color = [.4 .6 1];
h = axes('Units','pixels',...
    'Position',pos,...
    'XLim',[0 1],'YLim',[0 1],...
    'XTick',[],'YTick',[],...
    'Color',bg_color,...
    'XColor',bg_color,'YColor',bg_color);
patch([0 0 0 0],[0 1 1 0],fg_color,...
    'Parent',h,...
    'EdgeColor','none',...
    'EraseMode','none');

function startrun_Callback(hObject, eventdata, handles)
% hObject    handle to startrun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of startrun as text
%        str2double(get(hObject,'String')) returns contents of startrun as a double


% --- Executes during object creation, after setting all properties.
function startrun_CreateFcn(hObject, eventdata, handles)
% hObject    handle to startrun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function modelname_Callback(hObject, eventdata, handles)
% hObject    handle to modelname (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of modelname as text
%        str2double(get(hObject,'String')) returns contents of modelname as a double


% --- Executes during object creation, after setting all properties.
function modelname_CreateFcn(hObject, eventdata, handles)
% hObject    handle to modelname (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function keepfolders_Callback(hObject, eventdata, handles)
% hObject    handle to keepfolders (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of keepfolders as text
%        str2double(get(hObject,'String')) returns contents of keepfolders as a double


% --- Executes during object creation, after setting all properties.
function keepfolders_CreateFcn(hObject, eventdata, handles)
% hObject    handle to keepfolders (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in tab_group.
function pushbutton15_Callback(hObject, eventdata, handles)
% hObject    handle to tab_group (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in pushbutton16.
function pushbutton16_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton16 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in frame1.
function frame1_Callback(hObject, eventdata, handles)
% hObject    handle to frame1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in pushbutton19.
function pushbutton19_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton19 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in pushbutton20.
function pushbutton20_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton20 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in DIAGLEVEL1.
function DIAGLEVEL1_Callback(hObject, eventdata, handles)
% hObject    handle to DIAGLEVEL1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DIAGLEVEL1


% --- Executes on button press in DIAGLEVEL2.
function DIAGLEVEL2_Callback(hObject, eventdata, handles)
% hObject    handle to DIAGLEVEL2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DIAGLEVEL2


% --- Executes on button press in DIAGLEVEL3.
function DIAGLEVEL3_Callback(hObject, eventdata, handles)
% hObject    handle to DIAGLEVEL3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DIAGLEVEL3


% --- Executes on button press in DIAGLEVEL4.
function DIAGLEVEL4_Callback(hObject, eventdata, handles)
% hObject    handle to DIAGLEVEL4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DIAGLEVEL4



function MAX_ITER_Callback(hObject, eventdata, handles)
% hObject    handle to MAX_ITER (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of MAX_ITER as text
%        str2double(get(hObject,'String')) returns contents of MAX_ITER as a double


% --- Executes during object creation, after setting all properties.
function MAX_ITER_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MAX_ITER (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function EV_TYPE_Callback(hObject, eventdata, handles)
% hObject    handle to EV_TYPE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of EV_TYPE as text
%        str2double(get(hObject,'String')) returns contents of EV_TYPE as a double


% --- Executes during object creation, after setting all properties.
function EV_TYPE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EV_TYPE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function DIAGLEVEL_Callback(hObject, eventdata, handles)
% hObject    handle to DIAGLEVEL (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of DIAGLEVEL as text
%        str2double(get(hObject,'String')) returns contents of DIAGLEVEL as a double


% --- Executes during object creation, after setting all properties.
function DIAGLEVEL_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DIAGLEVEL (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function MV_STEP_HOR_Callback(hObject, eventdata, handles)
% hObject    handle to MV_STEP_HOR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of MV_STEP_HOR as text
%        str2double(get(hObject,'String')) returns contents of MV_STEP_HOR as a double


% --- Executes during object creation, after setting all properties.
function MV_STEP_HOR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MV_STEP_HOR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function SOLVER_Callback(hObject, eventdata, handles)
% hObject    handle to SOLVER (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of SOLVER as text
%        str2double(get(hObject,'String')) returns contents of SOLVER as a double


% --- Executes during object creation, after setting all properties.
function SOLVER_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SOLVER (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function NODES_Callback(hObject, eventdata, handles)
% hObject    handle to NODES (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of NODES as text
%        str2double(get(hObject,'String')) returns contents of NODES as a double


% --- Executes during object creation, after setting all properties.
function NODES_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NODES (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function plot_variables_Callback(hObject, eventdata, handles)
% hObject    handle to plot_variables (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of plot_variables as text
%        str2double(get(hObject,'String')) returns contents of plot_variables as a double


% --- Executes during object creation, after setting all properties.
function plot_variables_CreateFcn(hObject, eventdata, handles)
% hObject    handle to plot_variables (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


Contact us at files@mathworks.com