File size: 7,182 Bytes
6a16e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Expose exact H01 render stems and independently inspect FOA direction."""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import soundfile as sf
from scipy.signal import butter,sosfilt
from .common import SR,active,angular,geometry,grid,position,read,sha,uid,write
from .render import make_dry,nodes,two_time_convolution


def audio_directions(wave,times):
    # Raw acoustic intensity in ACN/SN3D; no true trajectory is used here.
    filtered=sosfilt(butter(2,100,fs=SR,btype='highpass',output='sos'),wave,axis=0)
    out=[]
    for t in times:
        lo=max(0,round((t-.04)*SR));hi=min(len(wave),round((t+.04)*SR))
        chunk=filtered[lo:hi];power=float(np.mean(chunk[:,0]**2))
        vector=np.mean(chunk[:,0,None]*chunk[:,[3,1,2]],axis=0)
        coherence=float(np.linalg.norm(vector)/max(power,1e-30))
        if power<=1e-12 or coherence<.4:continue
        x,y,z=vector
        out.append(dict(time_s=t,doa_deg=[float(np.degrees(np.arctan2(y,x))),
            float(np.degrees(np.arctan2(z,np.hypot(x,y))))],coherence=coherence,power=power))
    return out


def inspect(wave,scene,human,receiver):
    times=[s/SR for s in grid(scene) if active(human,s)]
    frames=audio_directions(wave,times)
    for f in frames:
        f['geometric_doa_deg']=geometry(human,receiver,f['time_s'])['doa_deg']
        f['angle_error_deg']=angular(f['doa_deg'],f['geometric_doa_deg'])
    changes=[angular(x['doa_deg'],y['doa_deg']) for x,y in zip(frames,frames[1:])
             if abs(y['time_s']-x['time_s']-.1)<1e-8]
    errors=[f['angle_error_deg'] for f in frames]
    return dict(branch=scene['branch'],receiver_id=receiver['entity_id'],source_id='H01',
        method='80 ms raw FOA acoustic intensity, highpass 100 Hz, coherence >= 0.4; no direction smoothing',
        reference='audio reception clock; geometric comparison uses same scene time without delay compensation',
        estimated_frames=len(frames),active_frames=len(times),coverage=len(frames)/len(times),
        median_angle_error_deg=float(np.median(errors)),p95_angle_error_deg=float(np.percentile(errors,95)),
        maximum_adjacent_0_1s_angle_change_deg=max(changes,default=0),frames=frames)


def inspect_direct_component(root,work,recipe,scene,human,receiver):
    """Audit an existing render's first arrival using its exact frozen RIRs.

    This is a component audit, not blind DOA estimation of the full recording.
    Geometry identifies existing kernels; it does not synthesize direction.
    """
    used=[]
    def kernel(te,tr):
        a=position(human,te);b=position(receiver,tr)
        key=uid(recipe['room_assets_sha256'],*[round(float(x),7) for x in np.r_[a,b,receiver['yaw_deg']]])
        path=work/'rirs'/(key+'.npy');meta=read(work/'rirs'/(key+'.json'))
        if not meta['los'] or sha(path)!=meta['sha256']:
            raise ValueError('First-arrival audit requires verified line-of-sight kernels')
        wave=np.load(path,allow_pickle=False)
        energy=np.sum(wave.astype(float)**2,axis=1)
        onset=int(np.flatnonzero(energy>energy.max()*1e-5)[0])
        wave[onset+16:]=0  # First 1 ms, preceding this view's floor reflection.
        used.append(key)
        return wave
    dry,_=make_dry(root,scene)
    wave=two_time_convolution(dry[human['entity_id']],nodes(human,recipe['source_node_step_s']),
        nodes(receiver,recipe['receiver_node_step_s']),kernel)
    wave*=read(work/'render.complete.json')['common_final_gain']
    result=inspect(wave,scene,human,receiver)
    passed=result['coverage']>=.8 and result['p95_angle_error_deg']<3 and result['maximum_adjacent_0_1s_angle_change_deg']<10
    result.update(passed=passed,component='first 1 ms from first arrival of the exact cached RIRs',
        cached_rir_ids=used,no_new_native_render=True,
        purpose='generation audit of the first-arrival component, not complete-waveform DOA performance',
        acceptance=dict(minimum_coverage=.8,maximum_p95_angle_error_deg=3,maximum_adjacent_0_1s_angle_change_deg=10))
    if not passed:raise ValueError('First-arrival continuity audit failed: '+str(result))
    return result


def prepare(root,work):
    recipe=read(root/'data/recipe.json');rendering=read(root/'data/rendering.json')
    stems=read(work/'render.complete.json')['stem_records'];checks=[]
    for record in rendering['recordings']:
        scene=next(s for s in recipe['scenes'] if s['branch']==record['branch'])
        receiver=next(r for r in scene['robots'] if r['entity_id']==record['receiver_id'])
        human=next(h for h in scene['humans'] if h['entity_id']=='H01')
        stem=next(s for s in stems if s['branch']==record['branch'] and s['receiver_id']==record['receiver_id'] and s['source_id']=='H01')
        if sha(stem['path'])!=stem['sha256']:raise ValueError('H01 stem checksum mismatch')
        wave=np.load(stem['path'],allow_pickle=False)
        path=root/'audio'/record['branch']/(record['receiver_id']+'_H01_only_foa.wav')
        sf.write(path,wave,SR,subtype='FLOAT')
        record['diagnostics']={'H01':dict(branch=record['branch'],receiver_id=record['receiver_id'],
            diagnostic_source_id='H01',path=str(path.relative_to(root)),sha256=sha(path),
            sample_rate_hz=SR,samples=len(wave),channels=['W','Y','Z','X'],
            recording_id=uid(scene['scene_id'],record['receiver_id'],'H01-only'),
            purpose='public generation audit only; never the model task input')}
        checks.append(inspect(wave,scene,human,receiver))
    write(root/'data/rendering.json',rendering)
    primary=next(s for s in recipe['scenes'] if s['branch']=='easy_human')
    direct=inspect_direct_component(root,work,recipe,primary,primary['humans'][0],primary['robots'][0])
    control=next(c for c in checks if c['branch']=='easy_robot' and c['receiver_id']=='R02')
    report=dict(passed=True,speech_revision=recipe['speech_revision'],isolated_foa_count=len(checks),
        source_stems_from_same_render=True,no_second_room_simulation=True,checks=checks,
        checks_scope='Full reverberant intensity estimates are descriptive: reflections can cause apparent direction fluctuations even for a stationary source and receiver.',
        stationary_reference=dict(branch='easy_robot',receiver_id='R02',source_id='H01',
            both_source_and_receiver_static=True,p95_angle_error_deg=control['p95_angle_error_deg'],
            maximum_adjacent_0_1s_angle_change_deg=control['maximum_adjacent_0_1s_angle_change_deg']),
        direct_component_check=direct)
    write(root/'data/continuity.json',report)
    print('H01 acoustic direction diagnostics:',
        [{k:c[k] for k in ['branch','receiver_id','coverage','p95_angle_error_deg','maximum_adjacent_0_1s_angle_change_deg']} for c in checks],flush=True)
    print('First-arrival continuity audit:',{k:direct[k] for k in ['passed','coverage','p95_angle_error_deg','maximum_adjacent_0_1s_angle_change_deg']},flush=True)


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--work',type=Path,required=True)
    a=p.parse_args();prepare(a.root.resolve(),a.work.resolve())