# Interpolation for Squaring


```python
import numpy as np
import matplotlib.pyplot as plt

import os
import sys
sys.path.append(os.path.join(os.getcwd(), '../build/'))
import pydeft as deft

plt.rc('font', family='serif')
plt.rc('xtick', labelsize='x-small')
plt.rc('ytick', labelsize='x-small')
```

Consider samples of a continuous function
\begin{equation}
    w(\mathbf{r}) = \cos{p x},
\end{equation}
such that we have enough samples to reconstruct the continuous function using Fourier-based interpolations. 

If we are interested in the quantitiy $w^2$, just squaring the values of the sampled points may not be enough to fully reconstruct the square of the continuous function. This is because larger frequency components have been introduced during the squaring, which might not be adequately described by the sampled points. Hence, the same set of sampled points that could successfully reconstruct $w$ may not adequately reconstruct $w^2$. This can be rectified by first interpolating the sampled points in $w$ before squaring the values on a denser grid. 


```python
# create box and data array

dense_factor = 11
grd_pts = 7
dense_grd_pts = grd_pts*dense_factor

box_vectors = np.eye(3)
box = deft.Box(box_vectors)

x_sparse =  np.arange(grd_pts)/grd_pts
x_dense =  np.arange(dense_grd_pts)/dense_grd_pts
x,y,z = np.meshgrid(x_sparse, np.arange(5)/5, np.arange(5)/5,indexing='ij')
p = np.pi*4
data = deft.Double3D([grd_pts, 5, 5])
data[...] = np.cos(p*x)

data_dense = deft.fourier_interpolate(data, [dense_grd_pts, 5, 5])    

# font
plt.rc('font', size=14)
fig = plt.figure(figsize=[9,3.5])
plt.plot(x_dense, np.cos(p*x_dense), color='0.5', ls = 'solid', linewidth = 2)
plt.plot(x_sparse, data[:,0,0], 'k+', markersize = 18)
plt.plot(x_dense, data_dense[:,0,0], 'k.', markersize = 8)
plt.legend(['$\cos(4\pi x)$', 'sampled points', 'interpolated points'], loc=(1.02,0.25))
plt.tight_layout()
plt.show()
```


```python
sparse_squared = deft.fourier_interpolate(data*data, [dense_grd_pts, 5, 5])        
    
# plot
plt.rc('font', size=14)
fig = plt.figure(figsize=[9,3.5])
plt.plot(x_dense, np.cos(p*x_dense)**2, color='0.5', ls = 'solid', linewidth = 2)
plt.plot(x_dense, data_dense[:,0,0]**2, 'k.', markersize = 8)
plt.plot(x_sparse, data[:,0,0]**2, 'k+', markersize = 18)
plt.plot(x_dense, sparse_squared[:,0,0], color='0.2', ls = 'dashed', linewidth = 1)
plt.set_xlabel('$x$-axis [one lattice cell]')
plt.legend(['$\cos^2(4\pi x)$', 'interpolated before squaring', 'sampled points squared', 'squared before interpolating'], loc=(1.02,0.25))
plt.tight_layout()
plt.show()
```

1ce76ea76ac2f947dfb5e5c92895c64d684b903e
ipynb
Jupyter Notebook
example/interpolation_squaring.ipynb
cw-tan/deft
abb4d23fa0bb53031c13daef9942bceba4afd655
MIT
example/interpolation_squaring.ipynb
cw-tan/deft
abb4d23fa0bb53031c13daef9942bceba4afd655
MIT
example/interpolation_squaring.ipynb
cw-tan/deft
abb4d23fa0bb53031c13daef9942bceba4afd655
MIT
Qwen/Qwen-72B
1. YES
2. YES