File size: 16,007 Bytes
347a3de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""VSCE continuous first-passage analysis for a planar isotropic OU process.

Model: dZ = -kappa*Z dt + sqrt(2*diffusion) dB, exit when |Z| >= radius.
Analytic bounds concern CONTINUOUS monitoring. Finite-volume probabilities are
numerical approximations, not interval-certified values. Classical first-passage
identities are rederived in the manuscript; none is claimed as newly discovered.
"""
from __future__ import annotations

import math
import numpy as np
from scipy.integrate import quad
from scipy.linalg import eigh_tridiagonal, solve_banded
from scipy.optimize import minimize_scalar, brentq
from scipy.special import hyp1f1

MAX_ANALYTIC_BETA = 650.0
MAX_FV_BETA = 15.0
FV_EXIT_RESOLUTION = 1e-11


def _positive_upper_from_log(logvalue: float) -> float:
    """Cap at one and round positive underflow upward, never to false zero."""
    return max(float(np.nextafter(0.0,1.0)),math.exp(min(0.0,logvalue)))


def _parameters(radius: float, kappa: float, diffusion: float,
                initial_radius: float = 0.0) -> tuple[float, float]:
    if not all(math.isfinite(v) for v in (radius, kappa, diffusion, initial_radius)):
        raise ValueError("parameters must be finite")
    if radius <= 0 or kappa <= 0 or diffusion <= 0:
        raise ValueError("radius, kappa and diffusion must be positive")
    if initial_radius < 0 or initial_radius > radius:
        raise ValueError("initial_radius must be in [0,radius]")
    beta = kappa * radius * radius / (2 * diffusion)
    x0 = kappa * initial_radius * initial_radius / (2 * diffusion)
    if not math.isfinite(beta) or beta <= 0 or beta > MAX_ANALYTIC_BETA:
        raise ValueError("dimensionless beta exceeds supported range (beta<=650)")
    return beta,x0


def _h_integral(x: float) -> float:
    """Integral_0^x expm1(u)/u du using a strictly positive series."""
    if x < 0:
        raise ValueError("x must be nonnegative")
    if x == 0:
        return 0.0
    if x > MAX_ANALYTIC_BETA:
        raise ValueError("Poisson integral supports x<=650; use log/arbitrary precision")
    term = x
    total = term
    for n in range(1, 100000):
        term *= x * n / (n + 1) ** 2
        total += term
        if n > x and term <= total * 2e-16:
            return total
    raise RuntimeError("mean-exit positive series did not converge")


def mean_exit_time(radius: float, kappa: float, diffusion: float,
                   initial_radius: float = 0.0) -> float:
    """Exact mean exit time (special-function identity evaluated numerically)."""
    beta, x0 = _parameters(radius, kappa, diffusion, initial_radius)
    if initial_radius == radius:
        return 0.0
    if x0 == 0:
        return _h_integral(beta) / kappa / 2
    # Direct integration prevents cancellation when the initial point is close
    # to the absorbing boundary; the integrand has removable value one at zero.
    val, _ = quad(lambda x: math.expm1(x) / x if x else 1.0,
                  x0, beta, epsabs=1e-12, epsrel=2e-12)
    return val / kappa / 2


def mean_exit_upper(radius: float, T: float, kappa: float, diffusion: float,
                    initial_radius: float = 0.0) -> float:
    """Stopped positive-Poisson certificate, not generic Markov on a mean.

    P(tau <= T) <= [h(x0)+T]/h(beta), Lh=1, h(0)=0.
    """
    if T < 0 or not math.isfinite(T):
        raise ValueError("T must be finite and nonnegative")
    beta, x0 = _parameters(radius, kappa, diffusion, initial_radius)
    if x0 == beta:
        return 1.0
    if T == 0:
        return 0.0
    hx0 = _h_integral(x0)
    log_initial = math.log(hx0) if hx0 else -math.inf
    log_time = math.log(2.0)+math.log(kappa)+math.log(T)
    log_numerator = float(np.logaddexp(log_initial,log_time))
    return _positive_upper_from_log(log_numerator-math.log(_h_integral(beta)))


def _log_kummer_positive(a: float, x: float) -> float:
    """log M(a,1,x), a,x >= 0, with a positive-series overflow fallback."""
    if a < 0 or x < 0:
        raise ValueError("positive arguments required")
    if a == 0 or x == 0:
        return 0.0
    direct = float(hyp1f1(a, 1.0, x))
    if math.isfinite(direct) and direct > 0:
        return math.log(direct)
    logterm = 0.0
    logsum = 0.0
    safe_after = math.ceil(x + math.sqrt(a*x) + 2)
    for n in range(1, 1000000):
        logterm += math.log(a+n-1) + math.log(x) - 2*math.log(n)
        logsum = float(np.logaddexp(logsum, logterm))
        if n > safe_after and logterm - logsum < math.log(2e-16):
            return logsum
    raise RuntimeError("Kummer positive series did not converge")


def log_laplace_exit(s: float, radius: float, kappa: float, diffusion: float,
                     initial_radius: float = 0.0) -> float:
    """log E[exp(-s*tau)] from the regular Kummer boundary-value solution."""
    if s < 0 or not math.isfinite(s):
        raise ValueError("s must be finite and nonnegative")
    beta, x0 = _parameters(radius, kappa, diffusion, initial_radius)
    a = s/(2*kappa)
    return _log_kummer_positive(a, x0) - _log_kummer_positive(a, beta)


def laplace_exit(s: float, radius: float, kappa: float, diffusion: float,
                 initial_radius: float = 0.0) -> float:
    return math.exp(log_laplace_exit(s, radius, kappa, diffusion, initial_radius))


def laplace_chernoff_upper(radius: float, T: float, kappa: float,
                          diffusion: float, initial_radius: float = 0.0) -> dict:
    """Optimize the valid bound exp(s*T)*E exp(-s*tau), s>=0.

    The analytic expression is a rigorous upper bound for every s; double
    precision evaluation/optimization is not an outward-rounded certificate.
    No reliance on the optimizer finding the global minimum is needed for bound
    validity. Returns the selected s and its log bound for rare-event reporting.
    """
    if T < 0 or not math.isfinite(T):
        raise ValueError("T must be finite and nonnegative")
    beta, x0 = _parameters(radius, kappa, diffusion, initial_radius)
    if x0 == beta:
        return {"upper":1.0,"log_upper":0.0,"s":0.0}
    if T == 0:
        return {"upper":0.0,"log_upper":-math.inf,"s":math.inf}
    if T >= mean_exit_time(radius,kappa,diffusion,initial_radius):
        return {"upper":1.0,"log_upper":0.0,"s":0.0}
    def objective(a):
        return (2*kappa*T*a + _log_kummer_positive(a,x0)
                - _log_kummer_positive(a,beta))
    high = 1.0
    old = objective(high)
    for _ in range(50):
        current = objective(2*high)
        if current >= old:
            high *= 2
            break
        high *= 2
        old = current
    result = minimize_scalar(objective,bounds=(0.0,high),method="bounded",
                             options={"xatol":1e-10})
    candidates = [(0.0,0.0),(float(result.fun),float(result.x)),
                  (objective(high),high)]
    logupper,a = min(candidates)
    min_positive = float(np.nextafter(0.0,1.0))
    underflow = logupper < math.log(min_positive)
    # Preserve a positive, outward-underflow-rounded value instead of returning
    # a false zero probability certificate at positive time and diffusion.
    upper = min_positive if underflow else math.exp(logupper)
    return {"upper":upper,"log_upper":logupper,"s":2*kappa*a,
            "underflow_rounded_up":underflow}


def additive_exponential_upper(radius: float, T: float, kappa: float,
                               diffusion: float,
                               initial_radius: float = 0.0) -> dict:
    """Optimize positive Lyapunov functions exp(a*x)-1, 0<a<1.

    Useful even when an exact Poisson solution is unavailable in extensions.
    """
    if T < 0 or not math.isfinite(T):
        raise ValueError("T must be finite and nonnegative")
    beta, x0 = _parameters(radius,kappa,diffusion,initial_radius)
    if x0 == beta:
        return {"upper":1.0,"a":0.5,"compensator":kappa}
    if T == 0:
        return {"upper":0.0,"a":0.5,"compensator":kappa}
    def bound(a):
        xstar = max(0.0,min(beta,(2*a-1)/(a*(1-a))))
        gstar = math.exp(a*xstar)*(1-(1-a)*xstar)
        c = 2*kappa*a*max(1.0,gstar)
        numerator = math.expm1(a*x0)+c*T
        if numerator == 0:
            upper = float(np.nextafter(0.0,1.0))
        else:
            upper = _positive_upper_from_log(math.log(numerator)-math.log(math.expm1(a*beta)))
        return upper,c
    opt = minimize_scalar(lambda a: bound(a)[0],bounds=(1e-8,1-1e-8),
                          method="bounded",options={"xatol":1e-12})
    upper,c = bound(float(opt.x))
    return {"upper":upper,"a":float(opt.x),"compensator":c}


def ou_continuous_bounds(radius: float, T: float, kappa: float,
                         diffusion: float) -> dict:
    """Bounds from a centered start; diffusion here is d, not D before q."""
    if T <= 0:
        raise ValueError("T must be positive")
    beta,_ = _parameters(radius,kappa,diffusion)
    endpoint = math.exp(-beta/(-math.expm1(-2*kappa*T)))
    direct = math.exp(min(0.0,2*kappa*T-beta))
    blocks = max(1,math.ceil(kappa*T))
    h = T/blocks
    block = min(1.0,blocks*(1+math.exp(2*kappa*h))*math.exp(-beta/4))
    mean = mean_exit_upper(radius,T,kappa,diffusion)
    chernoff = laplace_chernoff_upper(radius,T,kappa,diffusion)
    additive = additive_exponential_upper(radius,T,kappa,diffusion)
    return {"beta":beta,"endpoint_lower":endpoint,"v5_direct_upper":direct,
            "v5_block_upper":block,"poisson_upper":mean,
            "laplace_upper":chernoff["upper"],"laplace_s":chernoff["s"],
            "laplace_log_upper":chernoff["log_upper"],
            "additive_upper":additive["upper"],
            "upper":min(direct,block,mean,chernoff["upper"],additive["upper"]),
            "mean_exit_time":mean_exit_time(radius,kappa,diffusion)}


def poisson_clearance(T: float, kappa: float, diffusion: float,
                       error_budget: float, events: int = 1) -> float:
    """Choose common radius so the union of ``events`` exits has risk <= budget.

    Numerical root of the exact monotone sufficient inequality; independent
    events are not assumed. The returned radius is rounded slightly upward.
    """
    if T<=0 or kappa<=0 or diffusion<=0 or events<1 or int(events)!=events:
        raise ValueError("positive T,kappa,diffusion and integer events required")
    if not 0<error_budget<1:
        raise ValueError("error_budget must be between zero and one")
    target=2*kappa*events*T/error_budget
    if not math.isfinite(target) or target > _h_integral(MAX_ANALYTIC_BETA):
        raise ValueError("clearance target exceeds supported beta<=650")
    high=1.0
    while _h_integral(high)<target:
        high=min(MAX_ANALYTIC_BETA,high*2)
    beta=brentq(lambda b:_h_integral(b)-target,0.0,high,xtol=1e-13)
    return math.sqrt(2*diffusion*beta/kappa)*(1+2e-14)


def _fv_generator(beta: float, kappa: float, cells: int):
    """Weighted nodal finite-volume generator, absorbing node x=beta.

    Nodes i*beta/cells, i=0,...,cells-1, plus Dirichlet node beta. The
    regular origin has zero weighted flux. Off-diagonal rates are positive.
    """
    if not (0 < beta <= MAX_FV_BETA) or not 8 <= cells <= 2000 or kappa <= 0:
        raise ValueError("validated FV support: 0<beta<=15, 8<=cells<=2000, kappa>0")
    h = beta/cells
    x = np.arange(cells)*h
    left = np.maximum(0.0,x-h/2)
    right = x+h/2
    weights = np.exp(-left)*(-np.expm1(-(right-left)))
    face_x = (np.arange(cells)+0.5)*h
    conductance = 2*kappa*face_x*np.exp(-face_x)/h
    upper = conductance/weights
    lower = np.zeros(cells)
    lower[1:] = conductance[:-1]/weights[1:]
    diagonal = -(upper+lower)
    return x,weights,diagonal,upper,lower


def survival_fv(radius: float, times, kappa: float, diffusion: float,
                 cells: int = 400) -> dict:
    """Continuous-time killed-process PDE estimate from a centered start.

    Positive spatial discretization; exact matrix exponential in time (to
    floating precision). No Monte Carlo or sample monitoring is involved.
    Grid convergence and independent transform/MFPT checks remain necessary.
    Positive-time exits below 1e-11 are marked NaN/unresolved rather than zero.
    """
    beta,_ = _parameters(radius,kappa,diffusion)
    times = np.atleast_1d(np.asarray(times,dtype=float))
    if np.any(~np.isfinite(times)) or np.any(times<0):
        raise ValueError("times must be finite and nonnegative")
    x,w,diag,upper,lower = _fv_generator(beta,kappa,cells)
    offdiag = np.sqrt(upper[:-1]*lower[1:])
    eig,vec = eigh_tridiagonal(diag,offdiag)
    if eig[-1]>=0:
        raise ArithmeticError("principal eigenvalue unresolved; FV estimate rejected")
    coefficients = vec[0,:]*(vec.T@np.sqrt(w))/math.sqrt(w[0])
    raw = np.exp(np.outer(times,eig))@coefficients
    # Tiny clipping corrects roundoff, never supplies a certified interval.
    survival = np.clip(raw,0.0,1.0)
    survival[times==0] = 1.0
    probability = 1-survival
    resolved = (times==0)|(probability>FV_EXIT_RESOLUTION)
    probability[~resolved] = np.nan
    return {"times":times,"survival":survival,"exit_probability":probability,
            "cells":cells,"beta":beta,"principal_eigenvalue":float(-eig[-1]),
            "roundoff_clip_max":float(np.max(np.abs(raw-survival))),
            "resolved":resolved,"exit_resolution_floor":FV_EXIT_RESOLUTION,
            "max_supported_beta":MAX_FV_BETA,
            "interpretation":"PDE estimate; NaN means exit probability below numerical resolution"}


def mean_exit_fv(radius: float, kappa: float, diffusion: float,
                 cells: int = 400) -> float:
    beta,_ = _parameters(radius,kappa,diffusion)
    _,_,diag,upper,lower = _fv_generator(beta,kappa,cells)
    band = np.zeros((3,cells))
    band[0,1:] = -upper[:-1]
    band[1,:] = -diag
    band[2,:-1] = -lower[1:]
    return float(solve_banded((1,1),band,np.ones(cells))[0])


def laplace_exit_fv(s: float, radius: float, kappa: float, diffusion: float,
                    cells: int = 400) -> float:
    if s<0:
        raise ValueError("s must be nonnegative")
    beta,_ = _parameters(radius,kappa,diffusion)
    _,_,diag,upper,lower = _fv_generator(beta,kappa,cells)
    band = np.zeros((3,cells))
    band[0,1:] = -upper[:-1]
    band[1,:] = s-diag
    band[2,:-1] = -lower[1:]
    rhs = np.zeros(cells)
    rhs[-1] = upper[-1]  # absorbing boundary has Laplace value one
    return float(solve_banded((1,1),band,rhs)[0])


def simulate_nested_sampled_exit(radius: float, T: float, kappa: float,
                                  diffusion: float, fine_dt: float,
                                  sample_strides=(1,2,4,10), trials=20000,
                                  seed=20261013) -> dict:
    """Exact OU transitions, nested observation grids; every rate is a LOWER
    approximation to continuous monitoring, including the finest grid.
    """
    _parameters(radius,kappa,diffusion)
    steps = round(T/fine_dt)
    if steps<1 or abs(steps*fine_dt-T)>1e-10:
        raise ValueError("fine_dt must divide positive T")
    strides = sorted(set(map(int,sample_strides)))
    if any(s<1 or steps%s for s in strides) or trials<1:
        raise ValueError("positive strides must divide number of steps")
    rng = np.random.default_rng(seed)
    z = np.zeros((trials,2))
    hit = {s:np.zeros(trials,dtype=bool) for s in strides}
    decay = math.exp(-kappa*fine_dt)
    sigma = math.sqrt(diffusion/kappa*(-math.expm1(-2*kappa*fine_dt)))
    for step in range(1,steps+1):
        z = decay*z+sigma*rng.standard_normal((trials,2))
        outside = np.sum(z*z,axis=1)>=radius*radius
        for s in strides:
            if step%s==0:
                hit[s] |= outside
    return {"trials":trials,"seed":seed,"fine_dt":fine_dt,
            "T":T,"radius":radius,"kappa":kappa,"diffusion":diffusion,
            "counts":{str(s):int(hit[s].sum()) for s in strides},
            "rates":{str(s):float(hit[s].mean()) for s in strides},
            "interpretation":"sampled first exits; all rates underdetect continuous first exits"}