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

%  License:
%
%  Please contact the author at email: fguevara at math dot utah dot edu 
%  if you find this demo useful. Please also credit the author if you use this
%  demo in public. Portions of the code are automatically generated by Matlab
%  and as far as I understand are Copyright Mathworks, inc.
%  
%  Copyright (c) 2012, Fernando Guevara Vasquez 
%  All rights reserved.
%
%  Redistribution and use in source and binary forms, with or without
%  modification, are permitted provided that the following conditions are met:
%  
%   * Redistributions of source code must retain the above copyright notice,
%   this list of conditions and the following disclaimer.
%
%   * Redistributions in binary form must reproduce the above copyright notice,
%   this list of conditions and the following disclaimer in the documentation
%   and/or other materials provided with the distribution.
%
%  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
%  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%  POSSIBILITY OF SUCH DAMAGE.
%

% Last Modified by GUIDE v2.5 13-Feb-2010 15:35:02

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

% Choose default command line output for clk
handles.output = hObject;
handles.cloak = 0;
handles.pressed = 0;
% degree of cloaking poly
n = 10; 

 if (n>5)
  rxmin=-10; rxmax=10; rymin=-10; rymax=10;
  R = 0.2; zscat = 1.1; sig=-1+1e-2;
 else
  rxmin=-15; rxmax=15; rymin=-15; rymax=15;
  R = 0.1; zscat = 1.05; sig=-1+1e-3;
 end;
 nscat = 16; % number of points for scatter
 theta = (-nscat:nscat-1)*pi/nscat;

% scatterer
handles.R = R; handles.sig = sig; handles.n = n;
handles.rxmin=rxmin; handles.rxmax=rxmax;
handles.rymin=rymin; handles.rymax=rymax;
handles.nscat = nscat; handles.theta =  theta;
handles.scat_enabled = 1;
handles.caxis = [rxmin,rxmax];

%
uifun = @(z) z;

nx=128; ny=nx;
x = linspace(rxmin,rxmax,nx); y = linspace(rymin,rymax,ny);
[X,Y] = meshgrid(x,y); Z = X + 1i*Y;
handles.X=X; handles.Y=Y; handles.Z = Z;
handles.x=x; handles.y=y; handles.nx=nx;
handles.resolutions = [128,256,512];

% initial scatterer poisition
zscat = 1; handles.zscat=zscat;


% compute fields
rp = ensavgpoly(1./Z,n,n);
ui = uifun(Z);% incident field
ud=ui.*(1-rp); % device field
reutot = real(ui);
if (handles.scat_enabled)
 ui_scat=uifun(zscat + R*exp(1i*handles.theta));
 usi = scat_static(ui_scat,R,handles.nscat,Z-zscat,sig);% scattered field from ui
 reutot = reutot + real(usi);
end;

axis(handles.axes1); imagesc(x,y,reutot); axis xy;
set(handles.axes1,'xtick',[rxmin,0,rxmax]);
set(handles.axes1,'ytick',[rymin,0,rymax]);
caxis(handles.axes1,handles.caxis); colormap(jet(20));
if (handles.scat_enabled)
 plot_scat(handles);
end;


% save stuff for later
handles.uifun=uifun; handles.ui=ui; handles.ud=ud;

XLim = get(handles.axes1,'XLim');
YLim = get(handles.axes1,'YLim');
handles.xmin = XLim(1); handles.xmax = YLim(2);
handles.ymin = YLim(1); handles.ymax = YLim(2);


% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = clk_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 cloakbox.
function cloakbox_Callback(hObject, eventdata, handles)
% hObject    handle to cloakbox (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 cloakbox
handles.cloak=get(hObject,'Value');
redraw(handles); 
guidata(hObject,handles);


function redraw(handles)
zscat = handles.zscat; R = handles.R; Z = handles.Z; sig = handles.sig;
ui_scat=handles.uifun(zscat + R*exp(1i*handles.theta));


if (handles.cloak)
 n = handles.n;
 rp_scat=ensavgpoly(1./(zscat + R*exp(1i*handles.theta)),n,n);
 ud_scat=ui_scat.*(1-rp_scat);
 ui_scat = ui_scat - ud_scat;
end;

reutot = real(handles.ui);
if (handles.scat_enabled)
 us = scat_static(ui_scat,R,handles.nscat,Z-zscat,sig);% scattered field
 reutot = reutot + real(us);
end;
if (handles.cloak)
 reutot = reutot - real(handles.ud);
end;
axis(handles.axes1); imagesc(handles.x,handles.y,reutot); 
axis xy;
caxis(handles.axes1,handles.caxis);
set(handles.axes1,'xtick',[handles.rxmin,0,handles.rxmax]);
set(handles.axes1,'ytick',[handles.rymin,0,handles.rymax]);
if (handles.scat_enabled)
 plot_scat(handles);
end;


 
function plot_scat(handles)
n=64; theta=(0:n)*2*pi/n;
axis(handles.axes1); hold on;
R = handles.R; z = handles.zscat;
h=patch(real(z)+R*cos(theta),imag(z)+R*sin(theta),'k');
set(h,'edgecolor','none');
hold off;

function p = ensavgpoly(Z,n,s)
p = zeros(size(Z));
for j=0:n-1,
 p = p + Z.^j * nchoosek(s+j-1,j);
end;
p = (1-Z).^s .*p;

% function us = scat_static(ui,R,n,z)
%
% Computes scattered field for a 2D  disk scatterer of radius R, located at the
% origin. The conductivity is optional. If no conductivity is specified then
% the disk is assumed to be a perfect conductor.
%
% inputs
%  ui   incident field ui(R,theta) = ui(R*exp(1i*theta)) where 
%              theta =  (-n:n-1)*pi/n;
%  R    radius of scatterer
%  n    there are 2*n evaluation points of the incident field on the scatterer
%  z    points in the complex plane where we want to compute the scatterered
%       field.
%  sig  [OPTIONAL] conductivity
%
% outputs
%  us   scattered field evaluated at the points z

function us = scat_static(ui,R,n,z,sig)

% coefficients of ui in Fourier series
uih = fft(ifftshift(ui))/2/n;

% put zeroth frequency in the middle
uih = fftshift(uih);

if (nargin<5)
 % default perfectly conducting disk 
 uih=-uih; 
else
 % conductivity sig is given: in the limit sig->inf we get -1
 uih=((1-sig)/(1+sig))*uih; 
end;

% scattered field
%us = uih(0+n+1)*ones(size(z)); % constant component
us = zeros(size(z));
for j=1:n-1,
  zmj = 1./(z.^j);
  us = us + uih(-j+n+1) * R^j *      zmj ;
  us = us + uih(+j+n+1) * R^j * conj(zmj);
end;
j=n;
zmj = 1./(z.^j);
us = us + uih(-j+n+1) * R^j * conj(zmj);

% --- Executes on mouse motion over figure - except title and menu.
function figure1_WindowButtonMotionFcn(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)
pt = get(handles.axes1,'CurrentPoint');
if (handles.pressed)
  if ( handles.xmin <= pt(1) && pt(1) <= handles.xmax && ...
     handles.ymin <= pt(3) && pt(3) <= handles.ymax )
   handles.zscat = pt(1) + 1i*pt(3);
   guidata(hObject,handles);
   redraw(handles);
  end;
end;


% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonDownFcn(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)
handles.pressed=1;
pt = get(handles.axes1,'CurrentPoint');
if ( handles.xmin <= pt(1) && pt(1) <= handles.xmax && ...
     handles.ymin <= pt(3) && pt(3) <= handles.ymax )
   handles.zscat = pt(1) + 1i*pt(3);
   guidata(hObject,handles);
   redraw(handles);
end;
guidata(hObject,handles);


% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonUpFcn(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)
handles.pressed=0;
guidata(hObject,handles);



% --- Executes on button press in pbhide.
function pbhide_Callback(hObject, eventdata, handles)
% hObject    handle to pbhide (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if (handles.n>5)
 handles.zscat = 1.1;
else
 handles.zscat = 1.05;
end;
redraw(handles);
guidata(hObject,handles);


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

% Hints: contents = get(hObject,'String') returns resol contents as cell array
%        contents{get(hObject,'Value')} returns selected item from resol
handles.nx = handles.resolutions(get(hObject,'Value'));
x = linspace(handles.rxmin,handles.rxmax,handles.nx); 
y = linspace(handles.rymin,handles.rymax,handles.nx);
[X,Y] = meshgrid(x,y); Z = X + 1i*Y;
handles.X=X; handles.Y=Y; handles.Z = Z;
handles.x=x; handles.y=y;
% recompute fields
rp = ensavgpoly(1./handles.Z,handles.n,handles.n);
ui = handles.uifun(handles.Z);% incident field
ud=ui.*(1-rp); % device field
handles.ui=ui; handles.ud=ud;
redraw(handles);
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function resol_CreateFcn(hObject, eventdata, handles)
% hObject    handle to resol (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 cbscat.
function cbscat_Callback(hObject, eventdata, handles)
% hObject    handle to cbscat (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 cbscat
handles.scat_enabled = get(hObject,'Value');
redraw(handles);
guidata(hObject,handles);
