import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from scipy.ndimage import shift

def load_data(name):
    img = Image.open(name).convert('L')
    return np.array(img).astype(float) / 255.0

blue = load_data('blue_cloud.png')
red = load_data('red_cloud.png')

# Alignment 
dx, dy = -15, 15 
red_s = shift(red, [dy, dx], cval=0, order=1)

h, w = blue.shape
cy, cx = (h // 2) + 80, w // 2 
crop = 250 
b_sub = blue[cy-crop:cy+crop, cx-crop:cx+crop]
r_sub = red_s[cy-crop:cy+crop, cx-crop:cx+crop]

def get_clean_r(b, r):
    mask = (b > 0.1) & (r > 0.1)
    if np.count_nonzero(mask) < 10: return 0
    return np.corrcoef(b[mask], r[mask])[0, 1]

# Focus window on the central interaction 
r_val = get_clean_r(b_sub[200:300, 200:300], r_sub[200:300, 200:300])

def get_resid(data):
    m = data > 0.05
    res = np.zeros_like(data)
    res[m] = (data[m] - np.mean(data[m])) / np.std(data[m])
    return res

corr_map = get_resid(b_sub) * get_resid(r_sub)

plt.figure(figsize=(8, 7))

plt.imshow(corr_map, cmap='jet_r', vmin=-1.5, vmax=0.5, origin='lower')

cbar = plt.colorbar(label='Correlation Strength')
cbar.set_ticks([-1.5, -0.5, 0.5])
cbar.set_ticklabels([f'Min r = {r_val:.2f}', 'Neutral r = 0', 'Max r = 0.5'])

plt.title(f'Figure 2: Raw Pixel Correlation Map\nInteraction $r = {r_val:.2f}$')
plt.axis('off')
plt.show()
