import matplotlib.pyplot as plt
%matplotlib inline
# try:
#     import seaborn as sns
# except ImportError:
#     print("No seaborn installed. Oh well.")
    
import numpy as np 
# import pandas as pd
import astropy.io.fits as fits
from astropy.table import Table
import sherpa.astro.ui as ui
import astropy.modeling.models as models
from astropy.modeling.fitting import _fitter_to_model_params
from scipy.special import gammaln as scipy_gammaln
import os.path

# from clarsach.respond import RMF, ARF

"""
Explanation: Responses for RXTE HEXTE
End of explanation
"""


datadir = "./"
ui.load_data(id="p1", filename=datadir+"RXTE_HEXTE_ClusterA.fak")

d = ui.get_data("p1")

# conversion factor from keV to angstrom
c = 12.3984191

# This is the data in angstrom
bin_lo = d.bin_lo
bin_hi = d.bin_hi
print(bin_lo)
counts = d.counts
exposure = d.exposure

channel = d.channel

"""
Explanation: Sherpa Stuff
Daniela is doing some sherpa testing right now ...
End of explanation
"""


plt.figure(figsize=(10,7))
plt.plot(channel, counts)

"""
Explanation: RXTE does not have BIN_LO and BIN_HI set. Because of course it doesn't.
End of explanation
"""


arf_list = fits.open(datadir+"rxte_hexte_00may26_pwa.arf")

arf_list[1].data.field("ENERG_LO")[:10]

arf_list[1].data.columns

specresp = arf_list[1].data.field("SPECRESP")
energ_lo = arf_list[1].data.field("ENERG_LO")
energ_hi = arf_list[1].data.field("ENERG_HI")

energ_lo.shape

"""
Explanation: RXTE HEXTE has an ARF, just like a regular X-ray telescope (and unlike RXTE/PCA, which doesn't):
End of explanation
"""


rmf_list = fits.open(datadir+"rxte_hexte_97mar20c_pwa.rmf")
rmf_list[1].header["TUNIT1"]

rmf_list.info()

rmf_list["EBOUNDS"].columns

energ_lo = rmf_list["MATRIX"].data.field("ENERG_LO")
energ_hi = rmf_list["MATRIX"].data.field("ENERG_HI")

bin_lo = rmf_list["EBOUNDS"].data.field("E_MIN")
bin_hi = rmf_list["EBOUNDS"].data.field("E_MAX")
bin_mid = bin_lo + (bin_hi - bin_lo)/2.

"""
Explanation: Let's also load the rmf:
End of explanation
"""


arf = d.get_arf()

rmf = d.get_rmf()
rmf

"""
Explanation: Ok, so all of our files have the same units. This is good.
Let's also get the ARF and RMF from sherpa:
End of explanation
"""


from clarsach.models.powerlaw import Powerlaw

pl = Powerlaw(norm=1.0, phoindex=2.0)

m = pl.calculate(ener_lo=energ_lo, ener_hi=energ_hi)

plt.figure()
plt.loglog(energ_lo, m)

m_arf = arf.apply_arf(m)
m_rmf = rmf.apply_rmf(m_arf)

plt.figure()
plt.plot(bin_mid, counts, label="data")
plt.plot(bin_mid, m_rmf*1e5, label="model with RMF")
plt.legend()

"""
Explanation: Now we can make a model spectrum we can play around with! clarsach has an implementation of a Powerlaw model that matches the ISIS one that created the data:
End of explanation
"""


np.savetxt("../data/rxte_hexte_m_arf.txt", np.array([energ_lo, m_arf]).T)
np.savetxt("../data/rxte_hexte_m_rmf.txt", np.array([bin_mid, m_rmf]).T)

"""
Explanation: Let's save model with ARF and RMF applied:
End of explanation
"""


class PoissonLikelihood(object):
    
    def __init__(self, x_low, x_high, y, model, arf=None, rmf=None, exposure=1.0):
        self.x_low = x_low
        self.x_high = x_high
        self.y = y
        self.model = model
        self.arf = arf
        self.rmf = rmf
        self.exposure = exposure
        
    def evaluate(self, pars):
        # store the new parameters in the model

        self.model.norm = pars[0]
        self.model.phoindex = pars[1]
        
        # evaluate the model at the positions x
        mean_model = self.model.calculate(self.x_low, self.x_high)

        # run the ARF and RMF calculations
        if self.arf is not None:
            m_arf = self.arf.apply_arf(mean_model)
            
        else:
            m_arf = mean_model
            
        if self.rmf is not None:
            ymodel = self.rmf.apply_rmf(m_arf)
        else:
            ymodel = mean_model
                
        ymodel += 1e-20
        
        ymodel *= self.exposure
        # compute the log-likelihood
        loglike = np.sum(-ymodel + self.y*np.log(ymodel) \
               - scipy_gammaln(self.y + 1.))

        if np.isfinite(loglike):
            return loglike
        else:
            return -1.e16

    def __call__(self, pars):
        l = -self.evaluate(pars)
        #print(l)
        return l


