main.cpp 47.1 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
#include <bob.blitz/cleanup.h>
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
12
#include <bob.blitz/cppapi.h>
13
#include <bob.core/api.h>
14
#include <bob.extension/documentation.h>
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
15
#include <bob.io.base/api.h>
16

17
#include "cpp/error.h"
André Anjos's avatar
André Anjos committed
18

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
19 20 21
static int double1d_converter(PyObject *o, PyBlitzArrayObject **a) {
  if (PyBlitzArray_Converter(o, a) == 0)
    return 0;
22 23
  // in this case, *a is set to a new reference
  if ((*a)->type_num != NPY_FLOAT64 || (*a)->ndim != 1) {
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
24 25 26 27
    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);
28
    return 0;
29
  }
30
  return 1;
31
}
André Anjos's avatar
André Anjos committed
32

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
33 34 35
static int double2d_converter(PyObject *o, PyBlitzArrayObject **a) {
  if (PyBlitzArray_Converter(o, a) == 0)
    return 0;
36 37
  // in this case, *a is set to a new reference
  if ((*a)->type_num != NPY_FLOAT64 || (*a)->ndim != 2) {
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
38 39 40 41
    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);
42 43 44 45
    return 0;
  }
  return 1;
}
André Anjos's avatar
André Anjos committed
46

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
static auto epc_doc =
    bob::extension::FunctionDoc(
        "epc", "Calculates points of an Expected Performance Curve (EPC)",
        "Calculates the EPC curve given a set of positive and negative scores "
        "and a desired number of points. "
        "Returns a two-dimensional :py:class:`numpy.ndarray` of type float "
        "with the "
        "shape of ``(2, points)`` or ``(3, points)`` depending on the "
        "``thresholds`` argument. "
        "The rows correspond to the X (cost), Y (weighted error rate on the "
        "test set given the min. threshold on the development set), and the "
        "thresholds which were used to calculate the error (if the "
        "``thresholds`` argument was set to ``True``), respectively. "
        "Please note that, in order to calculate the EPC curve, one needs two "
        "sets of data comprising a development set and a test set. "
        "The minimum weighted error is calculated on the development set and "
        "then applied to the test set to evaluate the weighted error rate at "
        "that position.\n\n"
        "The EPC curve plots the HTER on the test set for various values of "
        "'cost'. "
        "For each value of 'cost', a threshold is found that provides the "
        "minimum weighted error (see "
        ":py:func:`bob.measure.min_weighted_error_rate_threshold`) on the "
        "development set. "
        "Each threshold is consecutively applied to the test set and the "
        "resulting weighted error values are plotted in the EPC.\n\n"
        "The cost points in which the EPC curve are calculated are distributed "
        "uniformly in the range :math:`[0.0, 1.0]`.\n\n"
        ".. note:: It is more memory efficient, when sorted arrays of scores "
        "are provided and the ``is_sorted`` parameter is set to ``True``.")
        .add_prototype("dev_negatives, dev_positives, test_negatives, "
                       "test_positives, n_points, [is_sorted], [thresholds]",
                       "curve")
        .add_parameter(
            "dev_negatives, dev_positives, test_negatives, test_positives",
            "array_like(1D, float)", "The scores for negatives and positives "
                                     "of the development and test set")
        .add_parameter(
            "n_points", "int",
            "The number of weights for which the EPC curve should be computed")
        .add_parameter("is_sorted", "bool",
                       "[Default: ``False``] Set this to ``True`` if the "
                       "scores are already sorted. If ``False``, scores will "
                       "be sorted internally, which will require more memory")
        .add_parameter("thresholds", "bool",
                       "[Default: ``False``] If ``True`` the function returns "
                       "an array with the shape of ``(3, points)`` where the "
                       "third row contains the thresholds that were calculated "
                       "on the development set.")
        .add_return("curve", "array_like(2D, float)",
                    "The EPC curve, with the first row containing the weights "
                    "and the second row containing the weighted errors on the "
                    "test set. If ``thresholds`` is ``True``, there is also a "
                    "third row which contains the thresholds that were "
                    "calculated on the development set.");
static PyObject *epc(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
104
  /* Parses input arguments in a single shot */
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
105
  char **kwlist = epc_doc.kwlist();
106

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
107 108 109 110
  PyBlitzArrayObject *dev_neg;
  PyBlitzArrayObject *dev_pos;
  PyBlitzArrayObject *test_neg;
  PyBlitzArrayObject *test_pos;
111
  Py_ssize_t n_points;
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
112 113 114 115 116 117 118 119 120 121
  PyObject *is_sorted = Py_False;
  PyObject *thresholds = Py_False;

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

  // protects acquired resources through this scope
122 123 124 125 126
  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);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
127 128 129 130 131 132
  auto result = bob::measure::epc(*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, PyObject_IsTrue(is_sorted),
                                  PyObject_IsTrue(thresholds));
André Anjos's avatar
André Anjos committed
133

134
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
135
  BOB_CATCH_FUNCTION("epc", 0)
136
}
André Anjos's avatar
André Anjos committed
137

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
static auto det_doc =
    bob::extension::FunctionDoc(
        "det", "Calculates points of an Detection Error-Tradeoff (DET) curve",
        "Calculates the DET curve given a set of negative and positive scores "
        "and a desired number of points. Returns a two-dimensional array of "
        "doubles that express on its rows:\n\n"
        "[0]  X axis values in the normal deviate scale for the "
        "false-accepts\n\n"
        "[1]  Y axis values in the normal deviate scale for the "
        "false-rejections\n\n"
        "You can plot the results using your preferred tool to first create a "
        "plot using rows 0 and 1 from the returned value and then replace the "
        "X/Y axis annotation using a pre-determined set of tickmarks as "
        "recommended by NIST. "
        "The derivative scales are computed with the "
        ":py:func:`bob.measure.ppndf` function.")
