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

% Last Modified by GUIDE v2.5 16-Dec-2016 11:54:32

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

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

% Update handles structure
guidata(hObject, handles);

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


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



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


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


% --- Executes during object creation, after setting all properties.
function SD1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SD1 (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 SD2_Callback(hObject, eventdata, handles)
% hObject    handle to SD2 (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 SD2 as text
%        str2double(get(hObject,'String')) returns contents of SD2 as a double
%global CharliesWorld 

%CharliesWorld = 5;

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


% --- Executes on button press in pcurve.
function pcurve_Callback(hObject, eventdata, handles)
% hObject    handle to pcurve (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
meanDiff = str2num(get(handles.MDiff,'String'));
std1 = str2num(get(handles.SD1,'String'));
std2 = str2num(get(handles.SD2,'String'));
leftCenter = (-1*meanDiff)/2; %Charlie's idea. We could have asked for explicit centers 
rightCenter = meanDiff/2; %Here, we simply plot them symmetrically around 0, splitting the mean difference
%We need to decide which range to plot
leftEdge = leftCenter-4*std1; %We hardcore the range as 
rightEdge = rightCenter+4*std2; %+/- 4 SD. We could make this a dial for the user to control
%Let's create our internal state variable.
%By convention, this is usually called x
%But I want other functions to see it.
%So what do we call it?
%We create it as a field of handles, so as handles is passed around
%x will be passed around with it
%We could let the user decide how granular
%to make this. But let's pick something, 
%how about 0.01?
handles.x = leftEdge:0.01:rightEdge;
%The two distributions - signal and noise distributions
%could be anything. It might actually be quite nice
%to let the user pick that. Maybe from a pulldown menu?
%For now, in the interest of time and to be
%conventional, let's start with normal distributions
handles.y = 0.5 .* normpdf(handles.x,leftCenter,std1); %Noise distribution
handles.y2 = 0.5 .* normpdf(handles.x,rightCenter,std2); %Signal distribution

%variableToBeNamed = 5;
%global CharliesWorld
%CharliesWorld

%Actual plotting
%Switch to the right axes - we only have one for now, but we'll add
%more. So get into the habit of doing this explicitly
axes(handles.curves) %Switch to these axes
hold off

plot(handles.x,handles.y, 'color','b','linewidth',2)
hold on
plot(handles.x,handles.y2, 'color','r','linewidth',2)
box off %Let's not box in the plot. Makes it look nicer

set(handles.plotROC,'Visible','on')

guidata(hObject, handles);


% --- Executes on button press in plotROC.
function plotROC_Callback(hObject, eventdata, handles)
% hObject    handle to plotROC (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%To calculate the ROC, we need to sweep
%an imaginary setCriterion from right to left
%and calculate the area under the respective
%curves at any point. 
%There are many ways to do this.
%We'll use a loop to illustrate what is going on
axes(handles.roc)
hold off %So replotting doesn't collide with the old plot
for ii = 1:length(handles.x) %Go through the entire internal variable
    FA(ii) = sum(handles.y(1,ii:length(handles.x)));
    %Summing from the iith element to the end of the noise distribution
    HIT(ii) = sum(handles.y2(1,ii:length(handles.x)));
    %Summing from the iith element to the end of the signal distribution 
end

HIT = HIT./100; %Normalize to get rate
FA = FA./100; %Same
plot(FA,HIT) %Plot it
xlabel('False alarms')
ylabel('Hits')

%This now updates the ROC curve for changes 
%in parameter values. But it is hard to judge
%what is going on. Let's add a reference, to judge
%what we would expect from chance performance
reference = 0:0.1:0.5; 
hold on
plot(reference,reference,'color','k')
box off
set(handles.setCriterion,'Visible','on')


% --- Executes on button press in setCriterion.
function setCriterion_Callback(hObject, eventdata, handles)
% hObject    handle to setCriterion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.criterion = ginput(1); 
%ginput brings up crosshairs. Let's the user
%pick a point in the plot, in units of the plot.
%The 1 signifies that we pick a single point

%Plot a line at that point
line([handles.criterion(1) handles.criterion(1)], ...
    [min(ylim) max(ylim)],'color','k')

%Now, we need to find the index of x that most
%closely corresponds to this value, then integrate
%the probability density from that point to the end
%for both signal and noise distributions.
tempX = handles.x-handles.criterion(1);
%Subtract our criterion value from all x. 
%Make this a temporary variable.
[temp1 temp2] = min(abs(tempX)); 
%Find the minimum of the absolute value of the difference
%That's the closest to the threshold.
%temp1 will be the value - not interesting.
%temp2 will be the index we are looking for.
thresholdInX = temp2; 
pHit = sum(handles.y2(thresholdInX:length(handles.x)));
pFP = sum(handles.y(thresholdInX:length(handles.x)));

axes(handles.roc)
hold on
plot(pFP/100,pHit/100,'.','color','k','markersize',20)
set(handles.hit,'String',num2str(pHit/100,'%1.2f'))
set(handles.miss,'String',num2str(0.5-pHit/100,'%1.2f'))
set(handles.fp,'String',num2str(pFP/100,'%1.2f'))
set(handles.cr,'String',num2str(0.5-pFP/100,'%1.2f'))
guidata(hObject, handles);



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


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


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


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


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