error_utils.py 23.3 KB
Newer Older
1
#!/usr/bin/env python
Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
2 3
# Ivana Chingovska <ivana.chingovska@idiap.ch>
# Fri Dec  7 12:33:37 CET 2012
4 5 6 7
"""Utility functions for computation of EPSC curve and related measurement"""

import bob.measure
import numpy
8
from bob.measure import far_threshold, eer_threshold, min_hter_threshold, farfrr, frr_threshold
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
9 10 11
from bob.bio.base.score.load import four_column
from collections import defaultdict
import re
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
12 13


Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
14
def calc_threshold(method, pos, negs, all_negs, far_value=None, is_sorted=False):
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
15 16 17 18 19
    """Calculates the threshold based on the given method.

    Parameters
    ----------
    method : str
Anjith GEORGE's avatar
Anjith GEORGE committed
20
        One of ``bpcer20``, ``eer``, ``min-hter``, ``apcer20``.
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
21 22
    pos : array_like
        The positive scores. They should be sorted!
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
23 24 25 26 27 28 29 30 31 32
    negs : list
        A list of array_like negative scores. Each item in the list corresponds to
        scores of one PAI.
    all_negs : array_like
        An array of all negative scores. This can be calculated from negs as well but we
        ask for it since you might have it already calculated.
    far_value : None, optional
        If method is far, far_value and all_negs are used to calculate the threshold.
    is_sorted : bool, optional
        If True, it means all scores are sorted and no sorting will happen.
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
33 34 35 36 37 38 39 40 41 42 43 44

    Returns
    -------
    float
        The calculated threshold.

    Raises
    ------
    ValueError
        If method is unknown.
    """
    method = method.lower()
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
45 46 47
    if "bpcer" in method:
        desired_apcer = 1 / float(method.replace("bpcer", ""))
        threshold = apcer_threshold(desired_apcer, pos, *negs, is_sorted=is_sorted)
Anjith GEORGE's avatar
Anjith GEORGE committed
48 49 50
    elif "apcer" in method:
        desired_bpcer = 1 / float(method.replace("apcer", ""))
        threshold = frr_threshold(all_negs, pos, desired_bpcer, True)
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
51 52 53 54 55 56
    elif method == "far":
        threshold = far_threshold(all_negs, pos, far_value, is_sorted=is_sorted)
    elif method == "eer":
        threshold = eer_threshold(all_negs, pos, is_sorted=is_sorted)
    elif method == "min-hter":
        threshold = min_hter_threshold(all_negs, pos, is_sorted=is_sorted)
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
57 58 59 60
    else:
        raise ValueError("Unknown threshold criteria: {}".format(method))

    return threshold
61 62 63 64 65


def calc_pass_rate(threshold, attacks):
    """Calculates the rate of successful spoofing attacks

66 67 68 69 70 71 72 73 74 75 76 77 78
    Parameters
    ----------
    threshold :
      the threshold used for classification
    scores :
      numpy with the scores of the spoofing attacks

    Returns
    -------
    float
      rate of successful spoofing attacks
    """
    return (attacks >= threshold).mean()
79 80


Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
81
def weighted_neg_error_rate_criteria(data, weight, thres, beta=0.5, criteria="eer"):
82 83 84
    """Given the single value for the weight parameter balancing between
    impostors and spoofing attacks and a threshold, calculates the error rates
    and their relationship depending on the criteria (difference in case of
85
    'eer', hter in case of 'min-hter' criteria)
86 87
    Keyword parameters:

88 89 90 91 92
      - data - the development data used to determine the threshold. List on 4
      numpy.arrays containing: negatives (licit), positives (licit),
      negatives (spoof), positivies (spoof)
      - weight - the weight parameter balancing between impostors and spoofing
      attacks
93
      - thres - the given threshold
94 95 96
      - beta - the weight parameter balancing between real accesses and all the
      negative samples (impostors and spoofing attacks). Note that this
      parameter will be overriden and not considered if the selected criteria
97 98
      is 'min-hter'.
      - criteria - 'eer', 'wer' or 'min-hter' criteria for decision threshold
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  """

    licit_neg = data[0]
    licit_pos = data[1]
    spoof_neg = data[2]
    spoof_pos = data[3]  # unpacking the data
    farfrr_licit = bob.measure.farfrr(licit_neg, licit_pos, thres)
    farfrr_spoof = bob.measure.farfrr(spoof_neg, spoof_pos, thres)

    frr = farfrr_licit[1]  # farfrr_spoof[1] should have the same value
    far_i = farfrr_licit[0]
    far_s = farfrr_spoof[0]

    far_w = (1 - weight) * far_i + weight * far_s

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
114
    if criteria == "eer":
