Created
October 26, 2018 13:58
-
-
Save edobez/5784824c9158f6b9056e449bfbcaebb3 to your computer and use it in GitHub Desktop.
Time-level hysteresis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hyst(x, thr1, thr2, thr1_time = 0, thr2_time = 0, initial = False): | |
def level_hysteresis(sig, thr): | |
when_over = sig > thr | |
when_under = 1-when_over | |
where_under = np.where(when_over == 0)[0] | |
over_cumsum = np.cumsum(when_over) | |
under_cumsum = np.cumsum(when_under) | |
return np.maximum(0, over_cumsum - over_cumsum[where_under[under_cumsum-1]]) | |
over = level_hysteresis(x, thr2) | |
under = level_hysteresis(-x, -thr1) | |
level = over-under | |
hi = level > thr2_time | |
lo = level < -thr1_time | |
lo_or_hi = lo | hi | |
ind = np.nonzero(lo_or_hi)[0] | |
cnt = np.cumsum(lo_or_hi) | |
return np.where(cnt, hi[ind[cnt-1]], initial), level | |
if __name__ == "__main__": | |
import numpy as np | |
from matplotlib import pyplot as plt | |
from typing import List | |
thr1 = 0.5 | |
thr1_time = 0 | |
thr2 = 1 | |
thr2_time = 0 | |
x = np.linspace(0, 5, 1000) | |
y = np.sin(x)+0.7*np.sin(3*x) | |
val_histeresis = hyst(y, thr1, thr2, thr1_time=10, thr2_time=10) | |
f, ax = plt.subplots(3, 1, sharex=True) | |
ax: List[plt.axes] | |
ax[0].plot(x, y) | |
ax[0].hlines(thr1, x[0], x[-1]) | |
ax[0].hlines(thr2, x[0], x[-1]) | |
ax[0].grid() | |
ax[1].plot(x, val_histeresis[0]) | |
ax[1].grid() | |
ax[2].plot(x, val_histeresis[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment