vuln_figure.py 40.6 KB
Newer Older
Yannick DAYER's avatar
Yannick DAYER committed
1
"""Runs error analysis on score sets, outputs metrics and plots"""
2 3 4

import click
import numpy as np
5
from tabulate import tabulate
6 7
import matplotlib.pyplot as mpl
import bob.measure.script.figure as measure_figure
8
from bob.measure.utils import get_thres, remove_nan
9
from bob.measure import (
Yannick DAYER's avatar
Yannick DAYER committed
10 11 12 13 14 15 16 17
    frr_threshold,
    far_threshold,
    farfrr,
    f_score,
    roc_auc_score,
    ppndf,
    min_weighted_error_rate_threshold,
    precision_recall,
18 19 20 21 22
)
from bob.measure import plot
from . import error_utils
import logging

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
logger = logging.getLogger(__name__)


def clean_scores(input_scores):
    """Returns a dict with each scores groups cleaned

    Parameters
    ----------
    input_scores: dict

    Returns
    -------
    clean_scores: dict
    """
    clean_scores = {}
    for key, scores in input_scores.items():
        clean_scores[key], _, _ = remove_nan(scores)
    return clean_scores


class Metrics(measure_figure.Metrics):
Yannick DAYER's avatar
Yannick DAYER committed
44
    """Compute metrics from score files
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

    Attributes
    ----------

    names: dict {str:str}
        pairs of metrics keys and corresponding row titles to display.
    """

    def __init__(
        self,
        ctx,
        scores,
        evaluation,
        func_load,
        names={
            "fta": "Licit Failure to Acquire",
            "fmr": "Licit False Match Rate",
            "fnmr": "Licit False Non Match Rate",
            "far": "Licit False Accept Rate",
            "frr": "Licit False Reject Rate",
            "hter": "Licit Half Total Error Rate",
            "iapmr": "Attack Presentation Match Rate",
        },
        **kwargs,
    ):
Yannick DAYER's avatar
Yannick DAYER committed
70 71 72
        super(Metrics, self).__init__(
            ctx, scores, evaluation, func_load, names, **kwargs
        )
73 74 75 76

    def _get_all_metrics(self, idx, input_scores, input_names):
        """ Compute all metrics for dev and eval scores"""
        # Parse input and remove/count failed samples (NaN)
Yannick DAYER's avatar
Yannick DAYER committed
77 78 79 80 81 82
        dev_neg, dev_neg_na, dev_neg_count = remove_nan(input_scores[0]["licit_neg"])
        dev_pos, dev_pos_na, dev_pos_count = remove_nan(input_scores[0]["licit_pos"])
        dev_spoof, dev_spoof_na, dev_spoof_count = remove_nan(input_scores[0]["spoof"])
        dev_fta = (dev_neg_na + dev_pos_na + dev_spoof_na) / (
            dev_neg_count + dev_pos_count + dev_spoof_count
        )
83
        if self._eval:
Yannick DAYER's avatar
Yannick DAYER committed
84 85 86 87 88 89 90 91 92 93 94 95
            eval_neg, eval_neg_na, eval_neg_count = remove_nan(
                input_scores[1]["licit_neg"]
            )
            eval_pos, eval_pos_na, eval_pos_count = remove_nan(
                input_scores[1]["licit_pos"]
            )
            eval_spoof, eval_spoof_na, eval_spoof_count = remove_nan(
                input_scores[1]["spoof"]
            )
            eval_fta = (eval_neg_na + eval_pos_na + eval_spoof_na) / (
                eval_neg_count + eval_pos_count + eval_spoof_count
            )
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
        dev_file = input_names[0]

        # Compute threshold on dev set
        threshold = (
            self.get_thres(self._criterion, dev_neg, dev_pos, self._far)
            if self._thres is None
            else self._thres[idx]
        )

        title = self._legends[idx] if self._legends is not None else None
        if self._thres is None:
            far_str = ""
            if self._criterion == "far" and self._far is not None:
                far_str = str(self._far)
            click.echo(
                f"[Min. criterion: {self._criterion.upper()} {far_str}] "
                f"Threshold on Development set `{title or dev_file}`: {threshold:e}",
                file=self.log_file,
            )
        else:
            click.echo(
                "[Min. criterion: user provided] Threshold on "
                f"Development set `{dev_file or title}`: {threshold:e}",
                file=self.log_file,
            )

        res = []
Yannick DAYER's avatar
Yannick DAYER committed
123 124 125 126 127
        res.append(
            self._strings(
                self._numbers(dev_neg, dev_pos, dev_spoof, threshold, dev_fta)
            )
        )
128 129 130 131 132

        if self._eval:
            # computes statistics for the eval set based on the threshold a
            # priori computed on the dev set
            res.append(
Yannick DAYER's avatar
Yannick DAYER committed
133 134 135
                self._strings(
                    self._numbers(eval_neg, eval_pos, eval_spoof, threshold, eval_fta)
                )
136 137 138 139 140 141 142
            )
        else:
            res.append(None)

        return res

    def _numbers(self, neg, pos, spoof, threshold, fta):
Yannick DAYER's avatar
Yannick DAYER committed
143
        """Computes each metric value"""
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
        # fpr and fnr
        fmr, fnmr = farfrr(neg, pos, threshold)
        hter = (fmr + fnmr) / 2.0
        far = fmr * (1 - fta)
        frr = fta + fnmr * (1 - fta)

        ni = neg.shape[0]  # number of impostors
        fm = int(round(fmr * ni))  # number of false accepts
        nc = pos.shape[0]  # number of clients
        fnm = int(round(fnmr * nc))  # number of false rejects

        # precision and recall
        precision, recall = precision_recall(neg, pos, threshold)

        # f_score
        f1_score = f_score(neg, pos, threshold, 1)

        # AUC ROC
        auc = roc_auc_score(neg, pos)
        auc_log = roc_auc_score(neg, pos, log_scale=True)

        # IAPMR at threshold
Yannick DAYER's avatar
Yannick DAYER committed
166
        iapmr, _ = farfrr(spoof, [0.0], threshold)
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
        spoof_total = len(spoof)
        spoof_match = int(round(iapmr * spoof_total))

        return {
            "fta": fta,
            "fmr": fmr,
            "fnmr": fnmr,
            "hter": hter,
            "far": far,
            "frr": frr,
            "fm": fm,
            "ni": ni,
            "fnm": fnm,
            "nc": nc,
            "precision": precision,
            "recall": recall,
            "f1_score": f1_score,
            "auc": auc,
            "auc_log": auc_log,
            "iapmr": iapmr,
            "spoof_match": spoof_match,
            "spoof_total": spoof_total,
        }

    def _strings(self, metrics):
