Graphegon / pygraphblas

GraphBLAS for Python
https://graphegon.github.io/pygraphblas/pygraphblas/index.html
Apache License 2.0
343 stars 27 forks source link

Typecasting during operations #59

Closed marci543 closed 4 years ago

marci543 commented 4 years ago

I would like to multiply 2 boolean matrices (A, B) and have the result as UINT64 (to count the number of possible paths).

Currently I have two solutions:

A = Matrix.from_lists([0, 0], [1, 2], [True]*2, 4, 4)
B = Matrix.from_lists([1, 2], [3, 3], [True]*2, 4, 4)
C = Matrix.sparse(UINT64, 4, 4)
A.mxm(B, semiring=UINT64.PLUS_TIMES, out=C)

print(A, A.type)
print(A.to_string())

print(B, B.type)
print(B.to_string())

print(C, C.type)
print(C.to_string())

assert C[0, 3] == 2

What is the intended way to cast a matrix/vector in pygraphblas? It looks like in GraphBLAS transpose method is the best way to cast a matrix: https://github.com/DrTimothyAldenDavis/GraphBLAS/blob/5e569f2fcb0597b4ad3c60fca1a4ff8e938fd111/Doc/GraphBLAS_UserGuide.tex#L9166-L9176

Is there a more convenient way to change types during an operation? A possible solution might be to infer the result type from the semiring/operator if applicable, otherwise add an optional typ parameter to all other operations.

Issue #42 might be related.

michelp commented 4 years ago

All good questions! For now the out parameter workaround is probably the most optimal. I like the idea of detecting the return type from the operator type, not sure if there's a gotcha there but it sounds reasonable and if someone doesn't like it they can use the out bypass.

michelp commented 4 years ago

Hi @marci543 I've pushed PR #72 which adds type promotion that takes the semiring, and left and right types into account when doing operations. Your example is now:

A = Matrix.from_lists([0, 0], [1, 2], [True]*2, 4, 4)
B = Matrix.from_lists([1, 2], [3, 3], [True]*2, 4, 4)
with UINT64.PLUS_TIMES:
    C = A @ B

print(A)
print(B)
print(C)

assert C[0, 3] == 2

    0 1 2 3
 0|   t t  | 0
 1|        | 1
 2|        | 2
 3|        | 3
    0 1 2 3
    0 1 2 3
 0|        | 0
 1|       t| 1
 2|       t| 2
 3|        | 3
    0 1 2 3
    0 1 2 3
 0|       2| 0
 1|        | 1
 2|        | 2
 3|        | 3
    0 1 2 3