File size: 19,896 Bytes
d22c410 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 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 | """
use the PPS data generated by AudioMothGPSDeploy_1_0_8_Hardware_1_1
to generate audio files starting at
a known time and having the exact desired sampling rate
"""
import pandas as pd
import numpy as np
from scipy.interpolate import interp1d
from datetime import datetime, timedelta
import pytz
from opensoundscape import Audio
import gc
from aru_metadata_parser.parse import parse_audiomoth_metadata_from_path
def parse_RMC_time_to_seconds(timestamp: str) -> float:
"""
Takes in the GPS-audiomoth formatted timestamp and returns unix epoch time in seconds.
Args:
timestamp: string in the format used by our GPS-audiomoths
'%Y-%m-%dT%H:%M:%S.%f' e.g. "2022-05-14T10:30:00.725"
Returns: time from unix-epoch in seconds (to 10^-6s resolution)as a float
"""
stamp_format = "%Y-%m-%dT%H:%M:%S.%f"
return datetime.strptime(timestamp, stamp_format).timestamp()
def parse_RMC_time_to_datetime(timestamp: str) -> datetime:
"""
Takes in the GPS-audiomoth formatted timestamp and returns datetime.datetime
localized with UTC timezone. Assumes the input time string is given in UTC.
Args:
timestamp: string in the format used by our GPS-audiomoths
'%Y-%m-%dT%H:%M:%S.%f' e.g. "2022-05-14T10:30:00.725"
Returns: datetime object localized to UTC timezone
"""
stamp_format = "%Y-%m-%dT%H:%M:%S.%f"
tz = pytz.timezone("UTC")
return tz.localize(datetime.strptime(timestamp, stamp_format))
def process_pps_file(pps_file, expected_sr=48000, sr_tol=50) -> pd.DataFrame:
"""
Using the PPS File, creates a table aligning GPS_TIME_SEC values with the corresponding PPS and SAMPLES_WRITTEN Values
This is the information we need to interpolate audio files to achieve "synchronized" files with the exact desired sampling rate
This function performs several checks to try to determine whether a value in the LAST_RMC_GPS_TIME column corresponds to the
PPS from the previous line. If so, the previous line's SAMPLES_WRITTEN value gives the number of samples written at the time of
the PPS, whose accurate time stamp is given by the LAST_RMC_GPS_TIME of the subsequent row.
If any of the validation checks fail, we discard the RMC data from that row. As long as there is eventually a good pairing of
RMC data (LAST_RMC_GPS_TIME) with a PPS, we will know the number of samples written and the exact time interval. This allows us
to interpolate to achieve the nominal sampling rate.
Args:
- pps_file: path to the pps file (comma separated file produced by the firmware `AudioMothGPSDeploy_1_0_8_Hardware_1_1`)
Returns:
- a DataFrame with rows in which GPS_TIME_SEC is matched with the corresponding PPS, SAMPLES_WRITTEN, and COUNTER values
columns: ["PPS","SAMPLES_WRITTEN", "GPS_TIME_SEC", "GPS_TIME_STR", "CPU_CLOCK_COUNTER"]
"""
pps_table = pd.read_csv(pps_file, index_col=0)
samples_written = []
gps_times_str = []
gps_times_sec = []
pps_numbers_out = []
counter_positions = []
pps_pings_with_no_RMC = []
# Buffer overflow check: Fail if any buffer overflows occurred
# a buffer overflow can be detected by a permanent difference of a multiple of 8 between
# BUFFERS_FILLED and BUFFERS_WRITTEN. A difference of 8 corresponds to 2^17 samples that were
# recorded from the sensor but never written to the WAV file. Thus TOTAL_SAMPLES is incorrect,
# it overstates the number of samples actually written to the WAV file (it accurately reports the
# number of samples recorded from the sensor into the buffer).
# It may be possible to correct for buffer overflows by inserting 0s at the appropriate positions
# in the WAV file, but here we fail rather than trying to correct buffer overflows.
final_row = pps_table.iloc[-1]
assert (
final_row["BUFFERS_FILLED"] - final_row["BUFFERS_WRITTEN"] < 8
), "Buffer overflow detected, WAV file has missing content"
pps_numbers = pps_table.index
# PPS Duplicate Check: check for duplicates in PPS number
if sum(pps_numbers.duplicated()) > 0:
raise ValueError(
f"PPS numbers are duplicated in this file. Something may be wrong: {pps_file}"
)
# PPS Sequence Check: check that PPS numbers are sequential from first to last
assert np.array_equal(
pps_numbers.values, list(range(pps_numbers[0], pps_numbers[-1] + 1))
), "PPS Numbers were not sequential integers"
for i, pps_number in enumerate(pps_numbers):
if i == 0: #: # if first pps ping, ignore
# TOTAL_SAMPLES starts at zero check
assert (
pps_table.loc[pps_numbers[i], "TOTAL_SAMPLES"] == 0
), "TOTAL_SAMPLES was not zero in first row of PPS file!"
continue
if pd.isnull(pps_table.loc[pps_numbers[i], "LAST_RMC_AUDIOMOTH_TIME"]):
# no RMC data in this row
continue
# pps_table contains a row for each pps ping recieved, written immediately when the pps is recieved
# the SAMPLES_WRITTEN column contains the current number of samples recorded to the WAV file
#
# The RMC data packet with GPS information relevant to a PPS arrives after the PPS
# A row contains the _most recent_ RMC data. So if we are making one row per second and getting data
# as expected, the RMC info will be in the row _after_ the PPS ping row to which it corresponds.
# The RMC data includes the audiomoth time at which the RMC was recieved, and should be after the
# pervious row's PPS Audiomoth time but before the current row's PPS Audiomoth time.
#
# let's call this row row1 and the previous row row0
# check that LAST_RMC_AUDIOMOTH_TIME falls between AUDIOMOTH_TIME of row0 and row1
# which are the times when the PPS ping was recieved, according to the AudioMoth clock.
# If true, the RMC data in row1 corresponds to PPS ping in row0
# So we can pair SAMPLES_WRITTEN from row0 with LAST_RMC_GPS_TIME from row1 to know
# the number samples taken at an accurate timestamp
row1 = pps_table.loc[pps_number]
row0 = pps_table.loc[pps_numbers[i - 1]]
# GPS Status Check
# The GPS status should be "A" if it is synced properly
# if not, discard this RMC info and go to the next row
if row1["STATUS"] != "A":
continue
# GPS_TIME integer check: GPS_TIME should contain even seconds
# if not, eg 3.301, something is wrong. Discard this RMC info and go to the next row
rmc_gps_time = parse_RMC_time_to_seconds(row1["LAST_RMC_GPS_TIME"])
if not np.isclose(rmc_gps_time % 1, 0, 1e-3):
# print(f'rmc time was non-integer: pps: {pps_number}, gps time {rmc_gps_time}')
continue # non-integer RMC GPS TIME!
# parse the timestamp of the LAST_RMC_AUDIOMOTH_TIME from this row, row1
row1_last_rmc_amtime = parse_RMC_time_to_seconds(
row1["LAST_RMC_AUDIOMOTH_TIME"]
)
# parse the timestamp of AUDIOMOTH_TIME (time PPS was recieved, internal clock) for previous row, row0
row0_pps_amtime = parse_RMC_time_to_seconds(row0["AUDIOMOTH_TIME"])
# parse the timestamp of AUDIOMOTH_TIME (time PPS was recieved, internal clock) for this row, row1
# row1_pps_amtime = parse_RMC_time_to_seconds(row1["AUDIOMOTH_TIME"])
# RMC within one second of previous PPS check:
# check that the RMC packet for this row was recieved within one second of the previous row's PPS
# if so, we match the RMC packet's GPS timestamp with the previous PPS ping's info about samples recorded
# we are using the internal AudioMoth clock to check the relative arrival time of messages, no GPS time is used yet
# Note that sometimes the RMC packet for PPS 4 arrives (eg 0.3 seconds) after the arrival of PPS 5, so this condition can
# be true even if the pairing is not correct. "observed smaple rate check" below attempts to catch these scenarios.
if (
row1_last_rmc_amtime > row0_pps_amtime
and row1_last_rmc_amtime < row0_pps_amtime + 1.0
):
# observed sample rate check
# check observed sample rate since the last RMC + PPS pairing, if off by more than tolerance,
# we assume this RMC is not aligned with the correct PPS
# for example, the RMC message for PPS 4 may have arrived after PPS 5, so we would be attemping to pair
# row1's RMC GPS time with the incorrect PPS information (SAMPLES_WRITTEN)
# can only check if we have one pairing already, so skip the first row
if len(samples_written) > 0:
observed_sr = (row0["TOTAL_SAMPLES"] - samples_written[-1]) / (
rmc_gps_time - gps_times_sec[-1]
)
if abs(observed_sr - expected_sr) > sr_tol:
print(
f"Observed sr {observed_sr} did not match expected {expected_sr} at PPS {pps_number}. Discarding RMC."
)
continue
# all of our checks have passed.
# add the information to our lists of paired accurate time + samples take
samples_written.append(row0["TOTAL_SAMPLES"])
gps_times_str.append(row1["LAST_RMC_GPS_TIME"])
pps_numbers_out.append(pps_numbers[i - 1])
# todo: retain a timestamp rather than string
gps_times_sec.append(rmc_gps_time)
# also save the COUNTER (CPU clock cycle position, 0-999) from row0 (recorded when PPS is recieved)
counter_positions.append(row0["COUNTER"])
else:
# this row's RMC data does not correspond to the previous row's PPS ping
# so we don't add it to our table of accurate time and number of samples
pps_pings_with_no_RMC.append(pps_number)
print(
f"There were {len(pps_pings_with_no_RMC)} PPS pings without corresponding RMC data in {pps_file}"
)
return pd.DataFrame(
zip(
pps_numbers_out,
samples_written,
gps_times_sec,
gps_times_str,
counter_positions,
),
columns=[
"PPS",
"SAMPLES_WRITTEN",
"GPS_TIME_SEC",
"GPS_TIME_STR",
"CPU_CLOCK_COUNTER",
],
)
def correct_sample_rate(
audio,
processed_pps_df,
desired_sr,
expected_sr=48000,
interpolation_method="nearest",
):
"""
Args:
- audio: Audio objecte
- processed_pps_df: a dataframe of samples written and the corresponding RMC time.
2 columns: SAMPLES_WRITTEN and RMC_TIME
- desired_sr: the desired sample_rate for the files.
- expected_sr: the expected sample rate of the input;
gives warning if input sr differs by more than 100 Hz on any interval
- interpolation_method: Can be e.g. "linear", "quadratic", "nearest". See scipy.interpolate.interp1d docs.
nearest is slightly faster than linear
Returns:
- Audio object with desired sample rate and updated .metadata['recording_start_time']
Also writes out a .wav file with corrected sample_rate
Each error in sampling rate is corrected between every RMC data
if pps pings are received every second and desired_sr = 48000
the first second is corrected to be exactly 48000, the second second is corrected to be
exactly 48000 samples. These are concatenated to form the entire audio file.
"""
dtype = audio.samples.dtype
new_samples = [] # make container for the resampled samples
for i in processed_pps_df.index[1:]:
# don't do first row - there are 0 samples written so far!
# find start and stop sample indices in the WAV file taken between RMC_TIME of the previous and current row
# the samples we want are [previous row SAMPLES WRITTEN, this row SAMPLES_WRITTEN)
# ie [include, exclude); python's `list[a:b]` syntax provides the desired slice [a,b)
this_row = processed_pps_df.loc[i]
previous_row = processed_pps_df.loc[i - 1]
end_sample_exclude = this_row["SAMPLES_WRITTEN"]
start_sample = previous_row["SAMPLES_WRITTEN"]
time_elapsed = this_row["GPS_TIME_SEC"] - previous_row["GPS_TIME_SEC"]
observed_sr = (end_sample_exclude - start_sample) / time_elapsed
# check that the observed_sr is close to the desired_sr
if abs(observed_sr - expected_sr) > 100:
print(
f"Warning: observed_sr = {observed_sr} is more than 100 Hz away from desired_sr = {expected_sr}. \
This may indicate a problem like missing audio data, or an error in the timestamps in the pps file. \
The offending line number in preprocessed_pps_df: {i}; PPS number {this_row['PPS']}"
)
##interpolate samples to achieve desired_sr across the time interval
raw_samples = audio.samples[start_sample:end_sample_exclude]
# TODO try including 1 before and 1 after second period, so we can better interpolate?
x_values = (
np.arange(len(raw_samples)) / observed_sr
) # time in seconds of each sample, assuming samples were taken at a constant rate (even spacing)
interpolator = interp1d(
x_values, raw_samples, kind=interpolation_method, fill_value="extrapolate"
) # need to extrapolate for the points outside the original data (e.g. beginning and ends if upsampling)
desired_x = (
np.arange(int(time_elapsed * desired_sr)) / desired_sr
) # TODO do I need to check that this int rounding is OK. What if the rounding is adding some error??
resampled = interpolator(desired_x)
# resampled = resampled[0: int(desired_sr*time_elapsed)] #why would it have a different number of samples than this? why do we need to trim/subset?
assert len(resampled) == int(time_elapsed * desired_sr)
resampled = resampled.astype(dtype=dtype)
new_samples.append(resampled)
samples_out = np.concatenate(new_samples)
# create new audio object with same metadata as the original
new_audio = audio._spawn(samples=samples_out, sample_rate=desired_sr)
# update the 'recording_start_time' in audio.metadata
start_time = processed_pps_df.loc[0, "GPS_TIME_STR"]
if new_audio.metadata is None:
new_audio.metadata = {}
new_audio.metadata["recording_start_time"] = parse_RMC_time_to_datetime(start_time)
return new_audio
# timestamp rounding utilities
def time_mod(time, delta, epoch=None):
if epoch is None:
epoch = datetime(1970, 1, 1, tzinfo=time.tzinfo)
return (time - epoch) % delta
def time_round(time, delta, epoch=None):
mod = time_mod(time, delta, epoch)
if mod < delta / 2:
return time - mod
return time + (delta - mod)
def time_floor(time, delta, epoch=None):
mod = time_mod(time, delta, epoch)
return time - mod
def time_ceil(time, delta, epoch=None):
mod = time_mod(time, delta, epoch)
if mod:
return time + (delta - mod)
return time
def trim_audio_by_datetime(
audio, start_datetime, end_datetime=None, duration=None, out_of_bounds_error=True
):
"""trim Audio object using the embeded datetime in .metadata['recording_start_time']
start_datetime and end_datetime should be _localized_ datetime objects, eg
pytz.timezone('UTC').localize(datetime(2020,4,4,10,25,15))
pass either end_datetime or duration
out_of_bounds_error: if True, raise error for requesting before or after this recording's start/end
If False, just use the part of the recording that overlaps with desired period
"""
if duration is not None:
assert end_datetime is None, "do not specify both duration and end_datetime"
end_datetime = start_datetime + datetime.timedelta(seconds=duration)
start_seconds = (
start_datetime - audio.metadata["recording_start_time"]
).total_seconds()
if start_seconds < 0:
if out_of_bounds_error:
raise ValueError(
f"start_datetime was before the beginning of the Audio file ({audio.metadata['recording_start_time']})"
)
# audio.trim will just get the audio starting at time 0 (equivalent to start_seconds = 0)
end_seconds = (
end_datetime - audio.metadata["recording_start_time"]
).total_seconds()
if end_seconds > audio.duration:
if out_of_bounds_error:
raise ValueError(
f"The targeted end time was after the end of the Audio file"
)
# else, audio.trim will just get the audio until the end of the file
return audio.trim(start_seconds, end_seconds)
def trim_to_start_on_minute(audio):
ts = audio.metadata["recording_start_time"]
if ts.second == 0:
return audio
else:
start_at_next = timedelta(minutes=1)
# new_ts = time_ceil(ts,start_at_next) #unused, but leaving for reference
mod = time_mod(ts, start_at_next)
offset = start_at_next.total_seconds() - mod.total_seconds()
# audio.trim also updates the recording start time meatadata field
return audio.trim(offset, audio.duration)
def sync_entire_sd(sd_folder, output_folder, output_sr, skip_if_completed=True):
audio_files = list(sd_folder.glob("*.WAV"))
success_record = []
# make the directory for each sd card in the output folder
out_sd = output_folder / sd_folder.stem
out_sd.mkdir(exist_ok=True, parents=True)
print(f"There are {len(audio_files)} files in {sd_folder}")
for file in audio_files:
# check if already completed
out_filename = out_sd / file.name
if out_filename.exists() and skip_if_completed:
# check if file has proper metadata (if not, re-do it)
try:
p = parse_audiomoth_metadata_from_path(out_filename)
assert "artist" in p
# success -> skip
success_record.append(True)
continue
except Exception as e:
# If there's an error with the existing file, we'll reprocess it
out_filename.unlink() # Remove the problematic file
try:
# Get the processed PPS DF
pps_file = file.parent / str(file.stem + ".PPS")
assert pps_file.exists()
processed_pps_df = process_pps_file(pps_file)
# Resample the audio
resampled_audio = correct_sample_rate(
Audio.from_file(file, dtype=np.float16),
processed_pps_df,
desired_sr=output_sr,
)
# if recording starts with seconds!=0 in timestamp, trim to start at next even minute
# this ensures the clips will align for 3s or 5s prediction windows
resampled_audio = trim_to_start_on_minute(resampled_audio)
# save
processed_pps_df.to_csv(out_sd / file.with_suffix(".csv").name)
resampled_audio.save(out_filename)
success_record.append(True)
# clean up memory after each file
del resampled_audio
gc.collect()
except Exception as exc:
print(f"Exception was raised while attempting to resample/sync {file}:")
print(exc)
success_record.append(False)
finally:
gc.collect() # free memory after each file
return pd.DataFrame(
zip(audio_files, success_record), columns=["audio_file", "success"]
)
|