File size: 11,717 Bytes
d980d12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""ELYRION III: declared four-state photochemical selection model.

All examples are mathematical simulations, not measured photoresist parameters.
States are A=eligible, B=marked, X=rejected within a pass, C=committed.
Arrays of occupancies have shape (4, n_points); columns conserve one material unit.
"""
from __future__ import annotations

from math import e, pi
import numpy as np
from scipy.optimize import brentq
from scipy.sparse import bmat, diags, lil_matrix
from scipy.sparse.linalg import expm_multiply

A, B, X, C = range(4)


def transition(source: int, target: int, action: float) -> np.ndarray:
    """Exact finite-action first-order source -> target stochastic matrix."""
    if source not in range(4) or target not in range(4) or source == target:
        raise ValueError("Two different state indices in 0..3 are required.")
    if not np.isfinite(action) or action < 0:
        raise ValueError("Action must be finite and nonnegative.")
    out = np.eye(4)
    stay = np.exp(-action)
    out[source, source] = stay
    out[target, source] = -np.expm1(-action)
    return out


def ideal_filter() -> np.ndarray:
    """Ideal limit A->X, B->A, X->X, C->C; finite-time exactness is NOT assumed."""
    out = np.zeros((4, 4))
    out[X, A] = out[A, B] = out[X, X] = out[C, C] = 1.0
    return out


def finite_filter(h_reject: float, h_reset: float) -> np.ndarray:
    """Reject unmarked A first, then reset protected B. Order is essential."""
    return transition(B, A, h_reset) @ transition(A, X, h_reject)


def ideal_commit(probability: float) -> np.ndarray:
    """Commit a fraction of A; reinitialize uncommitted X/B; preserve C."""
    if not np.isfinite(probability) or not 0 <= probability <= 1:
        raise ValueError("Commit probability must lie in [0,1].")
    out = np.zeros((4, 4))
    out[A, A], out[C, A] = 1.0 - probability, probability
    out[A, B] = out[A, X] = out[C, C] = 1.0
    return out


def mark(state: np.ndarray, action: float, fringe: np.ndarray) -> np.ndarray:
    """Patterned first-order A->B exposure; other states are optically inert."""
    state = np.asarray(state, dtype=float)
    fringe = np.asarray(fringe, dtype=float)
    if state.ndim != 2 or state.shape[0] != 4 or fringe.shape != (state.shape[1],):
        raise ValueError("Expected state (4,n) and fringe (n,).")
    if action < 0 or not np.isfinite(action) or np.any(fringe < 0):
        raise ValueError("Nonnegative finite action and nonnegative fringes required.")
    out = state.copy()
    moved = -np.expm1(-action * fringe) * state[A]
    out[A] -= moved
    out[B] += moved
    return out


def run_pass(fringes: np.ndarray, actions: np.ndarray,
             committed: float = 0.0, filter_action: float | None = None) -> np.ndarray:
    """One pass, with no commit at its end. Return all four state fields."""
    fringes = np.asarray(fringes, dtype=float)
    actions = np.asarray(actions, dtype=float)
    if fringes.ndim != 2 or actions.shape != (fringes.shape[0],):
        raise ValueError("Fringes must have shape (n_gates,n_points).")
    if not 0 <= committed <= 1:
        raise ValueError("Committed fraction must lie in [0,1].")
    state = np.zeros((4, fringes.shape[1]))
    state[A], state[C] = 1.0 - committed, committed
    filt = ideal_filter() if filter_action is None else finite_filter(filter_action, filter_action)
    for g, action in zip(fringes, actions):
        state = filt @ mark(state, float(action), g)
    return state


def fringes(m: int, theta: np.ndarray, phases: np.ndarray | None = None,
            floor: float = 0.0) -> np.ndarray:
    if not isinstance(m, (int, np.integer)) or m < 1 or floor < 0:
        raise ValueError("m>=1 and a nonnegative floor are required.")
    theta = np.asarray(theta, dtype=float).reshape(-1)
    if phases is None:
        phases = 2 * pi * np.arange(m) / m
    phases = np.asarray(phases, dtype=float)
    if phases.shape != (m,):
        raise ValueError("Exactly m phases required.")
    # Numerically nonnegative version of 1-cos(theta-phase).
    return 2 * np.sin((theta[None, :] - phases[:, None]) / 2)**2 + floor


def comb_profile(m: int, action: float | np.ndarray, theta: np.ndarray,
                 phases: np.ndarray | None = None, floor: float = 0.0) -> np.ndarray:
    g = fringes(m, theta, phases, floor)
    a = np.broadcast_to(np.asarray(action, dtype=float), (m,))
    if np.any(a < 0) or not np.all(np.isfinite(a)):
        raise ValueError("Actions must be finite and nonnegative.")
    return np.prod(-np.expm1(-a[:, None] * g), axis=0)


def log_midpoint_yield(m: int, action: float) -> float:
    if m < 2 or action <= 0:
        return -np.inf
    # Pair symmetric distances to avoid loss near 2*pi at large m.
    d = 2 * np.sin(pi * (2 * np.arange(m//2) + 1) / (2*m))**2
    result = 2*np.log(-np.expm1(-action*d)).sum()
    if m % 2:
        result += np.log(-np.expm1(-2*action))
    return float(result)


def optimal_action(m: int, target: float) -> float:
    """Unique per-gate action attaining all m prescribed midpoint yields."""
    if m < 2 or not 0 < target < 1:
        raise ValueError("m>=2 and 0<target<1 are required.")
    hi = float(m*m)
    while log_midpoint_yield(m, hi) < np.log(target):
        hi *= 2
    return float(brentq(lambda u: log_midpoint_yield(m, u)-np.log(target),
                        1e-14, hi, xtol=1e-12, rtol=1e-13))


def limit_product_bounds(c: float, terms: int = 12) -> tuple[float, float]:
    """Analytic truncation bounds evaluated in floating point (not interval arithmetic).

    Actual P_inf is between P_R*exp(-tail_log_bound) and P_R.
    Floating output is descriptive; the manuscript proves the exact inequalities.
    """
    if c <= 0 or terms < 1:
        raise ValueError("c>0, terms>=1 are required.")
    aa = c * pi*pi / 2
    r = np.arange(terms)
    upper = float(np.exp(2*np.log(-np.expm1(-aa*(2*r+1)**2)).sum()))
    qr = float(np.exp(-aa*(2*terms+1)**2))
    ratio = float(np.exp(-8*aa*(terms+1)))
    tail_log = 2*qr/((1-qr)*(1-ratio))
    return upper*np.exp(-tail_log), upper


def cubic_constant(target: float) -> float:
    if not 0 < target < 1:
        raise ValueError("0<target<1 required.")
    return float(brentq(lambda c: limit_product_bounds(c, 32)[1]-target,
                        1e-5, 20.0, xtol=1e-14))


def repeated_commits(survival: np.ndarray, coefficient: float, scale: float
                     ) -> tuple[np.ndarray, int, float]:
    """Log remaining fraction from finite full commits plus one partial commit.

    Commit weights sum to coefficient/scale. Collapse repetition algebraically;
    report the actual number of passes rather than treating them as free.
    """
    if coefficient < 0 or scale <= 0:
        raise ValueError("coefficient>=0 and scale>0 required.")
    survival = np.asarray(survival, dtype=float)
    if np.any(survival < 0) or np.any(survival >= 1):
        raise ValueError("0<=survival<1 required for finite logarithms.")
    x = coefficient/scale
    whole = int(np.floor(x))
    fractional = float(x-whole)
    logs = whole*np.log1p(-survival) + np.log1p(-fractional*survival)
    return logs, whole + int(fractional > 0), fractional


def hazard_example(action: float, n: int = 24) -> dict:
    """Exact finite 3D hazard target with three positive first-harmonic products."""
    if not 0 < action < 0.5:
        raise ValueError("0<action<1/2 required.")
    x = 2*pi*np.arange(n)/n
    mesh = np.meshgrid(x, x, x, indexing='ij')
    shifts = [(0., 0., 0.), (2.0, 0.7, 4.0), (4.6, 3.4, 1.2)]
    weights = [0.15, 0.10, 0.07]
    ideal_h = np.zeros((n, n, n))
    log_remaining = np.zeros_like(ideal_h)
    passes = 0
    qmax = 0.0
    for shift, w in zip(shifts, weights):
        gs = [1 + np.cos(mesh[j]-shift[j]) for j in range(3)]
        pp = np.prod(gs, axis=0)
        qs = np.prod([-np.expm1(-action*g) for g in gs], axis=0)
        ideal_h += w*pp
        logs, count, _ = repeated_commits(qs, w, action**3)
        log_remaining += logs
        passes += count
        qmax = max(qmax, float(qs.max()))
    target = -np.expm1(-ideal_h)
    written = -np.expm1(log_remaining)
    # Jensen gives product gate >= a^m exp(-m*a) product fringe for 0<=g<=2.
    relative = (1-np.exp(-3*action)) + qmax/(2*(1-qmax))
    grid_bound = relative*float(ideal_h.max())
    # Whole-domain bounds, not maxima inferred from a finite spatial grid.
    global_qmax = float((-np.expm1(-2*action))**3)
    global_hmax = 8*sum(weights)
    global_relative = (1-np.exp(-3*action)) + global_qmax/(2*(1-global_qmax))
    bound = global_relative*global_hmax
    return dict(target=target, written=written, error=float(abs(target-written).max()),
                hazard_error=float(abs(-log_remaining-ideal_h).max()), bound=bound,
                grid_bound=grid_bound,
                passes=passes, factor_gates=3*passes,
                primitive_ideal_maps=7*passes, # 3 marks + 3 filters + 1 commit/reinitialize
                mark_action=3*action*passes, action=action)


def diffusion_comb(m: int, action: float, diffusion: float, n: int | None = None,
                   floor: float = 0.0, rate: float = 1.0) -> dict:
    """Finite-difference semigroup simulation of actual finite-duration marking.

    Continuum theta-space generator is D_theta*d²/dtheta²; rate is sigma*P.
    Filters are ideal instantaneous operations here. No splitting during marking.
    Grid-dependent dark bound uses the exact discrete first-mode eigenvalue.
    """
    if m < 2 or action <= 0 or diffusion < 0 or floor < 0 or rate <= 0:
        raise ValueError("Invalid kinetic parameters.")
    n = n or 64*m
    if n % (2*m) != 0:
        raise ValueError("Grid size must be divisible by 2*m.")
    theta = 2*pi*np.arange(n)/n
    h = 2*pi/n
    lap = lil_matrix((n, n), dtype=float)
    for i in range(n):
        lap[i, i] = -2/h**2
        lap[i, (i-1)%n] = lap[i, (i+1)%n] = 1/h**2
    dd = diffusion*lap.tocsr()
    zero = diags(np.zeros(n), format='csr')
    s = np.ones(n)
    tau = action/rate
    for j in range(m):
        r = rate*(2*np.sin((theta-2*pi*j/m)/2)**2 + floor)
        rr = diags(r, format='csr')
        generator = bmat([[dd-rr, zero], [rr, dd]], format='csr')
        # A and B diffuse with the same D. B is the retained population after filtering.
        state = expm_multiply(tau*generator, np.concatenate([s, np.zeros(n)]))
        s = state[n:]
    dark_idx = np.arange(m)*(n//m)
    bright_idx = dark_idx + n//(2*m)
    lam = 4*diffusion*np.sin(h/2)**2 / h**2
    bounds = []
    for j in range(m):
        if lam == 0:
            avg_decay = 1.0
        else:
            avg_decay = np.exp(-lam*(m-j-1)*tau)*(-np.expm1(-lam*tau))/(lam*tau)
        exponent = action*(floor + max(0.0, 1-avg_decay))
        bounds.append(-np.expm1(-exponent))
    return dict(theta=theta, survival=s, dark=s[dark_idx], bright=s[bright_idx],
                bounds=np.asarray(bounds), time=m*tau, discrete_lambda=lam,
                diffusion=diffusion, action=action, m=m, n=n)


def diffusion_bright_bound(m: int, action: float, diffusion: float,
                           total_time: float, tube: float) -> float:
    """Continuum Brownian-tube sufficient bright lower bound, in theta units."""
    if not 0 < tube < pi:
        raise ValueError("0<tube<pi required.")
    theta = pi/m
    phase = 2*pi*np.arange(m)/m
    dist = abs((theta-phase+pi) % (2*pi)-pi)
    g_lower = 2*np.sin(np.maximum(0., dist-tube/m)/2)**2
    conditional = float(np.prod(-np.expm1(-action*g_lower)))
    if diffusion*total_time == 0:
        return conditional
    probability = max(0., 1-4*np.exp(-tube*tube/(4*diffusion*total_time*m*m)))
    return probability*conditional