%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%           M. Oh, S. Zhao, V. Matveev and F. Nadim (2012)
%    Neuromodulatory changes in short-term synaptic dynamics may be 
%   mediated by two distinct mechanisms of presynaptic calcium entry
%            Journal of Computational Neuroscience. 
%
%  Generates, analyzes and saves optimal parameter sets for Model 2
%                     Victor Matveev, 2012
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function sweepGsynRandModel2
global logFile prefix plotFlag Data tArray dFit;
% Parameters: 
% gMI tauCa gamma kpV kpS gm tauH hinfV hinfS 
%   1   2     3    4   5   6   7   8    9   
% K4  tauM  tauMVcnt tauMScnt gCa    
% 10   11     12       13      14  

RandStream.setDefaultStream ...
     (RandStream('mt19937ar', 'seed', sum(100*clock)));

tag = 'Gsyn';
fcostAll = @FitCostGsynModel2;

[ Data, dFit, tArray ] = getData(550);

fname = ['DataRandGsynModel2'];

X00 = [0.0018     40      0.003      40      3      0.0258     230 38     15     9       55      26      16    0.018 0];   
X0 = X00;

while (1)

    plotFlag  = 0;
    Cost0 = 1e6;

    while Cost0 > 25
        X0 = 3.5 * (X00 .* rand(size(X00)) );
        [Cost0, Dev0] = fcostAll(X0');
        fprintf('%g [%g %g %g %g %g %g %g]\n', Cost0, Dev0);
    end
    
    X0 = X0';
    plotFlag = 0;
    opt = optimset( 'Display', 'iter');
    X = fminsearch( fcostAll, X0, opt);
    [Cost, Dev] = fcostAll(X);

    if (Cost > 12) %|| sum(Dev > 12)
        continue;
    end

    logFile = fopen(fname,'a');
    fprintf(logFile, ' minCost = [minCost, %g];  minDev = [minDev; [%g %g %g %g %g %g %g]]; \n minParams = [minParams; [', Cost, Dev);
    fprintf(logFile, '%g ', X');
    fprintf(logFile, ']]; \n\n');
    fclose(logFile);

    plotFlag = 1;
    prefix = [fname, num2str(floor(Cost)), 'p' , num2str(floor((Cost-floor(Cost))*100000)) ];
    fcostAll(X);
    saveas(gcf, prefix, 'png');
    pause(2);
    close(gcf);

end
end