figure.py 28.9 KB
Newer Older
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
'''Runs error analysis on score sets, outputs metrics and plots'''

from __future__ import division, print_function
from abc import ABCMeta, abstractmethod
import sys
import ntpath
import numpy
import click
import matplotlib
import matplotlib.pyplot as mpl
from matplotlib.backends.backend_pdf import PdfPages
from tabulate import tabulate
from .. import plot
from .. import utils

LINESTYLES = [
    (0, ()),                    #solid
    (0, (4, 4)),                #dashed
    (0, (1, 5)),                #dotted
    (0, (3, 5, 1, 5)),          #dashdotted
    (0, (3, 5, 1, 5, 1, 5)),    #dashdotdotted
    (0, (5, 1)),                #densely dashed
    (0, (1, 1)),                #densely dotted
    (0, (3, 1, 1, 1)),          #densely dashdotted
    (0, (3, 1, 1, 1, 1, 1)),    #densely dashdotdotted
    (0, (5, 10)),               #loosely dashed
    (0, (3, 10, 1, 10)),        #loosely dashdotted
    (0, (3, 10, 1, 10, 1, 10)), #loosely dashdotdotted
    (0, (1, 10))                #loosely dotted
]

class MeasureBase(object):
    """Base class for metrics and plots.
    This abstract class define the framework to plot or compute metrics from a
    list of (positive, negative) scores tuples.

    Attributes
    ----------

    _scores: :any:`list`:
41
        List of input files (e.g. dev-{1, 2, 3}, {dev,eval}-scores1
42 43 44 45

    _ctx : :py:class:`dict`
        Click context dictionary.

46 47 48 49 50
    _eval : :py:class:`bool`
        True if eval data are used

    _titles: :any:`list`
        List of titles for each system (dev + (eval) scores)
51 52 53 54 55 56

    func_load:
        Function that is used to load the input files

    """
    __metaclass__ = ABCMeta #for python 2.7 compatibility
57
    def __init__(self, ctx, scores, eval, func_load):
58 59 60 61 62 63 64 65
        """
        Parameters
        ----------

        ctx : :py:class:`dict`
            Click context dictionary.

        scores : :any:`list`:
66 67 68 69
            List of input files (e.g. dev-{1, 2, 3}, {dev,eval}-scores1
            {dev,eval}-scores2)
        eval : :py:class:`bool`
            True if eval data are used
70 71 72
        func_load : Function that is used to load the input files
        """
        self._scores = scores
73
        self._min_arg = 1 if 'min_arg' not in ctx.meta else ctx.meta['min_arg']
74 75
        self._ctx = ctx
        self.func_load = func_load
76
        self.dev_names, self.eval_names, self.dev_scores, self.eval_scores = \
77
                self._load_files()
78 79 80 81 82 83
        self.n_sytem = len(self.dev_names[0]) # at least one set of dev scores
        self._titles = None if 'titles' not in ctx.meta else ctx.meta['titles']
        if self._titles is not None and len(self._titles) != self.n_sytem:
            raise click.BadParameter("Number of titles must be equal to the "
                                     "number of systems")
        self._eval = eval
84 85 86 87 88 89 90 91 92 93 94 95 96

    def run(self):
        """ Generate outputs (e.g. metrics, files, pdf plots).
        This function calls abstract methods
        :func:`~bob.measure.script.figure.MeasureBase.init_process` (before
        loop), :py:func:`~bob.measure.script.figure.MeasureBase.compute`
        (in the loop iterating through the different
        systems) and :py:func:`~bob.measure.script.figure.MeasureBase.end_process`
        (after the loop).
        """
        #init matplotlib, log files, ...
        self.init_process()
        #iterates through the different systems and feed `compute`
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        #with the dev (and eval) scores of each system
        # Note that more than one dev or eval scores score can be passed to
        # each system
        for idx in range(self.n_sytem):
            dev_score = []
            eval_score = []
            dev_file = []
            eval_file = []
            for arg in range(self._min_arg):
                dev_score.append(self.dev_scores[arg][idx])
                dev_file.append(self.dev_names[arg][idx])
                eval_score.append(self.eval_scores[arg][idx] \
                        if self.eval_scores[arg] is not None else None)
                eval_file.append(self.eval_names[arg][idx] \
                        if self.eval_names[arg] is not None else None)
            if self._min_arg == 1: # most of measure only take one arg
                                   # so do not pass a list of one arg
                #does the main computations/plottings here
                self.compute(idx, dev_score[0], dev_file[0], eval_score[0],
                             eval_file[0])
            else:
                #does the main computations/plottings here
                self.compute(idx, dev_score, dev_file, eval_score, eval_file)
