#! /usr/bin/python3
# -*- coding: utf-8 -*-

"""
    ****
    Beam
    ****
"""

__author__ = 'Alan Loh'
__copyright__ = 'Copyright 2020, nenupy'
__credits__ = ['Alan Loh']
__maintainer__ = 'Alan'
__email__ = 'alan.loh@obspm.fr'
__status__ = 'Production'
__all__ = [
    'Beam',
    'ABeam',
    'DBeam'
]

import numpy as np
import astropy.units as u
from astropy.coordinates import ICRS, SkyCoord, AltAz
from astropy.time import Time
from healpy.pixelfunc import get_interp_val

from nenupy.instru import (
    nenufar_ant_gain,
    desquint_elevation,
    analog_pointing,
    ma_antpos,
    ma_info,
    ma_pos
)
from nenupy.astro import (
    wavelength,
    toAltaz,
    ho_coord
)

import logging
log = logging.getLogger(__name__)

# ============================================================= #
# --------------------------- Beam ---------------------------- #
# ============================================================= #
class Beam(object):
    """
    """

    def __init__(self, freq, polar):
        self.freq = freq
        self.polar = polar

    # --------------------------------------------------------- #
    # --------------------- Getter/Setter --------------------- #
    @property
    def freq(self):
        return self._freq
    @freq.setter
    def freq(self, f):
        if not isinstance(f, u.Quantity):
            f *= u.MHz
        if not f.isscalar:
            raise ValueError(
                'Only scalar frequency allowed'
            )
        self._freq = f
        log.info(
            'Frequency sets at {}'.format(self._freq)
        )
        return

    @property
    def polar(self):
        return self._polar
    @polar.setter
    def polar(self, p):
        if not np.isscalar(p):
            raise ValueError(
                'Only scalar polar allowed'
            )
        allowed = ['NW', 'NE']
        if p.upper() not in allowed:
            raise ValueError(
                'Polarization {} not in {}'.format(
                    p,
                    allowed
                )
            )
        self._polar = p.upper()
        log.info(
            'Polarization sets at {}'.format(self._polar)
        )
        return

    # --------------------------------------------------------- #
    # ------------------------ Methods ------------------------ #
    def ant_gain(self, coords, time):
        """ Returns NenuFAR antenna gain values interpolated at
            coordinates ``coords`` at time ``time``.

            :param coords:
            :type coords: :class:`~astropy.coordinates.ICRS` or
                :class:`~astropy.coordinates.SkyCoord`
            :param time:
            :type time: :class:`~astropy.time.Time`

            :returns: NenuFAR normalized antenna gain
            :rtype: `~numpy.ndarray`

            :Example:
                To get back the HEALPix ant gain:

                >>> from nenupy.beam import Beam
                >>> import numpy as np
                >>> import astropy.units as u
                >>> from astropy.coordinates import ICRS
                >>> from astropy.time import Time
                >>> from healpy.pixelfunc import nside2npix, pix2ang
                >>> from healpy.visufunc import mollview
                >>> b = Beam(
                        freq=50,
                        polar='NE',
                    )
                >>> npix = nside2npix(nside=32)
                >>> ra, dec = pix2ang(
                        nside=32,
                        ipix=np.arange(npix),
                        lonlat=True
                    )
                >>> gain = b.ant_gain(
                        coords=ICRS(
                            ra=ra*u.deg,
                            dec=dec*u.deg
                        ),
                        time=Time.now()
                    )
                >>> mollview(gain)

        """
        if not isinstance(coords, (ICRS, SkyCoord)):
            raise TypeError(
                'coords should be ICRS or SkyCoord object'
            )
        if not isinstance(time, Time):
            raise TypeError(
                'time should be Time object'
            )
        hpxgain = nenufar_ant_gain(
            freq=self.freq,
            polar=self.polar,
            nside=32,
            time=time
        )
        log.info(
            'NenuFAR HEALPix antenna gain loaded.'
        )
        vals = get_interp_val(
            m=hpxgain,
            theta=coords.ra.deg,
            phi=coords.dec.deg,
            lonlat=True
        )
        log.info(
            'NenuFAR antenna gain values interpolated.'
        )
        return vals

    def array_factor(self, phase_center, coords, antpos):
        """
        """
        if not (isinstance(phase_center, AltAz) or hasattr(phase_center, 'altaz')):
            raise TypeError(
                'phase_center should be an AltAz instance'
            )
        if not (isinstance(coords, AltAz) or hasattr(coords, 'altaz')):
            raise TypeError(
                'coords should be an AltAz instance'
            )
        if not isinstance(antpos, np.ndarray):
            raise TypeError(
                'antpos should be an np.ndarray instance'
            )
        if antpos.shape[1] != 3:
            raise IndexError(
                'antpos should have 2nd dimension = 3 (x, y, z)'
            )
        def get_phi(az, el, antpos):
            """ az, el in radians
            """
            xyz_proj = np.array(
                [
                    np.cos(az) * np.cos(el),
                    np.sin(az) * np.cos(el),
                    np.sin(el)
                ]
            )
            antennas = np.array(antpos)
            phi = np.dot(antennas, xyz_proj)
            return phi
        phi0 = get_phi(
            az=[phase_center.az.rad],
            el=[phase_center.alt.rad],
            antpos=antpos
        )
        phi_grid = get_phi(
            az=coords.az.rad,
            el=coords.alt.rad,
            antpos=antpos
        )
        delay = phi_grid - phi0
        coeff = 2j * np.pi / wavelength(self.freq).value
        af = np.sum(np.exp(coeff*delay), axis=0)
        return np.real(af * af.conjugate())
    # --------------------------------------------------------- #
    # ----------------------- Internal ------------------------ #

# ============================================================= #

# ============================================================= #
# --------------------------- Beam ---------------------------- #
# ============================================================= #
class ABeam(Beam):
    """
    """

    def __init__(self, freq, polar, azana, elana, ma=0):
        super().__init__(
            freq=freq,
            polar=polar
        )
        self.azana = azana
        self.elana = elana
        self.ma = ma
        self.squint_freq = 30*u.MHz
        self.beamsquint = True

    # --------------------------------------------------------- #
    # --------------------- Getter/Setter --------------------- #
    @property
    def azana(self):
        """
        """
        return self._azana
    @azana.setter
    def azana(self, a):
        if not isinstance(a, u.Quantity):
            a *= u.deg
        self._azana = a
        log.info(
            'Desired analog azimuth: {}'.format(self._azana)
        )
        return

    @property
    def elana(self):
        """
        """
        return self._elana
    @elana.setter
    def elana(self, e):
        if not isinstance(e, u.Quantity):
            e *= u.deg
        self._elana = e
        log.info(
            'Desired analog elevation: {}'.format(self._elana)
        )
        return

    @property
    def ma(self):
        return self._ma
    @ma.setter
    def ma(self, m):
        if not isinstance(m, (int, np.integer)):
            raise TypeError(
                'ma should be integer'
            )
        max_ma_name = ma_info['ma'].size - 1
        if m > max_ma_name:
            raise ValueError(
                'select a MA name <= {}'.format(
                    max_ma_name
                )
            )
        self._ma = m
        self._rot = ma_info['rot'][ma_info['ma'] == m][0]
        log.info(
            'MA {} selected (rotation {} mod 60 deg)'.format(
                m,
                self._rot%60
            )
        )
        return

    @property
    def squint_freq(self):
        return self._squint_freq
    @squint_freq.setter
    def squint_freq(self, f):
        if not isinstance(f, u.Quantity):
            f *= u.MHz
        if not f.isscalar:
            raise ValueError(
                'Only scalar squint_freq allowed'
            )
        self._squint_freq = f
        log.info(
            'Squint frequency sets at {}'.format(f)
        )
        return

    @property
    def beamsquint(self):
        return self._beamsquint
    @beamsquint.setter
    def beamsquint(self, b):
        if not isinstance(b, bool):
            raise TypeError(
                'beamsquint should be a boolean'
            )
        self._beamsquint = b
        if b:
            log.info(
                'Beam squint correction activated.'
            )
        else:
            log.info(
                'No beam squint correction.'
            )

    # --------------------------------------------------------- #
    # ------------------------ Methods ------------------------ #
    def beam_values(self, coords, time):
        """
            :param coords:
            :type coords: :class:`~astropy.coordinates.ICRS` or
                :class:`~astropy.coordinates.SkyCoord`
            :param time:
            :type time: :class:`~astropy.time.Time`
        """
        if not isinstance(coords, (ICRS, SkyCoord)):
            raise TypeError(
                'coords should be ICRS or SkyCoord object'
            )
        if coords.isscalar:
            raise ValueError('coords should not be a scalar.')
        if not isinstance(time, Time):
            raise TypeError(
                'time should be Time object'
            )
        # Real pointing
        if self.beamsquint:
            el = desquint_elevation(
                elevation=self.elana,
                opt_freq=self.squint_freq
            )
        else:
            el = self.elana.copy()
        az, el = analog_pointing(self.azana, el)
        log.info(
            'Effective analog pointing=({}, {})'.format(
                az,
                el
            )
        )
        # Array factor
        phase_center = ho_coord(
                az=az,
                alt=el,
                time=time
        )
        altazcoords = toAltaz(
            skycoord=coords,
            time=time
        )
        arrfac = self.array_factor(
            phase_center=phase_center,
            coords=altazcoords,
            antpos=ma_antpos(
                rot=self._rot
            )
        )
        # Antenna Gain
        antgain = self.ant_gain(
            coords=coords,
            time=time
        )
        anagain = arrfac * antgain
        log.info(
            'Anabeam (rot {}) computed for {} pixels.'.format(
                self._rot%60,
                anagain.size
            )
        )
        return anagain
