# -*- coding: utf-8 -*-
"""
Created on Wed Feb 25 14:16:18 2026

@author: chuffard
"""

#Python simple two-channel trigger fluorescence and attenuance: either or, not and

# -*- coding: utf-8 -*-
"""
Created on Thu Oct  3 13:10:10 2024

@author: chuffard
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 13:32:29 2024

@author: chuffard
"""

import numpy as np
from datetime import datetime
import numpy as np
import pandas as pd
import sys
import os.path
import warnings
import glob
warnings.filterwarnings("ignore")


#%%

path = '//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Analyses/2025 MARS deployment/2025July_Nov'

#%% bring in atn data
##before deployment fix inf in atn code and prep for triggering

atn_files = glob.glob(path+'/*sip*')
atn = pd.concat((pd.read_csv(f) for f in atn_files), ignore_index=True)
atn["DateTime"] = pd.to_datetime(atn["Datetime"])
atn = atn.sort_values(by='DateTime')
atn['atn'] = pd.to_numeric(atn['atn'], errors='coerce')
atn['rounded_hour'] = atn['DateTime'].dt.round('H')
numeric_colsatn = atn.select_dtypes(include=['number']).columns
atn = atn.groupby('rounded_hour')['atn'].mean(numeric_only=True).reset_index()
atn['rm150atn'] = atn['atn'].rolling(150, min_periods=23).mean()
atn['Slope_rm_150atn'] = atn['rm150atn'].diff()


#%% Bring in fluoro data and prep for triggering

# fluoro_files = glob.glob(path+'/*fluorom*')
# fluorescence = pd.concat((pd.read_csv(f) for f in fluoro_files), ignore_index=True)
# fluorescence["DateTime"] = pd.to_datetime(fluorescence["SES Timestamp (ISO601)"])

fluorescence = pd.read_csv('//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Deployments/2026 Mooring/Prep analyses/TestingTriggerDualChannel_fluorescence.csv')
fluorescence["DateTime"] = pd.to_datetime(fluorescence["SES Timestamp (ISO601)"])
fluorescence = fluorescence.sort_values(by='DateTime')
fluorescence['Fluorescense_690'] = fluorescence['Fluorescense 690 Counts']-fluorescence['Dark Ref 690 Counts']
fluorescence['rounded_hour'] = fluorescence['DateTime'].dt.round('H')
fluorescence = fluorescence.groupby('rounded_hour').mean(numeric_only=True).reset_index()
#Round to nearest hour first. This will make it easier to combine later.
fluorescence['rm150Fluorescense_690'] = fluorescence['Fluorescense_690'].rolling(150, min_periods=23).mean()
fluorescence['Slope_rm_150fluoro'] = fluorescence['rm150Fluorescense_690'].diff()

#%% Triggering values

lowtrigger_atn = 0.007 #>97th percentile 
hightrigger_atn = 0.011# = 99.1th percentile- find percentiles from all MARS atn


hightrigger_fluoro= 2.4
lowtrigger_fluoro= 1.8  
use_min_period = 24
# filename = sys.argv[1]
# nrec = int(sys.argv[2])
nrec=150
#Find diff in slope
#trim first 150

#%% Trigger code
#Combine by floor minute
merged_df = pd.merge(atn[['rounded_hour','rm150atn' ,'Slope_rm_150atn']], fluorescence[['rounded_hour', 'rm150Fluorescense_690','Slope_rm_150fluoro']], on='rounded_hour', how='outer')

# #Start with high triggers

merged_df["TriggerHigh_atn"] = np.where(merged_df['Slope_rm_150atn'] >= hightrigger_atn, 'Trigger', 'Wait')
merged_df['Rate_HighTrigger_atn'] = (merged_df['TriggerHigh_atn'] == 'Trigger').rolling(144, min_periods=2).sum()
merged_df['Max_HighTrigger_rate_atn'] =  merged_df['Rate_HighTrigger_atn'].cummax()

merged_df["TriggerLow_atn"] = np.where(merged_df['Slope_rm_150atn'] >= lowtrigger_atn, 'Trigger', 'Wait')
merged_df['Rate_LowTrigger_atn'] = (merged_df['TriggerLow_atn'] == 'Trigger').rolling(144, min_periods=2).sum()
merged_df['Max_LowTrigger_rate_atn'] =  merged_df['Rate_LowTrigger_atn'].cummax()