120 121 122 123 124 125 126 127 128 129 130 131
        #setup final configuration, plotting properties, ...
        self.end_process()

    #protected functions that need to be overwritten
    def init_process(self):
        """ Called in :py:func:`~bob.measure.script.figure.MeasureBase`.run
        before iterating through the different sytems.
        Should reimplemented in derived classes"""
        pass

    #Main computations are done here in the subclasses
    @abstractmethod
132
    def compute(self, idx, dev_score, dev_file=None,
133
                eval_score=None, eval_file=None):
134
        """Compute metrics or plots from the given scores provided by
135 136 137 138 139 140 141 142 143
        :py:func:`~bob.measure.script.figure.MeasureBase.run`.
        Should reimplemented in derived classes

        Parameters
        ----------

        idx : :obj:`int`
            index of the system

144 145 146
        dev_score:
            Development scores. Can be a tuple (neg, pos) of
            :py:class:`numpy.ndarray` (e.g.
147
            :py:func:`~bob.measure.script.figure.Roc.compute`) or
148
            a :any:`list` of tuples of :py:class:`numpy.ndarray` (e.g. cmc)
149 150
        dev_file : str
            name of the dev file without extension
151 152
        eval_score:
            eval scores. Can be a tuple (neg, pos) of
153
            :py:class:`numpy.ndarray` (e.g.
154
            :py:func:`~bob.measure.script.figure.Roc.compute`) or
155
            a :any:`list` of tuples of :py:class:`numpy.ndarray` (e.g. cmc)
156 157
        eval_file : str
            name of the eval file without extension
158 159 160 161 162 163
        """
        pass

    #Things to do after the main iterative computations are done
    @abstractmethod
    def end_process(self):
164 165 166
        """ Called in :py:func:`~bob.measure.script.figure.MeasureBase`.run
        after iterating through the different sytems.
        Should reimplemented in derived classes"""
167 168 169 170 171 172 173 174 175 176
        pass

    #common protected functions

    def _load_files(self):
        ''' Load the input files and returns

        Returns
        -------

177 178 179 180 181
            dev_scores: :any:`list`: A list that contains, for each required
            dev score file, the output of ``func_load``
            eval_scores: :any:`list`: A list that contains, for each required
            eval score file, the output of ``func_load``
        '''
182 183 184 185 186 187 188 189 190 191

        def _extract_file_names(filenames):
            if filenames is None:
                return None
            res = []
            for file_path in filenames:
                _, name = ntpath.split(file_path)
                res.append(name.split(".")[0])
            return res

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        dev_scores = []
        eval_scores = []
        dev_files = []
        eval_files = []
        for arg in range(self._min_arg):
            key = 'dev_scores_%d' % arg
            dev_paths = self._scores if key not in self._ctx.meta else \
                    self._ctx.meta[key]
            key = 'eval_scores_%d' % arg
            eval_paths = None if key not in self._ctx.meta else \
                    self._ctx.meta[key]
            dev_files.append(_extract_file_names(dev_paths))
            eval_files.append(_extract_file_names(eval_paths))
            dev_scores.append(self.func_load(dev_paths))
            eval_scores.append(self.func_load(eval_paths))
        return (dev_files, eval_files, dev_scores, eval_scores)

    def _process_scores(self, dev_score, eval_score):
        '''Process score files and return neg/pos/fta for eval and dev'''
        dev_neg = dev_pos = dev_fta = eval_neg = eval_pos = eval_fta = None
212 213 214 215 216 217
        if dev_score[0] is not None:
            dev_score, dev_fta = utils.get_fta(dev_score)
            dev_neg, dev_pos = dev_score
            if dev_neg is None:
                raise click.UsageError("While loading dev-score file")

218 219 220 221 222
        if self._eval and eval_score is not None and eval_score[0] is not None:
            eval_score, eval_fta = utils.get_fta(eval_score)
            eval_neg, eval_pos = eval_score
            if eval_neg is None:
                raise click.UsageError("While loading eval-score file")
223

224
        return (dev_neg, dev_pos, dev_fta, eval_neg, eval_pos, eval_fta)
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241


class Metrics(MeasureBase):
    ''' Compute metrics from score files

    Attributes
    ----------

    _tablefmt: str
        Table format

    _criter: str
        Criterion to compute threshold, see :py:func:`bob.measure.utils.get_thres`

    _open_mode: str
        Open mode of the output file (e.g. `w`, `a+`)

242 243 244 245 246 247
    _thres: :any:`list`
        If given, uses those threshold instead of computing them. Lenght of the
        list must be the same as the number of systems.

    _far: :obj:`float`
        If given, uses this FAR to compute threshold
248 249 250 251 252 253 254 255

    _log: str
        Path to output log file

    log_file: str
        output stream

    '''
256 257
    def __init__(self, ctx, scores, evaluation, func_load):
        super(Metrics, self).__init__(ctx, scores, evaluation, func_load)
258 259 260 261 262 263
        self._tablefmt = None if 'tablefmt' not in ctx.meta else\
                ctx.meta['tablefmt']
        self._criter = None if 'criter' not in ctx.meta else ctx.meta['criter']
        self._open_mode = None if 'open_mode' not in ctx.meta else\
                ctx.meta['open_mode']
        self._thres = None if 'thres' not in ctx.meta else ctx.meta['thres']
264 265 266 267 268 269 270 271 272 273
        if self._thres is not None :
            if len(self._thres) == 1:
                self._thres = self._thres * len(self.dev_names)
            elif len(self._thres) != len(self.dev_names):
                raise click.BadParameter(
                    '#thresholds must be the same as #systems (%d)' \
                    % len(self.dev_names)
                )
        self._far = None if 'far_value' not in ctx.meta else \
        ctx.meta['far_value']
274 275 276 277 278
        self._log = None if 'log' not in ctx.meta else ctx.meta['log']
        self.log_file = sys.stdout
        if self._log is not None:
            self.log_file = open(self._log, self._open_mode)

279
    def compute(self, idx, dev_score, dev_file=None,
280
                eval_score=None, eval_file=None):
281
        ''' Compute metrics thresholds and tables (FAR, FMR, FNMR, HTER) for
282
        given system inputs'''
283 284
        dev_neg, dev_pos, dev_fta, eval_neg, eval_pos, eval_fta =\
                self._process_scores(dev_score, eval_score)
285 286
        threshold = utils.get_thres(self._criter, dev_neg, dev_pos, self._far) \
                if self._thres is None else self._thres[idx]
287
        title = self._titles[idx] if self._titles is not None else None
288
        if self._thres is None:
289 290 291 292
            far_str = ''
            if self._criter == 'far' and self._far is not None:
                far_str = str(self._far)
            click.echo("[Min. criterion: %s %s] Threshold on Development set `%s`: %e"\
293
                       % (self._criter.upper(), far_str, title or dev_file, threshold),
294 295 296 297
                       file=self.log_file)
        else:
            click.echo("[Min. criterion: user provider] Threshold on "
                       "Development set `%s`: %e"\
298
                       % (dev_file or title, threshold), file=self.log_file)
