daphne-eu / daphne

DAPHNE: An Open and Extensible System Infrastructure for Integrated Data Analysis Pipelines
Apache License 2.0
68 stars 62 forks source link

Working with mask #789

Closed stevanzou closed 4 months ago

stevanzou commented 4 months ago

Hi,

I want to use DaphneLib-Matrices combined with mask. Is this possible in DaphneLib or is a workaround needed?

Python code could be as follows: X[Y == 1] = 0 (X and Y are 2d arrays with the values 0 and 1)

Thanks in advance.

pdamme commented 4 months ago

Hi @stevanzou, this feature exists in DaphneDSL (the conditional ?:-operator known from several programming languages), so it was easy to add it to DaphneLib. You can now use the ifElse(thenVal, elseVal)-method on DaphneLib matrices. You call this method on the matrix that contains the mask (0/1 values). For every 1, the corresponging element from thenVal is returned; for every 0 the corresponding element from elseVal. Both thenVal and elseVal can be a matrix or a scalar. If they are matrices, they must have the same dimensions as the mask.

Example:

from daphne.context.daphne_context import DaphneContext

dc = DaphneContext()

M = (dc.seq(1, 8) % 3) == 1

X = dc.seq(1, 8)
Y = dc.seq(1, 8) * 10

# mat ? sca : sca
M.ifElse(3.141, 2.718).print().compute()
# mat ? mat : sca
M.ifElse(X, 0).print().compute()
# mat ? sca : mat
M.ifElse(0, Y).print().compute()
# mat ? mat : mat
M.ifElse(X, Y).print().compute()
DenseMatrix(8x1, double)
3.141
2.718
2.718
3.141
2.718
2.718
3.141
2.718
DenseMatrix(8x1, int64_t)
1
0
0
4
0
0
7
0
DenseMatrix(8x1, int64_t)
0
20
30
0
50
60
0
80
DenseMatrix(8x1, int64_t)
1
20
30
4
50
60
7
80

Even though it doesn't have an indexing-like notation, I think this is what you mean. If this solves your problem, please close this issue.