load.py 15.6 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
3
4
5
6
7
8
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Mon 23 May 2011 16:23:05 CEST

"""A set of utilities to load score files with different formats.
"""

import numpy
9
import csv
10
11
12
import tarfile
import os

13
14
15
import logging
logger = logging.getLogger('bob.measure')

André Anjos's avatar
André Anjos committed
16

17
def open_file(filename, mode='rt'):
André Anjos's avatar
André Anjos committed
18
19
20
21
22
23
24
25
  """Opens the given score file for reading.

  Score files might be raw text files, or a tar-file including a single score
  file inside.


  Parameters:

André Anjos's avatar
André Anjos committed
26
    filename (:py:class:`str`, ``file-like``): The name of the score file to
André Anjos's avatar
André Anjos committed
27
28
      open, or a file-like object open for reading. If a file name is given,
      the according file might be a raw text file or a (compressed) tar file
29
      containing a raw text file.
30

31

André Anjos's avatar
André Anjos committed
32
  Returns:
33

34

André Anjos's avatar
André Anjos committed
35
36
    ``file-like``: A read-only file-like object as it would be returned by
    :py:func:`open`.
37

38
  """
André Anjos's avatar
André Anjos committed
39

40
41
42
43
  if not isinstance(filename, str) and hasattr(filename, 'read'):
    # It seems that this is an open file
    return filename

44
45
46
  if not os.path.isfile(filename):
    raise IOError("Score file '%s' does not exist." % filename)
  if not tarfile.is_tarfile(filename):
47
    return open(filename, mode)
48
49
50
51
52
53
54
55
56
57
58
59
60
61

  # open the tar file for reading
  tar = tarfile.open(filename, 'r')
  # get the first file in the tar file
  tar_info = tar.next()
  while tar_info is not None and not tar_info.isfile():
    tar_info = tar.next()
  # check that one file was found in the archive
  if tar_info is None:
    raise IOError("The given file is a .tar file, but it does not contain any file.")

  # open the file for reading
  return tar.extractfile(tar_info)

André Anjos's avatar
André Anjos committed
62
63

def four_column(filename):
André Anjos's avatar
André Anjos committed
64
65
66
67
68
69
70
71
72
73
  """Loads a score set from a single file and yield its lines

  Loads a score set from a single file and yield its lines (to avoid loading
  the score file at once into memory).  This function verifies that all fields
  are correctly placed and contain valid fields.  The score file must contain
  the following information in each line:

  .. code-block:: text

     claimed_id real_id test_label score
74
75


André Anjos's avatar
André Anjos committed
76
  Parameters:
77

André Anjos's avatar
André Anjos committed
78
    filename (:py:class:`str`, ``file-like``): The file object that will be
André Anjos's avatar
André Anjos committed
79
      opened with :py:func:`open_file` containing the scores.
80

André Anjos's avatar
André Anjos committed
81

André Anjos's avatar
André Anjos committed
82
  Returns:
André Anjos's avatar
André Anjos committed
83

André Anjos's avatar
André Anjos committed
84
    str: The claimed identity -- the client name of the model that was used in
André Anjos's avatar
André Anjos committed
85
    the comparison
André Anjos's avatar
André Anjos committed
86

André Anjos's avatar
André Anjos committed
87
    str: The real identity -- the client name of the probe that was used in the
André Anjos's avatar
André Anjos committed
88
    comparison
89

André Anjos's avatar
André Anjos committed
90
91
92
    str: A label of the probe -- usually the probe file name, or the probe id

    float: The result of the comparison of the model and the probe
93

André Anjos's avatar
André Anjos committed
94
95
  """

96
97
  for i, l in enumerate(open_file(filename)):
    if isinstance(l, bytes): l = l.decode('utf-8')
André Anjos's avatar
André Anjos committed
98
99
100
101
102
103
104
105
106
    s = l.strip()
    if len(s) == 0 or s[0] == '#': continue #empty or comment
    field = [k.strip() for k in s.split()]
    if len(field) < 4:
      raise SyntaxError('Line %d of file "%s" is invalid: %s' % (i, filename, l))
    try:
      score = float(field[3])
    except:
      raise SyntaxError('Cannot convert score to float at line %d of file "%s": %s' % (i, filename, l))
107
    yield (field[0], field[1], field[2], score)
André Anjos's avatar
André Anjos committed
108
109
110


