
using PyCall
pygui(:qt)
using PyPlot
using DSP
using MAT
using DataFrames
push!(LOAD_PATH, "LOCALPKG/")
using LinearAcoustics_LOCAL
using MATLAB
#close("all")

SNR,Fs = 40.,8e3
room = 2
Nt = 560
t = 1000*collect(0:1/Fs:(Nt-1)/Fs)
Nf = floor(Int64,Nt/2)+1
f =collect(0:Fs/(2*Nf):(Nf-1)Fs/(2*Nf))./1000 
Nw = 700
Nm = 12
Ni = 50 
xmin = 30

results = [
   Dict("reg"=>"l2","model"=>"pwdm",  "src_opt" => 0, "w" => [], "w2" => [], "Ph" => [], "T" => []),
   Dict("reg"=>"l1","model"=>"pwdm",  "src_opt" => 0, "w" => [], "w2" => [], "Ph" => [], "T" => []),
   Dict("reg"=>"l21","model"=>"pwdm", "src_opt" => 0, "w" => [], "w2" => [], "Ph" => [], "T" => []),
   Dict("reg"=>"l1","model"=>"tesm",  "src_opt" => 0, "w" => [], "w2" => [], "Ph" => [], "T" => []),
   Dict("reg"=>"l1","model"=>"tesm",  "src_opt" => 1, "w" => [], "w2" => [], "Ph" => [], "T" => [])
]
	
for i = 1:length(results) 
#i = 4
	
		reg     = results[i]["reg"]
		src_opt = results[i]["src_opt"]
		model   = results[i]["model"]

		file = matopen(
		 "Data/P_Nw_$(Nw)_Nm_$(Nm)_Nt_$(Nt)_SNR_$(SNR)_$(reg)_Fs_$(Fs)_room_$(room)_srcopt$(src_opt)_$(model).mat")
		w     = read(file, "w")
		theta = read(file, "theta"    )
		phi   = read(file, "phi"      )
		close(file)

		if(model == "tesm")
			w =  w
		elseif(model == "pwdm")
			w =  hifft(w,Nt)
		end
			
		w /= vecnorm(abs(w),Inf)
		w = abs(w)
		println("$model $src_opt $reg compression: $(countnz(w)/length(w[:])*100)")

		prm = sortperm(theta)
		sort!(theta)
		wT = w[:,prm]
		w = 10*log10(w+1e-9)
		w[w.<-xmin] = -xmin
		wT = 10*log10(wT+1e-9)
		wT[wT.<-xmin] = -xmin
		

		results[i]["wT"] =  wT 
		results[i]["w"]  =  w
		results[i]["T"] =  theta 
		results[i]["Ph"] = phi 

end
		
figure(figsize=(5., 5.),dpi = dpi )
for kk = 1:length(results)

w = results[kk]["wT"]+xmin
theta = results[kk]["T"]

include("fig/mycp.jl")
indc = flipdim(floor(Int64,linspace(1,size(c,1),Nt)),1)
#cmap = get_cmap("summer")
c2 = irfft([rfft(c,1);zeros(152,3)],560,1)
l = linspace(5.,0.001,560)
dpi = 500

for i = 1:Nt

	polar(theta,w[i,:], c = (c[indc[i],1],
                                 c[indc[i],2],
				 c[indc[i],3]),
       linewidth=l[i])
	ylim([0,xmin])
	axis("off")
	savefig("Fig/fig/frames/a$(kk)_$(i).png",transparent = true)
	cla()

end

w = results[kk]["w"]+xmin
phi = results[kk]["Ph"]
for i = 1:Nt
	polar(phi+π/2,w[i,:], c = (c[indc[i],1],
                                 c[indc[i],2],
				 c[indc[i],3]),
       linewidth=l[i])
	ylim([0,xmin])
	axis("off")
	savefig("Fig/fig/frames/b$(kk)_$(i).png",transparent = true)
	cla()
end

end








