# Path: mitty/lib/bamfetch.py
# def fetch(bam_fp, reference):
#   return chain(*[bam_fp.fetch(reference=reference)] +
#                 ([bam_fp.fetch(until_eof=True)] if reference == bam_fp.references[-1] else []))
# 
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
# 
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
#                 color='k', linestyle='-', label='',
#                 yscale='linear', yticks=None, ylim=None, show_ax_label=False,
#                 ci=0.05):
#   """Interpret y (an array of length 2 * N + 3) as follows:
#     The indexes represent variant sizes from
# 
#     DEL len > N
#     DEL len from N to 1
#     SNPs
#     INS len from 1 to N
#     INS len > N
# 
#   :param ax:
#   :param y: success rate
#   :param cnt: number of counts in bin
#   :param color:
#   :param linestyle:
#   :param label:
#   :param yscale:
#   :param yticks:
#   :param ylim:
#   :param show_ax_label:
#   :return:
#   """
#   parts = bin_data_by_variant_size(num, den, bin_size)
#   x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
#   x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
#   xticks, xticklabels = [], []
#   for part in parts:
#     line_with_ci(ax, part, color=color, linestyle=linestyle)
#     xticks += part['xticks']
#     xticklabels += part['xticklabels']
# 
#   # The fixed reference lines
#   ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
#   ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
#   ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
# 
#   ax.set_xticks(xticks)
#   ax.set_xticklabels(xticklabels if show_ax_label else [])
# 
#   ax.set_yscale(yscale)
#   if yticks is not None:
#     ax.set_yticks(yticks)
#   if ylim is not None:
#     ax.set_ylim(ylim)
#   ax.get_yaxis().get_major_formatter().labelOnlyBase = False
#   ax.set_xlim(x_lim)
# 
#   return mpatches.Patch(color=color, linestyle=linestyle, label=label)  # patch_for_legend


from multiprocessing import Process, Queue
from matplotlib.colors import LogNorm
from mitty.lib.bamfetch import fetch
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
from mitty.benchmarking.plot.byvsize import plot_panels
import time
import logging
import matplotlib
import matplotlib.pyplot as plt
import pysam
import numpy as np

  :param ax:
  :param xmv_mat:
  :param plot_bin_size:
  :param show_ax_label:
  :return:
  """
  n0, d0 = alignment_accuracy_by_vsize(xmv_mat, 0)
  n50, d50 = alignment_accuracy_by_vsize(xmv_mat, 50)

  d0_p = plot_panels(ax,
                    num=n0,
                    den=d0,
                    bin_size=plot_bin_size,
                    yticks=[0.0, 0.5, 1.0], ylim=[-0.05, 1.05],
                    color='b', label=r'$d_{err} = 0$')
  d50_p = plot_panels(ax,
                    num=n50,
                    den=d50,
                    bin_size=plot_bin_size,
                    yticks=[0.0, 0.5, 1.0], ylim=[-0.05, 1.05],
                    color='r', label=r'$|d_{err}| \leq 50$')
  plt.legend(handles=[d0_p, d50_p], loc='lower center', fontsize=9)
  ax.set_ylabel('Fraction correctly aligned')


def plot_vcounts(ax, xmv_mat, plot_bin_size=5):
  v_cnt = xmv_mat.sum(axis=0).sum(axis=0)[1:]
  n_max = 10 ** np.ceil(np.log10(v_cnt.max() + 2))
  n_min = 10 ** int(np.log10(v_cnt.min() + 1))

# Path: mitty/lib/bamfetch.py
# def fetch(bam_fp, reference):
#   return chain(*[bam_fp.fetch(reference=reference)] +
#                 ([bam_fp.fetch(until_eof=True)] if reference == bam_fp.references[-1] else []))
# 
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
# 
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
#                 color='k', linestyle='-', label='',
#                 yscale='linear', yticks=None, ylim=None, show_ax_label=False,
#                 ci=0.05):
#   """Interpret y (an array of length 2 * N + 3) as follows:
#     The indexes represent variant sizes from
# 
#     DEL len > N
#     DEL len from N to 1
#     SNPs
#     INS len from 1 to N
#     INS len > N
# 
#   :param ax:
#   :param y: success rate
#   :param cnt: number of counts in bin
#   :param color:
#   :param linestyle:
#   :param label:
#   :param yscale:
#   :param yticks:
#   :param ylim:
#   :param show_ax_label:
#   :return:
#   """
#   parts = bin_data_by_variant_size(num, den, bin_size)
#   x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
#   x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
#   xticks, xticklabels = [], []
#   for part in parts:
#     line_with_ci(ax, part, color=color, linestyle=linestyle)
#     xticks += part['xticks']
#     xticklabels += part['xticklabels']
# 
#   # The fixed reference lines
#   ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
#   ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
#   ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
# 
#   ax.set_xticks(xticks)
#   ax.set_xticklabels(xticklabels if show_ax_label else [])
# 
#   ax.set_yscale(yscale)
#   if yticks is not None:
#     ax.set_yticks(yticks)
#   if ylim is not None:
#     ax.set_ylim(ylim)
#   ax.get_yaxis().get_major_formatter().labelOnlyBase = False
#   ax.set_xlim(x_lim)
# 
#   return mpatches.Patch(color=color, linestyle=linestyle, label=label)  # patch_for_legend


# Path: mitty/benchmarking/xmv.py
from multiprocessing import Process, Queue
from matplotlib.colors import LogNorm
from mitty.lib.bamfetch import fetch
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
from mitty.benchmarking.plot.byvsize import plot_panels
import time
import logging
import matplotlib
import matplotlib.pyplot as plt
import pysam
import numpy as np


  :param ax:
  :param xmv_mat:
  :param plot_bin_size:
  :param show_ax_label:
  :return:
  """
  n0, d0 = alignment_accuracy_by_vsize(xmv_mat, 0)
  n50, d50 = alignment_accuracy_by_vsize(xmv_mat, 50)

  d0_p = plot_panels(ax,
                    num=n0,
                    den=d0,
                    bin_size=plot_bin_size,
                    yticks=[0.0, 0.5, 1.0], ylim=[-0.05, 1.05],
                    color='b', label=r'$d_{err} = 0$')
  d50_p = plot_panels(ax,
                    num=n50,
                    den=d50,
                    bin_size=plot_bin_size,
                    yticks=[0.0, 0.5, 1.0], ylim=[-0.05, 1.05],
                    color='r', label=r'$|d_{err}| \leq 50$')
  plt.legend(handles=[d0_p, d50_p], loc='lower center', fontsize=9)
  ax.set_ylabel('Fraction correctly aligned')


def plot_vcounts(ax, xmv_mat, plot_bin_size=5):
  v_cnt = xmv_mat.sum(axis=0).sum(axis=0)[1:]
  n_max = 10 ** np.ceil(np.log10(v_cnt.max() + 2))
  n_min = 10 ** int(np.log10(v_cnt.min() + 1))

  tot_p = plot_panels(ax,