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

% Last Modified by GUIDE v2.5 20-Aug-2012 13:23:23

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @multigrid_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @multigrid_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 multigrid_gui is made visible.
function multigrid_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 multigrid_gui (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = multigrid_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 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)
method = get_method(handles);

N = 2048;
h = 1/N;
x = (0:h:1)';
f = -1*x.^0 + 100*cos(24*pi*x) + 5e4*cos(1e3*pi*x);

e = ones(N+1,1);
A = spdiags([e -2*e e], -1:1, N-1, N-1)/h^2;

u = A\f(2:(end-1));
u_exact = [0; u; 0];
u_numerical = zeros(N+1,1);

plot_handle = plot(handles.main_axis, x, u_exact, x, u_numerical);
set(handles.main_axis, 'XLim', [0 1]);
error_handle = plot(handles.error_axis, x, u_exact-u_numerical);

I = 2:N;

i = 0;
switch method
    case 'jacobi'
        while ishandle(plot_handle)
            i = i + 1;
            u_numerical = jacobi ( u_numerical, f, 0.5 );
            if mod(i,100) == 0
                set(plot_handle(2), 'YData', u_numerical);
                set(error_handle, 'YData', u_exact-u_numerical);
                set(handles.iterations, 'String', ['Number of iterations: ' int2str(i) ]);
                drawnow;
            end
        end
    case 'multigrid'
        u_numerical = multigrid(f);
        i=i+1;
        set(plot_handle(2), 'YData', u_numerical);
        set(error_handle, 'YData', u_exact - u_numerical);
        set(handles.iterations, 'String', 'Number of iterations: 1 multigrid sweep (V-cycle)');
        drawnow;
        
    case 'gauss-seidel'
        L = spdiags([e -2*e], -1:0, N-1, N-1)/h^2;
        while ishandle(plot_handle)
            i = i+1;
            u_numerical = gauss_seidel( u_numerical, f);
            if mod(i,100) == 0
                set(plot_handle(2), 'YData', u_numerical);
                set(error_handle, 'YData', u_exact-u_numerical);
                set(handles.iterations, 'String', ['Number of iterations: ' int2str(i) ]);
                drawnow;
            end
        end
end

function method = get_method(handles)
methodcontents = cellstr(get(handles.method,'String'));
switch methodcontents{get(handles.method,'Value')};
    case 'Jacobi'
        method = 'jacobi';
    case 'Gauss-Seidel'
        method = 'gauss-seidel';
    case 'Multigrid'
        method = 'multigrid';
end

function u = multigrid(f)

% 1D Poisson equation with Dirichlet boundary conditions

N = length(f) - 1;      % N is a power of 2
h = 1/N;                % true grid: N+1 points
u = zeros(N+1,1);
I = 2:N;

if N > 2,
    
    for k = 1:3
        u(I) = 1/2 * (u(I+1) + u(I-1) - h^2 * f(I));
    end
    
    residual = f(I) - 1/h^2 * (u(I+1) - 2*u(I) + u(I-1));
    residual = [0; residual; 0];
    coarse_residual = residual(1:2:end);
    coarse_err = multigrid(-coarse_residual);
    err = zeros(N+1,1);
    err = interp1(1:2:(N+1), coarse_err, 1:(N+1), 'linear');
    u = u - err';
    
    for k = 1:3
        u(I) = 1/2 * (u(I+1) + u(I-1) - h^2 * f(I));
    end       
else
    u(I) = -1/2 * h^2 * f(I);
end


function u = jacobi(u,f,w)
n = length(u);
I = 2:(n-1);
h = 1/n;
u(I) = w*(1/2 * ( u(I+1) + u(I-1) - h^2 * f(I) )) + (1-w)*u(I);

function u = gauss_seidel(u, f)
n = length(u);
h = 1/(n-1);
I = 2:(n-1);
e = ones(n, 1);
L = spdiags([e -2*e], -1:0, n-2,n-2);

u(I) = L\( h^2 * f(I) - u(I+1));


% --- 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


% --- 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 selection change in domain.
function domain_Callback(hObject, eventdata, handles)
% hObject    handle to domain (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 domain contents as cell array
%        contents{get(hObject,'Value')} returns selected item from domain


% --- Executes during object creation, after setting all properties.
function domain_CreateFcn(hObject, eventdata, handles)
% hObject    handle to domain (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
