# Copyright 2019 Balaji Veeramani. 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.
"""Ranking criteria for filter methods."""
import torch


def correlation(dataset):
    """Calculates the Pearson correlation coefficient for each covariate.

    Arguments:
        dataset: An iterable of (x, y) pairs of tensors.

    Returns:
        A one-dimensional tensor containing a Pearson correlation coefficient
        for each covariate.
    """
    x = torch.stack([x for x, y in dataset])
    y = torch.tensor([y for x, y in dataset])

    x_hat = torch.mean(x, dim = 0)
    y_hat = torch.mean(y)

    s_xy = torch.sum((x - x_hat) * (y - y_hat).view(-1, 1), dim=0)
    s2_x = torch.sum(torch.pow(x - x_hat, 2), dim=0)
    s2_y = torch.sum(torch.pow(y - y_hat, 2)).view(-1, 1)

    return torch.squeeze(s_xy / torch.sqrt(s2_x * s2_y))