# #If starting trigger is high, and trigger rate is low then lower threshold
# #If starting trigger rate is low and trigger rate is too high then raise threshold

conditionsatn = [
    (merged_df['Rate_LowTrigger_atn']  <= 1), #fire one low, then switch to high trigger
    (merged_df['Rate_HighTrigger_atn'] <= 1), #fire two high, then switch to higher trigger
    (merged_df['Rate_HighTrigger_atn'] ==3), #fire more 3 highs then even higher trigger
    (merged_df['Max_HighTrigger_rate_atn'] >= 4),#fire four or more highs, then use max trigger
    ((merged_df['Rate_HighTrigger_atn']).rolling(window=240, min_periods=1).sum()==0), #more than 1.5 week since last trigger, use the lower gear
    ]


# Define corresponding choices (results)
choicesatn = [np.where(merged_df['Slope_rm_150atn'] >= lowtrigger_atn, 'FireLow', 'Wait'), 
           np.where(merged_df['Slope_rm_150atn'] >= hightrigger_atn, 'FireHigh', 'Wait'), 
           np.where(merged_df['Slope_rm_150atn'] >= (hightrigger_atn*1.1), 'Fire1_1High', 'Wait'),
           np.where(merged_df['Slope_rm_150atn'] >= (hightrigger_atn*1.2), 'Fire1_2High', 'Wait'),
           np.where(merged_df['Slope_rm_150atn'] >= (hightrigger_atn), 'Fire_High', 'Wait')]
           
merged_df["Fire_trigger_atn"] = np.select(conditionsatn, choicesatn, default='Wait')

merged_df["TriggerHigh_fluoro"] = np.where(merged_df['Slope_rm_150fluoro'] >= hightrigger_fluoro, 'Trigger', 'Wait')
merged_df['Rate_HighTrigger_fluoro'] = (merged_df['TriggerHigh_fluoro'] == 'Trigger').rolling(144, min_periods=2).sum()
merged_df['Max_HighTrigger_rate_fluoro'] =  merged_df['Rate_HighTrigger_fluoro'].cummax()

merged_df["TriggerLow_fluoro"] = np.where(merged_df['Slope_rm_150fluoro'] >= lowtrigger_fluoro, 'Trigger', 'Wait')
merged_df['Rate_LowTrigger_fluoro'] = (merged_df['TriggerLow_fluoro'] == 'Trigger').rolling(144, min_periods=2).sum()
merged_df['Max_LowTrigger_rate_fluoro'] =  merged_df['Rate_LowTrigger_fluoro'].cummax()


conditionsfluoro = [
    (merged_df['Rate_LowTrigger_fluoro']  <= 1), #fire one low, then switch to high trigger
    (merged_df['Rate_HighTrigger_fluoro'] <= 2), #fire two high, then switch to higher trigger
    (merged_df['Rate_HighTrigger_fluoro'] ==3), #fire more 3 highs then even higher trigger
    (merged_df['Max_HighTrigger_rate_fluoro'] >= 4),#fire four or more highs, then use max trigger
    ((merged_df['Rate_HighTrigger_fluoro']).rolling(window=240, min_periods=1).sum()==0), #more than 1.5 week since last trigger, use the lower gear
    ]


# Define corresponding choices (results)
choicesfluoro = [np.where(merged_df['Slope_rm_150fluoro'] >= lowtrigger_fluoro, 'FireLow', 'Wait'), 
           np.where(merged_df['Slope_rm_150fluoro'] >= hightrigger_fluoro, 'FireHigh', 'Wait'), 
           np.where(merged_df['Slope_rm_150fluoro'] >= (hightrigger_fluoro*1.1), 'Fire1_1High', 'Wait'),
           np.where(merged_df['Slope_rm_150fluoro'] >= (hightrigger_fluoro*1.2), 'Fire1_2High', 'Wait'),
           np.where(merged_df['Slope_rm_150fluoro'] >= (hightrigger_fluoro), 'Fire_High', 'Wait')]
           
merged_df["Fire_trigger_fluoro"] = np.select(conditionsfluoro, choicesfluoro, default='Wait')


merged_df['combined_fire'] = np.where(merged_df['Fire_trigger_atn'].str.contains('ire')|merged_df['Fire_trigger_fluoro'].str.contains('ire'), 'Fire', 'Wait')

merged_df["Get_Down"] = np.where(
    (merged_df['combined_fire'] != 'Wait').rolling(window=48, min_periods=1).sum()==1,
    np.where((merged_df['combined_fire'] != 'Wait'), 'Fire!', 'Wait'),
    np.where(((merged_df['combined_fire'] == 'Wait').rolling(336, min_periods=2).sum()==0), 'Fire!', 'Wait'),
)

merged_df.to_csv('//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Deployments/2026 Mooring/Prep analyses/merged_df.csv')

#%% plotting to check. This yields 10 triggers from the last deployment, with a mix of triggers from atn vs fluoro, 
#
import matplotlib.pyplot as plt
import seaborn as sns
palette =["#3776ab", "#FF8C00"]
merged_df['size_val'] = merged_df['Get_Down'].map({'Wait': 50, 'Fire!': 300})


fig, axes = plt.subplots(3, 1, figsize=(8, 10), sharex=True)

# 3. Create the first scatterplot (Top)
fig, axes = plt.subplots(2, 1, figsize=(10, 10))

# 2. Plot on the first axis (axes[0])
sns.scatterplot(
    data=merged_df,
    x="rounded_hour",
    y="rm150atn",
    hue="Get_Down",       # Color by 'sex'
    size="size_val", # Size by the new 'size_val' column
    sizes=(50, 250), 
    ax=axes[0],# Optional: control the min/max point size range
    alpha=0.6  # Optional: adjust transparency for overlap
)


# 3. Plot on the second axis (axes[1])
sns.scatterplot(
    data=merged_df,
    x="rounded_hour",
    y="rm150Fluorescense_690",
    hue="Get_Down",       # Color by 'sex'
    size="size_val", # Size by the new 'size_val' column
    sizes=(50, 250), 
    ax=axes[1],# Optional: control the min/max point size range
    alpha=0.6  # Optional: adjust transparency for overlap
)

# Adjust layout to prevent overlap
plt.tight_layout()
plt.show()
fig.savefig('//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Deployments/2026 Mooring/Prep analyses/triggerplots.pdf', dpi=300, bbox_inches='tight')



#%%
#old stuff

# # 1. Create a new 'size_val' column based on the 'sex' (hue)
# # Assign different size values for each category ('Male' = 100, 'Female' = 200)

# # 2. Create the scatter plot
# plt.figure(figsize=(8, 6))
# sns.scatterplot(
#     data=merged_df,
#     x="rounded_hour",
#     y="rm150atn",
#     hue="Get_Down",       # Color by 'sex'
#     size="size_val", # Size by the new 'size_val' column
#     sizes=(50, 250), # Optional: control the min/max point size range
#     alpha=0.6        # Optional: adjust transparency for overlap
# )

# plt.title("Get vs down")
# plt.show()



























# # #If starting trigger is high, and trigger rate is low then lower threshold
# # #If starting trigger rate is low and trigger rate is too high then raise threshold

# conditionsfluoro = [
#     (merged_df['Max_LowTrigger_rate_fluoro']  <= 2),
#     (merged_df['Rate_HighTrigger_fluoro'] <= 2),
#     (merged_df['Rate_HighTrigger_fluoro'] > 2)&(merged_df['Max_HighTrigger_rate_fluoro'] < 4),
#     (merged_df['Max_HighTrigger_rate_fluoro'] >= 4)]


# # Define corresponding choices (results)
# choicesfluoro = [np.where(merged_df['Slope_rm_150fluoro'] >= lowtrigger_Fluoro, 'FireLow', 'Wait'), 
#            np.where(merged_df['Slope_rm_150fluoro'] >= hightrigger_Fluoro, 'FireHigh', 'Wait'), 
#            np.where(merged_df['Slope_rm_150fluoro'] >= (hightrigger_Fluoro*1.1), 'Fire1_1High', 'Wait'),
#            np.where(merged_df['Slope_rm_150fluoro'] >= (hightrigger_Fluoro*1.2), 'Fire1_2High', 'Wait')]
           
# merged_df["Fire_trigger_Fluoro"] = np.select(conditionsfluoro, choicesfluoro, default='Wait')

