main.cpp 32.5 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
3
4
/**
 * @author Andre Anjos <andre.anjos@idiap.ch>
 * @date Fri 25 Oct 16:54:55 2013
 *
André Anjos's avatar
André Anjos committed
5
 * @brief Bindings to bob::measure
André Anjos's avatar
André Anjos committed
6
7
8
9
10
 */

#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
André Anjos's avatar
André Anjos committed
11
12
#include <bob.blitz/cppapi.h>
#include <bob.blitz/cleanup.h>
13
14
15
#include <bob.core/api.h>
#include <bob.io.base/api.h>

André Anjos's avatar
André Anjos committed
16
#include "error.h"
André Anjos's avatar
André Anjos committed
17

18
static int double1d_converter(PyObject* o, PyBlitzArrayObject** a) {
19
20
  if (PyBlitzArray_Converter(o, a) == 0) return 0;
  
21
22
23
  // in this case, *a is set to a new reference
  if ((*a)->type_num != NPY_FLOAT64 || (*a)->ndim != 1) {
    PyErr_Format(PyExc_TypeError, "cannot convert blitz::Array<%s,%" PY_FORMAT_SIZE_T "d> to a blitz::Array<double,1>", PyBlitzArray_TypenumAsString((*a)->type_num), (*a)->ndim);
24
    return 0;
25
  }
26
  return 1;
27
}
André Anjos's avatar
André Anjos committed
28

André Anjos's avatar
André Anjos committed
29
30
PyDoc_STRVAR(s_epc_str, "epc");
PyDoc_STRVAR(s_epc_doc,
31
"epc(dev_negatives, dev_positives, test_negatives, test_positives, n_points) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
\n\
Calculates points of an Expected Performance Curve (EPC).\n\
\n\
Calculates the EPC curve given a set of positive and negative scores\n\
and a desired number of points. Returns a two-dimensional\n\
blitz::Array of doubles that express the X (cost) and Y (HTER on\n\
the test set given the min. HTER threshold on the development set)\n\
coordinates in this order. Please note that, in order to calculate\n\
the EPC curve, one needs two sets of data comprising a development\n\
set and a test set. The minimum weighted error is calculated on the\n\
development set and then applied to the test set to evaluate the\n\
half-total error rate at that position.\n\
\n\
The EPC curve plots the HTER on the test set for various values of\n\
'cost'. For each value of 'cost', a threshold is found that provides\n\
the minimum weighted error (see\n\
André Anjos's avatar
André Anjos committed
48
:py:func:`bob.measure.min_weighted_error_rate_threshold()`)\n\
André Anjos's avatar
André Anjos committed
49
50
51
52
53
54
55
on the development set. Each threshold is consecutively applied to\n\
the test set and the resulting HTER values are plotted in the EPC.\n\
\n\
The cost points in which the EPC curve are calculated are\n\
distributed uniformily in the range :math:`[0.0, 1.0]`.\n\
");

56
57
58
59
static PyObject* epc(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
60
61
62
    "dev_negatives",
    "dev_positives",
    "test_positives",
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    "test_negatives",
    "n_points",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* dev_neg = 0;
  PyBlitzArrayObject* dev_pos = 0;
  PyBlitzArrayObject* test_neg = 0;
  PyBlitzArrayObject* test_pos = 0;
  Py_ssize_t n_points = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&O&O&n",
        kwlist,
        &double1d_converter, &dev_neg,
        &double1d_converter, &dev_pos,
        &double1d_converter, &test_neg,
        &double1d_converter, &test_pos,
        &n_points
        )) return 0;

84
85
86
87
88
89
  //protects acquired resources through this scope
  auto dev_neg_ = make_safe(dev_neg);
  auto dev_pos_ = make_safe(dev_pos);
  auto test_neg_ = make_safe(test_neg);
  auto test_pos_ = make_safe(test_pos);