115 116 117
        if beta == 0.5:
            return abs(far_w - frr)
        else:
Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
118
            # return abs(far_w - frr)
119 120
            return abs((1 - beta) * frr - beta * far_w)

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
121
    elif criteria == "min-hter":
122 123 124 125 126 127
        return (far_w + frr) / 2

    else:
        return (1 - beta) * frr + beta * far_w


Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
128
def recursive_thr_search(data, span_min, span_max, weight, beta=0.5, criteria="eer"):
129 130 131 132 133
    """Recursive search for the optimal threshold given a criteria. It
    evaluates the full range of thresholds at 100 points, and computes the one
    which optimizes the threshold. In the next search iteration, it examines
    the region around the point that optimizes the threshold. The procedure
    stops when the search range is smaller then 1e-10.
134 135

  Keyword arguments:
136 137 138
    - data - the development data used to determine the threshold. List on 4
    numpy.arrays containing: negatives (licit), positives (licit), negatives
    (spoof), positivies (spoof)
139 140
    - span_min - the minimum of the search range
    - span_max - the maximum of the search range
141 142 143 144 145
    - weight - the weight parameter balancing between impostors and spoofing
    attacks
    - beta - the weight parameter balancing between real accesses and all the
    negative samples (impostors and spoofing attacks). Note that methods called
    within this function will override this parameter and not considered if the
146
    selected criteria is 'min-hter'.
147
    - criteria - the decision threshold criteria ('eer' for EER, 'wer' for
148
    Minimum WER or 'min-hter' for Minimum HTER criteria).
149 150 151 152 153 154 155 156
  """

    quit_thr = 1e-10
    steps = 100
    if abs((span_max - span_min) / span_max) < quit_thr:
        return span_max  # or span_min, it doesn't matter
    else:
        step_size = (span_max - span_min) / steps
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        thresholds = numpy.array([(i * step_size) + span_min for i in range(steps + 1)])
        weighted_error_rates = numpy.array(
            [
                weighted_neg_error_rate_criteria(data, weight, thr, beta, criteria)
                for thr in thresholds
            ]
        )
        selected_thres = thresholds[
            numpy.where(weighted_error_rates == min(weighted_error_rates))
        ]  # all the thresholds which have minimum weighted error rate
        thr = selected_thres[
            int(selected_thres.size / 2)
        ]  # choose the centrally positioned threshold
        return recursive_thr_search(
            data, thr - step_size, thr + step_size, weight, beta, criteria
        )


def weighted_negatives_threshold(
    licit_neg, licit_pos, spoof_neg, spoof_pos, weight, beta=0.5, criteria="eer"
):
178
    """Calculates the threshold for achieving the given criteria between the
Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
179
    FAR_w and the FRR, given the single value for the weight parameter
180 181 182
    balancing between impostors and spoofing attacks and a single value for the
    parameter beta balancing between the real accesses and the negatives
    (impostors and spoofing attacks)
183 184 185 186 187 188

  Keyword parameters:
    - licit_neg - numpy.array of scores for the negatives (licit scenario)
    - licit_pos - numpy.array of scores for the positives (licit scenario)
    - spoof_neg - numpy.array of scores for the negatives (spoof scenario)
    - spoof_pos - numpy.array of scores for the positives (spoof scenario)
189 190 191 192 193
    - weight - the weight parameter balancing between impostors and spoofing
    attacks
    - beta - the weight parameter balancing between real accesses and all the
    negative samples (impostors and spoofing attacks). Note that methods called
    within this function will override this parameter and not considered if the
194
    selected criteria is 'min-hter'.
195
    - criteria - the decision threshold criteria ('eer' for EER, 'wer' for
196
    Minimum WER or 'min-hter' for Minimum HTER criteria).
197 198 199 200 201 202 203
  """
    span_min = min(
        numpy.append(licit_neg, spoof_neg)
    )  # the min of the span where we will search for the threshold
    span_max = max(
        numpy.append(licit_pos, spoof_pos)
    )  # the max of the span where we will search for the threshold
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
204 205 206 207 208 209 210
    data = (
        licit_neg,
        licit_pos,
        spoof_neg,
        spoof_pos,
    )  # pack the data into a single list
    return recursive_thr_search(data, span_min, span_max, weight, beta, criteria)