# #############
# ##########

# merged_df['combined_fire'] = np.where(merged_df['Fire_trigger_atn'].str.contains('ire')|merged_df['Fire_trigger_Fluoro'].str.contains('ire'), 'Fire', 'Wait')

# merged_df["Get_Down"] = np.where(
#     (merged_df['combined_fire'] != 'Wait').rolling(window=48, min_periods=1).sum()==1,
#     np.where((merged_df['combined_fire'] != 'Wait'), 'Fire!', 'Wait'),
#     np.where(((merged_df['combined_fire'] == 'Wait').rolling(336, min_periods=2).sum()==0), 'Fire!', 'Wait'),
# )



















# # Conditions_merged = [
# #     (merged_df['Fire_trigger_atn'] =='*Fire*'),
# #     ((merged_df['Fire_trigger_atn'] != 'Wait').rolling(window=48, min_periods=1).sum()==1),

    
    
    
    
    
# #     ((merged_df['Fire_trigger_atn'] == 'Wait').rolling(336, min_periods=2).sum()==0),
    
    
# #     (merged_df['Rate_HighTrigger_fluoro'] <= 2),
# #     (merged_df['Rate_HighTrigger_fluoro'] > 2)&(merged_df['Max_HighTrigger_rate_fluoro'] < 4),
# #     (merged_df['Max_HighTrigger_rate_fluoro'] >= 4)]


# # # Define corresponding choices (results)
# # choicesfluoro = [(np.where((merged_df['Fire_trigger_atn'] != 'Wait'))|(np.where(((merged_df['Fire_trigger_Fluoro'] == 'Wait').rolling(336, min_periods=2).sum()==0))), 'Fire_atn', 'Wait'), 
# #            np.where(merged_df['Slope_rm_150_fluoro'] >= hightrigger_Fluoro, 'FireHigh', 'Wait'), 
# #            np.where(merged_df['Slope_rm_150_fluoro'] >= (hightrigger_Fluoro*1.1), 'Fire1_1High', 'Wait'),
# #            np.where(merged_df['Slope_rm_150_fluoro'] >= (hightrigger_Fluoro*1.2), 'Fire1_2High', 'Wait')]
           
# # merged_df["Fire_trigger_Fluoro"] = np.select(conditionsfluoro, choicesfluoro, default='Wait')









# # ###########

# # merged_df["Get_Down"] = np.where(
# #     (merged_df['Fire_trigger_atn'] != 'Wait').rolling(window=48, min_periods=1).sum()==1,
# #     np.where((merged_df['Fire_trigger_atn'] != 'Wait'), 'Fire_atn', 'Wait'),
# #     np.where(((merged_df['Fire_trigger_atn'] == 'Wait').rolling(336, min_periods=2).sum()==0), 'Fire!', 'Wait'),
# # )


# # merged_df["Get_Way_Down"] = np.where(
# #     (merged_df['Get_Down'] != 'Wait').rolling(window=48, min_periods=1).sum()==1,
# #     np.where((merged_df['Fire_trigger_Fluoro'] != 'Wait'), 'Fire_atn', 'Wait'),
# #     np.where(((merged_df['Fire_trigger_Fluoro'] == 'Wait').rolling(336, min_periods=2).sum()==0), 'Fire!', 'Wait'),
# # )







# # import timeit

# # def my_function():
# #     """The function to be timed."""
# #     total = 0
# #     for i in range(1000):
# #         total += i
# #     return total

# # # Time the function call (runs the function 10,000 times by default)
# # # Use a lambda to pass the function with arguments if needed
# # execution_time = timeit.timeit(lambda: my_function(), number=10000)

# # # Print the total time and average time per execution
# # print(f"Total time for 10,000 runs: {execution_time:.4f} seconds")
# # print(f"Average time per run: {execution_time / 10000:.6f} seconds")


# # # try:
# # #     # Ensure 'max_rate' column is not empty and the values are valid
# # #     if 'max_rate' in StationMcup.columns and not StationMcup['max_rate'].isnull().all():
# # #         # Apply condition element-wise to the 'max_rate' column
# # #         StationMcup["Fire_slope_trigger"] = np.where(
# # #             StationMcup['max_rate'].abs() >= 3,
# # #             np.where(StationMcup['slope'] >= hightrigger, 'Fire', 'Wait'),
# # #             np.where(StationMcup['slope'] >= lowtrigger, 'Fire', 'Wait')
# # #         )
# # #     else:
# # #         print("The 'max_rate' column is missing or contains all NaN values.")
# # # except Exception as e:
# # #     print(f"An error occurred: {e}")
    