299 300 301 302 303 304 305 306 307 308 309 310 311


        from .. import farfrr
        dev_fmr, dev_fnmr = farfrr(dev_neg, dev_pos, threshold)
        dev_far = dev_fmr * (1 - dev_fta)
        dev_frr = dev_fta + dev_fnmr * (1 - dev_fta)
        dev_hter = (dev_far + dev_frr) / 2.0

        dev_ni = dev_neg.shape[0]  # number of impostors
        dev_fm = int(round(dev_fmr * dev_ni))  # number of false accepts
        dev_nc = dev_pos.shape[0]  # number of clients
        dev_fnm = int(round(dev_fnmr * dev_nc))  # number of false rejects

312 313 314 315 316 317 318 319 320
        dev_fta_str = "%.1f%%" % (100 * dev_fta)
        dev_fmr_str = "%.1f%% (%d/%d)" % (100 * dev_fmr, dev_fm, dev_ni)
        dev_fnmr_str = "%.1f%% (%d/%d)" % (100 * dev_fnmr, dev_fnm, dev_nc)
        dev_far_str = "%.1f%%" % (100 * dev_far)
        dev_frr_str = "%.1f%%" % (100 * dev_frr)
        dev_hter_str = "%.1f%%" % (100 * dev_hter)
        headers = ['' or title, 'Development %s' % dev_file]
        raws = [['FtA', dev_fta_str],
                ['FMR', dev_fmr_str],
321 322 323 324 325
                ['FNMR', dev_fnmr_str],
                ['FAR', dev_far_str],
                ['FRR', dev_frr_str],
                ['HTER', dev_hter_str]]

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
        if self._eval and eval_neg is not None:
            # computes statistics for the eval set based on the threshold a priori
            eval_fmr, eval_fnmr = farfrr(eval_neg, eval_pos, threshold)
            eval_far = eval_fmr * (1 - eval_fta)
            eval_frr = eval_fta + eval_fnmr * (1 - eval_fta)
            eval_hter = (eval_far + eval_frr) / 2.0

            eval_ni = eval_neg.shape[0]  # number of impostors
            eval_fm = int(round(eval_fmr * eval_ni))  # number of false accepts
            eval_nc = eval_pos.shape[0]  # number of clients
            eval_fnm = int(round(eval_fnmr * eval_nc))  # number of false rejects

            eval_fta_str = "%.1f%%" % (100 * eval_fta)
            eval_fmr_str = "%.1f%% (%d/%d)" % (100 * eval_fmr, eval_fm, eval_ni)
            eval_fnmr_str = "%.1f%% (%d/%d)" % (100 * eval_fnmr, eval_fnm, eval_nc)

            eval_far_str = "%.1f%%" % (100 * eval_far)
            eval_frr_str = "%.1f%%" % (100 * eval_frr)
            eval_hter_str = "%.1f%%" % (100 * eval_hter)

            headers.append('Eval. % s' % eval_file)
            raws[0].append(eval_fta_str)
            raws[1].append(eval_fmr_str)
            raws[2].append(eval_fnmr_str)
            raws[3].append(eval_far_str)
            raws[4].append(eval_frr_str)
            raws[5].append(eval_hter_str)
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

        click.echo(tabulate(raws, headers, self._tablefmt), file=self.log_file)

    def end_process(self):
        ''' Close log file if needed'''
        if self._log is not None:
            self.log_file.close()

class PlotBase(MeasureBase):
    ''' Base class for plots. Regroup several options and code
    shared by the different plots

    Attributes
    ----------

    _output: str
        Path to the output pdf file

    _points: :obj:`int`
        Number of points used to draw curves


    _split: :obj:`bool`
376
        If False, dev and eval curves will be printed on the some figure
377

378 379
    _axlim: :any:`list`
        Minimum/Maximum values for the X and Y axes
380 381 382 383 384 385 386

    _x_rotation: :obj:`int`
        Rotation of the X axis labels

    _axisfontsize: :obj:`int`
        Axis font size
    '''
