Plot BAF and LRR for a list of files.

    :param file_names: contains the name of the input file for each sample.
    :param options: the options.

    :type file_names: dict
    :type options: argparse.Namespace

    Plots the BAF (B Allele Frequency) and LRR (Log R Ratio) of each samples.
    Only the sexual chromosome are shown.

def plot_baf_lrr(file_names, options):
    """Plot BAF and LRR for a list of files.

    :param file_names: contains the name of the input file for each sample.
    :param options: the options.

    :type file_names: dict
    :type options: argparse.Namespace

    Plots the BAF (B Allele Frequency) and LRR (Log R Ratio) of each samples.
    Only the sexual chromosome are shown.

    """
    # importing important stuff
    import matplotlib as mpl
    if options.format != "X11" and mpl.get_backend() != "agg":
        mpl.use("Agg")
    import matplotlib.pyplot as plt
    if options.format != "X11":
        plt.ioff()

    # For each of the sample/files
    for sample, file_name in file_names.iteritems():
        data = []

        # Reading the file
        open_func = open
        if file_name.endswith(".gz"):
            open_func = gzip.open
        with open_func(file_name, 'rb') as input_file:
            header_index = dict([
                (col_name, i)
                for i, col_name in
                enumerate(input_file.readline().rstrip("\r\n").split("\t"))
            ])
            for col_name in {"Chr", "Position", "B Allele Freq",
                             "Log R Ratio"}:
                if col_name not in header_index:
                    msg = "{}: no column named {}".format(file_name, col_name)
                    raise ProgramError(msg)

            # Reading the dat
            for line in input_file:
                row = line.rstrip("\r\n").split("\t")

                # We only need X and Y chromosomes
                chromosome = encode_chromosome(row[header_index["Chr"]])
                if chromosome not in {"X", "Y"}:
                    continue

                # The position
                position = row[header_index["Position"]]
                try:
                    position = int(position)
                except ValueError:
                    msg = "{}: impossible position {}".format(file_name,
                                                              position)
                    raise ProgramError(msg)

                # The BAF
                baf = row[header_index["B Allele Freq"]]
                try:
                    baf = float(baf)
                except ValueError:
                    msg = "{}: impossible baf {}".format(file_name, baf)
                    raise ProgramError(msg)

                # The LRR
                lrr = row[header_index["Log R Ratio"]]
                try:
                    lrr = float(lrr)
                except ValueError:
                    msg = "{}: impossible lrr {}".format(file_name, lrr)
                    raise ProgramError(msg)

                # Saving the data
                data.append((chromosome, position, lrr, baf))

        # Creating the numpy array
        data = np.array(data, dtype=[("chr", "a1"), ("pos", int),
                                     ("lrr", float), ("baf", float)])

        # Creating the figure and axes
        fig, axes = plt.subplots(2, 2, figsize=(20, 8))
        plt.subplots_adjust(left=0.05, right=0.97, wspace=0.15, hspace=0.3)
        fig.suptitle(sample, fontsize=16, weight="bold")

        # Setting subplot properties
        for ax in axes.flatten():
            ax.xaxis.set_ticks_position("bottom")
            ax.yaxis.set_ticks_position("left")
            ax.spines["top"].set_visible(False)
            ax.spines["right"].set_visible(False)
            ax.spines["bottom"].set_position(("outward", 9))
            ax.spines["left"].set_position(("outward", 9))

        # Separating the axes
        x_lrr_ax, x_baf_ax, y_lrr_ax, y_baf_ax = axes.flatten(order='F')

        # Printing the X chromosome
        curr_chr = data["chr"] == "X"
        x_lrr_ax.plot(data["pos"][curr_chr]/1000000.0, data["lrr"][curr_chr],
                      "o", ms=1, mec="#0099CC",
                      mfc="#0099CC")[0].set_clip_on(False)
        x_baf_ax.plot(data["pos"][curr_chr]/1000000.0, data["baf"][curr_chr],
                      "o", ms=1, mec="#669900",
                      mfc="#669900")[0].set_clip_on(False)
        x_lrr_ax.axhline(y=0, color="#000000", ls="--", lw=1.2)
        x_baf_ax.axhline(y=0.5, color="#000000", ls="--", lw=1.2)
        x_lrr_ax.set_ylabel("LRR", weight="bold")
        x_baf_ax.set_ylabel("BAF", weight="bold")
        x_baf_ax.set_xlabel("Position (Mb)", weight="bold")
        x_lrr_ax.set_title("Chromosome X", weight="bold")

        # Printing the X chromosome
        curr_chr = data["chr"] == "Y"
        y_lrr_ax.plot(data["pos"][curr_chr]/1000000.0, data["lrr"][curr_chr],
                      "o", ms=1, mec="#0099CC",
                      mfc="#0099CC")[0].set_clip_on(False)
        y_baf_ax.plot(data["pos"][curr_chr]/1000000.0, data["baf"][curr_chr],
                      "o", ms=1, mec="#669900",
                      mfc="#669900")[0].set_clip_on(False)
        y_lrr_ax.axhline(y=0, color="#000000", ls="--", lw=1.2)
        y_baf_ax.axhline(y=0.5, color="#000000", ls="--", lw=1.2)
        y_lrr_ax.set_ylabel("LRR", weight="bold")
        y_baf_ax.set_ylabel("BAF", weight="bold")
        y_baf_ax.set_xlabel("Position (Mb)", weight="bold")
        y_lrr_ax.set_title("Chromosome Y", weight="bold")

        # Saving the figure
        if options.format == "X11":
            plt.show()
        else:
            plt.savefig(
                "{}_{}_lrr_baf.{}".format(options.out, sample, options.format),
                dpi=options.dpi,
            )

        # Closing the figure
        plt.close(fig)