# # #result = np.where(((arr > 2) & (arr < 6)) | (arr == 7), -1, 100)
# # #atn.to_csv('//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Deployments/2026 Mooring/Prep analyses/TestingTriggerDualChannel_atn.csv')
   
# # #%%


# # fluorescence["TriggerHigh_Fluoro"] = np.where(fluorescence['Slope_rm_150Fluoro'] >= hightrigger_Fluoro, 'Trigger', 'Wait')
# # fluorescence['Rate_HighTrigger_Fluoro'] = (fluorescence['TriggerHigh_Fluoro'] == 'Trigger').rolling(144, min_periods=2).sum()
# # fluorescence['Max_HighTrigger_rate_Fluoro'] =  fluorescence['Rate_HighTrigger_Fluoro'].cummax()

# # fluorescence["TriggerLow_Fluoro"] = np.where(fluorescence['Slope_rm_150Fluoro'] >= lowtrigger_Fluoro, 'Trigger', 'Wait')
# # fluorescence['Rate_LowTrigger_Fluoro'] = (fluorescence['TriggerLow_Fluoro'] == 'Trigger').rolling(144, min_periods=2).sum()
# # fluorescence['Max_LowTrigger_rate_Fluoro'] =  fluorescence['Rate_LowTrigger_Fluoro'].cummax()

# # # #If starting trigger is high, and trigger rate is low then lower threshold
# # # #If starting trigger rate is low and trigger rate is too high then raise threshold

# # conditions = [
# #     (fluorescence['Max_LowTrigger_rate_Fluoro']  <= 2),
# #     (fluorescence['Rate_HighTrigger_Fluoro'] <= 2),
# #     (fluorescence['Rate_HighTrigger_Fluoro'] > 2)&(fluorescence['Max_HighTrigger_rate_Fluoro'] < 4),
# #     (fluorescence['Max_HighTrigger_rate_Fluoro'] >= 4)]

# # #add no fires for two days after a trigger


# # # Define corresponding choices (results)
# # choices = [np.where(fluorescence['Slope_rm_150Fluoro'] >= lowtrigger_Fluoro, 'FireLow', 'Wait'), 
# #            np.where(fluorescence['Slope_rm_150Fluoro'] >= hightrigger_Fluoro, 'FireHigh', 'Wait'), 
# #            np.where(fluorescence['Slope_rm_150Fluoro'] >= (hightrigger_Fluoro*1.1), 'Fire1_1High', 'Wait'),
# #            np.where(fluorescence['Slope_rm_150Fluoro'] >= (hightrigger_Fluoro*1.2), 'Fire1_2High', 'Wait')]
           
# # fluorescence["Fire_trigger"] = np.select(conditions, choices, default='Wait')
    

# # #fluorescence.to_csv('//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Deployments/2026 Mooring/Prep analyses/TestingTriggerDualChannel_fluorescence.csv')
   







# # # #%% OG

# # # #### 
# # # use_min_period = 24
# # # atn = atn.sort_values(by='Datetime')

# # # atn['rm150atn'] = atn['atn'].rolling(150, min_periods=23).mean()
# # # atn['Slope_rm_150atn'] = atn['rm150atn'].diff()

# # # ##what percentil are these values
# # # atn['Percentile_Rank'] = atn['Slope_rm_150atn'].rank(pct=True) * 100

# # # lowtrigger = 0.007 #97.05 th percentile (1 away from 97.1th)
# # # hightrigger = 0.011# = 99.1th percentile
# # # atn["triggerNrecslope_atn"] = np.where(atn['Slope_rm_150atn'] >= lowtrigger, 'LowTriggeratn', 'WaitSlopeatn')

# # # nsamples_6weeks = 32
# # # if (len(atn) > nsamples_6weeks):
# # #     #find the rolling rate low triggers in past ~1.5 months
# # #     atn['low_trigger_rate'] = (atn['triggerNrecslope_atn'] == 'LowTriggeratn').rolling(nsamples_6weeks, min_periods=2).sum()

