I have a collection of tensors of common shape (2,ncol). Example:
torch.tensor([[1, 2, 3, 7, 8], [3, 3, 1, 8, 7]], dtype=torch.long)
For each tensor, I want to determine if, for each column [[a], [b]], the reversed column [[b], [a]] is also in the tensor. For example, in this case, since ncol is odd, I can immediately say that this is not the case. But in this other example
torch.tensor([[1, 2, 3, 7, 8, 4], [3, 3, 1, 8, 7, 2]], dtype=torch.long)
I would actually have to perform the check. A naive solution would be
test = torch.tensor([[1, 2, 3, 7, 8, 4], [3, 3, 1, 8, 7, 2]], dtype=torch.long)
def are_column_paired(matrix: torch_geometric.data.Data) -> bool:
ncol = matrix.shape[1]
if ncol % 2 != 0:
all_paired = False
return all_paired
column_has_match = torch.zeros(ncol, dtype=torch.bool)
for i in range(ncol):
if column_has_match[i]:
continue
column = matrix[:, i]
j = i + 1
while not (column_has_match[i]) and (j <= (ncol - 1)):
if column_has_match[j]:
j = j + 1
continue
current_column = matrix[:, j]
current_column = current_column.flip(dims=[0])
if torch.equal(column, current_column):
column_has_match[i], column_has_match[j] = True, True
j = j + 1
all_paired = torch.all(column_has_match).item()
return all_paired
But of course this is slow and possibly not pythonic. How can I write a more efficient code?
PS note that while test here is very small, in the actual use case I expect ncol to be O(10^5).