Yannick DAYER's avatar
Yannick DAYER committed
192
        """Formats the metrics values into strings"""
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        return {
            "fta": f"{100 * metrics['fta']:.{self._decimal}f}%",
            "fmr": f"{100 * metrics['fmr']:.{self._decimal}f}% ({metrics['fm']}/{metrics['ni']})",
            "fnmr": f"{100 * metrics['fnmr']:.{self._decimal}f}% ({metrics['fnm']}/{metrics['nc']})",
            "far": f"{100 * metrics['far']:.{self._decimal}f}%",
            "frr": f"{100 * metrics['frr']:.{self._decimal}f}%",
            "hter": f"{100 * metrics['hter']:.{self._decimal}f}%",
            "precision": f"{metrics['precision']:.{self._decimal}f}",
            "recall": f"{metrics['recall']:.{self._decimal}f}",
            "f1_score": f"{metrics['f1_score']:.{self._decimal}f}",
            "auc": f"{metrics['auc']:.{self._decimal}f}",
            "auc_log": f"{metrics['auc_log']:.{self._decimal}f}",
            "iapmr": f"{100 * metrics['iapmr']:.{self._decimal}f}% ({metrics['spoof_match']}/{metrics['spoof_total']})",
        }

    def compute(self, idx, input_scores, input_names):
Yannick DAYER's avatar
Yannick DAYER committed
209
        """Compute metrics thresholds and tables for given system inputs"""
210 211 212 213 214 215 216 217 218 219 220 221 222 223
        # Title and headers
        title = self._legends[idx] if self._legends is not None else None
        headers = ["" or title, "Dev. %s" % input_names[0]]
        if self._eval and input_scores[1] is not None:
            headers.append("eval % s" % input_names[1])

        # Tables rows
        all_metrics = self._get_all_metrics(idx, input_scores, input_names)
        headers = [" " or title, "Development"]

        rows = []
        for key, name in self.names.items():
            if key not in all_metrics[0]:
                logger.warning(f"{key} not present in metrics.")
Yannick DAYER's avatar
Yannick DAYER committed
224
            rows.append([name, all_metrics[0].get(key, "N/A")])
225 226 227 228 229 230

        if self._eval:
            # computes statistics for the eval set based on the threshold a
            # priori
            headers.append("Evaluation")
            for row, key in zip(rows, self.names.keys()):
Yannick DAYER's avatar
Yannick DAYER committed
231
                row.append(all_metrics[1].get(key, "N/A"))
232 233

        click.echo(tabulate(rows, headers, self._tablefmt), file=self.log_file)
234 235 236 237 238


def _iapmr_dot(threshold, iapmr, real_data, **kwargs):
    # plot a dot on threshold versus IAPMR line and show IAPMR as a number
    axlim = mpl.axis()
Yannick DAYER's avatar
Yannick DAYER committed
239
    mpl.plot(threshold, 100.0 * iapmr, "o", color="C3", **kwargs)
240 241
    if not real_data:
        mpl.annotate(
Yannick DAYER's avatar
Yannick DAYER committed
242 243 244
            "IAPMR at\noperating point",
            xy=(threshold, 100.0 * iapmr),
            xycoords="data",
245
            xytext=(0.85, 0.6),
Yannick DAYER's avatar
Yannick DAYER committed
246 247 248 249 250 251
            textcoords="axes fraction",
            color="black",
            size="large",
            arrowprops=dict(facecolor="black", shrink=0.05, width=2),
            horizontalalignment="center",
            verticalalignment="top",
252 253
        )
    else:
Yannick DAYER's avatar
Yannick DAYER committed
254 255 256 257 258 259
        mpl.text(
            threshold + (threshold - axlim[0]) / 12,
            100.0 * iapmr,
            "%.1f%%" % (100.0 * iapmr,),
            color="C3",
        )
260 261 262 263 264 265 266 267


def _iapmr_line_plot(scores, n_points=100, **kwargs):
    axlim = mpl.axis()
    step = (axlim[1] - axlim[0]) / float(n_points)
    thres = [(k * step) + axlim[0] for k in range(2, n_points - 1)]
    mix_prob_y = []
    for k in thres:
Yannick DAYER's avatar
Yannick DAYER committed
268
        mix_prob_y.append(100.0 * error_utils.calc_pass_rate(k, scores))
269

Yannick DAYER's avatar
Yannick DAYER committed
270
    mpl.plot(thres, mix_prob_y, label="IAPMR", color="C3", **kwargs)
271 272 273 274 275 276 277 278


def _iapmr_plot(scores, threshold, iapmr, real_data, **kwargs):
    _iapmr_dot(threshold, iapmr, real_data, **kwargs)
    _iapmr_line_plot(scores, n_points=100, **kwargs)


class HistVuln(measure_figure.Hist):
Yannick DAYER's avatar
Yannick DAYER committed
279
    """ Histograms for vulnerability """
280 281 282

    def __init__(self, ctx, scores, evaluation, func_load):
        super(HistVuln, self).__init__(
Yannick DAYER's avatar
Yannick DAYER committed
283 284
            ctx, scores, evaluation, func_load, nhist_per_system=3
        )
285 286

    def _setup_hist(self, neg, pos):
Yannick DAYER's avatar
Yannick DAYER committed
287 288
        self._title_base = " "
        self._density_hist(pos[0], n=0, label="Genuine", color="C2")
289
        self._density_hist(
Yannick DAYER's avatar
Yannick DAYER committed
290
            neg[0], n=1, label="Zero-effort impostors", alpha=0.8, color="C0"
291 292
        )
        self._density_hist(
293
            neg[1],
Yannick DAYER's avatar
Yannick DAYER committed
294 295 296 297 298
            n=2,
            label="Presentation attack",
            alpha=0.4,
            color="C7",
            hatch="\\\\",
299 300
        )

301 302 303 304 305
    def _get_neg_pos_thres(self, idx, input_scores, input_names):
        """Get scores and threshold for the given system at index idx for vuln

        Returns
        -------
306
        dev_neg, dev_pos, eval_neg, eval_pos: list of arrays
307 308 309 310 311
            The scores negatives and positives for each set. Each element
            contains two lists: licit [0] and spoof [1]
        threshold: int
            The value of the threshold computed on the `dev` set licit scores.
        """
312 313

        dev_scores = clean_scores(input_scores[0])
314
        if self._eval:
315 316
            eval_scores = clean_scores(input_scores[1])
        else:
Yannick DAYER's avatar
Yannick DAYER committed
317
            eval_scores = {"licit_neg": [], "licit_pos": [], "spoof": []}
318 319

        threshold = (
Yannick DAYER's avatar
Yannick DAYER committed
320
            get_thres(self._criterion, dev_scores["licit_neg"], dev_scores["licit_pos"])
321 322 323
            if self._thres is None
            else self._thres[idx]
        )
324
        return (
Yannick DAYER's avatar
Yannick DAYER committed
325
            [
326
                dev_scores["licit_neg"], dev_scores["spoof"],
Yannick DAYER's avatar
Yannick DAYER committed
327 328
            ],
            [
329 330 331 332 333 334 335
                dev_scores["licit_pos"]
            ],
            [
                eval_scores["licit_neg"], eval_scores["spoof"],
            ],
            [
                eval_scores["licit_pos"],
Yannick DAYER's avatar
Yannick DAYER committed
336 337
            ],
            threshold,
338 339
        )

340
    def _lines(self, threshold, label, neg, pos, idx, **kwargs):
341
        spoof = neg[1]
342 343
        neg = neg[0]
        pos = pos[0]
344
        # plot EER treshold vertical line
345
        super(HistVuln, self)._lines(threshold, label, neg, pos, idx, **kwargs)
346

Yannick DAYER's avatar
Yannick DAYER committed
347
        if "iapmr_line" not in self._ctx.meta or self._ctx.meta["iapmr_line"]:
348
            # Plot iapmr_line (accepted PA vs threshold)
