File size: 2,838 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Task adapter for pyroomacoustics 0.8.4 MUSIC / NormMUSIC.

The numerical methods and STFT are unmodified vendored library code. Analysis
settings follow examples/doa_anechoic_room.py and the library's 3D defaults.
"""

import argparse
import json
import math
import os
from pathlib import Path
import sys

import numpy as np
from scipy.signal import resample_poly
import soundfile as sf

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE / "vendor"))
from pyroomacoustics.doa import MUSIC, NormMUSIC
from pyroomacoustics.transform.stft import analysis

CORE = Path(os.environ["CORE_DIR"])
sys.path.insert(0, str(CORE / "interface"))
from api import read_recordings, write_directions

FS = 16000
NFFT = 256
HOP = NFFT // 2


def recording(path, row, estimator):
    waveform, source_fs = sf.read(path, always_2d=True, dtype="float64")
    if waveform.shape[1] != estimator.M:
        raise ValueError("WAV channels do not match the supplied array geometry")
    if source_fs != FS:
        divisor = math.gcd(source_fs, FS)
        waveform = resample_poly(
            waveform, FS // divisor, source_fs // divisor, axis=0
        )

    for frame in range(row["frame_count"]):
        if row["kind"] == "static":
            segment = waveform
        else:
            start = round(frame * 0.25 * FS)
            stop = round((frame * 0.25 + 0.5) * FS)
            segment = waveform[start:stop]
        if len(segment) == 0:
            raise ValueError("The requested window contains no waveform samples")

        # Identical STFT call and axis order to the upstream anechoic example.
        snapshots = analysis(segment, NFFT, HOP, win=np.hanning(NFFT))
        snapshots = np.swapaxes(snapshots, 2, 0)
        estimator.locate_sources(snapshots)
        azimuth = float(np.rad2deg(estimator.azimuth_recon[0]))
        elevation = 90.0 - float(np.rad2deg(estimator.colatitude_recon[0]))
        yield row["recording"], frame, azimuth, elevation


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("data", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--algorithm", choices=("NormMUSIC", "MUSIC"), default="NormMUSIC")
    args = parser.parse_args()

    geometry = json.loads((CORE / "interface" / "array.json").read_text())
    positions = np.asarray(geometry["microphone_positions_m"], dtype=float).T
    algorithm = {"NormMUSIC": NormMUSIC, "MUSIC": MUSIC}[args.algorithm]
    estimator = algorithm(
        positions,
        FS,
        NFFT,
        c=float(geometry["speed_of_sound_m_s"]),
        dim=3,
    )
    rows = []
    for row in read_recordings(args.data):
        rows.extend(recording(args.data / row["waveform"], row, estimator))
    write_directions(args.output, rows)


if __name__ == "__main__":
    main()