Skip to content

Commit

Permalink
Cumsum cumprod (#492)
Browse files Browse the repository at this point in the history
* Add cumsum and cumprod procedures"

* Add cumsum and cumprod procedures

* Adding cumsum and cumprod testes

* Add mixin

* create another test block for cumsum

* Import the broadcasting operators

Co-authored-by: Mamy Ratsimbazafy <mamy_github@numforge.co>
  • Loading branch information
filipeclduarte and mratsim authored Jan 20, 2021
1 parent 93200f2 commit 71cf616
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/arraymancer/tensor/aggregate.nim
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import ./data_structure,
./init_cpu,
./higher_order_foldreduce,
./operators_broadcasted,
./math_functions,
./accessors,
./algorithms,
Expand Down Expand Up @@ -245,3 +246,35 @@ proc iqr*[T](t: Tensor[T]): float =
let tS = t.sorted
result = percentile(tS, 75, isSorted = true) -
percentile(tS, 25, isSorted = true)

proc cumsum*[T](t: Tensor[T], axis:int): Tensor[T] = # from hugogranstrom
## Calculates the cumulative sum of a rank-n Tensor.
## Inputs:
## - t: a rank-n tensor to cumulatively sum
## - axis: int
## Returns:
## - A tensor cumulatively summed at axis, that is, add each value to
mixin `_`
result = zeros_like(t)
for i, tAxis in enumerateAxis(t, axis):
var temp = result.atAxisIndex(axis, i)
if i == 0:
temp[_] = tAxis
else:
temp[_] = result.atAxisIndex(axis, i-1) + tAxis

proc cumprod*[T](t: Tensor[T], axis:int): Tensor[T] = # from hugogranstrom
## Calculates the cumulative sum of a rank-n Tensor.
## Inputs:
## - t: a rank-n tensor to cumulatively sum
## - axis: int
## Returns:
## - A tensor cumulatively summed at axis, that is, add each value to
mixin `_`
result = zeros_like(t)
for i, tAxis in enumerateAxis(t, axis):
var temp = result.atAxisIndex(axis, i)
if i == 0:
temp[_] = tAxis
else:
temp[_] = result.atAxisIndex(axis, i-1) *. tAxis
26 changes: 26 additions & 0 deletions tests/tensor/test_aggregate.nim
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,31 @@ proc main() =
[[3], [3], [3]], [[3], [3], [3]]
].toTensor

test "cumsum":
let a = [[0, 4, 7],
[1, 9, 5],
[3, 4, 1]].toTensor

check: cumsum(a, 0) == [[0, 4, 7],
[1, 13, 12],
[4, 17, 13]].toTensor

check: cumsum(a, 1) == [[0, 4, 11],
[1, 10, 15],
[3, 7, 8]].toTensor
test "cumprod":
let a = [[0, 4, 7],
[1, 9, 5],
[3, 4, 1]].toTensor

check: cumprod(a, 0) == [[0, 4, 7],
[0, 36, 35],
[0, 144, 35]].toTensor

check: cumprod(a, 1) == [[0, 0, 0],
[1, 9, 45],
[3, 12, 12]].toTensor


main()
GC_fullCollect()

0 comments on commit 71cf616

Please sign in to comment.