André Anjos's avatar
André Anjos committed
90
  auto result = bob::measure::epc(
91
92
93
94
95
96
      *PyBlitzArrayCxx_AsBlitz<double,1>(dev_neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(dev_pos),
      *PyBlitzArrayCxx_AsBlitz<double,1>(test_neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(test_pos),
      n_points);

97
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
98

99
}
André Anjos's avatar
André Anjos committed
100

André Anjos's avatar
André Anjos committed
101
102
PyDoc_STRVAR(s_det_str, "det");
PyDoc_STRVAR(s_det_doc,
103
"det(negatives, positives, n_points) -> numpy.ndarray\n\
104
\n\
André Anjos's avatar
André Anjos committed
105
Calculates points of an Detection Error-Tradeoff Curve (DET).\n\
106
\n\
André Anjos's avatar
André Anjos committed
107
108
109
Calculates the DET curve given a set of positive and negative scores and\n\
a desired number of points. Returns a two-dimensional array of doubles\n\
that express on its rows:\n\
110
\n\
André Anjos's avatar
André Anjos committed
111
112
[0]\n\
   X axis values in the normal deviate scale for the false-rejections\n\
113
\n\
André Anjos's avatar
André Anjos committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
[1]\n\
   Y axis values in the normal deviate scale for the false-accepts\n\
\n\
You can plot the results using your preferred tool to first create a\n\
plot using rows 0 and 1 from the returned value and then replace the\n\
X/Y axis annotation using a pre-determined set of tickmarks as\n\
recommended by NIST. The algorithm that calculates the deviate\n\
scale is based on function ppndf() from the NIST package DETware\n\
version 2.1, freely available on the internet. Please consult it for\n\
more details. By 20.04.2011, you could find such package `here\n\
<http://www.itl.nist.gov/iad/mig/tools/>`_.\n\
");

static PyObject* det(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
131
132
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    "n_points",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  Py_ssize_t n_points = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&n",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &n_points
        )) return 0;

149
150
151
152
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
153
154
155
156
157
  auto result = bob::measure::det(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      n_points);

158
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192

}

PyDoc_STRVAR(s_ppndf_str, "ppndf");
PyDoc_STRVAR(s_ppndf_doc,
"ppndf(value) -> float\n\
\n\
Returns the Deviate Scale equivalent of a false rejection/acceptance ratio.\n\
\n\
The algorithm that calculates the deviate scale is based on\n\
function ppndf() from the NIST package DETware version 2.1,\n\
freely available on the internet. Please consult it for more\n\
details.\n\
");

static PyObject* ppndf(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
    "value",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  double v = 0.;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "d", kwlist, &v)) return 0;

  return PyFloat_FromDouble(bob::measure::ppndf(v));

}

PyDoc_STRVAR(s_roc_str, "roc");
PyDoc_STRVAR(s_roc_doc,
193
"roc(negatives, positives, n_points) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
194
195
196
197
198
\n\
Calculates points of an Receiver Operating Characteristic (ROC).\n\
\n\
Calculates the ROC curve given a set of positive and negative scores\n\
and a desired number of points. Returns a two-dimensional array\n\
199
of doubles that express the X (FAR) and Y (FRR) coordinates in this\n\
André Anjos's avatar
André Anjos committed
200
201
202
203
204
205
206
207
208
order. The points in which the ROC curve are calculated are\n\
distributed uniformily in the range [min(negatives, positives),\n\
max(negatives, positives)].\n\
");

static PyObject* roc(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
209
210
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    "n_points",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  Py_ssize_t n_points = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&n",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &n_points
        )) return 0;

227
228
229
230
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
231
232
233
234
235
  auto result = bob::measure::roc(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      n_points);

236
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
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

}

PyDoc_STRVAR(s_farfrr_str, "farfrr");
PyDoc_STRVAR(s_farfrr_doc,
"farfrr(negatives, positives, threshold) -> (float, float)\n\
\n\
Calculates the false-acceptance (FA) ratio and the FR false-rejection\n\
(FR) ratio given positive and negative scores and a threshold.\n\
``positives`` holds the score information for samples that are\n\
labelled to belong to a certain class (a.k.a., 'signal' or 'client').\n\
``negatives`` holds the score information for samples that are\n\
labelled **not** to belong to the class (a.k.a., 'noise' or 'impostor').\n\
\n\
It is expected that 'positive' scores are, at least by design, greater\n\
than ``negative`` scores. So, every positive value that falls bellow the\n\
threshold is considered a false-rejection (FR). ``negative`` samples\n\
that fall above the threshold are considered a false-accept (FA).\n\
\n\
Positives that fall on the threshold (exactly) are considered\n\
correctly classified. Negatives that fall on the threshold (exactly)\n\
are considered **incorrectly** classified. This equivalent to setting\n\
the comparision like this pseudo-code:\n\
\n\
foreach (positive as K) if K < threshold: falseRejectionCount += 1\n\
foreach (negative as K) if K >= threshold: falseAcceptCount += 1\n\
\n\
The ``threshold`` value does not necessarily have to fall in the range\n\
covered by the input scores (negatives and positives altogether), but\n\
if it does not, the output will be either (1.0, 0.0) or (0.0, 1.0)\n\
depending on the side the threshold falls.\n\
\n\
The output is in form of a tuple of two double-precision real\n\
numbers. The numbers range from 0 to 1. The first element of the pair\n\
271
272
is the false-accept ratio (FAR). The second element of the pair is the\n\
false-rejection ratio (FRR).\n\
André Anjos's avatar
André Anjos committed
273
274
275
276
277
278
279
280
281
282
283
284
\n\
It is possible that scores are inverted in the negative/positive\n\
sense. In some setups the designer may have setup the system so\n\
``positive`` samples have a smaller score than the ``negative`` ones.\n\
In this case, make sure you normalize the scores so positive samples\n\
have greater scores before feeding them into this method.\n\
");

static PyObject* farfrr(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
285
286
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    "threshold",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  double threshold = 0.;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&d",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &threshold
        )) return 0;

