Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Export cumsum procedure and expand to work on n-dim Tensors #491

Open
filipeclduarte opened this issue Jan 4, 2021 · 1 comment
Open

Comments

@filipeclduarte
Copy link
Contributor

I have three suggestions:

  1. Export cumsum procedure:
    proc cumsum[T: SomeFloat](p: Tensor[T]): Tensor[T] {.noInit.} =
proc cumsum[T: SomeFloat](p: Tensor[T]): Tensor[T] {.noInit.} =
  ## Calculates the cumulative sum of a vector.
  ## Inputs:
  ##  - p: a rank-1 tensor to cumulatively sum
  ##
  ## TODO: implement parallel prefix sum
  ## See: https://en.wikipedia.org/wiki/Prefix_sum#Algorithm_2:_Work-efficient
  ##
  ## Returns:
  ##  - A tensor cumulatively summed, that is, add each value to
  ##    all previous values, sequentially
  result = p.clone()
  assert p.rank == 1
  assert p.shape[1] == 0
  let n_rows = p.shape[0]
  for i in 1..<n_rows:
    result[i] += result[i-1]
  1. Generalize this procedure to work on n-dimensional Tensors.

  2. Create a procedure to do cumulative product cumprod that is similar to cumsum, but instead of sum, use prod.

@filipeclduarte
Copy link
Contributor Author

@HugoGranstrom suggested this proc cumprod at the discord:

proc cumsum*[T](t: Tensor[T], axis: int): Tensor[T] =
  ## 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
  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

Then I suggested to create the cumprod as:

proc cumprod*[T](t: Tensor[T], axis:int): Tensor[T] = # from hugogranstrom
  ## Calculates the cumulative product of a rank-n Tensor.
  ## Inputs:
  ##  - t: a rank-n tensor to cumulatively sum
  ##  - axis: int
  ## Returns:
  ##  - A tensor cumulatively product at axis, that is, product each value
  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

I think these are useful for numerous tasks in scientific computing and finance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant