Algorithmresearch
Oscillator phase noise analysis
Also called Demir-Mehrotra-Roychowdhury phase noise, perturbation projection vector method.
Demir, Mehrotra and Roychowdhury's nonlinear analysis that projects noise on the oscillator's perturbation projection vector to get its phase diffusion and Lorentzian spectrum.
- Time
- O(I S n^3 + S n p) worst
- Space
- O(S n^2) extra
- Where
- I = the number of Newton iterations for the orbit; S = the number of time steps per period; n = the number of state variables; p = the number of noise sources
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alper Demir, Amit Mehrotra, Jaijeet Roychowdhury, 2000
Oscillator phase noise analysis computes how noise in an oscillator's devices spreads its output spectrum around the carrier. Demir, Mehrotra and Roychowdhury (2000) showed that the noise makes the oscillator's phase drift as a random walk, with a rate fixed by the perturbation projection vector (PPV), the periodic adjoint solution that measures how much a kick at each instant shifts the phase for good. This page belongs to the circuit simulation half of the logic and circuit simulation sub-area; the method takes the periodic orbit from shooting or harmonic balance and returns and the spectrum .
In plain words
An oscillator has no clock to follow: it keeps its own time. When noise pushes it, the size of the swing recovers, but a shift in its timing does not, because nothing pulls it back. The small shifts add up, so the timing wanders more and more.
The analysis first finds the noiseless repeating waveform. Then it computes, for every instant of the cycle and every node, how much a small push at that instant would shift the timing for good. A push at the peak of a swing often does nothing to the timing, while a push at a zero crossing does a lot. The noise at each instant is weighted by this sensitivity and averaged over the cycle. The result is one number, the rate at which the timing wanders, and from it follow the jitter and the shape of the spectrum near the carrier.
The problem
The oscillator is a state equation with states, a Jacobian and independent white noise sources of unit two-sided density, . A circuit in modified nodal analysis form with a nonsingular capacitance matrix gives this form; with algebraic unknowns the same method works on the differential-algebraic equation with more care. The noise columns of come from the device noise models of circuit noise analysis, for example for the thermal current of a resistor as a two-sided density.
Without noise the oscillator has a stable periodic orbit with an unknown period , a limit cycle. The PPV is the periodic solution of the adjoint equation with . The output is the diffusion constant
in seconds, and the single-sideband phase noise of the first harmonic at offset from ,
Demir, Mehrotra and Roychowdhury proved that the noisy solution stays close to , where the phase shift is asymptotically a Wiener process with ; the timing jitter after a time has the standard deviation . This is a model of a stochastic differential equation, and its spectrum is the power spectral density of the shifted waveform.
The device equations contain fitted parameters. In the example, the negative conductance of a cross-coupled transistor pair is modeled as ; and are fitted to the transistors. The noise of the tank resistor is the physical thermal noise; the noise models of real transistors also contain fitted coefficients.
The algorithm
PHASE-NOISE(F, A, B, x₀, T₀, S, offsets)- 1
(x_s, T) ← periodic orbit by shooting Newton with T unknown and a phase condition; P_k ← step Jacobians - 2
M ← P_{S−1} ⋯ P_1 P_0 - 3
v_S ← left eigenvector of M for the eigenvalue 1, scaled so that v_Sᵀ F(x_0) = 1 - 4
for k = S − 1 down to 0: v_k ← P_kᵀ v_{k+1} - 5
c ← (1/S) Σ_{k<S} |Bᵀ v_k|² - 6
for each offset f_m: 𝓛(f_m) ← 10 log₁₀ (f₀² c / (π² f₀⁴ c² + f_m²)), with f₀ = 1/T - 7
return x_s, T, v, c and 𝓛
Line L1 is shooting Newton for an autonomous circuit. The unknowns are the start state and ; the extra equation fixes one state at (the phase condition), and the extra column of the Newton matrix is . The implementation uses steps of the classical Runge-Kutta method and forms the exact Jacobian of each step. A circuit simulator would use the step matrices of its implicit integration instead, or a harmonic balance solution.
Lines L2 to L4 compute the PPV. The monodromy matrix carries a small change of the state at to its change one period later. Its eigenvalue 1 belongs to the direction along the orbit, ; the other eigenvalues of a stable orbit have magnitude below 1. Line L3 is a small eigenvalue problem: the implementation solves the bordered system , , where absorbs the step error by which the eigenvalue of the discrete differs from 1. Line L4 runs the transposed steps backward, which is the discrete adjoint equation, as in adjoint sensitivity analysis. Line L5 averages the projected noise over the period, and line L6 evaluates the Lorentzian.
Example
The Hopf oscillator, by hand. Take with , and noise on both states. The orbit is the circle of radius , traversed at the angular frequency . A radial kick decays and leaves the angle as it was, while a tangential kick of length shifts the angle by for good, a time shift of . So and . For , and , s, and dBc/Hz, because is negligible next to . The implementation with steps gave s and s, a relative error of , and to .
An LC oscillator, measured. A tank of µH and nF with a loss of Ω is driven by the negative conductance , with the fitted values mS and V; the states are the tank voltage and the inductor current, and the only noise is the thermal noise of at 300 K. The phase condition sets the inductor current to zero at . Starting from V and , line L1 converged in 5 Newton iterations with to MHz (the tank resonance is 5.0329 MHz) and a peak of 0.6298 V. The Floquet multipliers of were 1 and 0.6145. The results were:
| quantity | value |
|---|---|
| s | |
| dBc/Hz | |
| dBc/Hz | |
| dBc/Hz | |
| corner of the Lorentzian | Hz |
| largest |
The spectrum falls by 20 dB per decade because every practical offset is far above the corner. With , 200, 400 and 800, was , , and s. For a nearly sinusoidal swing of amplitude at , the voltage component of the PPV is about , which gives the estimate . With the measured first-harmonic amplitude V, the estimate is s, 0.6% below the PPV result; the difference comes from the distortion of the waveform. The analysis took 0.04 s of Python process time on one machine.
Two checks against simulation. First, a kick of V to the voltage or A to the current at a sample , followed by 20 periods without noise, moved the settled orbit by a time shift that agreed with to a relative error between and at four (sample, state) pairs, measured by central differences. Second, Monte Carlo runs of the noisy equation with the stochastic Heun method:
| oscillator | runs | measured |
|---|---|---|
| Hopf, , s, 600 paths, phase from the unwrapped angle | seeds 71, 72, 73 | 0.998, 1.061, 1.039 |
| LC, noise scaled by , 50 steps per period, 40 periods, 400 paths, phase from the last up-crossing | seed 5 | 0.954 |
| LC, the same, 100 steps per period, 30 periods, 300 paths | seeds 6, 7 | 1.039, 1.086 |
The standard error of a sample variance of Gaussian values is of it, 0.06 for 600 paths and 0.07 to 0.08 for 300 to 400, so the runs agree with within their statistics. The noise of the LC runs was scaled up so that the phase spread is visible after 40 periods; scales with it.
Correctness
The proof in proofs/correctness.md shows:
- The PPV exists and is unique. If the eigenvalue 1 of is simple, the left eigenvector with , carried by the adjoint equation, is periodic, and for all .
- The backward recurrence is the discrete adjoint. is the same for all along every solution of the linearized step map, so is the part of a kick at step that survives to the end of the period.
- The linearized phase is a random walk. For , the projection satisfies , so it is Gaussian with plus a bounded periodic term.
- Exact Hopf result. .
- The Lorentzian. If is a Wiener process with variance , the first harmonic has the spectrum in , with total power 1.
The extension from the linearized equation to the nonlinear oscillator is the theorem of Demir, Mehrotra and Roychowdhury and is cited, not proved; the Monte Carlo runs measure it. The error of the discrete PPV is measured.
The tests check, with fixed seeds, that for the Hopf oscillator equals to a relative ; that the PPV of the LC oscillator is periodic and normalized; the kick test at four (sample, state) pairs to a relative ; the sinusoidal estimate to 2%; that falls by 20 dB per decade; that the Lorentzian integrates to 1, by quadrature, to ; and the Hopf (seed 71) and LC (seed 5) Monte Carlo ratios within 0.25 and 0.3 of 1. The whole file takes about 4.5 s of CPU time.
Proof: The perturbation projection vector exists, is computed by the adjoint recurrence, and gives the phase diffusion constantfull
We use the notation of the page. The oscillator is with states, twice continuously differentiable with Jacobian , a constant matrix , and independent white noises with . The noiseless system has a periodic orbit of period with . Put , which has period , and let be the solution of , . The monodromy matrix is . We assume that the orbit is asymptotically stable in the sense of Floquet theory: the eigenvalue 1 of is simple and every other eigenvalue has magnitude less than 1.
The continuous perturbation projection vector
Lemma 1. . In particular , so 1 is an eigenvalue of with right eigenvector .
Proof. Differentiate with respect to : . So solves the variational equation, and the solution with value at is . At , periodicity gives .
Lemma 2. If and , then does not depend on .
Proof. .
Theorem 1 (the PPV). There is exactly one -periodic solution of the adjoint equation with . It satisfies for all , and is the left eigenvector of for the eigenvalue 1.
Proof. Every solution of the adjoint equation is , because . Since the eigenvalue 1 of is simple, its left and right eigenvectors and satisfy (otherwise would be orthogonal to the whole range of and to , which together span when the eigenvalue is simple). Scale so that and put . Then because . The function solves the same adjoint equation, because has period , and it has the value at ; by uniqueness it equals , so has period . By Lemmas 1 and 2, .
For uniqueness, a -periodic adjoint solution has , so and is a multiple of . The normalization fixes the multiple.
The discrete PPV of the implementation
The implementation replaces the flow by steps of a one-step method with step (the classical Runge-Kutta method). Line L1 returns a closed orbit of the map: for and . Put , the exact Jacobian of the step that the implementation forms by differentiating the four stages, and .
Theorem 2 (discrete adjoint). Let be any vector and for (line L4). Then for every sequence with , for every . If , then .
Proof. ; apply this from to . Also .
So is the exact component, measured by , that a small kick at step leaves at the end of the period: this is the discrete form of Lemma 2. The discrete map is not a flow, so 1 is an eigenvalue of only up to the step error, and is not exactly an eigenvector. Line L3 therefore solves the bordered system , , whose solution has when the eigenvalue is exactly 1. The size of , and so the error in and in , is measured on the page, not proved; it falls with the step error of the method.
The phase of the linearized noise is a random walk
Theorem 3. Let solve the linearized noise equation with , where is a standard -dimensional Wiener process. Then is a Gaussian process with mean 0 and
where has period and . The increments of over disjoint intervals are independent.
Proof. is deterministic and continuously differentiable, so the Itô product rule has no correction term: , because . Hence , a Wiener integral of a deterministic function: it is Gaussian with mean 0, its increments over disjoint intervals are independent, and by the Itô isometry with . The function has period and mean , so has period , and on one period it lies between and .
Line L5 computes by the rectangle rule on the samples of one period. For a smooth periodic integrand this rule converges faster than any power of , so its error is far below the error in .
Corollary 1 (the Hopf oscillator). For with , , and , the orbit is , , and .
Proof. In polar form the system is , , so the circle is an orbit of period with . The given has . On the orbit, with argument , and a direct product gives , so . Differentiation gives , the same vector. So solves the adjoint equation, and it is periodic, so it is the PPV by Theorem 1. Then , a constant, which is .
From the phase diffusion to the Lorentzian
Proposition 1. Let be a Wiener process with and . The stationary spectral density of is
and .
Proof. Put . The increment is Gaussian with variance , so the autocorrelation is , which does not depend on . With , the Fourier transform of is at , which is . For the integral, put , so that . Since , the integral is .
Line L6 reports , the density at offset relative to the power of the first harmonic, in dBc/Hz.
What is not proved
- The step from the linearized equation of Theorem 3 to the nonlinear oscillator: that the noisy solution is plus a deviation that stays small, and that the nonlinear phase is asymptotically a Wiener process with the same . This is the main theorem of Demir, Mehrotra and Roychowdhury (2000), and we cite it. The Monte Carlo runs on the page measure it for two oscillators; they do not prove it.
- That line L1 converges: it is Newton's method on the shooting equations with the period as an unknown, and its convergence near a stable orbit with a nonsingular bordered matrix follows from the local theorem for Newton's method for systems; the starting point is a matter of practice.
- The size of in line L3 and the error of the discrete PPV, which are measured.
- The near-sinusoidal estimate for the LC oscillator, which is an approximation and is compared, not proved.
Complexity
Line L1 costs shooting iterations of steps, each with work for the step Jacobian and its product into the monodromy matrix, so time. The PPV costs one more product of matrices, , one solve, and transposed products of each. Line L5 costs . The step Jacobians take space. For large circuits, simulators keep the sparse factors of the steps instead of dense , find the left eigenvector with an iterative solver, and apply as one transposed sparse solve per step.
Properties
- One number per oscillator. All white noise sources reduce to the scalar , and , the jitter and the spectra of all harmonics follow from it.
- Finite power. Unlike a linear time-invariant noise analysis, which gives a density that grows without bound as , the Lorentzian has a finite peak and total power 1: phase noise moves power, it does not add it.
- Nonlinear. The orbit, the PPV and the noise all come from the large-signal waveform, so amplitude limiting and the shape of the waveform are included.
- Cyclostationary noise. A noise source whose strength depends on the waveform enters as a time-varying column of in line L5 with no other change.
- Exact for the model. For a given orbit and PPV the result is exact; the error comes from the discretization of the orbit, which is small, as the table over shows.
Variants and improvements
- Frequency-domain PPV. Demir, Mehrotra and Roychowdhury also compute from the harmonic balance Jacobian, as the null vector of its transpose.
- Implicit integration. With the step matrices of a circuit simulator, as in shooting, and line L4 uses the transposed factors.
- Linear time-varying model. Hajimiri and Lee (1998) model phase noise with an impulse sensitivity function, the response of the phase to a charge kick at each instant, which plays the role of the PPV. Their model is linear in the phase, so it gives the region but not the finite Lorentzian peak.
- Colored noise. Flicker noise needs a separate treatment, because the phase is no longer a Wiener process; the white-noise result of this page covers the region.
- Injection locking and coupled oscillators. The same PPV gives the phase response to a small periodic input, which models locking range and oscillator coupling.
When to use it
Use the PPV method for the phase noise and jitter of free-running oscillators: LC and ring oscillators, voltage-controlled oscillators in phase-locked loops, crystal oscillators and relaxation oscillators. It needs the steady-state orbit, so run it after shooting or harmonic balance. For driven circuits with a fixed period, such as mixers, use periodic small-signal noise analysis; for small linear networks, use circuit noise analysis.
Pitfalls
- Linear analysis around the orbit. An ordinary linear noise analysis linearized at the periodic solution misses the phase diffusion and predicts a density that diverges at the carrier. The phase direction must be separated, as the PPV does.
- Euler-Maruyama in a Monte Carlo check. For the Hopf oscillator with , the Euler-Maruyama step map moves the orbit to the radius , because each step adds the factor to the squared radius. Five seeds gave measured ratios between 0.82 and 0.94 instead of 1, near the predicted . For the LC oscillator with 100 steps per period, the amplitude grew from 0.63 to 1.05 V and the ratio was 0.47. Use the stochastic Heun method or a small step, and compare the amplitude with the deterministic orbit.
- Phase measured by crossings. A crossing time mixes the phase with the bounded orbital deviation. Use a crossing late in the run, so that the diffusion term dominates.
- Weakly damped orbits. If the second Floquet multiplier is close to 1, the amplitude recovers slowly, the kick test needs many periods, and the linear analysis holds only for very small noise.
- Fitted parameters. The result depends on the fitted transistor parameters through the waveform, and on the fitted coefficients of the device noise models. The tanh law of the example is a model of the transistor pair, not of a real process.
- Units. The two-sided density and the one-sided density differ by a factor of 2 in ; the formula for assumes unit two-sided white noise in .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-noise-analysis/. The authors are listed in prov/Y2MTGG.jsonl.
"""Oscillator phase noise with the perturbation projection vector (PPV).
The oscillator is a state equation dx/dt = F(x) + B xi(t), where xi is a
vector of independent white noises with unit two-sided spectral density
(E xi(t) xi(s)^T = I delta(t - s)). A circuit with a nonsingular capacitance
matrix C reaches this form as dx/dt = -C^-1 f(x) plus the noise currents
scaled by C^-1.
The noiseless oscillator has a stable periodic orbit x_s(t) of period T. The
PPV v(t) is the periodic solution of the adjoint equation dv/dt = -A(t)^T v
with v(t)^T dx_s/dt = 1. Demir, Mehrotra and Roychowdhury showed that noise
makes the phase drift as a random walk, x(t) ~ x_s(t + alpha(t)), with
Var alpha(t) ~ c t and c = (1/T) int_0^T v^T B B^T v dt.
"""
import math
import sim3dense
BOLTZMANN = 1.380649e-23
class NoConvergence(RuntimeError):
pass
class Oscillator:
"""dx/dt = F(x) + B xi with the Jacobian A(x) = dF/dx."""
def __init__(self, n, F, A, B):
self.n, self.F, self.A, self.B = n, F, A, B
def lc_oscillator(l, c, r, gm, v0, temperature=300.0, noise_scale=1.0):
"""LC tank with loss r and a negative conductance i = gm v0 tanh(v / v0).
States (v, i_L). The tanh law models a cross-coupled differential pair;
its gm and v0 are fitted to the transistor pair. The noise is the thermal
current of r, two-sided density 2kT/r, times noise_scale.
"""
def F(x):
v, i = x
return [(-v / r - i + gm * v0 * math.tanh(v / v0)) / c, v / l]
def A(x):
s = 1.0 / math.cosh(x[0] / v0)
return [[(-1.0 / r + gm * s * s) / c, -1.0 / c], [1.0 / l, 0.0]]
amp = noise_scale * math.sqrt(2 * BOLTZMANN * temperature / r) / c
return Oscillator(2, F, A, [[amp], [0.0]])
def hopf_oscillator(mu, omega, sigma):
"""Hopf normal form with white noise sigma on both states; the orbit has radius sqrt(mu)."""
def F(x):
a, b = x
r2 = a * a + b * b
return [mu * a - omega * b - r2 * a, omega * a + mu * b - r2 * b]
def A(x):
a, b = x
r2 = a * a + b * b
return [[mu - r2 - 2 * a * a, -omega - 2 * a * b], [omega - 2 * a * b, mu - r2 - 2 * b * b]]
return Oscillator(2, F, A, [[sigma, 0.0], [0.0, sigma]])
def _add(x, y, s):
return [a + s * b for a, b in zip(x, y)]
def rk4_step(osc, x, h):
"""One classical Runge-Kutta step and its exact Jacobian d x_new / d x."""
n = osc.n
I = sim3dense.identity(n, 1.0)
k1, A1 = osc.F(x), osc.A(x)
d1 = A1
x2 = _add(x, k1, h / 2)
k2, A2 = osc.F(x2), osc.A(x2)
d2 = sim3dense.matmul(A2, [[I[i][j] + h / 2 * d1[i][j] for j in range(n)] for i in range(n)])
x3 = _add(x, k2, h / 2)
k3, A3 = osc.F(x3), osc.A(x3)
d3 = sim3dense.matmul(A3, [[I[i][j] + h / 2 * d2[i][j] for j in range(n)] for i in range(n)])
x4 = _add(x, k3, h)
k4, A4 = osc.F(x4), osc.A(x4)
d4 = sim3dense.matmul(A4, [[I[i][j] + h * d3[i][j] for j in range(n)] for i in range(n)])
xn = [x[i] + h / 6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(n)]
P = [[I[i][j] + h / 6 * (d1[i][j] + 2 * d2[i][j] + 2 * d3[i][j] + d4[i][j]) for j in range(n)] for i in range(n)]
return xn, P
def orbit(osc, x0, T, S):
"""S RK4 steps over [0, T]; returns the states x_0..x_S and the step Jacobians."""
h = T / S
xs, mats = [list(x0)], []
for _ in range(S):
x, P = rk4_step(osc, xs[-1], h)
xs.append(x)
mats.append(P)
return xs, mats
def limit_cycle(osc, x0, T0, S, p=1, value=0.0, tol=1e-12, max_iter=50):
"""Shooting Newton for an autonomous orbit with the phase condition x_0[p] = value.
The unknowns are x_0 and T. The derivative of x_S with respect to T is
taken as F(x_S), the derivative of the exact flow; the residual is exact,
so the iteration converges to the orbit of the discrete map.
Returns (x_0, T, states, step Jacobians, iterations).
"""
n = osc.n
x, T = list(x0), T0
x[p] = value
for it in range(1, max_iter + 1):
xs, mats = orbit(osc, x, T, S)
M = sim3dense.identity(n, 1.0)
for P in mats:
M = sim3dense.matmul(P, M)
fT = osc.F(xs[-1])
J = [[M[i][j] - (i == j) for j in range(n)] + [fT[i]] for i in range(n)]
J.append([1.0 if j == p else 0.0 for j in range(n)] + [0.0])
r = [xs[-1][i] - x[i] for i in range(n)] + [x[p] - value]
d = sim3dense.solve(J, [-v for v in r])
x = [x[i] + d[i] for i in range(n)]
T += d[n]
if max(abs(v) for v in d[:n]) <= tol * (1 + max(abs(v) for v in x)) and abs(d[n]) <= tol * T:
xs, mats = orbit(osc, x, T, S)
return x, T, xs, mats, it
raise NoConvergence("limit cycle")
def ppv(osc, xs, mats):
"""The PPV at x_0..x_S of the orbit, by the discrete adjoint recurrence."""
n = osc.n
M = sim3dense.identity(n, 1.0)
for P in mats: # @line L2
M = sim3dense.matmul(P, M)
f0 = osc.F(xs[0])
# bordered system: (M^T - I) v + mu f0 = 0, f0^T v = 1 (mu is 0 up to the step error)
K = [[M[j][i] - (i == j) for j in range(n)] + [f0[i]] for i in range(n)]
K.append(list(f0) + [0.0])
v0 = sim3dense.solve(K, [0.0] * n + [1.0])[:n] # @line L3
vs = [None] * len(xs)
vs[-1] = v0
for k in range(len(mats) - 1, -1, -1): # @line L4
P = mats[k]
vs[k] = [sum(P[a][b] * vs[k + 1][a] for a in range(n)) for b in range(n)]
return vs
def diffusion_constant(osc, vs):
"""c = (1/T) int v^T B B^T v dt, by the rectangle rule on the periodic samples."""
S = len(vs) - 1
total = 0.0
for v in vs[:S]:
w = [sum(v[a] * osc.B[a][j] for a in range(osc.n)) for j in range(len(osc.B[0]))]
total += sum(t * t for t in w)
return total / S
def ssb_phase_noise(c, f0, fm):
"""Single-sideband phase noise L(fm) in dBc/Hz from the Lorentzian of the first harmonic."""
return 10 * math.log10(f0 * f0 * c / (math.pi ** 2 * f0 ** 4 * c * c + fm * fm))
def phase_noise(osc, x0, T0, S, offsets, p=1, value=0.0):
"""PPV phase noise analysis.
Returns a dict with the orbit (x0, T, states), the PPV samples v, the
diffusion constant c (in s^2/s) and L(fm) in dBc/Hz for each offset fm.
"""
x, T, xs, mats, _ = limit_cycle(osc, x0, T0, S, p, value) # @line L1
vs = ppv(osc, xs, mats)
c = diffusion_constant(osc, vs) # @line L5
L = [ssb_phase_noise(c, 1 / T, fm) for fm in offsets] # @line L6
return {"x0": x, "T": T, "states": xs, "v": vs, "c": c, "L": L} # @line L7
def stochastic_heun(osc, x0, h, steps, rng):
"""One sample path of dx = F dt + B dW by the stochastic Heun method.
The noise is additive, so the method has strong order 1 and the drift
error of a deterministic second-order method; Euler-Maruyama would grow
the orbit of a fast oscillator and bias the phase variance.
Returns the states at every step.
"""
n, p = osc.n, len(osc.B[0])
sq = math.sqrt(h)
x = list(x0)
out = [list(x)]
for _ in range(steps):
dw = [rng.gauss(0.0, sq) for _ in range(p)]
noise = [sum(osc.B[i][j] * dw[j] for j in range(p)) for i in range(n)]
f = osc.F(x)
y = [x[i] + h * f[i] + noise[i] for i in range(n)]
g = osc.F(y)
x = [x[i] + h / 2 * (f[i] + g[i]) + noise[i] for i in range(n)]
out.append(x)
return out
sim3dense.py 70 lines
# SPDX-License-Identifier: MIT
# Shared helper of the sim3 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for Fraction, float or complex entries.
The circuit pages of group sim3 use this module as a reference solver and for
the small dense systems inside their tests. It holds no sparse method and no
circuit method. Matrices are lists of rows.
"""
from fractions import Fraction
class SingularMatrixError(ValueError):
"""The matrix has no inverse (a zero pivot in exact arithmetic)."""
def _exact(x):
return Fraction(x) if isinstance(x, int) else x
def solve(a, b, tol=0.0):
"""Solve a x = b by Gaussian elimination with partial pivoting.
With Fraction entries the result is exact. b is a vector or a matrix
(a list of rows); the result has the same shape.
"""
n = len(a)
m = [[_exact(x) for x in row] for row in a]
vec = not (b and isinstance(b[0], list))
rhs = [[_exact(x)] for x in b] if vec else [[_exact(x) for x in row] for row in b]
for k in range(n):
p = max(range(k, n), key=lambda i: abs(m[i][k]))
if abs(m[p][k]) <= tol:
raise SingularMatrixError(f"zero pivot in column {k}")
m[k], m[p] = m[p], m[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
for i in range(k + 1, n):
if m[i][k] != 0:
f = m[i][k] / m[k][k]
for j in range(k, n):
m[i][j] -= f * m[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
x = [[0] * len(rhs[0]) for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(len(rhs[0])):
s = rhs[i][j] - sum(m[i][k] * x[k][j] for k in range(i + 1, n))
x[i][j] = s / m[i][i]
return [r[0] for r in x] if vec else x
def transpose(a):
return [list(r) for r in zip(*a)]
def matvec(a, x):
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def matmul(a, b):
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def identity(n, one=1):
return [[one if i == j else 0 * one for j in range(n)] for i in range(n)]
def inverse(a):
return solve(a, identity(len(a)))
test_phase_noise_analysis.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-noise-analysis/. The authors are listed in prov/Y2MTGG.jsonl.
import math
import random
from phase_noise_analysis import (
BOLTZMANN,
Oscillator,
hopf_oscillator,
lc_oscillator,
orbit,
phase_noise,
ssb_phase_noise,
stochastic_heun,
)
LC = (1e-6, 1e-9, 200.0)
def lc_case(noise_scale=1.0):
l, c, r = LC
osc = lc_oscillator(l, c, r, 25e-3, 0.1, noise_scale=noise_scale)
return osc, phase_noise(osc, [0.3, 0.0], 2 * math.pi * math.sqrt(l * c), 400, [1e5, 1e6])
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def test_hopf_diffusion_constant_is_exact():
mu, omega, sigma = 1.0, 2 * math.pi, 0.1
osc = hopf_oscillator(mu, omega, sigma)
res = phase_noise(osc, [1.0, 0.0], 1.0, 200, [1.0])
assert abs(res["T"] - 2 * math.pi / omega) < 1e-7
# the only error is the RK4 error of the orbit radius (measured 1.7e-8 relative)
assert abs(res["c"] / (sigma ** 2 / (mu * omega ** 2)) - 1) < 1e-7
for v, x in zip(res["v"], res["states"]):
assert abs(dot(v, osc.F(x)) - 1) < 1e-12
def test_ppv_is_periodic_and_normalized_on_lc():
osc, res = lc_case()
v = res["v"]
assert max(abs(a - b) for a, b in zip(v[0], v[-1])) < 1e-6 * max(abs(a) for a in v[0])
for vk, x in zip(v, res["states"]):
assert abs(dot(vk, osc.F(x)) - 1) < 1e-6
def test_ppv_matches_impulse_response_on_lc():
# A small kick d at x_s(t_k) shifts the phase of the settled orbit by v_k^T d.
osc, res = lc_case()
xs, v, T = res["states"], res["v"], res["T"]
S = len(xs) - 1
for k in (S // 4, S // 3):
f = osc.F(xs[k])
for j, eps in ((0, 1e-6), (1, 1e-9)):
ends = []
for s in (eps, -eps):
x = list(xs[k])
x[j] += s
ends.append(orbit(osc, x, 20 * T, 20 * S)[0][-1])
d = [(a - b) / (2 * eps) for a, b in zip(*ends)]
shift = dot(d, f) / dot(f, f)
assert abs(shift - v[k][j]) < 1e-3 * abs(v[k][j])
def test_lc_diffusion_matches_sinusoidal_estimate():
l, c, r = LC
osc, res = lc_case()
xs = res["states"]
S = len(xs) - 1
re = sum(xs[k][0] * math.cos(2 * math.pi * k / S) for k in range(S)) * 2 / S
im = sum(xs[k][0] * math.sin(2 * math.pi * k / S) for k in range(S)) * 2 / S
w0 = 2 * math.pi / res["T"]
estimate = BOLTZMANN * 300 / (r * c * c * (re * re + im * im) * w0 * w0)
assert abs(res["c"] / estimate - 1) < 0.02
assert abs(res["L"][1] - res["L"][0] + 20) < 1e-3
def test_lorentzian_has_unit_power():
c, f0 = 2e-4, 1.0
total, n = 0.0, 200000
for i in range(n):
# f = a tan(u) maps (-pi/2, pi/2) onto the real line
u = -math.pi / 2 + (i + 0.5) * math.pi / n
a = math.pi * f0 * f0 * c
f = a * math.tan(u)
total += 10 ** (ssb_phase_noise(c, f0, f) / 10) * a / math.cos(u) ** 2 * math.pi / n
assert abs(total - 1) < 1e-9
def phase_spread(values):
m = sum(values) / len(values)
return sum((a - m) ** 2 for a in values) / (len(values) - 1)
def test_hopf_monte_carlo_phase_variance():
osc = hopf_oscillator(1.0, 2 * math.pi, 0.1)
c = phase_noise(osc, [1.0, 0.0], 1.0, 200, [1.0])["c"]
rng = random.Random(71)
h, steps, paths = 0.02, 500, 600
shifts = []
for _ in range(paths):
turn, prev = 0.0, 0.0
for x in stochastic_heun(osc, [1.0, 0.0], h, steps, rng)[1:]:
a = math.atan2(x[1], x[0])
turn += (a - prev + math.pi) % (2 * math.pi) - math.pi
prev = a
shifts.append((turn - 2 * math.pi * steps * h) / (2 * math.pi))
ratio = phase_spread(shifts) / (c * steps * h)
assert abs(ratio - 1) < 0.25 # 600 paths: standard error about 0.06
def up_crossings(path, h):
out = []
for k in range(len(path) - 1):
a, b = path[k][0], path[k + 1][0]
if a < 0 <= b:
out.append((k + a / (a - b)) * h)
return out
def test_lc_monte_carlo_timing_jitter():
osc, res = lc_case(noise_scale=1.3e4)
T, c, x0 = res["T"], res["c"], res["x0"]
S, periods, paths = 50, 40, 400
h = T / S
quiet = Oscillator(2, osc.F, osc.A, [[0.0], [0.0]])
nominal = up_crossings(stochastic_heun(quiet, x0, h, S * periods, random.Random(0)), h)
rng = random.Random(5)
shifts = []
for _ in range(paths):
noisy = up_crossings(stochastic_heun(osc, x0, h, S * periods, rng), h)
assert len(noisy) == len(nominal)
shifts.append(nominal[-1] - noisy[-1])
ratio = phase_spread(shifts) / (c * nominal[-1])
assert abs(ratio - 1) < 0.3 # 400 paths: standard error about 0.07
History
Earlier analyses of oscillator phase noise used linear time-invariant models of the oscillator. Hajimiri and Lee (1998) introduced a linear time-varying model with an impulse sensitivity function. Demir, Mehrotra and Roychowdhury (2000) gave a nonlinear theory: they separated the noisy solution into a phase shift and an orbital deviation, showed that the phase becomes a Wiener process with the diffusion constant computed from the Floquet left eigenvector, which they called the perturbation projection vector, and derived the Lorentzian spectrum. They also gave time-domain and harmonic balance methods to compute , which circuit simulators adopted.
References
- Alper Demir, Amit Mehrotra and Jaijeet Roychowdhury, Phase noise in oscillators, a unifying theory and numerical methods for characterization, IEEE Transactions on Circuits and Systems I, Fundamental Theory and Applications 47(5), 655 to 674, 2000, the split of the noisy solution into a phase shift and an orbital deviation, the perturbation projection vector as the Floquet left eigenvector, the diffusion constant c, the Lorentzian spectrum of the harmonics, and the numerical methods in the time and frequency domains
- Ali Hajimiri and Thomas H. Lee, A general theory of phase noise in electrical oscillators, IEEE Journal of Solid-State Circuits, 1998, the linear time-varying model of phase noise with the impulse sensitivity function
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Y2MTGG Edit this page History Report an error Markdown