Search code examples
pythonfor-loopwhile-loopreset

Resetting value when another value switches sign


I have a dataset from the constant current charge/discharge of a battery. The data looks like this:

time = np.arange(0,100,1)
current_discharge = [-2 for i in np.arange(0,50,1)]
current_charge = [2 for i in np.arange(50,100,1)]
current = current_discharge + current_charge

I want to calculate the absolute charge (abs(time*current)) as a function of time. For this, I need to reset the charge to zero when the current switches from negative to positive (i.e. at 50).

In my code below, it substracts from the cumulative charge after 50. Instead, I want the cumulative charge to go to zero at 50 and increase afterwards.

cumsum = 0
dQ_list = []
totalcharge = []

for i, t in zip(current,time):
    dQ = -(t+1-t)*i
    dQ_list.append(dQ)
    cumsum += dQ
    totalcharge.append(cumsum)

fig = plt.figure()
ax1 = plt.axes((0,0,1,0.5))
ax1.plot(time,current, label = "current vs time")
ax1.plot(time,totalcharge, label = "charge vs time")
ax1.set_xlabel("Time")

ax1.legend()

Solution

  • I'm not sure if I 100% got it, but I think this one is what you need:

    charge_started = False  # Flag to track if charge accumulation started
    
    for i, t in zip(current, time):
        dQ = -(t + 1 - t) * i
        dQ_list.append(dQ)
        if i < 0:  # Check if current is negative, while the current retreives
                   # from current_discharge, it behaves as it was in your code
            cumsum += dQ
            charge_started = True
        elif charge_started:
            cumsum = 0  # Reset cumsum to 0 when current becomes positive, it goes
                        # here only once
            charge_started = False
        else:
            cumsum += -dQ # all the other current, i put a - because you told you
                          # wanna see the current increase, you can adjust it as 
                          # you wish
        totalcharge.append(cumsum)