# # #     #Line to help keep tabs on whether the switch has been flipped and we're now using the high trigger

# # #     atn['max_rate'] = atn['low_trigger_rate'].cummax()

# # #     try:
# # #         # Ensure 'max_rate' column is not empty and the values are valid
# # #         if 'max_rate' in atn.columns and not atn['max_rate'].isnull().all():
# # #             # Apply condition element-wise to the 'max_rate' column
# # #             atn["Fire_slope_trigger"] = np.where(
# # #                 atn['max_rate'].abs() > 3,
# # #                 np.where(atn['Slope_rm_150atn'] >= hightrigger, 'Fire', 'Wait'),
# # #                 np.where(atn['Slope_rm_150atn'] >= lowtrigger, 'Fire', 'Wait')
# # #             )
# # #         else:
# # #             print("The 'max_rate' column is missing or contains all NaN values.")
# # #     except Exception as e:
# # #         print(f"An error occurred: {e}")

# # # #if doesn't fire in ~21 days, fire anyway
# # # matchlist = ['Wait'] * 30
# # # matchlist.insert(0,'Fire')

# # # def check_sequence(df, col_name, seq):
# # #     """
# # #     Checks if a sequence of values in a column matches a given list.

# # #     Args:
# # #         df: The DataFrame.
# # #         col_name: The name of the column to check.
# # #         seq: The sequence of strings to match.

# # #     Returns:
# # #         A new DataFrame with a 'match' column indicating if the sequence was found.
# # #     """

# # #     df['match'] = False
# # #     for i in range(len(df) - len(seq) + 1):
# # #         if df[col_name].iloc[i:i + len(seq)].tolist() == seq:
# # #             df.loc[i + len(seq) - 1, 'match'] = True
# # #     return df


# # # # Example usage:
# # # df = atn
# # # seq_to_match = matchlist

# # # df = check_sequence(df, 'Fire_slope_trigger', seq_to_match)
# # # df['match'] = df['match'].astype(str)
# # # df["Fire_anyway"] = np.where(df['match'].str.contains('T'), 'Fire', 'Wait')

# # # if (len(df) > nsamples_6weeks):
# # #     df['SendTrigger'] = np.where((df['Fire_anyway'] == 'Fire') |
# # #                         (df['Fire_slope_trigger'] =='Fire'), 'SendTrigger', 'Wait')
# # #     result = np.where((df['Fire_anyway'] == 'Fire') |
# # #              (df['Fire_slope_trigger'] =='Fire'), 'Event detected', 'Wait')
# # # else:
# # #     df['SendTrigger'] = np.where((df['Fire_anyway'] == 'Fire') |
# # #                         False, 'SendTrigger', 'Wait')
# # #     result = np.where((df['Fire_anyway'] == 'Fire') |
# # #              False, 'Event detected', 'Wait')

# # # # Emit result
# # # if (len(result) > 0):
# # #     print(result[len(result)-1])

# # # df.to_csv('//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Analyses/2025 MARS deployment/2025July_Nov/SES_triggered.csv', index=False)

# # df['Slope_rm_150atn'].hist(bins=100) 
# # df['z_score690slopeatn'] = stats.zscore(df['Slope_rm_150atn'], nan_policy='omit')

# # numeric_colsfluoro = df.select_dtypes(include=['number']).columns
# # datetime_column_name = df['Datetime']
# # is_datetime(df['Datetime'])

# # # 3. Save plots to a multi-page PDF
# # with PdfPages('all_sensor_plotsatn.pdf') as pdf:
# #     for col in numeric_colsfluoro:
# #         plt.figure(figsize=(10, 6)) # Create a new figure
# #         plt.plot(datetime_column_name, df[col], label=col)
# #         plt.title(f'Line Plot of {col}')
# #    #     plt.xlabel('DateTime_Hour')
# #         plt.ylabel('Value')
# #         plt.legend()
# #         plt.xticks(rotation=45) 
# #         plt.grid(True)
# #         # Save the current figure to the PDF
# #         pdf.savefig()
# #         plt.close() # Close to free up memory

# # print("PDF generated successfully: all_sensor_plots.pdf")

# # #%%
# # #! /usr/bin/env python

