Python scipy.signal.argrelmin() Examples

The following are 5 code examples of scipy.signal.argrelmin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.signal , or try the search function .
Example #1
Source File: detect.py    From yass with Apache License 2.0 6 votes vote down vote up
def voltage_threshold(recording, threshold, order=5):

    T, C = recording.shape
    spike_index = np.zeros((0, 2), 'int32')
    energy = np.zeros(0, 'float32')
    for c in range(C):
        single_chan_rec = recording[:, c]
        index = argrelmin(single_chan_rec, order=order)[0]
        index = index[single_chan_rec[index] < -threshold]
        spike_index_temp = np.vstack((index,
                                      np.ones(len(index), 'int32')*c)).T
        spike_index = np.concatenate((spike_index, spike_index_temp), axis=0)
        energy_ = np.abs(single_chan_rec[index])
        energy = np.hstack((energy, energy_))

    return spike_index, energy 
Example #2
Source File: oracle.py    From btgym with GNU Lesser General Public License v3.0 5 votes vote down vote up
def estimate_actions(self, episode_data):
        """
        Estimates hold/buy/sell signals based on local peaks filtered by time horizon and signal amplitude.

        Args:
            episode_data:   1D np.array of unscaled [but possibly resampled] price values in OHL[CV] format

        Returns:
            1D vector of signals of same length as episode_data
        """
        # Find local maxima and minima indices within time horizon:
        max_ind = signal.argrelmax(episode_data, order=self.time_threshold)
        min_ind = signal.argrelmin(episode_data, order=self.time_threshold)
        indices = np.append(max_ind, min_ind)
        # Append first and last points:
        indices = np.append(indices, [0, episode_data.shape[0] - 1])
        indices = np.sort(indices)

        indices_and_values = []

        for i in indices:
            indices_and_values.append([episode_data[i], i])

        # Filter by value:
        indices_and_values = self.filter_by_margine(indices_and_values, self.value_threshold)

        #print('filtered_indices_and_values:', indices_and_values)

        # Estimate advised actions (no 'close' btw):
        # Assume all 'hold':
        advice = np.ones(episode_data.shape[0], dtype=np.uint32) * self.action_space[0]

        for num, (v, i) in enumerate(indices_and_values[:-1]):
            if v < indices_and_values[num + 1][0]:
                advice[i] = self.action_space[1]

            else:
                advice[i] = self.action_space[2]

        return advice 
Example #3
Source File: signal.py    From PPG with MIT License 5 votes vote down vote up
def find_extrema(signal):
    signal = np.array(signal)
    extrema_index = np.sort(np.unique(np.concatenate((argrelmax(signal)[0], argrelmin(signal)[0]))))
    extrema = signal[extrema_index]
    return zip(extrema_index.tolist(), extrema.tolist()) 
