common_options.py 34 KB
Newer Older
1 2
'''Stores click common options for plots'''

3
import functools
4 5
import logging
import click
6
from click.types import INT, FLOAT
7
import matplotlib.pyplot as plt
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
8
import tabulate
9
from matplotlib.backends.backend_pdf import PdfPages
10
from bob.extension.scripts.click_helper import (
11 12 13
    bool_option, list_float_option, verbosity_option, open_file_mode_option,
    CONTEXT_SETTINGS
)
14

15
LOGGER = logging.getLogger(__name__)
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
16

17
def scores_argument(min_arg=1, force_eval=False, **kwargs):
18
    """Get the argument for scores, and add `dev-scores` and `eval-scores` in
19
    the context when `--eval` flag is on (default)
20 21 22

    Parameters
    ----------
23 24
    min_arg : int
        the minimum number of file needed to evaluate a system. For example,
25
        vulnerability analysis needs licit and spoof and therefore min_arg = 2
26 27 28

    Returns
    -------
29 30
     callable
      A decorator to be used for adding score arguments for click commands
31
    """
32 33
    def custom_scores_argument(func):
        def callback(ctx, param, value):
34 35 36
            min_a = min_arg or 1
            mutli = 1
            error = ''
37
            if ('evaluation' in ctx.meta and ctx.meta['evaluation']) or force_eval:
38 39 40 41 42
                mutli += 1
                error += '- %d evaluation file(s) \n' % min_a
            if 'train' in ctx.meta and ctx.meta['train']:
                mutli += 1
                error += '- %d training file(s) \n' % min_a
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
43
            # add more test here if other inputs are needed
44 45 46 47

            min_a *= mutli
            ctx.meta['min_arg'] = min_a
            if len(value) < 1 or len(value) % ctx.meta['min_arg'] != 0:
48
                raise click.BadParameter(
49 50 51 52
                    'The number of provided scores must be > 0 and a multiple of %d '
                    'because the following files are required:\n'
                    '- %d development file(s)\n' % (min_a, min_arg or 1) +
                    error, ctx=ctx
53
                )
54
            ctx.meta['scores'] = value
55
            return value
56 57 58 59
        return click.argument(
            'scores', type=click.Path(exists=True),
            callback=callback, **kwargs
        )(func)
60 61
    return custom_scores_argument

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
62

63 64 65 66 67 68 69 70
def no_legend_option(dflt=True, **kwargs):
    '''Get option flag to say if legend should be displayed or not'''
    return bool_option(
        'disp-legend', 'dl', 'If set, no legend will be printed.',
        dflt=dflt
    )


71 72
def eval_option(**kwargs):
    '''Get option flag to say if eval-scores are provided'''
73 74 75 76 77 78 79 80 81 82 83 84
    def custom_eval_option(func):
        def callback(ctx, param, value):
            ctx.meta['evaluation'] = value
            return value
        return click.option(
            '-e', '--eval', 'evaluation', is_flag=True, default=False,
            show_default=True,
            help='If set, evaluation scores must be provided',
            callback=callback, **kwargs)(func)
    return custom_eval_option


85 86 87 88 89 90 91 92 93 94 95 96
def hide_dev_option(dflt=False, **kwargs):
    '''Get option flag to say if dev plot should be hidden'''
    def custom_hide_dev_option(func):
        def callback(ctx, param, value):
            ctx.meta['hide_dev'] = value
            return value
        return click.option(
            '--hide-dev', is_flag=True, default=dflt,
            show_default=True,
            help='If set, hide dev related plots',
            callback=callback, **kwargs)(func)
    return custom_hide_dev_option
97

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
98

99 100
def sep_dev_eval_option(dflt=True, **kwargs):
    '''Get option flag to say if dev and eval plots should be in different
101
    plots'''
102
    return bool_option(
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
103
        'split', 's', 'If set, evaluation and dev curve in different plots',
104
        dflt
105 106
    )

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
107

108 109 110 111 112
def linestyles_option(dflt=False, **kwargs):
    ''' Get option flag to turn on/off linestyles'''
    return bool_option('line-linestyles', 'S', 'If given, applies a different '
                       'linestyles to each line.', dflt, **kwargs)

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
113

114 115
def cmc_option(**kwargs):
    '''Get option flag to say if cmc scores'''
