from .baseanalysis import BaseAnalysis
from .reciprocity import ReciprocityEstimator
from .connectivity import ConnectivityEstimator


def _save_divide(enumerator, denominator):
    if enumerator == 0:
        return 0
    if denominator != 0:
        return enumerator / denominator
    raise Exception("Division by zero")


class RelativeReciprocityEstimator(BaseAnalysis):
    """
    Estimate the reciprocity relative to an ER network of the same connectivity.
    See also :class:`ReciprocityEstimator <connectome.analysis.reciprocity.ReciprocityEstimator>`.

    Output keys: relative_reciprocity_ee, relative_reciprocity_ei, relative_reciprocity_ie, relative_reciprocity_ii
    """

    def analyse(self):
        reciprocity = ReciprocityEstimator(network=self.network)()
        connectivity = ConnectivityEstimator(network=self.network)()
        # note the reciprocity_xy is divided by connectivity_yx
        # the order of xy is REVERSED! And this has to be that way!
        relative_reciprocity = {"relative_reciprocity_ee": _save_divide(reciprocity['reciprocity_ee'], connectivity['p_ee']),
                                "relative_reciprocity_ei": _save_divide(reciprocity['reciprocity_ei'], connectivity['p_ie']),
                                "relative_reciprocity_ie": _save_divide(reciprocity['reciprocity_ie'], connectivity['p_ei']),
                                "relative_reciprocity_ii": _save_divide(reciprocity['reciprocity_ii'], connectivity['p_ii'])}
        return relative_reciprocity
