Skip to content

Commit

Permalink
Add all and any functions (which were missing from numpy).
Browse files Browse the repository at this point in the history
  • Loading branch information
AngelEzquerra committed Jan 12, 2024
1 parent 4b5f1d9 commit d0e07fc
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 11 deletions.
36 changes: 36 additions & 0 deletions src/arraymancer/tensor/aggregate.nim
Original file line number Diff line number Diff line change
Expand Up @@ -400,3 +400,39 @@ proc nonzero*[T](arg: Tensor[T]): Tensor[int] =
result[ax, k] = j
inc ax
inc k

func all*[T](t: Tensor[T]): bool =
## Returns true if all of the items in the input tensor are true or non-zero
##
## Input:
## - A tensor
##
## Returns:
## - True if at least one element is not zero
result = true
when T is Complex:
const zero: T = complex(0.0, 0.0)
else:
const zero: T = 0.T
for it in t:
if it == zero:
result = false
break

func any*[T](t: Tensor[T]): bool =
## Returns true if any of the items in the input tensor is true or non-zero
##
## Input:
## - A tensor
##
## Returns:
## - True if at least one element is not zero
result = false
when T is Complex:
const zero: T = complex(0.0, 0.0)
else:
const zero: T = 0.T
for it in t:
if it != zero:
result = true
break
62 changes: 51 additions & 11 deletions tests/tensor/test_aggregate.nim
Original file line number Diff line number Diff line change
Expand Up @@ -243,18 +243,58 @@ proc main() =
[1, 9, 45],
[3, 12, 12]].toTensor

suite "Testing logic functions":
test "Nonzero":
block:
let a = [[3, 0, 0], [0, 4, 0], [5, 6, 0]].toTensor()
let exp = [[0, 1, 2, 2], [0, 1, 0, 1]].toTensor
check a.nonzero == exp

test "Nonzero":
block:
let a = [[3, 0, 0], [0, 4, 0], [5, 6, 0]].toTensor()
let exp = [[0, 1, 2, 2], [0, 1, 0, 1]].toTensor
check a.nonzero == exp

block:
let a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]].toTensor
let mask = a >. 3
let exp = [[1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2]].toTensor
check nonzero(mask) == exp
block:
let a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]].toTensor
let mask = a >. 3
let exp = [[1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2]].toTensor
check nonzero(mask) == exp

test "all":
let a = [[1, 2, 3], [-4, -5, -6]].toTensor
let b = [[0, 2, 3], [4, 5, 6]].toTensor
let ca = a.asType(Complex64)
let cb = b.asType(Complex64)

check:
# Tensor[int]
all(a) == true
all(b) == false
# Tensor[float]
all(a.asType(float)) == true
all(b.asType(float)) == false
# Tensor[bool]
all(a !=. 0) == true
all(b >. 0) == false
# Tensor[complex]
all(ca) == true
all(cb) == false

test "any":
let a = [0, 0, 1].toTensor
let b = [0, 0, 0].toTensor
let ca = a.asType(Complex64)
let cb = b.asType(Complex64)

check:
# Tensor[int]
any(a) == true
any(b) == false
# Tensor[float]
any(a.asType(float)) == true
any(b.asType(float)) == false
# Tensor[bool]
any(a !=. 0) == true
any(b >. 0) == false
# Tensor[complex]
any(ca) == true
any(cb) == false

main()
GC_fullCollect()

0 comments on commit d0e07fc

Please sign in to comment.