import torch


def complex_to_mag_phase(data):
    """
    :param data (torch.Tensor): A complex valued tensor, where the size of the third last dimension should be 2
    :return: Mag and Phase (torch.Tensor): tensor of same size as input
    """

    assert data.size(-3) == 2
    mag = (data ** 2).sum(dim=-3).sqrt()
    phase = torch.atan2(data[:, 1, :, :], data[:, 0, :, :])
    return torch.stack((mag, phase), dim=-3)