test_filelist.py 15.7 KB
Newer Older
Amir Mohammadi's avatar
Amir Mohammadi committed
1
2
3
4
5
6
7
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

"""A few checks at the Verification Filelist database.
"""

import os
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
8
import bob.io.base
Amir Mohammadi's avatar
Amir Mohammadi committed
9
import bob.io.base.test_utils
10
11
12
13
14
from bob.bio.base.database import (
    CSVDatasetDevEval,
    CSVToSampleLoader,
    CSVDatasetCrossValidation,
)
15
import nose.tools
16
17
from bob.pipelines import DelayedSample, SampleSet
import numpy as np
18
from bob.bio.base.test.utils import atnt_database_directory
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
19
20
21
22
from bob.bio.base.pipelines.vanilla_biometrics import (
    Distance,
    VanillaBiometricsPipeline,
)
23
from bob.bio.base.database import FileListBioDatabase
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
24
25
26
from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import make_pipeline
from bob.pipelines import wrap
Amir Mohammadi's avatar
Amir Mohammadi committed
27

28
29
30
31
32

legacy_example_dir = os.path.realpath(
    bob.io.base.test_utils.datafile(".", __name__, "data/example_filelist")
)

33
34
35
example_dir = os.path.realpath(
    bob.io.base.test_utils.datafile(".", __name__, "data/example_csv_filelist")
)
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
36
37
38
atnt_protocol_path = os.path.realpath(
    bob.io.base.test_utils.datafile(".", __name__, "data/atnt")
)
Amir Mohammadi's avatar
Amir Mohammadi committed
39

40
41
42
43
44
45
atnt_protocol_path_cross_validation = os.path.join(
    os.path.realpath(
        bob.io.base.test_utils.datafile(".", __name__, "data/atnt/cross_validation/")
    ),
    "metadata.csv",
)
46

Amir Mohammadi's avatar
Amir Mohammadi committed
47

48
49
50
51
52
def check_all_true(list_of_something, something):
    """
    Assert if list of `Something` contains `Something`
    """
    return np.alltrue([isinstance(s, something) for s in list_of_something])
Amir Mohammadi's avatar
Amir Mohammadi committed
53
54


55
def test_csv_file_list_dev_only():
Amir Mohammadi's avatar
Amir Mohammadi committed
56

57
58
59
    dataset = CSVDatasetDevEval(example_dir, "protocol_only_dev")
    assert len(dataset.background_model_samples()) == 8
    assert check_all_true(dataset.background_model_samples(), DelayedSample)
Amir Mohammadi's avatar
Amir Mohammadi committed
60

61
62
    assert len(dataset.references()) == 2
    assert check_all_true(dataset.references(), SampleSet)
Amir Mohammadi's avatar
Amir Mohammadi committed
63

64
65
    assert len(dataset.probes()) == 10
    assert check_all_true(dataset.probes(), SampleSet)
Amir Mohammadi's avatar
Amir Mohammadi committed
66
67


68
def test_csv_file_list_dev_only_metadata():
Amir Mohammadi's avatar
Amir Mohammadi committed
69

70
71
    dataset = CSVDatasetDevEval(example_dir, "protocol_only_dev_metadata")
    assert len(dataset.background_model_samples()) == 8
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
72
73
74
75
76
77
78
    assert check_all_true(dataset.background_model_samples(), DelayedSample)
    assert np.alltrue(
        ["METADATA_1" in s.__dict__ for s in dataset.background_model_samples()]
    )
    assert np.alltrue(
        ["METADATA_2" in s.__dict__ for s in dataset.background_model_samples()]
    )
Amir Mohammadi's avatar
Amir Mohammadi committed
79

80
81
    assert len(dataset.references()) == 2
    assert check_all_true(dataset.references(), SampleSet)
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
82
83
    assert np.alltrue(["METADATA_1" in s.__dict__ for s in dataset.references()])
    assert np.alltrue(["METADATA_2" in s.__dict__ for s in dataset.references()])
Amir Mohammadi's avatar
Amir Mohammadi committed
84

85
86
    assert len(dataset.probes()) == 10
    assert check_all_true(dataset.probes(), SampleSet)
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
87
88
89
    assert np.alltrue(["METADATA_1" in s.__dict__ for s in dataset.probes()])
    assert np.alltrue(["METADATA_2" in s.__dict__ for s in dataset.probes()])
    assert np.alltrue(["references" in s.__dict__ for s in dataset.probes()])
Amir Mohammadi's avatar
Amir Mohammadi committed
90
91


92
def test_csv_file_list_dev_eval():
Amir Mohammadi's avatar
Amir Mohammadi committed
93

94
95
96
    dataset = CSVDatasetDevEval(example_dir, "protocol_dev_eval")
    assert len(dataset.background_model_samples()) == 8
    assert check_all_true(dataset.background_model_samples(), DelayedSample)
