#using PyCall
#pygui(:qt)
#using PyPlot

using DSP
using MAT
push!(LOAD_PATH, "LOCALPKG/")
using LinearAcoustics_LOCAL
using ProximalOperators_LOCAL,RegLS_LOCAL
#close("all")
srand(123)  # for reproducibility

env = AcEnv(8e3)  #acoustic environment Fs = 8e3, c =343 (default)

#choose model and regularization
reg, acmod, src_opt = NormL1,     tesm, 1  #l1  sTESM
#reg, acmod, src_opt = SqrNormL2,  tesm, 1  #Tik sTESM
#reg, acmod, src_opt = NormL21,    tesm, 1  #l21 sTESM

#reg, acmod, src_opt = NormL1,     tesm, 0  #l1   TESM
#reg, acmod, src_opt = SqrNormL2,  tesm, 0  #Tik  TESM
#reg, acmod, src_opt = NormL21,    tesm, 0  #l21  TESM

#reg, acmod, src_opt = NormL1,     pwdm, 0  #l1   PWDM
#reg, acmod, src_opt = SqrNormL2,  pwdm, 0  #Tik  PWDM
#reg, acmod, src_opt = NormL21,    pwdm, 0  #l21  PWDM

Solver = ZeroFPR

room = 2
SNR = 15.         # signal to noise ratio
Nm = 32            # number of microphones
K = 4             # K-fold cross validation
Nw =  700         #number of equivalent sources/plane wave directions
MaxIt,TOL = 3000,1e-5  #max iterations and tolerance for optimization
verb = 1

Nλ = 20          # number of λ tested 

Λ = logspace(0,log10(1e-6),Nλ) #vector of normalized tested λ
#Λ = linspace(1.,1e-3,Nλ)
cv_err   = zeros(length(Λ),K)
pr_err   = zeros(length(Λ))
fit_err  = zeros(length(Λ))
sp_lv  = zeros(length(Λ))

TT = 0.07                  #time window
Nt = round(Int64,env.Fs*TT)#time samples

include("chooseroom.jl")