# ============================================================= #

# ============================================================= #
# --------------------------- Beam ---------------------------- #
# ============================================================= #
class DBeam(Beam):
    """
    """

    def __init__(self, freq, polar, azdig, eldig, ma,
        azana=None, elana=None, squint_freq=30, beamsquint=True):
        super().__init__(
            freq=freq,
            polar=polar
        )
        self.azdig = azdig
        self.eldig = eldig
        self.ma = ma
        self.azana = azdig if azana is None else azana
        self.elana = eldig if elana is None else elana
        self.squint_freq = squint_freq
        self.beamsquint = beamsquint

    # --------------------------------------------------------- #
    # --------------------- Getter/Setter --------------------- #
    @property
    def azdig(self):
        """
        """
        return self._azdig
    @azdig.setter
    def azdig(self, a):
        if not isinstance(a, u.Quantity):
            a *= u.deg
        self._azdig = a
        log.info(
            'Digital azimuth: {}'.format(self._azdig)
        )
        return

    @property
    def eldig(self):
        """
        """
        return self._eldig
    @eldig.setter
    def eldig(self, e):
        if not isinstance(e, u.Quantity):
            e *= u.deg
        self._eldig = e
        log.info(
            'Digital elevation: {}'.format(self._eldig)
        )
        return

    @property
    def ma(self):
        return self._ma
    @ma.setter
    def ma(self, m):
        if isinstance(m, list):
            m = np.array(m)
        if np.isscalar(m):
            raise ValueError(
                'ma should at list be of length 2'
            )
        if not np.isin(m, ma_info['ma']).all():
            raise ValueError(
                'Some MA names are > {}'.format(
                    ma_info['ma'].max()
                )
            )
        self._ma = m.astype(int)
        log.info(
            'MAs {} selected for digital beam.'.format(
                self._ma
            )
        )
        return

    # --------------------------------------------------------- #
    # ------------------------ Methods ------------------------ #
    def beam_values(self, coords, time):
        """
            :param coords:
            :type coords: :class:`~astropy.coordinates.ICRS` or
                :class:`~astropy.coordinates.SkyCoord`
            :param time:
            :type time: :class:`~astropy.time.Time`
        """
        if not isinstance(coords, (ICRS, SkyCoord)):
            raise TypeError(
                'coords should be ICRS or SkyCoord object'
            )
        if not isinstance(time, Time):
            raise TypeError(
                'time should be Time object'
            )

        # Build the Mini-Array 'summed' response
        abeams = {}
        for ma in self.ma:
            rot = ma_info['rot'][ma_info['ma'] == ma][0]
            if str(rot%60) not in abeams.keys():
                ana = ABeam(
                    freq=self.freq,
                    polar=self.polar,
                    azana=self.azana,
                    elana=self.elana,
                    ma=ma
                )
                ana.beamsquint = self.beamsquint
                anavals = ana.beam_values(
                    coords=coords,
                    time=time
                )
                abeams[str(rot%60)] = anavals.copy()
            if not 'summa' in locals():
                summa = abeams[str(rot%60)]
            else:
                summa += abeams[str(rot%60)]
         # Array factor
        phase_center = ho_coord(
                az=self.azdig,
                alt=self.eldig,
                time=time
        )
        altazcoords = toAltaz(
            skycoord=coords,
            time=time
        )
        arrfac = self.array_factor(
            phase_center=phase_center,
            coords=altazcoords,
            antpos=ma_pos[np.isin(ma_info['ma'], self.ma)]
        )
        # Arrayfactor * summed MA response
        digigain = arrfac * summa
        log.info(
            'Digibeam computed for {} pixels.'.format(
                digigain.size
            )
        )
        return digigain
# ============================================================= #


#   Copyright 2020 The PyMC Developers
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
import warnings

from typing import (
    Callable,
    Dict,
    Generator,
    Iterable,
    List,
    Optional,
    Set,
    Tuple,
    Union,
)

import aesara
import aesara.tensor as at
import numpy as np
import scipy.sparse as sps

from aeppl.logprob import CheckParameterValue
from aesara import config, scalar
from aesara.compile.mode import Mode, get_mode
from aesara.gradient import grad
from aesara.graph import local_optimizer
from aesara.graph.basic import (
    Apply,
    Constant,
    Variable,
    clone_get_equiv,
    graph_inputs,
    walk,
)
from aesara.graph.fg import FunctionGraph
from aesara.graph.op import Op, compute_test_value
from aesara.sandbox.rng_mrg import MRG_RandomStream as RandomStream
from aesara.tensor.elemwise import Elemwise
from aesara.tensor.random.op import RandomVariable
from aesara.tensor.shape import SpecifyShape
from aesara.tensor.sharedvar import SharedVariable
from aesara.tensor.subtensor import AdvancedIncSubtensor, AdvancedIncSubtensor1
from aesara.tensor.var import TensorConstant, TensorVariable

from pymc.exceptions import ShapeError
from pymc.vartypes import continuous_types, int_types, isgenerator, typefilter

PotentialShapeType = Union[
    int, np.ndarray, Tuple[Union[int, Variable], ...], List[Union[int, Variable]], Variable
]

__all__ = [
    "gradient",
    "hessian",
    "hessian_diag",
    "inputvars",
    "cont_inputs",
    "floatX",
    "intX",
    "smartfloatX",
    "jacobian",
    "CallableTensor",
    "join_nonshared_inputs",
    "make_shared_replacements",
    "generator",
    "set_at_rng",
    "at_rng",
    "take_along_axis",
    "pandas_to_array",
]

def pandas_to_array(data):
    """Convert a pandas object to a NumPy array.

    XXX: When `data` is a generator, this will return an Aesara tensor!

    """
    if hasattr(data, "to_numpy") and hasattr(data, "isnull"):
        # typically, but not limited to pandas objects
        vals = data.to_numpy()
        null_data = data.isnull()
        if hasattr(null_data, "to_numpy"):
            # pandas Series
            mask = null_data.to_numpy()
        else:
            # pandas Index
            mask = null_data
        if mask.any():
            # there are missing values
            ret = np.ma.MaskedArray(vals, mask)
        else:
            ret = vals
    elif isinstance(data, np.ndarray):
        if isinstance(data, np.ma.MaskedArray):
            if not data.mask.any():
                # empty mask
                ret = data.filled()
            else:
                # already masked and rightly so
                ret = data
        else:
            # already a ndarray, but not masked
            mask = np.isnan(data)
            if np.any(mask):
                ret = np.ma.MaskedArray(data, mask)
            else:
                # no masking required
                ret = data
    elif isinstance(data, Variable):
        ret = data
    elif sps.issparse(data):
        ret = data
    elif isgenerator(data):
        ret = generator(data)
    else:
        ret = np.asarray(data)

    # type handling to enable index variables when data is int:
    if hasattr(data, "dtype"):
        if "int" in str(data.dtype):
            return intX(ret)
        # otherwise, assume float:
        else:
            return floatX(ret)
    # needed for uses of this function other than with pm.Data:
    else:
        return floatX(ret)

def change_rv_size(
    rv_var: TensorVariable,
    new_size: PotentialShapeType,
    expand: Optional[bool] = False,
) -> TensorVariable:
    """Change or expand the size of a `RandomVariable`.

    Parameters
    ==========
    rv_var
        The `RandomVariable` output.
    new_size
        The new size.
    expand:
        Expand the existing size by `new_size`.

    """
    # Check the dimensionality of the `new_size` kwarg
    new_size_ndim = np.ndim(new_size)
    if new_size_ndim > 1:
        raise ShapeError("The `new_size` must be ≤1-dimensional.", actual=new_size_ndim)
    elif new_size_ndim == 0:
        new_size = (new_size,)

    # Extract the RV node that is to be resized, together with its inputs, name and tag
    if isinstance(rv_var.owner.op, SpecifyShape):
        rv_var = rv_var.owner.inputs[0]
    rv_node = rv_var.owner
    rng, size, dtype, *dist_params = rv_node.inputs
    name = rv_var.name
    tag = rv_var.tag

    if expand:
        if rv_node.op.ndim_supp == 0 and at.get_vector_length(size) == 0:
            size = rv_node.op._infer_shape(size, dist_params)
        new_size = tuple(new_size) + tuple(size)

    # Make sure the new size is a tensor. This dtype-aware conversion helps
    # to not unnecessarily pick up a `Cast` in some cases (see #4652).
    new_size = at.as_tensor(new_size, ndim=1, dtype="int64")

    new_rv_node = rv_node.op.make_node(rng, new_size, dtype, *dist_params)
    rv_var = new_rv_node.outputs[-1]
    rv_var.name = name
    for k, v in tag.__dict__.items():
        rv_var.tag.__dict__.setdefault(k, v)

    if config.compute_test_value != "off":
        compute_test_value(new_rv_node)

    return rv_var

def extract_rv_and_value_vars(
    var: TensorVariable,
) -> Tuple[TensorVariable, TensorVariable]:
    """Return a random variable and it's observations or value variable, or ``None``.

    Parameters
    ==========
    var
        A variable corresponding to a ``RandomVariable``.

    Returns
    =======
    The first value in the tuple is the ``RandomVariable``, and the second is the
    measure/log-likelihood value variable that corresponds with the latter.

    """
    if not var.owner:
        return None, None

    if isinstance(var.owner.op, RandomVariable):
        rv_value = getattr(var.tag, "observations", getattr(var.tag, "value_var", None))
        return var, rv_value

    return None, None