303
304
305
306
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
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
  auto result = bob::measure::farfrr(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      threshold);

  PyObject* retval = PyTuple_New(2);
  PyTuple_SET_ITEM(retval, 0, PyFloat_FromDouble(result.first));
  PyTuple_SET_ITEM(retval, 1, PyFloat_FromDouble(result.second));
  return retval;

}

PyDoc_STRVAR(s_eer_threshold_str, "eer_threshold");
PyDoc_STRVAR(s_eer_threshold_doc,
"eer_threshold(negatives, positives) -> float\n\
\n\
Calculates the threshold that is as close as possible to the\n\
equal-error-rate (EER) given the input data. The EER should be the\n\
point where the FAR equals the FRR. Graphically, this would be\n\
equivalent to the intersection between the ROC (or DET) curves and the\n\
identity.\n\
");

static PyObject* eer_threshold(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
334
335
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
336
337
338
339
340
341
342
343
344
345
346
347
348
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos
        )) return 0;

349
350
351
352
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
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
  double result = bob::measure::eerThreshold(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos));

  return PyFloat_FromDouble(result);

}

PyDoc_STRVAR(s_min_weighted_error_rate_threshold_str,
    "min_weighted_error_rate_threshold");
PyDoc_STRVAR(s_min_weighted_error_rate_threshold_doc,
"min_weighted_error_rate_threshold(negatives, positives, cost) -> float\n\
\n\
Calculates the threshold that minimizes the error rate, given the\n\
input data. An optional parameter 'cost' determines the relative\n\
importance between false-accepts and false-rejections. This number\n\
should be between 0 and 1 and will be clipped to those extremes. The\n\
value to minimize becomes: ER_cost = [cost * FAR] + [(1-cost) * FRR].\n\
The higher the cost, the higher the importance given to **not** making\n\
mistakes classifying negatives/noise/impostors.\n\
");

static PyObject* min_weighted_error_rate_threshold(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
379
380
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
    "cost",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  double cost = 0.;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&d",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &cost
        )) return 0;

397
398
399
400
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  double result = bob::measure::minWeightedErrorRateThreshold(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      cost);

  return PyFloat_FromDouble(result);

}

PyDoc_STRVAR(s_min_hter_threshold_str, "min_hter_threshold");
PyDoc_STRVAR(s_min_hter_threshold_doc,
"min_hter_threshold(negatives, positives) -> float\n\
\n\
Calculates the :py:func:`min_weighted_error_rate_threshold()` with\n\
the cost set to 0.5.\n\
");

static PyObject* min_hter_threshold(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
422
423
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
424
425
426
427
428
429
430
431
432
433
434
435
436
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos
        )) return 0;

437
438
439
440
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
  double result = bob::measure::minHterThreshold(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos));

  return PyFloat_FromDouble(result);

}

PyDoc_STRVAR(s_precision_recall_str, "precision_recall");
PyDoc_STRVAR(s_precision_recall_doc,
"precision_recall(negatives, positives, threshold) -> (float, float)\n\
\n\
Calculates the precision and recall (sensitiveness) values given\n\
positive and negative scores and a threshold. ``positives`` holds the\n\
score information for samples that are labeled to belong to a certain\n\
class (a.k.a., 'signal' or 'client'). ``negatives`` holds the score\n\
information for samples that are labeled **not** to belong to the class\n\
(a.k.a., 'noise' or 'impostor'). For more precise details about how\n\
the method considers error rates, please refer to the documentation of\n\
the method :py:func:`farfrr`.\n\
");