Yannick DAYER's avatar
Yannick DAYER committed
349
            iapmr, _ = farfrr(spoof, [0.0], threshold)
350 351 352
            ax2 = mpl.twinx()
            # we never want grid lines on axis 2
            ax2.grid(False)
353
            real_data = self._ctx.meta.get("real_data", True)
354
            _iapmr_plot(spoof, threshold, iapmr, real_data=real_data)
355 356
            n = idx % self._step_print
            col = n % self._ncols
Yannick DAYER's avatar
Yannick DAYER committed
357
            rest_print = self.n_systems - int(idx / self._step_print) * self._step_print
358
            if col == self._ncols - 1 or n == rest_print - 1:
Yannick DAYER's avatar
Yannick DAYER committed
359 360 361 362
                ax2.set_ylabel("IAPMR (%)", color="C3")
            ax2.tick_params(axis="y", colors="C3")
            ax2.yaxis.label.set_color("C3")
            ax2.spines["right"].set_color("C3")
363 364


365
class Epc(measure_figure.PlotBase):
Yannick DAYER's avatar
Yannick DAYER committed
366
    """ Handles the plotting of EPC """
367 368 369

    def __init__(self, ctx, scores, evaluation, func_load):
        super(Epc, self).__init__(ctx, scores, evaluation, func_load)
370
        self._iapmr = self._ctx.meta.get("iapmr", True)
Yannick DAYER's avatar
Yannick DAYER committed
371
        self._titles = self._titles or ["EPC and IAPMR" if self._iapmr else "EPC"]
372
        self._x_label = self._x_label or "Weight $\\beta$"
373 374 375 376 377
        self._y_label = self._y_label or "HTER (%)"
        self._eval = True  # always eval data with EPC
        self._split = False
        self._nb_figs = 1

378
        if self._min_arg != 2:
Yannick DAYER's avatar
Yannick DAYER committed
379 380 381
            raise click.BadParameter(
                "You must provide 2 scores files: " "scores-{dev,eval}.csv"
            )
382 383

    def compute(self, idx, input_scores, input_names):
Yannick DAYER's avatar
Yannick DAYER committed
384
        """Plot EPC with IAPMR for vuln"""
385 386 387 388
        dev_scores = clean_scores(input_scores[0])
        if self._eval:
            eval_scores = clean_scores(input_scores[1])
        else:
Yannick DAYER's avatar
Yannick DAYER committed
389
            eval_scores = {"licit_neg": [], "licit_pos": [], "spoof": []}
390 391 392

        mpl.gcf().clear()
        mpl.grid()
393
        logger.info(f"EPC using {input_names[0]} and {input_names[1]}")
394
        plot.epc(
Yannick DAYER's avatar
Yannick DAYER committed
395 396 397 398
            dev_scores["licit_neg"],
            dev_scores["licit_pos"],
            eval_scores["licit_neg"],
            eval_scores["licit_pos"],
399
            self._points,
Yannick DAYER's avatar
Yannick DAYER committed
400 401 402
            color="C0",
            linestyle=self._linestyles[idx],
            label=self._label("HTER (licit)", idx),
403 404 405 406 407 408 409 410 411 412
        )
        mpl.xlabel(self._x_label)
        mpl.ylabel(self._y_label)
        if self._iapmr:
            ax1 = mpl.gca()
            mpl.gca().set_axisbelow(True)
            prob_ax = mpl.gca().twinx()
            step = 1.0 / float(self._points)
            thres = [float(k * step) for k in range(self._points)]
            thres.append(1.0)
Yannick DAYER's avatar
Yannick DAYER committed
413 414 415 416 417 418
            apply_thres = [
                min_weighted_error_rate_threshold(
                    dev_scores["licit_neg"], dev_scores["licit_pos"], t
                )
                for t in thres
            ]
419 420 421
            mix_prob_y = []
            for k in apply_thres:
                mix_prob_y.append(
Yannick DAYER's avatar
Yannick DAYER committed
422
                    100.0 * error_utils.calc_pass_rate(k, eval_scores["spoof"])
423 424
                )

425
            logger.info(f"IAPMR in EPC plot using {input_names[0]}, {input_names[1]}")
426
            mpl.plot(
Yannick DAYER's avatar
Yannick DAYER committed
427 428
                thres,
                mix_prob_y,
429
                label=self._label("IAPMR (spoof)", idx),
Yannick DAYER's avatar
Yannick DAYER committed
430
                color="C3",
431 432
            )

Yannick DAYER's avatar
Yannick DAYER committed
433 434 435 436
            prob_ax.tick_params(axis="y", colors="C3")
            prob_ax.yaxis.label.set_color("C3")
            prob_ax.spines["right"].set_color("C3")
            prob_ax.set_ylabel("IAPMR (%)", color="C3")
437
            prob_ax.set_axisbelow(True)
Yannick DAYER's avatar
Yannick DAYER committed
438 439 440
            ax1.yaxis.label.set_color("C0")
            ax1.tick_params(axis="y", colors="C0")
            ax1.spines["left"].set_color("C0")
441
            mpl.sca(ax1)
442 443


Yannick DAYER's avatar
Yannick DAYER committed
444
class Epsc(measure_figure.GridSubplot):
Yannick DAYER's avatar
Yannick DAYER committed
445
    """ Handles the plotting of EPSC """
446

Yannick DAYER's avatar
Yannick DAYER committed
447 448
    def __init__(self, ctx, scores, func_load, criteria, var_param, **kwargs):
        evaluation = ctx.meta.get("evaluation", True)
449
        super(Epsc, self).__init__(ctx, scores, evaluation, func_load)
Yannick DAYER's avatar
Yannick DAYER committed
450 451 452
        self._iapmr = self._ctx.meta.get("iapmr", False)
        self._wer = self._ctx.meta.get("wer", True)
        self._criteria = criteria or "eer"
453
        self._var_param = var_param or "omega"
Yannick DAYER's avatar
Yannick DAYER committed
454
        self._fixed_params = ctx.meta.get("fixed_params", [0.5])
Yannick DAYER's avatar
Yannick DAYER committed
455
        self._nb_subplots = 2 if (self._wer and self._iapmr) else 1
Yannick DAYER's avatar
Yannick DAYER committed
456
        if len(self._titles) < self._nb_figs * self._nb_subplots:
Yannick DAYER's avatar
Yannick DAYER committed
457
            self._titles = [v for v in self._titles for _ in range(self._nb_subplots)]
458 459 460
        self._eval = True  # always eval data with EPSC
        self._split = False
        self._nb_figs = 1
Yannick DAYER's avatar
Yannick DAYER committed
461
        self._sampling = ctx.meta.get("sampling", 5)
462 463 464
        self._axis1 = None
        self._axis2 = None

Yannick DAYER's avatar
Yannick DAYER committed
465
        if self._min_arg != 2:
Yannick DAYER's avatar
Yannick DAYER committed
466 467 468
            raise click.BadParameter(
                "You must provide 2 scores files: " "scores-{dev,eval}.csv"
            )
469 470 471 472 473

        self._ncols = 1 if self._iapmr else 0
        self._ncols += 1 if self._wer else 0

    def compute(self, idx, input_scores, input_names):
Yannick DAYER's avatar
Yannick DAYER committed
474
        """ Plot EPSC for vuln"""
