code: def import_gen(
      path,
      sample_file=None,
      tolerance=0.2,
      min_partitions=None,
      chromosome=None,
      reference_genome="default",
      contig_recoding=None,
      skip_invalid_loci=False,
  ) -> MatrixTable:
      """
      Import GEN file(s) as a :class:`.MatrixTable`.
  
      Examples
      --------
  
      >>> ds = hl.import_gen('data/example.gen',
      ...                    sample_file='data/example.sample',
      ...                    reference_genome='GRCh37')
  
      Notes
      -----
  
      For more information on the GEN file format, see `here
      <http://www.stats.ox.ac.uk/%7Emarchini/software/gwas/file_format.html#mozTocId40300>`__.
  
      If the GEN file has only 5 columns before the start of the genotype
      probability data (chromosome field is missing), you must specify the
      chromosome using the `chromosome` parameter.
  
      To load multiple files at the same time, use :ref:`Hadoop Glob Patterns
      <sec-hadoop-glob>`.
  
      **Column Fields**
  
      - `s` (:py:data:`.tstr`) -- Column key. This is the sample ID imported
        from the first column of the sample file.
  
      **Row Fields**
  
      - `locus` (:class:`.tlocus` or :class:`.tstruct`) -- Row key. The genomic
        location consisting of the chromosome (1st column if present, otherwise
        given by `chromosome`) and position (4th column if `chromosome` is not
        defined). If `reference_genome` is defined, the type will be
        :class:`.tlocus` parameterized by `reference_genome`. Otherwise, the type
        will be a :class:`.tstruct` with two fields: `contig` with type
        :py:data:`.tstr` and `position` with type :py:data:`.tint32`.
      - `alleles` (:class:`.tarray` of :py:data:`.tstr`) -- Row key. An array
        containing the alleles of the variant. The reference allele (4th column if
        `chromosome` is not defined) is the first element of the array and the
        alternate allele (5th column if `chromosome` is not defined) is the second
        element.
      - `varid` (:py:data:`.tstr`) -- The variant identifier. 2nd column of GEN
        file if chromosome present, otherwise 1st column.
      - `rsid` (:py:data:`.tstr`) -- The rsID. 3rd column of GEN file if
        chromosome present, otherwise 2nd column.
  
      **Entry Fields**
  
      - `GT` (:py:data:`.tcall`) -- The hard call corresponding to the genotype with
        the highest probability.
      - `GP` (:class:`.tarray` of :py:data:`.tfloat64`) -- Genotype probabilities
        as defined by the GEN file spec. The array is set to missing if the
        sum of the probabilities is a distance greater than the `tolerance`
        parameter from 1.0. Otherwise, the probabilities are normalized to sum to
        1.0. For example, the input ``[0.98, 0.0, 0.0]`` will be normalized to
        ``[1.0, 0.0, 0.0]``.
  
      Parameters
      ----------
      path : :class:`str` or :obj:`list` of :obj:`str`
          GEN files to import.
      sample_file : :class:`str`
          Sample file to import.
      tolerance : :obj:`float`
          If the sum of the genotype probabilities for a genotype differ from 1.0
          by more than the tolerance, set the genotype to missing.
      min_partitions : :obj:`int`, optional
          Number of partitions.
      chromosome : :class:`str`, optional
          Chromosome if not included in the GEN file
      reference_genome : :class:`str` or :class:`.ReferenceGenome`, optional
          Reference genome to use.
      contig_recoding : :obj:`dict` of :class:`str` to :obj:`str`, optional
          Dict of old contig name to new contig name. The new contig name must be
          in the reference genome given by `reference_genome`.
      skip_invalid_loci : :obj:`bool`
          If ``True``, skip loci that are not consistent with `reference_genome`.
  
      Returns
      -------
      :class:`.MatrixTable`
      """
      gen_table = import_lines(path, min_partitions)
      sample_table = import_lines(sample_file)
      rg = reference_genome.name if reference_genome else None
      contig_recoding = contig_recoding
      if contig_recoding is None:
          contig_recoding = hl.empty_dict(hl.tstr, hl.tstr)
      else:
          contig_recoding = hl.dict(contig_recoding)
  
      gen_table = gen_table.transmute(data=gen_table.text.split(" "))
  
      if chromosome is None:
          last_rowf_idx = 5
          contig_holder = gen_table.data[0]
      else:
          last_rowf_idx = 4
          contig_holder = chromosome
  
      contig_holder = contig_recoding.get(contig_holder, contig_holder)
  
      position = hl.int(gen_table.data[last_rowf_idx - 2])
      alleles = hl.array(
          [
              hl.str(gen_table.data[last_rowf_idx - 1]),
              hl.str(gen_table.data[last_rowf_idx]),
          ]
      )
      rsid = gen_table.data[last_rowf_idx - 3]
      varid = gen_table.data[last_rowf_idx - 4]
      if rg is None:
          locus = hl.struct(contig=contig_holder, position=position)
      else:
          if skip_invalid_loci:
              locus = hl.if_else(
                  hl.is_valid_locus(contig_holder, position, rg),
                  hl.locus(contig_holder, position, rg),
                  hl.missing(hl.tlocus(rg)),
              )
          else:
              locus = hl.locus(contig_holder, position, rg)
  
      gen_table = gen_table.annotate(
          locus=locus, alleles=alleles, rsid=rsid, varid=varid
      )
      gen_table = gen_table.annotate(
          entries=gen_table.data[last_rowf_idx + 1 :]
          .map(lambda x: hl.float64(x))
          .grouped(3)
          .map(lambda x: hl.struct(GP=x))
      )
      if skip_invalid_loci:
          gen_table = gen_table.filter(hl.is_defined(gen_table.locus))
  
      sample_table_count = (
          sample_table.count() - 2
      )  # Skipping first 2 unneeded rows in sample file
      gen_table = gen_table.annotate_globals(
          cols=hl.range(sample_table_count).map(
              lambda x: hl.struct(col_idx=x)
          )
      )
      mt = gen_table._unlocalize_entries("entries", "cols", ["col_idx"])
  
      sample_table = sample_table.tail(sample_table_count).add_index()
      sample_table = sample_table.annotate(
          s=sample_table.text.split(" ")[0]
      )
      sample_table = sample_table.key_by(sample_table.idx)
      mt = mt.annotate_cols(s=sample_table[hl.int64(mt.col_idx)].s)
  
      mt = mt.annotate_entries(
          GP=hl.rbind(
              hl.sum(mt.GP),
              lambda gp_sum: hl.if_else(
                  hl.abs(1.0 - gp_sum) > tolerance,
                  hl.missing(hl.tarray(hl.tfloat64)),
                  hl.abs((1 / gp_sum) * mt.GP),
              ),
          )
      )
      mt = mt.annotate_entries(
          GT=hl.rbind(
              hl.argmax(mt.GP),
              lambda max_idx: hl.if_else(
                  hl.len(mt.GP.filter(lambda y: y == mt.GP[max_idx]))
                  == 1,
                  hl.switch(max_idx)
                  .when(0, hl.call(0, 0))
                  .when(1, hl.call(0, 1))
                  .when(2, hl.call(1, 1))
                  .or_error("error creating gt field."),
                  hl.missing(hl.tcall),
              ),
          )
      )
      mt = mt.filter_entries(hl.is_defined(mt.GP))
  
      mt = mt.key_cols_by("s").drop("col_idx", "file", "data")
      mt = mt.key_rows_by("locus", "alleles").select_entries("GT", "GP")
      return mt
  