static PyObject* precision_recall(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
467
468
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
    "threshold",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  double threshold = 0.;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&d",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &threshold
        )) return 0;

485
486
487
488
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
  auto result = bob::measure::precision_recall(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      threshold);

  PyObject* retval = PyTuple_New(2);
  PyTuple_SET_ITEM(retval, 0, PyFloat_FromDouble(result.first));
  PyTuple_SET_ITEM(retval, 1, PyFloat_FromDouble(result.second));
  return retval;

}

PyDoc_STRVAR(s_f_score_str, "f_score");
PyDoc_STRVAR(s_f_score_doc,
"f_score(negatives, positives, threshold[, weight=1.0]) -> float\n\
\n\
This method computes F-score of the accuracy of the classification. It\n\
is a weighted mean of precision and recall measurements. The weight\n\
parameter needs to be non-negative real value. In case the weight\n\
parameter is 1, the F-score is called F1 score and is a harmonic mean\n\
between precision and recall values.\n\
");

static PyObject* f_score(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
516
517
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
    "threshold",
    "weight",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  double threshold = 0.;
  double weight = 1.0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&d|d",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &threshold, &weight
        )) return 0;

536
537
538
539
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
540
541
542
543
544
545
546
547
548
549
550
551
552
553
  auto result = bob::measure::f_score(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      threshold, weight);

  return PyFloat_FromDouble(result);

}

PyDoc_STRVAR(s_correctly_classified_negatives_str, "correctly_classified_negatives");
PyDoc_STRVAR(s_correctly_classified_negatives_doc,
"correctly_classified_negatives(negatives, threshold) -> int\n\
\n\
This method returns an array composed of booleans that pin-point\n\
André Anjos's avatar
André Anjos committed
554
which negatives where correctly classified in a \"negative\" score\n\
André Anjos's avatar
André Anjos committed
555
sample, given a threshold. It runs the formula: foreach (element k in\n\
André Anjos's avatar
André Anjos committed
556
negative) if negative[k] < threshold: returnValue[k] = true else:\n\
André Anjos's avatar
André Anjos committed
557
558
559
560
561
562
563
returnValue[k] = false\n\
");

static PyObject* correctly_classified_negatives(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
564
    "negatives",
André Anjos's avatar
André Anjos committed
565
566
567
568
569
570
571
572
573
574
575
576
577
578
    "threshold",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  double threshold = 0.;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&d",
        kwlist,
        &double1d_converter, &neg,
        &threshold
        )) return 0;

579
580
581
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);

André Anjos's avatar
André Anjos committed
582
583
584
585
  auto result = bob::measure::correctlyClassifiedNegatives(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      threshold);

586
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
587
588
589
590
591

}

PyDoc_STRVAR(s_correctly_classified_positives_str, "correctly_classified_positives");
PyDoc_STRVAR(s_correctly_classified_positives_doc,
592
"correctly_classified_positives(positives, threshold) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
593
594
595
596
597
598
599
600
601
602
603
604
\n\
This method returns a 1D array composed of booleans that pin-point\n\
which positives where correctly classified in a 'positive' score\n\
sample, given a threshold. It runs the formula: foreach (element k in\n\
positive) if positive[k] >= threshold: returnValue[k] = true else:\n\
returnValue[k] = false\n\
");

static PyObject* correctly_classified_positives(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
605
    "positives",
André Anjos's avatar
André Anjos committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    "threshold",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* pos = 0;
  double threshold = 0.;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&d",
        kwlist,
        &double1d_converter, &pos,
        &threshold
        )) return 0;

620
621
622
  //protects acquired resources through this scope
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
623
624
625
626
  auto result = bob::measure::correctlyClassifiedPositives(
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      threshold);

627
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
628
629
630
631
632

}

