⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ocd.m

📁 很优良的PID控制器设计仿真程序与模型,经过严格检验
💻 M
字号:
function varargout = ocd(varargin)
% OCD for designing optimal PID controller.  
%
%      This routine is a GUI which accept a Simulink model for PID system
%      simulation with variables to be optimized.  Once the model is setup.
%      the error signal in the system should be connected to the solo
%      Outport of Simulink under Sinks.
%
% Click Help button for more details.

%      Designed by Professor Dingyu Xue (c)
%      Northeastern University, Shenyang 110004, P R China
%      First released 17 April, 2003 
%      Contact address:
%             xue_dy@21cn.com
%             http://www.matlab-world.com/index_e.htm
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ocd_OpeningFcn, ...
                   'gui_OutputFcn',  @ocd_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(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

function h_btnView_Callback(hObject, eventdata, handles)
user_data=get(handles.h_btnCreate,'UserData');
str=user_data{6};
edit(str) 

function h_btnOptimize_Callback(hObject, eventdata, handles)
user_data=get(handles.h_btnCreate,'UserData');
if length(user_data)>=6
    str=user_data{6};  
    str_x0=get(handles.h_edtInit,'String');
    n=user_data{1};
    try
        x0=str2num(str_x0); 
        x0=x0(:); k=length(x0);
        if k<n, x0=[x0; abs(rand(n-k,1))]; end
        x0=x0(1:n);
        lb=str2num(get(handles.h_edtLower,'String'));
        ub=str2num(get(handles.h_edtUpper,'String'));
        key=get(handles.h_chkFixedStep,'Value');
        ff=msgbox({'Optimization process is going on.   Go back to the Command Window';
                   'for optimalization results.  Please wait ...'},'Optimizing ...');
        kTool=get(handles.h_lstToolbox,'Value'); 
        if key==1
           options=optimset('Display','iter','Jacobian','off');
           ctrl_pars=lsqnonlin(str,x0,lb,ub,options)
        else
            options=optimset('Display','iter','Jacobian','off','LargeScale','off');
            if length(lb)==0 & length(ub)==0
               switch kTool
                   case 1
                       ctrl_pars=fminsearch(str,x0,options)
                   case 2
                       ctrl_pars=fminunc(str,x0,options)
                   case 3
                       eval(['ctrl_pars=ga(@' str ',' int2str(length(x0)) ')'])
                   case 4
                       ctrl_pars=gaopt([zeros(size(x0(:))),100*ones(size(x0(:)))],str)
               end
            else
               ctrl_pars=fmincon(str,x0,[],[],[],[],lb,ub,[],options)
            end
        end
        assignin('base','ctrl_pars',ctrl_pars);
        set(handles.h_edtInit,'String',['[' num2str(ctrl_pars(:)') ']''']);
        pause(0.0001);
        delete(ff);
    catch
         errordlg({'Failed to get the optimum value'; lasterr},'Error');
         delete(ff);
     end
else
    errordlg('Nothing to optimize','Error');
end

function h_btnBrowse_Callback(hObject, eventdata, handles)[FileN,PathN]=uigetfile('*.mdl','Select a model name');
set(handles.h_edtFile,'String',FileN);
h_edtFile_Callback(hObject, eventdata, handles);

function h_edtFile_Callback(hObject, eventdata, handles)
FileN=get(handles.h_edtFile,'String');
if exist(FileN)~=4
    errordlg('The selected Simulink file is not in the search path.',...
        'Error: Model problem');
else
    set(handles.h_btnShow,'Enable','on')
end

function h_btnShow_Callback(hObject, eventdata, handles)open_system(get(handles.h_edtFile,'String'));

function h_edtVariables_Callback(hObject, eventdata, handles)set(handles.h_btnCreate,'Enable','on');

function h_btnCreate_Callback(hObject, eventdata, handles)strvars=get(handles.h_edtVariables,'String'); t_end=10;
try
    strvars=strvars(strvars~=' ');
    fpos=find(strvars==',');
    n=length(fpos)+1;
    str_vars={strvars(1:fpos(1)-1)};
    for i=1:n-2
        str_vars{i+1}=strvars(1+fpos(i):fpos(i+1)-1);
    end
    str_vars{n}=strvars(fpos(end)+1:end);
    key=0;
    for i=1:n
        if length(str_vars{i})==0, key=1; break; end
        if ~(isletter(str_vars{i}(1)) | str_vars{i}(1)=='_'), key=1; break; end
    end
    if key==1, disp_error_jump_out_of_try; end
    k=0;
    while 1
       str=['optfun_' int2str(k)];    
       if ~any([2 3 5 6]==exist(str)), break; end
       k=k+1;
    end
    try
        t_end=str2num(get(handles.h_edtTend,'String'));
    catch
        t_end=1;    
    end
    kAlg=get(handles.h_lstToolbox,'Value');
    t_alpha=[];
    if kAlg==3
        try
           t_alpha=str2num(get(handles.h_edtWeightPar,'String'));
        catch
           t_alpha=1;    
    end, end
    user_data={n};
    user_data{2}=str_vars;
    user_data{3}=t_end;
    user_data{4}=kAlg;
    user_data{5}=get(handles.h_edtFile,'String');
    user_data{6}=str;
    user_data{7}=t_alpha;
    set(handles.h_btnCreate,'UserData',user_data);
    key=optfun_file_save(str,handles);
    if key==1
        set([handles.h_btnView,handles.h_btnOptimize,handles.h_btnSave],'Enable','on');
    end    
catch
    errordlg('Wrong Variable list, please fill in again.','Error: Variable list');
end

function h_btnSave_Callback(hObject, eventdata, handles)
% save the objective function to another file name of the users' choice.[FileN,PathN]=uiputfile('*.m','Select a file name to save');
try
    optfun_file_save(FileN,handles,PathN);
catch
    errordlg({'Wrong File Name selected, try again.';lasterr},'Error:File Name');
end

function h_btnCancel_Callback(hObject, eventdata, handles)
% clear current simulink modelsset(handles.h_edtFile,'String','')
set([handles.h_btnShow,handles.h_btnView,handles.h_btnSave,handles.h_btnCreate],'Enable','off')

function h_btnHelp_Callback(hObject, eventdata, handles)
% a html file has been created to provide more details of such a function.
web(['file:' which('opt_ctrl.html')])

function h_lstToolbox_Callback(hObject, eventdata, handles)
kTool=get(handles.h_lstToolbox,'Value'); key=0;
strTool={'Optimization','Genetic Algorithm and Direct Search','GA Optimization'};
switch kTool
    case 2
        if exist('fminunc')~=2, key=1; end
    case 3
        if exist('gaoptimset')~=2, key=1; end
    case 4
        if exist('unifMutation')~=2, key=1; end
end
if key>0
   errordlg(['Error: ' strTool{kTool-1}, ' Toolbox not installed'],'Error');
   set(handles.h_lstToolbox,'Value',1);
end

function h_btnClear_Callback(hObject, eventdata, handles)
for i=0:1000
    try
       str=['optfun_' int2str(i)];    
       if exist(str)==2, delete([str '.m']); end
    catch
        errordlg({'Error deleting files';lasterr},'Error');
    end
end

%IMPORTANT: -----------------------------------------------------
%   default functions below, please DO NOT edit them manually!!!!
%----------------------------------------------------------------
function h_chkFixedStep_Callback(hObject, eventdata, handles)
if get(gco,'Value')==1,
   set([handles.h_edtStepSize,handles.h_txtStepSize],'Visible','on')
else
   set([handles.h_edtStepSize,handles.h_txtStepSize],'Visible','off')
end
function h_edtTend_CreateFcn(hObject, eventdata, handles)
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function h_edtVariables_CreateFcn(hObject, eventdata, handles)
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function h_edtFile_CreateFcn(hObject, eventdata, handles)
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function h_lstToolbox_CreateFcn(hObject, eventdata, handles)
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function h_edtInit_CreateFcn(hObject, eventdata, handles)if ispc    set(hObject,'BackgroundColor','white');else    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));endfunction h_edtStepSize_CreateFcn(hObject, eventdata, handles)
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function h_edtUpper_CreateFcn(hObject, eventdata, handles)
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function h_edtInit_Callback(hObject, eventdata, handles)
function h_edtTend_Callback(hObject, eventdata, handles)
function h_edtStepSize_Callback(hObject, eventdata, handles)
function h_edtLower_CreateFcn(hObject, eventdata, handles)function h_edtUpper_Callback(hObject, eventdata, handles)function h_edtLower_Callback(hObject, eventdata, handles)
function ocd_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
guidata(hObject, handles); 
function varargout = ocd_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
function key=optfun_file_save(str,handles,PathN)
key=1; kTool=get(handles.h_lstToolbox,'Value');
try
    if nargin<3, PathN=''; end
    fid=fopen([PathN str,'.m'],'w');
    if kTool==4 % if GAOT is used, rewrite the objective function
        fprintf(fid,'function [x,y]=%s(x,opts)\r\n',str);
    else
        fprintf(fid,'function y=%s(x)\r\n',str);
    end
    user_data=get(handles.h_btnCreate,'UserData');
    n=user_data{1};
    str_vars=user_data{2};
    t_end=user_data{3};
    kAlg=user_data{4};
    mod_name=user_data{5};
    fprintf(fid,'%% %s   An objective function function for optimal controller design\r\n',upper(str));
    fprintf(fid,'%%\r\n\r\n');
    fprintf(fid,'%%   The function is created by PID toolbox.\r\n');
    fprintf(fid,'%%   Date of creation %s\r\n',date);    
    for i=1:n
        fprintf(fid,'assignin(''base'',''%s'',x(%d));\r\n',str_vars{i},i);
    end
    k_Step=get(handles.h_chkFixedStep,'Value');
    if k_Step==1
       t_step=str2double(get(handles.h_edtStepSize,'String')); 
       fprintf(fid,'options=simset(''Solver'',''ode5'',''FixedStep'',%f);\r\n',t_step);
       fprintf(fid,'[t_time,x_state,y_out]=sim(''%s'',[0,%f],options);\r\n',mod_name,t_end);
    else
       fprintf(fid,'[t_time,x_state,y_out]=sim(''%s'',[0,%f]);\r\n',mod_name,t_end);
    end
    fprintf(fid,'y=y_out(end);\r\n');
    if kTool==4, fprintf(fid,'y=-y;\r\n'); end
    fclose(fid);
catch
    key=0;
    errordlg({'Error Creating optimization objective function file';lasterr},'Error');
end

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -