clc
clear
samples = 300;
nv=4;
data_samples =[100 300 500 800 1000 2000 3000]
for ind =1:1:size(data_samples,2)
    n =data_samples(ind);
for num =1:1:30
varm = 2.0.*eye(nv+1,nv+1)+rand(nv+1,nv+1);
varm = (varm+varm')./2;

 A = double(triu(rand(nv,nv) >= 0.30,1));
  Ad =A;
  AA =A;

  Ad =zeros(nv,nv);
  dmax =0.60*nv;
S_log = [];
for i =1:30
   S = rand(1,nv);
   S = double((S<=(1-1./dmax)));
   S_log = [S_log ; S];
   S = find(S==1);
    Ad = Ad | Learn_Acnestral_graph(S,nv,AA,varm,samples);
 end

[data Ut] = rand_dag_sample_f(AA,nv,zeros(1,n),varm,zeros(1,n),n);



for i =1:1:n
        val = data(i,:);
 for j =1:1:nv

    intv = Ad(:,j)';

    data1 = rand_dag_sample_f(AA,nv,intv,varm,val,n);
    U(i,j) = data(i,j) - mean(data1(:,j)); 

 end
  data1 = rand_dag_sample_f(AA,nv,ones(1,n),varm,val,n);
  U(i,nv+1) = data(i,nv+1) - mean(data1(:,nv+1));
end




 
 
 varmest = cov(U);
 
 varm;

Ed(num,ind)=(sqrt(sum(sum((varmest - varm).^2))));





for j = 0:1:2^nv-1
display("****************")
j+1
xxxx = decimalToBinaryVector(j,nv)
tmp_ind(j+1,:) = xxxx;
int = find(xxxx==0);
obs = find(xxxx==1);

sy = varmest(nv+1,obs);
sx = varmest(obs,obs);



syt = varm(nv+1,obs);
sxt = varm(obs,obs);


for i =1:1:n
 val = data(i,1:nv);
 V = U(i,obs);  
 datatmp = rand_dag_sample_f(AA,nv,ones(1,n),varm,val,n);
 Eest(i) =  mean(datatmp(:,nv+1))+  sy*inv(sx)*V';
  E(i) = data(i,nv+2);
  Vt = Ut(i,obs);
  E(i) = E(i) + syt*inv(sxt)*Vt';
end

Error(j+1) = sum(abs(Eest-E))./n
end
Error_F(ind,num,:)  = Error;
end


end

% tmpp = (abs(cov(Uapp)-var)./var).*100;
% max(max(tmpp))


save("data_inf_4_1.mat")