PyDoc_STRVAR(s_precision_recall_curve_str, "precision_recall_curve");
PyDoc_STRVAR(s_precision_recall_curve_doc,
633
"precision_recall_curve(negatives, positives, n_points) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
634
635
636
637
638
639
640
641
642
643
644
645
646
\n\
Calculates the precision-recall curve given a set of positive and\n\
negative scores and a number of desired points. Returns a\n\
two-dimensional array of doubles that express the X (precision)\n\
and Y (recall) coordinates in this order. The points in which the\n\
curve is calculated are distributed uniformly in\n\
the range [min(negatives, positives), max(negatives, positives)].\n\
");

static PyObject* precision_recall_curve(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
647
648
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
    "n_points",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  Py_ssize_t n_points = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&n",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &n_points
        )) return 0;

665
666
667
668
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
669
670
671
672
673
  auto result = bob::measure::precision_recall_curve(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      n_points);

674
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696

}

PyDoc_STRVAR(s_far_threshold_str, "far_threshold");
PyDoc_STRVAR(s_far_threshold_doc,
"far_threshold(negatives, positives[, far_value=0.001]) -> float\n\
\n\
Computes the threshold such that the real FAR is *at least* the\n\
requested ``far_value``.\n\
\n\
Keyword parameters:\n\
\n\
negatives\n\
   The impostor scores to be used for computing the FAR\n\
\n\
positives\n\
   The client scores; ignored by this function\n\
\n\
far_value\n\
   The FAR value where the threshold should be computed\n\
\n\
Returns the computed threshold (float)\n\
697
698
");

André Anjos's avatar
André Anjos committed
699
700
701
702
static PyObject* far_threshold(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
703
704
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
    "threshold",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  double far_value = 0.001;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&|d",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &far_value
        )) return 0;

721
722
723
724
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
  auto result = bob::measure::farThreshold(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      far_value);

  return PyFloat_FromDouble(result);

}

PyDoc_STRVAR(s_frr_threshold_str, "frr_threshold");
PyDoc_STRVAR(s_frr_threshold_doc,
"frr_threshold(negatives, positives[, frr_value=0.001]) -> float\n\
\n\
Computes the threshold such that the real FRR is *at least* the\n\
requested ``frr_value``.\n\
\n\
Keyword parameters:\n\
\n\
negatives\n\
   The impostor scores; ignored by this function\n\
\n\
positives\n\
   The client scores to be used for computing the FRR\n\
\n\
frr_value\n\
   The FRR value where the threshold should be computed\n\
\n\
Returns the computed threshold (float)\n\
");

static PyObject* frr_threshold(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
759
760
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
    "frr_value",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  double frr_value = 0.001;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&|d",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &frr_value
        )) return 0;

777
778
779
780
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
781
782
783
784
785
786
787
788
789
  auto result = bob::measure::frrThreshold(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      frr_value);

  return PyFloat_FromDouble(result);

}

André Anjos's avatar
André Anjos committed
790
791
792
793
794
795
796
797
798
799
800
801
802
PyDoc_STRVAR(s_eer_rocch_str, "eer_rocch");
PyDoc_STRVAR(s_eer_rocch_doc,
"eer_rocch(negatives, positives) -> float\n\
\n\
Calculates the equal-error-rate (EER) given the input data, on\n\
the ROC Convex Hull as done in the Bosaris toolkit\n\
(https://sites.google.com/site/bosaristoolkit/).\n\
");

static PyObject* eer_rocch(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
803
804
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
805
806
807
808
809
810
811
812
813
814
815
816
817
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos
        )) return 0;

818
819
820
821
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
822
823
824
825
826
827
828
829
830
831
832
  auto result = bob::measure::eerRocch(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos)
      );

  return PyFloat_FromDouble(result);

}

PyDoc_STRVAR(s_rocch_str, "rocch");
PyDoc_STRVAR(s_rocch_doc,
833
"rocch(negatives, positives) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
834
835
836
\n\
Calculates the ROC Convex Hull curve given a set of positive and\n\
negative scores. Returns a two-dimensional array of doubles\n\
837
that express the X (FAR) and Y (FRR) coordinates in this order.\n\
André Anjos's avatar
André Anjos committed
838
839
840
841
842
843
");

static PyObject* rocch(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
844
845
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
846
847
848
849
850
851
852
853
854
855
856
857
858
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos
        )) return 0;

859
860
861
862
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
863
864
865
866
867
  auto result = bob::measure::rocch(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos)
      );

868
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893

}

