import torch


def bound_patch_attack(patch_logits, affected_patch, bound=(-1, 1)):
    """Bound the effect of patch attack given affected patches
    Input:
    - patch_logits (pytorch tensor): patch logits returned by BagNet33
    - affected_patch (tuple): (x1, y1, x2, y2), where (x1, y1) is the top-left coordinate of top-left patch,
                                and (x2, y2) is the bottom-right coordinate of bottom-right patch.
    - bound (tuple): (lower bound, upper bound)
    Output:
    - class_logits_upper (pytorch tensor): upper bound of class logits, shape = (1000,)
    - class_logits_lower (pytorch tensor): lower bound of class logits, shape = (1000,)
    """
    x1, y1, x2, y2 = affected_patch
    upper, lower = patch_logits.clone(), patch_logits.clone()
    upper[x1:x2+1, y1:y2+1, :] = bound[1]
    lower[x1:x2+1, y1:y2+1, :] = bound[0]
    class_logits_upper = torch.mean(upper, dim=(0, 1))
    class_logits_lower = torch.mean(lower, dim=(0, 1))
    return (class_logits_lower, class_logits_upper)