# examples/visual_complexity.py
"""Compute patch heuristics and select distinct patches; no ViT inference."""

# region: full
import math

import torch
import torch.nn.functional as F


def select_patches(images, budget=96, patch_size=16, weights=(0.4, 0.3, 0.3),
                   temperature=0.4, generator=None):
    """Scores grayscale patches and samples without replacement per image.

    Args:
        images: Float tensor [batch, channels, height, width], values in [0, 1].
        budget: Number of distinct patches to retain per image.
        patch_size: Square patch side in pixels; must divide height and width.
        weights: Nonnegative weights for normalized edge, frequency and entropy.
        temperature: Positive softmax temperature; lower is more concentrated.
        generator: Optional torch.Generator on the same device as images.

    Returns:
        Selected patches [batch, budget, channels, patch_size, patch_size],
        row-major patch indices [batch, budget], and normalized scores [batch, n].

    Raises:
        ValueError: If the shape, input range or allocation parameters are invalid.
    """
    if images.ndim != 4 or not images.is_floating_point():
        raise ValueError("images must be a floating-point BCHW tensor")
    batch, channels, height, width = images.shape
    if min(images.shape) < 1 or not isinstance(patch_size, int) or patch_size < 2:
        raise ValueError("nonempty images and patch_size >= 2 are required")
    if height % patch_size or width % patch_size:
        raise ValueError("image dimensions must be divisible by patch_size")
    if not torch.isfinite(images).all() or images.min() < 0 or images.max() > 1:
        raise ValueError("images must contain finite values in [0, 1]")
    count = (height // patch_size) * (width // patch_size)
    if not isinstance(budget, int) or not 1 <= budget <= count:
        raise ValueError("budget must be between 1 and the patch count")
    if not math.isfinite(temperature) or temperature <= 0:
        raise ValueError("temperature must be positive")
    if len(weights) != 3 or any(not math.isfinite(w) or w < 0 for w in weights):
        raise ValueError("three finite nonnegative weights are required")

    # Float32 keeps FFT and convolution supported on CPU for half inputs.
    patches = F.unfold(images.float(), patch_size, stride=patch_size)
    patches = patches.transpose(1, 2).reshape(
        batch, count, channels, patch_size, patch_size)
    gray = patches.mean(dim=2).reshape(-1, 1, patch_size, patch_size)
    kernel_x = images.new_tensor(
        [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32)
    kernels = torch.stack((kernel_x, kernel_x.T)).unsqueeze(1)
    gradients = F.conv2d(F.pad(gray, (1, 1, 1, 1), mode="reflect"), kernels)
    edge = gradients.square().sum(dim=1).sqrt().mean(dim=(-2, -1))
    edge = edge / (4 * math.sqrt(2))

    # Remove the mean. Measure the fraction of AC power above 0.25 cycles/pixel.
    centered = gray[:, 0] - gray[:, 0].mean(dim=(-2, -1), keepdim=True)
    power = torch.fft.fft2(centered).abs().square()
    frequencies = torch.fft.fftfreq(patch_size, device=images.device)
    fy, fx = torch.meshgrid(frequencies, frequencies, indexing="ij")
    high = fx.square() + fy.square() > 0.25 ** 2
    total_power = power.sum(dim=(-2, -1))
    frequency = power[:, high].sum(dim=-1) / total_power.clamp_min(1e-12)

    # Intensity histogram entropy: ignores spatial arrangement within a patch.
    bins = 32
    values = (gray.flatten(1) * bins).long().clamp(max=bins - 1)
    histogram = torch.zeros((batch * count, bins), device=images.device)
    histogram.scatter_add_(1, values, torch.ones_like(values, dtype=torch.float32))
    probabilities = histogram / (patch_size * patch_size)
    entropy = -(probabilities * probabilities.clamp_min(1e-12).log2()).sum(dim=1)
    entropy = entropy / math.log2(bins)

    metrics = torch.stack((edge, frequency, entropy), dim=-1)
    coefficients = metrics.new_tensor(weights)
    coefficients = coefficients / coefficients.sum().clamp_min(1e-12)
    scores = (metrics * coefficients).sum(dim=-1).reshape(batch, count)
    probabilities = torch.softmax((scores - scores.max(dim=1, keepdim=True).values)
                                  / temperature, dim=1)
    # Keep every index eligible under extreme temperatures despite underflow.
    probabilities = probabilities.clamp_min(torch.finfo(probabilities.dtype).tiny)
    indices = torch.multinomial(probabilities, budget, replacement=False,
                                generator=generator).sort(dim=1).values
    gather = indices[:, :, None, None, None].expand(
        -1, -1, channels, patch_size, patch_size)
    return patches.gather(1, gather), indices, scores


if __name__ == "__main__":
    torch.manual_seed(7)
    # Synthetic inputs for an executable shape check, not an accuracy benchmark.
    images = torch.rand(2, 3, 224, 224)
    selected, positions, scores = select_patches(images)
    assert selected.shape == (2, 96, 3, 16, 16)
    assert all(row.unique().numel() == 96 for row in positions)
    print(f"Selected {selected.shape[1]} distinct patches from {scores.shape[1]}")
    print(f"Returned positions for all {images.shape[0]} images")
# endregion: full
