File size: 6,949 Bytes
a1a1fbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""

DISCO Convolutions
==================

This tutorial demonstrates Discrete-Continuous (DISCO) convolutions, which are
the building blocks of localized neural operator frameworks. DISCO convolutions
are crucial for:

- Learning localized patterns in data
- Handling both equidistant and unstructured grids
- Enabling efficient computation on irregular domains
- Bridging discrete and continuous representations

The tutorial covers various DISCO convolution types and their applications
in neural operator architectures.
    
"""

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Preparation


import os
import torch
import torch.nn as nn
import numpy as np
import math
from functools import partial

from matplotlib import image

from torch_harmonics.quadrature import (
    legendre_gauss_weights,
    lobatto_weights,
    clenshaw_curtiss_weights,
)

import matplotlib.pyplot as plt

cmap = "inferno"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

from neuralop.layers.discrete_continuous_convolution import (
    DiscreteContinuousConv2d,
    DiscreteContinuousConvTranspose2d,
    EquidistantDiscreteContinuousConv2d,
    EquidistantDiscreteContinuousConvTranspose2d,
)

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Let's start by loading an example image
try:
    _script_dir = os.path.dirname(os.path.abspath(__file__))
except NameError:
    _script_dir = os.getcwd()
einstein_path = os.path.join(_script_dir, "einstein.jpg")

nx = 90
ny = 120

img = image.imread(einstein_path)
data = nn.functional.interpolate(
    torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(ny, nx)
).squeeze()
plt.imshow(data, cmap=cmap)
plt.show()

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Let's create a grid on which the data lives

x_in = torch.linspace(0, 2, nx)
y_in = torch.linspace(0, 3, ny)

x_in, y_in = torch.meshgrid(x_in, y_in, indexing="ij")
grid_in = torch.stack([x_in.reshape(-1), y_in.reshape(-1)])

# compute the correct quadrature weights
# IMPORTANT: this needs to be done right in order for the DISCO convolution to be normalized proeperly
w_x = 2 * torch.ones_like(x_in) / nx
w_y = 3 * torch.ones_like(y_in) / ny
q_in = (w_x * w_y).reshape(-1)

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Visualize the grid

plt.figure(
    figsize=(4, 6),
)
plt.scatter(grid_in[0], grid_in[1], s=0.2)
plt.xlim(0, 2)
plt.ylim(0, 3)
plt.show()


# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Format data into the same format and plot it on the grid

data = data.permute(1, 0).flip(1).reshape(-1)

plt.figure(figsize=(4,6))
plt.tripcolor(grid_in[0], grid_in[1], data, cmap=cmap)
# plt.colorbar()
plt.xlim(0, 2)
plt.ylim(0, 3)
plt.show()

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# For the convolution output we require an output mesh
nxo = 90
nyo = 120

x_out = torch.linspace(0, 2, nxo)
y_out = torch.linspace(0, 3, nyo)

x_out, y_out = torch.meshgrid(x_out, y_out, indexing="ij")
grid_out = torch.stack([x_out.reshape(-1), y_out.reshape(-1)])

# compute the correct quadrature weights
w_x = 2 * torch.ones_like(x_out) / nxo
w_y = 3 * torch.ones_like(y_out) / nyo
q_out = (w_x * w_y).reshape(-1)

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Initialize the convolution and set the weights to something resembling an edge filter/finit differences
conv = DiscreteContinuousConv2d(
    1,
    1,
    grid_in=grid_in,
    grid_out=grid_out,
    quadrature_weights=q_in,
    kernel_shape=[2, 4],
    radius_cutoff=5 / nyo,
    periodic=False,
).float()

# initialize a kernel resembling an edge filter
w = torch.zeros_like(conv.weight)
w[0, 0, 1] = 1.0
w[0, 0, 3] = -1.0
conv.weight = nn.Parameter(w)
psi = conv.get_local_filter_matrix()

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Apply the DISCO convolution to the data and plot it
# in order to compute the convolved image, we need to first bring it into the right shape with `batch_size x n_channels x n_grid_points`
out = conv(data.reshape(1, 1, -1))

print(out.shape)

plt.figure(figsize=(4,6))
plt.imshow(torch.flip(out.squeeze().detach().reshape(nxo, nyo).transpose(0,1), dims=(-2, )), cmap=cmap)
plt.colorbar()
plt.show()

out1 = torch.flip(out.squeeze().detach().reshape(nxo, nyo).transpose(0, 1), dims=(-2,))

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Do the same but on an equidistant grid
conv_equi = EquidistantDiscreteContinuousConv2d(
    1,
    1,
    (nx, ny),
    (nxo, nyo),
    kernel_shape=[2, 4],
    radius_cutoff=5 / nyo,
    domain_length=[2, 3],
)

# initialize a kernel resembling an edge filter
w = torch.zeros_like(conv.weight)
w[0, 0, 1] = 1.0
w[0, 0, 3] = -1.0
conv_equi.weight = nn.Parameter(w)

data = nn.functional.interpolate(
    torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(ny, nx)
).float()

out_equi = conv_equi(data)

print(out_equi.shape)

plt.figure(figsize=(4,6))
plt.imshow(out_equi.squeeze().detach(), cmap=cmap)
plt.colorbar()
plt.show()

out2 = out_equi.squeeze().detach()

print(out2.shape)

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Visualize the local filter matrix

plt.figure(figsize=(4,6))
plt.imshow(conv_equi.get_local_filter_matrix()[0].detach(), cmap=cmap)
plt.colorbar()

# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Test the transpose convolution
convt = DiscreteContinuousConvTranspose2d(
    1,
    1,
    grid_in=grid_out,
    grid_out=grid_in,
    quadrature_weights=q_out,
    kernel_shape=[2, 4],
    radius_cutoff=3 / nyo,
    periodic=False,
).float()

# initialize a flat
w = torch.zeros_like(conv.weight)
w[0, 0, 0] = 1.0
w[0, 0, 1] = 1.0
w[0, 0, 2] = 1.0
w[0, 0, 3] = 1.0
convt.weight = nn.Parameter(w)

data = (
    nn.functional.interpolate(
        torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(ny, nx)
    )
    .squeeze().float()
    .permute(1, 0).flip(1).reshape(-1)
)
out = convt(data.reshape(1, 1, -1))

print(out.shape)

plt.figure(figsize=(4,6))
plt.imshow(torch.flip(out.squeeze().detach().reshape(nx, ny).transpose(0,1), dims=(-2, )), cmap=cmap)
plt.colorbar()
plt.show()


# %%
# .. raw:: html
#
#    <div style="margin-top: 3em;"></div>
#
# Test the equidistant transpose convolution
convt_equi = EquidistantDiscreteContinuousConvTranspose2d(
    1,
    1,
    (nxo, nyo),
    (nx, ny),
    kernel_shape=[2, 4],
    radius_cutoff=3 / nyo,
    domain_length=[2, 3],
)

# initialize a flat
w = torch.zeros_like(convt_equi.weight)
w[0, 0, 0] = 1.0
w[0, 0, 1] = 1.0
w[0, 0, 2] = 1.0
w[0, 0, 3] = 1.0
convt_equi.weight = nn.Parameter(w)

data = nn.functional.interpolate(
    torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(nyo, nxo)
).float()
out_equi = convt_equi(data)

print(out_equi.shape)

plt.figure(figsize=(4,6))
plt.imshow(out_equi.squeeze().detach(), cmap=cmap)
plt.colorbar()
plt.show()