Example #4
Source File: extract_yd.py    From deda with GNU General Public License v3.0 4 votes vote down vote up
def _getDotDistance(self, dots, axis):
        """ calculates dot distance from dist. between all neighbouring dots
        """
        # create distance matrix distM of dots
        z = np.array([complex(d[0],d[1]) for d in dots])
        #z = dots[:,axis] # TODO: test, ob alles auch hiermit funktionieren würde
        try:
            distM = abs(z[..., np.newaxis] - z)
        except MemoryError:
            self._raise(TooManyDotsException,self.ydPerInch)
        del z
        distM[distM==0] = np.max(distM)+1
        neighbours = np.argmin(distM, axis=0)
        #distances = distM.flat
        #distances = [abs(dots[i,axis]-dots[j,axis]) for i,j in enumerate(neighbours) if dots[i,axis]!=dots[j,axis]]
        distances = np.abs(dots[:,axis]-dots[neighbours,axis])
        distances = distances[distances>0]
        
        f = np.bincount(np.array(distances,dtype=np.uint16))
        #print(f[:15])
        #return np.argmax(f)
        self._print(3,"\n%s\n"%f[:30])
        maxima = np.array(argrelmax(f.argsort().argsort())[0])
        #maxima = [m for m in maxima if np.argmax(f)%m==0]
        MIN_DOT_DISTANCE = 0.01 # inches
        minDist = int(MIN_DOT_DISTANCE*self.imgDpi)
        if len(f[minDist:]) == 0: 
            self._raise(YDExtractingException,"Dot distances below minimum")
        maximum = np.argmax(f[minDist:])+minDist
        distance = maximum/2 if maximum/2.0 in maxima and float(maximum)/self.imgDpi==0.04 else maximum # because of Ricoh's marking dot
        """
        maxima_vals = f[maxima]
        threshold = np.percentile(f,93) #TODO schreiben TODO: oder percentile(f,...)?
        maxima = maxima[maxima_vals>threshold]
        maxima = [x for x in maxima if x<2 or x>len(f)-1-2 or not(f[x-2]<f[x] and f[x+2]>f[x] or f[x-2]>f[x] and f[x+2]<f[x])] #exclude hills on the way to maximum  #TODO: schreiben removed
        # a=f[x-2]-f[x]; b=f[x+2]-f[x]; a<0 and b>0 or a>0 and b<0 gdw a*b<0
        # pitch1 = 
        distance = maxima[1]
        """
        return distance

        """
        # calculate dmin from distribution of $distances 
        # distances for each dot to its closest one
        distances = np.min(distM, axis=0)
        del distM
        #div=100.0 #FIXME: depends on scaling? (hier: float2int)
        div = 1
        distances = np.array((distances*div).round(),dtype=np.int32)
        count = np.bincount(distances)
        maxima = argrelmax(count.argsort().argsort())[0]
        minima = argrelmin(count.argsort().argsort())[0]
        #dMin = minima[0]
        MIN_DOT_DISTANCE = 4/300.0 # inches # TODO: automatic detection of dublicate dots instead
        minDist = int(MIN_DOT_DISTANCE*self.imgDpi*div)
        import ipdb;ipdb.set_trace()
        distance = (np.argmax(count[minDist:])+minDist)/div
        return distance
        return maxima[1]
        """ 
Example #5
Source File: extract_yd.py    From deda with GNU General Public License v3.0 4 votes vote down vote up
def findPatternLen(self, m):
        distM = np.zeros(shape=(m.shape[0],m.shape[0]))
        z = m.copy()
        z[z==0] = -1
        z[z==.5] = 0
        for i in xrange(m.shape[0]):
            a = z[i]*z
            total = np.sum(a!=0,axis=1)
            a[a==1] = 0
            distM[i] = np.abs(np.sum(a,axis=1))/total
        # remove cols without ones:
        ones = np.sum(z==1,axis=1)
        remove = ones<=0
        distM[:,remove] = np.nan
        distM[remove,:] = np.nan
        
        div=50.0
        f = np.bincount(np.array((distM[np.isnan(distM)==False]*div).round(),dtype=np.int32).flat)
        minima = argrelmin(f.argsort().argsort())[0]
        if len(minima) > 1:
            threshold = minima[0]/div
        elif len(f)>0:
            threshold = f.argmax()/2/div
        else: threshold = 0
        self._print(3,"threshold=%f\n"%threshold)

        X1, X2 = np.nonzero(distM<=threshold)
        #func = lambda arr: np.argmax(np.bincount(arr))
        func = np.median
        #func = np.average
        #func = lambda x: x
        distances = [
            func(self._distances(X1[X2==i]))
            for i in xrange(m.shape[0])
            if len(X1[X2==i])>1
            #and 1 in m[i]
            ]
        distFreq = np.bincount(np.array(distances,dtype=np.int32))
        self._print(3,"Pattern length frequencies: \n%s\n"%repr(distFreq))
        MIN_MATRIX_PATTERN_LENGTH = 5 #4
        MAX_MATRIX_PATTERN_LENGTH = None # 30
        distFreqWindow = distFreq[MIN_MATRIX_PATTERN_LENGTH:MAX_MATRIX_PATTERN_LENGTH]
        if len(distFreqWindow)==0:
            self._print(0,"WARNING: Cannot detect pattern length.\n")
            return -1
        period = np.argmax(distFreqWindow)+MIN_MATRIX_PATTERN_LENGTH
        return period