File size: 4,567 Bytes
1263695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""Exact scalar contraction scheduling with at most one split request.

All arithmetic uses fractions.Fraction. A fragment (i, a) applies
    x <- a*x + (1-a)*centers[i].
The product of the fragment retentions for request i equals retentions[i].
This is an enlarged scheduling policy: at most n+1 updates replace n updates.
No claim of preserving a gradient-query count or sum of step sizes is made.
"""

from fractions import Fraction


def execute_fragments(centers, fragments, initial=0):
    """Evaluate a fragment list exactly."""
    x = Fraction(initial)
    centers = tuple(map(Fraction, centers))
    for i, retention in fragments:
        a = Fraction(retention)
        x = a * x + (1 - a) * centers[i]
    return x


def optimal_one_split_order(centers, retentions, initial=0, target=0):
    """Globally minimize squared terminal error over all finite fragmentations.

    Rational retentions must be in [0,1]. The returned policy splits at most
    one request into two fragments, each with the same target as its parent.
    The algorithm makes O(n**2) exact rational operations, apart from sorting;
    all rational operands have polynomial binary length in the input.
    It also returns the optimal squared error and the full attainable interval.
    """
    centers = tuple(map(Fraction, centers))
    retentions = tuple(map(Fraction, retentions))
    initial, target = Fraction(initial), Fraction(target)
    n = len(centers)
    if len(retentions) != n:
        raise ValueError("centers and retentions must have equal length")
    if any(a < 0 or a > 1 for a in retentions):
        raise ValueError("retentions must lie in [0,1]")

    minimum_order = sorted(range(n), key=lambda i: -centers[i])
    maximum_order = sorted(range(n), key=lambda i: centers[i])

    def unsplit(order):
        return [(i, retentions[i]) for i in order]

    minimum = execute_fragments(centers, unsplit(minimum_order), initial)
    maximum = execute_fragments(centers, unsplit(maximum_order), initial)
    best_endpoint = min(max(target, minimum), maximum)

    def result(fragments, split_request, swaps):
        endpoint = execute_fragments(centers, fragments, initial)
        return {
            "fragments": fragments,
            "split_request": split_request,
            "endpoint": endpoint,
            "objective": (endpoint - target) ** 2,
            "optimal_endpoint": best_endpoint,
            "attainable_interval": (minimum, maximum),
            "adjacent_swaps_examined": swaps,
        }

    if target <= minimum:
        return result(unsplit(minimum_order), None, 0)
    if target >= maximum:
        return result(unsplit(maximum_order), None, 0)

    # A bubble-sort path increases the endpoint from minimum to maximum.
    order = minimum_order[:]
    suffix = [Fraction(1)] * (n + 1)
    for p in range(n - 1, -1, -1):
        suffix[p] = retentions[order[p]] * suffix[p + 1]
    current = minimum
    swaps = 0
    for end in range(n - 1, 0, -1):
        for p in range(end):
            i, j = order[p], order[p + 1]
            if centers[i] <= centers[j]:
                continue
            ai, aj = retentions[i], retentions[j]
            later = suffix[p + 2]
            increment = later * (1 - ai) * (1 - aj) * (centers[i] - centers[j])
            following = current + increment
            swaps += 1
            if increment > 0 and current <= target <= following:
                lam = (target - current) / increment
                if lam == 0:
                    return result(unsplit(order), None, swaps)
                if lam == 1:
                    next_order = order[:]
                    next_order[p], next_order[p + 1] = j, i
                    return result(unsplit(next_order), None, swaps)
                # Final retention v interpolates the two adjacent endpoints.
                # The first retention ai/v keeps request i's total unchanged.
                v = 1 - lam * (1 - ai)
                first = ai / v  # v>0 for an interior interpolation, even if ai=0.
                fragments = (
                    unsplit(order[:p])
                    + [(i, first), (j, aj), (i, v)]
                    + unsplit(order[p + 2 :])
                )
                return result(fragments, i, swaps)
            order[p], order[p + 1] = j, i
            suffix[p + 1] = ai * later
            current = following
    raise ArithmeticError("attainable interval was not crossed")


if __name__ == "__main__":
    answer = optimal_one_split_order([-1, 1], [Fraction(1, 2)] * 2)
    print(answer)