I am trying to find an efficient way to apply the convolution of lists to a 3d matrix of 0 and 1, where approximately 5% of the matrix is 1, but the 1 can be placed randomly or grouped into a large contiguous "island" ( note that this is related to a separate question I asked here about more efficient ways to generate this matrix).

Essentially I want to convert a set of small cores (3x3x3) with this large matrix of 1s and 0s. I have an implementation (see below), but I wonder if there is a smarter way to take advantage of the sparse nature of my matrix; the fact that the 1 is placed at random makes this difficult.

Ultimately, my goal in doing this is to count the number of "interactions of three neighbors" (that is, the number of interactions 1-1-1, 1-1-0, 1-0-0 and 0-0- 0) in the matrix, where these interactions could have an arbitrary geometry specified by the 3x3x3 kernel. I have tried to think if there would be a more efficient way to implement this through the encoding of the matrix as a graph of some kind, but I am not familiar enough with that infrastructure in Mathematica to make much progress. Any help or advice to optimize this calculation would be greatly appreciated.

The work code: given a large but scattered three-dimensional matrix, M (which I create here through GrowRandArray), and a set of small 3x3x3 cores (here randomly selected from all possible 3x3x3 permutations of binary matrices with 3 1s), there is a more efficient way to implement "GetCounts" below:

```
GrowRandArray[percent_, size_] : = Module[{locs, phaseb, phase},
locs = Flatten[
Table[{i, j, k}, {i, 1, size}, {j, 1, size}, {k, 1, size}], two];
phaseb = RandomSample[locs, Ceiling[percent*size^3]];
phase =
SparseArray[
phaseb -> ConstantArray[1, Length[phaseb]], {size, size, size}]](* this is only to generate the large matrix for this example *)
GetCounts[Mat_, kernels_, num_] : =
Tell[Flatten[ListConvolve[#, Mat, 1] & / @ kernels], #]& / @
Distance[0, num];
M = GrowRandArray[0.1, 30];
kernelsFull =
ArrayReshape[#, {3, 3, 3}] & / @
Permutations[{1, 1, 1}~Join~ConstantArray[0, 3^3 - 3]];
kernels = RandomSample[kernelsFull, 20];
GetCounts[M, kernels, 3]
```