def split_four_column(filename):
André Anjos's avatar
André Anjos committed
111
  """Loads a score set from a single file and splits the scores
112

André Anjos's avatar
André Anjos committed
113
114
115
  Loads a score set from a single file and splits the scores between negatives
  and positives. The score file has to respect the 4 column format as defined
  in the method :py:func:`four_column`.
André Anjos's avatar
André Anjos committed
116
117
118
119

  This method avoids loading and allocating memory for the strings present in
  the file. We only keep the scores.

120

André Anjos's avatar
André Anjos committed
121
122
  Parameters:

André Anjos's avatar
André Anjos committed
123
    filename (:py:class:`str`, ``file-like``): The file object that will be
André Anjos's avatar
André Anjos committed
124
      opened with :py:func:`open_file` containing the scores.
André Anjos's avatar
André Anjos committed
125

André Anjos's avatar
André Anjos committed
126

André Anjos's avatar
André Anjos committed
127
  Returns:
128

André Anjos's avatar
André Anjos committed
129
    negatives (array): 1D float array containing the list of scores, for which
André Anjos's avatar
André Anjos committed
130
131
    the ``claimed_id`` and the ``real_id`` differed (see
    :py:func:`four_column`)
André Anjos's avatar
André Anjos committed
132
133

    positivies (array): 1D float array containing the list of scores, for which
André Anjos's avatar
André Anjos committed
134
135
    the ``claimed_id`` and the ``real_id`` are identical (see
    :py:func:`four_column`)
136
137

  """
André Anjos's avatar
André Anjos committed
138

139
140
  score_lines = load_score_with_generator(filename, 4)
  return get_negatives_positives_from_generator(score_lines)
André Anjos's avatar
André Anjos committed
141

André Anjos's avatar
André Anjos committed
142

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
143
def cmc_four_column(filename):
André Anjos's avatar
André Anjos committed
144
  """Loads scores to compute CMC curves from a file in four column format.
145

André Anjos's avatar
André Anjos committed
146
147
148
  The four column file needs to be in the same format as described in
  :py:func:`four_column`, and the ``test_label`` (column 3) has to contain the
  test/probe file name or a probe id.
149

André Anjos's avatar
André Anjos committed
150
151
152
153
154
  This function returns a list of tuples.  For each probe file, the tuple
  consists of a list of negative scores and a list of positive scores.
  Usually, the list of positive scores should contain only one element, but
  more are allowed.  The result of this function can directly be passed to,
  e.g., the :py:func:`bob.measure.cmc` function.
155

156

André Anjos's avatar
André Anjos committed
157
  Parameters:
158

André Anjos's avatar
André Anjos committed
159
    filename (:py:class:`str`, ``file-like``): The file object that will be
André Anjos's avatar
André Anjos committed
160
      opened with :py:func:`open_file` containing the scores.
161

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
162

André Anjos's avatar
André Anjos committed
163
  Returns:
164

André Anjos's avatar
André Anjos committed
165
    list: A list of tuples, where each tuple contains the ``negative`` and
André Anjos's avatar
André Anjos committed
166
167
168
    ``positive`` scores for one probe of the database. Both ``negatives`` and
    ``positives`` can be either an 1D :py:class:`numpy.ndarray` of type
    ``float``, or ``None``.
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
169

170
  """
André Anjos's avatar
André Anjos committed
171

André Anjos's avatar
André Anjos committed
172
173
174
  # extract positives and negatives
  pos_dict = {}
  neg_dict = {}
175
176
177
178
179
180
181
182
  # read four column list
  for (client_id, probe_id, probe_name, score) in four_column(filename):
    # check in which dict we have to put the score
    correct_dict = pos_dict if client_id == probe_id else neg_dict

    # append score
    if probe_name in correct_dict:
      correct_dict[probe_name].append(score)
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
183
    else:
184
      correct_dict[probe_name] = [score]
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
185

186
187
  # convert that into the desired format
  return _convert_cmc_scores(neg_dict, pos_dict)
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
188

André Anjos's avatar
André Anjos committed
189
190

