load.py 12.7 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
13
import tarfile
import os

def open_file(filename):
14
15
16
  """open_file(filename) -> file_like

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

19
  **Parameters:**
20

21
  ``filename`` : str or file-like
22
23
    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.
24

25
26
27
  **Returns:**

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

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

  # 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
52
53

def four_column(filename):
54
55
56
57
58
59
60
61
62
63
64
65
  """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
66

67
  **Yields:**
André Anjos's avatar
André Anjos committed
68

69
70
  ``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
71

72
73
74
75
76
77
78
79
  ``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
80
81
  """

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


def split_four_column(filename):
97
98
99
100
101
  """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
102
103
104
105

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

106
107
108
109
  **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
110

111
112
113
114
115
116
117
118
  **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`).
  """
André Anjos's avatar
André Anjos committed
119
120
121
  # split in positives and negatives
  neg = []
  pos = []
122
123
124
125
126
127
  # read four column list line by line
  for (client_id, probe_id, _, score) in four_column(filename):
    if client_id == probe_id:
      pos.append(score)
    else:
      neg.append(score)
André Anjos's avatar
André Anjos committed
128
129
130

  return (numpy.array(neg, numpy.float64), numpy.array(pos, numpy.float64))

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
131
132
133
134
def cmc_four_column(filename, load_only_negatives=False):
  """
  cmc_four_column(filename) -> cmc_scores
  
135
136
137
138

  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.
139
140
141
142

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

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
145
  
146
147
148
149
150
  **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
151
152
153
154
  ``load_only_negatives`` : boolean
    Set this argument to **True** if you want also to load the probes that has negative scores **only** (used for open-set recognition).


155
156
157
158
  **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
159

160
  """
André Anjos's avatar
André Anjos committed
161
162
163
  # extract positives and negatives
  pos_dict = {}
  neg_dict = {}
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
164
  # read four column list  
165
  for (client_id, probe_id, probe_name, score_str) in four_column(filename):
André Anjos's avatar
André Anjos committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    try:
      score = float(score_str)
      # check in which dict we have to put the score
      if client_id == probe_id:
        correct_dict = pos_dict
      else:
        correct_dict = neg_dict
      # append score
      if probe_name in correct_dict:
        correct_dict[probe_name].append(score)
      else:
        correct_dict[probe_name] = [score]
    except:
      raise SyntaxError("Cannot convert score '%s' to float" % score_str)

  # convert to lists of tuples of ndarrays
  retval = []
  import logging
  logger = logging.getLogger('bob')
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
  if(not load_only_negatives):
    for probe_name in sorted(pos_dict.keys()):
      if probe_name in neg_dict:
        retval.append((numpy.array(neg_dict[probe_name], numpy.float64), numpy.array(pos_dict[probe_name], numpy.float64)))
      else:
        logger.warn('For probe name "%s" there are only positive scores. This probe name is ignored.' % probe_name)

    #test if there are probes for which only negatives exist
    for probe_name in sorted(neg_dict.keys()):
      if not probe_name in pos_dict.keys():
        logger.warn('For probe name "%s" there are only negative scores. This probe name is ignored.' % probe_name)

  else:
    for probe_name in sorted(pos_dict.keys()):
André Anjos's avatar
André Anjos committed
199
      retval.append((numpy.array(neg_dict[probe_name], numpy.float64), numpy.array(pos_dict[probe_name], numpy.float64)))
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
200
201
202
203

    for probe_name in sorted(neg_dict.keys()):
      if not probe_name in pos_dict.keys():
        retval.append((numpy.array(neg_dict[probe_name], numpy.float64), numpy.array([], numpy.float64)))
André Anjos's avatar
André Anjos committed
204
205

  return retval
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
206
  
André Anjos's avatar
André Anjos committed
207
208

def five_column(filename):
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
  """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
238
239
  """

240
  for i, l in enumerate(open_file(filename)):
241
    if isinstance(l, bytes): l = l.decode('utf-8')
André Anjos's avatar
André Anjos committed
242
243
244
245
246
247
248
249
250
    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))
251
    yield (field[0], field[1], field[2], field[3], score)
André Anjos's avatar
André Anjos committed
252

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

André Anjos's avatar
André Anjos committed
254
def split_five_column(filename):
255
256
257
258
259
  """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
260
261
262
263

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

264
265
266
267
268
269
270
271
272
273
274
275
  **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
276
277
278
279
280
  """

  # split in positives and negatives
  neg = []
  pos = []
281
282
283
284
285
286
  # read five column list
  for (client_id, _, probe_id, _, score) in five_column(filename):
    if client_id == probe_id:
      pos.append(score)
    else:
      neg.append(score)
André Anjos's avatar
André Anjos committed
287
288
289

  return (numpy.array(neg, numpy.float64), numpy.array(pos, numpy.float64))

290

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
291
292
293
294
def cmc_five_column(filename, load_only_negatives=False):
  """
  cmc_four_column(filename) -> cmc_scores
  
295
296
297
  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
298

299
300
301
  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.
302
  The result of this function can directly be passed to, e.g., the :py:func:`bob.measure.cmc` function.
303
304
305
306
307
308

  **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
309
310
311
312
  ``load_only_negatives`` : boolean
    Set this argument to **True** if you want also to load the probes that has negative scores **only** (used for open-set recognition).


313
314
315
316
  **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
317

André Anjos's avatar
André Anjos committed
318
  """
319
  # extract positives and negatives
André Anjos's avatar
André Anjos committed
320
321
  pos_dict = {}
  neg_dict = {}
322
323
324
325
326
327
328
329
330
331
332
333
  # 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
    if client_id == probe_id:
      correct_dict = pos_dict
    else:
      correct_dict = neg_dict
    # 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
334
335
336
337
338

  # convert to lists of tuples of ndarrays
  retval = []
  import logging
  logger = logging.getLogger('bob')
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
  if(not load_only_negatives):

    for probe_name in sorted(pos_dict.keys()):
      if probe_name in neg_dict:
        retval.append((numpy.array(neg_dict[probe_name], numpy.float64), numpy.array(pos_dict[probe_name], numpy.float64)))
      else:
        logger.warn('For probe name "%s" there are only positive scores. This probe name is ignored.' % probe_name)
    # test if there are probes for which only negatives exist
    for probe_name in sorted(neg_dict.keys()):
      if not probe_name in pos_dict.keys():
         logger.warn('For probe name "%s" there are only negative scores. This probe name is ignored.' % probe_name)
  else:
  
    for probe_name in sorted(pos_dict.keys()):
André Anjos's avatar
André Anjos committed
353
      retval.append((numpy.array(neg_dict[probe_name], numpy.float64), numpy.array(pos_dict[probe_name], numpy.float64)))
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
354
355
356
357
358
359

    for probe_name in sorted(neg_dict.keys()):
      if not probe_name in pos_dict.keys():
        retval.append((numpy.array(neg_dict[probe_name], numpy.float64), numpy.array([], numpy.float64)))
  

André Anjos's avatar
André Anjos committed
360
  return retval