# Chapter 50: Computer Vision and Spatial Economic Measurement
# Fundamentals of Python for Financial Econometrics - Computer Vision and Spatial Economic Measurement
# Dataset: Ceteris Lab teaching sample

# Computer Vision and Spatial Economic Measurement
#
# **Opening question:** How does a model transform pixels into useful local patterns without being told the exact edge or texture to search for?

# %% Cell 2
import numpy as np

image = np.zeros((8, 8))
image[:, 4:] = 1
kernel = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
padded = np.pad(image, 1, mode="symmetric")
windows = np.lib.stride_tricks.sliding_window_view(padded, (3, 3))
feature = np.einsum("ijkl,kl->ij", windows, kernel)
print(float(np.abs(feature).max()), feature.shape)

# **Interpretation check:** Interpretation. The vertical edge creates a strong response where intensity changes across columns.

# %% Cell 4
import numpy as np

rng = np.random.default_rng(50)
batch = rng.normal(size=(4, 3, 16, 16))
kernels = rng.normal(size=(6, 3, 3, 3))
padded = np.pad(batch, ((0, 0), (0, 0), (1, 1), (1, 1)))
windows = np.lib.stride_tricks.sliding_window_view(padded, (3, 3), axis=(2, 3))
feature_maps = np.einsum("bchwkl,ockl->bohw", windows, kernels)
print("Input batch:", batch.shape)
print("Feature maps:", feature_maps.shape)

# **Interpretation check:** Interpretation. Padding preserves height and width, while eight learned filters replace the three input channels.

# Verified source output
#
# ```text
# 3.0 (8, 8)
# ```
#
# ```text
# (16, 8, 64, 64)
# ```
