File size: 16,065 Bytes
85407a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Render and validate a static V1 FOA RIR pilot with SoundSpaces 2.0."""

from __future__ import annotations

import argparse
import hashlib
import itertools
import json
import math
from pathlib import Path

import numpy as np
import quaternion  # noqa: F401 - import before Habitat to avoid allocator issues
from scipy.signal import butter, sosfilt

import habitat_sim
import habitat_sim.sim


DEFAULT_RENDERER = {
    "sampleRate": 32000,
    "frequencyBands": 8,
    "directSHOrder": 3,
    "indirectSHOrder": 1,
    "threadCount": 8,
    "updateDt": 0.02,
    "irTime": 2.5,
    "unitScale": 1.0,
    "globalVolume": 0.25,
    "indirectRayCount": 15000,
    "indirectRayDepth": 200,
    "sourceRayCount": 1500,
    "sourceRayDepth": 10,
    "maxDiffractionOrder": 10,
    "direct": True,
    "indirect": True,
    "diffraction": True,
    "transmission": True,
    "meshSimplification": False,
    "temporalCoherence": False,
    "enableMaterials": True,
    "dumpWaveFiles": False,
    "writeIrToFile": False,
}

CALIBRATION_SOURCES = {
    # All six sources are exactly 1 m from the receiver so the linear fit is
    # not biased by distance attenuation.
    "world_pos_x": ([1.0, 1.35, 0.0], [1.0, 0.0, 0.0]),
    "world_neg_x": ([-1.0, 1.35, 0.0], [-1.0, 0.0, 0.0]),
    "world_pos_y": ([0.0, 2.35, 0.0], [0.0, 1.0, 0.0]),
    "world_neg_y": ([0.0, 0.35, 0.0], [0.0, -1.0, 0.0]),
    "world_pos_z": ([0.0, 1.35, 1.0], [0.0, 0.0, 1.0]),
    "world_neg_z": ([0.0, 1.35, -1.0], [0.0, 0.0, -1.0]),
}


def canonical_json_hash(value) -> str:
    blob = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(blob).hexdigest()


def file_hash(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def set_if_present(obj, key, value) -> None:
    if not hasattr(obj, key):
        raise AttributeError(f"SoundSpaces acoustics config has no required field {key!r}")
    setattr(obj, key, value)


def create_simulator(stage_config: Path, dataset_config: Path, material_json: Path, renderer: dict):
    backend = habitat_sim.SimulatorConfiguration()
    backend.scene_id = str(stage_config)
    backend.scene_dataset_config_file = str(dataset_config)
    backend.load_semantic_mesh = True
    backend.enable_physics = False
    if hasattr(backend, "random_seed"):
        backend.random_seed = 20260826
    agent = habitat_sim.agent.AgentConfiguration()
    sim = habitat_sim.Simulator(habitat_sim.Configuration(backend, [agent]))
    if not sim.semantic_scene:
        sim.close()
        raise RuntimeError("Semantic scene was not loaded; refusing to fall back to default acoustic material")

    spec = habitat_sim.AudioSensorSpec()
    spec.uuid = "audio_sensor"
    spec.channelLayout.channelType = habitat_sim.sensor.RLRAudioPropagationChannelLayoutType.Ambisonics
    spec.channelLayout.channelCount = 4
    spec.position = [0.0, 0.0, 0.0]
    for key, value in renderer.items():
        set_if_present(spec.acousticsConfig, key, value)
    sim.add_sensor(spec)
    audio_sensor = sim.get_agent(0)._sensors["audio_sensor"]
    audio_sensor.setAudioMaterialsJSON(str(material_json))
    return sim


def set_listener_identity(sim, position) -> None:
    agent = sim.get_agent(0)
    state = agent.get_state()
    state.position = np.asarray(position, dtype=np.float32)
    state.rotation = np.quaternion(1.0, 0.0, 0.0, 0.0)
    state.sensor_states = {}
    agent.set_state(state, True)


def render(sim, source_position) -> np.ndarray:
    sensor = sim.get_agent(0)._sensors["audio_sensor"]
    sensor.setAudioSourceTransform(np.asarray(source_position, dtype=np.float32))
    observation = np.asarray(sim.get_sensor_observations()["audio_sensor"], dtype=np.float32)
    if observation.ndim != 2:
        raise RuntimeError(f"Unexpected RIR shape: {observation.shape}")
    rir = observation if observation.shape[0] == 4 else observation.T
    if rir.shape[0] != 4 or not np.isfinite(rir).all() or not np.any(rir):
        raise RuntimeError(f"Invalid FOA RIR: shape={rir.shape}")
    return np.ascontiguousarray(rir, dtype=np.float32)


def direct_sample_vector(rir: np.ndarray) -> tuple[int, np.ndarray]:
    energy = np.sum(np.square(rir.astype(np.float64)), axis=0)
    peak = int(np.argmax(energy))
    lo, hi = max(0, peak - 1), min(rir.shape[1], peak + 2)
    local = rir[:, lo:hi]
    index = int(np.argmax(np.sum(np.square(local.astype(np.float64)), axis=0)))
    return lo + index, local[:, index].astype(np.float64)


def infer_native_foa(calibration_rirs: dict[str, np.ndarray]) -> dict:
    directions, amplitudes, peaks = [], [], {}
    for name, (_, direction) in CALIBRATION_SOURCES.items():
        peak, vector = direct_sample_vector(calibration_rirs[name])
        directions.append(direction)
        amplitudes.append(vector)
        peaks[name] = peak
    design = np.column_stack([np.ones(len(directions)), np.asarray(directions, dtype=np.float64)])
    amplitude_matrix = np.asarray(amplitudes, dtype=np.float64)
    coefficients = np.linalg.lstsq(design, amplitude_matrix, rcond=None)[0].T
    scores = []
    for channel, row in enumerate(coefficients):
        intercept = abs(row[0])
        directional = float(np.linalg.norm(row[1:]))
        scores.append(intercept / (directional + 1e-12))
    w_channel = int(np.argmax(scores))
    direction_channels = [channel for channel in range(4) if channel != w_channel]
    best = None
    for permutation in itertools.permutations(range(3)):
        score = sum(abs(coefficients[channel, 1 + axis]) for channel, axis in zip(direction_channels, permutation))
        if best is None or score > best[0]:
            best = (score, permutation)
    assert best is not None
    native_by_world_axis = {}
    axis_names = ("world_x", "world_y", "world_z")
    for channel, axis in zip(direction_channels, best[1]):
        coefficient = coefficients[channel, 1 + axis]
        native_by_world_axis[axis_names[axis]] = {
            "channel": channel,
            "polarity": 1 if coefficient >= 0 else -1,
            "fit_coefficient": float(coefficient),
        }
    return {
        "method": "six_equal_distance_axis_sources_linear_fit",
        "native_normalization": "N3D",
        "w_channel": w_channel,
        "w_polarity": 1 if coefficients[w_channel, 0] >= 0 else -1,
        "world_axis_mapping": native_by_world_axis,
        "fit_coefficients_intercept_xyz": coefficients.tolist(),
        "direct_peak_samples": peaks,
    }


def native_to_ambix_robot(rir: np.ndarray, mapping: dict, yaw_deg: float) -> np.ndarray:
    w = mapping["w_polarity"] * rir[mapping["w_channel"]]
    world = {}
    for axis in ("world_x", "world_y", "world_z"):
        item = mapping["world_axis_mapping"][axis]
        world[axis] = item["polarity"] * rir[item["channel"]] / math.sqrt(3.0)
    yaw = math.radians(yaw_deg)
    cos_yaw, sin_yaw = math.cos(yaw), math.sin(yaw)
    right = cos_yaw * world["world_x"] - sin_yaw * world["world_z"]
    up = world["world_y"]
    front = -sin_yaw * world["world_x"] - cos_yaw * world["world_z"]
    return np.stack([w, -right, up, front]).astype(np.float32)


def decay_fit(signal: np.ndarray, sample_rate: int, upper_db: float, lower_db: float):
    energy = np.square(signal.astype(np.float64))
    peak = int(np.argmax(energy))
    decay = np.cumsum(energy[peak:][::-1])[::-1]
    if not len(decay) or decay[0] <= 0:
        return None
    db = 10.0 * np.log10(np.maximum(decay / decay[0], 1e-14))
    mask = (db <= upper_db) & (db >= lower_db)
    if np.count_nonzero(mask) < 20:
        return None
    times = np.arange(len(db), dtype=np.float64) / sample_rate
    slope, intercept = np.polyfit(times[mask], db[mask], 1)
    if slope >= 0:
        return None
    return {"rt60_s": float(-60.0 / slope), "slope_db_per_s": float(slope),
            "fit_intercept_db": float(intercept), "fit_points": int(np.count_nonzero(mask))}


def acoustic_metrics(rir_ambix: np.ndarray, sample_rate: int) -> dict:
    w = rir_ambix[0].astype(np.float64)
    peak = int(np.argmax(np.square(w)))
    direct_end = min(len(w), peak + max(1, round(0.003 * sample_rate)))
    c50_end = min(len(w), peak + round(0.050 * sample_rate))
    eps = 1e-18
    direct = float(np.sum(np.square(w[peak:direct_end]))) + eps
    reverberant = float(np.sum(np.square(w[direct_end:]))) + eps
    early = float(np.sum(np.square(w[peak:c50_end]))) + eps
    late = float(np.sum(np.square(w[c50_end:]))) + eps
    broadband = {
        "first_peak_s": float(peak / sample_rate),
        "drr_db": float(10 * math.log10(direct / reverberant)),
        "c50_db": float(10 * math.log10(early / late)),
        "edt_s": None,
        "t20_rt60_s": None,
        "t30_rt60_s": None,
    }
    edt = decay_fit(w, sample_rate, 0.0, -10.0)
    t20 = decay_fit(w, sample_rate, -5.0, -25.0)
    t30 = decay_fit(w, sample_rate, -5.0, -35.0)
    broadband["edt_s"] = None if edt is None else edt["rt60_s"]
    broadband["t20_rt60_s"] = None if t20 is None else t20["rt60_s"]
    broadband["t30_rt60_s"] = None if t30 is None else t30["rt60_s"]
    bands = {}
    nyquist = sample_rate / 2.0
    for centre in (500, 1000, 2000):
        low, high = centre / math.sqrt(2.0), centre * math.sqrt(2.0)
        sos = butter(4, [low / nyquist, high / nyquist], btype="bandpass", output="sos")
        filtered = sosfilt(sos, w)
        fit = decay_fit(filtered, sample_rate, -5.0, -25.0)
        bands[str(centre)] = None if fit is None else fit["rt60_s"]
    valid_bands = [value for value in bands.values() if value is not None]
    return {"broadband": broadband, "t20_rt60_octave_s": bands,
            "acceptance_rt60_median_s": None if not valid_bands else float(np.median(valid_bands))}


def main() -> None:
    root = Path(__file__).resolve().parents[1]
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--scenarios", type=Path, default=root.parent / "simulation_scenarios" / "pilot_scenarios.json")
    parser.add_argument("--scenario-id", default="EASE-V1-01")
    parser.add_argument("--scene-dir", type=Path, default=root / "scene" / "static_v1" / "exhibition_hall_base")
    parser.add_argument("--materials", type=Path, default=root / "materials" / "static_v1_absorptive.json")
    parser.add_argument("--output-dir", type=Path, default=root / "assets" / "static_v1" / "rir" / "EASE-V1-01")
    parser.add_argument("--target-rt60-s", type=float, nargs=2,
                        metavar=("MIN", "MAX"), help="override the scenario-wide acceptance interval")
    parser.add_argument("--rays", type=int, default=15000)
    parser.add_argument("--threads", type=int, default=8)
    args = parser.parse_args()

    scenario_doc = json.loads(args.scenarios.read_text(encoding="utf-8"))
    scenario = next(item for item in scenario_doc["scenarios"] if item["id"] == args.scenario_id)
    renderer = dict(DEFAULT_RENDERER)
    renderer["sampleRate"] = int(scenario_doc["audio_contract"]["sample_rate_hz"])
    renderer["indirectRayCount"] = args.rays
    renderer["sourceRayCount"] = max(500, args.rays // 10)
    renderer["threadCount"] = args.threads
    layout_path = (args.scene_dir / "layout.json").resolve()
    if not layout_path.is_file():
        raise FileNotFoundError(layout_path)
    layout = json.loads(layout_path.read_text(encoding="utf-8"))
    stage_config = Path(layout["stage_config"]).resolve()
    dataset_config = Path(layout["scene_dataset_config"]).resolve()
    semantic_glb = Path(layout["semantic_asset"]).resolve()
    materials = args.materials.resolve()
    for required in (stage_config, dataset_config, semantic_glb, materials, args.scenarios):
        if not required.is_file():
            raise FileNotFoundError(required)
    output_dir = args.output_dir.resolve()
    output_dir.mkdir(parents=True, exist_ok=True)

    listener_position = scenario["scene_sampling"]["receiver_position_candidates"][0]
    yaw_values = scenario["scene_sampling"]["receiver_yaw_deg_values"]
    listener_yaw = float(min(yaw_values, key=lambda value: abs(float(value))))
    sim = create_simulator(stage_config, dataset_config, materials, renderer)
    raw_rirs = {}
    try:
        set_listener_identity(sim, listener_position)
        for name, (position, _) in CALIBRATION_SOURCES.items():
            print(f"render calibration {name} @ {position}", flush=True)
            raw_rirs[name] = render(sim, position)
        mapping = infer_native_foa(raw_rirs)
        print("inferred native FOA mapping: " + json.dumps(mapping, ensure_ascii=False), flush=True)
        records = []
        for source in scenario["sources"]:
            print(f"render {scenario['id']} source {source['id']} @ {source['position']}", flush=True)
            raw = render(sim, source["position"])
            canonical = native_to_ambix_robot(raw, mapping, listener_yaw)
            raw_path = output_dir / f"{source['id']}.native_n3d.npy"
            canonical_path = output_dir / f"{source['id']}.ambix_sn3d.npy"
            np.save(raw_path, raw, allow_pickle=False)
            np.save(canonical_path, canonical, allow_pickle=False)
            metrics = acoustic_metrics(canonical, renderer["sampleRate"])
            records.append({
                "source_id": source["id"], "source_class": source["source_class"],
                "source_position_xyz_m": source["position"],
                "nominal_azimuth_deg": source["nominal_azimuth_deg"],
                "native_rir": raw_path.name, "canonical_rir": canonical_path.name,
                "shape": list(canonical.shape), "metrics": metrics,
            })
    finally:
        sim.close()

    target_rt60 = args.target_rt60_s or scenario["acoustic_profile"]["target_rt60_s_range"]
    medians = [item["metrics"]["acceptance_rt60_median_s"] for item in records]
    acceptance = all(value is not None and target_rt60[0] <= value <= target_rt60[1] for value in medians)
    fingerprint_payload = {
        "scenario": scenario, "renderer": renderer,
        "stage_sha256": file_hash(stage_config), "semantic_glb_sha256": file_hash(semantic_glb),
        "materials_sha256": file_hash(materials), "listener_position": listener_position, "listener_yaw_deg": listener_yaw,
    }
    manifest = {
        "renderer": "SoundSpaces 2.0 / Habitat-Sim AudioSensor",
        "scenario_id": scenario["id"], "sample_rate_hz": renderer["sampleRate"],
        "receiver_position_xyz_m": listener_position,
        "receiver_yaw_deg": listener_yaw,
        "scene": {
            "geometry_id": layout["geometry_id"],
            "room_size_variant": layout.get("room_size_variant", "base"),
            "room_size_m": layout["room_size_m"],
            "layout_template": layout.get("layout_template", "open_center"),
            "center_occluder_type": layout.get("center_occluder_type", "none"),
            "layout_sha256": file_hash(layout_path),
        },
        "materials_file": str(materials),
        "materials_sha256": file_hash(materials),
        "output_format": "AmbiX ACN SN3D [W,Y,Z,X], robot-relative",
        "native_format": "SoundSpaces four-channel Ambisonics N3D; mapping inferred, not assumed",
        "materials_enabled": True, "semantic_mesh_required_and_loaded": True,
        "renderer_config": renderer, "native_foa_calibration": mapping,
        "target_rt60_s_range": target_rt60, "rt60_acceptance_passed": acceptance,
        "acoustic_config_sha256": canonical_json_hash(fingerprint_payload), "rirs": records,
    }
    manifest_path = output_dir / "rir_manifest.json"
    manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(f"wrote {manifest_path}", flush=True)
    print(f"RT60 acceptance: {acceptance}; medians={medians}; target={target_rt60}", flush=True)
    if not acceptance:
        raise SystemExit(2)


if __name__ == "__main__":
    main()