function varargout = pde_gui(varargin)
% PDE_GUI MATLAB code for pde_gui.fig
%      PDE_GUI, by itself, creates a new PDE_GUI or raises the existing
%      singleton*.
%
%      H = PDE_GUI returns the handle to a new PDE_GUI or the handle to
%      the existing singleton*.
%
%      PDE_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PDE_GUI.M with the given input arguments.
%
%      PDE_GUI('Property','Value',...) creates a new PDE_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before pde_gui_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to pde_gui_OpeningFcn via varargin.
%
%      *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 pde_gui

% Last Modified by GUIDE v2.5 07-Sep-2012 09:48:12

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @pde_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @pde_gui_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 pde_gui is made visible.
function pde_gui_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   command line arguments to pde_gui (see VARARGIN)

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

if(isunix()) % fix a problem that arose on my damtp linux box
    set(handles.figure1,'renderer','painters');
end

% Update handles structure
guidata(hObject, handles);

update_grid(handles);

% UIWAIT makes pde_gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = pde_gui_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;


% --- Executes on selection change in edit_function.
function edit_function_Callback(hObject, eventdata, handles)
% hObject    handle to edit_function (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns edit_function contents as cell array
%        contents{get(hObject,'Value')} returns selected item from edit_function
try    
    update_grid(handles);
catch err
    h=msgbox(err.message,'Error','error','modal');
    waitfor(h);
end

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

% Hint: popupmenu 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 selection change in method.
function method_Callback(hObject, eventdata, handles)
% hObject    handle to method (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns method contents as cell array
%        contents{get(hObject,'Value')} returns selected item from method

try
    update_grid(handles);
catch err
    h=msgbox(err.message,'Error','error','modal');
    waitfor(h);
end

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

% Hint: popupmenu 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 run.
function run_Callback(hObject, eventdata, handles)
% hObject    handle to run (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
    n = get_gridsize(handles);
    M = 250;
    f = get_function(handles);
    meth = get_method(handles);
    mu = get_courant(handles);

    set(handles.run, 'String', 'Calculating...');
    set(handles.run, 'Enable', 'off');
    drawnow;
    u = solve_pde(f,n,mu,meth, M);
    set(handles.run, 'Enable', 'on');
    set(handles.run, 'String', 'Run');

    plot_z = zeros(n+2);
    plot_z(2:(n+1),2:(n+1)) = reshape(u(:,1),n,n);

    h = mesh(handles.axes1,plot_z);
    rotate3d on;
    axis([1 n+2 1 n+2 -1.5 1.5]);
    t = 2;
    while t <= M && max(u(:,t-1)) <= 1.5 && ishandle(h)
        plot_z = zeros(n+2);
        plot_z(2:(n+1),2:(n+1)) = reshape(u(:,t),n,n);
        set(h, 'ZData', plot_z);
        t = t+1;
        drawnow;
    end
catch err
    h=msgbox(err.message,'Error','error','modal');
    waitfor(h);
end


function grid_size_Callback(hObject, eventdata, handles)
% hObject    handle to grid_size (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 grid_size as text
%        str2double(get(hObject,'String')) returns contents of grid_size as a double


% --- Executes during object creation, after setting all properties.
function grid_size_CreateFcn(hObject, eventdata, handles)
% hObject    handle to grid_size (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 courant_number_Callback(hObject, eventdata, handles)
% hObject    handle to courant_number (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 courant_number as text
%        str2double(get(hObject,'String')) returns contents of courant_number as a double


% --- Executes during object creation, after setting all properties.
function courant_number_CreateFcn(hObject, eventdata, handles)
% hObject    handle to courant_number (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 mu = get_courant(handles)
mu = str2double(get(handles.courant_number,'String'));
assert( ~isnan(mu) && isreal(mu) && ~isinf(mu) && mu > 0,...
    'Invalid Courant number. Must be a positive real number.' );

function f = get_function(handles)
functioncontents = cellstr(get(handles.edit_function,'String'));
switch functioncontents{get(handles.edit_function,'Value')}
    case 'x(1-x)y(1-y)'
        f = @(x,y)(20*x*(1-x)*y*(1-y));
    otherwise
        f = @(x,y)(sin(2*pi*x)*sin(2*pi*y));
end

function n = get_gridsize(handles)
n = str2double(get(handles.grid_size,'String'));
assert(~isnan(n) && isreal(n) && ~isinf(n) && floor(n) ==n && ...
    and(n >= 1,n<=63), ...
    'Invalid grid size. Must be an integer between 1 and 63.');

function meth = get_method(handles)
methodcontents = cellstr(get(handles.method,'String'));
switch methodcontents{get(handles.method,'Value')}
    case 'Wave'
        meth = 'Wave';
    case 'Diffusion (Euler)'
        meth = 'Euler';
    otherwise
        meth = 'Crank-Nicolson';
end

function update_grid(handles)
n = get_gridsize(handles);
f = get_function(handles);
meth = get_method(handles);
mu = get_courant(handles);
u = solve_pde(f,n,mu,meth, 1);

plot_z = zeros(n+2);
plot_z(2:(n+1),2:(n+1)) = reshape(u(:,1),n,n);

if(isunix())
    set(handles.figure1,'renderer','painters');
end
%h =
mesh(handles.axes1,plot_z);
axis([1 n+2 1 n+2 -1.5 1.5]);
% set(h,'XLim',[1 n+1]);
% set(h,'YLim',[1 n+1]);
% set(h,'ZLim', [-1.5 1.5]);

function u = solve_pde ( f, n, mu, method, M )
    v = zeros(n);
    A = laplacian(n);
    I = speye(n^2);
    
    for i = 1:n
        for j = 1:n
            v(i,j) = f(i/(n+1),j/(n+1));
        end
    end
    u = zeros(n^2, M);
    u(:,1) = reshape(v,n^2,1);
    
    switch method
        case 'Euler'
            for i = 2:M
                u(:,i) = u(:,i-1)+mu*A*u(:,i-1);
            end
        case 'Crank-Nicolson'
            for i = 2:M
                u(:,i) = (I-0.5*0.25*A)\(((I+0.5*0.25*A)*u(:,i-1)));
            end
        case 'Wave'
            u(:,2) = u(:,1)+0.5*mu*A*u(:,1);
            for i = 3:M
                u(:,i) = (2*I+mu*A)*u(:,i-1)-u(:,i-2);
            end
    end

function v = mat_to_vec ( M )
n = size(M,1);
v = zeros(n^2,1);

for i = 1:n
    v( ((i-1)*n+1):(i*n) ) = M(:,i);
end

function M = vec_to_mat ( v )
n = size (v, 1);
d = floor(sqrt(n));

M = zeros(d);

for i = 1:d
    M(:,i) = v( ((i-1)*d+1):(i*d) );
end

function A = laplacian ( n )
I = speye(n,n);
E = sparse(2:n,1:n-1,1,n,n);
D = E+E'-2*I;
A = kron(D,I)+kron(I,D);


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

% Hint: place code in OpeningFcn to populate axes1


% --- Executes when figure1 is resized.
function figure1_ResizeFcn(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)
