main.cpp 32.3 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>
André Anjos's avatar
André Anjos committed
13
#include "error.h"
André Anjos's avatar
André Anjos committed
14

15
16
17
18
19
20
21
22
23
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
24

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

52
53
54
55
static PyObject* epc(PyObject*, PyObject* args, PyObject* kwds) {

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

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

93
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
94

95
}
André Anjos's avatar
André Anjos committed
96

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

145
146
147
148
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

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

}

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

223
224
225
226
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

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

}

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

299
300
301
302
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

345
346
347
348
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

393
394
395
396
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

433
434
435
436
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
  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[] = {
463
464
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
    "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;

481
482
483
484
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
  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[] = {
512
513
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
    "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;

532
533
534
535
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

575
576
577
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);

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

582
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
583
584
585
586
587

}

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

616
617
618
  //protects acquired resources through this scope
  auto pos_ = make_safe(pos);

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

623
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
624
625
626
627
628

}

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

661
662
663
664
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

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

}

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\
693
694
");

André Anjos's avatar
André Anjos committed
695
696
697
698
static PyObject* far_threshold(PyObject*, PyObject* args, PyObject* kwds) {

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

717
718
719
720
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
721
722
723
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
  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[] = {
755
756
    "negatives",
    "positives",
André Anjos's avatar
André Anjos committed
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
    "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;

773
774
775
776
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

814
815
816
817
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

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

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

855
856
857
858
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

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

}

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

902
  auto p_ = make_safe(p);
André Anjos's avatar
André Anjos committed
903

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

  return PyFloat_FromDouble(result);

}

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

931
932
933
934
935
936
937
938
939
940
941
  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;

942
943
944
945
946
  //protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);
  auto list_ = make_safe(list);

947
948
949
950
951
952
  auto result = bob::measure::roc_for_far(
      *PyBlitzArrayCxx_AsBlitz<double,1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double,1>(pos),
      *PyBlitzArrayCxx_AsBlitz<double,1>(list)
      );

953
  return PyBlitzArray_NUMPY_WRAP(PyBlitzArrayCxx_NewFromArray(result));
André Anjos's avatar
André Anjos committed
954
955
956

}

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

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

André Anjos's avatar
André Anjos committed
1088
static PyObject* create_module (void) {
André Anjos's avatar
André Anjos committed
1089

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

André Anjos's avatar
André Anjos committed
1098
1099
  /* imports bob.blitz C-API + dependencies */
  if (import_bob_blitz() < 0) return 0;
André Anjos's avatar
André Anjos committed
1100

1101
  return Py_BuildValue("O", m);
André Anjos's avatar
André Anjos committed
1102
1103
}

André Anjos's avatar
André Anjos committed
1104
PyMODINIT_FUNC BOB_EXT_ENTRY_NAME (void) {
André Anjos's avatar
André Anjos committed
1105
# if PY_VERSION_HEX >= 0x03000000
André Anjos's avatar
André Anjos committed
1106
  return
André Anjos's avatar
André Anjos committed
1107
# endif
André Anjos's avatar
André Anjos committed
1108
    create_module();
André Anjos's avatar
André Anjos committed
1109
}