def extract_obs_data(x: TensorVariable) -> np.ndarray:
    """Extract data from observed symbolic variables.

    Raises
    ------
    TypeError

    """
    if isinstance(x, Constant):
        return x.data
    if isinstance(x, SharedVariable):
        return x.get_value()
    if x.owner and isinstance(x.owner.op, (AdvancedIncSubtensor, AdvancedIncSubtensor1)):
        array_data = extract_obs_data(x.owner.inputs[0])
        mask_idx = tuple(extract_obs_data(i) for i in x.owner.inputs[2:])
        mask = np.zeros_like(array_data)
        mask[mask_idx] = 1
        return np.ma.MaskedArray(array_data, mask)

    raise TypeError(f"Data cannot be extracted from {x}")

def walk_model(
    graphs: Iterable[TensorVariable],
    walk_past_rvs: bool = False,
    stop_at_vars: Optional[Set[TensorVariable]] = None,
    expand_fn: Callable[[TensorVariable], Iterable[TensorVariable]] = lambda var: [],
) -> Generator[TensorVariable, None, None]:
    """Walk model graphs and yield their nodes.

    By default, these walks will not go past ``RandomVariable`` nodes.

    Parameters
    ==========
    graphs
        The graphs to walk.
    walk_past_rvs
        If ``True``, the walk will not terminate at ``RandomVariable``s.
    stop_at_vars
        A list of variables at which the walk will terminate.
    expand_fn
        A function that returns the next variable(s) to be traversed.
    """
    if stop_at_vars is None:
        stop_at_vars = set()

    def expand(var):
        new_vars = expand_fn(var)

        if (
            var.owner
            and (walk_past_rvs or not isinstance(var.owner.op, RandomVariable))
            and (var not in stop_at_vars)
        ):
            new_vars.extend(reversed(var.owner.inputs))

        return new_vars

    yield from walk(graphs, expand, False)

def replace_rvs_in_graphs(
    graphs: Iterable[TensorVariable],
    replacement_fn: Callable[[TensorVariable], Dict[TensorVariable, TensorVariable]],
    initial_replacements: Optional[Dict[TensorVariable, TensorVariable]] = None,
    **kwargs,
) -> Tuple[TensorVariable, Dict[TensorVariable, TensorVariable]]:
    """Replace random variables in graphs

    This will *not* recompute test values.

    Parameters
    ==========
    graphs
        The graphs in which random variables are to be replaced.

    Returns
    =======
    Tuple containing the transformed graphs and a ``dict`` of the replacements
    that were made.
    """
    replacements = {}
    if initial_replacements:
        replacements.update(initial_replacements)

    def expand_replace(var):
        new_nodes = []
        if var.owner and isinstance(var.owner.op, RandomVariable):
            new_nodes.extend(replacement_fn(var, replacements))
        return new_nodes

    for var in walk_model(graphs, expand_fn=expand_replace, **kwargs):
        pass

    if replacements:
        inputs = [i for i in graph_inputs(graphs) if not isinstance(i, Constant)]
        equiv = {k: k for k in replacements.keys()}
        equiv = clone_get_equiv(inputs, graphs, False, False, equiv)

        fg = FunctionGraph(
            [equiv[i] for i in inputs],
            [equiv[o] for o in graphs],
            clone=False,
        )

        fg.replace_all(replacements.items(), import_missing=True)

        graphs = list(fg.outputs)

    return graphs, replacements

def rvs_to_value_vars(
    graphs: Iterable[TensorVariable],
    apply_transforms: bool = False,
    initial_replacements: Optional[Dict[TensorVariable, TensorVariable]] = None,
    **kwargs,
) -> Tuple[TensorVariable, Dict[TensorVariable, TensorVariable]]:
    """Clone and replace random variables in graphs with their value variables.

    This will *not* recompute test values in the resulting graphs.

    Parameters
    ==========
    graphs
        The graphs in which to perform the replacements.
    apply_transforms
        If ``True``, apply each value variable's transform.
    initial_replacements
        A ``dict`` containing the initial replacements to be made.

    """

    # Avoid circular dependency
    from pymc.distributions import NoDistribution

    def transform_replacements(var, replacements):
        rv_var, rv_value_var = extract_rv_and_value_vars(var)

        if rv_value_var is None:
            # If RandomVariable does not have a value_var and corresponds to
            # a NoDistribution, we allow further replacements in upstream graph
            if isinstance(rv_var.owner.op, NoDistribution):
                return rv_var.owner.inputs

            else:
                warnings.warn(
                    f"No value variable found for {rv_var}; "
                    "the random variable will not be replaced."
                )
                return []

        transform = getattr(rv_value_var.tag, "transform", None)

        if transform is None or not apply_transforms:
            replacements[var] = rv_value_var
            # In case the value variable is itself a graph, we walk it for
            # potential replacements
            return [rv_value_var]

        trans_rv_value = transform.backward(rv_value_var, *rv_var.owner.inputs)
        replacements[var] = trans_rv_value

        # Walk the transformed variable and make replacements
        return [trans_rv_value]

    # Clone original graphs
    inputs = [i for i in graph_inputs(graphs) if not isinstance(i, Constant)]
    equiv = clone_get_equiv(inputs, graphs, False, False, {})
    graphs = [equiv[n] for n in graphs]

    if initial_replacements:
        initial_replacements = {
            equiv.get(k, k): equiv.get(v, v) for k, v in initial_replacements.items()
        }

    return replace_rvs_in_graphs(graphs, transform_replacements, initial_replacements, **kwargs)

def inputvars(a):
    """
    Get the inputs into Aesara variables

    Parameters
    ----------
        a: Aesara variable

    Returns
    -------
        r: list of tensor variables that are inputs
    """
    return [
        v
        for v in graph_inputs(makeiter(a))
        if isinstance(v, TensorVariable) and not isinstance(v, TensorConstant)
    ]

def cont_inputs(a):
    """
    Get the continuous inputs into Aesara variables

    Parameters
    ----------
        a: Aesara variable

    Returns
    -------
        r: list of tensor variables that are continuous inputs
    """
    return typefilter(inputvars(a), continuous_types)

def floatX(X):
    """
    Convert an Aesara tensor or numpy array to aesara.config.floatX type.
    """
    try:
        return X.astype(aesara.config.floatX)
    except AttributeError:
        # Scalar passed
        return np.asarray(X, dtype=aesara.config.floatX)

_conversion_map = {"float64": "int32", "float32": "int16", "float16": "int8", "float8": "int8"}

def intX(X):
    """
    Convert a aesara tensor or numpy array to aesara.tensor.int32 type.
    """
    intX = _conversion_map[aesara.config.floatX]
    try:
        return X.astype(intX)
    except AttributeError:
        # Scalar passed
        return np.asarray(X, dtype=intX)

def smartfloatX(x):
    """
    Converts numpy float values to floatX and leaves values of other types unchanged.
    """
    if str(x.dtype).startswith("float"):
        x = floatX(x)
    return x

"""
Aesara derivative functions
"""

def gradient1(f, v):
    """flat gradient of f wrt v"""
    return at.flatten(grad(f, v, disconnected_inputs="warn"))

empty_gradient = at.zeros(0, dtype="float32")

def gradient(f, vars=None):
    if vars is None:
        vars = cont_inputs(f)

    if vars:
        return at.concatenate([gradient1(f, v) for v in vars], axis=0)
    else:
        return empty_gradient

def jacobian1(f, v):
    """jacobian of f wrt v"""
    f = at.flatten(f)
    idx = at.arange(f.shape[0], dtype="int32")

    def grad_i(i):
        return gradient1(f[i], v)

    return aesara.map(grad_i, idx)[0]

def jacobian(f, vars=None):
    if vars is None:
        vars = cont_inputs(f)

    if vars:
        return at.concatenate([jacobian1(f, v) for v in vars], axis=1)
    else:
        return empty_gradient

def jacobian_diag(f, x):
    idx = at.arange(f.shape[0], dtype="int32")

    def grad_ii(i, f, x):
        return grad(f[i], x)[i]

    return aesara.scan(
        grad_ii, sequences=[idx], n_steps=f.shape[0], non_sequences=[f, x], name="jacobian_diag"
    )[0]

@aesara.config.change_flags(compute_test_value="ignore")
def hessian(f, vars=None):
    return -jacobian(gradient(f, vars), vars)

@aesara.config.change_flags(compute_test_value="ignore")
def hessian_diag1(f, v):
    g = gradient1(f, v)
    idx = at.arange(g.shape[0], dtype="int32")

    def hess_ii(i):
        return gradient1(g[i], v)[i]

    return aesara.map(hess_ii, idx)[0]

@aesara.config.change_flags(compute_test_value="ignore")
def hessian_diag(f, vars=None):
    if vars is None:
        vars = cont_inputs(f)

    if vars:
        return -at.concatenate([hessian_diag1(f, v) for v in vars], axis=0)
    else:
        return empty_gradient

def makeiter(a):
    if isinstance(a, (tuple, list)):
        return a
    else:
        return [a]

class IdentityOp(scalar.UnaryScalarOp):
    @staticmethod
    def st_impl(x):
        return x

    def impl(self, x):
        return x

    def grad(self, inp, grads):
        return grads

    def c_code(self, node, name, inp, out, sub):
        return f"{out[0]} = {inp[0]};"

    def __eq__(self, other):
        return isinstance(self, type(other))

    def __hash__(self):
        return hash(type(self))

def make_shared_replacements(point, vars, model):
    """
    Makes shared replacements for all *other* variables than the ones passed.

    This way functions can be called many times without setting unchanging variables. Allows us
    to use func.trust_input by removing the need for DictToArrayBijection and kwargs.

    Parameters
    ----------
    point: dictionary mapping variable names to sample values
    vars: list of variables not to make shared
    model: model

    Returns
    -------
    Dict of variable -> new shared variable
    """
    othervars = set(model.value_vars) - set(vars)
    return {
        var: aesara.shared(point[var.name], var.name + "_shared", broadcastable=var.broadcastable)
        for var in othervars
    }

