import torch


def layer_pen(Phi, k_dic, Gram):
    """Compute layer's penalization from layer's information

    Parameters
    ----------
    Phi: torch.Tensor of shape (n_samples, n_features_l+1)
         Coefficient tensor

    k_dic: dict
           Kernel and its parameter
           keys: {'kernel', 'kparam', 'lambda', 'outdim'}
           values: kernel type, parameter, regularization output dimension

    Gram: torch.Tensor of shape (n_samples, n_samples)
          Gram matrix

    Returns
    -------
    pen: float
         Penalization value
    """
    # Simpler formula if outmat = torch.eye
    try:
        N = torch.mm(Phi, torch.mm(k_dic['outmat'], torch.t(Phi)))
    except KeyError:
        N = torch.mm(Phi, torch.t(Phi))

    pen = k_dic['lambda'] * (Gram * N).sum()

    return pen