clear;
% clc;
% close all;

%% Options
run_optimisation = true;

%% Set up directories
current_dir = cd;
Idx_backslash = find(current_dir == filesep);
main_dir = current_dir; %(1:Idx_backslash(end));
data_dir = [main_dir '\data' filesep];
code_dir = [main_dir '\code' filesep];
output_dir = [main_dir '\output' filesep];
storage_dir = [main_dir '\storage' filesep];

%% Define constants
R = 8.314;
T = 310;
F = 96485;

%% Plot I-V curves
% UNITS:
%     I = G_GHK * K [=] mA
%     G_GHK = I/K [=] Amp.litre/mol
%     G_PMR [=] mS [=] mA/V
    
V = (-120:1:60)/1000;

cKo = 4.5;
cKi = 141.2;
cNao = 132;
cNai = 9;
Cai = 6e-5; %millimolar
PNaK = 0.01833; % [=] dimless
Cm = 0.001; % Unit microF

G_pmr = Cm*0.433*(1+0.6/(1+((3.8e-5/Cai)^1.4))); 

% E_K = R*T/F*log(cKo/cKi_st);
% E_K_st = R*T/F*log(cKo_st/cKi_st);
E_K = R*T/F*log((cKo+PNaK*cNao)/(cKi+PNaK*cNai));

I_lin = G_pmr*(V-E_K); % Unit mA    don't consider gating variable: just finding conductance.

fitRange = [31:91];
fitRange = [1:length(I_lin)];
error_func = @(G_GHK) square_error(I_lin(fitRange) - calc_IGHK(G_GHK,V(fitRange),cKi,cKo));

A = [];
b = [];
Aeq = [];
beq = [];
lb = [-Inf];
ub = [Inf];

options_ps = optimoptions('particleswarm','UseParallel',false,'HybridFcn',@fminunc,'SwarmSize',200);

if run_optimisation
    [G_GHK,fval,exitflag,output] = particleswarm(error_func,1,lb,ub,options_ps);
    save([storage_dir 'Ks_G_GHK.mat'],'G_GHK');
else
    load([storage_dir 'Ks_G_GHK.mat']);
end
I_GHK = calc_IGHK(G_GHK,V,cKi,cKo);

h = figure;
plot(1000*V,1e6*I_lin,'k--',1000*V,1e6*I_GHK,'k','LineWidth',2);
legend('LRd','BG','Location','southeast');
ylabel('Current (nA)');
xlabel('Voltage (mV)');
set(gca,'FontSize',16);

print_figure(h,output_dir,'Ks_IV_curve');