Runs step10 (check ethnicity).

    :param in_prefix: the prefix of the input files.
    :param in_type: the type of the input files.
    :param out_prefix: the output prefix.
    :param base_dir: the output directory.
    :param options: the options needed.

    :type in_prefix: str
    :type in_type: str
    :type out_prefix: str
    :type base_dir: str
    :type options: list

    :returns: a tuple containing the prefix of the output files (the input
              prefix for the next script) and the type of the output files
              (``bfile``).

    This function calls the :py:mod:`pyGenClean.Ethnicity.check_ethnicity`
    module. The required file type for this module is ``bfile``, hence the need
    to use the :py:func:`check_input_files` to check if the file input file
    type is the good one, or to create it if needed.

    .. note::
        The :py:mod:`pyGenClean.Ethnicity.check_ethnicity` module doesn't
        return usable output files. Hence, this function returns the input file
        prefix and its type.

def run_check_ethnicity(in_prefix, in_type, out_prefix, base_dir, options):
    """Runs step10 (check ethnicity).

    :param in_prefix: the prefix of the input files.
    :param in_type: the type of the input files.
    :param out_prefix: the output prefix.
    :param base_dir: the output directory.
    :param options: the options needed.

    :type in_prefix: str
    :type in_type: str
    :type out_prefix: str
    :type base_dir: str
    :type options: list

    :returns: a tuple containing the prefix of the output files (the input
              prefix for the next script) and the type of the output files
              (``bfile``).

    This function calls the :py:mod:`pyGenClean.Ethnicity.check_ethnicity`
    module. The required file type for this module is ``bfile``, hence the need
    to use the :py:func:`check_input_files` to check if the file input file
    type is the good one, or to create it if needed.

    .. note::
        The :py:mod:`pyGenClean.Ethnicity.check_ethnicity` module doesn't
        return usable output files. Hence, this function returns the input file
        prefix and its type.

    """
    # Creating the output directory
    os.mkdir(out_prefix)

    # We know we need bfile
    required_type = "bfile"
    check_input_files(in_prefix, in_type, required_type)

    # We need to inject the name of the input file and the name of the output
    # prefix
    script_prefix = os.path.join(out_prefix, "ethnicity")
    options += ["--{}".format(required_type), in_prefix,
                "--out", script_prefix]

    # We run the script
    try:
        check_ethnicity.main(options)
    except check_ethnicity.ProgramError as e:
        msg = "check_ethnicity: {}".format(e)
        raise ProgramError(msg)

    # Getting the multiplier value
    multiplier = check_ethnicity.parser.get_default("multiplier")
    if "--multiplier" in options:
        multiplier = options[options.index("--multiplier") + 1]

    # Getting the population of which the outliers were computed from
    outliers_of = check_ethnicity.parser.get_default("outliers_of")
    if "--outliers-of" in options:
        outliers_of = options[options.index("--outliers-of") + 1]

    # Was the reference populations required?
    skip_ref_pops = "--skip-ref-pops" in options

    # Computing the number of outliers
    outliers = None
    if not skip_ref_pops:
        with open(script_prefix + ".outliers", "r") as i_file:
            outliers = {
                tuple(line.rstrip("\r\n").split("\t")) for line in i_file
            }

    # Computing the number of markers used
    nb_markers_mds = 0
    with open(script_prefix + ".ibs.pruned_data.bim", "r") as i_file:
        for line in i_file:
            nb_markers_mds += 1

    # We write a LaTeX summary
    latex_file = os.path.join(script_prefix + ".summary.tex")
    graphics_paths = set()
    try:
        # TODO: IF THIS CHANGE, code in find_outliers needs to change to...
        with open(latex_file, "w") as o_file:
            print >>o_file, latex_template.subsection(
                check_ethnicity.pretty_name,
            )
            text = None
            if skip_ref_pops:
                text = (
                    "Principal components analysis was performed using {:,d} "
                    "marker{} on the study dataset only.".format(
                        nb_markers_mds,
                        "s" if nb_markers_mds > 1 else "",
                    )
                )

            else:
                text = (
                    "Using {:,d} marker{} and a multiplier of {}, there was a "
                    "total of {:,d} outlier{} of the {} population.".format(
                        nb_markers_mds,
                        "s" if nb_markers_mds > 1 else "",
                        multiplier,
                        len(outliers),
                        "s" if len(outliers) > 1 else "",
                        outliers_of,
                    )
                )
            print >>o_file, latex_template.wrap_lines(text)

            # Adding the figure if it exists
            fig = script_prefix + ".outliers.png"
            if os.path.isfile(fig):
                # Getting the paths
                graphics_path, path = os.path.split(fig)
                graphics_path = os.path.relpath(graphics_path, base_dir)

                # Getting the required template
                float_template = latex_template.jinja2_env.get_template(
                    "float_template.tex",
                )
                graphic_template = latex_template.jinja2_env.get_template(
                    "graphics_template.tex",
                )

                # The label
                label = re.sub(r"[/\\]", "_", script_prefix) + "_outliers"

                text = (
                    r"Figure~\ref{" + label + "} shows the first two "
                    "principal components of the MDS analysis, where outliers "
                    "of the " + outliers_of + " population are shown in grey."
                )
                print >>o_file, latex_template.wrap_lines(text)

                # Printing
                caption = (
                    "MDS plots showing the first two principal components of "
                    "the source dataset with the reference panels. The "
                    "outliers of the {} population are shown in grey, while "
                    "samples of the source dataset that resemble the {} "
                    "population are shown in orange. A multiplier of {} was "
                    "used to find the {:,d} outlier{}.".format(
                        outliers_of,
                        outliers_of,
                        multiplier,
                        len(outliers),
                        "s" if len(outliers) > 1 else "",
                    )
                )
                print >>o_file, float_template.render(
                    float_type="figure",
                    float_placement="H",
                    float_caption=latex_template.wrap_lines(caption),
                    float_label=label,
                    float_content=graphic_template.render(
                        width=r"0.8\textwidth",
                        path=latex_template.sanitize_fig_name(path),
                    ),
                )
                # Adding the path where the graphic is
                graphics_paths.add(graphics_path)

            # Adding the screeplot if it exists
            fig = script_prefix + ".smartpca.scree_plot.png"
            if os.path.isfile(fig):
                # Getting the paths
                graphics_path, path = os.path.split(fig)
                graphics_path = os.path.relpath(graphics_path, base_dir)

                # Getting the required template
                float_template = latex_template.jinja2_env.get_template(
                    "float_template.tex",
                )
                graphic_template = latex_template.jinja2_env.get_template(
                    "graphics_template.tex",
                )

                # The label
                label = re.sub(r"[/\\]", "_", script_prefix) + "_screeplot"

                text = (
                    r"Figure~\ref{" + label + "} shows the scree plot for the "
                    "principal components of the MDS analysis."
                )
                print >>o_file, latex_template.wrap_lines(text)

                # Printing
                caption = (
                    "Scree plot for the principal components of the MDS "
                    "analysis."
                )
                print >>o_file, float_template.render(
                    float_type="figure",
                    float_placement="H",
                    float_caption=caption,
                    float_label=label,
                    float_content=graphic_template.render(
                        height=r"0.95\textheight",
                        path=latex_template.sanitize_fig_name(path),
                    ),
                )
                # Adding the path where the graphic is
                graphics_paths.add(graphics_path)

    except IOError:
        msg = "{}: cannot write LaTeX summary".format(latex_file)
        raise ProgramError(msg)

    # Writing the summary results
    with open(os.path.join(base_dir, "results_summary.txt"), "a") as o_file:
        print >>o_file, "# {}".format(script_prefix)
        print >>o_file, ("Number of markers used for MDS analysis\t"
                         "{:,d}".format(nb_markers_mds))
        if not skip_ref_pops:
            print >>o_file, ("Number of {} outliers\t"
                             "{:,d}".format(outliers_of, len(outliers)))
        print >>o_file, "---"

    # We know this step doesn't produce an new data set, so we return the old
    # prefix and the old in_type
    return _StepResult(
        next_file=in_prefix,
        next_file_type=required_type,
        latex_summary=latex_file,
        description=check_ethnicity.desc,
        long_description=check_ethnicity.long_desc,
        graph_path=graphics_paths,
    )