loglike = PoissonLikelihood(energ_lo, energ_hi, counts, pl, arf=arf, rmf=rmf, exposure=exposure)
loglike([1.0, 2.0])

from scipy.optimize import minimize

opt = minimize(loglike, [1.0, 2.0], method="powell")

opt

m_fit = pl.calculate(energ_lo, energ_hi)
m_fit_arf = arf.apply_arf(m_fit)
m_fit_rmf = rmf.apply_rmf(m_fit_arf) * exposure

plt.figure()
plt.plot(bin_mid, counts, label="data")
plt.plot(bin_mid, m_fit_rmf, label="model with ARF")
plt.legend()

"""
Explanation: Okay, that looks pretty good!
Building a Model
Let's build a model for fitting a model to the data. We're going to do nothing fancy here, just a simple Poisson likelihood. It's similar to the one in the TestAthenaXIFU notebook, except it uses the Clarsach powerlaw function and integrates over bins.
End of explanation
"""


def apply_arf(spec, specresp, exposure=1.0):
    """
    Apply the anxilliary response to 
    a spectrum. 
    
    Parameters
    ----------
    spec : numpy.ndarray
        The source spectrum in flux units
        
    specresp: numpy.ndarray
        The response 
        
    exposure : float
        The exposure of the observation
        
    Returns
    -------
    spec_arf : numpy.ndarray
        The spectrum with the response applied.
    
    """
    spec_arf = spec*specresp*exposure
    return spec_arf

m_arf = apply_arf(m, arf.specresp)

m_arf_sherpa = arf.apply_arf(m)

np.allclose(m_arf, m_arf_sherpa)

plt.plot(m_arf, label="Clarsach ARF")
plt.plot(m_arf_sherpa, label="Sherpa ARF")
plt.legend()

"""
Explanation: The sherpa stuff works! Good!
Making Our Own ARF/RMF Classes
Ideally, we don't want to be dependent on the sherpa implementation.
We're now going to write our own implementations, and then test them on the model above.
Let's write a function that applies the ARF, which is just straightforward element-wise multiplication:
End of explanation
"""


def rmf_fold(spec, rmf, nchannels=None):
    
    #current_num_groups = 0
    #current_num_chans = 0
    
    nchannels = spec.shape[0]
    
    resp_idx = 0
    first_chan_idx = 0
    num_chans_idx =0
    counts_idx = 0
    
    counts = np.zeros(nchannels)
    
    for i in range(nchannels):
        source_bin_i = spec[i]
        current_num_groups = rmf.n_grp[i]
        
        while current_num_groups:
            counts_idx = int(rmf.f_chan[first_chan_idx] - rmf.offset)
            current_num_chans = rmf.n_chan[num_chans_idx]
            
            first_chan_idx += 1
            num_chans_idx +=1 
            
            while current_num_chans:
                counts[counts_idx] += rmf.matrix[resp_idx] * source_bin_i
                counts_idx += 1
                resp_idx += 1
                current_num_chans -= 1
            
            current_num_groups -= 1
            
    return counts




"""
Explanation: Let's look at the RMF, which is more complex. This requires a matrix multiplication. However, the response matrices are compressed to remove zeros and save space in memory, so they require a little more complex fiddling. Here's an implementation that is basically almost a line-by-line translation of the C++ code:
End of explanation
"""


def rmf_fold_vector(spec, rmf, nchannels=None):
    """
    Fold the spectrum through the redistribution matrix.
    
    Parameters
    ----------
    spec : numpy.ndarray
        The (model) spectrum to be folded
        
    rmf : sherpa.RMFData object
        The object with the RMF data
    
    """    
    # get the number of channels in the data
    nchannels = spec.shape[0]
    
    # an empty array for the output counts
    counts = np.zeros(nchannels)
    
    #print('len(nchannels): ' + str(nchannels))
    # index for n_chan and f_chan incrementation
    k = 0
    
    # index for the response matrix incrementation
    resp_idx = 0

    # loop over all channels
    for i in range(nchannels):
        
        # this is the current bin in the flux spectrum to 
        # be folded
        source_bin_i = spec[i]
        
        # get the current number of groups 
        current_num_groups = rmf.n_grp[i]
        
        for j in range(current_num_groups):
            counts_idx = int(rmf.f_chan[k] - rmf.offset)
            current_num_chans = int(rmf.n_chan[k])
            
            k += 1
            
            counts[counts_idx:counts_idx+current_num_chans] += rmf.matrix[resp_idx:resp_idx+current_num_chans] * source_bin_i
            resp_idx += current_num_chans
            
    return counts