154
        .add_prototype("negatives, positives, n_points, [min_far]", "curve")
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
155 156 157 158 159 160
        .add_parameter(
            "negatives, positives", "array_like(1D, float)",
            "The list of negative and positive scores to compute the DET for")
        .add_parameter("n_points", "int", "The number of points on the DET "
                                          "curve, for which the DET should be "
                                          "evaluated")
161 162 163 164
        .add_parameter("min_far", "int", "Minimum FAR in terms of 10^(min_far). "
                                         "This value is also used for min_frr. "
                                         "Default value is -8. Values should be "
                                         "negative.")
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
165
        .add_return("curve", "array_like(2D, float)",
166
                    "The DET curve, with the FPR in the first and the FNR in "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
167 168 169 170 171 172 173
                    "the second row");
static PyObject *det(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  char **kwlist = det_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
174
  Py_ssize_t n_points;
175
  int min_far = -8;
André Anjos's avatar
André Anjos committed
176

177
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&n|i", kwlist,
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
178
                                   &double1d_converter, &neg,
179
                                   &double1d_converter, &pos, &n_points, &min_far))
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
180
    return 0;
André Anjos's avatar
André Anjos committed
181

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
182
  // protects acquired resources through this scope
183 184 185
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
186 187
  auto result =
      bob::measure::det(*PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
188
                        *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), n_points, min_far);
André Anjos's avatar
André Anjos committed
189

190
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
191
  BOB_CATCH_FUNCTION("det", 0)
André Anjos's avatar
André Anjos committed
192 193
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
194 195 196 197 198 199 200 201 202 203 204
static auto ppndf_doc =
    bob::extension::FunctionDoc(
        "ppndf", "Returns the Deviate Scale equivalent of a false "
                 "rejection/acceptance ratio",
        "The algorithm that calculates the deviate scale is based on function "
        "ppndf() from the NIST package DETware version 2.1, freely available "
        "on the internet. "
        "Please consult it for more details. "
        "By 20.04.2011, you could find such package `here "
        "<http://www.itl.nist.gov/iad/mig/tools/>`_.")
        .add_prototype("value", "ppndf")
205
        .add_parameter("value", "float", "The value (usually FPR or FNR) for "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
206 207 208 209 210 211
                                         "which the ppndf should be calculated")
        .add_return("ppndf", "float",
                    "The derivative scale of the given value");
static PyObject *ppndf(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  char **kwlist = ppndf_doc.kwlist();
212
  double v;
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
213 214
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "d", kwlist, &v))
    return 0;
André Anjos's avatar
André Anjos committed
215

216
  return Py_BuildValue("d", bob::measure::ppndf(v));
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
217
  BOB_CATCH_FUNCTION("ppndf", 0)
André Anjos's avatar
André Anjos committed
218 219
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
220 221 222 223 224 225
static auto roc_doc =
    bob::extension::FunctionDoc(
        "roc",
        "Calculates points of an Receiver Operating Characteristic (ROC)",
        "Calculates the ROC curve given a set of negative and positive scores "
        "and a desired number of points. ")
226
        .add_prototype("negatives, positives, n_points, [min_far]", "curve")
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
227 228 229 230 231 232 233 234
        .add_parameter("negatives, positives", "array_like(1D, float)",
                       "The negative and positive scores, for which the ROC "
                       "curve should be calculated")
        .add_parameter("n_points", "int", "The number of points, in which the "
                                          "ROC curve are calculated, which are "
                                          "distributed uniformly in the range "
                                          "``[min(negatives, positives), "
                                          "max(negatives, positives)]``")
235 236 237 238
        .add_parameter("min_far", "int", "Minimum FAR in terms of 10^(min_far). "
                                         "This value is also used for min_frr. "
                                         "Default value is -8. Values should be "
                                         "negative.")
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
239 240
        .add_return("curve", "array_like(2D, float)",
                    "A two-dimensional array of doubles that express the X "
241
                    "(FPR) and Y (FNR) coordinates in this order");
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
242 243 244 245 246 247
static PyObject *roc(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  static char **kwlist = roc_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
248
  Py_ssize_t n_points;
249
  int min_far = -8;
André Anjos's avatar
André Anjos committed
250

251 252

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&n|i", kwlist,
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
253
                                   &double1d_converter, &neg,
254
                                   &double1d_converter, &pos, &n_points, &min_far))
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
255
    return 0;
André Anjos's avatar
André Anjos committed
256

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
257
  // protects acquired resources through this scope
258 259 260
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
261 262
  auto result =
      bob::measure::roc(*PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
263
                        *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), n_points, min_far);
André Anjos's avatar
André Anjos committed
264

265
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
266
  BOB_CATCH_FUNCTION("roc", 0)
