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
19
20
21
22
23
24
25
26
static int double1d_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 != 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);
    return 1;
  }
  return 0;
}
André Anjos's avatar
André Anjos committed
27

André Anjos's avatar
André Anjos committed
28
29
PyDoc_STRVAR(s_epc_str, "epc");
PyDoc_STRVAR(s_epc_doc,
30
"epc(dev_negatives, dev_positives, test_negatives, test_positives, n_points) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
\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
47
:py:func:`bob.measure.min_weighted_error_rate_threshold()`)\n\
André Anjos's avatar
André Anjos committed
48
49
50
51
52
53
54
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\
");

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

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
59
60
61
    "dev_negatives",
    "dev_positives",
    "test_positives",
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    "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;

83
84
85
86
87
88
  //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
89
  auto result = bob::measure::epc(
90
91
92
93
94
95
      *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);

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

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

André Anjos's avatar
André Anjos committed
100
101
PyDoc_STRVAR(s_det_str, "det");
PyDoc_STRVAR(s_det_doc,
102
"det(negatives, positives, n_points) -> numpy.ndarray\n\
103
\n\
André Anjos's avatar
André Anjos committed
104
Calculates points of an Detection Error-Tradeoff Curve (DET).\n\
105
\n\
André Anjos's avatar
André Anjos committed
106
107
108
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\
109
\n\
André Anjos's avatar
André Anjos committed
110
111
[0]\n\
   X axis values in the normal deviate scale for the false-rejections\n\
112
\n\
André Anjos's avatar
André Anjos committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
[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[] = {
130
131
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    "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;

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

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

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

}

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,
192
"roc(negatives, positives, n_points) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
193
194
195
196
197
\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\
198
of doubles that express the X (FAR) and Y (FRR) coordinates in this\n\
André Anjos's avatar
André Anjos committed
199
200
201
202
203
204
205
206
207
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[] = {
208
209
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    "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;

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

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

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

}

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\
270
271
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
272
273
274
275
276
277
278
279
280
281
282
283
\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[] = {
284
285
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    "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;

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

André Anjos's avatar
André Anjos committed
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
  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[] = {
333
334
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
335
336
337
338
339
340
341
342
343
344
345
346
347
    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;

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

André Anjos's avatar
André Anjos committed
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
  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[] = {
378
379
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    "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;

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

André Anjos's avatar
André Anjos committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
  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[] = {
421
422
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
423
424
425
426
427
428
429
430
431
432
433
434
435
    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;

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

André Anjos's avatar
André Anjos committed
440
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
  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[] = {
466
467
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
    "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;

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

André Anjos's avatar
André Anjos committed
488
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
  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[] = {
515
516
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    "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;

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

André Anjos's avatar
André Anjos committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
  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
553
which negatives where correctly classified in a \"negative\" score\n\
André Anjos's avatar
André Anjos committed
554
sample, given a threshold. It runs the formula: foreach (element k in\n\
André Anjos's avatar
André Anjos committed
555
negative) if negative[k] < threshold: returnValue[k] = true else:\n\
André Anjos's avatar
André Anjos committed
556
557
558
559
560
561
562
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[] = {
563
    "negatives",
André Anjos's avatar
André Anjos committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    "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;

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

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

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

}

PyDoc_STRVAR(s_correctly_classified_positives_str, "correctly_classified_positives");
PyDoc_STRVAR(s_correctly_classified_positives_doc,
591
"correctly_classified_positives(positives, threshold) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
592
593
594
595
596
597
598
599
600
601
602
603
\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[] = {
604
    "positives",
André Anjos's avatar
André Anjos committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
    "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;

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

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

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

}

PyDoc_STRVAR(s_precision_recall_curve_str, "precision_recall_curve");
PyDoc_STRVAR(s_precision_recall_curve_doc,
632
"precision_recall_curve(negatives, positives, n_points) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
633
634
635
636
637
638
639
640
641
642
643
644
645
\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[] = {
646
647
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    "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;

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

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

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

}

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\
696
697
");

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

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
702
703
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
    "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;

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

André Anjos's avatar
André Anjos committed
724
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
  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[] = {
758
759
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
    "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;

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

André Anjos's avatar
André Anjos committed
780
781
782
783
784
785
786
787
788
  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
789
790
791
792
793
794
795
796
797
798
799
800
801
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[] = {
802
803
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
804
805
806
807
808
809
810
811
812
813
814
815
816
    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;

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

André Anjos's avatar
André Anjos committed
821
822
823
824
825
826
827
828
829
830
831
  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,
832
"rocch(negatives, positives) -> numpy.ndarray\n\
André Anjos's avatar
André Anjos committed
833
834
835
\n\
Calculates the ROC Convex Hull curve given a set of positive and\n\
negative scores. Returns a two-dimensional array of doubles\n\
836
that express the X (FAR) and Y (FRR) coordinates in this order.\n\
André Anjos's avatar
André Anjos committed
837
838
839
840
841
842
");

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

  /* Parses input arguments in a single shot */
  static const char* const_kwlist[] = {
843
844
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
845
846
847
848
849
850
851
852
853
854
855
856
857
    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;

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

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

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

}

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[] = {
893
    "pmiss_pfa",
André Anjos's avatar
André Anjos committed
894
895
896
897
898
899
900
901
902
903
904
    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;

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

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

  return PyFloat_FromDouble(result);

}

913
914
PyDoc_STRVAR(s_roc_for_far_str, "roc_for_far");
PyDoc_STRVAR(s_roc_for_far_doc,
915
"roc_for_far(negatives, positives, far_list) -> numpy.ndarray\n\
916
917
\n\
Calculates the ROC curve given a set of positive and negative\n\
918
scores and the FAR values for which the FRR should be computed.\n\
919
920
921
922
923
924
925
926
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[] = {
927
928
    "negatives",
    "positives",
929
930
931
932
    "far_list",
    0 /* Sentinel */
  };
  static char** kwlist = const_cast<char**>(const_kwlist);
André Anjos's avatar
André Anjos committed
933

934
935
936
937
938
939
940
941
942
943
944
  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;

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

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

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

}

André Anjos's avatar
André Anjos committed
960
static PyMethodDef module_methods[] = {
961
962
963
964
965
966
    {
      s_epc_str,
      (PyCFunction)epc,
      METH_VARARGS|METH_KEYWORDS,
      s_epc_doc
    },
André Anjos's avatar
André Anjos committed
967
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
    {
      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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
    {
      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
    },
1069
1070
1071
1072
1073
1074
    {
      s_roc_for_far_str,
      (PyCFunction)roc_for_far,
      METH_VARARGS|METH_KEYWORDS,
      s_roc_for_far_doc
    },
1075
1076
    {0}  /* Sentinel */
};
André Anjos's avatar
André Anjos committed
1077

André Anjos's avatar
André Anjos committed
1078
1079
1080
1081
1082
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
1083
  BOB_EXT_MODULE_NAME,
André Anjos's avatar
André Anjos committed
1084
1085
  module_docstr,
  -1,
André Anjos's avatar
André Anjos committed
1086
  module_methods,
André Anjos's avatar
André Anjos committed
1087
1088
1089
1090
  0, 0, 0, 0
};
#endif

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

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

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

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

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