116 117
    return bool_option('cmc', 'C', 'If set, CMC score files are provided',
                       **kwargs)
118

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
119

120
def semilogx_option(dflt=False, **kwargs):
121
    '''Option to use semilog X-axis'''
122 123
    return bool_option('semilogx', 'G', 'If set, use semilog on X axis', dflt,
                       **kwargs)
124

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
125

126
def print_filenames_option(dflt=True, **kwargs):
127
    '''Option to tell if filenames should be in the title'''
128 129
    return bool_option('show-fn', 'P', 'If set, show filenames in title', dflt,
                       **kwargs)
130

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
131

132 133
def const_layout_option(dflt=True, **kwargs):
    '''Option to set matplotlib constrained_layout'''
134 135 136 137 138 139 140 141 142 143
    def custom_layout_option(func):
        def callback(ctx, param, value):
            ctx.meta['clayout'] = value
            plt.rcParams['figure.constrained_layout.use'] = value
            return value
        return click.option(
            '-Y', '--clayout/--no-clayout', default=dflt, show_default=True,
            help='(De)Activate constrained layout',
            callback=callback, **kwargs)(func)
    return custom_layout_option
144

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
145

146
def axes_val_option(dflt=None, **kwargs):
147
    ''' Option for setting min/max values on axes '''
148 149
    return list_float_option(
        name='axlim', short_name='L',
150 151
        desc='min/max axes values separated by commas (e.g. ``--axlim '
        ' 0.1,100,0.1,100``)',
152 153 154
        nitems=4, dflt=dflt, **kwargs
    )

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
155

156
def thresholds_option(**kwargs):
157
    ''' Option to give a list of thresholds '''
158 159
    return list_float_option(
        name='thres', short_name='T',
160 161
        desc='Given threshold for metrics computations, e.g. '
        '0.005,0.001,0.056',
162 163
        nitems=None, dflt=None, **kwargs
    )
164

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
165

Theophile GENTILHOMME's avatar
Theophile GENTILHOMME committed
166
def lines_at_option(dflt='1e-3', **kwargs):
167 168 169
    '''Get option to draw const far line'''
    return list_float_option(
        name='lines-at', short_name='la',
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
170
        desc='If given, draw vertical lines at the given axis positions. '
171 172
        'Your values must be separated with a comma (,) without space. '
        'This option works in ROC and DET curves.',
Theophile GENTILHOMME's avatar
Theophile GENTILHOMME committed
173
        nitems=None, dflt=dflt, **kwargs
174 175
    )

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
176

177 178 179 180 181 182 183 184
def x_rotation_option(dflt=0, **kwargs):
    '''Get option for rotartion of the x axis lables'''
    def custom_x_rotation_option(func):
        def callback(ctx, param, value):
            value = abs(value)
            ctx.meta['x_rotation'] = value
            return value
        return click.option(
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
185 186
            '-r', '--x-rotation', type=click.INT, default=dflt,
            show_default=True, help='X axis labels ration',
187 188 189
            callback=callback, **kwargs)(func)
    return custom_x_rotation_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
190

191
def legend_ncols_option(dflt=3, **kwargs):
192 193 194 195 196 197 198
    '''Get option for number of columns for legends'''
    def custom_legend_ncols_option(func):
        def callback(ctx, param, value):
            value = abs(value)
            ctx.meta['legends_ncol'] = value
            return value
        return click.option(
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
199 200
            '-lc', '--legends-ncol', type=click.INT, default=dflt,
            show_default=True,
201 202 203 204
            help='The number of columns of the legend layout.',
            callback=callback, **kwargs)(func)
    return custom_legend_ncols_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
205

206 207 208 209 210 211 212 213 214 215 216
def subplot_option(dflt=111, **kwargs):
    '''Get option to set subplots'''
    def custom_subplot_option(func):
        def callback(ctx, param, value):
            value = abs(value)
            nrows = value // 10
            nrows, ncols = divmod(nrows, 10)
            ctx.meta['n_col'] = ncols
            ctx.meta['n_row'] = nrows
            return value
        return click.option(
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
217 218
            '-sp', '--subplot', type=click.INT, default=dflt,
            show_default=True, help='The order of subplots.',
219 220 221
            callback=callback, **kwargs)(func)
    return custom_subplot_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
222

