If you want to drop negative contributions to the integrated area, we can simply take the source code np.trapz and rewrite it:
def abstrapz(y, x=None, dx=1.0): y = np.asanyarray(y) if x is None: d = dx else: x = np.asanyarray(x) d = np.diff(x) ret = (d * (y[1:] +y[:-1]) / 2.0) return ret[ret>0].sum()
Quick test:
np.trapz([-1,0,1]) 0.0 abstrapz([-1,0,1]) 0.5
If you just want to avoid areas where y less than zero, just mask the values โโof "y" less than zero to zero:
arr = np.array([-2,-1,0.5,1,2,1,0,5,3,0]) np.trapz(arr) 10.5 arr[arr<0] = 0 np.trapz(arr) 12.5
This is not the best way to do this, but it is a good approximation. If this is what you mean, I can update this.
I had to slightly modify your example, since trapz([-1,1]) will always return 0 by definition. We remove some functions this way, if you need to do this on multidimensional arrays, it is easy to add it back.
source share