Amir Mohammadi's avatar
Amir Mohammadi committed
97

98
99
    assert len(dataset.references()) == 2
    assert check_all_true(dataset.references(), SampleSet)
Amir Mohammadi's avatar
Amir Mohammadi committed
100

101
102
    assert len(dataset.probes()) == 10
    assert check_all_true(dataset.references(), SampleSet)
Amir Mohammadi's avatar
Amir Mohammadi committed
103

104
105
    assert len(dataset.references(group="eval")) == 6
    assert check_all_true(dataset.references(group="eval"), SampleSet)
Amir Mohammadi's avatar
Amir Mohammadi committed
106

107
108
    assert len(dataset.probes(group="eval")) == 13
    assert check_all_true(dataset.probes(group="eval"), SampleSet)
Amir Mohammadi's avatar
Amir Mohammadi committed
109
110


111
def test_csv_file_list_atnt():
Amir Mohammadi's avatar
Amir Mohammadi committed
112

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
113
    dataset = CSVDatasetDevEval(atnt_protocol_path, "idiap_protocol")
114
115
116
    assert len(dataset.background_model_samples()) == 200
    assert len(dataset.references()) == 20
    assert len(dataset.probes()) == 100
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
117
118


119
def run_experiment(dataset):
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
120
121
122
123
124
125
126
127
128
    def linearize(X):
        X = np.asarray(X)
        return np.reshape(X, (X.shape[0], -1))

    #### Testing it in a real recognition systems
    transformer = wrap(["sample"], make_pipeline(FunctionTransformer(linearize)))

    vanilla_biometrics_pipeline = VanillaBiometricsPipeline(transformer, Distance())

129
    return vanilla_biometrics_pipeline(
130
        dataset.background_model_samples(), dataset.references(), dataset.probes(),
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
131
132
    )

133
134
135

def data_loader(path):
    import bob.io.image
136

137
138
    return bob.io.base.load(path)

139

140
141
142
143
144
145
146
147
148
149
150
151
152
def test_atnt_experiment():

    dataset = CSVDatasetDevEval(
        dataset_protocol_path=atnt_protocol_path,
        protocol_name="idiap_protocol",
        csv_to_sample_loader=CSVToSampleLoader(
            data_loader=data_loader,
            dataset_original_directory=atnt_database_directory(),
            extension=".pgm",
        ),
    )

    scores = run_experiment(dataset)
153
154
    assert len(scores) == 100
    assert np.alltrue([len(s) == 20] for s in scores)
155
156
157
158
159
160
161


def test_atnt_experiment_cross_validation():

    samples_per_identity = 10
    total_identities = 40
    samples_for_enrollment = 1
162
163

    def run_cross_validataion_experiment(test_size=0.9):
164
165
166
167
168
169
170
171
172
173
174
175
        dataset = CSVDatasetCrossValidation(
            csv_file_name=atnt_protocol_path_cross_validation,
            random_state=0,
            test_size=test_size,
            csv_to_sample_loader=CSVToSampleLoader(
                data_loader=data_loader,
                dataset_original_directory=atnt_database_directory(),
                extension=".pgm",
            ),
        )

        scores = run_experiment(dataset)
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        assert len(scores) == int(
            total_identities
            * test_size
            * (samples_per_identity - samples_for_enrollment)
        )

    run_cross_validataion_experiment(test_size=0.9)
    run_cross_validataion_experiment(test_size=0.8)
    run_cross_validataion_experiment(test_size=0.5)


####
# Testing the Legacy file list
####

