-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsolver.py
More file actions
659 lines (583 loc) · 28.3 KB
/
Copy pathsolver.py
File metadata and controls
659 lines (583 loc) · 28.3 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
from copy import deepcopy
import os
from pathlib import Path
from typing import List, Optional, Tuple, Union
from loguru import logger
import matplotlib.pyplot as plt
import numpy as np
from numpy.typing import ArrayLike, NDArray
from slope2noise.rooms import RoomGeometry
from slope2noise.utils import decay_kernel
import spaudiopy as spa
import torch
from diff_gfdn.dnn import OneHotEncoding
from diff_gfdn.plot import order_position_matrices
from diff_gfdn.save_results import save_loss
from diff_gfdn.utils import db, db2lin, ms_to_samps, samps_to_ms
from .config import DNNType, SpatialSamplingConfig
from .dataloader import load_dataset, SpatialRoomDataset, SpatialThreeRoomDataset
from .model import (
Directional_Beamforming_Weights,
Directional_Beamforming_Weights_from_CNN,
Directional_Beamforming_Weights_from_MLP,
Omni_Amplitudes_from_MLP,
)
from .trainer import SpatialSamplingTrainer
# pylint: disable=E0606, E0601, W0718
# flake8: noqa:E231
class make_plots:
"""Class for making plots"""
def __init__(self, room_data: SpatialRoomDataset,
config_dict: SpatialSamplingConfig,
model: Union[Omni_Amplitudes_from_MLP,
Directional_Beamforming_Weights_from_MLP]):
"""
Initialise parameters for the class
Args:
room_data (SpatialRoomDataset): object of SpatialRoomDataset dataclass
config_dict (SpatialSamplingConfig): config file, read as dictionary
model (Omni_Amplitudes_from_MLP): the NN model to be tested
"""
self.room_data = deepcopy(room_data)
self.model = deepcopy(model)
self.config_dict = deepcopy(config_dict)
self.room = RoomGeometry(room_data.sample_rate,
room_data.num_rooms,
np.array(room_data.room_dims),
np.array(room_data.room_start_coord),
aperture_coords=room_data.aperture_coords)
# prepare the training and validation data
self.train_dataset, _, _ = load_dataset(
room_data,
config_dict.device,
network_type=config_dict.network_type,
batch_size=config_dict.batch_size,
grid_resolution_m=room_data.grid_spacing_m,
shuffle=False,
)
# get the reference output
self.src_pos = np.array(self.room_data.source_position).squeeze()
self.true_points = torch.tensor(self.room_data.receiver_position,
dtype=torch.float32)
self.true_amps = torch.tensor(self.room_data.amplitudes,
dtype=torch.float32)
self.one_hot_encoder = OneHotEncoding()
self._init_decay_kernel()
def _init_decay_kernel(self):
"""Initialise the decay kernels for calculating EDC errors"""
num_slopes = self.room_data.num_rooms
edc_len_samps = ms_to_samps(2000, self.room_data.sample_rate)
self.envelopes = np.zeros((num_slopes, edc_len_samps))
time_axis = np.linspace(0, (edc_len_samps - 1) /
self.room_data.sample_rate, edc_len_samps)
for k in range(num_slopes):
self.envelopes[k, :] = decay_kernel(np.expand_dims(
self.room_data.common_decay_times[:, k], axis=-1),
time_axis,
self.room_data.sample_rate,
normalize_envelope=True,
add_noise=False).squeeze()
self.envelopes = torch.tensor(self.envelopes, dtype=torch.float32)
def get_model_output(self, num_epochs: int,
grid_spacing_m: float) -> Tuple[NDArray, NDArray]:
"""
Get the estimated common slope amplitudes.
Returns the positions and the amplitudes at those positions
"""
# load the trained weights for the particular epoch
checkpoint_found = False
while not checkpoint_found:
try:
checkpoint = torch.load(Path(
f'{self.config_dict.train_dir}/checkpoints/grid_resolution={grid_spacing_m:.1f}/'
+ f'model_e{num_epochs - 1}.pt').resolve(),
weights_only=True,
map_location=torch.device('cpu'))
# Load the trained model state
self.model.load_state_dict(checkpoint, strict=False)
checkpoint_found = True
logger.debug(f'Checkpoint found for epoch = {num_epochs}')
break
except Exception as exc:
num_epochs -= 1
if num_epochs < 0:
raise FileNotFoundError(
'Trained model does not exist!') from exc
# run the model in eval mode
self.model.eval()
est_pos = torch.empty((0, 3))
est_amps = torch.empty((0, self.room_data.num_rooms)) if isinstance(
self.model, Omni_Amplitudes_from_MLP) else torch.empty(
(0, self.room_data.num_directions, self.room_data.num_rooms))
with torch.no_grad():
for data in self.train_dataset:
position = data['listener_position']
model_output = self.model(data)
if isinstance(self.model, Directional_Beamforming_Weights):
cur_est_amps = self.model.get_directional_amplitudes()
if isinstance(self.model,
Directional_Beamforming_Weights_from_CNN):
# shape H, W, 2
cur_est_mesh = data['mesh_2D']
# find points in the meshgrid closest to current receiver points
# shape B
_, _, closest_points_idx = self.one_hot_encoder(
cur_est_mesh, position)
# check if this works correctly
assert torch.allclose(
cur_est_mesh.reshape(-1, 2)[closest_points_idx, :],
position[:, :2])
# sample the closest points from the amplitudes
cur_est_amps = cur_est_amps[closest_points_idx, ...]
else:
cur_est_amps = model_output
est_pos = torch.vstack((est_pos, position))
est_amps = torch.vstack((est_amps, cur_est_amps))
return est_pos, est_amps
def plot_beamformer_output(self,
est_amps: NDArray,
filename: str,
pos_to_investigate: List,
contour_plot: bool = True,
db_limits: Optional[Tuple] = None) -> Tuple:
"""
Plot beamformer output as function of elevation and azimuth angles
est_amps (NDArray): amplitudes estimated by the DNN
filename (str): filename for saving
pos_to_investigate (List): the position at which to plot the directional
distribution of amplitudes
contour_plot (bool): whether to plot spherical or contour plot
db_limits (optional, tuple): the limits of the colorbar
"""
# Create grid of elevation and azimuth angles
num_azi = 20
num_el = 20
azimuths = np.linspace(0, 2 * np.pi, num_azi)
elevations = np.linspace(-np.pi / 2, np.pi / 2, num_el)
polars = np.pi / 2 - elevations
azimuth_grid, polar_grid = np.meshgrid(azimuths, polars)
elevation_grid = np.pi / 2 - polar_grid
x = np.cos(elevation_grid) * np.sin(azimuth_grid)
y = np.cos(elevation_grid) * np.cos(azimuth_grid)
z = np.sin(elevation_grid)
# Plotting beamforming weights as a spherical surface
fig, ax = plt.subplots(
self.room_data.num_rooms,
1,
# subplot_kw={'projection': '3d'},
figsize=(6, 3 * self.room_data.num_rooms))
# spherical harmonic interpolation
sph_matrix_orig = spa.sph.sh_matrix(
self.room_data.ambi_order,
self.room_data.sph_directions[0, :],
np.pi / 2 - self.room_data.sph_directions[1, :],
sh_type='real')
sph_matrix_dense = spa.sph.sh_matrix(self.room_data.ambi_order,
azimuth_grid.ravel(),
polar_grid.ravel(),
sh_type='real')
weights = np.einsum('nj, bjk -> bnk',
sph_matrix_orig.T / self.room_data.num_directions,
est_amps)
# retrieve the amplitudes by projecting on denser spherical grid
amps_interp = np.einsum('dn, bnk -> bdk', sph_matrix_dense, weights)
# find receiver position idx
rec_pos_idx = ((self.room_data.receiver_position -
pos_to_investigate)**2).sum(axis=1).argmin()
logger.info(
f"Plotting contours at position {np.round(self.room_data.receiver_position[rec_pos_idx, :], 2)}"
)
amps_interp_at_pos = amps_interp[rec_pos_idx, ...]
amps_interp_at_pos_db = db(amps_interp_at_pos, is_squared=True)
num_row, num_col = azimuth_grid.shape
if db_limits is None:
db_limits = np.zeros((2, self.room_data.num_rooms))
db_limits[0, :] = np.min(amps_interp_at_pos_db, axis=0)
db_limits[1, :] = np.max(amps_interp_at_pos_db, axis=0)
for k in range(self.room_data.num_rooms):
amps_interp_at_pos_db_2D = amps_interp_at_pos_db[:, k].reshape(
num_row, num_col)
# Plot the ellipsoid surface with beamforming weights as color values
if contour_plot:
surf = ax[k].contourf(np.degrees(azimuth_grid),
np.degrees(polar_grid),
amps_interp_at_pos_db_2D,
vmin=db_limits[0, k],
vmax=db_limits[1, k],
cmap='plasma')
ax[k].set_xlabel('Azimuth angles')
ax[k].set_ylabel('Polar angles')
else:
surf = ax[k].plot_surface(
x,
y,
z,
facecolors=plt.cm.viridis(amps_interp_at_pos_db_2D /
amps_interp_at_pos_db_2D.max()),
rstride=1,
cstride=1,
linewidth=0,
antialiased=False,
alpha=0.5,
)
ax[k].set_xlabel('X')
ax[k].set_ylabel('Y')
ax[k].set_zlabel('Z)')
# Add a colorbar
cbar = fig.colorbar(surf, ax=ax[k], shrink=0.8, aspect=5)
cbar.set_label('dB')
ax[k].set_title(f'Group = {k+1}')
fig.subplots_adjust(hspace=0.4)
fig.savefig(Path(f'{self.config_dict.train_dir}/{filename}').resolve())
return db_limits
def plot_amplitudes_in_space(self,
grid_resolution_m: float,
est_amps: NDArray,
est_points: NDArray,
verbose: bool = False):
"""
Plot the true and learned amplitudes as a function of space
Args:
grid_resolution_m (float): resolution of the uniform grid used for training
est_amps (NDArray): estimated omni (num_pos, num_groups) /
directional amplitudes from NN (num_pos, num_directions, num_groups)
est_points (NDArray): receiver positions at which the amplitudes were estimatied
verbose (bool): whether to print out mean and std of amplitudes
"""
logger.info("Making amplitude plots")
db_limits = torch.zeros((2, self.room_data.num_rooms))
if self.true_amps.ndim == 2:
db_limits[0, :], _ = torch.min(db(self.true_amps, is_squared=True),
dim=0)
db_limits[1, :], _ = torch.max(db(self.true_amps, is_squared=True),
dim=0)
# the amplitudes are omni directional
self.room.plot_amps_at_receiver_points(
self.true_points,
self.src_pos,
self.true_amps.T,
scatter_plot=False,
save_path=Path(
f'{self.config_dict.train_dir}/actual_amplitudes_in_space.png'
).resolve(),
title='Common slopes',
db_limits=db_limits)
self.room.plot_amps_at_receiver_points(
est_points,
self.src_pos,
est_amps.T,
scatter_plot=False,
save_path=Path(
f'{self.config_dict.train_dir}/learnt_amplitudes_in_space_'
+ f'grid_resolution_m={np.round(grid_resolution_m, 3)}.png'
).resolve(),
title=
f'Training grid resolution={np.round(grid_resolution_m, 3)}m',
db_limits=db_limits)
else:
# the amplitudes are direction dependent
for j in range(self.room_data.num_directions):
if verbose:
print(
f'Actual amplitudes mean : {np.round(self.true_amps[:, j, :].mean(dim=0), 3)},'
+
f'Est amplitudes mean: {np.round(est_amps[:, j, :].mean(dim=0), 3)} for direction {j}'
)
print(
f'Actual amplitudes STD: {np.round(self.true_amps[:, j, :].std(dim=0),3)},'
+
f'est amplitudes STD: {np.round(est_amps[:, j, :].std(dim=0), 3)} for direction {j}'
)
db_limits[0, :], _ = torch.min(db(self.true_amps[:, j, :],
is_squared=True),
dim=0)
db_limits[1, :], _ = torch.max(db(self.true_amps[:, j, :],
is_squared=True),
dim=0)
dir_string = (
f'az = {np.degrees(self.room_data.sph_directions[0, j]):.2f} deg, '
+
f' pol = {np.degrees(self.room_data.sph_directions[1, j]):.2f} deg'
)
directory = Path(
f'{self.config_dict.train_dir}/direction={j+1}').resolve()
if not os.path.exists(directory):
os.makedirs(directory)
self.room.plot_amps_at_receiver_points(
self.true_points,
self.src_pos,
self.true_amps[:, j, :].T,
scatter_plot=False,
save_path=f'{directory}/actual_amplitudes_in_space.png',
title='Common slopes, ' + dir_string,
db_limits=db_limits)
self.room.plot_amps_at_receiver_points(
est_points,
self.src_pos,
est_amps[:, j, :].T,
scatter_plot=False,
save_path=f'{directory}/learnt_amplitudes_in_space_' +
f'grid_resolution_m={np.round(grid_resolution_m, 3)}.png',
title=
f'Training grid resolution={np.round(grid_resolution_m, 3)}m, '
+ dir_string,
db_limits=db_limits)
def plot_edc_error_in_space(self,
grid_resolution_m: float,
est_amps: NDArray,
est_points: NDArray,
idx_in_valid_set: Optional[ArrayLike] = None):
"""
Plot the error between the CS EDC and MLP EDC in space
Args:
grid_resolution_m (float): resolution of the uniform grid used for training
est_amps (NDArray): estimated omni (num_pos, num_groups) /
directional amplitudes from NN (num_pos, num_directions, num_groups)
est_points (NDArray): receiver positions at which the amplitudes were estimatied
idx_in_valid_set (ArrayLike, optional): the indices of the receiver positions in the valid set,
if None, all receiver positions are plotted
"""
logger.info("Making EDC error plots")
# order the position indices in the estimated data according to the
# reference dataset
if idx_in_valid_set is None:
idx_in_valid_set = np.arange(0,
self.room_data.num_rec,
dtype=np.int32)
extend = ''
else:
extend = '_valid_set'
# returns idx in est_points that are closest to true_points[idx_in_valid_set]
ordered_pos_idx = order_position_matrices(
self.true_points[idx_in_valid_set], est_points)
if self.true_amps.ndim == 2:
original_edc = db(torch.einsum('bk, kt -> bt',
self.true_amps[idx_in_valid_set],
self.envelopes),
is_squared=True)
est_edc = db(torch.einsum('bk, kt -> bt',
est_amps[ordered_pos_idx],
self.envelopes),
is_squared=True)
error_db = torch.mean(torch.abs(original_edc - est_edc), dim=-1)
self.room.plot_edc_error_at_receiver_points(
self.true_points[idx_in_valid_set],
self.src_pos,
db2lin(error_db),
scatter_plot=False,
cur_freq_hz=None,
save_path=Path(
f'{self.config_dict.train_dir}/edc_error_in_space_' +
f'grid_resolution_m={np.round(grid_resolution_m, 3)}' +
extend + '.png').resolve(),
title=f'Grid resolution={np.round(grid_resolution_m, 3)}m')
else:
original_edc = db(torch.einsum('bjk, kt -> bjt',
self.true_amps[idx_in_valid_set],
self.envelopes),
is_squared=True)
est_edc = db(torch.einsum('bjk, kt -> bjt',
est_amps[ordered_pos_idx],
self.envelopes),
is_squared=True)
error_db = torch.mean(torch.abs(original_edc - est_edc), dim=-1)
logger.info(f'Mean EDC error in dB is {error_db.mean():.3f} dB')
for j in range(self.room_data.num_directions):
self.room.plot_edc_error_at_receiver_points(
self.true_points[idx_in_valid_set],
self.src_pos,
db2lin(error_db[:, j]),
scatter_plot=True,
cur_freq_hz=None,
save_path=Path(
f'{self.config_dict.train_dir}/direction={j+1}/edc_error_in_space_'
+
f'grid_resolution_m={np.round(grid_resolution_m, 3)}' +
extend + '.png').resolve(),
# title=
# f'az = {np.degrees(self.room_data.sph_directions[0, j]):.2f} deg,'
# +
# f' pol = {np.degrees(self.room_data.sph_directions[1, j]):.2f} deg'
)
############################################################################
def run_training_spatial_sampling(config_dict: SpatialSamplingConfig,
plot_results_only: bool = False):
"""
Run the training to test for spatial sampling resolution
Args:
config_dict: config file for training
plot_results_only (bool): training already done, only plot the results
Returns:
A list of ColorlessFDNResults dataclass, each for one FDN in the GFDN
"""
logger.info("Training the MLP to learn spatial mappings")
if "3room_FDTD" in config_dict.room_dataset_path:
# read the coupled room dataset
room_data = SpatialThreeRoomDataset(
Path(config_dict.room_dataset_path).resolve())
else:
logger.error("Currently only the three room dataset is supported")
config_dict = config_dict.model_copy(
update={'use_directional_rirs': room_data.sph_directions is not None})
# are we learning OMNI amplitudes or directional amplitudes?
if config_dict.use_directional_rirs:
if config_dict.network_type == DNNType.MLP:
logger.info("Using MLP for training")
model = Directional_Beamforming_Weights_from_MLP(
room_data.num_rooms,
room_data.ambi_order,
config_dict.dnn_config.num_fourier_features,
config_dict.dnn_config.mlp_config.num_hidden_layers,
config_dict.dnn_config.mlp_config.num_neurons_per_layer,
desired_directions=room_data.sph_directions,
beamformer_type=config_dict.dnn_config.beamformer_type,
device=config_dict.device,
)
elif config_dict.network_type == DNNType.CNN:
logger.info("Using CNN for training")
model = Directional_Beamforming_Weights_from_CNN(
room_data.num_rooms,
room_data.ambi_order,
config_dict.dnn_config.num_fourier_features,
config_dict.dnn_config.cnn_config.num_hidden_channels,
config_dict.dnn_config.cnn_config.num_layers,
config_dict.dnn_config.cnn_config.kernel_size,
desired_directions=room_data.sph_directions,
beamformer_type=config_dict.dnn_config.beamformer_type,
device=config_dict.device)
else:
model = Omni_Amplitudes_from_MLP(
room_data.num_rooms,
config_dict.dnn_config.num_fourier_features,
config_dict.dnn_config.mlp_config.num_hidden_layers,
config_dict.dnn_config.mlp_config.num_neurons_per_layer,
device=config_dict.device,
gain_limits=(db2lin(-100), db2lin(0)),
)
# set default device
torch.set_default_device(config_dict.device)
# move model to device (cuda or cpu)
model = model.to(config_dict.device)
# plot object
plot_obj = make_plots(room_data, config_dict, model)
if isinstance(model, Directional_Beamforming_Weights_from_MLP):
# at the aperture between the first and second rooms
pos_to_investigate = [4.0, 4.0, 1.5]
true_db_limits = plot_obj.plot_beamformer_output(
room_data.amplitudes,
pos_to_investigate=pos_to_investigate,
filename='true_directional_amplitudes.png')
# at least one mic in each room
assert config_dict.num_grid_spacing * room_data.grid_spacing_m <= np.min(
np.asarray(room_data.room_dims)[:, :2]
), "Reduce number of grid spacing points to have at least one mic in each room"
grid_resolution_m = np.arange(config_dict.num_grid_spacing, 0,
-1) * room_data.grid_spacing_m
# dictionary contains training loss for each grid_resolution of size num_epochs
trainer_loss = {}
valid_loss = {}
fig, ax = plt.subplots(2, 1, figsize=(6, 8))
for k in range(config_dict.num_grid_spacing):
# prepare the training and validation data
train_dataset, valid_dataset, dataset_ref = load_dataset(
room_data,
config_dict.device,
network_type=config_dict.network_type,
batch_size=config_dict.batch_size,
grid_resolution_m=np.round(grid_resolution_m[k], 1),
)
if not plot_results_only:
logger.info(
f"Training DNN for grid resolution = {np.round(grid_resolution_m[k], 1)} m"
)
# go back to training mode from evaluation mode
model.train()
# create the trainer object
trainer = SpatialSamplingTrainer(
model,
config_dict,
grid_spacing_m=grid_resolution_m[k],
sampling_rate=room_data.sample_rate,
ir_len_ms=samps_to_ms(room_data.rir_length,
room_data.sample_rate),
dataset_ref=dataset_ref,
common_decay_times=room_data.common_decay_times,
# receiver_positions=room_data.receiver_position,
)
# train the network
trainer.train(train_dataset, valid_dataset)
# save train loss evolution
save_loss(trainer.train_loss,
config_dict.train_dir +
f"grid_resolution={np.round(grid_resolution_m[k], 3)}",
save_plot=True,
filename='training_loss_vs_epoch')
# save the validation loss
save_loss(
trainer.valid_loss,
config_dict.train_dir +
f"grid_resolution={np.round(grid_resolution_m[k], 3)}",
save_plot=True,
filename='valid_loss_vs_position',
xaxis_label='Position #',
)
trainer_loss[grid_resolution_m[k]] = trainer.train_loss
valid_loss[grid_resolution_m[k]] = trainer.valid_loss
# plot the loss as a function of the grid_resolution
ax[0].semilogy(
np.arange(len(trainer_loss[grid_resolution_m[k]])),
trainer_loss[grid_resolution_m[k]],
label=f'Grid resolution = {np.round(grid_resolution_m[k], 3)}m'
)
ax[1].semilogy(
np.arange(len(trainer_loss[grid_resolution_m[k]])),
valid_loss[grid_resolution_m[k]],
label=f'Grid resolution = {np.round(grid_resolution_m[k], 3)}m'
)
del trainer
num_epochs = config_dict.max_epochs if plot_results_only else len(
trainer_loss[grid_resolution_m[k]])
# get the model output
est_points, est_amps = plot_obj.get_model_output(
num_epochs, grid_resolution_m[k])
# make plots
if isinstance(model, Directional_Beamforming_Weights_from_MLP):
_ = plot_obj.plot_beamformer_output(
est_amps,
pos_to_investigate=pos_to_investigate,
filename='learned_directional_amplitudes ' +
f'grid_resolution_m={np.round(grid_resolution_m[k], 3)}.png',
db_limits=true_db_limits)
plot_obj.plot_amplitudes_in_space(
grid_resolution_m[k],
est_amps,
est_points,
)
# plot EDC error for validation set only
if grid_resolution_m[k] > room_data.grid_spacing_m:
valid_rec_idx = []
for data in valid_dataset:
cur_valid_pos = data['listener_position'].detach().cpu().numpy(
)
indx = room_data.find_rec_idx_in_room_dataset(cur_valid_pos)
valid_rec_idx = np.concatenate((valid_rec_idx, indx))
plot_obj.plot_edc_error_in_space(
grid_resolution_m[k],
est_amps,
est_points,
valid_rec_idx,
)
else:
plot_obj.plot_edc_error_in_space(
grid_resolution_m[k],
est_amps,
est_points,
)
ax[0].set_xlabel('Epoch #')
ax[0].set_ylabel('Training loss (log)')
ax[1].set_xlabel('Epoch #')
ax[1].set_ylabel('Validation loss (log)')
ax[1].legend(loc='best', bbox_to_anchor=(1.1, 0.5))
fig.savefig(os.path.join(config_dict.train_dir,
'loss_vs_grid_resolution.png'),
bbox_inches="tight")