211 212 213 214 215 216 217 218 219 220 221 222 223 224


def epsc_weights(licit_neg, licit_pos, spoof_neg, spoof_pos, points=100):
    """Returns the weights for EPSC

  Keyword arguments:

    - points - number of points to calculate EPSC
  """
    step_size = 1 / float(points)
    weights = numpy.array([(i * step_size) for i in range(points + 1)])
    return weights


Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
225 226 227 228 229 230 231 232 233 234
def epsc_thresholds(
    licit_neg,
    licit_pos,
    spoof_neg,
    spoof_pos,
    points=100,
    criteria="eer",
    omega=None,
    beta=None,
):
235 236 237 238
    """Calculates the optimal thresholds for EPSC, for a range of the weight
    parameter balancing between impostors and spoofing attacks, and for a range
    of the beta parameter balancing between real accesses and all the negatives
    (impostors and spoofing attacks)
239 240 241 242 243 244 245 246

  Keyword arguments:

    - licit_neg - numpy.array of scores for the negatives (licit scenario)
    - licit_pos - numpy.array of scores for the positives (licit scenario)
    - spoof_neg - numpy.array of scores for the negatives (spoof scenario)
    - spoof_pos - numpy.array of scores for the positives (spoof scenario)
    - points - number of points to calculate EPSC
247
    - criteria - the decision threshold criteria ('eer', 'wer' or 'min-hter')
248 249 250 251
    - omega - the value of the parameter omega, balancing between impostors and
    spoofing attacks. If None, it is going to span the full range [0,1].
    Otherwise, can be set to a fixed value or a list of values.
    - beta - the value of the parameter beta, balancing between real accesses
Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
252
    and all the negatives (zero-effort impostors and spoofing attacks). If
253 254
    None, it is going to span the full range [0,1]. Otherwise, can be set to a
    fixed value or a list of values.
255 256 257 258

  """
    step_size = 1 / float(points)

Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
259
    if omega is None:
260
        omega = numpy.array([(i * step_size) for i in range(points + 1)])
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
261 262 263 264 265
    elif (
        not isinstance(omega, list)
        and not isinstance(omega, tuple)
        and not isinstance(omega, numpy.ndarray)
    ):
266 267 268 269
        omega = numpy.array([omega])
    else:
        omega = numpy.array(omega)

Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
270
    if beta is None:
271
        beta = numpy.array([(i * step_size) for i in range(points + 1)])
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
272 273 274 275 276
    elif (
        not isinstance(beta, list)
        and not isinstance(beta, tuple)
        and not isinstance(beta, numpy.ndarray)
    ):
277 278 279 280
        beta = numpy.array([beta])
    else:
        beta = numpy.array(beta)

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
281
    thresholds = numpy.ndarray([beta.size, omega.size], "float64")
282
    for bindex, b in enumerate(beta):
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
283 284 285 286 287 288 289 290 291
        thresholds[bindex, :] = numpy.array(
            [
                weighted_negatives_threshold(
                    licit_neg, licit_pos, spoof_neg, spoof_pos, w, b, criteria=criteria
                )
                for w in omega
            ],
            "float64",
        )
292 293 294 295 296 297 298 299

    return omega, beta, thresholds