def five_column(filename):
André Anjos's avatar
André Anjos committed
191
192
193
194
195
196
  """Loads a score set from a single file and yield its lines

  Loads a score set from a single file and yield its lines (to avoid loading
  the score file at once into memory).  This function verifies that all fields
  are correctly placed and contain valid fields.  The score file must contain
  the following information in each line:
197

André Anjos's avatar
André Anjos committed
198
  .. code-block:: text
199

André Anjos's avatar
André Anjos committed
200
     claimed_id model_label real_id test_label score
201
202


André Anjos's avatar
André Anjos committed
203
  Parameters:
204

André Anjos's avatar
André Anjos committed
205
    filename (:py:class:`str`, ``file-like``): The file object that will be
André Anjos's avatar
André Anjos committed
206
      opened with :py:func:`open_file` containing the scores.
207
208


André Anjos's avatar
André Anjos committed
209
  Returns:
210

André Anjos's avatar
André Anjos committed
211
    str: The claimed identity -- the client name of the model that was used in
André Anjos's avatar
André Anjos committed
212
    the comparison
213

André Anjos's avatar
André Anjos committed
214
215
216
    str: A label for the model -- usually the model file name, or the model id

    str: The real identity -- the client name of the probe that was used in the
André Anjos's avatar
André Anjos committed
217
    comparison
André Anjos's avatar
André Anjos committed
218
219
220
221

    str: A label of the probe -- usually the probe file name, or the probe id

    float: The result of the comparison of the model and the probe
222

André Anjos's avatar
André Anjos committed
223
224
  """

225
  for i, l in enumerate(open_file(filename)):
226
    if isinstance(l, bytes): l = l.decode('utf-8')
André Anjos's avatar
André Anjos committed
227
228
229
230
231
232
233
234
235
    s = l.strip()
    if len(s) == 0 or s[0] == '#': continue #empty or comment
    field = [k.strip() for k in s.split()]
    if len(field) < 5:
      raise SyntaxError('Line %d of file "%s" is invalid: %s' % (i, filename, l))
    try:
      score = float(field[4])
    except:
      raise SyntaxError('Cannot convert score to float at line %d of file "%s": %s' % (i, filename, l))
236
    yield (field[0], field[1], field[2], field[3], score)
André Anjos's avatar
André Anjos committed
237

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
238

André Anjos's avatar
André Anjos committed
239
def split_five_column(filename):
André Anjos's avatar
André Anjos committed
240
  """Loads a score set from a single file and splits the scores
241

André Anjos's avatar
André Anjos committed
242
243
244
  Loads a score set from a single file in five column format and splits the
  scores between negatives and positives. The score file has to respect the 5
  column format as defined in the method :py:func:`five_column`.
André Anjos's avatar
André Anjos committed
245
246
247
248

  This method avoids loading and allocating memory for the strings present in
  the file. We only keep the scores.

249

André Anjos's avatar
André Anjos committed
250
251
  Parameters:

André Anjos's avatar
André Anjos committed
252
    filename (:py:class:`str`, ``file-like``): The file object that will be
André Anjos's avatar
André Anjos committed
253
      opened with :py:func:`open_file` containing the scores.
André Anjos's avatar
André Anjos committed
254

255

André Anjos's avatar
André Anjos committed
256
  Returns:
257

André Anjos's avatar
André Anjos committed
258
    negatives (array): 1D float array containing the list of scores, for which
André Anjos's avatar
André Anjos committed
259
260
    the ``claimed_id`` and the ``real_id`` differed (see
    :py:func:`four_column`)
André Anjos's avatar
André Anjos committed
261
262

    positivies (array): 1D float array containing the list of scores, for which
André Anjos's avatar
André Anjos committed
263
264
    the ``claimed_id`` and the ``real_id`` are identical (see
    :py:func:`four_column`)
265

André Anjos's avatar
André Anjos committed
266
  """
André Anjos's avatar
André Anjos committed
267

268
269
  score_lines = load_score_with_generator(filename, 5)
  return get_negatives_positives_from_generator(score_lines)
André Anjos's avatar
André Anjos committed
270

