Download graders/ae_p17_young_convolution/check.py from amphora/MathConstructOptimize-Envs: direct link, hf CLI and curl.
- Browser
- Download file 1.85 kB
-
https://huggingface.co/datasets/amphora/MathConstructOptimize-Envs/resolve/main/graders/ae_p17_young_convolution/check.py
- Command line
-
hf download hf://datasets/amphora/MathConstructOptimize-Envs/graders/ae_p17_young_convolution/check.py
-
curl -L -o check.py https://huggingface.co/datasets/amphora/MathConstructOptimize-Envs/resolve/main/graders/ae_p17_young_convolution/check.py
1.85 kB
| """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} | |