def join_nonshared_inputs(
    point: Dict[str, np.ndarray],
    xs: List[TensorVariable],
    vars: List[TensorVariable],
    shared,
    make_shared: bool = False,
):
    """
    Takes a list of Aesara Variables and joins their non shared inputs into a single input.

    Parameters
    ----------
    point: a sample point
    xs: list of Aesara tensors
    vars: list of variables to join

    Returns
    -------
    tensors, inarray
    tensors: list of same tensors but with inarray as input
    inarray: vector of inputs
    """
    if not vars:
        raise ValueError("Empty list of variables.")

    joined = at.concatenate([var.ravel() for var in vars])

    if not make_shared:
        tensor_type = joined.type
        inarray = tensor_type("inarray")
    else:
        if point is None:
            raise ValueError("A point is required when `make_shared` is True")
        joined_values = np.concatenate([point[var.name].ravel() for var in vars])
        inarray = aesara.shared(joined_values, "inarray")

    if aesara.config.compute_test_value != "off":
        inarray.tag.test_value = joined.tag.test_value

    replace = {}
    last_idx = 0
    for var in vars:
        shape = point[var.name].shape
        arr_len = np.prod(shape, dtype=int)
        replace[var] = reshape_t(inarray[last_idx : last_idx + arr_len], shape).astype(var.dtype)
        last_idx += arr_len

    replace.update(shared)

    xs_special = [aesara.clone_replace(x, replace, strict=False) for x in xs]
    return xs_special, inarray

def reshape_t(x, shape):
    """Work around fact that x.reshape(()) doesn't work"""
    if shape != ():
        return x.reshape(shape)
    else:
        return x[0]

class CallableTensor:
    """Turns a symbolic variable with one input into a function that returns symbolic arguments
    with the one variable replaced with the input.
    """

    def __init__(self, tensor):
        self.tensor = tensor

    def __call__(self, input):
        """Replaces the single input of symbolic variable to be the passed argument.

        Parameters
        ----------
        input: TensorVariable
        """
        (oldinput,) = inputvars(self.tensor)
        return aesara.clone_replace(self.tensor, {oldinput: input}, strict=False)

scalar_identity = IdentityOp(scalar.upgrade_to_float, name="scalar_identity")
identity = Elemwise(scalar_identity, name="identity")

class GeneratorOp(Op):
    """
    Generator Op is designed for storing python generators inside aesara graph.

    __call__ creates TensorVariable
        It has 2 new methods
        - var.set_gen(gen): sets new generator
        - var.set_default(value): sets new default value (None erases default value)

    If generator is exhausted, variable will produce default value if it is not None,
    else raises `StopIteration` exception that can be caught on runtime.

    Parameters
    ----------
    gen: generator that implements __next__ (py3) or next (py2) method
        and yields np.arrays with same types
    default: np.array with the same type as generator produces
    """

    __props__ = ("generator",)

    def __init__(self, gen, default=None):
        from pymc.data import GeneratorAdapter

        super().__init__()
        if not isinstance(gen, GeneratorAdapter):
            gen = GeneratorAdapter(gen)
        self.generator = gen
        self.set_default(default)

    def make_node(self, *inputs):
        gen_var = self.generator.make_variable(self)
        return Apply(self, [], [gen_var])

    def perform(self, node, inputs, output_storage, params=None):
        if self.default is not None:
            output_storage[0][0] = next(self.generator, self.default)
        else:
            output_storage[0][0] = next(self.generator)

    def do_constant_folding(self, fgraph, node):
        return False

    __call__ = aesara.config.change_flags(compute_test_value="off")(Op.__call__)

    def set_gen(self, gen):
        from pymc.data import GeneratorAdapter

        if not isinstance(gen, GeneratorAdapter):
            gen = GeneratorAdapter(gen)
        if not gen.tensortype == self.generator.tensortype:
            raise ValueError("New generator should yield the same type")
        self.generator = gen

    def set_default(self, value):
        if value is None:
            self.default = None
        else:
            value = np.asarray(value, self.generator.tensortype.dtype)
            t1 = (False,) * value.ndim
            t2 = self.generator.tensortype.broadcastable
            if not t1 == t2:
                raise ValueError("Default value should have the same type as generator")
            self.default = value

def generator(gen, default=None):
    """
    Generator variable with possibility to set default value and new generator.
    If generator is exhausted variable will produce default value if it is not None,
    else raises `StopIteration` exception that can be caught on runtime.

    Parameters
    ----------
    gen: generator that implements __next__ (py3) or next (py2) method
        and yields np.arrays with same types
    default: np.array with the same type as generator produces

    Returns
    -------
    TensorVariable
        It has 2 new methods
        - var.set_gen(gen): sets new generator
        - var.set_default(value): sets new default value (None erases default value)
    """
    return GeneratorOp(gen, default)()

_at_rng = RandomStream()

def at_rng(random_seed=None):
    """
    Get the package-level random number generator or new with specified seed.

    Parameters
    ----------
    random_seed: int
        If not None
        returns *new* aesara random generator without replacing package global one

    Returns
    -------
    `aesara.tensor.random.utils.RandomStream` instance
        `aesara.tensor.random.utils.RandomStream`
        instance passed to the most recent call of `set_at_rng`
    """
    if random_seed is None:
        return _at_rng
    else:
        ret = RandomStream(random_seed)
        return ret

def set_at_rng(new_rng):
    """
    Set the package-level random number generator.

    Parameters
    ----------
    new_rng: `aesara.tensor.random.utils.RandomStream` instance
        The random number generator to use.
    """
    # pylint: disable=global-statement
    global _at_rng
    # pylint: enable=global-statement
    if isinstance(new_rng, int):
        new_rng = RandomStream(new_rng)
    _at_rng = new_rng

def floatX_array(x):
    return floatX(np.array(x))

def ix_(*args):
    """
    Aesara np.ix_ analog

    See numpy.lib.index_tricks.ix_ for reference
    """
    out = []
    nd = len(args)
    for k, new in enumerate(args):
        if new is None:
            out.append(slice(None))
        new = at.as_tensor(new)
        if new.ndim != 1:
            raise ValueError("Cross index must be 1 dimensional")
        new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))
        out.append(new)
    return tuple(out)

def largest_common_dtype(tensors):
    dtypes = {
        str(t.dtype) if hasattr(t, "dtype") else smartfloatX(np.asarray(t)).dtype for t in tensors
    }
    return np.stack([np.ones((), dtype=dtype) for dtype in dtypes]).dtype

def _make_along_axis_idx(arr_shape, indices, axis):
    # compute dimensions to iterate over
    if str(indices.dtype) not in int_types:
        raise IndexError("`indices` must be an integer array")
    shape_ones = (1,) * indices.ndim
    dest_dims = list(range(axis)) + [None] + list(range(axis + 1, indices.ndim))

    # build a fancy index, consisting of orthogonal aranges, with the
    # requested index inserted at the right location
    fancy_index = []
    for dim, n in zip(dest_dims, arr_shape):
        if dim is None:
            fancy_index.append(indices)
        else:
            ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim + 1 :]
            fancy_index.append(at.arange(n).reshape(ind_shape))

    return tuple(fancy_index)

def take_along_axis(arr, indices, axis=0):
    """Take values from the input array by matching 1d index and data slices.

    This iterates over matching 1d slices oriented along the specified axis in
    the index and data arrays, and uses the former to look up values in the
    latter. These slices can be different lengths.

    Functions returning an index along an axis, like argsort and argpartition,
    produce suitable indices for this function.
    """
    arr = at.as_tensor_variable(arr)
    indices = at.as_tensor_variable(indices)
    # normalize inputs
    if axis is None:
        arr = arr.flatten()
        arr_shape = (len(arr),)  # flatiter has no .shape
        _axis = 0
    else:
        if axis < 0:
            _axis = arr.ndim + axis
        else:
            _axis = axis
        if _axis < 0 or _axis >= arr.ndim:
            raise ValueError(
                "Supplied `axis` value {} is out of bounds of an array with "
                "ndim = {}".format(axis, arr.ndim)
            )
        arr_shape = arr.shape
    if arr.ndim != indices.ndim:
        raise ValueError("`indices` and `arr` must have the same number of dimensions")

    # use the fancy index
    return arr[_make_along_axis_idx(arr_shape, indices, _axis)]

@local_optimizer(tracks=[CheckParameterValue])
def local_remove_check_parameter(fgraph, node):
    """Rewrite that removes Aeppl's CheckParameterValue

    This is used when compile_rv_inplace
    """
    if isinstance(node.op, CheckParameterValue):
        return [node.inputs[0]]

@local_optimizer(tracks=[CheckParameterValue])
def local_check_parameter_to_ninf_switch(fgraph, node):
    if isinstance(node.op, CheckParameterValue):
        logp_expr, *logp_conds = node.inputs
        if len(logp_conds) > 1:
            logp_cond = at.all(logp_conds)
        else:
            (logp_cond,) = logp_conds
        out = at.switch(logp_cond, logp_expr, -np.inf)
        out.name = node.op.msg

        if out.dtype != node.outputs[0].dtype:
            out = at.cast(out, node.outputs[0].dtype)

        return [out]

aesara.compile.optdb["canonicalize"].register(
    "local_remove_check_parameter",
    local_remove_check_parameter,
    use_db_name_as_tag=False,
)

aesara.compile.optdb["canonicalize"].register(
    "local_check_parameter_to_ninf_switch",
    local_check_parameter_to_ninf_switch,
    use_db_name_as_tag=False,
)

