def extract_sample_name_from_sam_reader(sam_reader):
  """Returns the sample name as derived from the BAM file of reads.

  Args:
    sam_reader: Already opened sam_reader to use to extract the sample names
      from. This sam_reader will not be closed after this function returns.

  Returns:
    The sample ID annotated in the read group.

  Raises:
    ValueError: There is not exactly one unique sample name in the SAM/BAM.
  """
  samples = {
      rg.sample_id
      for rg in sam_reader.header.read_groups
      if rg.sample_id
  }
  if not samples:
    raise ValueError(
        'No non-empty sample name found in the input reads. Please provide the '
        'name of the sample with the --sample_name argument.')
  elif len(samples) > 1:
    raise ValueError(
        'Multiple samples ({}) were found in the input reads. DeepVariant can '
        'only call variants from a BAM file containing a single sample.'.format(
            ', '.join(sorted(samples))))
  return next(iter(samples))