"""modifications to opso code to use timestamps, since files might not start at the same time""" import datetime from opensoundscape import audio import numpy as np from opensoundscape import Audio from opensoundscape import localization from opensoundscape.localization import SPEED_OF_SOUND import pytz import pandas as pd # TODO: allow max_receiver_dist to vary by species; allow speed_of_sound to be calculated based on device temperature measurements class GetStartTimestamp: def __init__(self) -> None: self.cached_file = "" self.cached_recording_start_time = None # self.tz = pytz.timezone("UTC") def __call__(self, index_tuple): file, start_time, _ = index_tuple try: if file == self.cached_file: recording_start_dt = self.cached_recording_start_time else: recording_start_dt = Audio.from_file(file, duration=0.0001).metadata[ "recording_start_time" ] self.cached_file = file self.cached_recording_start_time = recording_start_dt except Exception as exc: raise Exception( f"Failed to retrieve recording start time from metadata of file {file}." ) from exc # return self.tz.localize(recording_start_dt + datetime.timedelta(seconds=start_time)) # if not ( # type(recording_start_dt) == datetime.datetime # and recording_start_dt.tzinfo is not None # ): # pass return recording_start_dt + datetime.timedelta(seconds=start_time) class SpatialEvent(localization.SpatialEvent): def _estimate_delays(self): """Hidden method to estimate time delay of event relative to receiver_files[0] with gcc Performs Generalized Cross Correlation of each file against the first, extracting the segment of audio of length self.duration at self.start_time Assumes audio files are synchronized such that they start at the same time Uses the following attributes of the object: cc_filter: filter for generalized cross correlation, see opensoundscape.signal_processing.gcc() max_delay: only delays in +/- this range (seconds) will be considered for possible delay (see opensoundscape.signal_processing.tdoa()); If None, defaults to self.max_delay bandpass_range: bandpass audio to [low, high] frequencies in Hz before cross correlation If None, defaults to self.bandpass_range= Returns: list of time delays, list of max cross correlation values each list is the same length as self.receiver_files, and each value corresponds to the cross correlation of one file relative to the first file (self.receiver_files[0]) Effects: sets self.tdoas and self.cc_maxs with the same values as those returned """ # we want to extract clips extending (max_delay) sec before and after the clip the CNN made the prediction on extracted_clip_start_timestamp = ( self.start_timestamp.to_pydatetime() - datetime.timedelta(seconds=self.max_delay) ) # TODO: could allow pd._libs.tslibs.timestamps.Timestamp in Audio.from_file as well as datetime.datetime # if they behave the same extracted_clip_duration = self.duration + 2 * self.max_delay reference_audio = Audio.from_file( self.receiver_files[0], start_timestamp=extracted_clip_start_timestamp, # offset=self.start_time - self.max_delay, #should be equivalent duration=extracted_clip_duration, ) if not np.isclose(reference_audio.duration, extracted_clip_duration, atol=1e-3): # don't try to localize self.error_msg = "did not get audio clip of desired length" self.tdoas = None self.cc_maxs = None return None, None # bandpass once now to avoid repeating operation for each receiver # could be None, or could be (None, None) - in either case, don't bandpass if self.bandpass_range is not None and self.bandpass_range[0] is not None: reference_audio = reference_audio.bandpass( low_f=self.bandpass_range[0], high_f=self.bandpass_range[1], order=9 ) # estimate time difference of arrival (tdoa) for each file relative to the first # skip the first because we don't need to cross correlate a file with itself tdoas = [0] # first file's delay to itself is zero cc_maxs = [1] # set first file's cc_max to 1 # catch the receivers that have an issue and should be discarded # e.g. their file starts or end during the time-window, so estimate_delays is not possible bad_receivers_index = [] for index, file in enumerate(self.receiver_files[1:]): # can't assume the start time of other files is the same audio2 = Audio.from_file( file, start_timestamp=extracted_clip_start_timestamp, duration=extracted_clip_duration, ) # catch edge cases where the audio lengths do not match. if ( abs(len(audio2.samples) - len(reference_audio.samples)) > 1 ): # allow for 1 sample difference bad_receivers_index.append(index + 1) else: tdoa, cc_max = audio.estimate_delay( primary_audio=audio2, reference_audio=reference_audio, max_delay=self.max_delay, bandpass_range=self.bandpass_range, cc_filter=self.cc_filter, return_cc_max=True, skip_ref_bandpass=True, ) tdoas.append(tdoa) cc_maxs.append(cc_max) self.tdoas = np.array(tdoas) self.cc_maxs = np.array(cc_maxs) # delete the bad receivers from this SpatialEvent if len(bad_receivers_index) > 0: print( f"Warning: {len(bad_receivers_index)} receivers were discarded because their audio files were not the same length as the primary receiver." ) # drop the bad receivers from the list of files and locations self.receiver_files = [ file for index, file in enumerate(self.receiver_files) if index not in bad_receivers_index ] self.receiver_locations = np.array( [ location for index, location in enumerate(self.receiver_locations) if index not in bad_receivers_index ] ) return self.tdoas, self.cc_maxs def estimate_location( self, localization_algorithm="gillette", use_stored_tdoas=True, return_self=False, ): """ Estimate spatial location of this event. This method first estimates the time delays (TDOAS) using cross-correlation, then estimates the location from those TDOAS. Localization is performed in 2d or 3d according to the dimensions of self.receiver_locations (x,y) or (x,y,z) Note: if self.tdoas or self.receiver_locations is None, first calls self._estimate_delays() to estimate the time delays. If you want to change some parameters of the localization (e.g. try a different cc_threshold, or bandpass_range), you can set the appropriate attribute (e.g. self.cc_threshold = 0.01) before calling self.estimate_location(). Args: - localization_algorithm: algorithm to use for estimating the location of a sound event from the locations and time delays of a set of detections. Options are 'gillette' or 'soundfinder'. Default is 'gillette'. - use_stored_tdoas: if True, uses the tdoas stored in self.tdoas to estimate the location. If False, first calls self._estimate_delays() to estimate the tdoas. default: True - return_self: if True, returns the SpatialEvent object itself. This is used under the hood for parallelization. Returns: Location estimate as cartesian coordinates (x,y) or (x,y,z) (units: meters) - if `return_self` is True, instead returns `self` Effects: - if self.tdoas or self.cc_maxs are None, or if use_stored_tdoas is False, sets these two attribute in the call to self._estimate_delays() - sets 4 attributes: location_estimate, receivers_used_for_localization, distance_residuals, residual_rms - if self.tdoas is none even after calling _estimate_delays, cross correlation failed and these attributes are set to None """ # If no values are already stored, perform generalized cross correlation to estimate time delays # or if user wants to re-estimate the time delays, perform generalized cross correlation to estimate time delays if self.tdoas is None or self.cc_maxs is None or use_stored_tdoas is False: self._estimate_delays() # Stores the results in the the attributes self.cc_maxs and self.tdoas if self.tdoas is not None: # cross correlation succeeded: location_estimate = self._localize_after_cross_correlation( localization_algorithm=localization_algorithm ) else: # cross correlation failed location_estimate = None self.location_estimate = None self.receivers_used_for_localization = None self.distance_residuals = None self.residual_rms = None # Sets the attributes self.location_estimate, self.receivers_used_for_localization, self.distance_residuals, self.residual_rms if return_self: return self # TODO: why return self? maybe just don't use the return arg instead? else: return location_estimate def to_dict(e): """SpatialEvent to json-able dictionary""" d = e.__dict__.copy() for key in d.keys(): if isinstance(d[key], np.ndarray): d[key] = d[key].tolist() if isinstance(d[key], pd.Timestamp): d[key] = str(d[key]) return d array_keys = ( "receiver_locations", "tdoas", "cc_maxs", "location_estimate", "distance_residuals", "receivers_used_for_localization", ) def from_dict(d): """Recover SpatialEvent from json""" s = SpatialEvent( receiver_files=d["receiver_files"], receiver_locations=d["receiver_locations"], max_delay=d["max_delay"], duration=d["duration"], ) for key in d.keys(): val = d[key] if key == "start_timestamp": val = pd.Timestamp(val) if key in array_keys: val = np.array(val) s.__setattr__(key, val) return s def events_to_df(list_of_events): """list of SpatialEvent objects to pd DataFrame""" return pd.DataFrame([e.__dict__ for e in list_of_events]) def df_to_events(df): """pd DataFrame to list of SpatialEvent objects works best if df was created using `events_to_df` """ return [from_dict(df.loc[i].to_dict()) for i in df.index] class SynchronizedRecorderArray(localization.SynchronizedRecorderArray): def __init__( self, file_coords, speed_of_sound=SPEED_OF_SOUND, ): """ Args: file_coords : pandas.DataFrame DataFrame with index filepath, and columns for x, y, (z) locations of reciever that recorded the audio file, in meters. Third coordinate is optional. Localization algorithms are in 2d if columns are (x,y) and 3d if columns are (x,y,z). When running .localize_detections() or .create_candidate_events(), Each audio file in `detections` must have a corresponding row in `file_coords` specifiying the location of the reciever that recorded the file. speed_of_sound : float, optional. Speed of sound in meters per second. Default is 343. """ self.file_coords = file_coords self.speed_of_sound = speed_of_sound def create_candidate_events( self, detections, min_n_receivers, max_receiver_dist, cc_threshold, bandpass_ranges, cc_filter, max_delay=None, ): """ Takes the detections dictionary and groups detections that are within `max_receiver_dist` of each other. args: detections: a dictionary of detections, with multi-index (file,start_time,end_time), and one column per class with 0/1 values for non-detection/detection The times in the index imply the same real world time across all files: eg 0 seconds assumes that the audio files all started at the same time, not on different dates/times min_n_receivers: if fewer nearby receivers have a simultaneous detection, do not create candidate event max_receiver_dist: the maximum distance between recorders to consider a detection as a single event bandpass_ranges: dictionary of form {"class name": [low_f, high_f]} for audio bandpass filtering during max_delay: the maximum delay (in seconds) to consider between receivers for a single event if None, defaults to max_receiver_dist / SPEED_OF_SOUND returns: a list of SpatialEvent objects to attempt to localize """ if max_delay is None: max_delay = max_receiver_dist / self.speed_of_sound # generate SpatialEvents for each detection, if enough nearby # receivers also had a detection at the same time # each SpatialEvent object contains the time and class name of a # detected event, a set of receivers' audio files, and receiver locations # and represents a single sound event that we will try to localize # # events will be redundant because each reciever with detection potentially # results in its own event containing nearby detections candidate_events = [] # list of SpatialEvents to try to localize detections = detections.copy() # don't change original # initialize instance of helper class used to calculate timestamp from file metadata # slow? get_start_ts = GetStartTimestamp() detections["start_timestamp"] = [ get_start_ts(index_tuple) for index_tuple in detections.index ] # add start_timestampe to multi-index detections = detections.reset_index(drop=False).set_index( ["file", "start_time", "end_time", "start_timestamp"] ) # iterate through all classes in detections (0/1) dataframe # with index (file,start_time,end_time), column for each class for cls_i in detections.columns: if bandpass_ranges is not None: bandpass_range = bandpass_ranges[cls_i] else: bandpass_range = None # select one column: contains 0/1 for each file and clip time period # (index: (file,start_time,end_time), values: 0 or 1) for a single class det_cls = detections[[cls_i]] # filter detection dataframe to select detections of this class det_cls = det_cls[det_cls[cls_i] > 0] # iterate through each clip start time in the df of detections # 2. groupby the start_timestamp rather than start time in seconds, perhaps (level=3) for timestamp_i, dets_at_time_i in det_cls.groupby(level="start_timestamp"): if len(dets_at_time_i) < min_n_receivers: continue # list all files with detections of this class at the same time files_w_dets = dets_at_time_i.reset_index()["file"].unique() # pre-generate a dictionary listing all close files for each audio file # dictionary will have a key for each audio file, and value listing all other receivers # within max_receiver_dist of that receiver # # eg {ARU_0.mp3: [ARU_1.mp3, ARU_2.mp3...], ARU_1... } # subset file coords dictionary to the files we are currently investigating file_coords_i = self.file_coords.loc[files_w_dets] nearby_files_dict = self.make_nearby_files_dict( file_coords_i, max_receiver_dist ) # for each file with detection of this class at this time, # check how many nearby recorders have a detection # at the same time. If there are enough, make a SpatialEvent # containing the spatial cluster of detections. The event # will be added to the list of candidate_events to localize for ref_file in files_w_dets: # check how many other detections are close enough to be detections of # the same sound event # instead, compute nearby_files_dict only on files grouped by time # since "recievers" is actually a list of all files! # first, use pre-created dictionary of nearby receivers for each audio file close_det_files = nearby_files_dict[ref_file] # if enough receivers, create a SpatialEvent using this set of receivers # +1 to count the reference receiver if len(close_det_files) + 1 >= min_n_receivers: receiver_files = [ref_file] + close_det_files receiver_locations = [ self.file_coords.loc[r] for r in receiver_files ] # find the clip end time #TODO hacky access to row of df clip = dets_at_time_i.loc[ref_file, :, :, timestamp_i] clip_start = clip.reset_index()["start_time"].values[0] clip_end = clip.reset_index()["end_time"].values[0] # specify a timestamp if we have one # 3. remove this code # if self.start_timestamp is None: # start_timestamp = None # else: # start_timestamp = self.start_timestamp + datetime.timedelta( # seconds=time_i # ) # create a SpatialEvent for this cluster of simultaneous detections candidate_events.append( SpatialEvent( receiver_files=receiver_files, receiver_locations=receiver_locations, bandpass_range=bandpass_range, cc_threshold=cc_threshold, max_delay=max_delay, start_time=clip_start, start_timestamp=timestamp_i, duration=clip_end - clip_start, class_name=cls_i, cc_filter=cc_filter, min_n_receivers=min_n_receivers, ) ) return candidate_events def make_nearby_files_dict(self, file_coords, r_max): """create dictinoary listing nearby files for each file pass a subset of self.file_coords pre-generate a dictionary listing all close files for each audio file dictionary will have a key for each audio file, and value listing all other receivers within r_max of that receiver eg {ARU_0.mp3: [ARU_1.mp3, ARU_2.mp3...], ARU_1... } The returned dictionary is used in create_candidate_events as a look-up table for recordings nearby a detection in any given file Args: r_max: maximum distance from each recorder in which to include other recorders in the list of 'nearby recorders', in meters Returns: dictionary with keys for each file and values = list of nearby recordings """ aru_files = file_coords.index.values nearby_files_dict = dict() for aru in aru_files: # make an entry in the dictionary for each file reference_receiver = file_coords.loc[aru] # location of receiver other_receivers = file_coords.drop([aru]) distances = np.array(other_receivers) - np.array(reference_receiver) euclid_distances = [np.linalg.norm(d) for d in distances] # boolean mask for whether recorder is close enough mask = [r <= r_max for r in euclid_distances] nearby_files_dict[aru] = list(other_receivers[mask].index) return nearby_files_dict