def compile_pymc(inputs, outputs, mode=None, **kwargs):
    """Use ``aesara.function`` with specialized pymc rewrites always enabled.

    Included rewrites
    -----------------
    random_make_inplace
        Ensures that compiled functions containing random variables will produce new
        samples on each call.
    local_check_parameter_to_ninf_switch
        Replaces Aeppl's CheckParameterValue assertions is logp expressions with Switches
        that return -inf in place of the assert.

    Optional rewrites
    -----------------
    local_remove_check_parameter
        Replaces Aeppl's CheckParameterValue assertions is logp expressions. This is used
        as an alteranative to the default local_check_parameter_to_ninf_switch whenenver
        this function is called within a model context and the model `check_bounds` flag
        is set to False.
    """

    # Avoid circular dependency
    from pymc.distributions import NoDistribution

    # Set the default update of a NoDistribution RNG so that it is automatically
    # updated after every function call
    output_to_list = outputs if isinstance(outputs, (list, tuple)) else [outputs]
    for rv in (
        node
        for node in walk_model(output_to_list, walk_past_rvs=True)
        if node.owner and isinstance(node.owner.op, NoDistribution)
    ):
        rng = rv.owner.inputs[0]
        if not hasattr(rng, "default_update"):
            rng.default_update = rv.owner.outputs[0]

    # If called inside a model context, see if check_bounds flag is set to False
    try:
        from pymc.model import modelcontext

        model = modelcontext(None)
        check_bounds = model.check_bounds
    except TypeError:
        check_bounds = True
    check_parameter_opt = (
        "local_check_parameter_to_ninf_switch" if check_bounds else "local_remove_check_parameter"
    )

    mode = get_mode(mode)
    opt_qry = mode.provided_optimizer.including("random_make_inplace", check_parameter_opt)
    mode = Mode(linker=mode.linker, optimizer=opt_qry)
    aesara_function = aesara.function(inputs, outputs, mode=mode, **kwargs)
    return aesara_function


import os
import shutil

from joblib import Parallel, delayed
import multiprocessing

from cached_property import cached_property

import datetime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from bilby.core.prior import (Constraint, DeltaFunction,
                              Interped, Prior)
from bilby.gw.prior import (CBCPriorDict,
                            convert_to_lal_binary_black_hole_parameters,
                            fill_from_fixed_priors, generate_mass_parameters)
from tqdm.auto import tqdm

from deep_gw_pe_followup.sample_cacher.cacher import load_probabilities, store_probabilities
from .conversions import calc_a2
from .placeholder_prior import PlaceholderDelta
from .prob_calculators import (get_p_cos2_given_xeff_q_a1_cos1, get_p_a1_given_xeff_q, get_p_cos1_given_xeff_q_a1)

from deep_gw_pe_followup.plotting.hist2d import plot_heatmap

import logging
from bilby.core.utils import logger

logger.setLevel(logging.INFO)

num_cores = multiprocessing.cpu_count()

D = dict(a1=0.01, cos1=0.01, cos2=0.01)
X = dict(
    a1=np.linspace(0, 1, int(1. / D['a1'])),
    cos1=np.linspace(-1, 1, int(2. / D['cos1'])),
    cos2=np.linspace(-1, 1, int(2. / D['cos2']))
)
MCMC_N = int(5e4)

def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

def find_boundary_idx(x):
    """finds idx where data is non zero (assumes that there wont be gaps)"""
    non_z = np.nonzero(x)[0]
    return non_z[0], non_z[-1]

def find_boundary(x, y):
    b1, b2 = find_boundary_idx(y)
    vals = [x[b1], x[b2]]
    start, end = min(vals), max(vals)
    return start, end

class RestrictedPrior(CBCPriorDict):
    def __init__(self, dictionary=None, filename=None, clean=False, build_cache=True, mcmc_n=MCMC_N, cache=None):
        """cache -- a dir with the cached prob files"""
        super().__init__(dictionary=dictionary, filename=filename, conversion_function=None)
        self.q = (self['q'] if 'q' in self else self['mass_ratio']).peak
        self.xeff = (self['xeff'] if 'xeff' in self else self['chi_eff']).peak
        self.mcmc_n = mcmc_n
        self.filename = filename
        if clean:
            shutil.rmtree(self.cache)
        self.cache = cache

        self.search_params = self.get_search_params()
        self.ndim = len(self.search_params)

        # build cache
        if build_cache:
            self['a_1'] = self.get_a1_prior()
            self['cos_tilt_1'] = self.get_cos1_prior(given_a1=0.5)
            self['cos_tilt_2'] = self.get_cos2_prior(given_a1=0.5, given_cos1=0.5)

        # we have forced the normalize_constraint_factor = 1
        # if we need to deal with constraints in post-processing
        self.constraint_prior_check()

    @property
    def cache(self):
        return self._cache

    @cache.setter
    def cache(self, c):
        if c is None:
            prior_dirname = ""
            # if self.filename and os.path.isfile(self.filename):
            #     prior_dirname = os.path.dirname(self.filename)
            c = os.path.join(
                prior_dirname,
                f"cache_q{self.q}-xeff{self.xeff}".replace(".", "_")
            )
        if os.path.isdir(c):
            logger.debug(f"Loading RestricedPrior from cache {c}")
            self._cache = c
        else:
            logger.debug(f"Building RestricedPrior cache {c}")
            self._cache = c
            os.makedirs(self._cache, exist_ok=True)
        self._cache = os.path.abspath(self._cache)

    @property
    def restricted_params(self):
        return ['a_1', 'cos_tilt_1', 'cos_tilt_2', 'a_2']

    def constraint_prior_check(self):
        constraint_present = False
        for p,v in self.items():
            if isinstance(v, Constraint):
                constraint_present = True
        if constraint_present:
            logger.warning(
                "bilby prior contraints are present but `normalize_constraint_factor` is set to 1."
                "The user will need to compute the constraint factor in post-processing."
            )

    def get_a1_prior(self):
        fname = os.path.join(self.cache, "a1_given_qxeff.h5")
        if os.path.exists(fname):
            data = load_probabilities(fname)
            logger.debug(f"Loaded {fname}")
        else:
            logger.debug(f"Creating {fname}")
            a1s = X['a1']
            da1 = a1s[1] - a1s[0]
            p_a1 = Parallel(n_jobs=num_cores, verbose=1)(
                delayed(get_p_a1_given_xeff_q)(a1, self.xeff, self.q, self.mcmc_n * 100)
                for a1 in tqdm(a1s, desc="Building a1 cache"))

            p_a1 = p_a1 / np.sum(p_a1) / da1
            data = pd.DataFrame(dict(a1=a1s, p_a1=p_a1))
            store_probabilities(data, fname)

        a1 = data.a1.values
        p_a1 = data.p_a1.values

        min_b, max_b = find_boundary(a1, p_a1)

        return Interped(xx=a1, yy=p_a1, minimum=min_b, maximum=max_b, name="a_1", latex_label=r"$a_1$")

    @cached_property
    def cached_cos1_data(self):
        fname = os.path.join(self.cache, "cos1_given_qxeffa1.h5")
        if os.path.isfile(fname):
            data = load_probabilities(fname)
            logger.debug(f"Loaded {fname}")
        else:
            logger.debug(f"Creating {fname}")
            a1s, cos1s = X['a1'], X['cos1']
            data = dict(a1=np.array([]), cos1=np.array([]), p_cos1=np.array([]))
            for a1 in tqdm(a1s, desc="Building p_cos1 cache"):
                p_cos1_for_a1 = Parallel(n_jobs=num_cores, verbose=1)(
                    delayed(get_p_cos1_given_xeff_q_a1)(cos1, a1, self.xeff, self.q, self.mcmc_n) for cos1 in cos1s)
                data['a1'] = np.append(data['a1'], np.array([a1 for _ in cos1s]))
                data['cos1'] = np.append(data['cos1'], cos1s)
                data['p_cos1'] = np.append(data['p_cos1'], p_cos1_for_a1)
            data = pd.DataFrame(data)
            store_probabilities(data, fname)
        return data

    @classmethod
    def from_bbh_priordict(cls, dict):
        dict = {k: v for k, v in dict.items()}
        return cls(dictionary=dict)

    def get_cos1_prior(self, given_a1, ):
        data = self.cached_cos1_data
        closest_a1 = find_nearest(data.a1, given_a1)
        data = data[data.a1 == closest_a1]
        cos1 = data.cos1.values
        p_cos1 = data.p_cos1.values

        try:
            min_b, max_b = find_boundary(cos1, p_cos1)
        except Exception:
            min_b = min(cos1)
            max_b = max(cos1)

        return Interped(
            xx=cos1, yy=p_cos1,
            minimum=min_b, maximum=max_b, name="cos_tilt_1",
            latex_label=r"$\cos \theta_1$"
        )

    def get_cos2_prior(self, given_a1, given_cos1):
        cos2s = X['cos2']
        dc2 = cos2s[1] - cos2s[0]

        args = (given_a1, self.xeff, self.q, given_cos1)
        p_cos2 = np.array([get_p_cos2_given_xeff_q_a1_cos1(cos2, *args) for cos2 in cos2s])
        p_cos2 = p_cos2 / np.sum(p_cos2) / dc2

        try:
            min_b, max_b = find_boundary(cos2s, p_cos2)
        except Exception:
            min_b = min(cos2s)
            max_b = max(cos2s)

        if min_b == max_b:
            return PlaceholderDelta(peak=min_b, name="cos_tilt_2", latex_label=r"$\cos \theta_2$")

        return Interped(
            xx=cos2s, yy=p_cos2,
            minimum=min_b, maximum=max_b, name="cos_tilt_2",
            latex_label=r"$\cos \theta_2$"
        )

    def sample_restricted(self, size=1):
        a1 = np.atleast_1d(self['a_1'].sample(size))
        if isinstance(size, int) and size > 10:
            cos1 = np.hstack([
                self.get_cos1_prior(i).sample(1)
                for i in tqdm(a1, desc="Getting cos1 samples", total=size)
            ])
            cos2 = np.hstack([
                self.get_cos2_prior(i, j).sample(1)
                for i, j in tqdm(zip(a1, cos1), desc="Getting cos2 samples", total=size)
            ])

        else:
            cos1 = np.hstack([self.get_cos1_prior(given_a1=i).sample(1) for i in a1])
            cos2 = np.hstack([
                self.get_cos2_prior(given_a1=i, given_cos1=j).sample(1)
                for i, j in zip(a1, cos1)
            ])
        return dict(
            a_1=a1,
            cos_tilt_1=cos1,
            cos_tilt_2=cos2,
        )

    def update_restricted_priors(self, sample):
        a1, c1 = sample['a_1'], sample['cos_tilt_1']
        self['cos_tilt_1'] = self.get_cos1_prior(given_a1=a1)
        self['cos_tilt_2'] = self.get_cos2_prior(given_a1=a1, given_cos1=c1)

    def get_search_params(self):
        """
        Go through the list of priors and add keys to the fixed and search
        parameter key list depending on whether
        the respective parameter is fixed.
        """
        search_parameter = list()
        for key in self:
            if isinstance(self[key], Prior) \
                    and self[key].is_fixed is False:
                search_parameter.append(key)
        return search_parameter

    # Overloaded functions

    def default_conversion_function(self, sample):
        if 'cos_tilt_1' in sample:
            sample['tilt_1'] = np.arccos(sample['cos_tilt_1'])
            sample['tilt_2'] = np.arccos(sample['cos_tilt_2'])
        sample['a_2'] = calc_a2(xeff=self.xeff, q=self.q, cos1=sample['cos_tilt_1'], cos2=sample['cos_tilt_2'],
                                a1=sample['a_1'])
        out_sample = fill_from_fixed_priors(sample, self)
        out_sample, _ = convert_to_lal_binary_black_hole_parameters(out_sample)
        out_sample = generate_mass_parameters(out_sample)
        return out_sample

    def sample_subset(self, keys=iter([]), size=None):
        samples = super().sample_subset(keys=keys, size=size)
        restricted_samples = self.sample_restricted(size)
        return {**samples, **restricted_samples}

    def prob(self, sample, **kwargs):
        self.update_restricted_priors(sample)
        return super().prob(sample)

    def ln_prob(self, sample, axis=None):
        self.update_restricted_priors(sample)
        self._prepare_evaluation(*zip(*sample.items()))
        res = {key: self[key].ln_prob(sample[key], **self.get_required_variables(key)) for key in sample}
        reslist = [v for v in res.values()]
        ln_prob = np.sum(reslist, axis=axis)
        return self.check_ln_prob(sample, ln_prob)

    def cdf(self, sample):
        self.update_restricted_priors(sample)
        return super().cdf(sample)

    def rescale_restricted(self, keys, theta):
        """theta:drawn from unit-cube"""
        unit = {k: t for k, t in zip(keys, theta)}
        scaled = {}
        scaled['a_1'] = self['a_1'].rescale(unit['a_1'])
        self['cos_tilt_1'] = self.get_cos1_prior(given_a1=scaled['a_1'])
        scaled['cos_tilt_1'] = self['cos_tilt_1'].rescale(unit['cos_tilt_1'])
        self['cos_tilt_2'] = self.get_cos2_prior(given_a1=scaled['a_1'], given_cos1=scaled['cos_tilt_1'])
        scaled['cos_tilt_2'] = self['cos_tilt_2'].rescale(unit['cos_tilt_2'])
        return scaled

    def rescale(self, keys, theta):
        """theta:drawn from unit-cube"""
        scaled = self.rescale_restricted(keys, theta)
        self.update_restricted_priors(scaled)
        return super().rescale(keys=keys, theta=theta)

    def normalize_constraint_factor(self, keys, min_accept=10000, sampling_chunk=50000, nrepeats=10):
        return 1.0

    def debug_sample(self, sample, fname='debug_prior.png'):
        self.update_restricted_priors(sample)
        nparam = len(self)
        fig, axes = plt.subplots(nparam, 1, figsize=(5, 2 * nparam))
        for i, label in enumerate(self):
            if not isinstance(self[label], DeltaFunction):
                xx = np.linspace(start=self[label].minimum, stop=self[label].maximum, num=100)
                yy = self[label].prob(xx)
                axes[i].plot(xx, yy, "C1")
                if label in sample:
                    axes[i].axvline(sample[label], c="C2", linestyle="--")
            else:
                axes[i].axvline(self[label].peak, c="C1")
                axes[i].axvline(self[label].peak, c="C2", linestyle="--")
            axes[i].set_xlabel(label.replace("_", " "))
        plt.tight_layout()
        plt.savefig(fname)

    def time_prior(self, n_evaluations=100):
        """ Times the prior evaluation and print an info message

        Parameters
        ==========
        n_evaluations: int
            The number of evaluations to estimate the evaluation time from

        """

        t1 = datetime.datetime.now()
        for _ in range(n_evaluations):
            theta = self.sample()
        total_time = (datetime.datetime.now() - t1).total_seconds()
        self._eval_time = total_time / n_evaluations

        if self._eval_time == 0:
            self._eval_time = np.nan
            logger.info("Unable to measure single prior sample time")
        else:
            logger.info("Single prior evaluation took {:.3e} s".format(self._eval_time))

    def plot_cache(self):
        """ Plot of a1 and 2D plot of a1-cos1 """
        fig, axes = plt.subplots(2, 1, figsize=(5, 6), sharex=True)
        axes[0].set_ylabel('p(a1)')
        axes[1].set_ylabel('cos1')
        axes[1].set_xlabel('a1')
        axes[0].plot(self['a_1'].xx, self['a_1'].yy)
        data = self.cached_cos1_data
        plot_heatmap(x=data['a1'], y=data['cos1'], p=data['p_cos1'], ax=axes[1])
        plt.tight_layout()
        plt.savefig(f"{self.cache}/plot.png")