223 224 225 226 227 228 229 230 231 232 233 234 235 236
def cost_option(**kwargs):
    '''Get option to get cost for FAR'''
    def custom_cost_option(func):
        def callback(ctx, param, value):
            if value < 0 or value > 1:
                raise click.BadParameter("Cost for FAR must be betwen 0 and 1")
            ctx.meta['cost'] = value
            return value
        return click.option(
            '-C', '--cost', type=float, default=0.99, show_default=True,
            help='Cost for FAR in minDCF',
            callback=callback, **kwargs)(func)
    return custom_cost_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
237

238 239 240 241 242 243
def points_curve_option(**kwargs):
    '''Get the number of points use to draw curves'''
    def custom_points_curve_option(func):
        def callback(ctx, param, value):
            if value < 2:
                raise click.BadParameter(
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
244 245
                    'Number of points to draw curves must be greater than 1',
                    ctx=ctx
246
                )
247
            ctx.meta['points'] = value
248 249 250 251 252 253 254
            return value
        return click.option(
            '-n', '--points', type=INT, default=100, show_default=True,
            help='The number of points use to draw curves in plots',
            callback=callback, **kwargs)(func)
    return custom_points_curve_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
255

256 257
def n_bins_option(**kwargs):
    '''Get the number of bins in the histograms'''
258 259 260
    possible_strings = ['auto', 'fd', 'doane',
                        'scott', 'rice', 'sturges', 'sqrt']

261 262
    def custom_n_bins_option(func):
        def callback(ctx, param, value):
263
            if value is None:
264
                value = ['doane']
265 266 267
            else:
                tmp = value.split(',')
                try:
268 269
                    value = [int(i) if i not in possible_strings
                             else i for i in tmp]
270 271
                except Exception:
                    raise click.BadParameter('Incorrect number of bins inputs')
272 273 274
            ctx.meta['n_bins'] = value
            return value
        return click.option(
275
            '-b', '--nbins', type=click.STRING, default='doane',
276 277 278 279
            help='The number of bins for the different quantities to plot, '
            'seperated by commas. For example, if you plot histograms '
            'of negative and positive scores '
            ', input something like `100,doane`. All the '
280 281 282 283
            'possible bin options can be found in https://docs.scipy.org/doc/'
            'numpy/reference/generated/numpy.histogram.html. Be aware that '
            'for some corner cases, the option `auto` and `fd` can lead to '
            'MemoryError.',
284 285 286
            callback=callback, **kwargs)(func)
    return custom_n_bins_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
287

288 289
def table_option(**kwargs):
    '''Get table option for tabulate package
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
290
    More informnations: https://pypi.org/project/tabulate/
291 292 293 294 295 296
    '''
    def custom_table_option(func):
        def callback(ctx, param, value):
            ctx.meta['tablefmt'] = value
            return value
        return click.option(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
297 298
            '--tablefmt', type=click.Choice(tabulate.tabulate_formats),
            default='rst', show_default=True, help='Format of printed tables.',
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
299
            callback=callback, **kwargs)(func)
300 301
    return custom_table_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
302

303 304 305 306 307 308 309 310
def output_plot_file_option(default_out='plots.pdf', **kwargs):
    '''Get options for output file for plots'''
    def custom_output_plot_file_option(func):
        def callback(ctx, param, value):
            ''' Save ouput file  and associated pdf in context list,
            print the path of the file in the log'''
            ctx.meta['output'] = value
            ctx.meta['PdfPages'] = PdfPages(value)
311
            LOGGER.debug("Plots will be output in %s", value)
312 313 314 315 316 317 318 319
            return value
        return click.option(
            '-o', '--output',
            default=default_out, show_default=True,
            help='The file to save the plots in.',
            callback=callback, **kwargs)(func)
    return custom_output_plot_file_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
320

321
def output_log_metric_option(**kwargs):
322
    '''Get options for output file for metrics'''
323
    def custom_output_log_file_option(func):
324 325
        def callback(ctx, param, value):
            if value is not None:
326
                LOGGER.debug("Metrics will be output in %s", value)
327 328 329 330 331
            ctx.meta['log'] = value
            return value
        return click.option(
            '-l', '--log', default=None, type=click.STRING,
            help='If provided, computed numbers are written to '
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
332
            'this file instead of the standard output.',
333
            callback=callback, **kwargs)(func)
334
    return custom_output_log_file_option
335

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
336

