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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
"""
This script evaluates the contribution of a technique from the ablation study for
improving the masker evaluation metrics. The differences in the metrics are computed
for all images of paired models, that is those which only differ in the inclusion or
not of the given technique. Then, statistical inference is performed through the
percentile bootstrap to obtain robust estimates of the differences in the metrics and
confidence intervals. The script plots the distribution of the bootrstraped estimates.
"""
print("Imports...", end="")
from argparse import ArgumentParser
import yaml
import os
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.stats import trim_mean
from tqdm import tqdm
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches


# -----------------------
# -----  Constants  -----
# -----------------------

dict_metrics = {
    "names": {
        "tpr": "TPR, Recall, Sensitivity",
        "tnr": "TNR, Specificity, Selectivity",
        "fpr": "FPR",
        "fpt": "False positives relative to image size",
        "fnr": "FNR, Miss rate",
        "fnt": "False negatives relative to image size",
        "mpr": "May positive rate (MPR)",
        "mnr": "May negative rate (MNR)",
        "accuracy": "Accuracy (ignoring may)",
        "error": "Error",
        "f05": "F05 score",
        "precision": "Precision",
        "edge_coherence": "Edge coherence",
        "accuracy_must_may": "Accuracy (ignoring cannot)",
    },
    "key_metrics": ["f05", "error", "edge_coherence"],
}
dict_techniques = {
    "depth": "depth",
    "segmentation": "seg",
    "seg": "seg",
    "dada_s": "dada_seg",
    "dada_seg": "dada_seg",
    "dada_segmentation": "dada_seg",
    "dada_m": "dada_masker",
    "dada_masker": "dada_masker",
    "spade": "spade",
    "pseudo": "pseudo",
    "pseudo-labels": "pseudo",
    "pseudo_labels": "pseudo",
}

# Model features
model_feats = [
    "masker",
    "seg",
    "depth",
    "dada_seg",
    "dada_masker",
    "spade",
    "pseudo",
    "ground",
    "instagan",
]

# Colors
palette_colorblind = sns.color_palette("colorblind")
color_cat1 = palette_colorblind[0]
color_cat2 = palette_colorblind[1]
palette_lightest = [
    sns.light_palette(color_cat1, n_colors=20)[3],
    sns.light_palette(color_cat2, n_colors=20)[3],
]
palette_light = [
    sns.light_palette(color_cat1, n_colors=3)[1],
    sns.light_palette(color_cat2, n_colors=3)[1],
]
palette_medium = [color_cat1, color_cat2]
palette_dark = [
    sns.dark_palette(color_cat1, n_colors=3)[1],
    sns.dark_palette(color_cat2, n_colors=3)[1],
]
palette_cat1 = [
    palette_lightest[0],
    palette_light[0],
    palette_medium[0],
    palette_dark[0],
]
palette_cat2 = [
    palette_lightest[1],
    palette_light[1],
    palette_medium[1],
    palette_dark[1],
]
color_cat1_light = palette_light[0]
color_cat2_light = palette_light[1]


def parsed_args():
    """
    Parse and returns command-line args

    Returns:
        argparse.Namespace: the parsed arguments
    """
    parser = ArgumentParser()
    parser.add_argument(
        "--input_csv",
        default="ablations_metrics_20210311.csv",
        type=str,
        help="CSV containing the results of the ablation study",
    )
    parser.add_argument(
        "--output_dir",
        default=None,
        type=str,
        help="Output directory",
    )
    parser.add_argument(
        "--technique",
        default=None,
        type=str,
        help="Keyword specifying the technique. One of: pseudo, depth, segmentation, dada_seg, dada_masker, spade",
    )
    parser.add_argument(
        "--dpi",
        default=200,
        type=int,
        help="DPI for the output images",
    )
    parser.add_argument(
        "--n_bs",
        default=1e6,
        type=int,
        help="Number of bootrstrap samples",
    )
    parser.add_argument(
        "--alpha",
        default=0.99,
        type=float,
        help="Confidence level",
    )
    parser.add_argument(
        "--bs_seed",
        default=17,
        type=int,
        help="Bootstrap random seed, for reproducibility",
    )

    return parser.parse_args()