387 388
    def __init__(self, ctx, scores, evaluation, func_load):
        super(PlotBase, self).__init__(ctx, scores, evaluation, func_load)
389 390 391
        self._output = None if 'output' not in ctx.meta else ctx.meta['output']
        self._points = None if 'points' not in ctx.meta else ctx.meta['points']
        self._split = None if 'split' not in ctx.meta else ctx.meta['split']
392
        self._axlim = None if 'axlim' not in ctx.meta else ctx.meta['axlim']
393 394 395 396
        self._clayout = None if 'clayout' not in ctx.meta else\
        ctx.meta['clayout']
        self._print_fn = False if 'show_fn' not in ctx.meta else\
        ctx.meta['show_fn']
397 398
        self._x_rotation = None if 'x_rotation' not in ctx.meta else \
                ctx.meta['x_rotation']
399
        self._axisfontsize = 6 if 'fontsize' not in ctx.meta else \
400 401
                ctx.meta['fontsize']

402
        self._nb_figs = 2 if self._eval and self._split else 1
403 404 405 406 407 408 409 410 411
        self._multi_plots = len(self.dev_scores) > 1
        self._colors = utils.get_colors(len(self.dev_scores))
        self._states = ['Development', 'Evaluation']
        self._title = ''
        self._x_label = 'FMR (%)'
        self._y_label = 'FNMR (%)'
        self._grid_color = 'silver'
        self._pdf_page = None
        self._end_setup_plot = True
412
        self._kwargs = {}
413 414 415 416 417 418 419 420 421

    def init_process(self):
        ''' Open pdf and set axis font size if provided '''
        if not hasattr(matplotlib, 'backends'):
            matplotlib.use('pdf')

        self._pdf_page = self._ctx.meta['PdfPages'] if 'PdfPages'in \
        self._ctx.meta else PdfPages(self._output)

422 423 424 425 426 427
        for i in range(self._nb_figs):
            fig = mpl.figure(i + 1)
            fig.clear()
            if self._axisfontsize is not None:
                mpl.rc('xtick', labelsize=self._axisfontsize)
                mpl.rc('ytick', labelsize=self._axisfontsize)
428 429 430
                mpl.rc('legend', fontsize=6)
                mpl.rc('axes', labelsize=8)
                #mpl.rcParams['figure.constrained_layout.use'] = self._clayout
431 432

    def end_process(self):
433
        ''' Set title, legend, axis labels, grid colors, save figures and
434 435 436 437 438 439
        close pdf is needed '''
        #only for plots
        if self._end_setup_plot:
            for i in range(self._nb_figs):
                fig = mpl.figure(i + 1)
                title = self._title
440
                if not self._eval:
441
                    title += (" (%s)" % self._states[0])
442
                elif self._split:
443 444 445 446 447 448
                    title += (" (%s)" % self._states[i])
                mpl.title(title)
                mpl.xlabel(self._x_label)
                mpl.ylabel(self._y_label)
                mpl.grid(True, color=self._grid_color)
                mpl.legend()
449
                self._set_axis()
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                #gives warning when applied with mpl
                fig.set_tight_layout(True)
                mpl.xticks(rotation=self._x_rotation)
                self._pdf_page.savefig(fig)

        #do not want to close PDF when running evaluate
        if 'PdfPages' in self._ctx.meta and \
           ('closef' not in self._ctx.meta or self._ctx.meta['closef']):
            self._pdf_page.close()


    #common protected functions

    def _label(self, base, name, idx):
        if self._titles is not None and len(self._titles) > idx:
            return self._titles[idx]
        if self._multi_plots:
            return base + (" %d (%s)" % (idx + 1, name))
        return base + (" (%s)" % name)

470
    def _set_axis(self):
471 472 473 474
        if self._axlim is not None and None not in self._axlim:
            mpl.axis(self._axlim)
        else:
            mpl.axes().autoscale()
