File size: 1,852 Bytes
1ca0407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Young's convolution inequality quotient ||f*g||_r / (||f||_p ||g||_q) for non-negative step functions.

f = sum_i a_i 1_[i, i+1), g = sum_j b_j 1_[j, j+1); then f*g is piecewise linear with knot values
(f*g)(k) = sum_{i+j=k-1} a_i b_j, so all three norms are integrated exactly (up to float64 rounding).
Upstream (classical_inequalities.ipynb) used np.convolve(mode="same") on samples of user callables, which
truncates the convolution's support; this closed form replaces it.
"""
import numpy as np

from run import Invalid, float_list


def _seg_power_integral(c0, c1, r):
    """int_0^1 ((1-s) c0 + s c1)^r ds for non-negative c0, c1 (vectorised, cancellation-free)."""
    hi, lo = np.maximum(c0, c1), np.minimum(c0, c1)
    out = np.zeros_like(hi)
    pos = hi > 0
    t = lo[pos] / hi[pos]
    with np.errstate(divide="ignore"):
        u = np.log(t)
    num, den = np.expm1((r + 1) * u), np.expm1(u)
    ratio = np.where(u == 0, r + 1, num / np.where(u == 0, 1.0, den))  # (1 - t^{r+1}) / (1 - t)
    out[pos] = hi[pos] ** r * ratio / (r + 1)
    return out


def _vec(v, name, max_len):
    a = np.array(float_list(v, None, name))
    if not 1 <= len(a) <= max_len:
        raise Invalid(f"need 1 <= len({name}) <= {max_len}")
    if a.min() < 0 or a.max() > 1e6 or a.max() <= 0:
        raise Invalid(f"{name}: entries must be in [0, 1e6] and not all zero")
    return a / a.max()


def check(inst, ans):
    p, q = inst["p"], inst["q"]
    r = 1.0 / (1.0 / p + 1.0 / q - 1.0)
    a = _vec(ans.get("f"), "f", inst["max_len"])
    b = _vec(ans.get("g"), "g", inst["max_len"])
    c = np.concatenate([[0.0], np.convolve(a, b), [0.0]])
    conv_r = float(np.sum(_seg_power_integral(c[:-1], c[1:], r))) ** (1.0 / r)
    fp = float(np.sum(a ** p)) ** (1.0 / p)
    gq = float(np.sum(b ** q)) ** (1.0 / q)
    return conv_r / (fp * gq), {"r": r}