"""
Explanation: Let's see if we can make this more vectorized:
End of explanation
"""


# not vectorized version
m_rmf = rmf_fold(m_arf, rmf)
%timeit m_rmf = rmf_fold(m_arf, rmf)

# vectorized version
m_rmf_v = rmf_fold_vector(m_arf, rmf)
%timeit m_rmf_v = rmf_fold_vector(m_arf, rmf)

# C++ (sherpa) version
m_rmf2 = rmf.apply_rmf(m_arf)
%timeit m_rmf2 = rmf.apply_rmf(m_arf)

"""
Explanation: Let's time the different implementations and compare them to the sherpa version (which is basically a wrapper around the C++):
End of explanation
"""


np.allclose(m_rmf_v[:len(m_rmf2)], m_rmf2)

np.allclose(m_rmf[:len(m_rmf2)], m_rmf2)

"""
Explanation: So my vectorized implementation is ~20 times slower than the sherpa version, and the non-vectorized version is really slow. But are they all the same?
End of explanation
"""


class RMF(object):
    
    def __init__(self, filename):
        
        self._load_rmf(filename)
        pass
    
    def _load_rmf(self, filename):
        """
        Load an RMF from a FITS file.
        
        Parameters
        ----------
        filename : str
            The file name with the RMF file
            
        Attributes
        ----------
        n_grp : numpy.ndarray
            the Array with the number of channels in each 
            channel set
        
        f_chan : numpy.ndarray
            The starting channel for each channel group;
            If an element i in n_grp > 1, then the resulting 
            row entry in f_chan will be a list of length n_grp[i];
            otherwise it will be a single number
            
        n_chan : numpy.ndarray
            The number of channels in each channel group. The same 
            logic as for f_chan applies
            
        matrix : numpy.ndarray
            The redistribution matrix as a flattened 1D vector
            
        energ_lo : numpy.ndarray
            The lower edges of the energy bins
        
        energ_hi : numpy.ndarray
            The upper edges of the energy bins
            
        detchans : int
            The number of channels in the detector
        
        """
        # open the FITS file and extract the MATRIX extension
        # which contains the redistribution matrix and 
        # anxillary information
        hdulist = fits.open(filename)

        # get all the extension names
        extnames = np.array([h.name for h in hdulist])

        # figure out the right extension to use
        if "MATRIX" in extnames:
            h = hdulist["MATRIX"]

        elif "SPECRESP MATRIX" in extnames:
            h = hdulist["SPECRESP MATRIX"]

        data = h.data
        hdr = h.header
        hdulist.close()
        
        # extract + store the attributes described in the docstring 
        n_grp = np.array(data.field("N_GRP"))
        f_chan = np.array(data.field('F_CHAN'))
        n_chan = np.array(data.field("N_CHAN"))
        matrix = np.array(data.field("MATRIX"))

        self.energ_lo = np.array(data.field("ENERG_LO"))
        self.energ_hi = np.array(data.field("ENERG_HI"))
        self.detchans = hdr["DETCHANS"]
        self.offset = self.__get_tlmin(h)

        # flatten the variable-length arrays
        self.n_grp, self.f_chan, self.n_chan, self.matrix = \
                self.__flatten_arrays(n_grp, f_chan, n_chan, matrix)
        
        return
    
    def __get_tlmin(self, h):
        """
        Get the tlmin keyword for `F_CHAN`.
        
        Parameters
        ----------
        h : an astropy.io.fits.hdu.table.BinTableHDU object
            The extension containing the `F_CHAN` column
            
        Returns
        -------
        tlmin : int
            The tlmin keyword
        """
        # get the header
        hdr = h.header
        # get the keys of all 
        keys = np.array(list(hdr.keys()))
        
        # find the place where the tlmin keyword is defined
        t = np.array(["TLMIN" in k for k in keys])
        
        # get the index of the TLMIN keyword
        tlmin_idx = np.hstack(np.where(t))[0]
        
        # get the corresponding value
        tlmin = np.int(list(hdr.items())[tlmin_idx][1])
        
        return tlmin
        
    def __flatten_arrays(self, n_grp, f_chan, n_chan, matrix):
        
        # find all non-zero groups
        nz_idx = (n_grp > 0)
        
        # stack all non-zero rows in the matrix
        matrix_flat = np.hstack(matrix[nz_idx])
        
        # some matrices actually have more elements
        # than groups in `n_grp`, so we'll only pick out
        # those values that have a correspondence in
        # n_grp
        f_chan_new = []
        n_chan_new = []
        for i,t in enumerate(nz_idx):
            if t:
                n = n_grp[i]
                f = f_chan[i]
                nc = n_chan[i]
                f_chan_new.append(f[:n])
                n_chan_new.append(nc[:n])

        n_chan_flat = np.hstack(n_chan_new)
        f_chan_flat = np.hstack(f_chan_new)

        # if n_chan is zero, we'll remove those as well.
        nz_idx2 = (n_chan_flat > 0)
        n_chan_flat = n_chan_flat[nz_idx2]
        f_chan_flat = f_chan_flat[nz_idx2]
        
        return n_grp, f_chan_flat, n_chan_flat, matrix_flat
            
    def apply_rmf(self, spec):
        """
        Fold the spectrum through the redistribution matrix.

        The redistribution matrix is saved as a flattened 1-dimensional 
        vector to save space. In reality, for each entry in the flux 
        vector, there exists one or more sets of channels that this 
        flux is redistributed into. The additional arrays `n_grp`, 
        `f_chan` and `n_chan` store this information:
            * `n_group` stores the number of channel groups for each 
              energy bin
            * `f_chan` stores the *first channel* that each channel 
              for each channel set 
            * `n_chan` stores the number of channels in each channel 
              set 
              
        As a result, for a given energy bin i, we need to look up the 
        number of channel sets in `n_grp` for that energy bin. We 
        then need to loop over the number of channel sets. For each 
        channel set, we look up the first channel into which flux 
        will be distributed as well as the number of channels in the 
        group. We then need to also loop over the these channels and 
        actually use the corresponding elements in the redistribution 
        matrix to redistribute the photon flux into channels. 
        
        All of this is basically a big bookkeeping exercise in making 
        sure to get the indices right.
        
        Parameters
        ----------
        spec : numpy.ndarray
            The (model) spectrum to be folded

        Returns
        -------
        counts : numpy.ndarray
            The (model) spectrum after folding, in 
            counts/s/channel

        """    

        # an empty array for the output counts
        counts = np.zeros_like(spec)

        # index for n_chan and f_chan incrementation
        k = 0

        # index for the response matrix incrementation
        resp_idx = 0

        # loop over all channels
        for i in range(spec.shape[0]):
            # this is the current bin in the flux spectrum to
            # be folded
            source_bin_i = spec[i]

            # get the current number of groups 
            current_num_groups = self.n_grp[i]

            # loop over the current number of groups
            for j in range(current_num_groups):

                current_num_chans = int(self.n_chan[k])

                if current_num_chans == 0:
                    k += 1
                    resp_idx += current_num_chans
                    continue


                else:
                    # get the right index for the start of the counts array 
                    # to put the data into
                    counts_idx = int(self.f_chan[k] - self.offset)
                    # this is the current number of channels to use
                    
                    k += 1
                    # add the flux to the subarray of the counts array that starts with 
                    # counts_idx and runs over current_num_chans channels
                    counts[counts_idx:counts_idx+current_num_chans] +=  self.matrix[resp_idx:resp_idx+current_num_chans] * \
                                                                        np.float(source_bin_i)
                    # iterate the response index for next round
                    resp_idx += current_num_chans


        return counts[:self.detchans]


"""
Explanation: They are! It looks like for this particular RXTE data set, it's working! 
Making an ARF/RMF Class
the ARF and RMF code would live well in a class, so let's wrap it into a class:
End of explanation
"""


rmf_new = RMF(datadir+"rxte_hexte_97mar20c_pwa.rmf")
m_rmf = rmf_new.apply_rmf(m_arf)

"""
Explanation: Let's make an object of that class and then make another model with the RMF applied:
End of explanation
"""


plt.figure(figsize=(10, 6))
plt.plot(m_rmf)
#plt.plot(m_rmf_v)

"""
Explanation: Hooray! What does the total spectrum look like?
End of explanation
"""


from clarsach import respond

rmf_c = respond.RMF(datadir+"rxte_hexte_97mar20c_pwa.rmf")

m_rmf_c = rmf_new.apply_rmf(m_arf)

np.allclose(m_rmf_c, m_rmf2)

plt.figure()
plt.plot(bin_mid, counts, label="data")
plt.plot(bin_mid, m_rmf_c*exposure, label="model", alpha=0.5)

"""
Explanation: There is, of course, also an implementation in clarsach:
End of explanation
"""