#if src_opt == 1
#	Adj = w -> acmod(w,s,posw,posm0,Nt,env,true)
#	FwV = w -> acmod(w,s,posw,posV, Nt,env)
#else 
#	Adj = w -> acmod(w,posw,posm0,Nt,env,true)
#	FwV = w -> acmod(w,posw,posV, Nt,env)
#end
#
#if acmod == tesm
#	dom = Float64           #time domain
#	w = zeros(dom,Nt,Nw)
#elseif acmod == pwdm
#	dom = Complex{Float64}  #freq domain 
#	w = zeros(dom,floor(Int64,Nt/2)+1,Nw)
#end
#
##compute maximum λ
#if reg == NormL1
#	λmax = vecnorm(Adj(p_t0), Inf)  #maximum λ
#elseif reg == NormL21
#	λmax = vecnorm(sqrt(sum(abs2(Adj(p_t0)),1)), Inf)  #maximum λ
#elseif reg == SqrNormL2
#	λmax = vecnorm(Adj(p_t0))^2  #maximum λ
#end
#	Λ = Λ.*λmax  
#
#if K != 1   #k-fold cv active 
#
#	Ncv = round(Int64,Nm/K)                #number of mic used in CV
#	data_ind = reshape(randperm(Nm),Ncv,K) #indices used for CV
#
#	for l = 1:length(Λ)
#
#
#		for k = 1:K 
#		
#			slv = Solver(tol = TOL, maxit = MaxIt, verbose = verb) 
#			w = 0.*w
#
#			ind_cv = data_ind[:,k][:]                            #ind cross validation
#			ind_t  = data_ind[(data_ind.!= data_ind[:,k])[:]][:] #ind training
#
#			posm, p_t  = posm0.pos[:,ind_t], p_t0[:,ind_t]      #train mics 
#			poscv,p_cv = posm0.pos[:,ind_cv],p_t0[:,ind_cv]     #cv    mics 
#
#			if src_opt == 1
#				Fw  = w -> acmod(w,s,posw,posm, Nt,env)  #update models
#				Adj = w -> acmod(w,s,posw,posm, Nt,env,true)
#				Fwcv= w -> acmod(w,s,posw,poscv,Nt,env)
#		
#			else
#				Fw  = w -> acmod(w,posw,posm, Nt,env)    #update models
#				Adj = w -> acmod(w,posw,posm, Nt,env,true)
#				Fwcv= w -> acmod(w,posw,poscv,Nt,env)
#			end
#
#			println("\n $(k)-fold , λ/λmax = $(Λ[l]/λmax) $(l)/$(Nλ)")
#
#			w, slv =  solve(Fw, Adj, p_t, reg(Λ[l]), w, slv)
#			p_cv2 = Fwcv(w) 
#		
#			#compute cross validation error
#			cv_err[l,k] = avr_mse(p_cv,p_cv2,Nt)
#			println("fit error CV: $(cv_err[l,k]) nnz = $(countnz(w)) \n")
#
#		end
#
#        end
#
#	posm = posm0
#	p_t  = copy(p_t0)
#
#	if src_opt == 1
#		Fw  = w -> acmod(w,s,posw,posm, Nt,env)  #update models
#		Adj = w -> acmod(w,s,posw,posm, Nt,env,true)
#	else
#		Fw  = w -> acmod(w,posw,posm, Nt,env)  #update models
#		Adj = w -> acmod(w,posw,posm, Nt,env,true)
#	end
#
#
#	for l = 1:length(Λ)
#	
#		slv = Solver(tol = TOL, maxit = MaxIt, verbose = verb) 
#		w = 0.*w
#
#		println("full training, λ/λmax = $(Λ[l]/λmax) $(l)/$(Nλ)")
#                #full training
#
#		w, slv =  solve(Fw, Adj, p_t, reg(Λ[l]), w, slv)
#		p_V2 = FwV(w)
#		p_t2 = Fw(w)
#
#		#compute prediction error 
#		pr_err[l]  = avr_mse(p_V,p_V2,Nt)
#		#compute fit error error 
#		fit_err[l] = avr_mse(p_t,p_t2,Nt)
#		sp_lv[l] = countnz(w)
#	        println("prediction err: $(pr_err[l]) nnz = $(countnz(w)) \n fit err: $(fit_err[l]) \n")
#
#	end
#
#	λ = Λ[indmin(mean(cv_err,2))] #optimal λ
#else
#	λ = 1.*Λ[1] #try with a single λ
#end
#
###############################
##    use all training set    #
##         with opt λ         #
###############################
#
#println("full training, optimal λ/λmax = $(λ/λmax)")
#posm = posm0
#p_t  = copy(p_t0)
#if src_opt == 1
#	Fw  = w ->  acmod(w,s,posw,posm,Nt,env)
#	Adj = w ->  acmod(w,s,posw,posm,Nt,env,true)
#else
#	Fw  = w ->  acmod(w,posw,posm,Nt,env)
#	Adj = w ->  acmod(w,posw,posm,Nt,env,true)
#end
#
#@time w, slv =  solve(Fw, Adj, p_t, reg(λ), 0.*w, 
#		 Solver(tol = TOL, maxit = MaxIt))
#p_t2 = Fw(w)
#p_V2 = FwV(w)
#
##compute prediction error 
#pr_err_opt  = avr_mse(p_V,p_V2,Nt)
##compute fit error error 
#fit_err_opt = avr_mse(p_t,p_t2,Nt)
#sp_lv_opt = countnz(w)
#
#println("fit error at mic: $(fit_err_opt)")
#println("prediction error in area: $(pr_err_opt)")
#println("cost function: $(0.5*vecnorm(p_t-p_t2)^2+reg(λ)(w) )")
#
#cv_err_m = mean(cv_err,2)
#if acmod == pwdm
#	p_t2 = hifft(p_t2,Nt)
#	p_t  = hifft(p_t,Nt)
#	p_V2 = hifft(p_V2,Nt)
#	p_V  = hifft(p_V,Nt)
#end
#
#if K!=1
#include("save_stuff.jl")
#
##figure()
##subplot(2,1,1)
##semilogx(Λ./λmax,10*log10(cv_err_m),":*")
##semilogx(Λ./λmax,10*log10(minimum(cv_err,2)),":k")
##semilogx(Λ./λmax,10*log10(maximum(cv_err,2)),":k")
##semilogx(Λ[indmin(cv_err_m)]./λmax,10*log10(cv_err_m[indmin(cv_err_m)]),"ro")
##title("cross validation error")
##subplot(2,1,2)
##semilogx(Λ./λmax,10*log10(pr_err),":*")
##semilogx(Λ[indmin(pr_err)]./λmax, 10*log10(pr_err[indmin(pr_err)]), "ro")
##title("ir interpolation error")
##xlabel("Λ")
#end
#
#quit()
#
#
#
#
#
#