André Anjos's avatar
André Anjos committed
267 268
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
static auto farfrr_doc =
    bob::extension::FunctionDoc(
        "farfrr", "Calculates the false-acceptance (FA) ratio and the "
                  "false-rejection (FR) ratio for the given positive and "
                  "negative scores and a score threshold",
        "``positives`` holds the score information for samples that are "
        "labeled to belong to a certain class (a.k.a., 'signal' or 'client'). "
        "``negatives`` holds the score information for samples that are "
        "labeled **not** to belong to the class (a.k.a., 'noise' or "
        "'impostor'). "
        "It is expected that 'positive' scores are, at least by design, "
        "greater than 'negative' scores. "
        "So, every 'positive' value that falls bellow the threshold is "
        "considered a false-rejection (FR). "
        "`negative` samples that fall above the threshold are considered a "
        "false-accept (FA).\n\n"
        "Positives that fall on the threshold (exactly) are considered "
        "correctly classified. "
        "Negatives that fall on the threshold (exactly) are considered "
        "**incorrectly** classified. "
        "This equivalent to setting the comparison like this pseudo-code:\n\n"
        "  ``foreach (positive as K) if K < threshold: falseRejectionCount += "
        "1``\n\n"
        "  ``foreach (negative as K) if K >= threshold: falseAcceptCount += "
        "1``\n\n"
        "The output is in form of a tuple of two double-precision real "
        "numbers. "
        "The numbers range from 0 to 1. "
297 298
        "The first element of the pair is the false positive ratio (FPR), the "
        "second element the false negative ratio (FNR).\n\n"
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
        "The ``threshold`` value does not necessarily have to fall in the "
        "range covered by the input scores (negatives and positives "
        "altogether), but if it does not, the output will be either (1.0, 0.0) "
        "or (0.0, 1.0), depending on the side the threshold falls.\n\n"
        "It is possible that scores are inverted in the negative/positive "
        "sense. "
        "In some setups the designer may have setup the system so 'positive' "
        "samples have a smaller score than the 'negative' ones. "
        "In this case, make sure you normalize the scores so positive samples "
        "have greater scores before feeding them into this method.")
        .add_prototype("negatives, positives, threshold", "far, frr")
        .add_parameter(
            "negatives", "array_like(1D, float)",
            "The scores for comparisons of objects of different classes")
        .add_parameter(
            "positives", "array_like(1D, float)",
            "The scores for comparisons of objects of the same class")
        .add_parameter("threshold", "float", "The threshold to separate "
                                             "correctly and incorrectly "
                                             "classified scores")
        .add_return("far", "float",
320
                    "The False Positve Rate (FPR) for the given threshold")
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
321
        .add_return("frr", "float",
322
                    "The False Negative Rate (FNR) for the given threshold");
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
323 324 325 326 327 328
static PyObject *farfrr(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  char **kwlist = farfrr_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
329
  double threshold;
André Anjos's avatar
André Anjos committed
330

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
331 332 333 334
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&d", kwlist,
                                   &double1d_converter, &neg,
                                   &double1d_converter, &pos, &threshold))
    return 0;
André Anjos's avatar
André Anjos committed
335

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
336
  // protects acquired resources through this scope
337 338 339
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
340 341 342
  auto result =
      bob::measure::farfrr(*PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
                           *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), threshold);
André Anjos's avatar
André Anjos committed
343

344
  return Py_BuildValue("dd", result.first, result.second);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
345
  BOB_CATCH_FUNCTION("farfrr", 0)
André Anjos's avatar
André Anjos committed
346 347
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
348 349 350 351 352
static auto eer_threshold_doc =
    bob::extension::FunctionDoc(
        "eer_threshold", "Calculates the threshold that is as close as "
                         "possible to the equal-error-rate (EER) for the given "
                         "input data",
353
        "The EER should be the point where the FPR equals the FNR. "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
        "Graphically, this would be equivalent to the intersection between the "
        "ROC (or DET) curves and the identity.\n\n"
        ".. note::\n\n"
        "   The scores will be sorted internally, requiring the scores to be "
        "copied.\n"
        "   To avoid this copy, you can sort both sets of scores externally in "
        "ascendant order, and set the ``is_sorted`` parameter to ``True``")
        .add_prototype("negatives, positives, [is_sorted]", "threshold")
        .add_parameter(
            "negatives, positives", "array_like(1D, float)",
            "The set of negative and positive scores to compute the threshold")
        .add_parameter("is_sorted", "bool", "[Default: ``False``] Are both "
                                            "sets of scores already in "
                                            "ascendantly sorted order?")
        .add_return("threshold", "float", "The threshold (i.e., as used in "
                                          ":py:func:`bob.measure.farfrr`) "
370
                                          "where FPR and FNR are as close as "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
                                          "possible");
static PyObject *eer_threshold(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  char **kwlist = eer_threshold_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
  PyObject *is_sorted = Py_False;

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

  // protects acquired resources through this scope
386 387 388
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
389
  double result = bob::measure::eerThreshold(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
390 391
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), PyObject_IsTrue(is_sorted));
André Anjos's avatar
André Anjos committed
392

