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44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""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