nuclear convolution in python

To perform nuclear convolution in Python, we can use the convolve function from the scipy library.

Here's how it can be done:

main.py
import numpy as np
from scipy.signal import convolve

# example matrices
A = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
B = np.array([[2, 1],
              [1, 2]])

# flip the second matrix along both axes
B = np.flip(B, axis=0)
B = np.flip(B, axis=1)

# perform the convolution
C = convolve(A, B, mode='valid')

# print the results
print(A)
print(B)
print(C)
390 chars
22 lines

In this example, we define two matrices A and B, and then perform a nuclear convolution of A with B. The first step in the process is to flip B along both axes, which is necessary for nuclear convolution. We then use the convolve function with the mode parameter set to 'valid' in order to discard the parts of the convolution that lie outside the boundary of A. The resulting matrix C is the nuclear convolution of A and B.

Note that the mode parameter can be set to 'full' or 'same' in order to include the boundary parts of the convolution in the output.

gistlibby LogSnag