#!/usr/bin/env python3
"""Fixed feature-map CAM/Grad-CAM and tiny input-optimization mechanics.

No CNN, dataset, checkpoint, image generation or model training is used.
Autograd differentiates a hand-set mean-GAP linear head and a 3D objective.
"""

from fractions import Fraction as F
import json
import torch

DTYPE = torch.float64
DEVICE = "cpu"


def head_logit(features, weights, bias):
    return (features.mean(dim=(-2, -1)) * weights).sum() + bias


def python_logit(features, weights, bias):
    """Scalar arithmetic reference, independent of tensor mean/autograd."""
    return sum(w * sum(sum(row) for row in channel) / 4
               for w, channel in zip(weights, features)) + bias


def peak_normalize(nonnegative_map):
    maximum = nonnegative_map.max()
    return nonnegative_map / maximum if maximum.item() > 0 else torch.zeros_like(nonnegative_map)


def map_checks():
    features = torch.tensor([[[1., 2.], [0., 1.]],
                             [[0., 1.], [3., 2.]]], dtype=DTYPE, device=DEVICE, requires_grad=True)
    weights = torch.tensor([2., -1.], dtype=DTYPE, device=DEVICE)
    bias = 0.5
    spatial_count = 4
    logit = head_logit(features, weights, bias)
    gradients, = torch.autograd.grad(logit, features)
    alpha = gradients.mean(dim=(-2, -1))
    cam_signed = (weights[:, None, None] * features).sum(dim=0)
    gradcam_signed = (alpha[:, None, None] * features).sum(dim=0)
    cam_positive, gradcam_positive = torch.relu(cam_signed), torch.relu(gradcam_signed)

    shifted_logit = head_logit(features, weights, bias + 2)
    shifted_gradient, = torch.autograd.grad(shifted_logit, features)
    finite = torch.empty_like(features)
    step = 1e-5
    source = features.detach().tolist()
    for k in range(2):
        for i in range(2):
            for j in range(2):
                plus = [[row[:] for row in channel] for channel in source]
                minus = [[row[:] for row in channel] for channel in source]
                plus[k][i][j] += step
                minus[k][i][j] -= step
                finite[k, i, j] = (python_logit(plus, weights.tolist(), bias)
                                   - python_logit(minus, weights.tolist(), bias)) / (2 * step)

    expected_cam = torch.tensor([[2., 3.], [-3., 0.]], dtype=DTYPE)
    torch.testing.assert_close(cam_signed, expected_cam, rtol=0, atol=0)
    torch.testing.assert_close(alpha, weights / spatial_count, rtol=0, atol=0)
    torch.testing.assert_close(gradcam_signed, cam_signed / spatial_count, rtol=0, atol=0)
    torch.testing.assert_close(gradients, finite, rtol=0, atol=1e-9)
    torch.testing.assert_close(shifted_gradient, gradients, rtol=0, atol=0)
    torch.testing.assert_close(cam_signed.mean() + bias, logit, rtol=0, atol=0)
    torch.testing.assert_close(gradcam_signed.sum() + bias, logit, rtol=0, atol=0)
    torch.testing.assert_close(peak_normalize(cam_positive), peak_normalize(gradcam_positive), rtol=0, atol=0)
    assert (gradcam_positive.sum() + bias).item() != logit.item()

    return {"feature_shape_K_H_W": list(features.shape), "feature_maps": source,
            "class_weights": weights.tolist(), "bias": bias, "GAP_convention": "mean of 4 spatial positions",
            "gap_features": features.mean(dim=(-2, -1)).detach().tolist(), "raw_class_logit": logit.item(),
            "score_gradients_wrt_features": gradients.tolist(), "central_difference_gradients": finite.tolist(),
            "central_difference_max_abs_error": (gradients - finite).abs().max().item(),
            "gradcam_alpha": alpha.tolist(), "CAM_signed": cam_signed.detach().tolist(),
            "GradCAM_before_ReLU": gradcam_signed.detach().tolist(),
            "CAM_after_ReLU_for_comparison": cam_positive.detach().tolist(),
            "GradCAM_after_ReLU": gradcam_positive.detach().tolist(),
            "CAM_mean_plus_bias": (cam_signed.mean() + bias).item(),
            "GradCAM_before_ReLU_sum_plus_bias": (gradcam_signed.sum() + bias).item(),
            "GradCAM_after_ReLU_sum_plus_bias": (gradcam_positive.sum() + bias).item(),
            "peak_normalized_CAM_positive": peak_normalize(cam_positive).detach().tolist(),
            "peak_normalized_GradCAM": peak_normalize(gradcam_positive).detach().tolist(),
            "bias_plus_2_changes_logit_to": shifted_logit.item(),
            "bias_shift_max_gradient_change": (shifted_gradient - gradients).abs().max().item(),
            "scope": "head-only fixed feature maps, not input pixels; signed CAM and standard positive Grad-CAM are distinct"}


