function nnpredict(cmd,arg1,arg2,arg3)
%NNPREDICT Neural Network Predictive Controller GUI for Neural Network Controller Toolbox.
%
%  Synopsis
%
%    nnpredict(cmd,arg1,arg2,arg3)
%
%  Warning!!
%
%    This function may be altered or removed in future
%    releases of the Neural Network Toolbox. We recommend
%    you do not write code which calls this function.
%    This function is generally being called from a Simulink block.

% Orlando De Jesus, Martin Hagan, 1-25-00
% Copyright 1992-2002 The MathWorks, Inc.
% $Revision: 1.5 $ $Date: 2002/04/14 21:11:28 $


% CONSTANTS
me = 'Neural Network Predictive Control';

% DEFAULTS
if nargin == 0, cmd = ''; else cmd = lower(cmd); end

% FIND WINDOW IF IT EXISTS
fig = 0;

% 9/3/99 We alow the program to see hidden handles
fig=findall(0,'type','figure','name',me);
if (size(fig,1)==0), fig=0; end

if length(get(fig,'children')) == 0, fig = 0; end

% GET WINDOW DATA IF IT EXISTS
if fig
  H = get(fig,'userdata');
  
  if strcmp(cmd,'')
    if get(H.gcbh_ptr,'userdata')~=arg1
      delete(fig);
      fig=0;
    end
  else
     % ODJ 1-13-00 We check if the field SimulationStatus exist before reading that field
    if isfield(get(H.gcbh_ptr,'userdata'))
       if isfield(get_param(get_param(get(H.gcbh_ptr,'userdata'),'parent'),'objectparameters'),'SimulationStatus')
          SimulationStatus=get_param(get_param(get(H.gcbh_ptr,'userdata'),'parent'),'SimulationStatus');
       else
          SimulationStatus='none';
       end
    else
       SimulationStatus='none';
    end
    if (strcmp(SimulationStatus,'running') | strcmp(SimulationStatus,'paused')) & ~strcmp(cmd,'close')
      set(H.error_messages(1,1),'string','You must stop the simulation to change NN configuration parameters.');
      return;
    end
  end
end

%==================================================================
% Activate the window.
%
% ME() or ME('')
%==================================================================

if strcmp(cmd,'')
  if fig
    figure(fig)
    set(fig,'visible','on')
  else
    nncontrolutil('nnpredict','init',arg1,arg2);
  end

%==================================================================
% Close the window.
%
% ME() or ME('')
%==================================================================

elseif strcmp(cmd,'close') & (fig)
   delete(fig)
   return;

elseif (strcmp(cmd,'apply') | strcmp(cmd,'ok')) & (fig)
  arg1=get(H.gcbh_ptr,'userdata');
  
  a1 = str2num(get(H.N2_edit,'string'));
  if length(a1) == 0, a1=0; end
  if a1<2,
     N2=get_param(arg1,'N2'); 
     present_error(H,H.N2_edit,N2,1, ...
         'Please, correct the cost horizon value (N2)'); 
     return
  else set_param(arg1,'N2',num2str(a1)); end
  
  a1 = str2num(get(H.Nu_edit,'string'));
  if length(a1) == 0, a1=0; end
  if a1<2,
     Nu=get_param(arg1,'Nu'); 
     present_error(H,H.Nu_edit,Nu,1, ...
         'Please, correct the control horizon value (Nu)'); 
     return
  else set_param(arg1,'Nu',num2str(a1)); end
    
  a1 = str2num(get(H.rho_edit,'string'));
  if length(a1) == 0,
     rho=get_param(arg1,'rho'); 
     present_error(H,H.rho_edit,rho,1, ...
         'Please, correct the control weighting factor'); 
     return
  else set_param(arg1,'rho',num2str(a1)); end
    
  a1 = str2num(get(H.alpha_edit,'string'));
  if length(a1) == 0,
     alpha=get_param(arg1,'alpha');
     present_error(H,H.alpha_edit,alpha,1, ...
         'Please, search parameter'); 
     return
  else set_param(arg1,'alpha',num2str(a1)); end
    
  func_index=['csrchgol';'csrchbac';'csrchhyb';'csrchbre';'csrchcha'];
  a1 = get(H.csrchfun_edit,'value');
  if (a1 < 1) | (a1 > 5), 
     csrchfun=get_param(arg1,'csrchfun'); 
     a1=strmatch(csrchfun,func_index);
     set(H.csrchfun_edit,'value',a1);
     present_error(H,H.csrchfun_edit,a1,0, ...
        'Please, correct the minimization function'); 
     return
  else set_param(arg1,'csrchfun',func_index(a1,:)); end
    
  a1 = str2num(get(H.maxiter_edit,'string'));
  if length(a1) == 0, a1=0; end
  if a1<1,
     maxiter=get_param(arg1,'maxiter');
     present_error(H,H.maxiter_edit,maxiter,1, ...
         'Please, correct the number of iterations per sample time'); 
     return
  else set_param(arg1,'maxiter',num2str(a1)); end
    
  if strcmp(cmd,'ok')
     delete(fig)
  else
    set(H.error_messages(1,1),'string',sprintf(' '));
  end
  
