From b85c2d69d67371b29307578e134a1c0bda036daf Mon Sep 17 00:00:00 2001 From: linarphy Date: Wed, 30 Aug 2023 01:49:51 +0200 Subject: [PATCH] Update how to find start and stop position of a peak --- classes/science/plate.py | 36 ++++++++++++++++++++---------------- function/utils.py | 31 ++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 17 deletions(-) diff --git a/classes/science/plate.py b/classes/science/plate.py index bdd0d48..0c2f6e7 100644 --- a/classes/science/plate.py +++ b/classes/science/plate.py @@ -271,16 +271,18 @@ class Plate: Set spectrum area """ self.spectrum = Border() + list_ = convolve( + mean( + self.data[ self.border.slice() ], + axis = 1 , + ) , + ones( 200 ), + 'valid' , + ) indexes = find_peak_low_high( - convolve( - mean( - self.data[ self.border.slice() ], - axis = 1 , - ) , - ones( 200 ), - 'valid' , - ), + list_ , + ( max( list_ ) + mean( list_ ) ) / 2, )[0] self.spectrum.y.min = indexes[0] + self.border.y.min + 100 @@ -289,15 +291,17 @@ class Plate: import matplotlib.pyplot as plt plt.imshow( self.data[ self.border.slice() ] , aspect = 'auto' ) plt.show() + list_ = convolve( + mean( + self.data[ self.border.slice() ], + axis = 0 , + ) , + ones( 200 ), + 'valid' , + ) indexes = find_peak_low_high( - convolve( - mean( - self.data[ self.border.slice() ], - axis = 0 , - ) , - ones( 200 ), - 'valid' , - ), + list_ , + mean( list_ ) + max( list_ ) / 2, )[0] self.spectrum.x.min = indexes[0] + self.border.x.min + 100 diff --git a/function/utils.py b/function/utils.py index e60ef12..2aee6d5 100644 --- a/function/utils.py +++ b/function/utils.py @@ -208,10 +208,39 @@ def near_value( list_ , value ): index = np.append( index , np.where( list_ == value ) ) return np.round( np.sort( index ) ).astype( int ) # triage -def find_peak_low_high( list_ ): +def find_peak_low_high( list_ , value ): """ Return index of start and end of the biggest peak in a list """ + indexes = near_value( + list_, + value, + ) + list_ = np.gradient( list_ ) + if list_[ indexes[0] ] < 0: + indexes.insert( 0 , 0 ) + if list_[ indexes[0] ] < 0: + indexes.insert( 0 , 0 ) # start with a descent + if list_[ indexes[-1] ] > 0: + indexes.append( len( list_ ) - 1 ) + if list_[ indexes[-1] ] > 0: + indexes.append( len( list_ ) - 1 ) # end with a rise + + if len( indexes ) % 2 == 1: + raise Exception( + 'number of peaks doesn\'t match what it should be' + ) + rises = [ + indexes[ i ] for i in range( 0 , len( indexes ) , 2 ) + ] + descents = [ + indexes[ i ] for i in range( 1 , len( indexes ) , 2 ) + ] + np.where( list_[ : rises[0] ] < 0 )[-1] + np.where( list_[ descents[ i - 1 ] : rises[ i ] ] < 0 )[-1] + np.where( list_[ rises[ i - 1 ] : descents[ i ] ] < 0 )[-1] + first_rise , last_rise = indexes[0] , indexes[0] + first_descent , last_descent = indexes[1] , indexes[1] min_diff = ( max( list_ ) - min( list_ ) ) * 0.001 max_high_value = max( list_ ) min_high_value = min( list_ )