337 338 339 340 341 342 343 344 345 346 347 348 349 350
def no_line_option(**kwargs):
    '''Get option flag to say if no line should be displayed'''
    def custom_no_line_option(func):
        def callback(ctx, param, value):
            ctx.meta['no_line'] = value
            return value
        return click.option(
            '--no-line', is_flag=True, default=False,
            show_default=True,
            help='If set does not display vertical lines',
            callback=callback, **kwargs)(func)
    return custom_no_line_option


351
def criterion_option(lcriteria=['eer', 'min-hter', 'far'], **kwargs):
352 353 354 355 356 357 358
    """Get option flag to tell which criteriom is used (default:eer)

    Parameters
    ----------
    lcriteria : :any:`list`
        List of possible criteria
    """
359
    def custom_criterion_option(func):
360
        list_accepted_crit = lcriteria if lcriteria is not None else \
361 362
            ['eer', 'min-hter', 'far']

363 364
        def callback(ctx, param, value):
            if value not in list_accepted_crit:
Theophile GENTILHOMME's avatar
Theophile GENTILHOMME committed
365
                raise click.BadParameter('Incorrect value for `--criterion`. '
366 367
                                         'Must be one of [`%s`]' %
                                         '`, `'.join(list_accepted_crit))
368
            ctx.meta['criterion'] = value
369 370
            return value
        return click.option(
371 372
            '-c', '--criterion', default='eer',
            help='Criterion to compute plots and '
373
            'metrics: %s)' % ', '.join(list_accepted_crit),
374 375
            callback=callback, is_eager=True, show_default=True,
            **kwargs)(func)
376 377
    return custom_criterion_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
378

379
def decimal_option(dflt=1, **kwargs):
380 381 382 383 384 385 386 387 388 389 390 391
    '''Get option to get decimal value'''
    def custom_decimal_option(func):
        def callback(ctx, param, value):
            ctx.meta['decimal'] = value
            return value
        return click.option(
            '-d', '--decimal', type=click.INT, default=dflt,
            help='Number of decimals to be printed.',
            callback=callback, show_default=True, **kwargs)(func)
    return custom_decimal_option


392 393 394
def far_option(**kwargs):
    '''Get option to get far value'''
    def custom_far_option(func):
395
        def callback(ctx, param, value):
396
            if value is not None and (value > 1 or value < 0):
397 398
                raise click.BadParameter("FAR value should be between 0 and 1")
            ctx.meta['far_value'] = value
399 400
            return value
        return click.option(
401
            '-f', '--far-value', type=click.FLOAT, default=None,
402 403
            help='The FAR value for which to compute threshold. This option '
            'must be used alongside `--criterion far`.',
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
404
            callback=callback, show_default=True, **kwargs)(func)
405
    return custom_far_option
406

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
407

408 409 410 411 412 413 414 415 416 417 418 419
def min_far_option(dflt=1e-4, **kwargs):
    '''Get option to get min far value'''
    def custom_min_far_option(func):
        def callback(ctx, param, value):
            if value is not None and (value > 1 or value < 0):
                raise click.BadParameter("FAR value should be between 0 and 1")
            ctx.meta['min_far_value'] = value
            return value
        return click.option(
            '-M', '--min-far-value', type=click.FLOAT, default=dflt,
            help='Select the minimum FAR value used in ROC and DET plots; '
            'should be a power of 10.',
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
420
            callback=callback, show_default=True, **kwargs)(func)
421 422
    return custom_min_far_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437
def figsize_option(dflt='4,3', **kwargs):
    """Get option for matplotlib figsize

    Parameters
    ----------
    dflt : str
        matplotlib default figsize for the command. must be a a list of int
        separated by commas.

    Returns
    -------
    callable
        A decorator to be used for adding score arguments for click commands
    """
438 439 440 441
    def custom_figsize_option(func):
        def callback(ctx, param, value):
            ctx.meta['figsize'] = value if value is None else \
                    [float(x) for x in value.split(',')]
442 443
            if value is not None:
                plt.rcParams['figure.figsize'] = ctx.meta['figsize']
444 445
            return value
        return click.option(
446 447
            '--figsize', default=dflt, show_default=True,
            help='If given, will run '
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
448 449
            '``plt.rcParams[\'figure.figsize\']=figsize)``. '
            'Example: --fig-size 4,6',
450 451 452
            callback=callback, **kwargs)(func)
    return custom_figsize_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
