common_options.py 33.2 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
11
from bob.extension.scripts.click_helper import (
    bool_option, list_float_option, verbosity_option, open_file_mode_option)
12

13
LOGGER = logging.getLogger(__name__)
14

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
15

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

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

    Returns
    -------
28
29
     callable
      A decorator to be used for adding score arguments for click commands
30
    """
31
32
    def custom_scores_argument(func):
        def callback(ctx, param, value):
33
34
35
            min_a = min_arg or 1
            mutli = 1
            error = ''
36
            if ('evaluation' in ctx.meta and ctx.meta['evaluation']) or force_eval:
37
38
39
40
41
                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
42
            # add more test here if other inputs are needed
43
44
45
46

            min_a *= mutli
            ctx.meta['min_arg'] = min_a
            if len(value) < 1 or len(value) % ctx.meta['min_arg'] != 0:
47
                raise click.BadParameter(
48
49
50
51
                    '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
52
                )
53
            ctx.meta['scores'] = value
54
            return value
55
56
57
58
        return click.argument(
            'scores', type=click.Path(exists=True),
            callback=callback, **kwargs
        )(func)
59
60
    return custom_scores_argument

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
61

62
63
64
65
66
67
68
69
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
    )


70
71
def eval_option(**kwargs):
    '''Get option flag to say if eval-scores are provided'''
72
73
74
75
76
77
78
79
80
81
82
83
    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


84
85
86
87
88
89
90
91
92
93
94
95
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
96

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
97

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

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
106

107
108
109
110
111
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
112

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

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
118

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

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
124

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

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
130

131
132
def const_layout_option(dflt=True, **kwargs):
    '''Option to set matplotlib constrained_layout'''
133
134
135
136
137
138
139
140
141
142
    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
143

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
144

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

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
154

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

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
164

Theophile GENTILHOMME's avatar
Theophile GENTILHOMME committed
165
def lines_at_option(dflt='1e-3', **kwargs):
166
167
168
    '''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
169
        desc='If given, draw vertical lines at the given axis positions. '
170
171
        '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
172
        nitems=None, dflt=dflt, **kwargs
173
174
    )

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
175

176
177
178
179
180
181
182
183
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
184
185
            '-r', '--x-rotation', type=click.INT, default=dflt,
            show_default=True, help='X axis labels ration',
186
187
188
            callback=callback, **kwargs)(func)
    return custom_x_rotation_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
189

190
def legend_ncols_option(dflt=3, **kwargs):
191
192
193
194
195
196
197
    '''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
198
199
            '-lc', '--legends-ncol', type=click.INT, default=dflt,
            show_default=True,
200
201
202
203
            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
204

205
206
207
208
209
210
211
212
213
214
215
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
216
217
            '-sp', '--subplot', type=click.INT, default=dflt,
            show_default=True, help='The order of subplots.',
218
219
220
            callback=callback, **kwargs)(func)
    return custom_subplot_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
221

222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
236

237
238
239
240
241
242
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
243
244
                    'Number of points to draw curves must be greater than 1',
                    ctx=ctx
245
                )
246
            ctx.meta['points'] = value
247
248
249
250
251
252
253
            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
254

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

260
261
    def custom_n_bins_option(func):
        def callback(ctx, param, value):
262
            if value is None:
263
                value = ['doane']
264
265
266
            else:
                tmp = value.split(',')
                try:
267
268
                    value = [int(i) if i not in possible_strings
                             else i for i in tmp]
269
270
                except Exception:
                    raise click.BadParameter('Incorrect number of bins inputs')
271
272
273
            ctx.meta['n_bins'] = value
            return value
        return click.option(
274
            '-b', '--nbins', type=click.STRING, default='doane',
275
276
277
278
            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 '
279
280
281
282
            '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.',
283
284
285
            callback=callback, **kwargs)(func)
    return custom_n_bins_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
286

287
288
def table_option(**kwargs):
    '''Get table option for tabulate package
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
289
    More informnations: https://pypi.org/project/tabulate/
290
291
292
293
294
295
    '''
    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
296
297
            '--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
298
            callback=callback, **kwargs)(func)
299
300
    return custom_table_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
301

302
303
304
305
306
307
308
309
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)
310
            LOGGER.debug("Plots will be output in %s", value)
311
312
313
314
315
316
317
318
            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
319

320
def output_log_metric_option(**kwargs):
321
    '''Get options for output file for metrics'''
322
    def custom_output_log_file_option(func):
323
324
        def callback(ctx, param, value):
            if value is not None:
325
                LOGGER.debug("Metrics will be output in %s", value)
326
327
328
329
330
            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
331
            'this file instead of the standard output.',
332
            callback=callback, **kwargs)(func)
333
    return custom_output_log_file_option
334

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
335

336
337
338
339
340
341
342
343
344
345
346
347
348
349
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


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

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

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

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
377

378
379
380
def far_option(**kwargs):
    '''Get option to get far value'''
    def custom_far_option(func):
381
        def callback(ctx, param, value):
382
            if value is not None and (value > 1 or value < 0):
383
384
                raise click.BadParameter("FAR value should be between 0 and 1")
            ctx.meta['far_value'] = value
385
386
            return value
        return click.option(
387
            '-f', '--far-value', type=click.FLOAT, default=None,
388
389
            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
390
            callback=callback, show_default=True, **kwargs)(func)
391
    return custom_far_option
392

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
393

394
395
396
397
398
399
400
401
402
403
404
405
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
406
            callback=callback, show_default=True, **kwargs)(func)
407
408
    return custom_min_far_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
409

410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
    """