#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import numpy
from pyscf.lib.parameters import BOHR

unknown = 1.999999

#########################
# JCP 41 3199 (1964).
BRAGG = 1/BOHR * numpy.array((unknown,  # Ghost atom
        0.35,                                     1.40,             # 1s
        1.45, 1.05, 0.85, 0.70, 0.65, 0.60, 0.50, 1.50,             # 2s2p
        1.80, 1.50, 1.25, 1.10, 1.00, 1.00, 1.00, 1.80,             # 3s3p
        2.20, 1.80,                                                 # 4s
        1.60, 1.40, 1.35, 1.40, 1.40, 1.40, 1.35, 1.35, 1.35, 1.35, # 3d
                    1.30, 1.25, 1.15, 1.15, 1.15, 1.90,             # 4p
        2.35, 2.00,                                                 # 5s
        1.80, 1.55, 1.45, 1.45, 1.35, 1.30, 1.35, 1.40, 1.60, 1.55, # 4d
                    1.55, 1.45, 1.45, 1.40, 1.40, 2.10,             # 5p
        2.60, 2.15,                                                 # 6s
        1.95, 1.85, 1.85, 1.85, 1.85, 1.85, 1.85,                   # La, Ce-Eu
        1.80, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,             # Gd, Tb-Lu
              1.55, 1.45, 1.35, 1.35, 1.30, 1.35, 1.35, 1.35, 1.50, # 5d
                    1.90, 1.80, 1.60, 1.90, 1.45, 2.10,             # 6p
        1.80, 2.15,                                                 # 7s
        1.95, 1.80, 1.80, 1.75, 1.75, 1.75, 1.75,
        1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,
        1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75,
                    1.75, 1.75, 1.75, 1.75, 1.75, 1.75,
        1.75, 1.75,
        1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75))

# from Gerald Knizia's CtDftGrid, which is based on
#       http://en.wikipedia.org/wiki/Covalent_radius
# and
#       Beatriz Cordero, Veronica Gomez, Ana E. Platero-Prats, Marc Reves,
#       Jorge Echeverria, Eduard Cremades, Flavia Barragan and Santiago
#       Alvarez.  Covalent radii revisited. Dalton Trans., 2008, 2832-2838,
#       doi:10.1039/b801115j
COVALENT = 1/BOHR * numpy.array((unknown,  # Ghost atom
        0.31,                                     0.28,             # 1s
        1.28, 0.96, 0.84, 0.73, 0.71, 0.66, 0.57, 0.58,             # 2s2p
        1.66, 1.41, 1.21, 1.11, 1.07, 1.05, 1.02, 1.06,             # 3s3p
        2.03, 1.76,                                                 # 4s
        1.70, 1.60, 1.53, 1.39, 1.50, 1.42, 1.38, 1.24, 1.32, 1.22, # 3d
                    1.22, 1.20, 1.19, 1.20, 1.20, 1.16,             # 4p
        2.20, 1.95,                                                 # 5s
        1.90, 1.75, 1.64, 1.54, 1.47, 1.46, 1.42, 1.39, 1.45, 1.44, # 4d
                    1.42, 1.39, 1.39, 1.38, 1.39, 1.40,             # 5p
        2.44, 2.15,                                                 # 6s
        2.07, 2.04, 2.03, 2.01, 1.99, 1.98, 1.98,                   # La, Ce-Eu
        1.96, 1.94, 1.92, 1.92, 1.89, 1.90, 1.87, 1.87,             # Gd, Tb-Lu
              1.75, 1.70, 1.62, 1.51, 1.44, 1.41, 1.36, 1.36, 1.32, # 5d
                    1.45, 1.46, 1.48, 1.40, 1.50, 1.50,             # 6p
        2.60, 2.21,                                                 # 7s
        2.15, 2.06, 2.00, 1.96, 1.90, 1.87, 1.80, 1.69))

