common_options.py 16.3 KB
Newer Older
1
2
3
4
'''Stores click common options for plots'''

import logging
import click
5
from click.types import INT, FLOAT
6
7
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
8
from bob.extension.scripts.click_helper import (bool_option, list_float_option)
9

10
LOGGER = logging.getLogger(__name__)
11

12
13
14
15
16
17
18
19
20
21
22
23
24
25
def scores_argument(eval_mandatory=False, min_len=1, **kwargs):
    """Get the argument for scores, and add `dev-scores` and `eval-scores` in
    the context when `--evaluation` flag is on (default)

    Parameters
    ----------
    eval_mandatory :
        If evaluation files are mandatory
    min_len :
        The min lenght of inputs files that are needed. If eval_mandatory is
        True, this quantity is multiplied by 2.

    Returns
    -------
26
27
     callable
      A decorator to be used for adding score arguments for click commands
28
    """
29
30
31
    def custom_scores_argument(func):
        def callback(ctx, param, value):
            length = len(value)
32
33
34
35
36
37
38
            min_arg = min_len or 1
            ctx.meta['min_arg'] = min_arg
            if length < min_arg:
                raise click.BadParameter(
                    'You must provide at least %d score files' % min_arg,
                    ctx=ctx
                )
39
40
            else:
                ctx.meta['scores'] = value
41
42
43
44
45
46
                step = 1
                if eval_mandatory or ctx.meta['evaluation']:
                    step = 2
                    if (length % (min_arg * 2)) != 0:
                        pref = 'T' if eval_mandatory else \
                                ('When `--evaluation` flag is on t')
47
48
                        raise click.BadParameter(
                            '%sest-score(s) must '
49
50
51
                            'be provided along with dev-score(s). '
                            'You must provide at least %d score files.' \
                            % (pref, min_arg * 2), ctx=ctx
52
                        )
53
54
55
56
57
58
59
60
61
62
63
                for arg in range(min_arg):
                    ctx.meta['dev_scores_%d' % arg] = [
                        value[i] for i in range(arg * step, length,
                                                min_arg * step)
                    ]
                    if step > 1:
                        ctx.meta['eval_scores_%d' % arg] = [
                            value[i] for i in range((arg * step + 1),
                                                    length, min_arg * step)
                        ]
                ctx.meta['n_sys'] = len(ctx.meta['dev_scores_0'])
64
                if 'titles' in ctx.meta and \
65
                   len(ctx.meta['titles']) != ctx.meta['n_sys']:
66
67
68
                    raise click.BadParameter(
                        '#titles not equal to #sytems', ctx=ctx
                    )
69
            return value
70
71
72
73
        return click.argument(
            'scores', type=click.Path(exists=True),
            callback=callback, **kwargs
        )(func)
74
75
    return custom_scores_argument

76
77
78
79
80
81
def eval_option(**kwargs):
    '''Get option flag to say if eval-scores are provided'''
    return bool_option(
        'evaluation', 'e', 'If set, evaluation scores must be provided',
        dflt=True
    )
82

83
84
def sep_dev_eval_option(dflt=True, **kwargs):
    '''Get option flag to say if dev and eval plots should be in different
85
    plots'''
86
    return bool_option(
87
88
        'split', 's','If set, evaluation and dev curve in different plots',
        dflt
89
90
91
92
93
    )

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

95
def semilogx_option(dflt=False, **kwargs):
96
    '''Option to use semilog X-axis'''
97
    return bool_option('semilogx', 'G', 'If set, use semilog on X axis', dflt)
98

99
100
101
102
def show_dev_option(dflt=False, **kwargs):
    '''Option to tell if should show dev histo'''
    return bool_option('show-dev', 'D', 'If set, show dev histograms', dflt)

103
def print_filenames_option(dflt=True, **kwargs):
104
105
106
107
108
    '''Option to tell if filenames should be in the title'''
    return bool_option('show-fn', 'P', 'If set, show filenames in title', dflt)

