File size: 11,596 Bytes
347d9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render each three-episode base as one calibrated, normalized bundle."""
from __future__ import annotations
import argparse,fcntl,gzip,json,math,os,shutil,time,traceback
from pathlib import Path
import numpy as np
import soundfile as sf
from dynamic_demo.render import make_dry,two_time_convolution
from exhibition_dataset.render import NativeRenderer,source_mask,fixed_source
from .noise import waveform as noise_waveform
from .common import *
from .geometry import audit
from .resume_binding import compatible_cleanup_only

def code_binding():
    repo=Path(__file__).resolve().parents[1]
    names=['exhibition_v3/render.py','exhibition_v3/common.py','exhibition_v3/geometry.py',
        'exhibition_dataset/render.py','exhibition_dataset/noise.py','exhibition_v3/noise.py','dynamic_demo/render.py',
        'dynamic_dataset/common.py','dynamic_demo/common.py','exhibition_dataset/common.py']
    return {name:sha(repo/name) for name in names}

def noise_component(root,episode,receiver,engine):
    count=episode['duration_samples'];pre=math.ceil(engine.recipe['renderer']['irTime']*SR)
    dry=noise_waveform(episode['noise'],count+pre,root)
    dry=np.r_[dry,np.zeros(pre+1,np.float32)]
    rn=sorted(set([0.,pre/SR]+[round(t+pre/SR,9) for t in rir_nodes(receiver)]))
    source=fixed_source(episode['noise'])
    rendered=two_time_convolution(dry,[0.],rn,
        lambda te,tr:engine.kernel(source,receiver,0.,max(0.,tr-pre/SR)),
        max_tail_s=engine.recipe['renderer']['irTime']+.001)
    return rendered[pre:pre+count]

def run(root,group,gpu,cache):
    ensure_compute();root=root.resolve();cache=cache.resolve()
    result_path=root/'reports/bases'/f"{group['index']:04d}.json"
    binding=dict(plan_sha256=sha(root/'private/plans'/f"{group['index']:04d}.json"),code=code_binding())
    if result_path.exists():
        result=read(result_path)
        if result['binding']!=binding and not compatible_cleanup_only(result['binding'],binding):
            raise ValueError('Completed bundle uses different plan or rendering code')
        for record in result['recordings']:
            if sha(root/record['path'])!=record['sha256']:raise ValueError('Completed FOA checksum mismatch')
        return result
    cache.mkdir(parents=True,exist_ok=True)
    started=time.monotonic();engine_root=cache/'engine';(engine_root/'assets').mkdir(parents=True,exist_ok=True)
    link=engine_root/'assets/room'
    if not link.exists():link.symlink_to(root/'shared/rooms'/group['room_id']/'assets/room',target_is_directory=True)
    engine=NativeRenderer(engine_root,group,cache/'rirs',gpu)
    original=engine.kernel
    def kernel(source,receiver,te,tr):
        write(root/'operations/progress'/f"{group['index']:04d}.json",dict(time_unix=time.time(),
            base_index=group['index'],source_id=source['entity_id'],receiver_id=receiver['entity_id'],
            source_time_s=te,receiver_time_s=tr,gpu=gpu,pid=os.getpid(),host=os.environ.get('HOSTNAME')))
        return original(source,receiver,te,tr)
    engine.kernel=kernel
    components={};records=[];measurements=[];waves={};checks=[]
    try:
        episodes=group['static_episodes']+group['dynamic_episodes'];base=episodes[0]
        dry,gains=make_dry(root,base)
        calibration=None;noise_gain=0.
        if base['noise']['enabled']:
            target=base['humans'][0];receiver=base['robots'][0]
            rendered=two_time_convolution(dry[target['entity_id']],[0.],[0.],
                lambda te,tr:engine.kernel(target,receiver,te,tr),max_tail_s=group['renderer']['irTime']+.001)
            noise=noise_component(root,base,receiver,engine);mask=source_mask(target,len(dry[target['entity_id']]))
            signal_power=float(np.mean(rendered[mask,0].astype(float)**2));noise_power=float(np.mean(noise[mask,0].astype(float)**2))
            if signal_power<=0 or noise_power<=0:raise ValueError('Invalid static SNR reference power')
            noise_gain=math.sqrt(signal_power/(noise_power*10**(base['noise']['nominal_snr_db']/10)))
            calibration=dict(reference_episode_id=base['episode_id'],reference_human='H01',reference_receiver='R01',
                channel='W',mask='emitted H01 speech activity',signal_power=signal_power,unit_noise_power=noise_power,
                nominal_snr_db=base['noise']['nominal_snr_db'],shared_noise_emission_gain=noise_gain,
                policy='unchanged across every derivative and receiver; received SNR is separately measured')
        for episode in episodes:
            if audit(episode,group['room']) is None:raise ValueError('Independent geometry acceptance failed')
            eid=episode['episode_id'];mode=episode['mode'];dry,current_gains=make_dry(root,episode)
            if current_gains!=gains:raise ValueError('Dry emission gains changed between base derivatives')
            for receiver in episode['robots']:
                rid=receiver['entity_id'];stems={}
                for source in episode['humans']+episode['playback_sources']:
                    sid=source['entity_id']
                    if sid==rid:continue
                    key=uid('stem',source,receiver,episode['duration_samples'])
                    if key not in components:
                        components[key]=two_time_convolution(dry[sid],rir_nodes(source),rir_nodes(receiver),
                            lambda te,tr,s=source:engine.kernel(s,receiver,te,tr),max_tail_s=group['renderer']['irTime']+.001)
                    stems[sid]=components[key]
                noise=np.zeros((episode['duration_samples'],4),np.float32)
                if episode['noise']['enabled']:
                    key=uid('noise',episode['noise'],receiver,episode['duration_samples'])
                    if key not in components:components[key]=noise_component(root,episode,receiver,engine)*noise_gain
                    noise=components[key]
                speech=sum((x.astype(np.float64) for x in stems.values()),np.zeros_like(noise,dtype=np.float64))
                wave=(speech+noise).astype(np.float32)
                if not np.isfinite(wave).all() or not np.any(wave):raise ValueError('Invalid or silent FOA')
                waves[(eid,rid)]=wave
                records.append(dict(recording_id=uid(eid,rid,'recording'),episode_id=eid,scene_id=group['scene_id'],
                    base_scene_id=group['base_scene_id'],receiver_robot_id=rid,mode=mode,
                    path=f'{mode}/public/audio/test/{eid}/{rid}_foa.wav',num_samples=len(wave),sample_rate_hz=SR,
                    num_channels=4,channels=['W','Y','Z','X'],ordering='ACN',normalization='SN3D',subtype='FLOAT',global_start_sample=0,
                    raw_peak=float(np.max(np.abs(wave)))))
                checks.append(dict(episode_id=eid,receiver_id=rid,source_ids=list(stems),own_playback_excluded=rid not in stems,
                    noise_included=episode['noise']['enabled'],finite=True,
                    mixture_reconstruction_error=float(np.max(np.abs(wave.astype(float)-speech-noise)))))
                for human in episode['humans']:
                    mask=source_mask(human,len(wave));target=stems[human['entity_id']][:,0].astype(float)
                    competing=speech[:,0]-target
                    powers=[float(np.mean(x[mask]**2)) for x in [target,competing,noise[:,0].astype(float)]]
                    sp,ip,npower=powers
                    ratio=lambda denom:10*math.log10(sp/denom) if sp>0 and denom>1e-30 else None
                    snr=ratio(npower)
                    if calibration and eid==base['episode_id'] and rid=='R01' and human['entity_id']=='H01':
                        if abs(snr-base['noise']['nominal_snr_db'])>.001:raise ValueError('Static anchor SNR calibration failed')
                    measurements.append(dict(episode_id=eid,receiver_id=rid,source_id=human['entity_id'],
                        target_power=sp,competing_speech_power=ip,environmental_noise_power=npower,
                        snr_db=snr,sir_db=ratio(ip),sinr_db=ratio(ip+npower),mask='emitted target speech activity; received W channel',
                        nominal_static_anchor_snr_db=episode['noise'].get('nominal_snr_db')))
            print('EPISODE',group['index'],episode['variant_id'],'rirs',len(engine.records),flush=True)
        # ONE common scale preserves all cross-receiver and static/dynamic energy ratios.
        scale=min(1.,.9/max(record['raw_peak'] for record in records))
        for record in records:
            wave=waves[(record['episode_id'],record['receiver_robot_id'])]*scale
            path=root/record['path'];path.parent.mkdir(parents=True,exist_ok=True);temporary=path.with_suffix('.part.wav')
            write_float_wav(temporary,wave);temporary.replace(path)
            back,rate=sf.read(path,dtype='float32');np.testing.assert_array_equal(back,wave)
            if rate!=SR:raise ValueError('FOA sample rate differs')
            record.update(sha256=sha(path),common_final_gain=scale,final_peak=float(np.max(np.abs(wave))))
        rir_path=root/'private/rir_audits'/f"{group['index']:04d}.jsonl.gz";rir_path.parent.mkdir(parents=True,exist_ok=True)
        with gzip.open(rir_path,'wt') as f:
            for record in sorted(engine.records.values(),key=lambda r:r['rir_id']):f.write(json.dumps(record,separators=(',',':'))+'\n')
        result=dict(passed=True,binding=binding,base_scene_id=group['base_scene_id'],index=group['index'],room_id=group['room_id'],
            recordings=records,acoustic_measurements=measurements,audio_checks=checks,noise_calibration=calibration,
            dry_gains=gains,common_final_gain=scale,final_normalization_applied=True,rir_count=len(engine.records),
            rir_audit_path=str(rir_path.relative_to(root)),rir_audit_sha256=sha(rir_path),
            wall_seconds=time.monotonic()-started,completed_unix=time.time(),host=os.environ.get('HOSTNAME'),gpu=gpu)
        write(result_path,result);print('BASE COMPLETE',group['index'],round(result['wall_seconds'],1),flush=True)
        return result
    finally:engine.close()

def worker(root,gpu,shard,shards,cache_root,limit=800):
    ensure_compute()
    for index in range(shard,limit,shards):
        path=root/'private/plans'/f'{index:04d}.json'
        if not path.exists():raise ValueError('Frozen plan missing: '+str(path))
        lock_path=root/'operations/locks'/f'{index:04d}.lock';lock_path.parent.mkdir(parents=True,exist_ok=True)
        with lock_path.open('a+') as lock:
            fcntl.flock(lock,fcntl.LOCK_EX)
            cache=cache_root/f'{index:04d}'
            try:
                run(root,read(path),gpu,cache)
                if cache.exists():shutil.rmtree(cache)
                error=root/'reports/errors'/f'{index:04d}.json'
                if error.exists():error.unlink()
            except Exception as exc:
                write(root/'reports/errors'/f'{index:04d}.json',dict(index=index,error=repr(exc),traceback=traceback.format_exc(),time_unix=time.time()))
                print('BASE FAILED',index,repr(exc),flush=True)
                raise
    write(root/'operations/workers'/f'{shard:02d}.json',dict(complete=True,shard=shard,shards=shards))

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--gpu',type=int,required=True)
    p.add_argument('--shard',type=int,default=0);p.add_argument('--shards',type=int,default=16);p.add_argument('--limit',type=int,default=800)
    p.add_argument('--cache-root',type=Path,required=True);a=p.parse_args();worker(a.root,a.gpu,a.shard,a.shards,a.cache_root,a.limit)