424
425
426
427
    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(',')]
428
429
            if value is not None:
                plt.rcParams['figure.figsize'] = ctx.meta['figsize']
430
431
            return value
        return click.option(
432
433
            '--figsize', default=dflt, show_default=True,
            help='If given, will run '
Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
434
435
            '``plt.rcParams[\'figure.figsize\']=figsize)``. '
            'Example: --fig-size 4,6',
436
437
438
            callback=callback, **kwargs)(func)
    return custom_figsize_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
439

440
def legend_loc_option(dflt='best', **kwargs):
Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
441
    '''Get the legend location of the plot'''
442
443
    def custom_legend_loc_option(func):
        def callback(ctx, param, value):
444
445
            ctx.meta['legend_loc'] = value.replace(
                '-', ' ') if value else value
446
447
            return value
        return click.option(
448
            '-lc', '--legend-loc', default=dflt, show_default=True,
449
450
451
452
453
            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',
454
455
456
            callback=callback, **kwargs)(func)
    return custom_legend_loc_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
457

458
459
460
461
462
463
464
465
466
467
468
469
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
470

471
472
473
474
475
476
477
478
479
480
481
482
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
483

484
485
486
def legends_option(**kwargs):
    '''Get the legends option for the different systems'''
    def custom_legends_option(func):
487
        def callback(ctx, param, value):
488
489
            if value is not None:
                value = value.split(',')
490
            ctx.meta['legends'] = value
491
492
            return value
        return click.option(
493
            '-lg', '--legends', type=click.STRING, default=None,
494
            help='The title for each system comma separated. '
495
            'Example: --legends ISV,CNN',
496
            callback=callback, **kwargs)(func)
497
    return custom_legends_option
498

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
499

500
501
502
503
504
505
506
507
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
508
509
            help="The title of the plots. Provide just a space (-t ' ') to "
            "remove the titles from figures.",
510
511
512
            callback=callback, **kwargs)(func)
    return custom_title_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
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\" '
            'is a possible input'
            'Provide just a space (-t ' ') to '
            'remove the titles from figures.',
            callback=callback, **kwargs)(func)
    return custom_title_option


533
534
535
536
537
538
539
540
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
541
            show_default=True, help='Label for x-axis',
542
543
544
            callback=callback, **kwargs)(func)
    return custom_x_label_option

Amir MOHAMMADI's avatar
lint    
Amir MOHAMMADI committed
545

546
547
548
549
550
551
552
553
554
555
556
557
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
558

559
560
561
562
563
564
565
566
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
567
568
            '--style', multiple=True,
            type=click.types.Choice(sorted(plt.style.available)),
569
570
571
572
            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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
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
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
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
849
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


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

        @click.command()
        @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)
        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}).

    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}}
    """


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

        @click.command()
        @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

        @click.command()
        @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

        @click.command()
        @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

        @click.command()
        @scores_argument(nargs=-1)
        @output_plot_file_option(default_out='hist.pdf')
        @eval_option()
        @hide_dev_option()
        @n_bins_option()
        @legends_option()
        @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()
        @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

        @click.command()
        @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']))
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986


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

        @click.command('multi-metrics')
        @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}}
    """