%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%           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 1
%                     Victor Matveev, 2012
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function sweepGsynRandModel1
global logFile prefix plotFlag Data tArray dFit; 
% tauH tauCa gamma minfV minfS  tauMmax tauMV tauMS   gm   hinfV hinfS 
%   1    2      3     4     5     6       7     8     9    10   11   
% K4 tauM tauMVcnt tauMScnt   gCa 
% 12  13    14        15      16  

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

fcostAll = @FitCostGsynModel1;

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

fname = ['DataRandGsynModel1'];

X00 = [776.641 30.1194 0.00813397 44.924 1.81141 1800 50 8 0.231789 43.3722 21.3902 1.84466 46.7599 40.2047 9.57299 0.00886014];

while (1)

    plotFlag  = 0;
    Cost0 = 1e6;

    while Cost0 > 28
        X0 = 3.5 * (X00 .* rand(size(X00)) );
        X0(7) = 45 + 10*rand;   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        [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 > 10)
        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');
    close(gcf);
end
end