
%%%%%%%%%% Simulation of a factor model with block structure %%%%%%%%%%%%%%
 
% clearing

clear
clc


%%%%%%

t_vec = [100 150 200]
n_vec = [100 1000 2000]
com_fac_vec = [1]
q_vec = 1
load_type_vec = ['normal']
dist_type_vec = ['normal']
delta_vec = 0
tau_vec = [.1 .4 .8]
n_blocks_vec = [2,10,20]
factor_per_block_vec = [1]
type_vec = [1]   %% 1 = homogeneous , 2 = heterogeneous
theta_vec = [0.5]%,0.7,0.9]
share_vec = [0,0.5,0.75,0.9]
k_vec = 3


iterator_full = makeTuples(t_vec,n_vec,com_fac_vec,...
                      tau_vec, ...
                      n_blocks_vec,factor_per_block_vec,type_vec,...
                      theta_vec,share_vec);

iterator = iterator_full(iterator_full(:,2)./iterator_full(:,5)>10,:);
idx = iterator(:,3)== iterator(:,6); 
iterator = iterator(idx,:);



T = iterator(:,1);
n = iterator(:,2);
r_c = iterator(:,3);
tau = iterator(:,4);
n_blocks = iterator(:,5);
r_b = iterator(:,6);
block_dim = iterator(:,7);
theta = iterator(:,8);
share = iterator(:,9);


res_table = table(T,n,r_c,tau,n_blocks,r_b,block_dim,theta,share);

parfor i = 2:100
    
    
    Solution = arrayfun(@(TT,nn,rc,ta,nb,rb,bd,th,sh) ...
                        BQML_test(TT,nn,... %% T,n
                                   rc,1,0.5,...  %% r_c, q, mu
                                   'normal','normal',0,...   %% load_dist, idio_dist, idio autocorr
                                   ta,...                  %% idio cross corr
                                   nb,rb,... %% blocks number, factor per block
                                   bd, ...%% homogeneous or heterogenous block dimensions
                                   th,sh, ...%% noise to signal, share of missings
                                   3),...
                       res_table.T,res_table.n,res_table.r_c,res_table.tau,res_table.n_blocks,...
                       res_table.r_b,res_table.block_dim,res_table.theta,res_table.share) %%%

    abc = struct2table(Solution)
    location = strcat('simulation_results',filesep,'Exp_01',filesep,'table',string(i),'.csv')
    writetable(abc,location)
end



