aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/ranking/ReciprocalRankNormalizer.java
blob: fca920a7a657fa3e87178a43ffa0dafb930cd306 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.ranking;

import java.util.Arrays;

class ReciprocalRankNormalizer extends Normalizer {

    private final double k;

    ReciprocalRankNormalizer(int maxSize, double k) {
        super(maxSize);
        this.k = k;
    }

    static record IdxScore(int index, double score) {}

    void normalize() {
        if (size < 1) return;
        IdxScore[] temp = new IdxScore[size];
        for (int i = 0; i < size; i++) {
            double val = data[i];
            if (Double.isNaN(val)) val = Double.NEGATIVE_INFINITY;
            temp[i] = new IdxScore(i, val);
        }
        Arrays.sort(temp, (a, b) -> Double.compare(b.score, a.score));
        for (int i = 0; i < size; i++) {
            int idx = temp[i].index;
            double old = data[idx];
            data[idx] = 1.0 / (k + 1.0 + i);
        }
    }

    String normalizing() { return "reciprocal-rank{k:" + k + "}"; }
}