driven_harmonic_oscillator.py ダウンロード/コピー
driven_harmonic_oscillator.py をダウンロード
driven_harmonic_oscillator.py
driven_harmonic_oscillator.py
1"""
2概要:
3 交流電場で駆動される1次元調和ポテンシャル中の電子を可視化します。
4詳細説明:
5 計算には無次元化された振動子単位を使用します。
6 xi = x / sqrt(hbar/(m omega0)), tau = omega0 t,
7 H/(hbar omega0) = -1/2 d^2/dxi^2 + 1/2 xi^2 + f0 xi cos(Omega tau)
8 ここで f0 = e E0 sqrt(hbar/(m omega0))/(hbar omega0) です。
9 符号は電子に対応し、そのポテンシャルエネルギーは +e E(t) x となります。
10 波動関数は2次のスプリットオペレータ法を用いて伝播されます。
11 減衰は現象論的な重心摩擦 q'' + gamma q' + q = -f(t) として扱われます。
12 数値モードでは一様な運動量キックを適用し、解析モードでは定数パラメータステップごとに重心を厳密に伝播させ、ガウシアン波束を使用します。
13 これは熱緩和や一般的な開放量子系モデルではありません。
14 波動関数の垂直オフセットの1と2は表示用のベースラインであり、エネルギーではありません。
15"""
16
17# Labeled version: numerical and analytic animation modes.
18
19import argparse
20
21import numpy as np
22from scipy.linalg import expm
23import matplotlib.pyplot as plt
24from matplotlib.animation import FuncAnimation
25from matplotlib.widgets import Button, RadioButtons, Slider
26
27
28class DrivenOscillator:
29 """
30 概要:
31 駆動される1次元調和振動子を数値的に解くためのクラスです。
32 詳細説明:
33 FFTベースのスプリットオペレータ法を用いて波動関数の時間発展を計算します。
34 引数:
35 :param ngrid: 空間グリッドの点数
36 :type ngrid: int
37 :param xmax: 空間グリッドの最大値
38 :type xmax: float
39 :param dt: 時間ステップ
40 :type dt: float
41 :param f0: 電場振幅
42 :type f0: float
43 :param omega: 駆動角振動数
44 :type omega: float
45 :param initial_n: 初期状態の調和振動子量子数
46 :type initial_n: int
47 """
48 def __init__(self, ngrid=1024, xmax=9.0, dt=0.004, f0=0.20, omega=1.0,
49 initial_n=0):
50 self.x = np.linspace(-xmax, xmax, ngrid, endpoint=False)
51 self.dx = self.x[1] - self.x[0]
52 self.k = 2.0 * np.pi * np.fft.fftfreq(ngrid, d=self.dx)
53 self.dt = dt
54 self.f0 = f0
55 self.omega = omega
56 self.tau = 0.0
57 self.gamma = 0.0
58
59 # Harmonic-oscillator eigenfunctions generated by the recurrence.
60 psi = np.pi ** (-0.25) * np.exp(-self.x**2 / 2.0)
61 if initial_n > 0:
62 psi1 = np.sqrt(2.0) * self.x * psi
63 for n in range(1, initial_n):
64 psi, psi1 = psi1, (
65 np.sqrt(2.0 / (n + 1.0)) * self.x * psi1
66 - np.sqrt(n / (n + 1.0)) * psi
67 )
68 psi = psi1
69 self.psi = psi.astype(complex)
70 self._normalize()
71 self.kinetic_half = np.exp(-1j * (self.k**2 / 2.0) * dt)
72
73 def _normalize(self):
74 """
75 概要:
76 波動関数のノルムを1に正規化します。
77 """
78 self.psi /= np.sqrt(np.sum(np.abs(self.psi) ** 2) * self.dx)
79
80 def potential(self, tau):
81 """
82 概要:
83 指定された時刻におけるポテンシャルエネルギーを計算します。
84 引数:
85 :param tau: 無次元化された時間
86 :type tau: float
87 戻り値:
88 :returns: ポテンシャルの配列
89 :rtype: numpy.ndarray
90 """
91 return 0.5 * self.x**2 + self.f0 * self.x * np.cos(self.omega * tau)
92
93 def damp(self, duration):
94 """
95 概要:
96 波束の形状を保ちながら、重心の運動量に対して減衰を適用します。
97 引数:
98 :param duration: 減衰を適用する時間
99 :type duration: float
100 """
101 # Uniform momentum kick damps only the centroid, preserving packet shape.
102 derivative = np.fft.ifft(1j * self.k * np.fft.fft(self.psi))
103 momentum = float(np.real(np.sum(self.psi.conj() * (-1j * derivative)) * self.dx))
104 delta = momentum * np.expm1(-self.gamma * duration)
105 self.psi *= np.exp(1j * delta * self.x)
106
107 def step(self, nsteps=1):
108 """
109 概要:
110 指定されたステップ数だけ波動関数を時間発展させます。
111 詳細説明:
112 各ステップの途中でポテンシャルを評価するスプリットオペレータ法を使用します。
113 引数:
114 :param nsteps: 進めるステップ数
115 :type nsteps: int
116 """
117 for _ in range(nsteps):
118 if self.gamma:
119 self.damp(self.dt / 2)
120 mid = self.tau + 0.5 * self.dt
121 phase_v = np.exp(-0.5j * self.potential(mid) * self.dt)
122 self.psi *= phase_v
123 self.psi = np.fft.ifft(self.kinetic_half * np.fft.fft(self.psi))
124 self.psi *= phase_v
125 if self.gamma:
126 self.damp(self.dt / 2)
127 self.tau += self.dt
128 self._normalize() # suppress accumulated FFT round-off error
129
130 def expectation_x(self):
131 """
132 概要:
133 位置xの期待値を計算します。
134 戻り値:
135 :returns: 位置の期待値
136 :rtype: float
137 """
138 return float(np.sum(self.x * np.abs(self.psi) ** 2) * self.dx)
139
140
141class AnalyticDrivenOscillator:
142 """
143 概要:
144 初期基底状態の振動子に対するコヒーレント状態の厳密解を提供するクラスです。
145 詳細説明:
146 電場により中心がq(t)だけシフトします。q(t)は q''+q=-f0 cos(Omega t) の解です。
147 減衰は現象論的な重心摩擦であり、バスのマスター方程式ではありません。
148 表示されるn=0とn=1の曲線は、このコヒーレント状態の最初の2つの定常基底項であり、その和は一般に完全な状態とはなりません。
149 引数:
150 :param x: 空間グリッドの配列
151 :type x: numpy.ndarray
152 :param dt: 時間ステップ
153 :type dt: float
154 :param f0: 電場振幅
155 :type f0: float
156 :param omega: 駆動角振動数
157 :type omega: float
158 """
159 def __init__(self, x, dt=0.004, f0=0.20, omega=1.0):
160 self.x, self.dt, self.f0, self.omega = x, dt, f0, omega
161 self.dx = x[1] - x[0]
162 self.tau = 0.0
163 self.gamma = 0.0
164 self.q = self.p = 0.0
165 self._key = None
166 self.phi0 = np.pi ** (-0.25) * np.exp(-x**2 / 2.0)
167 self.phi1 = np.sqrt(2.0) * x * self.phi0
168
169 def potential(self, tau):
170 """
171 概要:
172 指定された時刻におけるポテンシャルエネルギーを計算します。
173 引数:
174 :param tau: 無次元化された時間
175 :type tau: float
176 戻り値:
177 :returns: ポテンシャルの配列
178 :rtype: numpy.ndarray
179 """
180 return 0.5 * self.x**2 + self.f0 * self.x * np.cos(self.omega * tau)
181
182 def qp(self):
183 """
184 概要:
185 現在位置と運動量を返します。
186 戻り値:
187 :returns: 位置と運動量のタプル
188 :rtype: tuple
189 """
190 return self.q, self.p
191
192 def wavefunction(self):
193 """
194 概要:
195 現在の波動関数を計算します。
196 戻り値:
197 :returns: 波動関数の配列
198 :rtype: numpy.ndarray
199 """
200 q, p = self.qp()
201 # An overall phase is immaterial for density and omitted deliberately.
202 return np.exp(1j * p * (self.x - q / 2.0)) * np.pi**(-0.25) * np.exp(-(self.x-q)**2 / 2.0)
203
204 def components_01(self):
205 """
206 概要:
207 基底状態と第1励起状態の成分を計算します。
208 戻り値:
209 :returns: 状態0の波、状態1の波、状態0の係数、状態1の係数のタプル
210 :rtype: tuple
211 """
212 q, p = self.qp()
213 alpha = (q + 1j * p) / np.sqrt(2.0)
214 c0 = np.exp(-0.5 * abs(alpha)**2)
215 c1 = alpha * c0
216 # Same phase convention as wavefunction(); c_n already includes motion.
217 psi0 = c0 * self.phi0
218 psi1 = c1 * self.phi1
219 return psi0, psi1, c0, c1
220
221 def step(self, nsteps=1):
222 """
223 概要:
224 指定されたステップ数だけ状態を時間発展させます。
225 引数:
226 :param nsteps: 進めるステップ数
227 :type nsteps: int
228 """
229 duration = nsteps * self.dt
230 key = (self.f0, self.omega, self.gamma, duration)
231 if key != self._key:
232 matrix = np.array([[0, 1, 0, 0], [-1, -self.gamma, -self.f0, 0],
233 [0, 0, 0, -self.omega], [0, 0, self.omega, 0]])
234 self._propagator = expm(matrix * duration)
235 self._key = key
236 state = self._propagator @ [self.q, self.p, np.cos(self.omega*self.tau),
237 np.sin(self.omega*self.tau)]
238 self.q, self.p = state[:2]
239 self.tau += duration
240
241 def expectation_x(self):
242 """
243 概要:
244 位置の期待値を返します。
245 戻り値:
246 :returns: 位置の期待値
247 :rtype: float
248 """
249 return self.qp()[0]
250
251
252def main():
253 """
254 概要:
255 コマンドライン引数を解析し、駆動調和振動子のシミュレーションとアニメーションを実行します。
256 """
257 parser = argparse.ArgumentParser(description=__doc__)
258 parser.add_argument("--field", type=float, default=0.20,
259 help="dimensionless field amplitude f0 (default: 0.20)")
260 parser.add_argument("--omega", type=float, default=1.0,
261 help="drive angular frequency Omega/omega0 (default: 1.0)")
262 parser.add_argument("--state", type=int, default=0,
263 help="initial harmonic-oscillator quantum number (default: 0)")
264 parser.add_argument("--mode", choices=("numerical", "analytic"), default="numerical",
265 help="propagation mode (analytic is exact for initial n=0)")
266 parser.add_argument("--damping", type=float, default=0.0,
267 help="centroid damping gamma/omega0 (default: 0)")
268 args = parser.parse_args()
269 if not 0 <= args.damping <= 2:
270 parser.error("--damping must be between 0 and 2")
271
272 numerical = DrivenOscillator(f0=args.field, omega=args.omega, initial_n=args.state)
273 analytic = AnalyticDrivenOscillator(numerical.x, f0=args.field, omega=args.omega)
274 numerical.gamma = analytic.gamma = args.damping
275 sim = numerical if args.mode == "numerical" else analytic
276 initial_numerical_psi = numerical.psi.copy()
277 steps_per_frame = 8
278 density_scale = 3.0
279 running = True
280
281 fig, ax = plt.subplots(figsize=(12, 8))
282 fig.subplots_adjust(bottom=0.38)
283 ax.set(xlim=(-7, 7), ylim=(-0.8, 5.3), xlabel=r"$\xi=x/x_0$",
284 ylabel=r"energy / probability density",
285 title="Driven 1D harmonic oscillator (dimensionless units)")
286 ax.grid(alpha=0.25)
287 fixed_potential, = ax.plot(sim.x, 0.5 * sim.x**2, color="gray", lw=0.8,
288 label=r"fixed $V_0(\xi)=\xi^2/2$")
289 potential_line, = ax.plot(sim.x, sim.potential(0), color="black", lw=0.7,
290 label=r"total $V(\xi,\tau)$")
291 initial_psi = numerical.psi if sim is numerical else analytic.wavefunction()
292 density_line, = ax.plot(sim.x, density_scale * np.abs(initial_psi)**2,
293 color="tab:blue", lw=2.0, label=r"$3|\psi|^2$")
294 real_line, = ax.plot(sim.x, 1.0 + np.real(initial_psi), color="tab:orange", alpha=0.8,
295 label=r"$1+\mathrm{Re}\,\psi$")
296 imag_line, = ax.plot(sim.x, 1.0 + np.imag(initial_psi), color="tab:green", alpha=0.8,
297 label=r"$1+\mathrm{Im}\,\psi$")
298 component0_line, = ax.plot([], [], color="tab:purple", lw=1.6, ls="--",
299 label=r"$2+\mathrm{Re}\,\psi_{n=0}$")
300 component1_line, = ax.plot([], [], color="tab:brown", lw=1.6, ls="--",
301 label=r"$2+\mathrm{Re}\,\psi_{n=1}$")
302 xmean_line = ax.axvline(sim.expectation_x(), color="tab:red", ls="--",
303 label=r"$\langle\xi\rangle$")
304 ax.axvline(0, color="0.25", lw=1.5, zorder=2)
305 ax.axhline(1, color="0.7", lw=0.6, ls=":")
306 ax.axhline(2, color="0.7", lw=0.6, ls=":")
307 minimum_line = ax.axvline(-sim.f0, color="tab:cyan", ls="-.", lw=1.5,
308 label=r"potential minimum $\xi_{\min}$")
309 minimum_dot, = ax.plot([], [], "o", color="tab:cyan", ms=6)
310 info = ax.text(0.02, 0.96, "", transform=ax.transAxes, va="top",
311 bbox={"facecolor": "white", "alpha": 0.85, "edgecolor": "none"})
312 ax.legend(loc="upper right")
313
314 # Labels are separate figure text so they remain visible beside the mode box.
315 fig.text(0.17, 0.245, r"External field amplitude: $f_0=eE_0x_0/(\hbar\omega_0)$",
316 fontsize=10)
317 fig.text(0.17, 0.165, r"Photon energy / level spacing: $E_\gamma/(\hbar\omega_0)=\Omega/\omega_0$",
318 fontsize=10)
319 ax_field = fig.add_axes((0.25, 0.210, 0.55, 0.03))
320 ax_omega = fig.add_axes((0.25, 0.130, 0.55, 0.03))
321 field_slider = Slider(ax_field, "", 0.0, 1.0, valinit=sim.f0, valstep=0.01)
322 omega_slider = Slider(ax_omega, "", 0.1, 2.0,
323 valinit=sim.omega, valstep=0.01)
324 fig.text(0.17, 0.085, r"Centroid damping: $\gamma/\omega_0$", fontsize=10)
325 ax_damping = fig.add_axes((0.25, 0.050, 0.40, 0.025))
326 damping_slider = Slider(ax_damping, "", 0.0, 2.0,
327 valinit=args.damping, valstep=0.01)
328 button_ax = fig.add_axes((0.72, 0.035, 0.11, 0.06))
329 button = Button(button_ax, "Pause")
330 restart_ax = fig.add_axes((0.84, 0.035, 0.11, 0.06))
331 restart_button = Button(restart_ax, "Restart")
332 mode_ax = fig.add_axes((0.015, 0.115, 0.13, 0.115))
333 mode_choice = RadioButtons(mode_ax, ("numerical", "analytic"), active=(args.mode == "analytic"))
334
335 def on_slider(_):
336 for engine in (numerical, analytic):
337 engine.f0 = field_slider.val
338 engine.omega = omega_slider.val
339 engine.gamma = damping_slider.val
340
341 def on_mode(label):
342 nonlocal sim
343 old = sim
344 sim = numerical if label == "numerical" else analytic
345 if sim is old:
346 return
347 if sim is analytic:
348 analytic.q = numerical.expectation_x()
349 derivative = np.fft.ifft(1j * numerical.k * np.fft.fft(numerical.psi))
350 analytic.p = float(np.real(np.sum(numerical.psi.conj() * (-1j*derivative))*numerical.dx))
351 else:
352 numerical.psi = analytic.wavefunction().copy()
353 numerical._normalize()
354 sim.tau = old.tau
355
356 def toggle(_):
357 nonlocal running
358 running = not running
359 button.label.set_text("Pause" if running else "Resume")
360
361 def restart(_):
362 nonlocal running
363 numerical.tau = analytic.tau = 0.0
364 numerical.psi = initial_numerical_psi.copy()
365 analytic.q = analytic.p = 0.0
366 running = True
367 button.label.set_text("Pause")
368 draw_frame()
369 fig.canvas.draw_idle()
370
371 restart_button.on_clicked(restart)
372 damping_slider.on_changed(on_slider)
373 field_slider.on_changed(on_slider)
374 omega_slider.on_changed(on_slider)
375 button.on_clicked(toggle)
376 mode_choice.on_clicked(on_mode)
377
378 def draw_frame():
379 psi = sim.psi if sim is numerical else sim.wavefunction()
380 rho = np.abs(psi) ** 2
381 potential_line.set_ydata(sim.potential(sim.tau))
382 density_line.set_ydata(density_scale * rho)
383 real_line.set_ydata(1.0 + np.real(psi))
384 imag_line.set_ydata(1.0 + np.imag(psi))
385 xmean_line.set_xdata([sim.expectation_x()] * 2)
386 minimum = -sim.f0 * np.cos(sim.omega * sim.tau)
387 minimum_line.set_xdata([minimum] * 2)
388 minimum_dot.set_data([minimum], [-0.5 * minimum**2])
389 norm = np.sum(rho) * sim.dx
390 if sim is analytic:
391 psi0, psi1, c0, c1 = analytic.components_01()
392 component0_line.set_data(sim.x, 2.0 + np.real(psi0))
393 component1_line.set_data(sim.x, 2.0 + np.real(psi1))
394 component_text = rf"$|c_0|^2={abs(c0)**2:.3f},\ |c_1|^2={abs(c1)**2:.3f}$"
395 else:
396 component0_line.set_data([], [])
397 component1_line.set_data([], [])
398 component_text = ""
399 photon_energy = sim.omega # E_gamma/(hbar omega0)
400 level_spacing = 1.0 # (E1-E0)/(hbar omega0)
401 detuning = photon_energy - level_spacing
402 if abs(detuning) < 0.02:
403 resonance = "on resonance"
404 elif abs(detuning) < 0.10:
405 resonance = "near resonance"
406 else:
407 resonance = "off resonance"
408 info.set_text(
409 f"{('analytic' if sim is analytic else 'numerical')} mode; tau = omega0 t = {sim.tau:.2f}" + "\n"
410 + rf"$\langle\xi\rangle={sim.expectation_x():.3f},\ \xi_{{\min}}={minimum:.3f},\ \gamma/\omega_0={sim.gamma:.2f}$" + "\n"
411 + rf"$E_\gamma/(\hbar\omega_0)={photon_energy:.3f}$, $(E_1-E_0)/(\hbar\omega_0)={level_spacing:.3f}$" + "\n"
412 + rf"$[E_\gamma-(E_1-E_0)]/(\hbar\omega_0)={detuning:+.3f}$ ({resonance})" + "\n"
413 + rf"$\int |\psi|^2d\xi={norm:.8f}$" + ("\n" + component_text if component_text else "")
414 )
415 return (fixed_potential, potential_line, density_line, real_line, imag_line,
416 component0_line, component1_line, xmean_line, minimum_line, minimum_dot, info)
417
418 def update(_):
419 if running:
420 sim.step(steps_per_frame)
421 return draw_frame()
422
423 animation = FuncAnimation(fig, update, init_func=draw_frame, interval=30, blit=False, cache_frame_data=False)
424 # Keep a reference alive until the GUI closes.
425 _ = animation
426 plt.show()
427
428
429if __name__ == "__main__":
430 main()