package com.ankurm.rageval;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Rank-based retrieval metrics. Every method takes the ranked list of passage ids a retriever returned
* (best first) and the ground truth, and is a pure function with no dependencies.
*
*
Conventions, all pinned by {@code MetricsTest}:
*
* - Rank is 1-based; {@code k} cuts the list to its first k entries.
* - Duplicates are removed first (first occurrence wins), so two chunks of one document cannot
* count twice.
* - A list shorter than k is not padded: precision still divides by k.
* - With no relevant passages, recall and nDCG are undefined and return {@code NaN}.
*
*/
public final class Metrics {
private Metrics() {}
/** 1 if any relevant passage is in the top k, else 0. */
public static double hitAtK(List ranked, Set relevant, int k) {
return top(ranked, k).stream().anyMatch(relevant::contains) ? 1 : 0;
}
/** Distinct relevant passages found in the top k, divided by all relevant passages. */
public static double recallAtK(List ranked, Set relevant, int k) {
if (relevant.isEmpty()) return Double.NaN;
long found = top(ranked, k).stream().filter(relevant::contains).count();
return (double) found / relevant.size();
}
/** Relevant passages in the top k, divided by k (not by the list length). */
public static double precisionAtK(List ranked, Set relevant, int k) {
long found = top(ranked, k).stream().filter(relevant::contains).count();
return (double) found / k;
}
/** 1 / rank of the first relevant passage, or 0 if none is in the list. */
public static double reciprocalRank(List ranked, Set relevant) {
List list = distinct(ranked);
for (int i = 0; i < list.size(); i++) {
if (relevant.contains(list.get(i))) return 1.0 / (i + 1);
}
return 0;
}
/**
* nDCG@k with exponential gain: DCG = sum (2^grade - 1) / log2(rank + 1), divided by the DCG of the
* best possible ordering of the graded passages.
*/
public static double ndcgAtK(List ranked, Map grades, int k) {
if (grades.isEmpty()) return Double.NaN;
double dcg = 0;
List list = top(ranked, k);
for (int i = 0; i < list.size(); i++) {
dcg += gain(grades.getOrDefault(list.get(i), 0), i + 1);
}
List ideal = grades.values().stream().sorted(java.util.Comparator.reverseOrder()).toList();
double idcg = 0;
for (int i = 0; i < Math.min(k, ideal.size()); i++) idcg += gain(ideal.get(i), i + 1);
return dcg / idcg;
}
private static double gain(int grade, int rank) {
return (Math.pow(2, grade) - 1) / (Math.log(rank + 1) / Math.log(2));
}
static List distinct(List ranked) {
return new ArrayList<>(new LinkedHashSet<>(ranked));
}
static List top(List ranked, int k) {
List list = distinct(ranked);
return list.subList(0, Math.min(k, list.size()));
}
}