def weighted_err(error_1, error_2, weight):
    """Calculates the weighted error rate between the two input parameters

  Keyword arguments:
300 301
    - error_1 - the first input error rate (FAR for zero effort impostors
    usually)
302 303 304 305 306 307
    - error_2 - the second input error rate (SFAR)
    - weight - the given weight
  """
    return (1 - weight) * error_1 + weight * error_2


Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
308 309 310
def error_rates_at_weight(
    licit_neg, licit_pos, spoof_neg, spoof_pos, omega, threshold, beta=0.5
):
311 312 313
    """Calculates several error rates: FRR, FAR (zero-effort impostors), SFAR,
    FAR_w, HTER_w for a given value of w. It returns the calculated threshold
    as a last argument
314 315 316 317 318 319 320 321

  Keyword arguments:

    - licit_neg - numpy.array of scores for the negatives (licit scenario)
    - licit_pos - numpy.array of scores for the positives (licit scenario)
    - spoof_neg - numpy.array of scores for the negatives (spoof scenario)
    - spoof_pos - numpy.array of scores for the positives (spoof scenario)
    - threshold - the given threshold
322 323 324 325 326
    - omega - the omega parameter balancing between impostors and spoofing
    attacks
    - beta - the weight parameter balancing between real accesses and all the

negative samples (impostors and spoofing attacks).
327 328 329
  """

    farfrr_licit = bob.measure.farfrr(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
330 331
        licit_neg, licit_pos, threshold
    )  # calculate test frr @ threshold (licit scenario)
332
    farfrr_spoof = bob.measure.farfrr(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
333 334
        spoof_neg, spoof_pos, threshold
    )  # calculate test frr @ threshold (spoof scenario)
335

Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
336 337
    # we can take this value from farfrr_spoof as well, it doesn't matter
    frr = farfrr_licit[1]
338 339 340 341 342 343 344 345 346 347
    far = farfrr_licit[0]
    sfar = farfrr_spoof[0]

    far_w = weighted_err(far, sfar, omega)
    hter_w = (far_w + frr) / 2
    wer_wb = weighted_err(frr, far_w, beta)

    return (frr, far, sfar, far_w, wer_wb, hter_w, threshold)


Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
348 349 350
def epsc_error_rates(
    licit_neg, licit_pos, spoof_neg, spoof_pos, thresholds, omega, beta
):
Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
351 352
    """Calculates several error rates: FAR_w and WER_wb for the given weights
    (omega and beta) and thresholds (the thresholds need to be computed first
353
    using the method: epsc_thresholds() before passing to this method)
354

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    Parameters
    ----------
    licit_neg : array_like
        array of scores for the negatives (licit scenario)
    licit_pos : array_like
        array of scores for the positives (licit scenario)
    spoof_neg : array_like
        array of scores for the negatives (spoof scenario)
    spoof_pos : array_like
        array of scores for the positives (spoof scenario)
    thresholds : array_like
        ndarray with threshold values
    omega : array_like
        array of the omega parameter balancing between impostors
        and spoofing attacks
    beta : array_like
        array of the beta parameter balancing between real accesses
        and all negatives (impostors and spoofing attacks)

    Returns
    -------
    far_w_errors: array_like
        FAR_w
    wer_wb_errors: array_like
        WER_wb
    """
381

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
382 383
    far_w_errors = numpy.ndarray((beta.size, omega.size), "float64")
    wer_wb_errors = numpy.ndarray((beta.size, omega.size), "float64")
384 385 386

    for bindex, b in enumerate(beta):
        errors = [
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
387 388 389 390 391 392 393 394 395
            error_rates_at_weight(
                licit_neg,
                licit_pos,
                spoof_neg,
                spoof_pos,
                w,
                thresholds[bindex, windex],
                b,
            )
396 397 398 399 400 401 402 403
            for windex, w in enumerate(omega)
        ]
        far_w_errors[bindex, :] = [errors[i][3] for i in range(len(errors))]
        wer_wb_errors[bindex, :] = [errors[i][4] for i in range(len(errors))]

    return far_w_errors, wer_wb_errors


Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
404 405 406
def all_error_rates(
    licit_neg, licit_pos, spoof_neg, spoof_pos, thresholds, omega, beta
):
Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
407 408
    """Calculates several error rates: FAR_w and WER_wb for the given weights
    (omega and beta) and thresholds (the thresholds need to be computed first
409
    using the method: epsc_thresholds() before passing to this method)
410

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    Parameters
    ----------
    licit_neg : array_like
        array of scores for the negatives (licit scenario)
    licit_pos : array_like
        array of scores for the positives (licit scenario)
    spoof_neg : array_like
        array of scores for the negatives (spoof scenario)
    spoof_pos : array_like
        array of scores for the positives (spoof scenario)
    thresholds : array_like
        ndarray with threshold values
    omega : array_like
        array of the omega parameter balancing between impostors
        and spoofing attacks
    beta : array_like
        array of the beta parameter balancing between real accesses
        and all negatives (impostors and spoofing attacks)

    Returns
    -------
    far_w_errors: array_like
        FAR_w
    wer_wb_errors: array_like
        WER_wb
    """
