from core.explanations.analyzers.BaseExplanationAnalyzer import BaseExplanationAnalyzer
from core.explanations.analyzers.IndividualExplanationAnalyzer import IndividualExplanationAnalyzer


class AggregatorExplanationAnalyzer(BaseExplanationAnalyzer):

    @staticmethod
    def calc_feature_importance(explanations, sample_size):
        feature_importances = {n: 0 for n in range(sample_size)}

        for explanations_for_sample in explanations:
            if not explanations_for_sample:
                continue

            feature_importance = IndividualExplanationAnalyzer.calc_feature_importance(
                explanations=explanations_for_sample,
                sample_size=sample_size
            )

            for feature, importance in feature_importance.items():
                feature_importances[feature] += importance

        # Normalize the feature importances
        for feature, importance in feature_importances.items():
            feature_importances[feature] = importance / len(explanations)

        return feature_importances