393
  return Py_BuildValue("d", result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
394
  BOB_CATCH_FUNCTION("eer_threshold", 0)
André Anjos's avatar
André Anjos committed
395 396
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
397 398 399 400 401 402 403 404 405
static auto min_weighted_error_rate_threshold_doc =
    bob::extension::FunctionDoc(
        "min_weighted_error_rate_threshold", "Calculates the threshold that "
                                             "minimizes the error rate for the "
                                             "given input data",
        "The ``cost`` parameter determines the relative importance between "
        "false-accepts and false-rejections. "
        "This number should be between 0 and 1 and will be clipped to those "
        "extremes. "
406 407
        "The value to minimize becomes: :math:`ER_{cost} = cost * FPR + "
        "(1-cost) * FNR`. "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
408 409 410 411 412 413 414 415 416 417 418
        "The higher the cost, the higher the importance given to **not** "
        "making mistakes classifying negatives/noise/impostors.\n\n"
        ".. note:: "
        "The scores will be sorted internally, requiring the scores to be "
        "copied. "
        "To avoid this copy, you can sort both sets of scores externally in "
        "ascendant order, and set the ``is_sorted`` parameter to ``True``")
        .add_prototype("negatives, positives, cost, [is_sorted]", "threshold")
        .add_parameter(
            "negatives, positives", "array_like(1D, float)",
            "The set of negative and positive scores to compute the threshold")
419 420
        .add_parameter("cost", "float", "The relative cost over FPR with "
                                        "respect to FNR in the threshold "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434
                                        "calculation")
        .add_parameter("is_sorted", "bool", "[Default: ``False``] Are both "
                                            "sets of scores already in "
                                            "ascendantly sorted order?")
        .add_return(
            "threshold", "float",
            "The threshold for which the weighted error rate is minimal");
static PyObject *min_weighted_error_rate_threshold(PyObject *, PyObject *args,
                                                   PyObject *kwds) {
  BOB_TRY
  char **kwlist = min_weighted_error_rate_threshold_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
435
  double cost;
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
436
  PyObject *is_sorted = Py_False;
André Anjos's avatar
André Anjos committed
437

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
438 439 440 441
  if (!PyArg_ParseTupleAndKeywords(
          args, kwds, "O&O&d|O", kwlist, &double1d_converter, &neg,
          &double1d_converter, &pos, &cost, &is_sorted))
    return 0;
André Anjos's avatar
André Anjos committed
442

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
443
  // protects acquired resources through this scope
444 445 446
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
447
  double result = bob::measure::minWeightedErrorRateThreshold(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
448 449
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), cost,
450
      PyObject_IsTrue(is_sorted));
André Anjos's avatar
André Anjos committed
451

452
  return Py_BuildValue("d", result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
453
  BOB_CATCH_FUNCTION("min_weighted_error_rate_threshold", 0)
André Anjos's avatar
André Anjos committed
454 455
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
static auto min_hter_threshold_doc =
    bob::extension::FunctionDoc("min_hter_threshold",
                                "Calculates the "
                                ":py:func:`bob.measure.min_weighted_error_rate_"
                                "threshold` with ``cost=0.5``")
        .add_prototype("negatives, positives, [is_sorted]", "threshold")
        .add_parameter(
            "negatives, positives", "array_like(1D, float)",
            "The set of negative and positive scores to compute the threshold")
        .add_parameter("is_sorted", "bool", "[Default: ``False``] Are both "
                                            "sets of scores already in "
                                            "ascendantly sorted order?")
        .add_return(
            "threshold", "float",
            "The threshold for which the weighted error rate is minimal");
static PyObject *min_hter_threshold(PyObject *, PyObject *args,
                                    PyObject *kwds) {
  BOB_TRY
  char **kwlist = min_hter_threshold_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
  PyObject *is_sorted = Py_False;

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

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

André Anjos's avatar
André Anjos committed
489
  double result = bob::measure::minHterThreshold(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
490 491
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), PyObject_IsTrue(is_sorted));
André Anjos's avatar
André Anjos committed
492

493
  return Py_BuildValue("d", result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
494
  BOB_CATCH_FUNCTION("min_hter_threshold", 0)
André Anjos's avatar
André Anjos committed
495 496
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
static auto precision_recall_doc =
    bob::extension::FunctionDoc(
        "precision_recall", "Calculates the precision and recall "
                            "(sensitiveness) values given negative and "
                            "positive scores and a threshold",
        "Precision and recall are computed as:\n\n"
        ".. math::\n\n"
        "   \\mathrm{precision} = \\frac{tp}{tp + fp}\n\n"
        "   \\mathrm{recall} = \\frac{tp}{tp + fn}\n\n"
        "where :math:`tp` are the true positives, :math:`fp` are the false "
        "positives and :math:`fn` are the false negatives.\n\n"
        "``positives`` holds the score information for samples that are "
        "labeled to belong to a certain class (a.k.a., 'signal' or 'client'). "
        "``negatives`` holds the score information for samples that are "
        "labeled **not** to belong to the class (a.k.a., 'noise' or "
        "'impostor'). "
        "For more precise details about how the method considers error rates, "
        "see :py:func:`bob.measure.farfrr`.")
        .add_prototype("negatives, positives, threshold", "precision, recall")
        .add_parameter("negatives, positives", "array_like(1D, float)",
                       "The set of negative and positive scores to compute the "
                       "measurements")
        .add_parameter("threshold", "float",
                       "The threshold to compute the measures for")
        .add_return("precision", "float",
                    "The precision value for the given negatives and positives")
        .add_return("recall", "float",
                    "The recall value for the given negatives and positives");
static PyObject *precision_recall(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  static char **kwlist = precision_recall_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
531
  double threshold;
André Anjos's avatar
André Anjos committed
532

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
533 534 535 536
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&d", kwlist,
                                   &double1d_converter, &neg,
                                   &double1d_converter, &pos, &threshold))
    return 0;
André Anjos's avatar
André Anjos committed
537

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
538
  // protects acquired resources through this scope
539 540 541
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
542
  auto result = bob::measure::precision_recall(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
543 544
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), threshold);
André Anjos's avatar
André Anjos committed
545

546
  return Py_BuildValue("dd", result.first, result.second);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
547
  BOB_CATCH_FUNCTION("precision_recall", 0)
André Anjos's avatar
André Anjos committed
548 549
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
static auto f_score_doc =
    bob::extension::FunctionDoc(
        "f_score", "This method computes the F-score of the accuracy of the "
                   "classification",
        "The F-score is a weighted mean of precision and recall measurements, "
        "see :py:func:`bob.measure.precision_recall`. "
        "It is computed as:\n\n"
        ".. math::\n\n"
        "    \\mathrm{f-score} = (1 + "
        "w^2)\\frac{\\mathrm{precision}\\cdot{}\\mathrm{recall}}{w^2\\cdot{}"
        "\\mathrm{precision} + \\mathrm{recall}}\n\n"
        "The weight :math:`w` needs to be non-negative real value. "
        "In case the weight parameter is 1 (the default), the F-score is "
        "called F1 score and is a harmonic mean between precision and recall "
        "values.")
        .add_prototype("negatives, positives, threshold, [weight]", "f_score")
        .add_parameter("negatives, positives", "array_like(1D, float)",
                       "The set of negative and positive scores to compute the "
                       "precision and recall")
        .add_parameter("threshold", "float",
                       "The threshold to compute the precision and recall for")
        .add_parameter("weight", "float", "[Default: ``1``] The weight "
                                          ":math:`w` between precision and "
                                          "recall")
        .add_return("f_score", "float", "The computed f-score for the given "
                                        "scores and the given threshold");
static PyObject *f_score(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  static char **kwlist = f_score_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
582
  double threshold;
André Anjos's avatar
André Anjos committed
583 584
  double weight = 1.0;

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
585 586 587 588
  if (!PyArg_ParseTupleAndKeywords(
          args, kwds, "O&O&d|d", kwlist, &double1d_converter, &neg,
          &double1d_converter, &pos, &threshold, &weight))
    return 0;
André Anjos's avatar
André Anjos committed
589

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
590
  // protects acquired resources through this scope
591 592 593
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
594 595 596
  auto result = bob::measure::f_score(*PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
                                      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos),
                                      threshold, weight);
André Anjos's avatar
André Anjos committed
597

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
598 599
  return Py_BuildValue("d", result);
  BOB_CATCH_FUNCTION("f_score", 0)
André Anjos's avatar
André Anjos committed
600 601
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
static auto correctly_classified_negatives_doc =
    bob::extension::FunctionDoc(
        "correctly_classified_negatives",
        "This method returns an array composed of booleans that pin-point, "
        "which negatives where correctly classified for the given threshold",
        "The pseudo-code for this function is:\n\n"
        "  ``foreach (k in negatives) if negatives[k] < threshold: "
        "classified[k] = true else: classified[k] = false``")
        .add_prototype("negatives, threshold", "classified")
        .add_parameter(
            "negatives", "array_like(1D, float)",
            "The scores generated by comparing objects of different classes")
        .add_parameter("threshold", "float", "The threshold, for which scores "
                                             "should be considered to be "
                                             "correctly classified")
        .add_return("classified", "array_like(1D, bool)",
                    "The decision for each of the ``negatives``");
static PyObject *correctly_classified_negatives(PyObject *, PyObject *args,
                                                PyObject *kwds) {
  BOB_TRY
  static char **kwlist = correctly_classified_negatives_doc.kwlist();

  PyBlitzArrayObject *neg;
625
  double threshold;
André Anjos's avatar
André Anjos committed
626

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
627 628 629
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&d", kwlist,
                                   &double1d_converter, &neg, &threshold))
    return 0;