static int double2d_converter(PyObject* o, PyBlitzArrayObject** a) {
  if (PyBlitzArray_Converter(o, a) != 0) return 1;
  // in this case, *a is set to a new reference
  if ((*a)->type_num != NPY_FLOAT64 || (*a)->ndim != 2) {
    PyErr_Format(PyExc_TypeError, "cannot convert blitz::Array<%s,%" PY_FORMAT_SIZE_T "d> to a blitz::Array<double,2>", PyBlitzArray_TypenumAsString((*a)->type_num), (*a)->ndim);
    return 1;
  }
  return 0;
}

PyDoc_STRVAR(s_rocch2eer_str, "rocch2eer");
PyDoc_STRVAR(s_rocch2eer_doc,
"rocch2eer(pmiss_pfa) -> float\n\
\n\
Calculates the threshold that is as close as possible to the\n\
equal-error-rate (EER) given the input data.\n\
");

static PyObject* rocch2eer(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
894
    "pmiss_pfa",
André Anjos's avatar
André Anjos committed
895
896
897
898
899
900
901
902
903
904
905
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);

  PyBlitzArrayObject* p = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&",
        kwlist,
        &double2d_converter, &p
        )) return 0;

906
  auto p_ = make_safe(p);
André Anjos's avatar
André Anjos committed
907

908
  auto result = bob::measure::rocch2eer(*PyBlitzArrayCxx_AsBlitz<double,2>(p));
André Anjos's avatar
André Anjos committed
909
910
911
912
913

  return PyFloat_FromDouble(result);

}

914
915
PyDoc_STRVAR(s_roc_for_far_str, "roc_for_far");
PyDoc_STRVAR(s_roc_for_far_doc,
916
"roc_for_far(negatives, positives, far_list) -> numpy.ndarray\n\
917
918
\n\
Calculates the ROC curve given a set of positive and negative\n\
919
scores and the FAR values for which the FRR should be computed.\n\
920
921
922
923
924
925
926
927
The resulting ROC curve holds a copy of the given FAR values (row\n\
0), and the corresponding FRR values (row 1).\n\
");

static PyObject* roc_for_far(PyObject*, PyObject* args, PyObject* kwds) {

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
928
929
    "negatives",
    "positives",
930
931
932
933
    "far_list",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);
André Anjos's avatar
André Anjos committed
934

935
936
937
938
939
940
941
942
943
944
945
  PyBlitzArrayObject* neg = 0;
  PyBlitzArrayObject* pos = 0;
  PyBlitzArrayObject* list = 0;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&O&",
        kwlist,
        &double1d_converter, &neg,
        &double1d_converter, &pos,
        &double1d_converter, &list
        )) return 0;

946
947
948
949
950
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);
  auto list_ = make_safe(list);

951
952
953
954
955
956
  auto result = bob::measure::roc_for_far(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      *PyBlitzArrayCxx_AsBlitz<double,1>(list)
      );

957
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
958
959
960

}

