clear;
clc;
tic;
format long
problem_path = './WindFarmOptimization/';
ws_path =  '../WindFarmOptimization/windscenarios';
save_path = '../../Results/';
addpath(problem_path)
addpath(ws_path)

%% experiment setup
runTime = 10;
popsize=50;
max_it = 200;

%% wind farm parameters
rows = 21;
cols =21;
cell_width= 77.0 * 3;
% turbine_num = [15,20,25];
% NA_type_list = 0:12;
turbine_num = [30,35,40];
NA_type_list = 0;

%% wind scenarios
wind_type = [1,2,3,4];
n_speeds = [3,3,4,6];
n_directions = [12,12,12,12];
unifrom = [0,1,0,0];
algorithmDir = 'CGA';
for wt = 1:length(n_speeds)
    for tn = turbine_num
        for NA_type = NA_type_list

            % generation constraints
            NA_loc_array = gene_NA_loc(NA_type);
             
            % Generating a wind farm with Jensen' wake model
            [wf,ws_folder] = gene_windfram(rows,cols,tn,cell_width,NA_loc_array,n_speeds(wt),n_directions(wt),unifrom(wt));
            
            folder = sprintf('%s/%s/%s/tn%d_NA%d',save_path,algorithmDir,ws_folder,tn, NA_type);

            if ~exist(folder,'dir')
                mkdir(folder)
            end

            eta=zeros(max_it,runTime);
            fitness = zeros(max_it,runTime);

            farmlayout= zeros(runTime,max_it,wf.cols*wf.rows);
            farmlayout_NA= zeros(runTime,max_it,wf.cols*wf.rows);
            parfor t=1:runTime
                fprintf('CGA - %s TN %d NA %d run %d\n', ws_folder,tn,NA_type,t)
                [BestChart,Bestfitness,farmlayout(t,:,:),farmlayout_NA(t,:,:)]=GA(popsize,wf,max_it,t,NA_type,tn,ws_folder,algorithmDir);
                eta(:,t) = BestChart;
                fitness(:,t) = Bestfitness;
            end
            for t = 1:runTime
                save_results(reshape(farmlayout(t,:,:),size(farmlayout(t,:,:),2),size(farmlayout_NA(t,:,:),3)),reshape(farmlayout_NA(t,:,:),size(farmlayout_NA(t,:,:),2),size(farmlayout(t,:,:),3)),t,folder)
            end
            save(sprintf('%s/eta.mat',folder),"eta")
            save(sprintf('%s/fitness.mat',folder),"fitness")
            disp(mean(eta(end,:)))

        end

    end
end

toc;