271

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
272
def cmc_five_column(filename):
André Anjos's avatar
André Anjos committed
273
274
275
276
277
278
279
280
281
282
283
  """Loads scores to compute CMC curves from a file in five column format.

  The five column file needs to be in the same format as described in
  :py:func:`five_column`, and the ``test_label`` (column 4) has to contain the
  test/probe file name or a probe id.

  This function returns a list of tuples.  For each probe file, the tuple
  consists of a list of negative scores and a list of positive scores.
  Usually, the list of positive scores should contain only one element, but
  more are allowed.  The result of this function can directly be passed to,
  e.g., the :py:func:`bob.measure.cmc` function.
284

André Anjos's avatar
André Anjos committed
285

André Anjos's avatar
André Anjos committed
286
  Parameters:
287

André Anjos's avatar
André Anjos committed
288
    filename (:py:class:`str`, ``file-like``): The file object that will be
André Anjos's avatar
André Anjos committed
289
      opened with :py:func:`open_file` containing the scores.
290
291


André Anjos's avatar
André Anjos committed
292
  Returns:
293

André Anjos's avatar
André Anjos committed
294
    list: A list of tuples, where each tuple contains the ``negative`` and
André Anjos's avatar
André Anjos committed
295
    ``positive`` scores for one probe of the database.
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
296

André Anjos's avatar
André Anjos committed
297
  """
298
  # extract positives and negatives
André Anjos's avatar
André Anjos committed
299
300
  pos_dict = {}
  neg_dict = {}
301
302
303
  # read four column list
  for (client_id, _, probe_id, probe_name, score) in five_column(filename):
    # check in which dict we have to put the score
304
305
    correct_dict = pos_dict if client_id == probe_id else neg_dict

306
307
308
309
310
    # append score
    if probe_name in correct_dict:
      correct_dict[probe_name].append(score)
    else:
      correct_dict[probe_name] = [score]
André Anjos's avatar
André Anjos committed
311

312
313
  # convert that into the desired format
  return _convert_cmc_scores(neg_dict, pos_dict)
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
COLUMNS = {
  4 : ('claimed_id', 'real_id', 'test_label', 'score'),
  5 : ('claimed_id', 'model_label', 'real_id', 'test_label', 'score')
}

def load_score_with_generator(filename, ncolumns=None):
  """Load scores using :py:class:`csv.reader` and yield the scores line by line in a dictionary.

  Parameters:

    filename (:py:class:`str`, ``file-like``): The file object that will be
      opened with :py:func:`open_file` containing the scores.

    ncolumns (:py:class:`int`, optional): 4, 5 or None (the default),
      specifying the number of columns in the score file. If None is provided,
      the number of columns will be guessed.


  Yields:

    line: A dictionary which contains not only the actual ``score`` but also the
    ``claimed_id``, ``real_id``, ``test_label`` (and ``['model_label']``)
  """

  if ncolumns is None:
    f = open_file(filename)
    try:
      line = f.readline()
      ncolumns = len(line.split())
    except Exception:
      logger.warn('Could not guess the number of columns in file: {}. '
                  'Assuming 4 column format.'.format(filename))
      ncolumns = 4
    finally:
      f.close()
  elif ncolumns not in (4,5):
    raise ValueError("ncolumns of 4 and 5 are supported only.")

  names = COLUMNS[ncolumns]
  r = csv.reader(open_file(filename, mode='rb'), delimiter=' ')
  for n, splits in enumerate(r):
    assert len(splits) == ncolumns, "The line %d: %s of file %s is not compatible" % (n, " ".join(splits), filename)
    splits[-1] = float(splits[-1])
    yield {names[i] : splits[i] for i in range(ncolumns)}


def get_negatives_positives_from_generator(score_lines):
  """Take the output of :py:func:`load_score_with_generator` and return negatives and positives.  This
  function aims to replace split_four_column and split_five_column but takes a
  different input. It's up to you to use which one.
  """
  positives, negatives = [], []
  for line in score_lines:
    which = positives if line['claimed_id'] == line['real_id'] else negatives
    which.append(line['score'])

  return (numpy.array(negatives), numpy.array(positives))


375
def load_score(filename, ncolumns=None):
376
377
  """Load scores using numpy.loadtxt and return the data as a numpy array.

André Anjos's avatar
André Anjos committed
378
  Parameters:
379

André Anjos's avatar
André Anjos committed
380
    filename (:py:class:`str`, ``file-like``): The file object that will be
André Anjos's avatar
André Anjos committed
381
      opened with :py:func:`open_file` containing the scores.
382

André Anjos's avatar
André Anjos committed
383
384
385
    ncolumns (:py:class:`int`, optional): 4, 5 or None (the default),
      specifying the number of columns in the score file. If None is provided,
      the number of columns will be guessed.
386
387


André Anjos's avatar
André Anjos committed
388
389
390
  Returns:

    array: An array which contains not only the actual scores but also the
André Anjos's avatar
André Anjos committed
391
    ``claimed_id``, ``real_id``, ``test_label`` and ``['model_label']``
392
393
394

  """