André Anjos's avatar
André Anjos committed
961
static PyMethodDef module_methods[] = {
962
963
964
965
966
967
    {
      s_epc_str,
      (PyCFunction)epc,
      METH_VARARGS|METH_KEYWORDS,
      s_epc_doc
    },
André Anjos's avatar
André Anjos committed
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
    {
      s_det_str,
      (PyCFunction)det,
      METH_VARARGS|METH_KEYWORDS,
      s_det_doc
    },
    {
      s_ppndf_str,
      (PyCFunction)ppndf,
      METH_VARARGS|METH_KEYWORDS,
      s_ppndf_doc
    },
    {
      s_roc_str,
      (PyCFunction)roc,
      METH_VARARGS|METH_KEYWORDS,
      s_roc_doc
    },
    {
      s_farfrr_str,
      (PyCFunction)farfrr,
      METH_VARARGS|METH_KEYWORDS,
      s_farfrr_doc
    },
    {
      s_eer_threshold_str,
      (PyCFunction)eer_threshold,
      METH_VARARGS|METH_KEYWORDS,
      s_eer_threshold_doc
    },
    {
      s_min_weighted_error_rate_threshold_str,
      (PyCFunction)min_weighted_error_rate_threshold,
      METH_VARARGS|METH_KEYWORDS,
      s_min_weighted_error_rate_threshold_doc
    },
    {
      s_min_hter_threshold_str,
      (PyCFunction)min_hter_threshold,
      METH_VARARGS|METH_KEYWORDS,
      s_min_hter_threshold_doc
    },
    {
      s_precision_recall_str,
      (PyCFunction)precision_recall,
      METH_VARARGS|METH_KEYWORDS,
      s_precision_recall_doc
    },
    {
      s_f_score_str,
      (PyCFunction)f_score,
      METH_VARARGS|METH_KEYWORDS,
      s_f_score_doc
    },
    {
      s_correctly_classified_negatives_str,
      (PyCFunction)correctly_classified_negatives,
      METH_VARARGS|METH_KEYWORDS,
      s_correctly_classified_negatives_doc
    },
    {
      s_correctly_classified_positives_str,
      (PyCFunction)correctly_classified_positives,
      METH_VARARGS|METH_KEYWORDS,
      s_correctly_classified_positives_doc
    },
    {
      s_precision_recall_curve_str,
      (PyCFunction)precision_recall_curve,
      METH_VARARGS|METH_KEYWORDS,
      s_precision_recall_curve_doc
    },
    {
      s_far_threshold_str,
      (PyCFunction)far_threshold,
      METH_VARARGS|METH_KEYWORDS,
      s_far_threshold_doc
    },
    {
      s_frr_threshold_str,
      (PyCFunction)frr_threshold,
      METH_VARARGS|METH_KEYWORDS,
      s_frr_threshold_doc
    },
André Anjos's avatar
André Anjos committed
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
    {
      s_eer_rocch_str,
      (PyCFunction)eer_rocch,
      METH_VARARGS|METH_KEYWORDS,
      s_eer_rocch_doc
    },
    {
      s_rocch_str,
      (PyCFunction)rocch,
      METH_VARARGS|METH_KEYWORDS,
      s_rocch_doc
    },
    {
      s_rocch2eer_str,
      (PyCFunction)rocch2eer,
      METH_VARARGS|METH_KEYWORDS,
      s_rocch2eer_doc
    },
1070
1071
1072
1073
1074
1075
    {
      s_roc_for_far_str,
      (PyCFunction)roc_for_far,
      METH_VARARGS|METH_KEYWORDS,
      s_roc_for_far_doc
    },
1076
1077
    {0}  /* Sentinel */
};
André Anjos's avatar
André Anjos committed
1078

André Anjos's avatar
André Anjos committed
1079
1080
1081
1082
1083
PyDoc_STRVAR(module_docstr, "Bob metrics and performance figures");

#if PY_VERSION_HEX >= 0x03000000
static PyModuleDef module_definition = {
  PyModuleDef_HEAD_INIT,
André Anjos's avatar
André Anjos committed
1084
  BOB_EXT_MODULE_NAME,
André Anjos's avatar
André Anjos committed
1085
1086
  module_docstr,
  -1,
André Anjos's avatar
André Anjos committed
1087
  module_methods,
André Anjos's avatar
André Anjos committed
1088
1089
1090
1091
  0, 0, 0, 0
};
#endif

André Anjos's avatar
André Anjos committed
1092
static PyObject* create_module (void) {
André Anjos's avatar
André Anjos committed
1093

André Anjos's avatar
André Anjos committed
1094
1095
1096
# if PY_VERSION_HEX >= 0x03000000
  PyObject* m = PyModule_Create(&module_definition);
# else
André Anjos's avatar
André Anjos committed
1097
  PyObject* m = Py_InitModule3(BOB_EXT_MODULE_NAME, module_methods, module_docstr);
André Anjos's avatar
André Anjos committed
1098
# endif
André Anjos's avatar
André Anjos committed
1099
1100
  if (!m) return 0;
  auto m_ = make_safe(m); ///< protects against early returns
André Anjos's avatar
André Anjos committed
1101

André Anjos's avatar
André Anjos committed
1102
1103
  /* imports bob.blitz C-API + dependencies */
  if (import_bob_blitz() < 0) return 0;
1104
1105
  if (import_bob_core_logging() < 0) return 0;
  if (import_bob_io_base() < 0) return 0;
André Anjos's avatar
André Anjos committed
1106

1107
  return Py_BuildValue("O", m);
André Anjos's avatar
André Anjos committed
1108
1109
}

André Anjos's avatar
André Anjos committed
1110
PyMODINIT_FUNC BOB_EXT_ENTRY_NAME (void) {
André Anjos's avatar
André Anjos committed
1111
# if PY_VERSION_HEX >= 0x03000000
André Anjos's avatar
André Anjos committed
1112
  return
André Anjos's avatar
André Anjos committed
1113
# endif
André Anjos's avatar
André Anjos committed
1114
    create_module();
André Anjos's avatar
André Anjos committed
1115
}