multiply a matrix by a vector in the Python Calculator filter

How do I multiply a matrix (array with number of components = 9) with a vector (array with number of components = 3) in the Python Calculator? I have a somewhat more complex expression that I want to do but it’s failing in the matrix vector multiplication. I’ve tried:

  • matrix*vector – this results in a 9 component array
  • multiply(matrix,vector) – also results in a 9 component array
  • numpy.matmul(matrix,vector) – results in an error message about unaligned shapes – ValueError: shapes (9261,3,3) and (9261,3) not aligned: 3 (dim 2) != 9261 (dim 0)

Thanks,
Andy

I think you need dot(matrix,vector) in this case.

OK, that’s weird. Wouldn’t that return a dot product (i.e., a scalar)?

Nope, not dot(matrix, vector) either. I tried that and got the following:

Traceback (most recent call last):
  File "/home/acbauer/Code/ParaView/debug/lib64/python3.6/site-packages/paraview/detail/calculator.py", line 212, in execute
    retVal = compute(inputs, expression, ns=variables)
  File "/home/acbauer/Code/ParaView/debug/lib64/python3.6/site-packages/paraview/detail/calculator.py", line 150, in compute
    retVal = eval(subEx, globals(), mylocals)
  File "<string>", line 1, in <module>
  File "/home/acbauer/Code/ParaView/debug/lib64/python3.6/site-packages/vtkmodules/numpy_interface/algorithms.py", line 99, in new_dfunc
    return apply_dfunc(dfunc, array1, val2)
  File "/home/acbauer/Code/ParaView/debug/lib64/python3.6/site-packages/vtkmodules/numpy_interface/algorithms.py", line 91, in apply_dfunc
    return dfunc(l[0], l[1])
  File "/home/acbauer/Code/ParaView/debug/lib64/python3.6/site-packages/vtkmodules/numpy_interface/internal_algorithms.py", line 292, in dot
    if a1.DataSet == a2.DataSet : va.DataSet = a1.DataSet
AttributeError: 'numpy.ndarray' object has no attribute 'DataSet'

It would be a scalar if both components were vectors ( 3 components). If I am not wrong the convention comes from numpy itself

  • If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

But I agree it is not intuitive or expected unless you have used numpy before.

Hm not sure what is wrong. I just tried the following:

  • Create fast uniform grid source
  • Python Calculator with expression strain(Swirl) to get a matrix (Array Name = M)
  • Python Calculator with expression dot(M,Swirl)

I think there are multiple bugs in the Python Calculator. I think there’s matrix transpose that shouldn’t be happening – https://gitlab.kitware.com/vtk/vtk/-/merge_requests/10414. I’m a bit concerned about how this works with AOS arrays too. I haven’t gotten there yet to verify functionality though.

Hmm, more weirdness – doing “mag(matrix)” results in a vector. I’m not sure that is what’s expected either.

For the original issue of matrix-vector products it looks like I can use np.einsum() – np.einsum('...jk,...j', matrix, vector)