def const_layout_option(dflt=True, **kwargs):
    '''Option to set matplotlib constrained_layout'''
109
110
111
112
113
114
115
116
117
118
    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
119

120
def axes_val_option(dflt=None, **kwargs):
121
    ''' Option for setting min/max values on axes '''
122
123
    return list_float_option(
        name='axlim', short_name='L',
124
125
        desc='min/max axes values separated by commas (e.g. ``--axlim '
        ' 0.1,100,0.1,100``)',
126
127
128
129
        nitems=4, dflt=dflt, **kwargs
    )

def thresholds_option(**kwargs):
130
    ''' Option to give a list of thresholds '''
131
132
    return list_float_option(
        name='thres', short_name='T',
133
134
        desc='Given threshold for metrics computations, e.g. '
        '0.005,0.001,0.056',
135
136
        nitems=None, dflt=None, **kwargs
    )
137

138
139
140
141
def lines_at_option(**kwargs):
    '''Get option to draw const far line'''
    return list_float_option(
        name='lines-at', short_name='la',
142
        desc='If given, draw veritcal lines at the given axis positions',
143
144
145
        nitems=None, dflt=None, **kwargs
    )

146
147
148
149
150
151
152
153
154
155
156
157
158
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(
            '-r', '--x-rotation', type=click.INT, default=dflt, show_default=True,
            help='X axis labels ration',
            callback=callback, **kwargs)(func)
    return custom_x_rotation_option

159
160
161
162
163
164
165
166
167
168
169
170
171
172
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

173
174
175
176
177
178
179
180
181
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(
                    'Number of points to draw curves must be greater than 1'
                    , ctx=ctx
                )
182
            ctx.meta['points'] = value
183
184
185
186
187
188
189
190
191
192
193
            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

def n_bins_option(**kwargs):
    '''Get the number of bins in the histograms'''
    def custom_n_bins_option(func):
        def callback(ctx, param, value):
194
195
196
            if value is None:
                value = 'auto'
            elif value < 2:
197
198
199
200
201
202
203
                raise click.BadParameter(
                    'Number of bins must be greater than 1'
                    , ctx=ctx
                )
            ctx.meta['n_bins'] = value
            return value
        return click.option(
204
205
            '-b', '--nbins', type=INT, default=None,
            help='The number of bins in the histogram(s). Default: `auto`',
206
207
208
209
210
211
212
213
214
215
216
217
            callback=callback, **kwargs)(func)
    return custom_n_bins_option

def table_option(**kwargs):
    '''Get table option for tabulate package
    More informnations: https://pypi.python.org/pypi/tabulate
    '''
    def custom_table_option(func):
        def callback(ctx, param, value):
            ctx.meta['tablefmt'] = value
            return value
        return click.option(
218
            '--tablefmt', type=click.STRING, default='rst',
219
            show_default=True, help='Format for table display: `plain`, '
220
            '`simple`, `grid`, `fancy_grid`, `pipe`, `orgtbl`, '
221
222
            '`jira`, `presto`, `psql`, `rst`, `mediawiki`, `moinmoin`, '
            '`youtrack`, `html`, `latex`, '
223
224
225
226
227
228
229
230
231
232
233
234
            '`latex_raw`, `latex_booktabs`, `textile`',
            callback=callback,**kwargs)(func)
    return custom_table_option

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)
235
            LOGGER.debug("Plots will be output in %s", value)
236
237
238
239
240
241
242
243
            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

244
def output_log_metric_option(**kwargs):
245
    '''Get options for output file for metrics'''
246
    def custom_output_log_file_option(func):
247
248
        def callback(ctx, param, value):
            if value is not None:
249
                LOGGER.debug("Metrics will be output in %s", value)
250
251
252
253
254
255
256
            ctx.meta['log'] = value
            return value
        return click.option(
            '-l', '--log', default=None, type=click.STRING,
            help='If provided, computed numbers are written to '
              'this file instead of the standard output.',
            callback=callback, **kwargs)(func)