453

454
def legend_loc_option(dflt='best', **kwargs):
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
455
    '''Get the legend location of the plot'''
456 457
    def custom_legend_loc_option(func):
        def callback(ctx, param, value):
458 459
            ctx.meta['legend_loc'] = value.replace(
                '-', ' ') if value else value
460 461
            return value
        return click.option(
462
            '-lc', '--legend-loc', default=dflt, show_default=True,
463 464 465 466 467
            type=click.Choice(['best', 'upper-right', 'upper-left',
                               'lower-left', 'lower-right', 'right',
                               'center-left', 'center-right', 'lower-center',
                               'upper-center', 'center']),
            help='The legend location code',
468 469 470
            callback=callback, **kwargs)(func)
    return custom_legend_loc_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
471

472 473 474 475 476 477 478 479 480 481 482 483
def line_width_option(**kwargs):
    '''Get line width option for the plots'''
    def custom_line_width_option(func):
        def callback(ctx, param, value):
            ctx.meta['line_width'] = value
            return value
        return click.option(
            '--line-width',
            type=FLOAT, help='The line width of plots',
            callback=callback, **kwargs)(func)
    return custom_line_width_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
484

485 486 487 488 489 490 491 492 493 494 495 496
def marker_style_option(**kwargs):
    '''Get marker style otpion for the plots'''
    def custom_marker_style_option(func):
        def callback(ctx, param, value):
            ctx.meta['marker_style'] = value
            return value
        return click.option(
            '--marker-style',
            type=FLOAT, help='The marker style of the plots',
            callback=callback, **kwargs)(func)
    return custom_marker_style_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
497

498 499 500
def legends_option(**kwargs):
    '''Get the legends option for the different systems'''
    def custom_legends_option(func):
501
        def callback(ctx, param, value):
502 503
            if value is not None:
                value = value.split(',')
504
            ctx.meta['legends'] = value
505 506
            return value
        return click.option(
507
            '-lg', '--legends', type=click.STRING, default=None,
508
            help='The legend for each system comma separated. '
509
            'Example: --legends ISV,CNN',
510
            callback=callback, **kwargs)(func)
511
    return custom_legends_option
512

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
513

514 515 516 517 518 519 520 521
def title_option(**kwargs):
    '''Get the title option for the different systems'''
    def custom_title_option(func):
        def callback(ctx, param, value):
            ctx.meta['title'] = value
            return value
        return click.option(
            '-t', '--title', type=click.STRING, default=None,
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
522 523
            help="The title of the plots. Provide just a space (-t ' ') to "
            "remove the titles from figures.",
524 525 526
            callback=callback, **kwargs)(func)
    return custom_title_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
527

528 529 530 531 532 533 534 535 536 537 538 539
def titles_option(**kwargs):
    '''Get the titles option for the different plots'''
    def custom_title_option(func):
        def callback(ctx, param, value):
            if value is not None:
                value = value.split(',')
            ctx.meta['titles'] = value or []
            return value or []
        return click.option(
            '-ts', '--titles', type=click.STRING, default=None,
            help='The titles of the plots seperated by commas. '
            'For example, if the figure has two plots, \"MyTitleA,MyTitleB\" '
540 541
            'is a possible input.'
            ' Provide just a space (-ts \' \') to '
542 543 544 545 546
            'remove the titles from figures.',
            callback=callback, **kwargs)(func)
    return custom_title_option


547 548 549 550 551 552 553 554
def x_label_option(dflt=None, **kwargs):
    '''Get the label option for X axis '''
    def custom_x_label_option(func):
        def callback(ctx, param, value):
            ctx.meta['x_label'] = value
            return value
        return click.option(
            '-xl', '--x-lable', type=click.STRING, default=dflt,
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
555
            show_default=True, help='Label for x-axis',
556 557 558
            callback=callback, **kwargs)(func)
    return custom_x_label_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
559

560 561 562 563 564 565 566 567 568 569 570 571
def y_label_option(dflt=None, **kwargs):
    '''Get the label option for Y axis '''
    def custom_y_label_option(func):
        def callback(ctx, param, value):
            ctx.meta['y_label'] = value
            return value
        return click.option(
            '-yl', '--y-lable', type=click.STRING, default=dflt,
            help='Label for y-axis',
            callback=callback, **kwargs)(func)
    return custom_y_label_option

Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
572