imports: import os
  import re
  from collections import defaultdict
  import avro.schema
  from avro.datafile import DataFileReader
  from avro.io import DatumReader
  import hail
  from hail import ir
  from hail.expr import StructExpression, LocusExpression, expr_array, expr_float64, expr_str, expr_numeric, expr_call, expr_bool, expr_int32, to_expr, analyze
  from hail.expr.types import hail_type, tarray, tfloat64, tstr, tint32, tstruct, tcall, tbool, tint64, tfloat32
  from hail.genetics.reference_genome import reference_genome_type
  from hail.ir.utils import parse_type
  from hail.matrixtable import MatrixTable
  from hail.methods.misc import require_biallelic, require_row_key_variant, require_col_key_str
  from hail.table import Table
  from hail.typecheck import typecheck, nullable, oneof, dictof, anytype, sequenceof, enumeration, sized_tupleof, numeric, table_key_type, char
  from hail.utils import new_temp_file
  from hail.utils.deduplicate import deduplicate
  from hail.utils.java import Env, FatalError, jindexed_seq_args, warning
  from hail.utils.java import info
  from hail.utils.misc import wrap_to_list, plural
  from .import_lines_helpers import split_lines, should_remove_line
label_desc: Use image node_id 12 for calling a global function with example usage: import_gen(path, sample_file, tolerance, min_partitions, chromosome, reference_genome, contig_recoding, skip_invalid_loci) and returns: mt