191

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
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
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
def test_query():
    db = FileListBioDatabase(
        legacy_example_dir, "test", use_dense_probe_file_list=False
    )

    assert (
        len(db.groups()) == 5
    )  # 5 groups (dev, eval, world, optional_world_1, optional_world_2)

    assert len(db.client_ids()) == 6  # 6 client ids for world, dev and eval
    assert len(db.client_ids(groups="world")) == 2  # 2 client ids for world
    assert (
        len(db.client_ids(groups="optional_world_1")) == 2
    )  # 2 client ids for optional world 1
    assert (
        len(db.client_ids(groups="optional_world_2")) == 2
    )  # 2 client ids for optional world 2
    assert len(db.client_ids(groups="dev")) == 2  # 2 client ids for dev
    assert len(db.client_ids(groups="eval")) == 2  # 2 client ids for eval

    assert len(db.tclient_ids()) == 2  # 2 client ids for T-Norm score normalization
    assert len(db.zclient_ids()) == 2  # 2 client ids for Z-Norm score normalization

    assert len(db.model_ids_with_protocol()) == 6  # 6 model ids for world, dev and eval
    assert len(db.model_ids_with_protocol(groups="world")) == 2  # 2 model ids for world
    assert (
        len(db.model_ids_with_protocol(groups="optional_world_1")) == 2
    )  # 2 model ids for optional world 1
    assert (
        len(db.model_ids_with_protocol(groups="optional_world_2")) == 2
    )  # 2 model ids for optional world 2
    assert len(db.model_ids_with_protocol(groups="dev")) == 2  # 2 model ids for dev
    assert len(db.model_ids_with_protocol(groups="eval")) == 2  # 2 model ids for eval

    assert (
        len(db.tmodel_ids_with_protocol()) == 2
    )  # 2 model ids for T-Norm score normalization

    assert len(db.objects(groups="world")) == 8  # 8 samples in the world set

    assert (
        len(db.objects(groups="dev", purposes="enroll")) == 8
    )  # 8 samples for enrollment in the dev set
    assert (
        len(db.objects(groups="dev", purposes="enroll", model_ids="3")) == 4
    )  # 4 samples for to enroll model '3' in the dev set
    assert (
        len(db.objects(groups="dev", purposes="enroll", model_ids="7")) == 0
    )  # 0 samples for enrolling model '7' (it is a T-Norm model)
    assert (
        len(db.objects(groups="dev", purposes="probe")) == 8
    )  # 8 samples as probes in the dev set
    assert (
        len(db.objects(groups="dev", purposes="probe", classes="client")) == 8
    )  # 8 samples as client probes in the dev set
    assert (
        len(db.objects(groups="dev", purposes="probe", classes="impostor")) == 4
    )  # 4 samples as impostor probes in the dev set

    assert len(db.tobjects(groups="dev")) == 8  # 8 samples for enrolling T-norm models
    assert (
        len(db.tobjects(groups="dev", model_ids="7")) == 4
    )  # 4 samples for enrolling T-norm model '7'
    assert (
        len(db.tobjects(groups="dev", model_ids="3")) == 0
    )  # 0 samples for enrolling T-norm model '3' (no T-Norm model)
    assert len(db.zobjects(groups="dev")) == 8  # 8 samples for Z-norm impostor accesses

    assert db.client_id_from_model_id("1", group=None) == "1"
    assert db.client_id_from_model_id("3", group=None) == "3"
    assert db.client_id_from_model_id("6", group=None) == "6"
    assert db.client_id_from_t_model_id("7", group=None) == "7"


def test_query_protocol():
    db = FileListBioDatabase(
        os.path.dirname(legacy_example_dir),
        "test",
        protocol="example_filelist",
        use_dense_probe_file_list=False,
    )

    assert (
        len(db.groups()) == 5
    )  # 5 groups (dev, eval, world, optional_world_1, optional_world_2)

    assert len(db.client_ids()) == 6  # 6 client ids for world, dev and eval
    assert len(db.client_ids(groups="world",)) == 2  # 2 client ids for world
    assert (
        len(db.client_ids(groups="optional_world_1",)) == 2
    )  # 2 client ids for optional world 1
    assert (
        len(db.client_ids(groups="optional_world_2",)) == 2
    )  # 2 client ids for optional world 2
    assert len(db.client_ids(groups="dev",)) == 2  # 2 client ids for dev
    assert len(db.client_ids(groups="eval",)) == 2  # 2 client ids for eval

    assert len(db.tclient_ids()) == 2  # 2 client ids for T-Norm score normalization
    assert len(db.zclient_ids()) == 2  # 2 client ids for Z-Norm score normalization

    assert len(db.model_ids_with_protocol()) == 6  # 6 model ids for world, dev and eval
    assert (
        len(db.model_ids_with_protocol(groups="world",)) == 2
    )  # 2 model ids for world
    assert (
        len(db.model_ids_with_protocol(groups="optional_world_1",)) == 2
    )  # 2 model ids for optional world 1
    assert (
        len(db.model_ids_with_protocol(groups="optional_world_2",)) == 2
    )  # 2 model ids for optional world 2
    assert len(db.model_ids_with_protocol(groups="dev",)) == 2  # 2 model ids for dev
    assert len(db.model_ids_with_protocol(groups="eval",)) == 2  # 2 model ids for eval

    assert (
        len(db.tmodel_ids_with_protocol()) == 2
    )  # 2 model ids for T-Norm score normalization

    assert len(db.objects(groups="world",)) == 8  # 8 samples in the world set

    assert (
        len(db.objects(groups="dev", purposes="enroll",)) == 8
    )  # 8 samples for enrollment in the dev set
    assert (
        len(db.objects(groups="dev", purposes="enroll", model_ids="3",)) == 4
    )  # 4 samples for to enroll model '3' in the dev set
    assert (
        len(db.objects(groups="dev", purposes="enroll", model_ids="7",)) == 0
    )  # 0 samples for enrolling model '7' (it is a T-Norm model)
    assert (
        len(db.objects(groups="dev", purposes="probe",)) == 8
    )  # 8 samples as probes in the dev set
    assert (
        len(db.objects(groups="dev", purposes="probe", classes="client",)) == 8
    )  # 8 samples as client probes in the dev set
    assert (
        len(db.objects(groups="dev", purposes="probe", classes="impostor",)) == 4
    )  # 4 samples as impostor probes in the dev set

    assert len(db.tobjects(groups="dev",)) == 8  # 8 samples for enrolling T-norm models
    assert (
        len(db.tobjects(groups="dev", model_ids="7",)) == 4
    )  # 4 samples for enrolling T-norm model '7'
    assert (
        len(db.tobjects(groups="dev", model_ids="3",)) == 0
    )  # 0 samples for enrolling T-norm model '3' (no T-Norm model)
    assert len(db.zobjects(groups="dev")) == 8  # 8 samples for Z-norm impostor accesses

    assert db.client_id_from_model_id("1", group=None) == "1"
    assert db.client_id_from_model_id("3", group=None) == "3"
    assert db.client_id_from_model_id("6", group=None) == "6"
    assert db.client_id_from_t_model_id("7", group=None) == "7"

    # check other protocols
    assert len(db.objects(protocol="non-existent")) == 0

    prot = "example_filelist2"
    assert (
        len(db.model_ids_with_protocol(protocol=prot)) == 3
    )  # 3 model ids for dev only
    nose.tools.assert_raises(
        ValueError, db.model_ids_with_protocol, protocol=prot, groups="eval"
    )  # eval does not exist for this protocol
    assert len(db.objects(protocol=prot, groups="dev", purposes="enroll")) == 12
    assert len(db.objects(protocol=prot, groups="dev", purposes="probe")) == 9