André Anjos's avatar
André Anjos committed
630

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
631
  // protects acquired resources through this scope
632 633
  auto neg_ = make_safe(neg);

André Anjos's avatar
André Anjos committed
634
  auto result = bob::measure::correctlyClassifiedNegatives(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
635
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg), threshold);
André Anjos's avatar
André Anjos committed
636

637
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
638
  BOB_CATCH_FUNCTION("correctly_classified_negatives", 0)
André Anjos's avatar
André Anjos committed
639 640
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
static auto correctly_classified_positives_doc =
    bob::extension::FunctionDoc(
        "correctly_classified_positives",
        "This method returns an array composed of booleans that pin-point, "
        "which positives where correctly classified for the given threshold",
        "The pseudo-code for this function is:\n\n"
        "  ``foreach (k in positives) if positives[k] >= threshold: "
        "classified[k] = true else: classified[k] = false``")
        .add_prototype("positives, threshold", "classified")
        .add_parameter(
            "positives", "array_like(1D, float)",
            "The scores generated by comparing objects of the same classes")
        .add_parameter("threshold", "float", "The threshold, for which scores "
                                             "should be considered to be "
                                             "correctly classified")
        .add_return("classified", "array_like(1D, bool)",
                    "The decision for each of the ``positives``");
static PyObject *correctly_classified_positives(PyObject *, PyObject *args,
                                                PyObject *kwds) {
  BOB_TRY
  static char **kwlist = correctly_classified_positives_doc.kwlist();

  PyBlitzArrayObject *pos;
664
  double threshold;
André Anjos's avatar
André Anjos committed
665

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
666 667 668
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&d", kwlist,
                                   &double1d_converter, &pos, &threshold))
    return 0;
André Anjos's avatar
André Anjos committed
669

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
670
  // protects acquired resources through this scope
671 672
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
673
  auto result = bob::measure::correctlyClassifiedPositives(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
674
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), threshold);
André Anjos's avatar
André Anjos committed
675

676
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
677
  BOB_CATCH_FUNCTION("correctly_classified_positives", 0)
André Anjos's avatar
André Anjos committed
678 679
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
static auto precision_recall_curve_doc =
    bob::extension::FunctionDoc(
        "precision_recall_curve", "Calculates the precision-recall curve given "
                                  "a set of positive and negative scores and a "
                                  "number of desired points",
        "The points in which the curve is calculated are distributed uniformly "
        "in the range ``[min(negatives, positives), max(negatives, "
        "positives)]``")
        .add_prototype("negatives, positives, n_points", "curve")
        .add_parameter("negatives, positives", "array_like(1D, float)",
                       "The set of negative and positive scores to compute the "
                       "measurements")
        .add_parameter("n_points", "int", "The number of thresholds for which "
                                          "precision and recall should be "
                                          "evaluated")
        .add_return("curve", "array_like(2D, float)",
                    "2D array of floats that express the X (precision) and Y "
                    "(recall) coordinates");
static PyObject *precision_recall_curve(PyObject *, PyObject *args,
                                        PyObject *kwds) {
  BOB_TRY
  char **kwlist = precision_recall_curve_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
705
  Py_ssize_t n_points;
André Anjos's avatar
André Anjos committed
706

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
707 708 709 710
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&n", kwlist,
                                   &double1d_converter, &neg,
                                   &double1d_converter, &pos, &n_points))
    return 0;