Yannick DAYER's avatar
Yannick DAYER committed
475 476 477 478
        dev_scores = clean_scores(input_scores[0])
        if self._eval:
            eval_scores = clean_scores(input_scores[1])
        else:
Yannick DAYER's avatar
Yannick DAYER committed
479
            eval_scores = {"licit_neg": [], "licit_pos": [], "spoof": []}
Yannick DAYER's avatar
Yannick DAYER committed
480

Yannick DAYER's avatar
Yannick DAYER committed
481 482 483 484
        merge_sys = (
            self._fixed_params is None or len(self._fixed_params) == 1
        ) and self.n_systems > 1
        legend = ""
485 486 487
        if self._legends is not None and idx < len(self._legends):
            legend = self._legends[idx]
        elif self.n_systems > 1:
Yannick DAYER's avatar
Yannick DAYER committed
488
            legend = "Sys%d" % (idx + 1)
489

Yannick DAYER's avatar
Yannick DAYER committed
490
        if self._axis1 is None:
491 492 493 494 495 496 497 498 499 500 501
            # axes should only be created once
            self._axis1 = self.create_subplot(0)
            if self._ncols == 2:
                self._axis2 = self.create_subplot(1)
            else:
                self._axis2 = self._axis1
        points = 10
        for pi, fp in enumerate(self._fixed_params):
            if merge_sys:
                assert pi == 0
                pi = idx
Yannick DAYER's avatar
Yannick DAYER committed
502
            if self._var_param == "omega":
503
                omega, beta, thrs = error_utils.epsc_thresholds(
Yannick DAYER's avatar
Yannick DAYER committed
504 505 506
                    dev_scores["licit_neg"],
                    dev_scores["licit_pos"],
                    dev_scores["spoof"],
507
                    dev_scores["licit_pos"],
508 509
                    points=points,
                    criteria=self._criteria,
Yannick DAYER's avatar
Yannick DAYER committed
510 511
                    beta=fp,
                )
512 513
            else:
                omega, beta, thrs = error_utils.epsc_thresholds(
Yannick DAYER's avatar
Yannick DAYER committed
514 515 516
                    dev_scores["licit_neg"],
                    dev_scores["licit_pos"],
                    dev_scores["spoof"],
517
                    dev_scores["licit_pos"],
518 519
                    points=points,
                    criteria=self._criteria,
Yannick DAYER's avatar
Yannick DAYER committed
520
                    omega=fp,
521 522 523
                )

            errors = error_utils.all_error_rates(
Yannick DAYER's avatar
Yannick DAYER committed
524 525 526
                eval_scores["licit_neg"],
                eval_scores["licit_pos"],
                eval_scores["spoof"],
527
                eval_scores["licit_pos"],
Yannick DAYER's avatar
Yannick DAYER committed
528 529 530
                thrs,
                omega,
                beta,
531 532 533
            )  # error rates are returned in a list in the
            # following order: frr, far, IAPMR, far_w, wer_w
            mpl.sca(self._axis1)
Yannick DAYER's avatar
Yannick DAYER committed
534
            # Between zero-effort impostors and Presentation attacks
535
            if self._wer:
