import emcee
import corner
import numpy as np
import matplotlib.pyplot as plt

#---------------------------------------------

def log_likelihood(a0, a1, a2, a3, x, y, yerr):
    model = a0 * x**a1 * (1 - np.exp(-1 * a2 * x ** (-1 * a3)))
    sigma2 = yerr**2
    return -0.5 * np.sum((y - model) ** 2 / sigma2 + np.log(2*np.pi*sigma2))


def nll(theta, x, y, yerr):
    a0, a1, a2, a3 = theta
    return -log_likelihood(a0, a1, a2, a3, x, y, yerr)

def log_prior(a0, a1, a2, a3):
    if -1e10 < a0 < 1e10 and \
       -10 < a1 < 10 and \
       0.01< a2 < 1e10 and \
       -10 < a3 < 10:
        return 0.0
    return -np.inf

def log_probability(theta, x, y, yerr):
    a0, a1, a2, a3 = theta
    lp = log_prior(a0,a1,a2,a3)
    if not np.isfinite(lp):
        return -np.inf
    return lp + log_likelihood(a0,a1,a2,a3, x, y, yerr)
#---------------------------------------------

def norp_mcmc_fit(obsfreq, spec, spec_err, debug=False):
	# Preparation of MCMC 
	x = obsfreq
	y = spec
	yerr = spec_err

	#initial
	#norp_alpha
	galpha_tk = 2.9
	galpha_tn = -2.0

	#from plot
	gfluxpk = spec.max()
	gfreqpk = obsfreq[spec.argmax()]

	#Initial Guess From Yokoyama Program

	a1 = galpha_tk
	a3 = a1 - galpha_tn
	a0 = gfluxpk - (gfreqpk**a1)
	a2 = gfreqpk**a3
		
	gues =[a0,a1,a2,a3]
	
	#MCMC Loop
	loopCnt=0
	converged_flag = False
	while converged_flag != True:
		print("Guess:")
		print("a0 = {0:.3f}".format(gues[0]))
		print("a1 = {0:.3f}".format(gues[1]))
		print("a2 = {0:.3f}".format(gues[2]))
		print("a3 = {0:.3f}".format(gues[3]))
	
		pos = gues + 1e-4 * np.random.randn(32, 4)
		nwalkers, ndim = pos.shape

		sampler = emcee.EnsembleSampler(
    		nwalkers, ndim, log_probability, args=(x, y, yerr)
		)
		sampler.run_mcmc(pos, 10000, progress=True);

		fig, axes = plt.subplots(4, figsize=(10, 7), sharex=True)
		samples = sampler.get_chain()
		labels = ["a0", "a1", "a2", "a3"]
		
		for i in range(ndim):
			ax = axes[i]
			ax.plot(samples[:, :, i], "k", alpha=0.3)
			ax.set_xlim(0, len(samples))
			ax.set_ylabel(labels[i])
			ax.yaxis.set_label_coords(-0.1, 0.5)
			
		axes[-1].set_xlabel("step number");
		plt.show()

		flat_samples = sampler.get_chain(discard=3000, thin=15, flat=True)

		sol=[]
		for i in range(ndim):
			mcmc = np.percentile(flat_samples[:, i], [16, 50, 84])
			sol.append(mcmc[1])
            
		try:
				tau = sampler.get_autocorr_time()
            # ここに到達すれば「収束した（信頼できる）」と判定
				converged_flag = True
				print("norp_mcmc_fit: Converged!")
		except emcee.autocorr.AutocorrError:
			# エラーが発生した場合は「収束していない」と判定
				converged_flag = False
				if loopCnt >=10:
					print("norp_mcmc_fit: Not converged yet even 10 iterations. ")
					print("########################################")
					print("#### Fitting Process Terminated!!! #####")
					print("########################################")
					return sol, [], []
				else:
					print("norp_mcmc_fit: Not converged yet. Start re-fit using the result as the guess")
                
		gues =[sol[0],sol[1], sol[2], sol[3]]
		loopCnt = loopCnt +1
			
	#-------Loop End------------------
	
	tau = sampler.get_autocorr_time()
	wasu = np.max(tau) 
	flat_samples = sampler.get_chain(discard=int(wasu*3), thin=int(wasu/2.0), flat=True)
	sampNum = flat_samples.shape[0]

	fig = corner.corner(flat_samples, labels=labels)
	plt.show()
	sol=[]
	ferr = []
	
	for i in range(ndim):
		mcmc = np.percentile(flat_samples[:, i], [16, 50, 84])
		q = np.diff(mcmc)
		sol.append(mcmc[1])
		ferr.append(mcmc[0])
		ferr.append(mcmc[2])

	xx = (np.arange(1000)*0.1+0.9)
	yy = sol[0] * xx**sol[1] * (1 - np.exp(-1 * sol[2] * xx ** (-1 * sol[3])))
	
	tf = xx[np.argmax(yy)]
	tf_y = a2**(1./a3)
	pl = sol[3]-sol[1]
	plerr = np.sqrt(((ferr[3]-ferr[2])/2.)**2+((ferr[7]-ferr[6])/2.)**2)
	fitres =[pl, plerr, tf, tf_y] 
    
	inds = np.random.randint(len(flat_samples), size=int(sampNum*0.1))
	
	for ind in inds:
	    sample = flat_samples[ind]
	    yya = sample[0] * xx**sample[1] * (1 - np.exp(-1 * sample[2] * xx ** (-1 * sample[3])))
	    plt.plot(xx, yya, "C1", alpha=0.1)
	    
	plt.plot(obsfreq, spec,marker='.', ms=10, linewidth=0)
	plt.errorbar(obsfreq, spec, yerr=spec_err, fmt=".k", capsize=0)
	plt.plot(xx,yy, color='darkblue')	
	plt.xlabel('Frequency [GHz]')
	plt.ylabel('Solar Fluxes Stokes-I [SFU]')
	plt.axvline(tf, color="black", linestyle="--")
	plt.xscale('log')
	plt.yscale('log')
	plt.show()

		
	return sol, ferr, fitres