def add_ci_mean(
    ax, sample_measure, bs_mean, bs_std, ci, color, alpha, fontsize, invert=False
):

    # Fill area between CI
    dist = ax.lines[0]
    dist_y = dist.get_ydata()
    dist_x = dist.get_xdata()
    linewidth = dist.get_linewidth()

    x_idx_low = np.argmin(np.abs(dist_x - ci[0]))
    x_idx_high = np.argmin(np.abs(dist_x - ci[1]))
    x_ci = dist_x[x_idx_low:x_idx_high]
    y_ci = dist_y[x_idx_low:x_idx_high]

    ax.fill_between(x_ci, 0, y_ci, facecolor=color, alpha=alpha)

    # Add vertical lines of CI
    ax.vlines(
        x=ci[0],
        ymin=0.0,
        ymax=y_ci[0],
        color=color,
        linewidth=linewidth,
        label="ci_low",
    )
    ax.vlines(
        x=ci[1],
        ymin=0.0,
        ymax=y_ci[-1],
        color=color,
        linewidth=linewidth,
        label="ci_high",
    )

    # Add annotations
    bbox_props = dict(boxstyle="round, pad=0.4", fc="w", ec="k", lw=2)

    if invert:
        ha_l = "right"
        ha_u = "left"
    else:
        ha_l = "left"
        ha_u = "right"
    ax.text(
        ci[0],
        0.0,
        s="L = {:.4f}".format(ci[0]),
        ha=ha_l,
        va="bottom",
        fontsize=fontsize,
        bbox=bbox_props,
    )
    ax.text(
        ci[1],
        0.0,
        s="U = {:.4f}".format(ci[1]),
        ha=ha_u,
        va="bottom",
        fontsize=fontsize,
        bbox=bbox_props,
    )

    # Add vertical line of bootstrap mean
    x_idx_mean = np.argmin(np.abs(dist_x - bs_mean))
    ax.vlines(
        x=bs_mean, ymin=0.0, ymax=dist_y[x_idx_mean], color="k", linewidth=linewidth
    )

    # Add annotation of bootstrap mean
    bbox_props = dict(boxstyle="round, pad=0.4", fc="w", ec="k", lw=2)

    ax.text(
        bs_mean,
        0.6 * dist_y[x_idx_mean],
        s="Bootstrap mean = {:.4f}".format(bs_mean),
        ha="center",
        va="center",
        fontsize=fontsize,
        bbox=bbox_props,
    )

    # Add vertical line of sample_measure
    x_idx_smeas = np.argmin(np.abs(dist_x - sample_measure))
    ax.vlines(
        x=sample_measure,
        ymin=0.0,
        ymax=dist_y[x_idx_smeas],
        color="k",
        linewidth=linewidth,
        linestyles="dotted",
    )

    # Add SD
    bbox_props = dict(boxstyle="darrow, pad=0.4", fc="w", ec="k", lw=2)

    ax.text(
        bs_mean,
        0.4 * dist_y[x_idx_mean],
        s="SD = {:.4f} = SE".format(bs_std),
        ha="center",
        va="center",
        fontsize=fontsize,
        bbox=bbox_props,
    )


def add_null_pval(ax, null, color, alpha, fontsize):

    # Fill area between CI
    dist = ax.lines[0]
    dist_y = dist.get_ydata()
    dist_x = dist.get_xdata()
    linewidth = dist.get_linewidth()

    x_idx_null = np.argmin(np.abs(dist_x - null))
    if x_idx_null >= (len(dist_x) / 2.0):
        x_pval = dist_x[x_idx_null:]
        y_pval = dist_y[x_idx_null:]
    else:
        x_pval = dist_x[:x_idx_null]
        y_pval = dist_y[:x_idx_null]

    ax.fill_between(x_pval, 0, y_pval, facecolor=color, alpha=alpha)

    # Add vertical lines of null
    dist = ax.lines[0]
    linewidth = dist.get_linewidth()
    y_max = ax.get_ylim()[1]
    ax.vlines(
        x=null,
        ymin=0.0,
        ymax=y_max,
        color="k",
        linewidth=linewidth,
        linestyles="dotted",
    )

    # Add annotations
    bbox_props = dict(boxstyle="round, pad=0.4", fc="w", ec="k", lw=2)

    ax.text(
        null,
        0.75 * y_max,
        s="Null hypothesis = {:.1f}".format(null),
        ha="center",
        va="center",
        fontsize=fontsize,
        bbox=bbox_props,
    )