573 574 575 576 577 578 579 580
def style_option(**kwargs):
    '''Get option for matplotlib style'''
    def custom_style_option(func):
        def callback(ctx, param, value):
            ctx.meta['style'] = value
            plt.style.use(value)
            return value
        return click.option(
Amir MOHAMMADI's avatar
lint  
Amir MOHAMMADI committed
581 582
            '--style', multiple=True,
            type=click.types.Choice(sorted(plt.style.available)),
583 584 585 586
            help='The matplotlib style to use for plotting. You can provide '
            'multiple styles by repeating this option',
            callback=callback, **kwargs)(func)
    return custom_style_option
587 588 589 590 591 592


def metrics_command(docstring, criteria=('eer', 'min-hter', 'far')):
    def custom_metrics_command(func):
        func.__doc__ = docstring

593
        @click.command(context_settings=CONTEXT_SETTINGS)
594 595 596 597 598 599 600 601 602 603 604 605
        @scores_argument(nargs=-1)
        @eval_option()
        @table_option()
        @output_log_metric_option()
        @criterion_option(criteria)
        @thresholds_option()
        @far_option()
        @legends_option()
        @open_file_mode_option()
        @verbosity_option()
        @click.pass_context
        @functools.wraps(func)
606
        @decimal_option()
607 608 609 610 611 612 613 614
        def wrapper(*args, **kwds):
            return func(*args, **kwds)
        return wrapper
    return custom_metrics_command


METRICS_HELP = """Prints a table that contains {names} for a given
    threshold criterion ({criteria}).
615
    {hter_note}
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

    You need to provide one or more development score file(s) for each
    experiment. You can also provide evaluation files along with dev files. If
    evaluation scores are provided, you must use flag `--eval`.

    {score_format}

    Resulting table format can be changed using the `--tablefmt`.

    Examples:

        $ {command} -v scores-dev

        $ {command} -e -l results.txt sys1/scores-{{dev,eval}}

        $ {command} -e {{sys1,sys2}}/scores-{{dev,eval}}
632

633 634 635 636 637 638 639
    """


def roc_command(docstring):
    def custom_roc_command(func):
        func.__doc__ = docstring

640
        @click.command(context_settings=CONTEXT_SETTINGS)
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
        @scores_argument(nargs=-1)
        @titles_option()
        @legends_option()
        @no_legend_option()
        @legend_loc_option(dflt=None)
        @sep_dev_eval_option()
        @output_plot_file_option(default_out='roc.pdf')
        @eval_option()
        @semilogx_option(True)
        @lines_at_option()
        @axes_val_option()
        @min_far_option()
        @x_rotation_option()
        @x_label_option()
        @y_label_option()
        @points_curve_option()
        @const_layout_option()
        @figsize_option()
        @style_option()
        @linestyles_option()
        @verbosity_option()
        @click.pass_context
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            return func(*args, **kwds)
        return wrapper
    return custom_roc_command


ROC_HELP = """Plot ROC (receiver operating characteristic) curve.
    The plot will represent the false match rate on the horizontal axis and the
    false non match rate on the vertical axis.  The values for the axis will be
    computed using :py:func:`bob.measure.roc`.

    You need to provide one or more development score file(s) for each
    experiment. You can also provide evaluation files along with dev files. If
    evaluation scores are provided, you must use flag `--eval`.

    {score_format}

    Examples:

        $ {command} -v scores-dev

        $ {command} -e -v sys1/scores-{{dev,eval}}

        $ {command} -e -v -o my_roc.pdf {{sys1,sys2}}/scores-{{dev,eval}}
    """


def det_command(docstring):
    def custom_det_command(func):
        func.__doc__ = docstring

695
        @click.command(context_settings=CONTEXT_SETTINGS)
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
        @scores_argument(nargs=-1)
        @output_plot_file_option(default_out='det.pdf')
        @titles_option()
        @legends_option()
        @no_legend_option()
        @legend_loc_option(dflt='upper-right')
        @sep_dev_eval_option()
        @eval_option()
        @axes_val_option(dflt='0.01,95,0.01,95')
        @min_far_option()
        @x_rotation_option(dflt=45)
        @x_label_option()
        @y_label_option()
        @points_curve_option()
        @lines_at_option()
        @const_layout_option()
        @figsize_option()
        @style_option()
        @linestyles_option()
        @verbosity_option()
        @click.pass_context
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            return func(*args, **kwds)
        return wrapper
    return custom_det_command


