load.py 13.2 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Mon 23 May 2011 16:23:05 CEST

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

import numpy
10
11
12
import tarfile
import os

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

16
def open_file(filename, mode='rt'):
17
18
19
  """open_file(filename) -> file_like

  Opens the given score file for reading.
20
21
  Score files might be raw text files, or a tar-file including a single score file inside.

22
  **Parameters:**
23

24
  ``filename`` : str or file-like
25
26
    The name of the score file to 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 containing a raw text file.
27

28
29
30
  **Returns:**

  ``file_like`` : file-like
31
32
    A read-only file-like object as it would be returned by open().
  """
33
34
35
36
  if not isinstance(filename, str) and hasattr(filename, 'read'):
    # It seems that this is an open file
    return filename

37
38
39
  if not os.path.isfile(filename):
    raise IOError("Score file '%s' does not exist." % filename)
  if not tarfile.is_tarfile(filename):
40
    return open(filename, mode)
41
42
43
44
45
46
47
48
49
50
51
52
53
54

  # 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
55
56

def four_column(filename):
57
58
59
60
61
62
63
64
65
66
67
68
  """four_column(filename) -> claimed_id, real_id, test_label, score

  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:

    claimed_id real_id test_label score

  **Parametes:**

  ``filename`` : str or file-like
    The file object that will be opened with :py:func:`open_file` containing the scores.
André Anjos's avatar
André Anjos committed
69

70
  **Yields:**
André Anjos's avatar
André Anjos committed
71

72
73
  ``claimed_id`` : str
    The claimed identity -- the client name of the model that was used in the comparison
André Anjos's avatar
André Anjos committed
74

75
76
77
78
79
80
81
82
  ``real_id`` : str
    The real identity -- the client name of the probe that was used in the comparison

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

  ``score`` : float
    The result of the comparison of the model and the probe
André Anjos's avatar
André Anjos committed
83
84
  """

85
86
  for i, l in enumerate(open_file(filename)):
    if isinstance(l, bytes): l = l.decode('utf-8')
André Anjos's avatar
André Anjos committed
87
88
89
90
91
92
93
94
95
    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))
96
    yield (field[0], field[1], field[2], score)
André Anjos's avatar
André Anjos committed
97
98
99


def split_four_column(filename):
100
101
102
103
104
  """split_four_column(filename) -> negatives, positives

  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
105
106
107
108

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

109
110
111
112
  **Parameters:**

  ``filename`` : str or file-like
    The file that will be opened with :py:func:`open_file` containing the scores.
André Anjos's avatar
André Anjos committed
113

114
115
116
117
118
119
120
121
  **Returns:**

  ``negatives`` : array_like(1D, float)
    The list of ``score``'s, for which the ``claimed_id`` and the ``real_id`` differed (see :py:func:`four_column`).

  ``positives`` : array_like(1D, float)
    The list of ``score``'s, for which the ``claimed_id`` and the ``real_id`` are identical (see :py:func:`four_column`).
  """
122
123
  score_lines = load_score(filename, 4)
  return get_negatives_positives(score_lines)
André Anjos's avatar
André Anjos committed
124

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
125
def cmc_four_column(filename):
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
126
  """cmc_four_column(filename) -> cmc_scores
127
128
129
130

  Loads scores to compute CMC curves from a file in four column format.
  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.
131
132
133
134

  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.
135
  The result of this function can directly be passed to, e.g., the :py:func:`bob.measure.cmc` function.
136

137

138
139
140
141
142
  **Parameters:**

  ``filename`` : str or file-like
    The file that will be opened with :py:func:`open_file` containing the scores.

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

144
145
  **Returns:**

146
147
148
  ``cmc_scores`` : [(negatives, positives)]
    A list of tuples, where each tuple contains the ``negative`` and ``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
149

150
  """
André Anjos's avatar
André Anjos committed
151
152
153
  # extract positives and negatives
  pos_dict = {}
  neg_dict = {}
154
155
156
157
158
159
160
161
  # 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
162
    else:
163
      correct_dict[probe_name] = [score]
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
164