257
    return custom_output_log_file_option
258

259
260
261
262
263
264
265
266
def criterion_option(lcriteria=['eer', 'hter', 'far'], **kwargs):
    """Get option flag to tell which criteriom is used (default:eer)

    Parameters
    ----------
    lcriteria : :any:`list`
        List of possible criteria
    """
267
268
    def custom_criterion_option(func):
        def callback(ctx, param, value):
269
270
            list_accepted_crit = lcriteria if lcriteria is not None else \
                    ['eer', 'hter', 'far']
271
272
273
274
275
276
277
278
279
280
281
282
            if value not in list_accepted_crit:
                raise click.BadParameter('Incorrect value for `--criter`. '
                                         'Must be one of [`%s`]' %
                                         '`, `'.join(list_accepted_crit))
            ctx.meta['criter'] = value
            return value
        return click.option(
            '--criter', default='eer', help='Criterion to compute plots and '
            'metrics: `eer` (default), `hter`',
            callback=callback, is_eager=True ,**kwargs)(func)
    return custom_criterion_option

283
284
285
def far_option(**kwargs):
    '''Get option to get far value'''
    def custom_far_option(func):
286
        def callback(ctx, param, value):
287
            if value is not None and (value > 1 or value < 0):
288
289
                raise click.BadParameter("FAR value should be between 0 and 1")
            ctx.meta['far_value'] = value
290
291
            return value
        return click.option(
292
            '-f', '--far-value', type=click.FLOAT, default=None,
293
            help='The FAR value for which to compute metrics',
294
            callback=callback, show_default=True,**kwargs)(func)
295
    return custom_far_option
296

297
298
299
300
301
302
def figsize_option(**kwargs):
    '''Get option for matplotlib figsize'''
    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(',')]
303
304
            if value is not None:
                plt.rcParams['figure.figsize'] = ctx.meta['figsize']
305
306
            return value
        return click.option(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
307
            '--figsize', help='If given, will run '
308
            '``plt.rcParams[\'figure.figsize\']=figsize)``. Example: --fig-size 4,6',
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
            callback=callback, **kwargs)(func)
    return custom_figsize_option

def legend_ncols_option(**kwargs):
    '''Get the number of columns to set in the legend of the plot'''
    def custom_legend_ncols_option(func):
        def callback(ctx, param, value):
            ctx.meta['legend_ncol'] = value
            return value
        return click.option(
            '--legend-ncol', default=3, show_default=True,
            type=INT, help='The number of columns of the legend layout.',
            callback=callback, **kwargs)(func)
    return custom_legend_ncols_option

def legend_loc_option(**kwargs):
    '''Get tthe legend location of the plot'''
    def custom_legend_loc_option(func):
        def callback(ctx, param, value):
            ctx.meta['legend_loc'] = value
            return value
        return click.option(
            '--legend-location', default=0, show_default=True,
            type=INT, help='The lengend location code',
            callback=callback, **kwargs)(func)
    return custom_legend_loc_option

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

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

def titles_option(**kwargs):
361
    '''Get the titles option for the different systems'''
362
363
    def custom_titles_option(func):
        def callback(ctx, param, value):
364
365
366
            if value is not None:
                value = value.split(',')
            ctx.meta['titles'] = value
367
368
            return value
        return click.option(
369
            '-ts', '--titles', type=click.STRING, default=None,
370
            help='The title for each system comma separated. '
371
372
373
374
            'Example: --titles ISV,CNN',
            callback=callback, **kwargs)(func)
    return custom_titles_option

375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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,
            help='The title of the plots',
            callback=callback, **kwargs)(func)
    return custom_title_option

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,
            help='Label for x-axis',
            callback=callback, **kwargs)(func)
    return custom_x_label_option

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

411
412
413
414
415
416
417
418
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(
419
            '--style', multiple=True, type=click.types.Choice(sorted(plt.style.available)),
420
421
422
423
            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