pythonspectrum

Finding if there are n data points in a row that are less than a certain number


I am working with a spectrum in Python and I have fit a line to that spectrum. I want a code that can detect if there have been let's say, 10, data points on the spectrum in a row that are less than the fitted line. Does anyone know how a simple and quick way to do this?

I currently have something like this:

count = 0
for i in range(lowerbound, upperbound):
    if spectrum[i] < fittedline[i]
        count += 1
    if count > 15:
        *do whatever*

If I changed the first if statement line to be:

if spectrum[i] < fittedline[i] & spectrum[i+1] < fittedline[i+1] & so on

I'm sure the algorithm would work, but is there a smarter way for me to automate this in the case where I want the user to input a number for how many data points in a row must be less than the fitted line?


Solution

  • Your attempt is pretty close to working! For consecutive points, all you need to do is reset the count if one point doesn't satisfy your condition.

    num_points = int(input("How many points must be less than the fitted line? "))
    
    count = 0
    for i in range(lowerbound, upperbound):
        if spectrum[i] < fittedline[i]:
            count += 1
        else: # If the current point is NOT below the threshold, reset the count
            count = 0
    
        if count >= num_points:
            print(f"{count} consecutive points found at location {i-count+1}-{i}!")
    

    Let's test this:

    lowerbound = 0
    upperbound = 10
    
    num_points = 5
    
    spectrum = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    fittedline = [1, 2, 10, 10, 10, 10, 10, 8, 9, 10]
    

    Running the code with these values gives:

    5 consecutive points found at location 2-6!