# # use_min_period = 24
# # fluoro = fluorescence.sort_values(by='DateTime')
# # fluoro.columns
# # fluoro['rm150fluoro'] = fluoro['Fluorescense_690'].rolling(150, min_periods=23).mean()
# # fluoro['Slope_rm_150fluoro'] = fluoro['rm150fluoro'].diff()
# # fluoro['z_score690slopefluoro'] = stats.zscore(df['Slope_rm_150fluoro'], nan_policy='omit')


# # threshold5 = fluoro['Slope_rm_150fluoro'].quantile(0.95)
# # threshold3 = fluoro['Slope_rm_150fluoro'].quantile(0.97)

# # lowtrigger =threshold5
# # hightrigger = threshold3
# # fluoro["triggerNrecslope_fluoro"] = np.where(fluoro['Slope_rm_150fluoro'] >= lowtrigger, 'LowTriggerfluoro', 'WaitSlopefluoro')

# # nsamples_6weeks = 32
# # if (len(fluoro) > nsamples_6weeks):
# #     #find the rolling rate low triggers in past ~1.5 months
# #     fluoro['low_trigger_rate'] = (fluoro['triggerNrecslope_fluoro'] == 'LowTriggerfluoro').rolling(nsamples_6weeks, min_periods=2).sum()

# #     #Line to help keep tabs on whether the switch has been flipped and we're now using the high trigger

# #     fluoro['max_rate'] = fluoro['low_trigger_rate'].cummax()

# #     try:
# #         # Ensure 'max_rate' column is not empty and the values are valid
# #         if 'max_rate' in fluoro.columns and not fluoro['max_rate'].isnull().all():
# #             # Apply condition element-wise to the 'max_rate' column
# #             fluoro["Fire_slope_trigger"] = np.where(
# #                 fluoro['max_rate'].abs() > 3,
# #                 np.where(fluoro['Slope_rm_150fluoro'] >= hightrigger, 'Fire', 'Wait'),
# #                 np.where(fluoro['Slope_rm_150fluoro'] >= lowtrigger, 'Fire', 'Wait')
# #             )
# #         else:
# #             print("The 'max_rate' column is missing or contains all NaN values.")
# #     except Exception as e:
# #         print(f"An error occurred: {e}")

# # #if doesn't fire in ~21 days, fire anyway
# # matchlist = ['Wait'] * 30
# # matchlist.insert(0,'Fire')

# # def check_sequence(df, col_name, seq):
# #     """
# #     Checks if a sequence of values in a column matches a given list.

# #     Args:
# #         df: The DataFrame.
# #         col_name: The name of the column to check.
# #         seq: The sequence of strings to match.

# #     Returns:
# #         A new DataFrame with a 'match' column indicating if the sequence was found.
# #     """

# #     df['match'] = False
# #     for i in range(len(df) - len(seq) + 1):
# #         if df[col_name].iloc[i:i + len(seq)].tolist() == seq:
# #             df.loc[i + len(seq) - 1, 'match'] = True
# #     return df


# # # Example usage:
# # df = fluoro
# # seq_to_match = matchlist

# # df = check_sequence(df, 'Fire_slope_trigger', seq_to_match)
# # df['match'] = df['match'].astype(str)
# # df["Fire_anyway"] = np.where(df['match'].str.contains('T'), 'Fire', 'Wait')

# # if (len(df) > nsamples_6weeks):
# #     df['SendTrigger'] = np.where((df['Fire_anyway'] == 'Fire') |
# #                         (df['Fire_slope_trigger'] =='Fire'), 'SendTrigger', 'Wait')
# #     result = np.where((df['Fire_anyway'] == 'Fire') |
# #              (df['Fire_slope_trigger'] =='Fire'), 'Event detected', 'Wait')
# # else:
# #     df['SendTrigger'] = np.where((df['Fire_anyway'] == 'Fire') |
# #                         False, 'SendTrigger', 'Wait')
# #     result = np.where((df['Fire_anyway'] == 'Fire') |
# #              False, 'Event detected', 'Wait')

# # # Emit result
# # if (len(result) > 0):
# #     print(result[len(result)-1])

# # df.to_csv('//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Analyses/2025 MARS deployment/2025July_Nov/SES_triggeredFluoro.csv', index=False)