475

476 477 478 479 480 481 482 483
class Roc(PlotBase):
    ''' Handles the plotting of ROC

    Attributes
    ----------

    _semilogx: :obj:`bool`
        If true, X-axis will be semilog10
484 485 486

    _fmr_at: :obj:`float`
        If not None, plot a vertical line at this value on the dev plot and
487
        corresponding dots on the eval plot (if any).
488
    '''
489 490
    def __init__(self, ctx, scores, evaluation, func_load):
        super(Roc, self).__init__(ctx, scores, evaluation, func_load)
491
        self._semilogx = True if 'semilogx' not in ctx.meta else\
492 493 494 495 496 497
        ctx.meta['semilogx']
        self._fmr_at = None if 'fmr_at' not in ctx.meta else\
        ctx.meta['fmr_at']
        self._title = 'ROC'
        self._x_label = 'FMR'
        self._y_label = ("1 - FNMR" if self._semilogx else "FNMR")
498 499 500
        #custom defaults
        if self._axlim is None:
            self._axlim = [1e-4, 1.0, 1e-4, 1.0]
501

502
    def compute(self, idx, dev_score, dev_file=None,
503
                eval_score=None, eval_file=None):
504 505
        ''' Plot ROC for dev and eval data using
        :py:func:`bob.measure.plot.roc`'''
506 507
        dev_neg, dev_pos, _, eval_neg, eval_pos, _ =\
                self._process_scores(dev_score, eval_score)
508
        mpl.figure(1)
509
        if self._eval:
510 511 512 513
            linestyle = '-' if not self._split else LINESTYLES[idx % 14]
            plot.roc(
                dev_neg, dev_pos, self._points, self._semilogx,
                color=self._colors[idx], linestyle=linestyle,
514
                label=self._label('development', dev_file, idx, **self._kwargs)
515 516 517 518 519 520 521
            )
            linestyle = '--'
            if self._split:
                mpl.figure(2)
                linestyle = LINESTYLES[idx % 14]

            plot.roc(
522
                eval_neg, eval_pos, self._points, self._semilogx,
523
                color=self._colors[idx], linestyle=linestyle,
524
                label=self._label('eval', eval_file, idx, **self._kwargs)
525 526 527
            )
            if self._fmr_at is not None:
                from .. import farfrr
528
                eval_fmr, eval_fnmr = farfrr(eval_neg, eval_pos, self._fmr_at)
529
                if self._semilogx:
530 531
                    eval_fnmr = 1 - eval_fnmr
                mpl.scatter(eval_fmr, eval_fnmr, c=self._colors[idx], s=30)
532 533 534 535
        else:
            plot.roc(
                dev_neg, dev_pos, self._points, self._semilogx,
                color=self._colors[idx], linestyle=LINESTYLES[idx % 14],
536
                label=self._label('development', dev_file, idx, **self._kwargs)
537 538 539 540
            )

    def end_process(self):
        ''' Draw vertical line on the dev plot at the given fmr and print the
541
        corresponding points on the eval plot for all the systems '''
542 543 544 545 546 547 548 549
        #draw vertical lines
        if self._fmr_at is not None:
            mpl.figure(1)
            mpl.plot([self._fmr_at, self._fmr_at], [0., 1.], "--", color='black')
        super(Roc, self).end_process()

class Det(PlotBase):
    ''' Handles the plotting of DET '''
550 551
    def __init__(self, ctx, scores, evaluation, func_load):
        super(Det, self).__init__(ctx, scores, evaluation, func_load)
552
        self._title = 'DET'
553 554 555
        #custom defaults here
        if self._x_rotation is None:
            self._x_rotation = 50
556

557
    def compute(self, idx, dev_score, dev_file=None,
558
                eval_score=None, eval_file=None):
559 560
        ''' Plot DET for dev and eval data using
        :py:func:`bob.measure.plot.det`'''
