# %% [markdown] # # Try localization # %% import sys sys.path.append("..") from loca_utils import SynchronizedRecorderArray import numpy as np import pandas as pd from glob import glob from pathlib import Path from time import time as timer from tqdm.autonotebook import tqdm from loca_utils import to_dict import json try: from redacted_paths import REDACTED_RESAMPLED_ROOT1, REDACTED_OUTPUT_DIR except ImportError: print("redacted paths not available in this compute environment") # %% [markdown] # # set up variables # choose only recordings starting at the same time? #fixed _estimate_delays and SpatialEvent, but check grouping logic # %% deployment = "loca2023grid2" # choose only recordings starting at the same time? #fixed _estimate_delays and SpatialEvent, but check grouping logic score_files = glob(f"{REDACTED_OUTPUT_DIR}/birdnet_preds/loca2023_grid1-2/*/*.csv") audio_files = glob(f"{REDACTED_RESAMPLED_ROOT1}/*/*.WAV") out_dir = f"{REDACTED_OUTPUT_DIR}/localized_detections/loca2023grid2/" # save json of SpatialEvents here # print(f"found {len(audio_files)} files for {deployment}") # len(score_files) # localization parameters min_n_receivers = 4 max_receiver_dist = 100 # try 60m and 100m cc_threshold = 0.01 # 0 # %% [markdown] # # Create table of audio files and recorder positions # # %% recorder_locations = pd.read_csv("../../resources/locations_utm_grid1-2.csv") # %% card_locs = recorder_locations.set_index("card_code") # %% file_position_df = pd.DataFrame({"file": audio_files}) file_position_df["card"] = file_position_df["file"].apply(lambda x: Path(x).parent.stem) file_position_df[["x", "y", "z"]] = [ card_locs.loc[c][["utm_E", "utm_N", "ortho_height"]] for c in file_position_df["card"] ] # format to match expectation of SynchronizedRecorderArray file_coords argument: # index=file path, columns = x,y,(optional z) position file_coords = file_position_df.set_index("file")[["x", "y", "z"]] # %% [markdown] # # Use localization tools to estimate song positions # %% [markdown] # since we need to concatenate all detections into one big df (is this efficient? or will it cause speed issues later?) # we should chunk analysis into small sections as much as possible, eg recording periods # %% # all recording periods from this grid files_subset = glob( f"{REDACTED_OUTPUT_DIR}/birdnet_preds/loca2023_grid1-2/*/*.csv" ) # only grid2 cards cards = card_locs[card_locs.grid == "grid2"].index.values files_subset = [f for f in files_subset if Path(f).parent.stem in cards] len(files_subset) # %% [markdown] # ## aggregate score dfs into sparse detection df # - Threshold detections # - make sparse df # - concatenate across all cards in the grid # # works well, one df is 20 M but 41 sparse dfs combined are only 1 M in memory! # %% [markdown] # instead of recomputing, load pickled df # %% # from scipy.sparse import csr_matrix # def make_spars_df(path): # d = pd.read_csv(path, index_col=[0, 1, 2]) # threshold = 1 # sp_arr = csr_matrix(d > threshold) # return pd.DataFrame.sparse.from_spmatrix(sp_arr, index=d.index, columns=d.columns) # sparse_detection_dfs = [make_spars_df(path) for path in tqdm(files_subset)] # detections = pd.concat(sparse_detection_dfs) # sp_counts = detections.astype(int).sum() # sp_list = sp_counts[sp_counts > 4].index.values # detections.to_pickle('./sparse_detections_grid1.pkl') # # detections.to_hdf('sparse_detections_grid1.h5', key='df', mode='w') # reloaded = pd.read_pickle('./sparse_detections_grid1.pkl') # reloaded.shape # (detections.astype(int).sum(0) == reloaded.astype(int).sum(0)).all() # filtered = detections[detections.astype(bool).sum(1)>0] # filtered.to_pickle('./sparse_detections_grid1_no_empty_rows.pkl') # %% detections = pd.read_pickle( f"{REDACTED_OUTPUT_DIR}/preds_aggregated/dets_grid2_thresh1.pkl" ) sp_counts = detections.astype(int).sum() sp_list = sp_counts[sp_counts > 4].index.values import warnings # warnings.simplefilter("always") # %% species_freq_ranges = pd.read_csv("../../resources/species_freq_ranges.csv").set_index( "scientific" ) bandpass_ranges = { sp: [species_freq_ranges.at[sp, "low_f"], species_freq_ranges.at[sp, "high_f"]] for sp in detections.columns } # warn if species missing bandpass ranges: sp_missing_f_range = [ species_freq_ranges.at[s, "english_common"] for s in sp_list if np.isnan(bandpass_ranges[s][0]) or bandpass_ranges[s][0] is None ] if len(sp_missing_f_range) > 0: warnings.warn( f"{len(sp_missing_f_range)} classes have detections but bandpass range is unspecified: \n{sp_missing_f_range}" ) sp_missing_f_range # %% [markdown] # ## localize detections # %% # create relative positions for c in file_coords.columns: file_coords[c] = file_coords[c] - file_coords[c].min() # %% # reposition for positive values with min 0 file_coords_2d = file_coords[["x", "y"]] # %% # array = SynchronizedRecorderArray(file_coords_2d) # sp = 'Setophaga pensylvanica' # events = array.create_candidate_events( # detections=detections[[sp]], # max_receiver_dist=max_receiver_dist, # min_n_receivers=min_n_receivers, # bandpass_ranges=bandpass_ranges, # cc_threshold=cc_threshold, # cc_filter='phat' # ) # len(events) # %% t0 = timer() array = SynchronizedRecorderArray(file_coords_2d) for sp in tqdm(sp_list): if bandpass_ranges[sp][0] is None or np.isnan(bandpass_ranges[sp][0]): continue # we'll just skip these classes for now? print(f"now localizing {sp} detections") localized_events, unlocalized_events = array.localize_detections( detections=detections[[sp]], max_receiver_dist=max_receiver_dist, min_n_receivers=min_n_receivers, bandpass_ranges=bandpass_ranges, return_unlocalized=True, cc_threshold=cc_threshold, localization_algorithm="soundfinder", num_workers=16, ) if len(localized_events) > 0: events_dict = {"localized_events": [to_dict(e) for e in localized_events]} with open( out_dir + f'loca2023grid2_{sp.replace(" ", "_")}_localized_events.json', "w+", ) as f: json.dump(events_dict, f) print(f"saved {len(localized_events)} localized {sp} detections to {out_dir}") else: print(f"Zero events localized for {sp}") print(f"time elapsed: {(timer()-t0)/60} min") print("finished all species") # %% # example of reloading the events: # from loca_utils import from_dict # with open('test_saving.json','r') as f: # reloaded_events = json.load(f) # events = [from_dict(d) for d in reloaded_events['localized_events']]