"""Sparseness metrics for explanation evaluation in the MUPPET benchmark framework.

This module provides sparseness metrics for evaluating the sparsity of
explanations generated by XAI methods. It extends the Quantus sparseness
metric with custom evaluation logic adapted for the MUPPET framework.

Classes:
    Sparseness: Custom sparseness metric extending Quantus sparseness evaluation
"""

import numpy as np
from quantus import Sparseness as QuantusSparseness


class Sparseness(QuantusSparseness):
    """Custom sparseness metric that extends Quantus Sparseness.

    Provides specialized evaluation logic for measuring the sparseness
    of explanations by extending the Quantus framework implementation.

    Args:
        x (np.ndarray): The input to be evaluated on an instance-basis.
        a (np.ndarray): The explanation to be evaluated on an instance-basis.

    """

    @staticmethod
    def evaluate_instance(x: np.ndarray, a: np.ndarray) -> float:
        """Evaluate instance gets model and data for a single instance as input and returns the evaluation result.

        Args:
            x (np.ndarray): The input to be evaluated on an instance-basis.
            a (np.ndarray): The explanation to be evaluated on an instance-basis.

        Returns:
            float: The evaluation results.
        """
        if len(x.shape) <= 2:
            newshape = np.prod(x.shape)
        else:
            newshape = np.prod(x.shape[1:])

        a = np.array(np.reshape(a, newshape), dtype=np.float64)
        a += 0.0000001
        a = np.sort(a)
        score = (
            np.sum((2 * np.arange(1, a.shape[0] + 1) - a.shape[0] - 1) * a)
        ) / (a.shape[0] * np.sum(a))
        return score