%==================================================================
% Execute Training.
%
% ME('training')
%==================================================================

elseif strcmp(cmd,'training') & (fig)
  arg1=get(H.gcbh_ptr,'userdata');
  arg2=get(H.gcb_ptr,'userdata');
  nnident('',arg1,arg2,'nnpredict');

%==================================================================
% Initialize the window.
%
% ME('init')
%==================================================================

elseif strcmp(cmd,'init') & (~fig)

  % 1-13-00 ODJ We check if the system is locked.
  sys_par=arg2;
  sys_par2=arg2;
  while ~isempty(sys_par2)
      sys_par=sys_par2;
      sys_par2=get_param(sys_par,'parent');
  end
  if strcmp('on',get_param(sys_par,'lock'))
      window_en='off';
  else
      window_en='on';
  end

  fig = figure('CloseRequestFcn','nncontrolutil(''nnpredict'',''close'')', ...
   'Interruptible','off', ...
   'BusyAction','cancel', ...
   'HandleVis','Callback', ...
   'Color',[0.8 0.8 0.8], ...
  'MenuBar','none', ...
   'Name',me, ...
   'numbertitle','off', ...
   'IntegerHandle',  'off',...
  'PaperUnits','points', ...
  'Position',[39 26 480 297], ...
  'Tag','Fig4', ...
  'ToolBar','none');
  frame1 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
  'ListboxTop',0, ...
  'Position',[5 64 350 23], ...
  'Style','frame', ...
  'Tag','Frame1');
  frame2 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
  'ListboxTop',0, ...
  'Position',[5 89 164 60], ...
  'Style','frame', ...
  'Tag','Frame2');
  frame3 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
  'ListboxTop',0, ...
  'Position',[171 89 184 60], ...
  'Style','frame', ...
  'Tag','Frame3');
  H.Title_nnpredict = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
  'FontSize',14, ...
  'ListboxTop',0, ...
  'Position',[30 171.75 300 21.75], ...
  'String','Neural Network Predictive Control', ...
  'Style','text', ...
  'Tag','Title_nnpredict');
  frame4 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
  'ListboxTop',0, ...
  'Position',[5 36 350 26], ...
  'Style','frame', ...
  'Tag','Frame4');
  H.Train_NN = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
  'Callback','nncontrolutil(''nnpredict'',''training'');', ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[15 41 90 15], ...
  'String','Plant Identification', ...
  'ToolTipStr','Opens a window where you can develop the neural network plant model.',...
  'Tag','Pushbutton1');
  H.OK_but = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
  'Callback','nncontrolutil(''nnpredict'',''ok'')', ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[125 41 60 15], ...
  'String','OK', ...
   'ToolTipStr','Save the parameters into the neural network controller block and close this window.',...
  'Tag','OK_but');
  H.Cancel_but = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
  'Callback','nncontrolutil(''nnpredict'',''close'')', ...
  'ListboxTop',0, ...
  'Position',[205 41 60 15], ...
  'String','Cancel', ...
   'ToolTipStr','Discard the neural network controller parameters.',...
  'Tag','Pushbutton1');
  H.Apply_but = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
  'Callback','nncontrolutil(''nnpredict'',''apply'')', ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[285 41 60 15], ...
  'String','Apply', ...
   'ToolTipStr','Save the parameters into the neural network controller block.',...
  'Tag','Apply_but');
  H.N2_edit = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[1 1 1], ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[120 130.5 45 15], ...
  'String','', ...
  'Style','edit', ...
   'ToolTipStr','Cost horizon value for the set-point error.',...
  'Tag','N2_edit');
  H.N2_text = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','right', ...
  'ListboxTop',0, ...
  'Position',[10 130.5 100 15], ...
  'String','Cost Horizon (N2)', ...
  'Style','text', ...
   'ToolTipStr','Horizon over which the set-point error is minimized.',...
  'Tag','StaticText2');
  H.Nu_text = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','right', ...
  'ListboxTop',0, ...
  'Position',[10 99 100 15], ...
  'String','Control Horizon (Nu)', ...
  'Style','text', ...
   'ToolTipStr','Horizon over which the deviation in control action is minimized.',...
  'Tag','StaticText2');
  H.Nu_edit = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[1 1 1], ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[120 99 45 15], ...
  'String','2', ...
  'Style','edit', ...
   'ToolTipStr','Horizon over which the deviation in control action is minimized.',...
  'Tag','Nu_edit');
  H.rho_text2 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','right', ...
  'ListboxTop',0, ...
  'Position',[189 130.5 95 15], ...
  'String','Control Weighting Factor (', ...
  'Style','text', ...
   'ToolTipStr','Control weighting factor that multiplies the deviation in control action.',...
  'Tag','StaticText2');
  H.rho_text = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
  'FontName','Symbol', ...
  'FontSize',10, ...
  'ListboxTop',0, ...
  'Position',[284 130.5 7 15], ...
  'String','r', ...
  'Style','text', ...
   'ToolTipStr','Control weighting factor that multiplies the deviation in control action.',...
  'Tag','StaticText2');
  H.rho_text3 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','left', ...
  'ListboxTop',0, ...
  'Position',[291 130.5 4 15], ...
  'String',')', ...
  'Style','text', ...
   'ToolTipStr','Control weighting factor that multiplies the deviation in control action.',...
  'Tag','StaticText2');
  H.rho_edit = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[1 1 1], ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[305 130.5 45 15], ...
  'String','0.03', ...
  'Style','edit', ...
   'ToolTipStr','Control weighting factor that multiplies the deviation in control action.',...
  'Tag','rho_edit');
  H.alpha_text2 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','right', ...
  'ListboxTop',0, ...
  'Position',[189 99 95 15], ...
  'String','Search Parameter (', ...
  'Style','text', ...
   'ToolTipStr','Search parameter to be used in the minimization routine.',...
  'Tag','StaticText2');
  H.alpha_text = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
  'FontName','Symbol', ...
  'FontSize',10, ...
  'ListboxTop',0, ...
  'Position',[284 99 7 15], ...
  'String','a', ...
  'Style','text', ...
   'ToolTipStr','Search parameter to be used in the minimization routine.',...
  'Tag','StaticText2');
  H.alpha_text3 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','left', ...
  'ListboxTop',0, ...
  'Position',[291 99 4 15], ...
  'String',')', ...
  'Style','text', ...
   'ToolTipStr','Search parameter to be used in the minimization routine.',...
  'Tag','StaticText2');
  H.alpha_edit = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[1 1 1], ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[305 99 45 15], ...
  'String','0.001', ...
  'Style','edit', ...
   'ToolTipStr','Search parameter to be used in the minimization routine.',...
  'Tag','EditText1');
  H.csrchfun_edit = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[1 1 1], ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Max',5, ...
  'Position',[107 68.25 58 15], ...
  'String',['csrchgol';'csrchbac';'csrchhyb';'csrchbre';'csrchcha'], ...
  'Style','popupmenu', ...
  'Tag','PopupMenu1', ...
  'Value',1);
  H.csrchfun_text = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','right', ...
  'ListboxTop',0, ...
  'Position',[10 68.25 85 15], ...
  'String','Minimization Routine', ...
  'Style','text', ...
   'ToolTipStr','Line search routine to be used in the optimization algorithm.',...
  'Tag','StaticText3');
  H.maxiter_edit = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[1 1 1], ...
    'Enable',window_en, ...
  'ListboxTop',0, ...
  'Position',[305 68.25 45 15], ...
  'String','2', ...
  'Style','edit', ...
   'ToolTipStr','Maximum number of iterations of the optimization algorithm per sample time.',...
  'Tag','maxiter_edit');
  H.maxiter_text = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
    'Enable',window_en, ...
   'HorizontalAlignment','right', ...
  'ListboxTop',0, ...
  'Position',[185 68.25 110 15], ...
  'String','Iterations Per Sample Time', ...
  'Style','text', ...
   'ToolTipStr','Maximum number of iterations of the optimization algorithm per sample time.',...
   'Tag','StaticText2');
  frame4 = uicontrol('Parent',fig, ...
  'Units','points', ...
  'BackgroundColor',[0.8 0.8 0.8], ...
  'ListboxTop',0, ...
  'Position',[5 12 350 22], ...
  'Style','frame', ...
  'Tag','Frame4');
  H.error_messages(1,1)= uicontrol('Parent',fig, ...
  'Units','points', ...
   'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ...
  'FontWeight','bold', ...
  'ForegroundColor',[0 0 1], ...
  'ListboxTop',0, ...
  'Position',[6 13 348 20], ...
  'Style','text', ...
  'ToolTipStr','Feedback line with important messages for the user.',...
  'Tag','StaticText1');