André Anjos's avatar
André Anjos committed
711

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
712
  // protects acquired resources through this scope
713 714 715
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

André Anjos's avatar
André Anjos committed
716
  auto result = bob::measure::precision_recall_curve(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
717 718
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), n_points);
André Anjos's avatar
André Anjos committed
719

720
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
721
  BOB_CATCH_FUNCTION("precision_recall_curve", 0)
André Anjos's avatar
André Anjos committed
722 723
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
724 725
static auto far_threshold_doc =
    bob::extension::FunctionDoc(
726
        "far_threshold", "Computes the threshold such that the real FPR is "
727
                         "**at most** the requested ``far_value`` if possible",
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
728
        "\n\n.. note::\n\n"
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
729 730 731 732 733 734 735 736 737
        "   The scores will be sorted internally, requiring the scores to be "
        "copied.\n"
        "   To avoid this copy, you can sort the ``negatives`` scores "
        "externally in ascendant order, and set the ``is_sorted`` parameter to "
        "``True``")
        .add_prototype("negatives, positives, [far_value], [is_sorted]",
                       "threshold")
        .add_parameter(
            "negatives", "array_like(1D, float)",
738
            "The set of negative scores to compute the FPR threshold")
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
739 740 741
        .add_parameter(
            "positives", "array_like(1D, float)",
            "Ignored, but needs to be specified -- may be given as ``[]``")