437

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
438 439 440 441 442 443
    frr_errors = numpy.ndarray((beta.size, omega.size), "float64")
    far_errors = numpy.ndarray((beta.size, omega.size), "float64")
    sfar_errors = numpy.ndarray((beta.size, omega.size), "float64")
    far_w_errors = numpy.ndarray((beta.size, omega.size), "float64")
    wer_wb_errors = numpy.ndarray((beta.size, omega.size), "float64")
    hter_wb_errors = numpy.ndarray((beta.size, omega.size), "float64")
444 445 446

    for bindex, b in enumerate(beta):
        errors = [
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
447 448 449 450 451 452 453 454 455
            error_rates_at_weight(
                licit_neg,
                licit_pos,
                spoof_neg,
                spoof_pos,
                w,
                thresholds[bindex, windex],
                b,
            )
456 457 458 459 460 461 462 463 464
            for windex, w in enumerate(omega)
        ]
        frr_errors[bindex, :] = [errors[i][0] for i in range(len(errors))]
        far_errors[bindex, :] = [errors[i][1] for i in range(len(errors))]
        sfar_errors[bindex, :] = [errors[i][2] for i in range(len(errors))]
        far_w_errors[bindex, :] = [errors[i][3] for i in range(len(errors))]
        wer_wb_errors[bindex, :] = [errors[i][4] for i in range(len(errors))]
        hter_wb_errors[bindex, :] = [errors[i][5] for i in range(len(errors))]

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    return (
        frr_errors,
        far_errors,
        sfar_errors,
        far_w_errors,
        wer_wb_errors,
        hter_wb_errors,
    )


def calc_aue(
    licit_neg,
    licit_pos,
    spoof_neg,
    spoof_pos,
    thresholds,
    omega,
    beta,
    l_bound=0,
    h_bound=1,
    var_param="omega",
):
487 488
    """Calculates AUE of EPSC for the given thresholds and weights

489
    Keyword arguments:
490 491 492 493 494 495 496 497

    - licit_neg - numpy.array of scores for the negatives (licit scenario)
    - licit_pos - numpy.array of scores for the positives (licit scenario)
    - spoof_neg - numpy.array of scores for the negatives (spoof scenario)
    - spoof_pos - numpy.array of scores for the positives (spoof scenario)
    - l_bound - lower bound of integration
    - h_bound - higher bound of integration
    - points - number of points to calculate EPSC
498
    - criteria - the decision threshold criteria ('eer', 'wer' or 'min-hter')
Amir MOHAMMADI's avatar
nit  
Amir MOHAMMADI committed
499
    - var_param - name of the parameter which is varied on the abscissa
500
    ('omega' or 'beta')
501 502 503 504
  """

    from scipy import integrate

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
505 506 507 508
    if var_param == "omega":
        errors = all_error_rates(
            licit_neg, licit_pos, spoof_neg, spoof_pos, thresholds, omega, beta
        )
509 510
        weights = omega  # setting the weights to the varying parameter
    else:
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
511 512 513
        errors = all_error_rates(
            licit_neg, licit_pos, spoof_neg, spoof_pos, thresholds, omega, beta
        )
514 515 516 517 518 519 520
        weights = beta  # setting the weights to the varying parameter

    wer_errors = errors[4].reshape(1, errors[4].size)

    l_ind = numpy.where(weights >= l_bound)[0][0]
    h_ind = numpy.where(weights <= h_bound)[0][-1]
    aue = integrate.cumtrapz(wer_errors, weights)
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
521
    aue = numpy.append([0], aue)  # for indexing purposes, aue is cumulative integration
522 523 524
    aue = aue[h_ind] - aue[l_ind]

    return aue
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664


def apcer_threshold(desired_apcer, pos, *negs, is_sorted=False):
    """Computes the threshold given the desired APCER as the criteria.

    APCER is computed as max of all APCER_PAI values.
    The threshold will be computed such that the real APCER is **at most** the desired
    value.

    Parameters
    ----------
    desired_apcer : float
        The desired APCER value.
    pos : list
        An array or list of positive scores in float.
    *negs
        A list of negative scores. Each item corresponds to the negative scores of one
        PAI.
    is_sorted : bool, optional
        Set to ``True`` if ALL arrays (pos and negs) are sorted.

    Returns
    -------
    float
        The computed threshold that satisfies the desired APCER.
    """
    threshold = max(
        far_threshold(neg, pos, desired_apcer, is_sorted=is_sorted) for neg in negs
    )
    return threshold


def apcer_bpcer(threshold, pos, *negs):
    """Computes APCER_PAI, APCER, and BPCER given the positive scores and a list of
    negative scores and a threshold.

    Parameters
    ----------
    threshold : float
        The threshold to be used to compute the error rates.
    pos : list
        An array or list of positive scores in float.
    *negs
        A list of negative scores. Each item corresponds to the negative scores of one
        PAI.

    Returns
    -------
    tuple
        A tuple such as (list of APCER_PAI, APCER, BPCER)
    """
    apcers = []
    assert len(negs) > 0, negs
    for neg in negs:
        far, frr = farfrr(neg, pos, threshold)
        apcers.append(far)
    bpcer = frr  # bpcer will be the same in all cases
    return apcers, max(apcers), bpcer


def negatives_per_pai_and_positives(filename, regexps=None, regexp_column="real_id"):
    """Returns scores for Bona-Fide samples and scores for each PAI.
    By default, the real_id column (second column) is used as indication for each
    Presentation Attack Instrument (PAI).

    For example, if you have scores like:
        001 001    bona_fide_sample_1_path 0.9
        001 print  print_sample_1_path     0.6
        001 print  print_sample_2_path     0.6
        001 replay replay_sample_1_path    0.2
        001 replay replay_sample_2_path    0.2
        001 mask   mask_sample_1_path      0.5
        001 mask   mask_sample_2_path      0.5
    this function will return 3 sets of negative scores (for each print, replay, and
    mask PAIs).

    Otherwise, you can provide a list regular expressions that match each PAI.
    For example, if you have scores like:
        001 001      bona_fide_sample_1_path 0.9
        001 print/1  print_sample_1_path     0.6
        001 print/2  print_sample_2_path     0.6
        001 replay/1 replay_sample_1_path    0.2
        001 replay/2 replay_sample_2_path    0.2
        001 mask/1   mask_sample_1_path      0.5
        001 mask/2   mask_sample_2_path      0.5
    and give a list of regexps as ('print', 'replay', 'mask') the function will return 3
    sets of negative scores (for each print, replay, and mask PAIs).


    Parameters
    ----------
    filename : str
        Path to the score file.
    regexps : None, optional
        A list of regular expressions that match each PAI. If not given, the values in
        the real_id column are used to find scores for different PAIs.
    regexp_column : str, optional
        If a list of regular expressions are given, those patterns will be matched
        against the values in this column.

    Returns
    -------
    tuple
        A tuple containing pos scores and a dict of negative scores mapping PAIs to
        their scores.

    Raises
    ------
    ValueError
        If none of the given regular expressions match the values in regexp_column.
    """
    pos = []
    negs = defaultdict(list)
    if regexps:
        regexps = [re.compile(pattern) for pattern in regexps]
        assert regexp_column in ("claimed_id", "real_id", "test_label"), regexp_column

    for claimed_id, real_id, test_label, score in four_column(filename):
        # if it is a Bona-Fide score
        if claimed_id == real_id:
            pos.append(score)
            continue
        if not regexps:
            negs[real_id].append(score)
            continue
        # if regexps is not None or empty and is not a Bona-Fide score
        string = {
            "claimed_id": claimed_id,
            "real_id": real_id,
            "test_label": test_label,
        }[regexp_column]
        for pattern in regexps:
            if pattern.match(string):
                negs[pattern.pattern].append(score)
                break
        else:  # this else is for the for loop: ``for pattern in regexps:``
            raise ValueError(
                f"No regexps: {regexps} match `{string}' from `{regexp_column}' column"
            )
    return pos, negs