Yannick DAYER's avatar
Yannick DAYER committed
536 537 538 539 540 541 542 543 544
                logger.debug(
                    f"Plotting EPSC: WER for system {idx+1}, fix param {pi}: {fp}"
                )
                set_title = (
                    self._titles[(idx // self.n_systems) * self._nb_subplots]
                    if self._titles
                    else None
                )
                display = set_title.replace(" ", "") if set_title is not None else True
545
                wer_title = set_title or "EPSC"
546
                if display:
Yannick DAYER's avatar
Yannick DAYER committed
547
                    self._axis1.set_title(wer_title)
548
                base = f"({legend}) " if legend.strip() else ""
Yannick DAYER's avatar
Yannick DAYER committed
549
                if self._var_param == "omega":
Yannick DAYER's avatar
Yannick DAYER committed
550 551
                    label = f"{base}$\\beta={fp:.1f}$"
                    self._axis1.plot(
Yannick DAYER's avatar
Yannick DAYER committed
552 553 554 555 556 557
                        omega,
                        100.0 * errors[4].flatten(),
                        color=self._colors[pi],
                        linestyle="-",
                        label=label,
                    )
Yannick DAYER's avatar
Yannick DAYER committed
558
                    self._axis1.set_xlabel(self._x_label or "Weight $\\omega$")
559
                else:
Yannick DAYER's avatar
Yannick DAYER committed
560 561
                    label = f"{base}$\\omega={fp:.1f}$"
                    self._axis1.plot(
Yannick DAYER's avatar
Yannick DAYER committed
562 563 564 565 566 567
                        beta,
                        100.0 * errors[4].flatten(),
                        color=self._colors[pi],
                        linestyle="-",
                        label=label,
                    )
Yannick DAYER's avatar
Yannick DAYER committed
568 569 570 571
                    self._axis1.set_xlabel(self._x_label or "Weight $\\beta$")
                self._axis1.set_ylabel(self._y_label or "WER$_{\\omega,\\beta}$ (%)")
                self._axis1.grid(True)
                self._axis1.legend(loc=self._legend_loc)
572 573

            if self._iapmr:
Yannick DAYER's avatar
Yannick DAYER committed
574 575 576
                logger.debug(
                    f"Plotting EPSC: IAPMR for system {idx+1}, fix param {pi}: {fp}"
                )
577
                mpl.sca(self._axis2)
Yannick DAYER's avatar
Yannick DAYER committed
578 579 580 581 582 583
                set_title = (
                    self._titles[(idx // self.n_systems) * self._nb_subplots + 1]
                    if self._titles
                    else None
                )
                display = set_title.replace(" ", "") if set_title is not None else True
584
                iapmr_title = set_title or "EPSC"
585
                if display:
Yannick DAYER's avatar
Yannick DAYER committed
586
                    self._axis2.set_title(iapmr_title)
587
                base = f"({legend}) " if legend.strip() else ""
Yannick DAYER's avatar
Yannick DAYER committed
588
                if self._var_param == "omega":
Yannick DAYER's avatar
Yannick DAYER committed
589 590
                    label = f"{base} $\\beta={fp:.1f}$"
                    self._axis2.plot(
Yannick DAYER's avatar
Yannick DAYER committed
591 592 593 594 595
                        omega,
                        100.0 * errors[2].flatten(),
                        color=self._colors[pi],
                        linestyle="-",
                        label=label,
596
                    )
Yannick DAYER's avatar
Yannick DAYER committed
597
                    self._axis2.set_xlabel(self._x_label or "Weight $\\omega$")
598
                else:
Yannick DAYER's avatar
Yannick DAYER committed
599 600
                    label = f"{base} $\\omega={fp:.1f}$"
                    self._axis2.plot(
Yannick DAYER's avatar
Yannick DAYER committed
601 602 603 604 605
                        beta,
                        100.0 * errors[2].flatten(),
                        linestyle="-",
                        color=self._colors[pi],
                        label=label,
606
                    )
Yannick DAYER's avatar
Yannick DAYER committed
607
                    self._axis2.set_xlabel(self._x_label or "Weight $\\beta$")
608

Yannick DAYER's avatar
Yannick DAYER committed
609 610 611
                self._axis2.set_ylabel(self._y_label or "IAPMR (%)")
                self._axis2.grid(True)
                self._axis2.legend(loc=self._legend_loc)
612

Yannick DAYER's avatar
Yannick DAYER committed
613
    def end_process(self):
614
        """Sets the legend."""
Yannick DAYER's avatar
Yannick DAYER committed
615 616 617 618 619 620
        if self._end_setup_plot:
            for i in range(self._nb_figs):
                fig = mpl.figure(i + 1)
                if self._disp_legend:
                    mpl.legend(loc=self._legend_loc)
                self._pdf_page.savefig(fig)
621 622
        self._end_setup_plot = False
        super().end_process()
623

Yannick DAYER's avatar
Yannick DAYER committed
624

625
class Epsc3D(Epsc):
Yannick DAYER's avatar
Yannick DAYER committed
626 627
    """ 3D EPSC plots for vuln"""

628 629
    def __init__(self, ctx, scores, func_load, criteria, var_param, **kwargs):
        super().__init__(ctx, scores, func_load, criteria, var_param, **kwargs)
Yannick DAYER's avatar
Yannick DAYER committed
630
        if self._nb_subplots != 1:
Yannick DAYER's avatar
Yannick DAYER committed
631 632 633
            raise ValueError(
                "You cannot plot more than one type of plot (WER or IAPMR)."
            )
634 635

    def compute(self, idx, input_scores, input_names):
Yannick DAYER's avatar
Yannick DAYER committed
636
        """ Implements plots"""
Yannick DAYER's avatar
Yannick DAYER committed
637 638 639 640
        dev_scores = clean_scores(input_scores[0])
        if self._eval:
            eval_scores = clean_scores(input_scores[1])
        else:
Yannick DAYER's avatar
Yannick DAYER committed
641
            eval_scores = {"licit_neg": [], "licit_pos": [], "spoof": []}
642

643
        default_title = "EPSC 3D"
Yannick DAYER's avatar
Yannick DAYER committed
644
        title = self._titles[idx] if self._titles else default_title
645

Yannick DAYER's avatar
Yannick DAYER committed
646
        mpl.rcParams.pop("key", None)
647 648 649

        points = self._sampling or 5

Yannick DAYER's avatar
Yannick DAYER committed
650
        # Compute threshold values on dev
651
        omega, beta, thrs = error_utils.epsc_thresholds(
Yannick DAYER's avatar
Yannick DAYER committed
652 653 654
            dev_scores["licit_neg"],
            dev_scores["licit_pos"],
            dev_scores["spoof"],
655
            dev_scores["licit_pos"],
656
            points=points,
Yannick DAYER's avatar
Yannick DAYER committed
657 658
            criteria=self._criteria,
        )
659

Yannick DAYER's avatar
Yannick DAYER committed
660
        # Compute errors on eval
661
        errors = error_utils.all_error_rates(
Yannick DAYER's avatar
Yannick DAYER committed
662 663 664
            eval_scores["licit_neg"],
            eval_scores["licit_pos"],
            eval_scores["spoof"],
665
            eval_scores["licit_pos"],
Yannick DAYER's avatar
Yannick DAYER committed
666 667 668
            thrs,
            omega,
            beta,
669 670 671 672 673
        )
        # error rates are returned in a list as 2D numpy.ndarrays in
        # the following order: frr, far, IAPMR, far_w, wer_wb, hter_wb
        wer_errors = 100 * errors[2 if self._iapmr else 4]

Yannick DAYER's avatar
Yannick DAYER committed
674
        if not self._axis1:
Yannick DAYER's avatar
Yannick DAYER committed
675
            self._axis1 = mpl.gcf().add_subplot(111, projection="3d")
676 677 678

        W, B = np.meshgrid(omega, beta)

Yannick DAYER's avatar
Yannick DAYER committed
679 680
        label = self._legends[idx] if self._legends else f"Sys {idx+1}"
        self._axis1.plot_wireframe(
Yannick DAYER's avatar
Yannick DAYER committed
681 682 683 684 685 686
            W,
            B,
            wer_errors,
            color=self._colors[idx],
            antialiased=False,
            label=label,
Yannick DAYER's avatar
Yannick DAYER committed
687
        )
688 689

        if self._iapmr:
Yannick DAYER's avatar
Yannick DAYER committed
690 691
            self._axis1.azim = -30
            self._axis1.elev = 50
692

Yannick DAYER's avatar
Yannick DAYER committed
693 694 695
        self._axis1.set_xlabel(self._x_label or r"Weight $\omega$")
        self._axis1.set_ylabel(self._y_label or r"Weight $\beta$")
        self._axis1.set_zlabel(
696 697 698
            r"WER$_{\omega,\beta}$ (%)" if self._wer else "IAPMR (%)"
        )

Yannick DAYER's avatar
Yannick DAYER committed
699
        if title.replace(" ", ""):
700 701 702
            mpl.title(title)


Yannick DAYER's avatar
Yannick DAYER committed
703
class BaseVulnDetRoc(measure_figure.PlotBase):
Yannick DAYER's avatar
Yannick DAYER committed
704
    """Base for DET and ROC"""
705

Yannick DAYER's avatar
Yannick DAYER committed
706 707
    def __init__(self, ctx, scores, evaluation, func_load, real_data, no_spoof):
        super(BaseVulnDetRoc, self).__init__(ctx, scores, evaluation, func_load)
708
        self._no_spoof = no_spoof
Yannick DAYER's avatar
Yannick DAYER committed
709
        self._fnmrs_at = ctx.meta.get("fnmr", [])
Yannick DAYER's avatar
Yannick DAYER committed
710
        self._fnmrs_at = [] if self._fnmrs_at is None else self._fnmrs_at
711 712
        self._real_data = True if real_data is None else real_data
        self._min_dig = -4 if self._min_dig is None else self._min_dig
Yannick DAYER's avatar
Yannick DAYER committed
713
        self._tpr = ctx.meta.get("tpr", True)
714 715

    def compute(self, idx, input_scores, input_names):
Yannick DAYER's avatar
Yannick DAYER committed
716
        """Implements plots"""
Yannick DAYER's avatar
Yannick DAYER committed
717 718 719 720
        dev_scores = clean_scores(input_scores[0])
        if self._eval:
            eval_scores = clean_scores(input_scores[1])
        else:
Yannick DAYER's avatar
Yannick DAYER committed
721
            eval_scores = {"licit_neg": [], "licit_pos": [], "spoof": []}
Yannick DAYER's avatar
Yannick DAYER committed
722 723 724 725 726

        mpl.figure(1)
        if self._eval:
            logger.info(f"dev curve using {input_names[0]}")
            self._plot(
Yannick DAYER's avatar
Yannick DAYER committed
727 728 729
                dev_scores["licit_neg"],
                dev_scores["licit_pos"],
                dev_scores["spoof"],
Yannick DAYER's avatar
Yannick DAYER committed
730 731 732 733 734 735 736 737 738 739 740 741
                npoints=self._points,
                tpr=self._tpr,
                min_far=self._min_dig,
                color=self._colors[idx],
                linestyle=self._linestyles[idx],
                label=self._label("dev", idx),
                alpha=self._alpha,
            )
            if not self._fnmrs_at:
                logger.info("Plotting fnmr line at dev eer threshold for dev")
                dev_threshold = get_thres(
                    criter="eer",
Yannick DAYER's avatar
Yannick DAYER committed
742 743 744 745 746
                    neg=dev_scores["licit_neg"],
                    pos=dev_scores["licit_pos"],
                )
                _, fnmr_at_dev_threshold = farfrr(
                    [0.0], dev_scores["licit_pos"], dev_threshold
Yannick DAYER's avatar
Yannick DAYER committed
747 748 749 750 751 752 753 754 755 756 757
                )
            fnmrs_dev = self._fnmrs_at or [fnmr_at_dev_threshold]
            self._draw_fnmrs(idx, dev_scores, fnmrs_dev)

            if self._split:
                mpl.figure(2)

            # Add the eval plot
            linestyle = "--" if not self._split else self._linestyles[idx]
            logger.info(f"eval curve using {input_names[1]}")
            self._plot(
Yannick DAYER's avatar
Yannick DAYER committed
758 759 760
                eval_scores["licit_neg"],
                eval_scores["licit_pos"],
                eval_scores["spoof"],
Yannick DAYER's avatar
Yannick DAYER committed
761 762 763 764 765 766 767 768 769 770
                linestyle=linestyle,
                npoints=self._points,
                tpr=self._tpr,
                min_far=self._min_dig,
                color=self._colors[idx],
                label=self._label("eval", idx),
                alpha=self._alpha,
            )
            if not self._fnmrs_at:
                logger.info("printing fnmr at dev eer threshold for eval")
Yannick DAYER's avatar
Yannick DAYER committed
771 772 773
                _, fnmr_at_dev_threshold = farfrr(
                    [0.0], eval_scores["licit_pos"], dev_threshold
                )
Yannick DAYER's avatar
Yannick DAYER committed
774 775 776 777 778 779
            fnmrs_dev = self._fnmrs_at or [fnmr_at_dev_threshold]
            self._draw_fnmrs(idx, eval_scores, fnmrs_dev, True)

        # Only dev scores available
        else:
            logger.info(f"dev curve using {input_names[0]}")
780
            self._plot(
Yannick DAYER's avatar
Yannick DAYER committed
781 782 783
                dev_scores["licit_neg"],
                dev_scores["licit_pos"],
                dev_scores["spoof"],
Yannick DAYER's avatar
Yannick DAYER committed
784 785 786 787 788 789 790 791 792 793 794 795
                npoints=self._points,
                tpr=self._tpr,
                min_far=self._min_dig,
                color=self._colors[idx],
                linestyle=self._linestyles[idx],
                label=self._label("dev", idx),
                alpha=self._alpha,
            )
            if not self._fnmrs_at:
                logger.info("Plotting fnmr line at dev eer threshold for dev")
                dev_threshold = get_thres(
                    criter="eer",
Yannick DAYER's avatar
Yannick DAYER committed
796 797 798 799 800
                    neg=dev_scores["licit_neg"],
                    pos=dev_scores["licit_pos"],
                )
                _, fnmr_at_dev_threshold = farfrr(
                    [0.0], dev_scores["licit_pos"], dev_threshold
Yannick DAYER's avatar
Yannick DAYER committed
801 802 803 804 805 806 807 808 809 810 811 812 813
                )
            fnmrs_dev = self._fnmrs_at or [fnmr_at_dev_threshold]
            self._draw_fnmrs(idx, dev_scores, fnmrs_dev)

    def _get_farfrr(self, x, y, thres):
        return None, None

    def _plot(self, x, y, s, npoints, **kwargs):
        pass

    def _draw_fnmrs(self, idx, scores, fnmrs=[], eval=False):
        pass

Yannick DAYER's avatar
Yannick DAYER committed
814

Yannick DAYER's avatar
Yannick DAYER committed
815
class DetVuln(BaseVulnDetRoc):
Yannick DAYER's avatar
Yannick DAYER committed
816
    """DET for vuln"""
Yannick DAYER's avatar
Yannick DAYER committed
817 818

    def __init__(self, ctx, scores, evaluation, func_load, real_data, no_spoof):
Yannick DAYER's avatar
Yannick DAYER committed
819 820 821
        super(DetVuln, self).__init__(
            ctx, scores, evaluation, func_load, real_data, no_spoof
        )
Yannick DAYER's avatar
Yannick DAYER committed
822 823
        self._x_label = self._x_label or "FMR (%)"
        self._y_label = self._y_label or "FNMR (%)"
Yannick DAYER's avatar
Yannick DAYER committed
824 825
        self._semilogx = ctx.meta.get("semilogx", False)
        add = ""
Yannick DAYER's avatar
Yannick DAYER committed
826
        if not self._titles:
Yannick DAYER's avatar
Yannick DAYER committed
827
            self._titles = [""] * self._nb_figs
Yannick DAYER's avatar
Yannick DAYER committed
828 829 830
        if not self._no_spoof:
            add = " and overlaid SPOOF scenario"
        for i, t in enumerate(self._titles):
831 832 833 834 835 836
            if self._eval and (i % 2):
                dev_eval = ", eval group"
            elif self._eval:
                dev_eval = ", dev group"
            else:
                dev_eval = ""
Yannick DAYER's avatar
Yannick DAYER committed
837 838
            self._titles[i] = t or ("DET: LICIT" + add + dev_eval)
        self._legend_loc = self._legend_loc or "upper right"
Yannick DAYER's avatar
Yannick DAYER committed
839 840 841 842 843 844 845 846 847 848 849 850 851 852

    def _set_axis(self):
        if self._axlim is not None and None not in self._axlim:
            plot.det_axis(self._axlim)
        else:
            plot.det_axis([0.01, 99, 0.01, 99])

    def _get_farfrr(self, x, y, thres):
        points = farfrr(x, y, thres)
        return points, [ppndf(i) for i in points]

    def _plot(self, x, y, s, npoints, **kwargs):
        logger.info("Plotting DET")
        plot.det(
Yannick DAYER's avatar
Yannick DAYER committed
853 854 855
            x,
            y,
            npoints,
Yannick DAYER's avatar
Yannick DAYER committed
856
            min_far=self._min_dig,
Yannick DAYER's avatar
Yannick DAYER committed
857 858 859
            color=kwargs.get("color"),
            linestyle=kwargs.get("linestyle"),
            label=kwargs.get("label"),
860
        )
Yannick DAYER's avatar
Yannick DAYER committed
861
        if not self._no_spoof and s is not None:
862 863
            ax1 = mpl.gca()
            ax2 = ax1.twiny()
Yannick DAYER's avatar
Yannick DAYER committed
864 865 866 867
            ax2.set_xlabel("IAPMR (%)", color="C3")
            ax2.tick_params(
                axis="x", colors="C3", labelrotation=self._x_rotation, labelcolor="C3"
            )
868 869 870
            # Prevent tick labels overlap
            ax2.tick_params(axis="both", which="major", labelsize="x-small")
            ax1.tick_params(axis="both", which="major", labelsize="x-small")
Yannick DAYER's avatar
Yannick DAYER committed
871
            ax2.spines["top"].set_color("C3")
Yannick DAYER's avatar
Yannick DAYER committed
872
            plot.det(
Yannick DAYER's avatar
Yannick DAYER committed
873 874 875
                s,
                y,
                npoints,
Yannick DAYER's avatar
Yannick DAYER committed
876
                min_far=self._min_dig,
Yannick DAYER's avatar
Yannick DAYER committed
877 878 879
                color="C3",
                linestyle=":",
                label="Spoof " + kwargs.get("label"),
880
            )
Yannick DAYER's avatar
Yannick DAYER committed
881
            self._set_axis()
882 883
            mpl.sca(ax1)

Yannick DAYER's avatar
Yannick DAYER committed
884 885
    def _draw_fnmrs(self, idx, scores, fnmrs=[], eval=False):
        for line in fnmrs:
Yannick DAYER's avatar
Yannick DAYER committed
886 887 888
            thres_baseline = frr_threshold(
                scores["licit_neg"], scores["licit_pos"], line
            )
889 890 891 892

            axlim = mpl.axis()

            farfrr_licit, farfrr_licit_det = self._get_farfrr(
Yannick DAYER's avatar
Yannick DAYER committed
893
                scores["licit_neg"], scores["licit_pos"], thres_baseline
894 895 896 897 898
            )
            if farfrr_licit is None:
                return

            farfrr_spoof, farfrr_spoof_det = self._get_farfrr(
Yannick DAYER's avatar
Yannick DAYER committed
899 900 901
                scores["spoof"],
                scores["licit_pos"],
                frr_threshold(scores["spoof"], scores["licit_pos"], farfrr_licit[1]),
902 903 904
            )

            if not self._real_data:
905
                # Takes specified FNMR value as EER
906 907 908 909
                mpl.axhline(
                    y=farfrr_licit_det[1],
                    xmin=axlim[2],
                    xmax=axlim[3],
Yannick DAYER's avatar
Yannick DAYER committed
910 911 912 913
                    color="k",
                    linestyle="--",
                    label="%s @ EER" % self._y_label,
                )
914 915 916 917 918
            else:
                mpl.axhline(
                    y=farfrr_licit_det[1],
                    xmin=axlim[0],
                    xmax=axlim[1],
Yannick DAYER's avatar
Yannick DAYER committed
919 920 921 922
                    color="k",
                    linestyle="--",
                    label="%s = %.2f%%" % ("FNMR", farfrr_licit[1] * 100),
                )
923 924

            if not self._real_data:
Yannick DAYER's avatar
Yannick DAYER committed
925 926
                label_licit = "%s @ operating point" % self._x_label
                label_spoof = "IAPMR @ operating point"
927
            else:
Yannick DAYER's avatar
Yannick DAYER committed
928 929
                label_licit = "FMR=%.2f%%" % (farfrr_licit[0] * 100)
                label_spoof = "IAPMR=%.2f%%" % (farfrr_spoof[0] * 100)
930

931
            # Annotations and drawing of the points
932 933
            text_x_offset = 2
            text_y_offset = 5
934
            # Licit
935 936 937 938 939 940 941
            mpl.annotate(
                xy=(farfrr_licit_det[0], farfrr_licit_det[1]),
                text=label_licit,
                xytext=(text_x_offset, text_y_offset),
                textcoords="offset points",
                fontsize="small",
            )
942 943 944
            mpl.plot(
                farfrr_licit_det[0],
                farfrr_licit_det[1],
Yannick DAYER's avatar
Yannick DAYER committed
945
                "o",
Yannick DAYER's avatar
Yannick DAYER committed
946
                color=self._colors[idx],
947
            )  # FAR point, licit scenario
948
            # Spoof
949 950
            axlim = self._axlim or [0.01,99,0.1,99]
            if farfrr_spoof_det[0] > axlim[0] and farfrr_spoof_det[0] < axlim[1]:
951 952 953 954 955 956 957 958 959 960 961 962 963 964
                mpl.annotate(
                    xy=(farfrr_spoof_det[0], farfrr_spoof_det[1]),
                    text=label_spoof,
                    xytext=(text_x_offset, text_y_offset),
                    textcoords="offset points",
                    fontsize="small",
                )
                mpl.plot(
                    farfrr_spoof_det[0],
                    farfrr_spoof_det[1],
                    "o",
                    color="C3",
                )  # FAR point, spoof scenario
            else:
965
                logger.warning(f"The IAPMR for an FNMR of {line} is outside the plot.")
966 967 968


class RocVuln(BaseVulnDetRoc):
Yannick DAYER's avatar
Yannick DAYER committed
969
    """ROC for vuln"""
970 971

    def __init__(self, ctx, scores, evaluation, func_load, real_data, no_spoof):
Yannick DAYER's avatar
Yannick DAYER committed
972 973 974
        super(RocVuln, self).__init__(
            ctx, scores, evaluation, func_load, real_data, no_spoof
        )
975 976
        self._x_label = self._x_label or "FMR"
        self._y_label = self._y_label or "1 - FNMR"
Yannick DAYER's avatar
Yannick DAYER committed
977 978
        self._semilogx = ctx.meta.get("semilogx", True)
        add = ""
Yannick DAYER's avatar
Yannick DAYER committed
979
        if not self._titles:
Yannick DAYER's avatar
Yannick DAYER committed
980
            self._titles = [""] * self._nb_figs
981 982
        if not self._no_spoof:
            add = " and overlaid SPOOF scenario"
Yannick DAYER's avatar
Yannick DAYER committed
983
        for i, t in enumerate(self._titles):
984 985 986 987 988 989
            if self._eval and (i % 2):
                dev_eval = ", eval group"
            elif self._eval:
                dev_eval = ", dev group"
            else:
                dev_eval = ""
Yannick DAYER's avatar
Yannick DAYER committed
990
            self._titles[i] = t or ("ROC: LICIT" + add + dev_eval)
Yannick DAYER's avatar
Yannick DAYER committed
991
        if self._legend_loc == "best":
Yannick DAYER's avatar
Yannick DAYER committed
992
            self._legend_loc = "lower right" if self._semilogx else "upper right"
993

Yannick DAYER's avatar
Yannick DAYER committed
994
    def _plot(self, x, y, s, npoints, **kwargs):
995
        logger.info("Plotting ROC")
996
        plot.roc(
Yannick DAYER's avatar
Yannick DAYER committed
997 998
            x,
            y,
Yannick DAYER's avatar
Yannick DAYER committed
999 1000 1001
            npoints=npoints,
            semilogx=self._semilogx,
            tpr=self._tpr,
1002
            min_far=self._min_dig,
Yannick DAYER's avatar
Yannick DAYER committed
1003 1004 1005
            color=kwargs.get("color"),
            linestyle=kwargs.get("linestyle"),
            label=kwargs.get("label"),
1006
        )
Yannick DAYER's avatar
Yannick DAYER committed
1007 1008
        if not self._no_spoof and s is not None:
            ax1 = mpl.gca()
Yannick DAYER's avatar
Yannick DAYER committed
1009 1010 1011 1012 1013 1014 1015
            ax1.plot(
                [0],
                [0],
                linestyle=":",
                color="C3",
                label="Spoof " + kwargs.get("label"),
            )
Yannick DAYER's avatar
Yannick DAYER committed
1016
            ax2 = ax1.twiny()
Yannick DAYER's avatar
Yannick DAYER committed
1017
            ax2.set_xlabel("IAPMR (%)", color="C3")
Yannick DAYER's avatar
Yannick DAYER committed
1018
            mpl.xticks(rotation=self._x_rotation)
Yannick DAYER's avatar
Yannick DAYER committed
1019 1020 1021 1022
            ax2.tick_params(
                axis="x", colors="C3", labelrotation=self._x_rotation, labelcolor="C3"
            )
            ax2.spines["top"].set_color("C3")
Yannick DAYER's avatar
Yannick DAYER committed
1023
            plot.roc(
Yannick DAYER's avatar
Yannick DAYER committed
1024 1025
                s,
                y,
Yannick DAYER's avatar
Yannick DAYER committed
1026 1027 1028 1029
                npoints=npoints,
                semilogx=self._semilogx,
                tpr=self._tpr,
                min_far=self._min_dig,
Yannick DAYER's avatar
Yannick DAYER committed
1030 1031 1032
                color="C3",
                linestyle=":",
                label="Spoof " + kwargs.get("label"),
Yannick DAYER's avatar
Yannick DAYER committed
1033 1034 1035
            )
            self._set_axis()
            mpl.sca(ax1)
1036 1037 1038 1039 1040 1041

    def _get_farfrr(self, x, y, thres):
        points = farfrr(x, y, thres)
        points2 = (points[0], 1 - points[1])
        return points, points2

Yannick DAYER's avatar
Yannick DAYER committed
1042 1043
    def _draw_fnmrs(self, idx, scores, fnmrs=[], evaluation=False):
        for line in fnmrs:
Yannick DAYER's avatar
Yannick DAYER committed
1044 1045 1046
            thres_baseline = frr_threshold(
                scores["licit_neg"], scores["licit_pos"], line
            )
Yannick DAYER's avatar
Yannick DAYER committed
1047 1048 1049 1050

            axlim = mpl.axis()

            farfrr_licit, farfrr_licit_roc = self._get_farfrr(
Yannick DAYER's avatar
Yannick DAYER committed
1051
                scores["licit_neg"], scores["licit_pos"], thres_baseline
Yannick DAYER's avatar
Yannick DAYER committed
1052 1053 1054 1055 1056
            )
            if farfrr_licit is None:
                return

            farfrr_spoof, farfrr_spoof_roc = self._get_farfrr(
Yannick DAYER's avatar
Yannick DAYER committed
1057 1058 1059
                scores["spoof"],
                scores["licit_pos"],
                frr_threshold(scores["spoof"], scores["licit_pos"], farfrr_licit[1]),
Yannick DAYER's avatar
Yannick DAYER committed
1060 1061 1062 1063 1064 1065 1066
            )

            if not self._real_data and not evaluation:
                mpl.axhline(
                    y=farfrr_licit_roc[1],
                    xmin=axlim[2],
                    xmax=axlim[3],
Yannick DAYER's avatar
Yannick DAYER committed
1067 1068 1069 1070
                    color="k",
                    linestyle="--",
                    label=f"{self._y_label} @ EER",
                )
Yannick DAYER's avatar
Yannick DAYER committed
1071 1072 1073 1074 1075
            elif not evaluation:
                mpl.axhline(
                    y=farfrr_licit_roc[1],
                    xmin=axlim[0],
                    xmax=axlim[1],
Yannick DAYER's avatar
Yannick DAYER committed
1076 1077
                    color="k",
                    linestyle="--",
Yannick DAYER's avatar
Yannick DAYER committed
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
                    label=f"FNMR = {farfrr_licit[1] * 100:.2f}%",
                )

            if not self._real_data:
                label_licit = f"{self._x_label} @ operating point"
                label_spoof = "IAPMR @ operating point"
            else:
                label_licit = f"FMR={farfrr_licit[0] * 100:.2f}%"
                label_spoof = f"IAPMR={farfrr_spoof[0] * 100:.2f}%"

            mpl.plot(
                farfrr_licit_roc[0],
                farfrr_licit_roc[1],
Yannick DAYER's avatar
Yannick DAYER committed
1091
                "o",
Yannick DAYER's avatar
Yannick DAYER committed
1092
                color=self._colors[idx],
Yannick DAYER's avatar
Yannick DAYER committed
1093
                label=label_licit,
Yannick DAYER's avatar
Yannick DAYER committed
1094 1095 1096 1097
            )  # FAR point, licit scenario
            mpl.plot(
                farfrr_spoof_roc[0],
                farfrr_spoof_roc[1],
Yannick DAYER's avatar
Yannick DAYER committed
1098 1099 1100
                "o",
                color="C3",
                label=label_spoof,
Yannick DAYER's avatar
Yannick DAYER committed
1101 1102
            )  # FAR point, spoof scenario

1103

Yannick DAYER's avatar
Yannick DAYER committed
1104
class FmrIapmr(measure_figure.PlotBase):
Yannick DAYER's avatar
Yannick DAYER committed
1105
    """FMR vs IAPMR"""
1106 1107 1108 1109 1110 1111

    def __init__(self, ctx, scores, evaluation, func_load):
        super(FmrIapmr, self).__init__(ctx, scores, evaluation, func_load)
        self._eval = True  # Always ask for eval data
        self._split = False
        self._nb_figs = 1
Yannick DAYER's avatar
Yannick DAYER committed
1112
        self._semilogx = ctx.meta.get("semilogx", False)
Yannick DAYER's avatar
Yannick DAYER committed
1113
        if not self._titles:
Yannick DAYER's avatar
Yannick DAYER committed
1114
            self._titles = [""] * self._nb_figs
Yannick DAYER's avatar
Yannick DAYER committed
1115 1116 1117 1118 1119
        for i, t in enumerate(self._titles):
            self._titles[i] = t or "FMR vs IAPMR"
        self._x_label = self._x_label or "FMR"
        self._y_label = self._y_label or "IAPMR"
        if self._min_arg != 2:
Yannick DAYER's avatar
Yannick DAYER committed
1120 1121 1122
            raise click.BadParameter(
                "You must provide 2 scores files: " "scores-{dev,eval}.csv"
            )
1123 1124

    def compute(self, idx, input_scores, input_names):
Yannick DAYER's avatar
Yannick DAYER committed
1125
        """ Implements plots"""
Yannick DAYER's avatar
Yannick DAYER committed
1126 1127 1128
        dev_scores = clean_scores(input_scores[0])
        if self._eval:
            eval_scores = clean_scores(input_scores[1])
1129 1130 1131
        fmr_list = np.linspace(0, 1, 100)
        iapmr_list = []
        for i, fmr in enumerate(fmr_list):
Yannick DAYER's avatar
Yannick DAYER committed
1132 1133
            thr = far_threshold(dev_scores["licit_neg"], dev_scores["licit_pos"], fmr)
            iapmr_list.append(farfrr(eval_scores["spoof"], [0.0], thr)[0])
1134 1135
            # re-calculate fmr since threshold might give a different result
            # for fmr.
Yannick DAYER's avatar
Yannick DAYER committed
1136 1137
            fmr_list[i], _ = farfrr(eval_scores["licit_neg"], [0.0], thr)
        label = self._legends[idx] if self._legends is not None else f"system {idx+1}"
1138
        logger.info(f"Plot FmrIapmr using: {input_names[1]}")
1139 1140 1141 1142
        if self._semilogx:
            mpl.semilogx(fmr_list, iapmr_list, label=label)
        else:
            mpl.plot(fmr_list, iapmr_list, label=label)