#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Copyright 2015 Pierre Paleo <pierre.paleo@esrf.fr>
#  License: BSD
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
#  * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
#  * Neither the name of ESRF nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE


from __future__ import absolute_import
from __future__ import print_function


from __future__ import division
import numpy as np
import astra

class AstraToolbox:
    """
    ASTRA toolbox wrapper for parallel beam geometry.
    """

    def __init__(self, n_x, n_y, angles, dwidth=None, rot_center=None, fullscan=False, super_sampling=None):
        """
        Initialize the ASTRA toolbox with a simple parallel configuration.
        The image is assumed to be square, and the detector count is equal to the number of rows/columns.

        n_x : integer
            number of pixels of the X (columns) dimension
        n_y : integer
            nimber of pixels of the Y (rows) dimension
        angles : integer or numpy.ndarray
            number of projection angles (if integer), or custom series of angles
        dwidth : integer
            detector width (number of pixels). If not provided, max(n_x, n_y) is taken.
        rot_center : float
            user-defined rotation center
        fullscan : boolean
            if True, use a 360 scan configuration
        super_sampling : integer
            Detector and Pixel supersampling
        """

        angle_max = np.pi
        if fullscan: angle_max *= 2
        if isinstance(angles, int):
            angles = np.linspace(0, angle_max, angles, False)
        n_angles = angles.shape[0]
        if dwidth is None: dwidth = max(n_x, n_y)

        self.vol_geom = astra.create_vol_geom(n_x, n_y)
        self.proj_geom = astra.create_proj_geom('parallel', 1.0, dwidth, angles)

        if rot_center:
            o_angles = np.ones(n_angles) if isinstance(n_angles, int) else np.ones_like(n_angles)
            self.proj_geom['option'] = {'ExtraDetectorOffset': (rot_center - n_x / 2.) * o_angles}
        self.proj_id = astra.create_projector('cuda', self.proj_geom, self.vol_geom)

        # vg : Volume geometry
        self.vg = astra.projector.volume_geometry(self.proj_id)
        # pg : projection geometry
        self.pg = astra.projector.projection_geometry(self.proj_id)

        # ---- Configure Projector ------
        # sinogram shape
        self.sshape = astra.functions.geom_size(self.pg)
        # Configure projector
        self.cfg_proj = astra.creators.astra_dict('FP_CUDA')
        self.cfg_proj['ProjectorId'] = self.proj_id
        if super_sampling:
            self.cfg_proj['option'] = {'DetectorSuperSampling':super_sampling}

        # ---- Configure Backprojector ------
        # volume shape
        self.vshape = astra.functions.geom_size(self.vg)
        # Configure backprojector
        self.cfg_backproj = astra.creators.astra_dict('BP_CUDA')
        self.cfg_backproj['ProjectorId'] = self.proj_id
        if super_sampling:
            self.cfg_backproj['option'] = {'PixelSuperSampling':super_sampling}
        # -------------------
        self.n_x = n_x
        self.n_y = n_y
        self.dwidth = dwidth
        self.n_a = angles.shape[0]
        self.rot_center = rot_center if rot_center else dwidth//2
        self.angles = angles


    def __checkArray(self, arr):
        if arr.dtype != np.float32:
            arr = arr.astype(np.float32)
        if arr.flags['C_CONTIGUOUS']==False:
            arr = np.ascontiguousarray(arr)
        return arr


    def backproj(self, s, filt=False):
        if filt is True:
            sino = self.filter_projections(s)
        else:
            sino = s
        sino = self.__checkArray(sino)
        # In
        sid = astra.data2d.link('-sino', self.pg, sino)
        self.cfg_backproj['ProjectionDataId'] = sid
        # Out
        v = np.zeros(self.vshape, dtype=np.float32)
        vid = astra.data2d.link('-vol', self.vg, v)
        self.cfg_backproj['ReconstructionDataId'] = vid

        bp_id = astra.algorithm.create(self.cfg_backproj)
        astra.algorithm.run(bp_id)
        astra.algorithm.delete(bp_id)
        astra.data2d.delete([sid, vid])
        return v


    def proj(self, v):
        v = self.__checkArray(v)
        # In
        vid = astra.data2d.link('-vol', self.vg, v)
        self.cfg_proj['VolumeDataId'] = vid
        # Out
        s = np.zeros(self.sshape, dtype=np.float32)
        sid = astra.data2d.link('-sino',self.pg, s)
        self.cfg_proj['ProjectionDataId'] = sid

        fp_id = astra.algorithm.create(self.cfg_proj)
        astra.algorithm.run(fp_id)
        astra.algorithm.delete(fp_id)
        astra.data2d.delete([vid, sid])
        return s



    def filter_projections(self, sino):
        nb_angles, l_x = sino.shape
        ramp = 1./l_x * np.hstack((np.arange(l_x), np.arange(l_x, 0, -1)))
        return np.fft.ifft(ramp * np.fft.fft(sino, 2*l_x, axis=1), axis=1)[:, :l_x].real


    def run_algorithm(self, alg, n_it, data):
        rec_id = astra.data2d.create('-vol', self.vol_geom)
        sino_id = astra.data2d.create('-sino', self.proj_geom, data)
        cfg = astra.astra_dict(alg)
        cfg['ReconstructionDataId'] = rec_id
        cfg['ProjectionDataId'] = sino_id
        alg_id = astra.algorithm.create(cfg)
        print(("Running %s" %alg))
        astra.algorithm.run(alg_id, n_it)
        rec = astra.data2d.get(rec_id)
        astra.algorithm.delete(alg_id)
        astra.data2d.delete(rec_id)
        astra.data2d.delete(sino_id)
        return rec


    def fbp(self, sino):
        """
        Runs the Filtered Back-Projection algorithm on the provided sinogram.

        sino : numpy.ndarray
            sinogram. Its shape must be consistent with the current tomography configuration
        """
        return self.backproj(sino, filt=True)


    def cleanup(self):
        astra.data2d.delete(self.proj_id)


#~ def clipCircle(x): # in-place !
    #~ return astra.extrautils.clipCircle(x)


def generate_coords(img_shp, center=None):
    R, C = np.indices(img_shp, dtype=np.float64)
    if center is None:
        center0, center1 = img_shp[0] / 2., img_shp[1] / 2.
    else:
        center0, center1 = center
    R += 0.5 - center0
    C += 0.5 - center1
    return R, C


def clipCircle(x): # out-of-place !
    res = np.copy(x)
    R, C = generate_coords(x.shape)
    res[R**2 + C**2 > (min(x.shape)//2)**2] = 0
    return res