def plot_bootstrap_distr(
    sample_measure, bs_samples, alpha, color_ci, color_pval=None, null=None
):

    # Compute results from bootstrap
    q_low = (1.0 - alpha) / 2.0
    q_high = 1.0 - q_low
    ci = np.quantile(bs_samples, [q_low, q_high])
    bs_mean = np.mean(bs_samples)
    bs_std = np.std(bs_samples)

    if null is not None and color_pval is not None:
        pval_flag = True
        pval = np.min([[np.mean(bs_samples > null), np.mean(bs_samples < null)]]) * 2
    else:
        pval_flag = False

    # Set up plot
    sns.set(style="whitegrid")
    fontsize = 24
    font = {"family": "DejaVu Sans", "weight": "normal", "size": fontsize}
    plt.rc("font", **font)
    alpha_plot = 0.5

    # Initialize the matplotlib figure
    fig, ax = plt.subplots(figsize=(30, 12), dpi=args.dpi)

    # Plot distribution of bootstrap means
    sns.kdeplot(bs_samples, color="b", linewidth=5, gridsize=1000, ax=ax)

    y_lim = ax.get_ylim()

    # Change spines
    sns.despine(left=True, bottom=True)

    # Annotations
    add_ci_mean(
        ax,
        sample_measure,
        bs_mean,
        bs_std,
        ci,
        color=color_ci,
        alpha=alpha_plot,
        fontsize=fontsize,
    )

    if pval_flag:
        add_null_pval(ax, null, color=color_pval, alpha=alpha_plot, fontsize=fontsize)

    # Legend
    ci_patch = mpatches.Patch(
        facecolor=color_ci,
        edgecolor=None,
        alpha=alpha_plot,
        label="{:d} % confidence interval".format(int(100 * alpha)),
    )

    if pval_flag:
        if pval == 0.0:
            pval_patch = mpatches.Patch(
                facecolor=color_pval,
                edgecolor=None,
                alpha=alpha_plot,
                label="P value / 2 = {:.1f}".format(pval / 2.0),
            )
        elif np.around(pval / 2.0, decimals=4) > 0.0000:
            pval_patch = mpatches.Patch(
                facecolor=color_pval,
                edgecolor=None,
                alpha=alpha_plot,
                label="P value / 2 = {:.4f}".format(pval / 2.0),
            )
        else:
            pval_patch = mpatches.Patch(
                facecolor=color_pval,
                edgecolor=None,
                alpha=alpha_plot,
                label="P value / 2 < $10^{}$".format(np.ceil(np.log10(pval / 2.0))),
            )

        leg = ax.legend(
            handles=[ci_patch, pval_patch],
            ncol=1,
            loc="upper right",
            frameon=True,
            framealpha=1.0,
            title="",
            fontsize=fontsize,
            columnspacing=1.0,
            labelspacing=0.2,
            markerfirst=True,
        )
    else:
        leg = ax.legend(
            handles=[ci_patch],
            ncol=1,
            loc="upper right",
            frameon=True,
            framealpha=1.0,
            title="",
            fontsize=fontsize,
            columnspacing=1.0,
            labelspacing=0.2,
            markerfirst=True,
        )

    plt.setp(leg.get_title(), fontsize=fontsize, horizontalalignment="left")

    # Set X-label
    ax.set_xlabel("Bootstrap estimates", rotation=0, fontsize=fontsize, labelpad=10.0)

    # Set Y-label
    ax.set_ylabel("Density", rotation=90, fontsize=fontsize, labelpad=10.0)

    # Ticks
    plt.setp(ax.get_xticklabels(), fontsize=0.8 * fontsize, verticalalignment="top")
    plt.setp(ax.get_yticklabels(), fontsize=0.8 * fontsize)

    ax.set_ylim(y_lim)

    return fig, bs_mean, bs_std, ci, pval


