from operator import add


def _aggreggate_explainer_values_dict(values, provenance):
    """Aggregates explainer values across features created from a common feature.

    For example, let's say the pipeline has a natural language featurizer that creates the columns: LSA_1, LSA_2, PolarityScore,
    MeanCharacter, and DiversityScore from a column called "text_feature".

    The values dictionary input to this function will have a key for each of the features created by the natural language featurizer,
    but it will not have a key for the original "text_feature" column. It will look like this:

    {"LSA_1": [0.2], "LSA_0": [0.3], "PolarityScore": [0.1], "MeanCharacters": [0.05], "DiversityScore": [-0.1], ...}

    After this function, the values dictionary will look like: {"text_feature": [0.55]}

    This aggregation will happen for all features for which we know the provenance/lineage. Other features will
    be left as they are.

    Args:
        values (dict): A mapping of feature names to a list of explainer values for each data point.
        provenance (dict): A mapping from a feature in the original data to the names of the features that were created
            from that feature.

    Returns:
        dict: Dictionary mapping from feature name to explainer values.
    """
    child_to_parent = {}
    for parent_feature, children in provenance.items():
        for child in children:
            if child in values:
                child_to_parent[child] = parent_feature

    agg_values = {}
    for feature_name, explainer_list in values.items():
        # Only aggregate features for which we know the parent-feature
        if feature_name in child_to_parent:
            parent = child_to_parent[feature_name]
            if parent not in agg_values:
                agg_values[parent] = [0] * len(explainer_list)
            # Elementwise-sum without numpy
            agg_values[parent] = list(map(add, agg_values[parent], explainer_list))
        else:
            agg_values[feature_name] = explainer_list
    return agg_values