561 562
        dev_neg, dev_pos, _, eval_neg, eval_pos, _ =\
                self._process_scores(dev_score, eval_score)
563
        mpl.figure(1)
564
        if self._eval and eval_neg is not None:
565 566 567 568
            linestyle = '-' if not self._split else LINESTYLES[idx % 14]
            plot.det(
                dev_neg, dev_pos, self._points, color=self._colors[idx],
                linestyle=linestyle, axisfontsize=self._axisfontsize,
569
                label=self._label('development', dev_file, idx, **self._kwargs)
570 571 572 573 574
            )
            if self._split:
                mpl.figure(2)
            linestyle = '--' if not self._split else LINESTYLES[idx % 14]
            plot.det(
575
                eval_neg, eval_pos, self._points, color=self._colors[idx],
576
                linestyle=linestyle, axisfontsize=self._axisfontsize,
577
                label=self._label('eval', eval_file, idx, **self._kwargs)
578 579 580 581 582
            )
        else:
            plot.det(
                dev_neg, dev_pos, self._points, color=self._colors[idx],
                linestyle=LINESTYLES[idx % 14], axisfontsize=self._axisfontsize,
583
                label=self._label('development', dev_file, idx, **self._kwargs)
584 585
            )

586
    def _set_axis(self):
587 588 589 590
        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])
591 592 593

class Epc(PlotBase):
    ''' Handles the plotting of EPC '''
594 595 596 597
    def __init__(self, ctx, scores, evaluation, func_load):
        super(Epc, self).__init__(ctx, scores, evaluation, func_load)
        if 'eval_scores_0' not in self._ctx.meta:
            raise click.UsageError("EPC requires dev and eval score files")
598 599 600
        self._title = 'EPC'
        self._x_label = 'Cost'
        self._y_label = 'Min. HTER (%)'
601
        self._eval = True #always eval data with EPC
602
        self._split = False
603
        self._nb_figs = 1
604

605
    def compute(self, idx, dev_score, dev_file, eval_score, eval_file=None):
606 607
        ''' Plot EPC using
        :py:func:`bob.measure.plot.epc`'''
608 609
        dev_neg, dev_pos, _, eval_neg, eval_pos, _ =\
                self._process_scores(dev_score, eval_score)
610
        plot.epc(
611
            dev_neg, dev_pos, eval_neg, eval_pos, self._points,
612
            color=self._colors[idx], linestyle=LINESTYLES[idx % 14],
613
            label=self._label('curve', dev_file + "_" + eval_file, idx, **self._kwargs)
614 615 616
        )

class Hist(PlotBase):
617
    ''' Functional base class for histograms
618 619 620 621 622 623 624

    Attributes
    ----------

    _nbins: :obj:`int`, str
    Number of bins. Default: `auto`

625 626 627
    _thres: :any:`list`
        If given, uses those threshold instead of computing them. Lenght of the
        list must be the same as the number of systems.
628 629 630 631

    _criter: str
        Criterion to compute threshold (eer or hter)
    '''
632 633
    def __init__(self, ctx, scores, evaluation, func_load):
        super(Hist, self).__init__(ctx, scores, evaluation, func_load)
634 635
        self._nbins = None if 'nbins' not in ctx.meta else ctx.meta['nbins']
        self._thres = None if 'thres' not in ctx.meta else ctx.meta['thres']
636 637
        self._show_dev = ((not self._eval) if 'show_dev' not in ctx.meta else\
                ctx.meta['show_dev']) or not self._eval
638 639 640 641 642 643 644 645
        if self._thres is not None and len(self._thres) != len(self.dev_names):
            if len(self._thres) == 1:
                self._thres = self._thres * len(self.dev_names)
            else:
                raise click.BadParameter(
                    '#thresholds must be the same as #systems (%d)' \
                    % len(self.dev_names)
                )
646
        self._criter = None if 'criter' not in ctx.meta else ctx.meta['criter']