DET_HELP = """Plot DET (detection error trade-off) curve.
    modified ROC curve which plots error rates on both axes
    (false positives on the x-axis and false negatives on the y-axis).

    You need to provide one or more development score file(s) for each
    experiment. You can also provide evaluation files along with dev files. If
    evaluation scores are provided, you must use flag `--eval`.

    {score_format}

    Examples:

        $ {command} -v scores-dev

        $ {command} -e -v sys1/scores-{{dev,eval}}

        $ {command} -e -v -o my_det.pdf {{sys1,sys2}}/scores-{{dev,eval}}
    """


def epc_command(docstring):
    def custom_epc_command(func):
        func.__doc__ = docstring

748
        @click.command(context_settings=CONTEXT_SETTINGS)
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
        @scores_argument(min_arg=1, force_eval=True, nargs=-1)
        @output_plot_file_option(default_out='epc.pdf')
        @titles_option()
        @legends_option()
        @no_legend_option()
        @legend_loc_option(dflt='upper-center')
        @points_curve_option()
        @const_layout_option()
        @x_label_option()
        @y_label_option()
        @figsize_option()
        @style_option()
        @linestyles_option()
        @verbosity_option()
        @click.pass_context
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            return func(*args, **kwds)
        return wrapper
    return custom_epc_command


EPC_HELP = """Plot EPC (expected performance curve).
    plots the error rate on the eval set depending on a threshold selected
    a-priori on the development set and accounts for varying relative cost
    in [0; 1] of FPR and FNR when calculating the threshold.

    You need to provide one or more development score and eval file(s)
    for each experiment.

    {score_format}

    Examples:

        $ {command} -v scores-{{dev,eval}}

        $ {command} -v -o my_epc.pdf {{sys1,sys2}}/scores-{{dev,eval}}
    """


def hist_command(docstring):
    def custom_hist_command(func):
        func.__doc__ = docstring

793
        @click.command(context_settings=CONTEXT_SETTINGS)
794 795 796 797 798
        @scores_argument(nargs=-1)
        @output_plot_file_option(default_out='hist.pdf')
        @eval_option()
        @hide_dev_option()
        @n_bins_option()
799
        @titles_option()
800 801 802 803 804 805 806 807 808 809 810
        @no_legend_option()
        @legend_ncols_option()
        @criterion_option()
        @far_option()
        @no_line_option()
        @thresholds_option()
        @subplot_option()
        @const_layout_option()
        @print_filenames_option()
        @figsize_option(dflt=None)
        @style_option()
811 812
        @x_label_option()
        @y_label_option()
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
        @verbosity_option()
        @click.pass_context
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            return func(*args, **kwds)
        return wrapper
    return custom_hist_command


HIST_HELP = """ Plots histograms of positive and negatives along with threshold
    criterion.

    You need to provide one or more development score file(s) for each
    experiment. You can also provide evaluation files along with dev files. If
    evaluation scores are provided, you must use the `--eval` flag. The
    threshold is always computed from development score files.

    By default, when eval-scores are given, only eval-scores histograms are
    displayed with threshold line computed from dev-scores.

    {score_format}

    Examples:

        $ {command} -v scores-dev

        $ {command} -e -v sys1/scores-{{dev,eval}}

        $ {command} -e -v --criterion min-hter {{sys1,sys2}}/scores-{{dev,eval}}
    """


def evaluate_command(docstring, criteria=('eer', 'min-hter', 'far')):
    def custom_evaluate_command(func):
        func.__doc__ = docstring

849
        @click.command(context_settings=CONTEXT_SETTINGS)
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
        @scores_argument(nargs=-1)
        @legends_option()
        @sep_dev_eval_option()
        @table_option()
        @eval_option()
        @criterion_option(criteria)
        @far_option()
        @output_log_metric_option()
        @output_plot_file_option(default_out='eval_plots.pdf')
        @lines_at_option()
        @points_curve_option()
        @const_layout_option()
        @figsize_option(dflt=None)
        @style_option()
        @linestyles_option()
        @verbosity_option()
        @click.pass_context
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            return func(*args, **kwds)
        return wrapper
    return custom_evaluate_command


