def ap_from_ranks(ranks, nres):
    """ Computes Average Precision for retrieval results given by the retrieved ranks of the relevant documents.
    
    ranks - Ordered list of ranks of true positives (zero-based).
    nres  = Total number of positives in dataset.
    
    Returns: Area under the precision-recall curve.
    """

    # accumulate trapezoids in PR-plot
    ap = 0.0

    # All have an x-size of:
    recall_step = 1.0 / nres

    for ntp, rank in enumerate(ranks):

        # y-size on left side of trapezoid:
        # ntp = nb of true positives so far
        # rank = nb of retrieved items so far
        precision_0 = 1.0 if rank == 0 else ntp / float(rank)

        # y-size on right side of trapezoid:
        # ntp and rank are increased by one
        precision_1 = (ntp+1) / float(rank+1)

        ap += (precision_1 + precision_0) * recall_step / 2.0

    return ap