def prepare_no_blood(name_scene='F(1)', id_exbl=24, index=0):
    """
    performs the experiment from discussion: 
    number of blood pixels
    data for Fig.10
    parameters:
        name_scene: name of the output image
        id_exbl: id of the reference spectrum
        index: iteration of the experiment
    """
    data_scene, anno_scene = load_ds(name_scene)

    blood_exbl = load_exbl(id_exbl)

    X_bg = data_scene[anno_scene != 1]
    X_blood_raw = data_scene[anno_scene == 1]

    N_blood = len(X_blood_raw)

    ratio_V = RATIOS_V
    ratio_N = RATIOS_N

    res = np.zeros((len(ratio_V), len(ratio_N)))

    indices = np.arange(len(X_blood_raw))
    np.random.shuffle(indices)

    iii = 0
    for i_v, ratio_vectors in enumerate(ratio_V):
        for i_n, t_N in enumerate(ratio_N):
            iii += 1
            print(iii, ratio_vectors, t_N)
            no_vectors = int(ratio_vectors * N_blood)
            N = int(t_N * no_vectors) if t_N <= 1 else int(t_N)

            X_blood = X_blood_raw[indices]
            X_blood = X_blood[:no_vectors]

            X = np.vstack((X_bg, X_blood))
            y = np.concatenate(
                (np.zeros(len(X_bg),
                          dtype=np.int32), np.ones(len(X_blood),
                                                   dtype=np.int32)))
            blood = blood_exbl

            mf = TwoStageMatchedFilter()
            mf.fit(blood, X, N=N, N_supression=0)
            pred_2 = mf.predict(X, stage='second')
            vauc2, _, _ = comp_pr(pred_2, y)
            res[i_v, i_n] = vauc2
    np.savez_compressed('res/exp_no_blood_{}_{}'.format(name_scene, index),
                        res=res)
def show_table_row(name_frame, name_scene, code, N=1000, N_supression=0):
    """
    plots rows of the result table (in LaTeX), Tab.3
    parameters:
        name_frame: name of the source image (inductive scenario)
        name_scene: name of the output image
        code: code for results file name
        N: no. vectors in the 2nd stage as int or percentage string e.g. '33p'
        N_supression: no. supressed vectors (extension of the algorithm, unused)
    """
    str = ""
    str += "{}&".format(code)
    for i_f, f in enumerate(['scene', 'frame', 'exbl']):
        fname = "res/{}_{}_{}_{}_{}.npz".format(name_frame, name_scene, N,
                                                N_supression, f)
        res = np.load(fname)
        vauc, _, _ = comp_pr(res['pred_1'], res['anno'])
        str += "{:0.2f}&".format(vauc)
        if f == "exbl":
            vauc, _, _ = comp_pr(res['pred_2'], res['anno'])
            str += "{:0.2f}\\NN".format(vauc)
    print(str)
def show_sensitivity_analysis(N_supression=0, is_pr=True, show=True):
    """
    Graph of the impact of parameter N (no. vectors) , Fig.11
    parameters:
        N_supression: no. supressed vectors (extension of the algorithm, unused)
        is_pr: use PR (True) or ROC (FALSE) AUC
        show: True for plot.plot(), False for imsave    
    """
    images_n = [IMAGES[i] for i in [11, 4, 7, 8]]
    markers = ['s', 'v', '<', '>', '1', '.', 'p']
    plt.rcParams.update({'font.size': 14})
    val_N = [
        100, 250, 500, 750, 1000, 1250, 1500, 1750, 2000, 3000, 4000, 5000
    ]
    for i_im, im in enumerate(images_n):
        nn = []
        for N in val_N:
            name_frame = im['name_frame']
            name_scene = im['name_scene']
            fname = "res/{}_{}_{}_{}_{}.npz".format(name_frame, name_scene, N,
                                                    N_supression, "exbl")
            res = np.load(fname)
            pred = res['pred_2']
            if is_pr:
                vauc, _, _ = comp_pr(pred, res['anno'])
                nn.append(vauc)
            else:
                vauc, _, _ = comp_roc(pred, res['anno'])
                nn.append(vauc)
        plt.plot(val_N,
                 nn,
                 label=im['code'],
                 marker=markers[i_im],
                 markevery=2)
    if is_pr:
        plt.ylabel('AUC(PR)')
    else:
        plt.ylabel('AUC(ROC)')

    plt.xlabel('N')
    plt.legend()
    plt.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig('res/san_{}_{}.pdf'.format(N, "pr" if is_pr else "roc"),
                    bbox_inches='tight',
                    pad_inches=0)
    plt.close()
def compare_in_columns(Ns=[750, 1000, '10p', '20p']):
    """
    plots rows of the result table (in LaTeX), Tab.4
    compare results for different values of N
    parameters:
    Ns: list values of N to plot for    
    """
    for im in IMAGES:
        ss = "{}".format(im['code'].replace("_", "\_"))
        for N in Ns:
            fname = "res/{}_{}_{}_{}_{}.npz".format(im['name_frame'],
                                                    im['name_scene'], N, 0,
                                                    'exbl')
            res = np.load(fname)
            vauc, _, _ = comp_pr(res['pred_2'], res['anno'])
            ss += "&{:0.2f}".format(vauc)
        ss += '\\NN'
        print(ss)
def show_stats(name_frame='F(1)',
               name_scene='E(1)',
               code='E(1)',
               N=1000,
               N_supression=0,
               is_pr=True,
               show=True):
    """
    plots pr and roc curves for a given detection Fig.6-8
    parameters:
        name_frame: name of the source image (inductive scenario)
        name_scene: name of the output image
        code: code for results file name
        N: no. vectors in the 2nd stage as int or percentage string e.g. '33p'
        N_supression: no. supressed vectors (extension of the algorithm, unused)
        is_pr: use PR (True) or ROC (FALSE) AUC
        show: True for plot.plot(), False for imsave    
    
    """
    plt.rcParams.update({'font.size': 14})
    markers = ['s', 'v', '<', '>', '1', '.', 'p']
    labels = ['Ideal MF', 'Inductive MF', 'Algorithm 1']
    for i_f, f in enumerate(['scene', 'frame', 'exbl']):
        fname = "res/{}_{}_{}_{}_{}.npz".format(name_frame, name_scene, N,
                                                N_supression, f)
        print(fname)
        res = np.load(fname)
        pred = res['pred_2'] if f in ['exbl'] else res['pred_1']

        if is_pr:
            vauc, precision, recall = comp_pr(pred, res['anno'])
            plt.plot(recall,
                     precision,
                     label="{} AUC:{:0.2f}".format(labels[i_f], vauc),
                     alpha=0.7,
                     marker=markers[i_f],
                     markevery=0.3,
                     lw=2)
        else:
            vauc, fpr, tpr = comp_roc(pred, res['anno'])
            plt.plot(fpr,
                     tpr,
                     label="{} AUC:{:0.2f}".format(labels[i_f], vauc),
                     alpha=0.7,
                     marker=markers[i_f],
                     markevery=0.3,
                     lw=2)

    if is_pr:
        plt.ylabel('Precision')
        plt.xlabel('Recall')
    else:
        plt.ylabel('TPR')
        plt.xlabel('FPR')
        plt.plot([0, 1], [0, 1], color='navy', lw=1, linestyle='--', alpha=0.1)

    plt.legend()
    plt.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig('res/res_{}_{}_{}.pdf'.format(code, N,
                                                  'pr' if is_pr else 'roc'),
                    bbox_inches='tight',
                    pad_inches=0)
    plt.close()