if __name__ == "__main__":
    # -----------------------------
    # -----  Parse arguments  -----
    # -----------------------------
    args = parsed_args()
    print("Args:\n" + "\n".join([f"    {k:20}: {v}" for k, v in vars(args).items()]))

    # Determine output dir
    if args.output_dir is None:
        output_dir = Path(os.environ["SLURM_TMPDIR"])
    else:
        output_dir = Path(args.output_dir)
    if not output_dir.exists():
        output_dir.mkdir(parents=True, exist_ok=False)

    # Store args
    output_yml = output_dir / "{}_bootstrap.yml".format(args.technique)
    with open(output_yml, "w") as f:
        yaml.dump(vars(args), f)

    # Determine technique
    if args.technique.lower() not in dict_techniques:
        raise ValueError("{} is not a valid technique".format(args.technique))
    else:
        technique = dict_techniques[args.technique.lower()]

    # Read CSV
    df = pd.read_csv(args.input_csv, index_col="model_img_idx")

    # Find relevant model pairs
    model_pairs = []
    for mi in df.loc[df[technique]].model_feats.unique():
        for mj in df.model_feats.unique():
            if mj == mi:
                continue

            if df.loc[df.model_feats == mj, technique].unique()[0]:
                continue

            is_pair = True
            for f in model_feats:
                if f == technique:
                    continue
                elif (
                    df.loc[df.model_feats == mj, f].unique()[0]
                    != df.loc[df.model_feats == mi, f].unique()[0]
                ):
                    is_pair = False
                    break
                else:
                    pass
            if is_pair:
                model_pairs.append((mi, mj))
                break

    print("\nModel pairs identified:\n")
    for pair in model_pairs:
        print("{} & {}".format(pair[0], pair[1]))

    df["base"] = ["N/A"] * len(df)
    for spp in model_pairs:
        df.loc[df.model_feats.isin(spp), "depth_base"] = spp[1]

    # Build bootstrap data
    data = {m: [] for m in dict_metrics["key_metrics"]}
    for m_with, m_without in model_pairs:
        df_with = df.loc[df.model_feats == m_with]
        df_without = df.loc[df.model_feats == m_without]
        for metric in data.keys():
            diff = (
                df_with.sort_values(by="img_idx")[metric].values
                - df_without.sort_values(by="img_idx")[metric].values
            )
            data[metric].extend(diff.tolist())

    # Run bootstrap
    measures = ["mean", "median", "20_trimmed_mean"]
    bs_data = {meas: {m: np.zeros(args.n_bs) for m in data.keys()} for meas in measures}

    np.random.seed(args.bs_seed)
    for m, data_m in data.items():
        for idx, s in enumerate(tqdm(range(args.n_bs))):
            # Sample with replacement
            bs_sample = np.random.choice(data_m, size=len(data_m), replace=True)

            # Store mean
            bs_data["mean"][m][idx] = np.mean(bs_sample)

            # Store median
            bs_data["median"][m][idx] = np.median(bs_sample)

            # Store 20 % trimmed mean
            bs_data["20_trimmed_mean"][m][idx] = trim_mean(bs_sample, 0.2)

for metric in dict_metrics["key_metrics"]:
    sample_measure = trim_mean(data[metric], 0.2)
    fig, bs_mean, bs_std, ci, pval = plot_bootstrap_distr(
        sample_measure,
        bs_data["20_trimmed_mean"][metric],
        alpha=args.alpha,
        color_ci=color_cat1_light,
        color_pval=color_cat2_light,
        null=0.0,
    )

    # Save figure
    output_fig = output_dir / "{}_bootstrap_{}_{}.png".format(
        args.technique, metric, "20_trimmed_mean"
    )
    fig.savefig(output_fig, dpi=fig.dpi, bbox_inches="tight")

    # Store results
    output_results = output_dir / "{}_bootstrap_{}_{}.yml".format(
        args.technique, metric, "20_trimmed_mean"
    )
    results_dict = {
        "measure": "20_trimmed_mean",
        "sample_measure": float(sample_measure),
        "bs_mean": float(bs_mean),
        "bs_std": float(bs_std),
        "ci_left": float(ci[0]),
        "ci_right": float(ci[1]),
        "pval": float(pval),
    }
    with open(output_results, "w") as f:
        yaml.dump(results_dict, f)