EVALUATE_HELP = '''Runs error analysis on score sets.

    \b
    1. Computes the threshold using a criteria (EER by default) on
       development set scores
    2. Applies the above threshold on evaluation set scores to compute the
       HTER if a eval-score (use --eval) set is provided.
    3. Reports error rates on the console or in a log file.
    4. Plots ROC, DET, and EPC curves and score distributions to a multi-page
       PDF file

    You need to provide 1 or 2 score files for each biometric system in this
    order:

    \b
    * development scores
    * evaluation scores

    {score_format}

    Examples:

        $ {command} -v dev-scores

        $ {command} -v /path/to/sys-{{1,2,3}}/scores-dev

        $ {command} -e -v /path/to/sys-{{1,2,3}}/scores-{{dev,eval}}

        $ {command} -v -l metrics.txt -o my_plots.pdf dev-scores

    This command is a combination of metrics, roc, det, epc, and hist commands.
    If you want more flexibility in your plots, please use the individual
    commands.
    '''


def evaluate_flow(ctx, scores, evaluation, metrics, roc, det, epc, hist,
                  **kwargs):
    # open_mode is always write in this command.
    ctx.meta['open_mode'] = 'w'
    criterion = ctx.meta.get('criterion')
    if criterion is not None:
        click.echo("Computing metrics with %s..." % criterion)
        ctx.invoke(metrics, scores=scores, evaluation=evaluation)
        if 'log' in ctx.meta:
            click.echo("[metrics] => %s" % ctx.meta['log'])

    # avoid closing pdf file before all figures are plotted
    ctx.meta['closef'] = False
    if evaluation:
        click.echo("Starting evaluate with dev and eval scores...")
    else:
        click.echo("Starting evaluate with dev scores only...")
    click.echo("Computing ROC...")
    # set axes limits for ROC
    ctx.forward(roc)  # use class defaults plot settings
    click.echo("Computing DET...")
    ctx.forward(det)  # use class defaults plot settings
    if evaluation:
        click.echo("Computing EPC...")
        ctx.forward(epc)  # use class defaults plot settings
    # the last one closes the file
    ctx.meta['closef'] = True
    click.echo("Computing score histograms...")
    ctx.meta['criterion'] = 'eer'  # no criterion passed in evaluate
    ctx.forward(hist)
    click.echo("Evaluate successfully completed!")
    click.echo("[plots] => %s" % (ctx.meta['output']))
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962


def n_protocols_option(required=True, **kwargs):
    '''Get option for number of protocols.'''
    def custom_n_protocols_option(func):
        def callback(ctx, param, value):
            value = abs(value)
            ctx.meta['protocols_number'] = value
            return value
        return click.option(
            '-pn', '--protocols-number', type=click.INT,
            show_default=True, required=required,
            help='The number of protocols of cross validation.',
            callback=callback, **kwargs)(func)
    return custom_n_protocols_option


def multi_metrics_command(docstring, criteria=('eer', 'min-hter', 'far')):
    def custom_metrics_command(func):
        func.__doc__ = docstring

963
        @click.command('multi-metrics', context_settings=CONTEXT_SETTINGS)
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        @scores_argument(nargs=-1)
        @eval_option()
        @n_protocols_option()
        @table_option()
        @output_log_metric_option()
        @criterion_option(criteria)
        @thresholds_option()
        @far_option()
        @legends_option()
        @open_file_mode_option()
        @verbosity_option()
        @click.pass_context
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            return func(*args, **kwds)
        return wrapper
    return custom_metrics_command


MULTI_METRICS_HELP = """Multi protocol (cross-validation) metrics.

    Prints a table that contains {names} for a given threshold criterion
    ({criteria}). The metrics are averaged over several protocols. The idea is
    that each protocol corresponds to one fold in your cross-validation.

    You need to provide as many as development score files as the number of
    protocols per system. You can also provide evaluation files along with dev
    files. If evaluation scores are provided, you must use flag `--eval`. The
    number of protocols must be provided using the `--protocols-number` option.

    {score_format}

    Resulting table format can be changed using the `--tablefmt`.

    Examples:

        $ {command} -v {{p1,p2,p3}}/scores-dev

        $ {command} -v -e {{p1,p2,p3}}/scores-{{dev,eval}}

        $ {command} -v -e {{sys1,sys2}}/{{p1,p2,p3}}/scores-{{dev,eval}}
    """