docstr: This script computes the SDR and SI-SNR metrics and saves
  them into a csv file
docstr_tok: ["This","script","computes","the","SDR","and","SI-SNR","metrics","and","saves","them","into","a","csv","file"]
code: def save_results(self, test_data):
      """This script computes the SDR and SI-SNR metrics and saves
      them into a csv file"""
      # This package is required for SDR computation
      from mir_eval.separation import bss_eval_sources
  
      # Create folders where to store audio
      save_file = os.path.join(
          self.hparams.output_folder, "test_results.csv"
      )
  
      count = 0
      # Variable init
      all_sisnrs = []
      all_sisnrs_i = []
      all_pesqs = []
      all_stois = []
      all_sdrs = []
      all_sdrs_i = []
      csv_columns = [
          "snt_id",
          "snt",
          "sdr",
          "sdr_i",
          "si-snr",
          "si-snr_i",
          "pesq",
          "stoi",
          "csig",
          "cbak",
          "covl",
      ]
  
      test_loader = sb.dataio.dataloader.make_dataloader(test_data)
  
      with open(save_file, "w") as results_csv:
          writer = csv.DictWriter(results_csv, fieldnames=csv_columns)
          writer.writeheader()
  
          # Loop over all test sentence
          with tqdm(test_loader, dynamic_ncols=True) as t:
              for i, batch in enumerate(t):
                  # Apply Enhancement
                  noisy, noisy_len = batch.noisy_sig
                  snt_id = batch.id
                  clean = batch.clean_sig
                  noisy_wav = (
                      batch.noisy_wav[0]
                      .split("/")[-1]
                      .replace(".wav", "")
                  )
  
                  with torch.no_grad():
                      predictions, clean = self.compute_forward_enhance(
                          batch, sb.Stage.TEST
                      )
  
                  # Write enhanced wavs for sanity check
                  if self.hparams.save_audio:
                      self.save_audio(
                          snt_id[0],
                          batch.noisy_sig,
                          clean,
                          predictions[0],
                          batch,
                      )
  
                  psq_mode = (
                      "wb"
                      if self.hparams.enhance_sample_rate == 16000
                      else "nb"
                  )
  
                  try:
                      # Compute SI-SNR
                      sisnr = self.compute_objectives_enhance(
                          predictions, clean
                      )
  
                      # Compute SI-SNR improvement
                      noisy_signal = noisy
  
                      noisy_signal = noisy_signal.to(clean.device)
                      sisnr_baseline = self.compute_objectives_enhance(
                          [noisy_signal.squeeze(-1), None], clean
                      )
                      sisnr_i = sisnr - sisnr_baseline
  
                      # Compute SDR
                      sdr, _, _, _ = bss_eval_sources(
                          clean[0].t().cpu().numpy(),
                          predictions[0][0].t().detach().cpu().numpy(),
                      )
  
                      sdr_baseline, _, _, _ = bss_eval_sources(
                          clean[0].t().cpu().numpy(),
                          noisy_signal[0].t().detach().cpu().numpy(),
                      )
  
                      sdr_i = sdr.mean() - sdr_baseline.mean()
  
                      # Compute PESQ
                      psq = pesq(
                          self.hparams.enhance_sample_rate,
                          clean.squeeze().cpu().numpy(),
                          predictions[0].squeeze().cpu().numpy(),
                          mode=psq_mode,
                      )
                      # Compute STOI
                      stoi_score = stoi(
                          clean.squeeze().cpu().numpy(),
                          predictions[0].squeeze().cpu().numpy(),
                          fs_sig=self.hparams.enhance_sample_rate,
                          extended=False,
                      )
  
                  except Exception:
                      # this handles all sorts of error that may
                      # occur when evaluating a enhanced file.
                      count += 1
                      continue
  
                  # Saving on a csv file
                  row = {
                      "snt_id": snt_id[0],
                      "snt": noisy_wav,
                      "si-snr": -sisnr.item(),
                      "si-snr_i": -sisnr_i.item(),
                      "pesq": psq,
                      "stoi": stoi_score,
                      "sdr": sdr.mean(),
                      "sdr_i": sdr_i,
                  }
                  writer.writerow(row)
  
                  # Metric Accumulation
                  all_sisnrs.append(-sisnr.item())
                  all_sisnrs_i.append(-sisnr_i.item())
                  all_pesqs.append(psq)
                  all_stois.append(stoi_score)
                  all_sdrs.append(sdr.mean())
                  all_sdrs_i.append(sdr_i.mean())
  
              row = {
                  "snt_id": "avg",
                  "snt": "avg",
                  "si-snr": np.array(all_sisnrs).mean(),
                  "si-snr_i": np.array(all_sisnrs_i).mean(),
                  "pesq": np.array(all_pesqs).mean(),
                  "stoi": np.array(all_stois).mean(),
                  "sdr": np.array(all_sdrs).mean(),
                  "sdr_i": np.array(all_sdrs_i).mean(),
              }
              writer.writerow(row)
  
      logger.info(
          "Mean SISNR is {}".format(np.array(all_sisnrs).mean())
      )
      logger.info(
          "Mean SISNRi is {}".format(np.array(all_sisnrs_i).mean())
      )
      logger.info("Mean PESQ {}".format(np.array(all_pesqs).mean()))
      logger.info("Mean STOI {}".format(np.array(all_stois).mean()))
      logger.info("Mean SDR is {}".format(np.array(all_sdrs).mean()))
      logger.info("Mean SDRi is {}".format(np.array(all_sdrs_i).mean()))
      logger.info("Total discarded files {}".format(count))
  
imports: import os
  import sys
  import csv
  import logging
  import numpy
  from tqdm import tqdm
  from pesq import pesq
  from pystoi import stoi
  import torch
  import torchaudio
  import torch.nn.functional
  import speechbrain
  from hyperpyyaml import load_hyperpyyaml
  from speechbrain.utils.metric_stats import MetricStats
  from speechbrain.utils.distributed import run_on_main
  from speechbrain.utils.data_utils import undo_padding
label_desc: Use image node_id 14 for calling the ASR obj's underlying member method code with example usage: obj.save_results(test_data) without return types