742
        .add_parameter("far_value", "float", "[Default: ``0.001``] The FPR "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
743 744 745 746 747 748 749 750 751
                                             "value, for which the threshold "
                                             "should be computed")
        .add_parameter("is_sorted", "bool",
                       "[Default: ``False``] Set this to ``True`` if the "
                       "``negatives`` are already sorted in ascending order. "
                       "If ``False``, scores will be sorted internally, which "
                       "will require more memory")
        .add_return(
            "threshold", "float",
752
            "The threshold such that the real FPR is at most ``far_value``");
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
753 754 755 756 757 758
static PyObject *far_threshold(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  static char **kwlist = far_threshold_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
André Anjos's avatar
André Anjos committed
759
  double far_value = 0.001;
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
760
  PyObject *is_sorted = Py_False;
André Anjos's avatar
André Anjos committed
761

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
762 763 764 765
  if (!PyArg_ParseTupleAndKeywords(
          args, kwds, "O&O&|dO", kwlist, &double1d_converter, &neg,
          &double1d_converter, &pos, &far_value, is_sorted))
    return 0;
André Anjos's avatar
André Anjos committed
766

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
767
  // protects acquired resources through this scope
768 769 770
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
771 772 773 774
  auto result =
      bob::measure::farThreshold(*PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
                                 *PyBlitzArrayCxx_AsBlitz<double, 1>(pos),
                                 far_value, PyObject_IsTrue(is_sorted));
André Anjos's avatar
André Anjos committed
775

776
  return Py_BuildValue("d", result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
777
  BOB_CATCH_FUNCTION("far_threshold", 0)
André Anjos's avatar
André Anjos committed
778 779
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
780 781
static auto frr_threshold_doc =
    bob::extension::FunctionDoc(
782
        "frr_threshold", "Computes the threshold such that the real FNR is "
783
                         "**at most** the requested ``frr_value`` if possible",
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
784
        "\n\n.. note::\n\n"
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
785 786 787 788 789 790 791 792 793 794 795 796
        "   The scores will be sorted internally, requiring the scores to be "
        "copied.\n"
        "   To avoid this copy, you can sort the ``positives`` scores "
        "externally in ascendant order, and set the ``is_sorted`` parameter to "
        "``True``")
        .add_prototype("negatives, positives, [frr_value], [is_sorted]",
                       "threshold")
        .add_parameter(
            "negatives", "array_like(1D, float)",
            "Ignored, but needs to be specified -- may be given as ``[]``")
        .add_parameter(
            "positives", "array_like(1D, float)",
797 798
            "The set of positive scores to compute the FNR threshold")
        .add_parameter("frr_value", "float", "[Default: ``0.001``] The FNR "
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
799 800 801 802 803 804 805 806 807
                                             "value, for which the threshold "
                                             "should be computed")
        .add_parameter("is_sorted", "bool",
                       "[Default: ``False``] Set this to ``True`` if the "
                       "``positives`` are already sorted in ascendant order. "
                       "If ``False``, scores will be sorted internally, which "
                       "will require more memory")
        .add_return(
            "threshold", "float",
808
            "The threshold such that the real FRR is at most ``frr_value``");
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
809 810 811 812 813 814
static PyObject *frr_threshold(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  char **kwlist = frr_threshold_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
André Anjos's avatar
André Anjos committed
815
  double frr_value = 0.001;
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
816
  PyObject *is_sorted = Py_False;
André Anjos's avatar
André Anjos committed
817

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
818 819 820 821
  if (!PyArg_ParseTupleAndKeywords(
          args, kwds, "O&O&|dO", kwlist, &double1d_converter, &neg,
          &double1d_converter, &pos, &frr_value, &is_sorted))
    return 0;
André Anjos's avatar
André Anjos committed
822

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
823
  // protects acquired resources through this scope
824 825 826
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
827 828 829 830
  auto result =
      bob::measure::frrThreshold(*PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
                                 *PyBlitzArrayCxx_AsBlitz<double, 1>(pos),
                                 frr_value, PyObject_IsTrue(is_sorted));
André Anjos's avatar
André Anjos committed
831

832
  return Py_BuildValue("d", result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
833
  BOB_CATCH_FUNCTION("frr_threshold", 0)
André Anjos's avatar
André Anjos committed
834 835
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849
static auto eer_rocch_doc =
    bob::extension::FunctionDoc(
        "eer_rocch", "Calculates the equal-error-rate (EER) given the input "
                     "data, on the ROC Convex Hull (ROCCH)",
        "It replicates the EER calculation from the Bosaris toolkit "
        "(https://sites.google.com/site/bosaristoolkit/).")
        .add_prototype("negatives, positives", "threshold")
        .add_parameter(
            "negatives, positives", "array_like(1D, float)",
            "The set of negative and positive scores to compute the threshold")
        .add_return("threshold", "float",
                    "The threshold for the equal error rate");
static PyObject *eer_rocch(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
André Anjos's avatar
André Anjos committed
850
  /* Parses input arguments in a single shot */
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
851
  char **kwlist = eer_rocch_doc.kwlist();
André Anjos's avatar
André Anjos committed
852

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
853 854
  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
André Anjos's avatar
André Anjos committed
855

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
856 857 858 859
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&", kwlist,
                                   &double1d_converter, &neg,
                                   &double1d_converter, &pos))
    return 0;
André Anjos's avatar
André Anjos committed
860

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
861
  // protects acquired resources through this scope
862 863 864
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

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

869
  return Py_BuildValue("d", result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
870
  BOB_CATCH_FUNCTION("eer_rocch", 0)
André Anjos's avatar
André Anjos committed
871 872
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
873 874 875 876 877 878 879 880 881
static auto rocch_doc =
    bob::extension::FunctionDoc("rocch", "Calculates the ROC Convex Hull "
                                         "(ROCCH) curve given a set of "
                                         "positive and negative scores")
        .add_prototype("negatives, positives", "curve")
        .add_parameter(
            "negatives, positives", "array_like(1D, float)",
            "The set of negative and positive scores to compute the curve")
        .add_return("curve", "array_like(2D, float)",
882 883
                    "The ROC curve, with the first row containing the FPR, and "
                    "the second row containing the FNR");
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
884 885
static PyObject *rocch(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
André Anjos's avatar
André Anjos committed
886
  /* Parses input arguments in a single shot */
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
887
  char **kwlist = rocch_doc.kwlist();
André Anjos's avatar
André Anjos committed
888

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
889 890
  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
André Anjos's avatar
André Anjos committed
891

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
892 893 894 895
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&", kwlist,
                                   &double1d_converter, &neg,
                                   &double1d_converter, &pos))
    return 0;
André Anjos's avatar
André Anjos committed
896

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
897
  // protects acquired resources through this scope
898 899 900
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
901 902
  auto result = bob::measure::rocch(*PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
                                    *PyBlitzArrayCxx_AsBlitz<double, 1>(pos));
André Anjos's avatar
André Anjos committed
903

904
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
905
  BOB_CATCH_FUNCTION("rocch", 0)
André Anjos's avatar
André Anjos committed
906 907
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
static auto rocch2eer_doc =
    bob::extension::FunctionDoc(
        "rocch2eer", "Calculates the threshold that is as close as possible to "
                     "the equal-error-rate (EER) given the input data")
        .add_prototype("pmiss_pfa", "threshold")
        // I don't know, what the pmiss_pfa parameter is, so I leave out its
        // documentation (a .. todo:: will be generated automatically)
        //.add_parameter("pmiss_pfa", "array_like(2D, float)", "???")
        .add_return("threshold", "float",
                    "The computed threshold, at which the EER can be obtained");
static PyObject *rocch2eer(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  static char **kwlist = rocch2eer_doc.kwlist();

  PyBlitzArrayObject *p;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kwlist,
                                   &double2d_converter, &p))
    return 0;
André Anjos's avatar
André Anjos committed
927

928
  auto p_ = make_safe(p);
André Anjos's avatar
André Anjos committed
929

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
930
  auto result = bob::measure::rocch2eer(*PyBlitzArrayCxx_AsBlitz<double, 2>(p));
André Anjos's avatar
André Anjos committed
931

932
  return Py_BuildValue("d", result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
933
  BOB_CATCH_FUNCTION("rocch2eer", 0)
André Anjos's avatar
André Anjos committed
934 935
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
936 937 938
static auto roc_for_far_doc =
    bob::extension::FunctionDoc(
        "roc_for_far", "Calculates the ROC curve for a given set of positive "
939 940
                       "and negative scores and the FPR values, for which the "
                       "FNR should be computed",
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
941 942 943 944 945 946 947 948 949 950 951
        ".. note::\n\n"
        "   The scores will be sorted internally, requiring the scores to be "
        "copied.\n"
        "   To avoid this copy, you can sort both sets of scores externally in "
        "ascendant order, and set the ``is_sorted`` parameter to ``True``")
        .add_prototype("negatives, positives, far_list, [is_sorted]", "curve")
        .add_parameter(
            "negatives, positives", "array_like(1D, float)",
            "The set of negative and positive scores to compute the curve")
        .add_parameter(
            "far_list", "array_like(1D, float)",
952
            "A list of FPR values, for which the FNR values should be computed")
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
953 954 955 956 957 958
        .add_parameter("is_sorted", "bool",
                       "[Default: ``False``] Set this to ``True`` if both sets "
                       "of scores are already sorted in ascending order. If "
                       "``False``, scores will be sorted internally, which "
                       "will require more memory")
        .add_return("curve", "array_like(2D, float)",
959 960
                    "The ROC curve, which holds a copy of the given FPR values "
                    "in row 0, and the corresponding FNR values in row 1");
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
961 962
static PyObject *roc_for_far(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
963
  /* Parses input arguments in a single shot */
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
964 965 966 967 968 969 970 971 972 973 974 975 976
  char **kwlist = roc_for_far_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
  PyBlitzArrayObject *far;
  PyObject *is_sorted = Py_False;

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

  // protects acquired resources through this scope
977 978
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);
979
  auto far_ = make_safe(far);
980

981
  auto result = bob::measure::roc_for_far(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
982 983 984
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(far), PyObject_IsTrue(is_sorted));
985

986
  return PyBlitzArrayCxx_AsNumpy(result);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
987
  BOB_CATCH_FUNCTION("roc_for_far", 0)
André Anjos's avatar
André Anjos committed
988 989
}

André Anjos's avatar
André Anjos committed
990
static PyMethodDef module_methods[] = {
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
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
    {epc_doc.name(), (PyCFunction)epc, METH_VARARGS | METH_KEYWORDS,
     epc_doc.doc()},
    {det_doc.name(), (PyCFunction)det, METH_VARARGS | METH_KEYWORDS,
     det_doc.doc()},
    {ppndf_doc.name(), (PyCFunction)ppndf, METH_VARARGS | METH_KEYWORDS,
     ppndf_doc.doc()},
    {roc_doc.name(), (PyCFunction)roc, METH_VARARGS | METH_KEYWORDS,
     roc_doc.doc()},
    {farfrr_doc.name(), (PyCFunction)farfrr, METH_VARARGS | METH_KEYWORDS,
     farfrr_doc.doc()},
    {eer_threshold_doc.name(), (PyCFunction)eer_threshold,
     METH_VARARGS | METH_KEYWORDS, eer_threshold_doc.doc()},
    {min_weighted_error_rate_threshold_doc.name(),
     (PyCFunction)min_weighted_error_rate_threshold,
     METH_VARARGS | METH_KEYWORDS, min_weighted_error_rate_threshold_doc.doc()},
    {min_hter_threshold_doc.name(), (PyCFunction)min_hter_threshold,
     METH_VARARGS | METH_KEYWORDS, min_hter_threshold_doc.doc()},
    {precision_recall_doc.name(), (PyCFunction)precision_recall,
     METH_VARARGS | METH_KEYWORDS, precision_recall_doc.doc()},
    {f_score_doc.name(), (PyCFunction)f_score, METH_VARARGS | METH_KEYWORDS,
     f_score_doc.doc()},
    {correctly_classified_negatives_doc.name(),
     (PyCFunction)correctly_classified_negatives, METH_VARARGS | METH_KEYWORDS,
     correctly_classified_negatives_doc.doc()},
    {correctly_classified_positives_doc.name(),
     (PyCFunction)correctly_classified_positives, METH_VARARGS | METH_KEYWORDS,
     correctly_classified_positives_doc.doc()},
    {precision_recall_curve_doc.name(), (PyCFunction)precision_recall_curve,
     METH_VARARGS | METH_KEYWORDS, precision_recall_curve_doc.doc()},
    {far_threshold_doc.name(), (PyCFunction)far_threshold,
     METH_VARARGS | METH_KEYWORDS, far_threshold_doc.doc()},
    {frr_threshold_doc.name(), (PyCFunction)frr_threshold,
     METH_VARARGS | METH_KEYWORDS, frr_threshold_doc.doc()},
    {eer_rocch_doc.name(), (PyCFunction)eer_rocch, METH_VARARGS | METH_KEYWORDS,
     eer_rocch_doc.doc()},
    {rocch_doc.name(), (PyCFunction)rocch, METH_VARARGS | METH_KEYWORDS,
     rocch_doc.doc()},
    {rocch2eer_doc.name(), (PyCFunction)rocch2eer, METH_VARARGS | METH_KEYWORDS,
     rocch2eer_doc.doc()},
    {roc_for_far_doc.name(), (PyCFunction)roc_for_far,
     METH_VARARGS | METH_KEYWORDS, roc_for_far_doc.doc()},
    {0} /* Sentinel */
1033
};
André Anjos's avatar
André Anjos committed
1034

André Anjos's avatar
André Anjos committed
1035 1036 1037
PyDoc_STRVAR(module_docstr, "Bob metrics and performance figures");

#if PY_VERSION_HEX >= 0x03000000
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
1038 1039 1040 1041 1042 1043 1044 1045 1046
static PyModuleDef module_definition = {PyModuleDef_HEAD_INIT,
                                        BOB_EXT_MODULE_NAME,
                                        module_docstr,
                                        -1,
                                        module_methods,
                                        0,
                                        0,
                                        0,
                                        0};
André Anjos's avatar
André Anjos committed
1047 1048
#endif

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
1049
static PyObject *create_module(void) {
André Anjos's avatar
André Anjos committed
1050

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
1051 1052
#if PY_VERSION_HEX >= 0x03000000
  PyObject *m = PyModule_Create(&module_definition);
1053
  auto m_ = make_xsafe(m);
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
1054 1055 1056 1057 1058 1059 1060 1061
  const char *ret = "O";
#else
  PyObject *m =
      Py_InitModule3(BOB_EXT_MODULE_NAME, module_methods, module_docstr);
  const char *ret = "N";
#endif
  if (!m)
    return 0;
André Anjos's avatar
André Anjos committed
1062

André Anjos's avatar
André Anjos committed
1063
  /* imports bob.blitz C-API + dependencies */
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
1064 1065 1066 1067 1068 1069
  if (import_bob_blitz() < 0)
    return 0;
  if (import_bob_core_logging() < 0)
    return 0;
  if (import_bob_io_base() < 0)
    return 0;
André Anjos's avatar
André Anjos committed
1070

1071
  return Py_BuildValue(ret, m);
André Anjos's avatar
André Anjos committed
1072 1073
}

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
1074 1075
PyMODINIT_FUNC BOB_EXT_ENTRY_NAME(void) {
#if PY_VERSION_HEX >= 0x03000000
André Anjos's avatar
André Anjos committed
1076
  return
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
1077 1078
#endif
      create_module();
André Anjos's avatar
André Anjos committed
1079
}