165
166
  # 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
167

André Anjos's avatar
André Anjos committed
168
169
170


def five_column(filename):
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
  """five_column(filename) -> claimed_id, model_label, real_id, test_label, score

  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:

    claimed_id model_label real_id test_label score

  **Parametes:**

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

  **Yields:**

  ``claimed_id`` : str
    The claimed identity -- the client name of the model that was used in the comparison

  ``model_label`` : str
    A label for the model -- usually the model file name, or the model id

  ``real_id`` : str
    The real identity -- the client name of the probe that was used in the comparison

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

  ``score`` : float
    The result of the comparison of the model and the probe.
André Anjos's avatar
André Anjos committed
200
201
  """

202
  for i, l in enumerate(open_file(filename)):
203
    if isinstance(l, bytes): l = l.decode('utf-8')
André Anjos's avatar
André Anjos committed
204
205
206
207
208
209
210
211
212
    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))
213
    yield (field[0], field[1], field[2], field[3], score)
André Anjos's avatar
André Anjos committed
214

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

André Anjos's avatar
André Anjos committed
216
def split_five_column(filename):
217
218
219
220
221
  """split_five_column(filename) -> negatives, positives

  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 4 column
  format as defined in the method :py:func:`five_column`.
André Anjos's avatar
André Anjos committed
222
223
224
225

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

226
227
228
229
230
231
232
233
234
235
236
237
  **Parameters:**

  ``filename`` : str or file-like
    The file that will be opened with :py:func:`open_file` containing the scores.

  **Returns:**

  ``negatives`` : array_like(1D, float)
    The list of ``score``'s, for which the ``claimed_id`` and the ``real_id`` differed (see :py:func:`five_column`).

  ``positives`` : array_like(1D, float)
    The list of ``score``'s, for which the ``claimed_id`` and the ``real_id`` are identical (see :py:func:`five_column`).
André Anjos's avatar
André Anjos committed
238
  """
239
240
  score_lines = load_score(filename, 5)
  return get_negatives_positives(score_lines)
André Anjos's avatar
André Anjos committed
241

242

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
243
def cmc_five_column(filename):
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
244
  """cmc_four_column(filename) -> cmc_scores
245

246
247
248
  Loads scores to compute CMC curves from a file in five column format.
  The four 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.
André Anjos's avatar
André Anjos committed
249

250
251
252
  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.
253
  The result of this function can directly be passed to, e.g., the :py:func:`bob.measure.cmc` function.
254
255
256
257
258
259
260
261
262
263

  **Parameters:**

  ``filename`` : str or file-like
    The file that will be opened with :py:func:`open_file` containing the scores.

  **Returns:**

  ``cmc_scores`` : [(array_like(1D, float), array_like(1D, float))]
    A list of tuples, where each tuple contains the ``negative`` and ``positive`` scores for one probe of the database
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
264

André Anjos's avatar
André Anjos committed
265
  """
266
  # extract positives and negatives
André Anjos's avatar
André Anjos committed
267
268
  pos_dict = {}
  neg_dict = {}
269
270
271
  # 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
272
273
    correct_dict = pos_dict if client_id == probe_id else neg_dict

274
275
276
277
278
    # 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
279

280
281
  # 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
282

283

284
def load_score(filename, ncolumns = 4):
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
  """Load scores using numpy.loadtxt and return the data as a numpy array.

  **Parameters:**

  ``filename`` : str or file-like
    A path or file-like object that will be read with :py:func:`numpy.loadtxt`
    containing the scores.

  ``ncolumns`` : 4 or 5 [default is 4]
    Specifies the number of columns in the score file.

  **Returns:**

  ``score_lines`` : numpy array
    An array which contains not only the actual scores but also the
    'claimed_id', 'real_id', 'test_label', and ['model_label']

  """

304
  convertfunc = lambda x : x
305
306
307
308
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

  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):
  """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.
  """
  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
  positives."""
  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"""
  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.
  """
  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)
377
378
379
380
381
382
383
384
385
386

def _convert_cmc_scores(neg_dict, pos_dict):
  """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."""
  # 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]