# %% [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_ROOT2, 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 = "grid3" # 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_{deployment}/*/*.csv" ) audio_files = glob(f"{REDACTED_RESAMPLED_ROOT2}/*/*.WAV") out_dir = f"{REDACTED_OUTPUT_DIR}/localized_detections/loca2023{deployment}/" # 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_grid3.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) # remove files from recorders missing/incorrect metadata cards_to_remove = [ c for c in file_position_df.card.unique() if not c in card_locs.index.values ] cards_to_remove += ["MSD-1654"] # this card was listed as deployed at two locations # remove files for these cards, which have no/conflicting deployment metadata file_position_df = file_position_df[ file_position_df["card"].apply(lambda x: x not in cards_to_remove) ] # add coordinates to the table listing every audio file 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"]] # %% # load detections saved as sparse df detections = pd.read_pickle( f"{REDACTED_OUTPUT_DIR}/preds_aggregated/dets_{deployment}_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 # %% # create relative positions for c in file_coords.columns: file_coords[c] = file_coords[c] - file_coords[c].min() # file_coords_2d = file_coords[["x", "y"]] # use 3d for grid3! # %% # 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) 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'loca2023{deployment}_{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']]