chadb
chadb

Reputation: 51

Bounded cumulative sum in python without looping

I need to perform a cumulative sum with bounds - kind of like the charge state of a capacitor. It can't go above its maximum charge, and can't go below 0. Something like:

Initial  Cumulative Sum Constrained Sum
 1        1               1
 7        8               8
 5        13              10
 -8       5               2
 -7       -2              0
 3        1               3

I have a piece of code:

charge_0 = 0
for i in range (1, len(charge_discharge)):
    charge_1 = min(battery_size,max(0,(charge_0+charge_discharge[i])))
    StorageSOC.append(charge_1)
    charge_0 = charge_1

It works faster than some other options, but I know it is not optimized. A simple cumulative sum is orders of magnitude faster, so I am sure there is a better way to do this. I can't just apply a clip at the bounds. What is the right way to do this without the for loop?

Upvotes: 1

Views: 564

Answers (2)

Glauco
Glauco

Reputation: 1465

In the example, j0 and j1 are not defined. no cumsum involved in this piece, please refer a mwe for the correct use of a question

This can be faster using vectorial approach on numpy or pandas, both have cumsum operation.

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54743

You don't need both old and new. And you're skipping element 0. This is a tiny bit faster, but I don't believe you can eliminate the loop.

charge = 0
for delta in charge_discharge:
    charge = min(battery_size,max(0,charge+delta))
    StorageSOC.append(charge)

Upvotes: 1

Related Questions