def calc_ap(prec, recall):
    """
    Computes average precision from precision recall curves. Curves
    are expected to be same size and 1D.
    """
    assert prec.size() == recall.size(), "Precision and recall curves must be same size"
    ap = 0.0
    if len(prec) == 0:
        return ap
    prev_r = 0.0
    prev_p = prec[0]
    for p, r in zip(prec, recall):
        ap += (r - prev_r) * (p + prev_p) / 2.0
        prev_r = r
        prev_p = p

    return ap