[[9, 1, 4], [10, 1, 3], [0, 1, 2], [3, 1, 1], [9, 1, 1]], # Mendon [[6, 1, 2], [10, 1, 0], [8, 1, 4], [10, 1, 0], [10, 1, 5]], # TonyGrove [[7, 1, 0], [1, 1, 1], [10, 1, 0], [0, 1, 5], [1, 1, 3]] # WaterLab ] pdqParam = pd.DataFrame(pdqParams, columns=sensors, index=sites) print(pdqParam) ######################################### # TEMPERATURE # ######################################### # RULES BASED DETECTION # ######################################### maximum = 18 minimum = -2 temp_df = rules_detect.range_check(temp_df, maximum, minimum) length = 6 temp_df = rules_detect.persistence(temp_df, length) size = rules_detect.group_size(temp_df) temp_df = rules_detect.interpolate(temp_df) # MODEL CREATION # ######################################### p, d, q = pdqParam[sensor[0]][site] print("p: " + str(p)) print("d: " + str(d)) print("q: " + str(q)) model_fit, residuals, predictions = modeling_utilities.build_arima_model( temp_df['observed'], p, d, q, summary=True) # DETERMINE THRESHOLD AND DETECT ANOMALIES #
def ARIMA_detect(df, sensor, params, rules=False, plots=True, summary=True, output=True): """ """ print('\nProcessing ARIMA detections.') # RULES BASED DETECTION # if rules: df = rules_detect.range_check(df, params['max_range'], params['min_range']) df = rules_detect.persistence(df, params['persist']) size = rules_detect.group_size(df) df = rules_detect.interpolate(df) print(sensor + ' rules based detection complete. Longest detected group = ' + str(size)) # MODEL CREATION # [p, d, q] = params['pdq'] model_fit, residuals, predictions = modeling_utilities.build_arima_model( df['observed'], p, d, q, summary) print(sensor + ' ARIMA model complete.') # DETERMINE THRESHOLD AND DETECT ANOMALIES # threshold = anomaly_utilities.set_dynamic_threshold( residuals[0], params['window_sz'], params['alpha'], params['threshold_min']) threshold.index = residuals.index if plots: plt.figure() anomaly_utilities.plt_threshold(residuals, threshold, sensor) plt.show() print('Threshold determination complete.') detections = anomaly_utilities.detect_anomalies(df['observed'], predictions, residuals, threshold, summary=True) # WIDEN AND NUMBER ANOMALOUS EVENTS # df['labeled_event'] = anomaly_utilities.anomaly_events( df['labeled_anomaly'], params['widen']) df['detected_anomaly'] = detections['anomaly'] df['all_anomalies'] = df.eval('detected_anomaly or anomaly') df['detected_event'] = anomaly_utilities.anomaly_events( df['all_anomalies'], params['widen']) # DETERMINE METRICS # anomaly_utilities.compare_events(df, params['widen']) metrics = anomaly_utilities.metrics(df) e_metrics = anomaly_utilities.event_metrics(df) # OUTPUT RESULTS # if output: print('Model type: ARIMA') print('Sensor: ' + sensor) anomaly_utilities.print_metrics(metrics) print('Event based calculations:') anomaly_utilities.print_metrics(e_metrics) print('Model report complete\n') # GENERATE PLOTS # if plots: plt.figure() anomaly_utilities.plt_results(raw=df['raw'], predictions=detections['prediction'], labels=df['labeled_event'], detections=df['detected_event'], sensor=sensor) plt.show() ARIMA_detect = ModelWorkflow() ARIMA_detect.df = df ARIMA_detect.model_fit = model_fit ARIMA_detect.threshold = threshold ARIMA_detect.detections = detections ARIMA_detect.metrics = metrics ARIMA_detect.e_metrics = e_metrics return ARIMA_detect
def LSTM_detect_multivar(sensor_array, sensors, params, LSTM_params, model_type, name, rules=False, plots=True, summary=True, output=True, model_output=True, model_save=True): """ """ print('\nProcessing LSTM multivariate ' + str(model_type) + ' detections.') # RULES BASED DETECTION # if rules: size = dict() for snsr in sensors: sensor_array[snsr], r_c = rules_detect.range_check( sensor_array[snsr], params[snsr].max_range, params[snsr].min_range) sensor_array[snsr], p_c = rules_detect.persistence( sensor_array[snsr], params[snsr].persist) size[snsr] = rules_detect.group_size(sensor_array[snsr]) sensor_array[snsr] = rules_detect.interpolate(sensor_array[snsr]) print(snsr + ' maximum detected group length = ' + str(size[snsr])) print('Rules based detection complete.\n') # Create new data frames with raw and observed (after applying rules) and preliminary anomaly detections for selected sensors df_raw = pd.DataFrame(index=sensor_array[sensors[0]].index) df_observed = pd.DataFrame(index=sensor_array[sensors[0]].index) df_anomaly = pd.DataFrame(index=sensor_array[sensors[0]].index) for snsr in sensors: df_raw[snsr + '_raw'] = sensor_array[snsr]['raw'] df_observed[snsr + '_obs'] = sensor_array[snsr]['observed'] df_anomaly[snsr + '_anom'] = sensor_array[snsr]['anomaly'] print('Raw data shape: ' + str(df_raw.shape)) print('Observed data shape: ' + str(df_observed.shape)) print('Initial anomalies data shape: ' + str(df_anomaly.shape)) # MODEL CREATION # if model_type == 'vanilla': model = modeling_utilities.LSTM_multivar(df_observed, df_anomaly, df_raw, LSTM_params, summary, name, model_output, model_save) else: model = modeling_utilities.LSTM_multivar_bidir(df_observed, df_anomaly, df_raw, LSTM_params, summary, name, model_output, model_save) print('multivariate ' + str(model_type) + ' LSTM model complete.\n') # Plot Metrics and Evaluate the Model if plots: plt.figure() plt.plot(model.history.history['loss'], label='Training Loss') plt.plot(model.history.history['val_loss'], label='Validation Loss') plt.legend() plt.show() # DETERMINE THRESHOLD AND DETECT ANOMALIES # ts = LSTM_params['time_steps'] residuals = pd.DataFrame(model.test_residuals) residuals.columns = sensors predictions = pd.DataFrame(model.predictions) predictions.columns = sensors if model_type == 'vanilla': residuals.index = df_observed[ts:].index predictions.index = df_observed[ts:].index observed = df_observed[ts:] else: residuals.index = df_observed[ts:-ts].index predictions.index = df_observed[ts:-ts].index observed = df_observed[ts:-ts] threshold = dict() detections = dict() for snsr in sensors: threshold[snsr] = anomaly_utilities.set_dynamic_threshold( residuals[snsr], params[snsr]['window_sz'], params[snsr]['alpha'], params[snsr]['threshold_min']) threshold[snsr].index = residuals.index detections[snsr] = anomaly_utilities.detect_anomalies( observed[snsr + '_obs'], predictions[snsr], residuals[snsr], threshold[snsr], summary=True) if plots: plt.figure() anomaly_utilities.plt_threshold(residuals[snsr], threshold[snsr], sensors[snsr]) plt.show() print('Threshold determination complete.') # WIDEN AND NUMBER ANOMALOUS EVENTS # all_data = dict() for snsr in sensors: if model_type == 'vanilla': all_data[snsr] = sensor_array[snsr].iloc[ts:] else: all_data[snsr] = sensor_array[snsr].iloc[ts:-ts] all_data[snsr]['labeled_event'] = anomaly_utilities.anomaly_events( all_data[snsr]['labeled_anomaly'], params[snsr]['widen']) all_data[snsr]['detected_anomaly'] = detections[snsr]['anomaly'] all_data[snsr]['all_anomalies'] = all_data[snsr].eval( 'detected_anomaly or anomaly') all_data[snsr]['detected_event'] = anomaly_utilities.anomaly_events( all_data[snsr]['all_anomalies'], params[snsr]['widen']) # DETERMINE METRICS # metrics = dict() e_metrics = dict() for snsr in sensors: anomaly_utilities.compare_events(all_data[snsr], params[snsr]['widen']) metrics[snsr] = anomaly_utilities.metrics(all_data[snsr]) e_metrics[snsr] = anomaly_utilities.event_metrics(all_data[snsr]) # OUTPUT RESULTS # if output: for snsr in sensors: print('\nModel type: LSTM multivariate ' + str(model_type)) print('Sensor: ' + snsr) anomaly_utilities.print_metrics(metrics[snsr]) print('Event based calculations:') anomaly_utilities.print_metrics(e_metrics[snsr]) print('Model report complete\n') # GENERATE PLOTS # if plots: for snsr in sensors: plt.figure() anomaly_utilities.plt_results( raw=sensor_array[snsr]['raw'], predictions=detections[snsr]['prediction'], labels=sensor_array[snsr]['labeled_event'], detections=all_data[snsr]['detected_event'], sensor=snsr) plt.show() LSTM_detect_multivar = ModelWorkflow() LSTM_detect_multivar.sensor_array = sensor_array LSTM_detect_multivar.df_observed = df_observed LSTM_detect_multivar.df_raw = df_raw LSTM_detect_multivar.df_anomaly = df_anomaly LSTM_detect_multivar.model = model LSTM_detect_multivar.threshold = threshold LSTM_detect_multivar.detections = detections LSTM_detect_multivar.all_data = all_data LSTM_detect_multivar.metrics = metrics LSTM_detect_multivar.e_metrics = e_metrics return LSTM_detect_multivar
def LSTM_detect_univar(df, sensor, params, LSTM_params, model_type, name, rules=False, plots=True, summary=True, output=True, model_output=True, model_save=True): """ """ print('\nProcessing LSTM univariate ' + str(model_type) + ' detections.') # RULES BASED DETECTION # if rules: df = rules_detect.range_check(df, params['max_range'], params['min_range']) df = rules_detect.persistence(df, params['persist']) size = rules_detect.group_size(df) df = rules_detect.interpolate(df) print( sensor + ' rules based detection complete. Maximum detected group length = ' + str(size)) # MODEL CREATION # if model_type == 'vanilla': model = modeling_utilities.LSTM_univar(df, LSTM_params, summary, name, model_output, model_save) else: model = modeling_utilities.LSTM_univar_bidir(df, LSTM_params, summary, name, model_output, model_save) print(sensor + ' ' + str(model_type) + ' LSTM model complete.') if plots: plt.figure() plt.plot(model.history.history['loss'], label='Training Loss') plt.plot(model.history.history['val_loss'], label='Validation Loss') plt.legend() plt.show() # DETERMINE THRESHOLD AND DETECT ANOMALIES # ts = LSTM_params['time_steps'] threshold = anomaly_utilities.set_dynamic_threshold( model.test_residuals[0], params['window_sz'], params['alpha'], params['threshold_min']) if model_type == 'vanilla': threshold.index = df[ts:].index else: threshold.index = df[ts:-ts].index residuals = pd.DataFrame(model.test_residuals) residuals.index = threshold.index if plots: plt.figure() anomaly_utilities.plt_threshold(residuals, threshold, sensor) plt.show() if model_type == 'vanilla': observed = df[['observed']][ts:] else: observed = df[['observed']][ts:-ts] print('Threshold determination complete.') detections = anomaly_utilities.detect_anomalies(observed, model.predictions, model.test_residuals, threshold, summary=True) # WIDEN AND NUMBER ANOMALOUS EVENTS # if model_type == 'vanilla': df_anomalies = df.iloc[ts:] else: df_anomalies = df.iloc[ts:-ts] df_anomalies['labeled_event'] = anomaly_utilities.anomaly_events( df_anomalies['labeled_anomaly'], params['widen']) df_anomalies['detected_anomaly'] = detections['anomaly'] df_anomalies['all_anomalies'] = df_anomalies.eval( 'detected_anomaly or anomaly') df_anomalies['detected_event'] = anomaly_utilities.anomaly_events( df_anomalies['all_anomalies'], params['widen']) # DETERMINE METRICS # anomaly_utilities.compare_events(df_anomalies, params['widen']) metrics = anomaly_utilities.metrics(df_anomalies) e_metrics = anomaly_utilities.event_metrics(df_anomalies) # OUTPUT RESULTS # if output: print('Model type: LSTM univariate ' + str(model_type)) print('Sensor: ' + sensor) anomaly_utilities.print_metrics(metrics) print('Event based calculations:') anomaly_utilities.print_metrics(e_metrics) print('Model report complete\n') # GENERATE PLOTS # if plots: plt.figure() anomaly_utilities.plt_results( raw=df['raw'], predictions=detections['prediction'], labels=df['labeled_event'], detections=df_anomalies['detected_event'], sensor=sensor) plt.show() LSTM_detect_univar = ModelWorkflow() LSTM_detect_univar.df = df LSTM_detect_univar.model = model LSTM_detect_univar.threshold = threshold LSTM_detect_univar.detections = detections LSTM_detect_univar.df_anomalies = df_anomalies LSTM_detect_univar.metrics = metrics LSTM_detect_univar.e_metrics = e_metrics return LSTM_detect_univar
year, path="LRO_data/") # RULES DETECTION PARAMETERS # ######################################### maximum = [20, 2700, 9.5, 15] minimum = [-2, 150, 7.5, 5] length = [10, 10, 10, 20] # RULES BASED ANOMALY DETECTION # ######################################### # size = [] range_count = [] persist_count = [] for i in range(0, len(sensor_array)): sensor_array[sensor[i]], r_c = rules_detect.range_check( sensor_array[sensor[i]], maximum[i], minimum[i]) range_count.append(r_c) sensor_array[sensor[i]], p_c = rules_detect.persistence( sensor_array[sensor[i]], length[i]) persist_count.append(p_c) # s = rules_detect.group_size(sensor_array[sensor[i]]) # size.append(s) sensor_array[sensor[i]] = rules_detect.add_labels(sensor_array[sensor[i]], -9999) sensor_array[sensor[i]] = rules_detect.interpolate(sensor_array[sensor[i]]) # print(str(sensor[i]) + ' maximum detected group length = ' + str(size[i])) print('Rules based detection complete.\n') # ANOMALY DETECTION PARAMETERS # ######################################### window_sz = [30, 40, 20, 30]
# - Use a subset of raw data that is in decent shape without NaNs, -9999 values, or data gaps. # df_sub = df.loc['2017-01-01 00:00':'2017-07-01 00:00'] # - Use raw data that have been preprocessed to filter out extreme values and have drift correction applied. # - Either with raw or corrected data for training, use data that are not labeled as anomalous/corrected. # df_cor = df_cor.replace(-9999, np.NaN) # RULES BASED DETECTION # ######################################### # General sensor ranges for LRO data: # Temp min: -5, max: 30 # SpCond min: 100, max: 900 # pH min: 7.5, max: 9.0 # do min: 2, max: 16 maximum = 900 minimum = 150 df = rules_detect.range_check(df, maximum, minimum) length = 6 df = rules_detect.persistence(df, length) size = rules_detect.group_size(df) df = rules_detect.interpolate(df) ######################################### # LSTM Univariate Vanilla Model # ######################################### # MODEL CREATION # ######################################### # scales data, reshapes data, builds and trains model, evaluates model results time_steps = 10 samples = 5000 cells = 128
"\n\n###########################################\n#Processing data for site: " + sites[j] + ".\n###########################################") df_full, sensor_array = anomaly_utilities.get_data(sites[j], sensor, year, path="LRO_data/") # RULES BASED ANOMALY DETECTION # ######################################### range_count = [] persist_count = [] methods_output.rules_metrics = [] # size = [] for i in range(0, len(sensor_array)): sensor_array[sensor[i]], r_c = rules_detect.range_check( sensor_array[sensor[i]], site_params[j][i].max_range, site_params[j][i].min_range) range_count.append(r_c) sensor_array[sensor[i]], p_c = rules_detect.persistence( sensor_array[sensor[i]], site_params[j][i].persist) persist_count.append(p_c) # s = rules_detect.group_size(sensor_array[sensor[i]]) # size.append(s) sensor_array[sensor[i]] = rules_detect.add_labels( sensor_array[sensor[i]], -9999) sensor_array[sensor[i]] = rules_detect.interpolate( sensor_array[sensor[i]]) # print(str(sensor[i]) + ' longest detected group = ' + str(size[i])) # metrics for rules based detection # df_rules_metrics = sensor_array[sensor[i]]
sensors = ['temp', 'cond', 'ph', 'do'] years = [2014, 2015, 2016, 2017, 2018, 2019] df_full, sensor_array = anomaly_utilities.get_data(site, sensors, years, path="LRO_data/") #### Rules Based Anomaly Detection ######################################### range_count = dict() persist_count = dict() rules_metrics = dict() for snsr in sensor_array: sensor_array[snsr], range_count[snsr] = \ rules_detect.range_check(sensor_array[snsr], site_params[site][snsr]['max_range'], site_params[site][snsr]['min_range']) sensor_array[snsr], persist_count[snsr] = \ rules_detect.persistence(sensor_array[snsr], site_params[site][snsr]['persist'], output_grp=True) sensor_array[snsr] = rules_detect.add_labels(sensor_array[snsr], -9999) sensor_array[snsr] = rules_detect.interpolate(sensor_array[snsr]) # s = rules_detect.group_size(sensor_array[snsr]) # size.append(s) # print(str(snsr) + ' longest detected group = ' + str(size)) # metrics for rules based detection # df_rules_metrics = sensor_array[snsr] df_rules_metrics['labeled_event'] = anomaly_utilities.anomaly_events( df_rules_metrics['labeled_anomaly'], wf=0) df_rules_metrics['detected_event'] = anomaly_utilities.anomaly_events( df_rules_metrics['anomaly'], wf=0) anomaly_utilities.compare_events(df_rules_metrics, wf=0)