%lecture_040412.m

%% 2.  3-down 1-up staircase method

p.coherenceList = 2.^(-4:1:0);
p.nTrials = 50;
p.responseInterval = 1;
p.ITI = 3;


currentID = length(p.coherenceList);

%%

clear display dots

% Set display parameters
display.dist = 50;  %cm
display.width = 30; %cm
display.skipChecks = 1; %avoid Screen's timing checks and verbosity

% Set up dot parameters
dots.nDots = 200;
dots.speed = 5;
dots.lifetime = 12;
dots.apertureSize = [12,12];
dots.center = [0,0];
dots.color = [255,255,255];
dots.size = 8;
dots.coherence = .5;

duration = 1; %seconds



%Start the trial

try
    display = OpenWindow(display);
    
    drawText(display,[0,6],'Press "u" for up and "d" for down',[255,255,255]);
    drawText(display,[0,5],'Press Any Key to Begin.',[255,255,255]);
    
    display = drawFixation(display);
    
    %while KbCheck; end
    KbWait;
    startTime= getSecs;
    correctInARow = 0;
    for trialNum = 1:p.nTrials
        %choose either up or down for the dot direction
        trialDirection = ceil(rand(1)+.5);  %50/50 chance of a 1 (up) or a 2 (down)
        dots.direction = (trialDirection-1)*180; %1 -> 0 degrees, 2 -> 180 degrees
        
        results.intensity(trialNum) = p.coherenceList(currentID);
        
        
        
        dots.coherence = results.intensity(trialNum);
        %Show the stimulus d
        movingDots(display,dots,duration);
        
        %Get the response within the first second after the stimulus
        keys = waitTill(p.responseInterval);
        
        %Interpret the response provide feedback
        if isempty(keys)  %No key was pressed, yellow fixation
            correct = NaN;
            display.fixation.color{1} = [255,255,0];
        else
            %Correct response, green fixation
            if (keys{end}(1)=='u' && dots.direction == 0) || (keys{end}(1)=='d' && dots.direction == 180)
                results.response(trialNum) = 1;
                display.fixation.color{1} = [0,255,0];
                correctInARow = correctInARow  + 1;
                if correctInARow == 3
                    currentID = max(currentID-1,1);
                    
                    correctInARow = 0;
                end
                
                %Incorrect response, red fixation
            elseif (keys{end}(1)=='d' && dots.direction == 0) || (keys{end}(1)=='u' && dots.direction == 180)
                results.response(trialNum) = 0;
                display.fixation.color{1} = [255,0,0];
                currentID = min(currentID+1,length(p.coherenceList));
                correctInARow = 0;
                %Wrong key was pressed, blue fixation
            else
                results.response(trialNum) = NaN;
                display.fixation.color{1} = [0,0,255];
            end
        end
        
        %Flash the fixation with color
        drawFixation(display);
        waitTill(.5);
        display.fixation.color{1} = [255,255,255];
        drawFixation(display);
        waitTill(trialNum*p.ITI,startTime);
        
    end
    
catch ME
    Screen('CloseAll');
    rethrow(ME)
end
Screen('CloseAll');

save PaolaStaircaseData p results display

%%
figure(1)
clf
stairs(log(results.intensity));
set(gca,'YTick',log(p.coherenceList));
logy2raw
hold on


%%

intensities = unique(results.intensity);

for i=1:length(intensities)
    id = results.intensity == intensities(i);
    nTrials(i) = sum(id);
    PC(i) =    sum(results.response(id))/nTrials(i);
end

figure(2)
clf
plot(log(intensities),PC,'ko','MarkerFaceColor','g','MarkerSize',12);
set(gca,'XTick',log(intensities));
logx2raw
xlabel('Cohererence');
ylabel('Percent Correct');



%% plot a typical Weibul function

x =  exp(linspace(log(1/32),log(1),51));

p.b = 3;
p.t = .1;

y = Weibull(p,x);

figure(3)
clf
h1=plot(log(x),y,'b-');

hold on

p.b = 2;
y = Weibull(p,x);
h2= plot(log(x),y,'r-');

p.t = .2;
y = Weibull(p,x);
h3= plot(log(x),y,'g-');



set(gca,'XTick',log(p.coherenceList))



logx2raw

legend([h1,h2,h3],{'b=3, t= .1','b=2 t= .1','b = 2, t= .2'});
%%
figure(2)
hold on
plot(log(x),y,'g-');


%% likelihood
prob = Weibull(p,results.intensity);

likelihood = prod(prob.^results.response)*prod((1-prob).^(1-results.response));

log(likelihood)

logLikelihood = sum( results.response.*log(prob) + (1-results.response).*(log(1-prob)))

fitPsychometricFunction(p,results)

%% better guess
p.b = 2.5;
p.t = .2;

prob = Weibull(p,results.intensity);

prob = prob*.99;

likelihood = prod(prob.^results.response)*prod((1-prob).^(1-results.response));

log(likelihood)

logLikelihood = sum( results.response.*log(prob) + (1-results.response).*(log(1-prob)))

fitPsychometricFunction(p,results)


%% get matlab to find the best fitting parameters

fitPsychometricFunction(p,results)

freeParams = {'t','b'};


bestP = fit('fitPsychometricFunction',p,freeParams,results);


y = Weibull(bestP,x);

figure(2)
hold on
plot(log(x),y,'c-');
%legend([h1,h2,h3,h4],{'b=3, t= .1','b=2 t= .1','b = 2, t= .2','best'});