def test_noztnorm():
    db = FileListBioDatabase(
        os.path.join(os.path.dirname(legacy_example_dir), "example_filelist2"), "test"
    )
    assert len(db.all_files())


def test_query_dense():
    db = FileListBioDatabase(legacy_example_dir, "test", use_dense_probe_file_list=True)

    assert len(db.objects(groups="world")) == 8  # 8 samples in the world set

    assert (
        len(db.objects(groups="dev", purposes="enroll")) == 8
    )  # 8 samples for enrollment in the dev set
    assert (
        len(db.objects(groups="dev", purposes="probe")) == 8
    )  # 8 samples as probes in the dev set


def test_annotation():
    db = FileListBioDatabase(
        legacy_example_dir,
        "test",
        use_dense_probe_file_list=False,
        annotation_directory=legacy_example_dir,
        annotation_type="named",
    )
    f = [o for o in db.objects() if o.path == "data/model4_session1_sample2"][0]
    annots = db.annotations(f)

    assert annots is not None
    assert "key1" in annots
    assert "key2" in annots
    assert annots["key1"] == (20, 10)
    assert annots["key2"] == (40, 30)


def test_multiple_extensions():
    # check that the old behavior still works
    db = FileListBioDatabase(
        legacy_example_dir,
        "test",
        use_dense_probe_file_list=False,
        original_directory=legacy_example_dir,
        original_extension=".pos",
    )
    file = bob.bio.base.database.BioFile(
        4, "data/model4_session1_sample2", "data/model4_session1_sample2"
    )
    file_name = db.original_file_name(file, True)
    assert file_name == os.path.join(legacy_example_dir, file.path + ".pos")

    # check that the new behavior works as well
    db = FileListBioDatabase(
        legacy_example_dir,
        "test",
        use_dense_probe_file_list=False,
        original_directory=legacy_example_dir,
        original_extension=[".jpg", ".pos"],
    )
    file_name = db.original_file_name(file)
    assert file_name == os.path.join(legacy_example_dir, file.path + ".pos")

    file = bob.bio.base.database.BioFile(
        4, "data/model4_session1_sample1", "data/model4_session1_sample1"
    )
    nose.tools.assert_raises(IOError, db.original_file_name, file, False)


def test_driver_api():
    from bob.db.base.script.dbmanage import main

    assert (
        main(
            (
                "bio_filelist dumplist --list-directory=%s --self-test"
                % legacy_example_dir
            ).split()
        )
        == 0
    )
    assert (
        main(
            (
                "bio_filelist dumplist --list-directory=%s --purpose=enroll --group=dev --class=client --self-test"
                % legacy_example_dir
            ).split()
        )
        == 0
    )
    assert (
        main(
            (
                "bio_filelist checkfiles --list-directory=%s --self-test"
                % legacy_example_dir
            ).split()
        )
        == 0
    )
458