395
396
397
398
399
400
401
402
403
404
405
406
407
408
  def convertfunc(x):
    return x

  if ncolumns not in (4, 5):
    f = open_file(filename)
    try:
      line = f.readline()
      ncolumns = len(line.split())
    except Exception:
      logger.warn('Could not guess the number of columns in file: {}. '
                  'Assuming 4 column format.'.format(filename))
      ncolumns = 4
    finally:
      f.close()
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440

  if ncolumns == 4:
    names = ('claimed_id', 'real_id', 'test_label', 'score')
    converters = {
      0: convertfunc,
      1: convertfunc,
      2: convertfunc,
      3: float}

  elif ncolumns == 5:
    names = ('claimed_id', 'model_label', 'real_id', 'test_label', 'score')
    converters = {
      0: convertfunc,
      1: convertfunc,
      2: convertfunc,
      3: convertfunc,
      4: float}
  else:
    raise ValueError("ncolumns of 4 and 5 are supported only.")

  score_lines = numpy.genfromtxt(
    open_file(filename, mode='rb'), dtype=None, names=names,
    converters=converters, invalid_raise=True)
  new_dtype = []
  for name in score_lines.dtype.names[:-1]:
    new_dtype.append((name, str(score_lines.dtype[name]).replace('S', 'U')))
  new_dtype.append(('score', float))
  score_lines = numpy.array(score_lines, new_dtype)
  return score_lines


def get_negatives_positives(score_lines):
André Anjos's avatar
André Anjos committed
441
442
443
  """Take the output of load_score and return negatives and positives.  This
  function aims to replace split_four_column and split_five_column but takes a
  different input. It's up to you to use which one.
444
  """
André Anjos's avatar
André Anjos committed
445

446
447
448
449
450
451
452
453
  pos_mask = score_lines['claimed_id'] == score_lines['real_id']
  positives = score_lines['score'][pos_mask]
  negatives = score_lines['score'][numpy.logical_not(pos_mask)]
  return (negatives, positives)


def get_negatives_positives_all(score_lines_list):
  """Take a list of outputs of load_score and return stacked negatives and
André Anjos's avatar
André Anjos committed
454
455
456
  positives.
  """

457
458
459
460
461
462
463
464
465
466
467
468
  negatives, positives = [], []
  for score_lines in score_lines_list:
    neg_pos = get_negatives_positives(score_lines)
    negatives.append(neg_pos[0])
    positives.append(neg_pos[1])
  negatives = numpy.vstack(negatives).T
  positives = numpy.vstack(positives).T
  return (negatives, positives)


def get_all_scores(score_lines_list):
  """Take a list of outputs of load_score and return stacked scores"""
André Anjos's avatar
André Anjos committed
469

470
471
472
473
474
475
476
477
  return numpy.vstack([score_lines['score']
                       for score_lines in score_lines_list]).T


def dump_score(filename, score_lines):
  """Dump scores that were loaded using :py:func:`load_score`
  The number of columns is automatically detected.
  """
André Anjos's avatar
André Anjos committed
478

479
480
481
482
483
484
485
  if len(score_lines.dtype) == 5:
    fmt = '%s %s %s %s %.9f'
  elif len(score_lines.dtype) == 4:
    fmt = '%s %s %s %.9f'
  else:
    raise ValueError("Only scores with 4 and 5 columns are supported.")
  numpy.savetxt(filename, score_lines, fmt=fmt)
486

André Anjos's avatar
André Anjos committed
487

488
def _convert_cmc_scores(neg_dict, pos_dict):
André Anjos's avatar
André Anjos committed
489
490
491
492
493
  """Converts the negative and positive scores read with
  :py:func:`cmc_four_column` or :py:func:`cmc_four_column` into a format that
  is handled by the :py:func:`bob.measure.cmc` and similar functions.
  """

494
495
496
497
498
499
500
  # convert to lists of tuples of ndarrays (or None)
  probe_names = sorted(set(neg_dict.keys()).union(set(pos_dict.keys())))
  # get all scores in the desired format
  return [(
    numpy.array(neg_dict[probe_name], numpy.float64) if probe_name in neg_dict else None,
    numpy.array(pos_dict[probe_name], numpy.float64) if probe_name in pos_dict else None
  ) for probe_name in probe_names]