#
# vdw from ASE
#
# Van der Waals radii in [A] taken from
# http://www.webelements.com/periodicity/van_der_waals_radius/
# and the references given there.
# Additional source 5 from http://de.wikipedia.org/wiki/Van-der-Waals-Radius
#
# 1. A. Bondi, J. Phys. Chem., 1964, 68, 441.
#
# 2. L. Pauling, The Nature of the Chemical Bond,
#    Cornell University Press, USA, 1945.
#
# 3. J.E. Huheey, E.A. Keiter, and R.L. Keiter in Inorganic Chemistry
#    Principles of Structure and Reactivity, 4th edition, HarperCollins,
#    New York, USA, 1993.W.W. Porterfield in Inorganic chemistry,
#    a unified approach, Addison Wesley Publishing Co.,
#    Reading Massachusetts, USA, 1984.
#
# 4. A.M. James and M.P. Lord in Macmillan's Chemical and Physical Data,
#    Macmillan, London, UK, 1992.
#
# 5. Manjeera Mantina, Adam C. Chamberlin, Rosendo Valero,
#    Christopher J. Cramer, Donald G. Truhlar Consistent van der Waals Radii
#    for the Whole Main Group. In J. Phys. Chem. A. 2009, 113, 5806-5812,
#    doi:10.1021/jp8111556
VDW = 1/BOHR * numpy.array((unknown,  # Ghost atom
    1.20,       #  1 H
    1.40,       #  2 He [1]
    1.82,       #  3 Li [1]
    1.53,       #  4 Be [5]
    1.92,       #  5 B  [5]
    1.70,       #  6 C  [1]
    1.55,       #  7 N  [1]
    1.52,       #  8 O  [1]
    1.47,       #  9 F  [1]
    1.54,       # 10 Ne [1]
    2.27,       # 11 Na [1]
    1.73,       # 12 Mg [1]
    1.84,       # 13 Al [5]
    2.10,       # 14 Si [1]
    1.80,       # 15 P  [1]
    1.80,       # 16 S  [1]
    1.75,       # 17 Cl [1]
    1.88,       # 18 Ar [1]
    2.75,       # 19 K  [1]
    2.31,       # 20 Ca [5]
    unknown,    # 21 Sc
    unknown,    # 22 Ti
    unknown,    # 23 V
    unknown,    # 24 Cr
    unknown,    # 25 Mn
    unknown,    # 26 Fe
    unknown,    # 27 Co
    1.63,       # 28 Ni [1]
    1.40,       # 29 Cu [1]
    1.39,       # 30 Zn [1]
    1.87,       # 31 Ga [1]
    2.11,       # 32 Ge [5]
    1.85,       # 33 As [1]
    1.90,       # 34 Se [1]
    1.85,       # 35 Br [1]
    2.02,       # 36 Kr [1]
    3.03,       # 37 Rb [5]
    2.49,       # 38 Sr [5]
    unknown,    # 39 Y
    unknown,    # 40 Zr
    unknown,    # 41 Nb
    unknown,    # 42 Mo
    unknown,    # 43 Tc
    unknown,    # 44 Ru
    unknown,    # 45 Rh
    1.63,       # 46 Pd [1]
    1.72,       # 47 Ag [1]
    1.58,       # 48 Cd [1]
    1.93,       # 49 In [1]
    2.17,       # 50 Sn [1]
    2.06,       # 51 Sb [5]
    2.06,       # 52 Te [1]
    1.98,       # 53 I  [1]
    2.16,       # 54 Xe [1]
    3.43,       # 55 Cs [5]
    2.49,       # 56 Ba [5]
    unknown,    # 57 La
    unknown,    # 58 Ce
    unknown,    # 59 Pr
    unknown,    # 60 Nd
    unknown,    # 61 Pm
    unknown,    # 62 Sm
    unknown,    # 63 Eu
    unknown,    # 64 Gd
    unknown,    # 65 Tb
    unknown,    # 66 Dy
    unknown,    # 67 Ho
    unknown,    # 68 Er
    unknown,    # 69 Tm
    unknown,    # 70 Yb
    unknown,    # 71 Lu
    unknown,    # 72 Hf
    unknown,    # 73 Ta
    unknown,    # 74 W
    unknown,    # 75 Re
    unknown,    # 76 Os
    unknown,    # 77 Ir
    1.75,       # 78 Pt [1]
    1.66,       # 79 Au [1]
    1.55,       # 80 Hg [1]
    1.96,       # 81 Tl [1]
    2.02,       # 82 Pb [1]
    2.07,       # 83 Bi [5]
    1.97,       # 84 Po [5]
    2.02,       # 85 At [5]
    2.20,       # 86 Rn [5]
    3.48,       # 87 Fr [5]
    2.83,       # 88 Ra [5]
    unknown,    # 89 Ac
    unknown,    # 90 Th
    unknown,    # 91 Pa
    1.86,       # 92 U [1]
    unknown,    # 93 Np
    unknown,    # 94 Pu
    unknown,    # 95 Am
    unknown,    # 96 Cm
    unknown,    # 97 Bk
    unknown,    # 98 Cf
    unknown,    # 99 Es
    unknown,    #100 Fm
    unknown,    #101 Md
    unknown,    #102 No
    unknown,    #103 Lr
))

# Universal Force Field (UFF)
# J. Am. Chem. Soc., 1992, 114 (25), pp 10024-10035
UFF = 1/BOHR * numpy.array((unknown,  # Ghost atom
    1.4430,     #  1  H
    1.8100,     #  2  He
    1.2255,     #  3  Li
    1.3725,     #  4  Be
    2.0415,     #  5  B
    1.9255,     #  6  C
    1.8300,     #  7  N
    1.7500,     #  8  O
    1.6820,     #  9  F
    1.6215,     # 10  Ne
    1.4915,     # 11  Na
    1.5105,     # 12  Mg
    2.2495,     # 13  Al
    2.1475,     # 14  Si
    2.0735,     # 15  P
    2.0175,     # 16  S
    1.9735,     # 17  Cl
    1.9340,     # 18  Ar
    1.9060,     # 19  K
    1.6995,     # 20  Ca
    1.6475,     # 21  Sc
    1.5875,     # 22  Ti
    1.5720,     # 23  V
    1.5115,     # 24  Cr
    1.4805,     # 25  Mn
    1.4560,     # 26  Fe
    1.4360,     # 27  Co
    1.4170,     # 28  Ni
    1.7475,     # 29  Cu
    1.3815,     # 30  Zn
    2.1915,     # 31  Ga
    2.1400,     # 32  Ge
    2.1150,     # 33  As
    2.1025,     # 34  Se
    2.0945,     # 35  Br
    2.0705,     # 36  Kr
    2.0570,     # 37  Rb
    1.8205,     # 38  Sr
    1.6725,     # 39  Y
    1.5620,     # 40  Zr
    1.5825,     # 41  Nb
    1.5260,     # 42  Mo
    1.4990,     # 43  Tc
    1.4815,     # 44  Ru
    1.4645,     # 45  Rh
    1.4495,     # 46  Pd
    1.5740,     # 47  Ag
    1.4240,     # 48  Cd
    2.2315,     # 49  In
    2.1960,     # 50  Sn
    2.2100,     # 51  Sb
    2.2350,     # 52  Te
    2.2500,     # 53  I
    2.2020,     # 54  Xe
    2.2585,     # 55  Cs
    1.8515,     # 56  Ba
    1.7610,     # 57  La
    1.7780,     # 58  Ce
    1.8030,     # 59  Pr
    1.7875,     # 60  Nd
    1.7735,     # 61  Pm
    1.7600,     # 62  Sm
    1.7465,     # 63  Eu
    1.6840,     # 64  Gd
    1.7255,     # 65  Tb
    1.7140,     # 66  Dy
    1.7045,     # 67  Ho
    1.6955,     # 68  Er
    1.6870,     # 69  Tm
    1.6775,     # 70  Yb
    1.8200,     # 71  Lu
    1.5705,     # 72  Hf
    1.5850,     # 73  Ta
    1.5345,     # 74  W
    1.4770,     # 75  Re
    1.5600,     # 76  Os
    1.4200,     # 77  Ir
    1.3770,     # 78  Pt
    1.6465,     # 79  Au
    1.3525,     # 80  Hg
    2.1735,     # 81  Tl
    2.1485,     # 82  Pb
    2.1850,     # 83  Bi
    2.3545,     # 84  Po
    2.3750,     # 85  At
    2.3825,     # 86  Rn
    2.4500,     # 87  Fr
    1.8385,     # 88  Ra
    1.7390,     # 89  Ac
    1.6980,     # 90  Th
    1.7120,     # 91  Pa
    1.6975,     # 92  U
    1.7120,     # 93  Np
    1.7120,     # 94  Pu
    1.6905,     # 95  Am
    1.6630,     # 96  Cm
    1.6695,     # 97  Bk
    1.6565,     # 98  Cf
    1.6495,     # 99  Es
    1.6430,     #100  Fm
    1.6370,     #101  Md
    1.6240,     #102  No
    1.6180,     #103  Lr
    unknown,    #104  Rf
    unknown,    #105  Db
    unknown,    #106  Sg
    unknown,    #107  Bh
    unknown,    #108  Hs
    unknown,    #109  Mt
    unknown,    #110  Ds
    unknown,    #111  Rg
    unknown,    #112  Cn
    unknown,    #113  Nh
    unknown,    #114  Fl
    unknown,    #115  Mc
    unknown,    #116  Lv
    unknown,    #117  Ts
    unknown,    #118  Og
))

