code: def impute_sex(
      call,
      aaf_threshold=0.0,
      include_par=False,
      female_threshold=0.2,
      male_threshold=0.8,
      aaf=None,
  ) -> Table:
      r"""Impute sex of samples by calculating inbreeding coefficient on the
      X chromosome.
  
      .. include:: ../_templates/req_tvariant.rst
  
      .. include:: ../_templates/req_biallelic.rst
  
      Examples
      --------
  
      Remove samples where imputed sex does not equal reported sex:
  
      >>> imputed_sex = hl.impute_sex(dataset.GT)
      >>> dataset_result = dataset.filter_cols(imputed_sex[dataset.s].is_female != dataset.pheno.is_female,
      ...                                      keep=False)
  
      Notes
      -----
  
      We have used the same implementation as `PLINK v1.7
      <https://zzz.bwh.harvard.edu/plink/summary.shtml#sexcheck>`__.
  
      Let `gr` be the the reference genome of the type of the `locus` key (as
      given by :attr:`.tlocus.reference_genome`)
  
      1. Filter the dataset to loci on the X contig defined by `gr`.
  
      2. Calculate alternate allele frequency (AAF) for each row from the dataset.
  
      3. Filter to variants with AAF above `aaf_threshold`.
  
      4. Remove loci in the pseudoautosomal region, as defined by `gr`, unless
         `include_par` is ``True`` (it defaults to ``False``)
  
      5. For each row and column with a non-missing genotype call, :math:`E`, the
         expected number of homozygotes (from population AAF), is computed as
         :math:`1.0 - (2.0*\mathrm{maf}*(1.0-\mathrm{maf}))`.
  
      6. For each row and column with a non-missing genotype call, :math:`O`, the
         observed number of homozygotes, is computed interpreting ``0`` as
         heterozygote and ``1`` as homozygote`
  
      7. For each row and column with a non-missing genotype call, :math:`N` is
         incremented by 1
  
      8. For each column, :math:`E`, :math:`O`, and :math:`N` are combined across
         variants
  
      9. For each column, :math:`F` is calculated by :math:`(O - E) / (N - E)`
  
      10. A sex is assigned to each sample with the following criteria:
          - Female when ``F < 0.2``
          - Male when ``F > 0.8``
          Use `female_threshold` and `male_threshold` to change this behavior.
  
      **Annotations**
  
      The returned column-key indexed :class:`.Table` has the following fields in
      addition to the matrix table's column keys:
  
      - **is_female** (:py:data:`.tbool`) -- True if the imputed sex is female,
        false if male, missing if undetermined.
      - **f_stat** (:py:data:`.tfloat64`) -- Inbreeding coefficient.
      - **n_called**  (:py:data:`.tint64`) -- Number of variants with a genotype call.
      - **expected_homs** (:py:data:`.tfloat64`) -- Expected number of homozygotes.
      - **observed_homs** (:py:data:`.tint64`) -- Observed number of homozygotes.
  
      call : :class:`.CallExpression`
          A genotype call for each row and column. The source dataset's row keys
          must be [[locus], alleles] with types :class:`.tlocus` and
          :class:`.tarray` of :obj:`.tstr`. Moreover, the alleles array must have
          exactly two elements (i.e. the variant must be biallelic).
      aaf_threshold : :obj:`float`
          Minimum alternate allele frequency threshold.
      include_par : :obj:`bool`
          Include pseudoautosomal regions.
      female_threshold : :obj:`float`
          Samples are called females if F < female_threshold.
      male_threshold : :obj:`float`
          Samples are called males if F > male_threshold.
      aaf : :class:`str` or :obj:`None`
          A field defining the alternate allele frequency for each row. If
          ``None``, AAF will be computed from `call`.
  
      Return
      ------
      :class:`.Table`
          Sex imputation statistics per sample.
  
      """
      if aaf_threshold < 0.0 or aaf_threshold > 1.0:
          raise FatalError(
              "Invalid argument for `aaf_threshold`. Must be in range [0, 1]."
          )
  
      mt = call._indices.source
      mt, _ = mt._process_joins(call)
      mt = mt.annotate_entries(call=call)
      mt = require_biallelic(mt, "impute_sex")
      if aaf is None:
          mt = mt.annotate_rows(
              aaf=agg.call_stats(mt.call, mt.alleles).AF[1]
          )
          aaf = "aaf"
  
      rg = mt.locus.dtype.reference_genome
      mt = hl.filter_intervals(
          mt,
          hl.map(
              lambda x_contig: hl.parse_locus_interval(x_contig, rg),
              rg.x_contigs,
          ),
          keep=True,
      )
      if not include_par:
          interval_type = hl.tarray(hl.tinterval(hl.tlocus(rg)))
          mt = hl.filter_intervals(
              mt, hl.literal(rg.par, interval_type), keep=False
          )
  
      mt = mt.filter_rows(
          (mt[aaf] > aaf_threshold) & (mt[aaf] < (1 - aaf_threshold))
      )
      mt = mt.annotate_cols(ib=agg.inbreeding(mt.call, mt[aaf]))
      kt = mt.select_cols(
          is_female=hl.if_else(
              mt.ib.f_stat < female_threshold,
              True,
              hl.if_else(
                  mt.ib.f_stat > male_threshold,
                  False,
                  hl.missing(tbool),
              ),
          ),
          **mt.ib,
      ).cols()
  
      return kt
  
imports: import builtins
  import itertools
  import math
  from typing import Dict, Callable, Optional, Union, Tuple, List
  import hail
  import hail
  import hail.expr.aggregators
  from hail import ir
  from hail.expr import Expression, ExpressionException, expr_float64, expr_call, expr_any, expr_numeric, expr_locus, analyze, raise_unless_entry_indexed, raise_unless_row_indexed, matrix_table_source, table_source, raise_unless_column_indexed
  from hail.expr.types import tbool, tarray, tfloat64, tint32
  from hail.genetics.reference_genome import reference_genome_type
  from hail.linalg import BlockMatrix
  from hail.matrixtable import MatrixTable
  from hail.methods.misc import require_biallelic, require_row_key_variant
  from hail.stats import LinearMixedModel
  from hail.table import Table
  from hail.typecheck import typecheck, nullable, numeric, oneof, sized_tupleof, sequenceof, enumeration, anytype
  from hail.utils import wrap_to_list, new_temp_file, FatalError
  from hail.utils.java import Env, info, warning
  from .None import pca
  from .None import relatedness
  from ..backend.spark_backend import SparkBackend
label_desc: Use image node_id 1 for calling a global function with example usage: impute_sex(call, aaf_threshold, include_par, female_threshold, male_threshold, aaf) and returns: kt