def input_ascent(prior_strength):
    vector = torch.tensor([2., -1., 0.5], dtype=DTYPE, device=DEVICE)
    u = torch.zeros(3, dtype=DTYPE, device=DEVICE, requires_grad=True)
    learning_rate, total_steps = 0.2, 20
    records, objectives = [], []
    max_gradient_error = 0.
    for step in range(total_steps + 1):
        activation = (vector * u).sum()
        penalty = prior_strength / 2 * u.square().sum()
        objective = activation - penalty
        gradient, = torch.autograd.grad(objective, u)
        max_gradient_error = max(max_gradient_error, (gradient - (vector - prior_strength * u)).abs().max().item())
        objectives.append(objective.item())
        if step in (0, 1, 5, total_steps):
            records.append({"step": step, "input_u": u.detach().tolist(), "feature_activation": activation.item(),
                            "L2_penalty": penalty.item(), "objective": objective.item(),
                            "objective_gradient": gradient.detach().tolist()})
        if step < total_steps:
            # Optimize the input, not the fixed vector. No optimizer or model fit.
            with torch.no_grad():
                u.add_(learning_rate * gradient)

    if prior_strength == 0:
        expected = total_steps * learning_rate * vector
        optimum_note = "No finite maximizer: a nonzero linear feature is unbounded on unconstrained R^3"
        analytic = None
    else:
        optimum = vector / prior_strength
        # For lambda=.5, lr=.2, recurrence is u_n=(1-(9/10)^n)*(4,-2,1).
        q = F(1) - F(9, 10) ** total_steps
        expected = torch.tensor([float(F(4) * q), float(F(-2) * q), float(q)], dtype=DTYPE)
        analytic = {"optimal_input": optimum.tolist(), "optimal_objective": 5.25,
                    "finite_step_exact_factor": str(q), "finite_step_reference": expected.tolist(),
                    "objective_gap_to_optimum": 5.25 - records[-1]["objective"]}
        optimum_note = "Unique maximum for this unconstrained concave quadratic; no claim for a CNN objective"
    torch.testing.assert_close(u, expected, rtol=0, atol=1e-12)
    assert max_gradient_error < 1e-12
    assert all(b >= a - 1e-12 for a, b in zip(objectives, objectives[1:]))
    return {"fixed_feature_vector": vector.tolist(), "optimized_variable": "unconstrained 3D input u",
            "objective": "v dot u - lambda/2 * ||u||^2", "lambda": prior_strength,
            "learning_rate": learning_rate, "updates": total_steps, "selected_actual_iterates": records,
            "max_autograd_vs_analytic_gradient_error": max_gradient_error,
            "finite_step_max_reference_error": (u.detach() - expected).abs().max().item(),
            "analytic_reference": analytic, "optimization_scope": optimum_note}


def main():
    result = {"environment": {"torch": torch.__version__, "device": DEVICE, "dtype": "float64",
                              "random_sampling": False, "model_or_dataset_download": False},
              "CAM_GradCAM_fixed_maps": map_checks(),
              "feature_activation_input_ascent_no_prior": input_ascent(0.0),
              "feature_activation_input_ascent_L2_prior": input_ascent(0.5),
              "limits": ["no CNN forward, real photograph, trained checkpoint, localization accuracy or pixel causal test",
                         "mean-GAP linear head gives alpha=w/Z; this equality is not general for nonlinear heads",
                         "ReLU discards negative evidence; peak normalization can hide raw constant scale",
                         "input ascent is actual optimization of a hand-set vector, not a generated CNN image or model training",
                         "L2 prior here is a toy constraint, not a claim to natural-image realism"]}
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