# Allinger's MM3 radii
# From http://pcmsolver.readthedocs.io/en/latest/users/input.html
MM3 = 1/BOHR * numpy.array((unknown,  # Ghost atom
    1.62,       #  1  H
    1.53,       #  2  He
    2.55,       #  3  Li
    2.23,       #  4  Be
    2.15,       #  5  B
    2.04,       #  6  C
    1.93,       #  7  N
    1.82,       #  8  O
    1.71,       #  9  F
    1.60,       # 10  Ne
    2.70,       # 11  Na
    2.43,       # 12  Mg
    2.36,       # 13  Al
    2.29,       # 14  Si
    2.22,       # 15  P
    2.15,       # 16  S
    2.07,       # 17  Cl
    1.99,       # 18  Ar
    3.09,       # 19  K
    2.81,       # 20  Ca
    2.61,       # 21  Sc
    2.39,       # 22  Ti
    2.29,       # 23  V
    2.25,       # 24  Cr
    2.24,       # 25  Mn
    2.23,       # 26  Fe
    2.23,       # 27  Co
    2.22,       # 28  Ni
    2.26,       # 29  Cu
    2.29,       # 30  Zn
    2.46,       # 31  Ga
    2.44,       # 32  Ge
    2.36,       # 33  As
    2.29,       # 34  Se
    2.22,       # 35  Br
    2.15,       # 36  Kr
    3.25,       # 37  Rb
    3.00,       # 38  Sr
    2.71,       # 39  Y
    2.54,       # 40  Zr
    2.43,       # 41  Nb
    2.39,       # 42  Mo
    2.36,       # 43  Tc
    2.34,       # 44  Ru
    2.34,       # 45  Rh
    2.37,       # 46  Pd
    2.43,       # 47  Ag
    2.50,       # 48  Cd
    2.64,       # 49  In
    2.59,       # 50  Sn
    2.52,       # 51  Sb
    2.44,       # 52  Te
    2.36,       # 53  I
    2.28,       # 54  Xe
    3.44,       # 55  Cs
    3.07,       # 56  Ba
    2.78,       # 57  La
    2.74,       # 58  Ce
    2.73,       # 59  Pr
    2.73,       # 60  Nd
    2.72,       # 61  Pm
    2.71,       # 62  Sm
    2.94,       # 63  Eu
    2.71,       # 64  Gd
    2.70,       # 65  Tb
    2.69,       # 66  Dy
    2.67,       # 67  Ho
    2.67,       # 68  Er
    2.67,       # 69  Tm
    2.79,       # 70  Yb
    2.65,       # 71  Lu
    2.53,       # 72  Hf
    2.43,       # 73  Ta
    2.39,       # 74  W
    2.37,       # 75  Re
    2.35,       # 76  Os
    2.36,       # 77  Ir
    2.39,       # 78  Pt
    2.43,       # 79  Au
    2.53,       # 80  Hg
    2.59,       # 81  Tl
    2.74,       # 82  Pb
    2.66,       # 83  Bi
    2.59,       # 84  Po
    2.51,       # 85  At
    2.43,       # 86  Rn
    3.64,       # 87  Fr
    3.27,       # 88  Ra
    3.08,       # 89  Ac
    2.74,       # 90  Th
    2.64,       # 91  Pa
    2.52,       # 92  U
    2.52,       # 93  Np
    2.52,       # 94  Pu
    unknown,    # 95  Am
    unknown,    # 96  Cm
    unknown,    # 97  Bk
    unknown,    # 98  Cf
    unknown,    # 99  Es
    unknown,    #100  Fm
    unknown,    #101  Md
    unknown,    #102  No
    unknown,    #103  Lr
    2.73,       #104  Rf
    2.63,       #105  Db
    unknown,    #106  Sg
    1.62,       #107  Bh
    unknown,    #108  Hs
    unknown,    #109  Mt
    unknown,    #110  Ds
    unknown,    #111  Rg
    unknown,    #112  Cn
    unknown,    #113  Nh
    unknown,    #114  Fl
    unknown,    #115  Mc
    unknown,    #116  Lv
    unknown,    #117  Ts
    unknown,    #118  Og
))
del unknown


from typing import Union
import numpy as np
from ._data_converter import NameProcess
from .interpolators import Material, Interpolators, MaterialFactory

_AVOGADRO = 0.60221367  # * 1e+24 mole^-1

ENERGY_GRID_DEFAULT = np.array([1.0E+03, 1.5E+03, 2.0E+03, 3.0E+03, 4.0E+03, 5.0E+03,
                                6.0E+03, 8.0E+03, 1.0E+04, 1.5E+04, 2.0E+04, 3.0E+04, 4.0E+04,
                                5.0E+04, 6.0E+04, 8.0E+04, 1.0E+05, 1.5E+05, 2.0E+05, 3.0E+05,
                                4.0E+05, 5.0E+05, 6.0E+05, 8.0E+05, 1.0E+06, 1.022E+06, 1.25E+06,
                                1.5E+06, 2.0E+06, 2.044E+06, 3.0E+06, 4.0E+06, 5.0E+06, 6.0E+06,
                                7.0E+06, 8.0E+06, 9.0E+06, 1.0E+07, 1.1E+07, 1.2E+07, 1.3E+07,
                                1.4E+07, 1.5E+07, 1.6E+07, 1.8E+07, 2.0E+07, 2.2E+07, 2.4E+07,
                                2.6E+07, 2.8E+07, 3.0E+07, 4.0E+07, 5.0E+07, 6.0E+07, 8.0E+07,
                                1.0E+08, 1.5E+08, 2.0E+08, 3.0E+08, 4.0E+08, 5.0E+08, 6.0E+08,
                                8.0E+08, 1.0E+09, 1.5E+09, 2.0E+09, 3.0E+09, 4.0E+09, 5.0E+09,
                                6.0E+09, 8.0E+09, 1.0E+10, 1.5E+10, 2.0E+10, 3.0E+10, 4.0E+10,
                                5.0E+10, 6.0E+10, 8.0E+10, 1.0E+11], dtype='d')

_INTERPOLATOS = Interpolators()

def calculate_attenuation(material: Material, energy: np.ndarray = None):
    """
    Calculate attenuation (cm2/gramm) for gamma-ray (at energies between 1 keV and 100 GeV) for next process:

        * Coherent scattering
        * Incoherent (Compton) scattering
        * Photoelectric absorption
        * Pair production in the field of the atomic nucleus and in the field of the atomic electrons

    Based on NIST XCOM data: https://www.nist.gov/pml/xcom-photon-cross-sections-database

    Parameters
    ----------
    material
            special class description simple material or compound

    energy
            energies of gamma-quanta in eV, used `ENERGY_GRID_DEFAULT` by default

    Returns
    -------
    data : ndarray with attenuation in cm2/gramm
    """
    if not isinstance(material, Material):
        raise Exception("Except material")

    if len(material) == 1:
        element = material.elements_by_Z[0]
        data = calculate_cross_section(element, energy)
        # Attenutaion coefficient = macro_cross_secction/denisty = \
        # = micro_cross_section/atom_weight[gr]
        # atom_weight[gr] = atom_weight[amu] / AVOGADRO
        atom_weigth = MaterialFactory.get_element_mass(element)
        for name in data.dtype.names:
            data[name] /= _AVOGADRO / atom_weigth
        return data
    elif len(material) > 1:
        atom_weights_amu = MaterialFactory.get_elements_mass_list(material.elements_by_Z)
        data = calculate_cross_section(material.elements_by_Z[0], energy)
        for name in data.dtype.names:
            data[name] *= ( material.weights[0] * _AVOGADRO / atom_weights_amu[0])

        for atom_weight_amu, element, weight in zip(atom_weights_amu[1:], material.elements_by_Z[1:], material.weights):
            temp = calculate_cross_section(element, energy)
            for name in data.dtype.names:
                data[name] +=  temp[name] * weight * _AVOGADRO / atom_weight_amu
        return data
    else:
        raise Exception("Empty material")

def calculate_cross_section(element : Union[int, str], energy: np.ndarray = None) -> np.ndarray:
    """
    Calculate cross-section (barn/atom) for gamma-ray (at energies between 1 keV and 100 GeV) for next process:

        * Coherent scattering
        * Incoherent (Compton) scattering
        * Photoelectric absorption
        * Pair production in the field of the atomic nucleus and in the field of the atomic electrons

    Based on NIST XCOM data: https://www.nist.gov/pml/xcom-photon-cross-sections-database

    Parameters
    ----------
    element
            atomic number or symbol of element

    energy
            energies of gamma-quanta in eV, used `ENERGY_GRID_DEFAULT` by default

    Returns
    -------
    data : ndarray with cross-section in barn/atom
    """
    if energy is None:
        energy = ENERGY_GRID_DEFAULT

    if not isinstance(element, int):
        element = MaterialFactory.get_element_from_symbol(element)

    n = len(energy)
    dtype = np.dtype([("energy", "d"),
                      (NameProcess.COHERENT, 'd'),
                      (NameProcess.INCOHERENT, 'd'),
                      (NameProcess.PHOTOELECTRIC, 'd'),
                      (NameProcess.PAIR_ATOM, 'd'),
                      (NameProcess.PAIR_ELECTRON, 'd'),
                      ("total_without_coherent", "d"),
                      ("total", "d")])

    data = np.zeros(n, dtype=dtype)
    data["energy"] = np.asarray(energy)

    for k, v in _INTERPOLATOS.get_interpolators(element).items():
        data[k] = v(data["energy"])
        data["total"] += data[k]
    data["total_without_coherent"] -= data[NameProcess.COHERENT]
    return data