% We create the menus for the block.
  H.Handles.Menus.File.Top= uimenu('Parent',fig, ...
  'Label','File');
  H.Handles.Menus.File.ImportModel = uimenu('Parent',...
   H.Handles.Menus.File.Top,...
  'Label','Import Network...',...
  'Accelerator','I',...
  'Callback','nncontrolutil(''nnimport'',''init'',gcbf,''nnpredict'',''nnpredict'');',...
    'Enable',window_en, ...
   'Tag','ImportModel');
  H.Handles.Menus.File.Export = uimenu('Parent',H.Handles.Menus.File.Top, ...
   'Label','Export Network...', ...
   'Accelerator','E', ...
   'Callback','nncontrolutil(''nnexport'',''init'',gcbf,''nnpredict'',''nnpredict'')', ...
    'Enable',window_en, ...
   'Tag','ExportMenu');
  H.Handles.Menus.File.Save_NN = uimenu('Parent',...
   H.Handles.Menus.File.Top,...
   'Label','Save',...
   'Separator','on', ...
   'Accelerator','S',...
   'Callback','nncontrolutil(''nnpredict'',''apply'');',...
    'Enable',window_en, ...
   'Tag','ImportModel');
  H.Handles.Menus.File.Save_Exit_NN = uimenu('Parent',...
   H.Handles.Menus.File.Top,...
   'Label','Save and Exit',...
   'Accelerator','A',...
   'Callback','nncontrolutil(''nnpredict'',''ok'');',...
    'Enable',window_en, ...
   'Tag','ImportModel');
  H.Handles.Menus.File.Close = uimenu('Parent',H.Handles.Menus.File.Top, ...
   'Callback','nncontrolutil(''nnpredict'',''close'',gcbf);', ...
   'Separator','on', ...
   'Label','Exit', ...
   'Accelerator','X', ...
   'Tag','CloseMenu');

  H.Handles.Menus.Window.Top = uimenu(fig, 'Label', 'Window', ...
   'Callback', winmenu('callback'), 'Tag', 'winmenu');
  winmenu(fig);  % Initialize the submenu

  H.Handles.Menus.Help.Top = uimenu('Parent',fig, ...
   'Label','Help');
  H.Handles.Menus.Help.Main = uimenu('Parent',H.Handles.Menus.Help.Top, ...
   'Label','Main Help', ...
   'Callback','nncontrolutil(''nnpredicthelp'',''main'');',...
   'Accelerator','H');
  H.Handles.Menus.Help.PlantIdent = uimenu('Parent',H.Handles.Menus.Help.Top, ...
   'Label','Plant Identification...', ...
   'CallBack','nncontrolutil(''nnpredicthelp'',''plant_ident'');');
  H.Handles.Menus.Help.Simulation = uimenu('Parent',H.Handles.Menus.Help.Top, ...
   'Label','Simulation...', ...
   'Separator','on',...
   'CallBack','nncontrolutil(''nnpredicthelp'',''simulation'');');

  H.gcbh_ptr = uicontrol('Parent',fig,'visible','off');
  set(H.gcbh_ptr,'userdata',arg1);
  H.gcb_ptr = uicontrol('Parent',fig,'visible','off');
  set(H.gcb_ptr,'userdata',arg2);
  
  N2=get_param(arg1,'N2'); 
  set(H.N2_edit,'string',num2str(N2));
    
  Nu=get_param(arg1,'Nu'); 
  set(H.Nu_edit,'string',num2str(Nu));
       
  rho=get_param(arg1,'rho'); 
  set(H.rho_edit,'string',num2str(rho));
    
  alpha=get_param(arg1,'alpha'); 
  set(H.alpha_edit,'string',num2str(alpha));
    
  func_index=['csrchgol';'csrchbac';'csrchhyb';'csrchbre';'csrchcha'];
  csrchfun=get_param(arg1,'csrchfun'); 
  vv=strmatch(csrchfun,func_index);
  set(H.csrchfun_edit,'value',vv);
    
  maxiter=get_param(arg1,'maxiter'); 
  set(H.maxiter_edit,'string',maxiter);
  set(fig,'userdata',H)
  
  set(H.error_messages(1,1),'string',sprintf('Perform plant identification before controller configuration.'));
end

function present_error(H,text_field,field_value,field_type,message)

if text_field~=0
   if field_type      % Number
      set(text_field,'string',num2str(field_value));
   else               % ASCII or No change.
      set(text_field,'string',field_value);
   end
else
   text_field=0;
end   
set(H.error_messages,'string',message);
errordlg(message,'Plant Identification Warning','modal');