647 648 649 650
        self._y_label = 'Dev. probability density' if self._eval else \
                'density'
        self._x_label = 'Scores' if not self._eval else ''
        self._title_base = 'Scores'
651 652
        self._end_setup_plot = False

653
    def compute(self, idx, dev_score, dev_file=None,
654
                eval_score=None, eval_file=None):
655
        ''' Draw histograms of negative and positive scores.'''
656 657
        dev_neg, dev_pos, eval_neg, eval_pos, threshold = \
        self._get_neg_pos_thres(idx, dev_score, eval_score)
658 659

        fig = mpl.figure()
660 661
        mpl.title(self._get_title(dev_file, eval_file))
        if eval_neg is not None and self._show_dev:
662
            mpl.subplot(2, 1, 1)
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
            mpl.title(self._get_title(dev_file, eval_file))
        if self._show_dev:
            self._setup_hist(dev_neg, dev_pos)
            mpl.ylabel(self._y_label)
            mpl.xlabel(self._x_label)
            if eval_neg is not None and self._show_dev:
                ax = mpl.gca()
                ax.axes.get_xaxis().set_ticklabels([])
            #Setup lines, corresponding axis and legends
            self._lines(threshold, dev_neg, dev_pos)
            if self._eval:
                self._plot_legends()

        if eval_neg is not None:
            if self._show_dev:
                mpl.subplot(2, 1, 2)
            self._setup_hist(
                eval_neg, eval_pos
681
            )
682
            mpl.ylabel('Eval. probability density')
683
            mpl.xlabel(self._x_label)
684 685 686 687
            #Setup lines, corresponding axis and legends
            self._lines(threshold, eval_neg, eval_pos)
            if not self._show_dev:
                self._plot_legends()
688 689 690

        fig.set_tight_layout(True)
        self._pdf_page.savefig(fig)
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

    def _get_title(self, dev_file, eval_file):
        title = self._title_base if not self._print_fn else \
                ('%s (%s)' % (
                    self._title_base,
                    dev_file + (" / %s" % eval_file if self._eval else "")
                ))
        return title

    def _plot_legends(self):
        lines = []
        labels = []
        for ax in mpl.gcf().get_axes():
            li, la = ax.get_legend_handles_labels()
            lines += li
            labels += la
        if self._show_dev and self._eval:
            mpl.legend(
                lines, labels, loc='upper center', ncol=6,
                bbox_to_anchor=(0.5, -0.01), fontsize=6
            )
        else:
            mpl.legend(lines, labels,
                       loc='best', fancybox=True, framealpha=0.5)


    def _get_neg_pos_thres(self, idx, dev_score, eval_score):
        dev_neg, dev_pos, _, eval_neg, eval_pos, _ = self._process_scores(
            dev_score, eval_score
        )
        threshold = utils.get_thres(
            self._criter, dev_neg,
            dev_pos
        ) if self._thres is None else self._thres[idx]
        return (dev_neg, dev_pos, eval_neg, eval_pos, threshold)

    def _density_hist(self, scores, **kwargs):
        n, bins, patches = mpl.hist(
            scores, normed=True, bins=self._nbins, **kwargs
        )
        return (n, bins, patches)

    def _lines(self, threshold, neg=None, pos=None, **kwargs):
        label = 'Threshold' if self._criter is None else self._criter.upper()
        kwargs.setdefault('color', 'C3')
        kwargs.setdefault('linestyle', '--')
        kwargs.setdefault('label', label)
        _, _, ymax, ymin = mpl.axis()
        # plot a vertical threshold line
        mpl.axvline(x=threshold, ymin=ymin, ymax=ymax, **kwargs)

    def _setup_hist(self, neg, pos):
        ''' This function can be overwritten in derived classes'''
        self._density_hist(
            pos, label='Positives', alpha=0.5, color='blue', **self._kwargs
        )
        self._density_hist(
            neg, label='Negatives', alpha=0.5, color='red', **self._kwargs
        )