relax_2d_ionic.py ダウンロード/コピー

relax_2d_ionic.py をダウンロード

relax_2d_ionic.py
relax_2d_ionic.py
  1#!/usr/bin/env python3
  2"""
  3概要:
  4    Born-Mayer型のポテンシャルを用いた2次元A+X-イオン結晶格子の構造最適化を行います。
  5詳細説明:
  6    X陰イオンはa=bの正方格子を形成します。各ユニットセルにおいて、1つのA陽イオンが(x, y)の位置を自由に動くことができます。
  7    セルあたりのエネルギーには、4つの最近接A-X相互作用と2つのX-X結合が含まれます。A-A相互作用は省略されています。
  8"""
  9
 10from __future__ import annotations
 11
 12import argparse
 13import time
 14from dataclasses import dataclass
 15
 16import matplotlib.pyplot as plt
 17import numpy as np
 18from scipy.optimize import minimize
 19
 20
 21@dataclass(frozen=True)
 22class Params:
 23    """
 24    概要:
 25        計算に用いるパラメータを保持するデータクラスです。
 26    詳細説明:
 27        各パラメータは初期値とともに設定されています。
 28    引数:
 29        :param c_ax: A-X間のクーロン引力係数
 30        :type c_ax: float
 31        :param b_ax: A-X間の斥力係数
 32        :type b_ax: float
 33        :param rho_ax: A-X間の斥力の減衰距離
 34        :type rho_ax: float
 35        :param c_xx: X-X間のクーロン反発係数
 36        :type c_xx: float
 37        :param b_xx: X-X間の斥力係数
 38        :type b_xx: float
 39        :param rho_xx: X-X間の斥力の減衰距離
 40        :type rho_xx: float
 41        :param a_min: 格子定数の最小値
 42        :type a_min: float
 43    """
 44    c_ax: float = 1.0
 45    b_ax: float = 8.0
 46    rho_ax: float = 0.18
 47    c_xx: float = 1.0
 48    b_xx: float = 4.0
 49    rho_xx: float = 0.22
 50    a_min: float = 0.30
 51
 52
 53def sigmoid(z: float) -> float:
 54    """
 55    概要:
 56        シグモイド関数を計算します。
 57    引数:
 58        :param z: 入力値
 59        :type z: float
 60    戻り値:
 61        :returns: 0から1の範囲の計算結果
 62        :rtype: float
 63    """
 64    if z >= 0.0:
 65        return 1.0 / (1.0 + np.exp(-z))
 66    ez = np.exp(z)
 67    return ez / (1.0 + ez)
 68
 69
 70def logit(u: float) -> float:
 71    """
 72    概要:
 73        ロジット関数を計算します。
 74    引数:
 75        :param u: 0から1の範囲の入力値
 76        :type u: float
 77    戻り値:
 78        :returns: ロジット関数の計算結果
 79        :rtype: float
 80    """
 81    return float(np.log(u / (1.0 - u)))
 82
 83
 84def unpack(q: np.ndarray, p: Params) -> tuple[float, float, float]:
 85    """
 86    概要:
 87        制約のない最適化変数qを物理的な変数a、x、yに変換します。
 88    詳細説明:
 89        格子定数aはa_minより大きく、xとyは0からaの範囲に制限されます。
 90    引数:
 91        :param q: 3要素の最適化変数配列
 92        :type q: numpy.ndarray
 93        :param p: パラメータオブジェクト
 94        :type p: Params
 95    戻り値:
 96        :returns: a、x、yのタプル
 97        :rtype: tuple
 98    """
 99    a = p.a_min + np.exp(np.clip(q[0], -50.0, 50.0))
100    x = a * sigmoid(float(q[1]))
101    y = a * sigmoid(float(q[2]))
102    return float(a), float(x), float(y)
103
104
105def pack(a: float, x: float, y: float, p: Params) -> np.ndarray:
106    """
107    概要:
108        物理的な変数a、x、yを制約のない最適化変数qに変換します。
109    引数:
110        :param a: 格子定数
111        :type a: float
112        :param x: x座標
113        :type x: float
114        :param y: y座標
115        :type y: float
116        :param p: パラメータオブジェクト
117        :type p: Params
118    戻り値:
119        :returns: 3要素の最適化変数配列
120        :rtype: numpy.ndarray
121    例外:
122        :raises ValueError: aがa_min以下、またはx、yが0からaの範囲外の場合に発生します
123    """
124    if a <= p.a_min or not (0.0 < x < a and 0.0 < y < a):
125        raise ValueError("Require a > a_min and 0 < x,y < a")
126    return np.array([np.log(a - p.a_min), logit(x / a), logit(y / a)])
127
128
129def v_ax(r: np.ndarray | float, p: Params) -> np.ndarray | float:
130    """
131    概要:
132        A-X間の相互作用ポテンシャルを計算します。
133    引数:
134        :param r: A-X間の距離
135        :type r: numpy.ndarray | float
136        :param p: パラメータオブジェクト
137        :type p: Params
138    戻り値:
139        :returns: ポテンシャルエネルギー
140        :rtype: numpy.ndarray | float
141    """
142    return -p.c_ax / r + p.b_ax * np.exp(-r / p.rho_ax)
143
144
145def v_xx(r: float, p: Params) -> float:
146    """
147    概要:
148        X-X間の相互作用ポテンシャルを計算します。
149    引数:
150        :param r: X-X間の距離
151        :type r: float
152        :param p: パラメータオブジェクト
153        :type p: Params
154    戻り値:
155        :returns: ポテンシャルエネルギー
156        :rtype: float
157    """
158    return p.c_xx / r + p.b_xx * np.exp(-r / p.rho_xx)
159
160
161def physical_energy(a: float, x: float, y: float, p: Params) -> float:
162    """
163    概要:
164        セルあたりの全ポテンシャルエネルギーを計算します。
165    詳細説明:
166        Aイオンの周囲にある4つのXイオンとの相互作用と、正方格子の2つの独立した最近接X-X結合のエネルギーを合計します。
167        距離がゼロに近すぎる場合は非常に大きな値を返します。
168    引数:
169        :param a: 格子定数
170        :type a: float
171        :param x: x座標
172        :type x: float
173        :param y: y座標
174        :type y: float
175        :param p: パラメータオブジェクト
176        :type p: Params
177    戻り値:
178        :returns: 全ポテンシャルエネルギー
179        :rtype: float
180    """
181    # Four X corners around the A ion. Each A-X bond is counted once.
182    dx = np.array([x, x - a, x, x - a])
183    dy = np.array([y, y, y - a, y - a])
184    r = np.hypot(dx, dy)
185    if np.min(r) < 1.0e-10:
186        return 1.0e100
187    # A square X lattice has two independent nearest-neighbour X-X bonds/cell.
188    return float(np.sum(v_ax(r, p)) + 2.0 * v_xx(a, p))
189
190
191def energy_q(q: np.ndarray, p: Params) -> float:
192    """
193    概要:
194        最適化変数qに対するエネルギーを計算します。
195    引数:
196        :param q: 3要素の最適化変数配列
197        :type q: numpy.ndarray
198        :param p: パラメータオブジェクト
199        :type p: Params
200    戻り値:
201        :returns: 全ポテンシャルエネルギー
202        :rtype: float
203    """
204    return physical_energy(*unpack(q, p), p)
205
206
207class Animator:
208    """
209    概要:
210        最適化の過程をアニメーション表示するためのクラスです。
211    詳細説明:
212        指定されたステップごとに格子構造とエネルギー履歴をプロットします。
213    引数:
214        :param p: パラメータオブジェクト
215        :type p: Params
216        :param frame_step: アニメーションを更新するステップ間隔
217        :type frame_step: int
218        :param sleep_time: 1フレームの表示時間
219        :type sleep_time: float
220        :param enabled: アニメーションを有効にするかどうか
221        :type enabled: bool
222        :param history: 状態とエネルギーの履歴リスト
223        :type history: list
224        :param iteration: 現在の反復回数
225        :type iteration: int
226        :param fig: matplotlibのFigureオブジェクト
227        :type fig: matplotlib.figure.Figure
228    """
229    def __init__(self, p: Params, frame_step: int, sleep_time: float, enabled: bool):
230        """
231        概要:
232            Animatorクラスの初期化を行います。
233        """
234        self.p = p
235        self.frame_step = frame_step
236        self.sleep_time = sleep_time
237        self.enabled = enabled
238        self.history: list[tuple[float, float, float, float]] = []
239        self.iteration = 0
240        self.fig = None
241        if enabled:
242            plt.ion()
243            self.fig, (self.ax_s, self.ax_e) = plt.subplots(1, 2, figsize=(11, 5))
244
245    def add(self, q: np.ndarray, force_draw: bool = False) -> None:
246        """
247        概要:
248            最適化の現在の状態を履歴に追加し、必要に応じて描画を更新します。
249        引数:
250            :param q: 現在の最適化変数配列
251            :type q: numpy.ndarray
252            :param force_draw: 強制的に描画を更新するかどうか
253            :type force_draw: bool
254        戻り値:
255            :returns: なし
256            :rtype: None
257        """
258        a, x, y = unpack(np.asarray(q), self.p)
259        e = physical_energy(a, x, y, self.p)
260        self.history.append((a, x, y, e))
261        draw = force_draw or self.iteration % self.frame_step == 0
262        if self.enabled and draw:
263            self._draw(a, x, y, e)
264        self.iteration += 1
265
266    def _draw(self, a: float, x: float, y: float, e: float) -> None:
267        """
268        概要:
269            現在の格子構造とエネルギーの履歴をプロットします。
270        引数:
271            :param a: 格子定数
272            :type a: float
273            :param x: x座標
274            :type x: float
275            :param y: y座標
276            :type y: float
277            :param e: 現在のエネルギー
278            :type e: float
279        戻り値:
280            :returns: なし
281            :rtype: None
282        """
283        assert self.fig is not None
284        self.ax_s.clear()
285        # Show a 3x3 part of the periodic X lattice and A ions in four cells.
286        grid = np.arange(-1, 3) * a
287        gx, gy = np.meshgrid(grid, grid)
288        self.ax_s.scatter(gx, gy, s=150, c="tab:blue", label="X-", zorder=3)
289        for i in range(-1, 2):
290            for j in range(-1, 2):
291                self.ax_s.scatter(i * a + x, j * a + y, s=85, c="tab:red",
292                                  label="A+" if i == -1 and j == -1 else None, zorder=4)
293        self.ax_s.plot([0, a, a, 0, 0], [0, 0, a, a, 0], "k--", lw=1)
294        self.ax_s.set(xlim=(-0.25*a, 1.25*a), ylim=(-0.25*a, 1.25*a),
295                      aspect="equal", xlabel="x", ylabel="y",
296                      title=f"iteration {self.iteration}\na={a:.5f}, x/a={x/a:.5f}, y/a={y/a:.5f}")
297        self.ax_s.legend(loc="upper right")
298
299        self.ax_e.clear()
300        energies = [h[3] for h in self.history]
301        self.ax_e.plot(np.arange(len(energies)), energies, "o-", ms=3)
302        self.ax_e.set(xlabel="optimization iteration", ylabel="energy / cell",
303                      title=f"E = {e:.8f}")
304        self.ax_e.grid(alpha=0.3)
305        self.fig.tight_layout()
306        self.fig.canvas.draw_idle()
307        self.fig.canvas.flush_events()
308        plt.pause(max(self.sleep_time, 1.0e-4))
309
310
311def parse_args() -> argparse.Namespace:
312    """
313    概要:
314        コマンドライン引数を解析します。
315    戻り値:
316        :returns: 解析されたコマンドライン引数を格納したオブジェクト
317        :rtype: argparse.Namespace
318    """
319    ap = argparse.ArgumentParser(
320        description="Relax a 2D A+X- lattice (dimensionless units).")
321    ap.add_argument("--method", choices=["nelder-mead", "bfgs", "cg"],
322                    default="bfgs", help="optimization algorithm")
323    ap.add_argument("--a0", type=float, default=2.0, help="initial lattice constant")
324    ap.add_argument("--x0", type=float, default=0.96, help="initial A x coordinate")
325    ap.add_argument("--y0", type=float, default=1.03, help="initial A y coordinate")
326    ap.add_argument("--frame-step", type=int, default=1,
327                    help="draw every N optimization iterations")
328    ap.add_argument("--print-step", type=int, default=1,
329                    help="print every N recorded iterations (0: final result only)")
330    ap.add_argument("--sleep", type=float, default=0.10,
331                    help="pause time for each displayed frame [s]")
332    ap.add_argument("--no-animation", action="store_true",
333                    help="run without live animation")
334    ap.add_argument("--maxiter", type=int, default=1000)
335    ap.add_argument("--tol", type=float, default=1.0e-6)
336    ap.add_argument("--c-ax", type=float, default=1.0)
337    ap.add_argument("--b-ax", type=float, default=8.0)
338    ap.add_argument("--rho-ax", type=float, default=0.18)
339    ap.add_argument("--c-xx", type=float, default=1.0)
340    ap.add_argument("--b-xx", type=float, default=4.0)
341    ap.add_argument("--rho-xx", type=float, default=0.22)
342    ap.add_argument("--a-min", type=float, default=0.30)
343    return ap.parse_args()
344
345
346def main() -> None:
347    """
348    概要:
349        メイン処理を実行し、格子構造の最適化を行います。
350    詳細説明:
351        コマンドライン引数を読み込み、初期構造を設定した上で、指定された最適化手法を用いてエネルギーが最小となる構造を探索します。
352        結果はコンソールに出力され、アニメーションが有効な場合は画面に表示されます。
353    戻り値:
354        :returns: なし
355        :rtype: None
356    例外:
357        :raises SystemExit: 不正な引数や初期構造が指定された場合に発生します
358    """
359    args = parse_args()
360    if args.frame_step < 1 or args.print_step < 0 or args.sleep < 0.0:
361        raise SystemExit(
362            "--frame-step must be >= 1, --print-step >= 0, and --sleep >= 0")
363    p = Params(args.c_ax, args.b_ax, args.rho_ax,
364               args.c_xx, args.b_xx, args.rho_xx, args.a_min)
365    try:
366        q0 = pack(args.a0, args.x0, args.y0, p)
367    except ValueError as exc:
368        raise SystemExit(f"Invalid initial structure: {exc}") from exc
369
370    method_map = {"nelder-mead": "Nelder-Mead", "bfgs": "BFGS", "cg": "CG"}
371    animator = Animator(p, args.frame_step, args.sleep, not args.no_animation)
372    animator.add(q0, force_draw=True)
373
374    def callback(q: np.ndarray) -> None:
375        """
376        概要:
377            最適化の各ステップで呼び出されるコールバック関数です。
378        引数:
379            :param q: 現在の最適化変数配列
380            :type q: numpy.ndarray
381        戻り値:
382            :returns: なし
383            :rtype: None
384        """
385        animator.add(q)
386
387    options = {"maxiter": args.maxiter}
388    if args.method == "nelder-mead":
389        options.update({"xatol": args.tol, "fatol": args.tol})
390    else:
391        options.update({"gtol": args.tol})
392
393    t0 = time.perf_counter()
394    result = minimize(energy_q, q0, args=(p,), method=method_map[args.method],
395                      callback=callback, tol=args.tol, options=options)
396    elapsed = time.perf_counter() - t0
397    final = unpack(result.x, p)
398    if not animator.history or not np.allclose(animator.history[-1][:3], final):
399        animator.add(result.x, force_draw=True)
400    elif animator.enabled:
401        animator._draw(*animator.history[-1])
402
403    a, x, y = final
404    if args.print_step > 0:
405        print("\n=== Optimization history ===")
406        print(f"{'iter':>6s} {'a':>14s} {'x':>14s} {'y':>14s} "
407              f"{'x/a':>14s} {'y/a':>14s} {'energy/cell':>18s}")
408        print("-" * 104)
409        last_index = len(animator.history) - 1
410        indices = list(range(0, len(animator.history), args.print_step))
411        if not indices or indices[-1] != last_index:
412            indices.append(last_index)
413        for i in indices:
414            ai, xi, yi, ei = animator.history[i]
415            print(f"{i:6d} {ai:14.8f} {xi:14.8f} {yi:14.8f} "
416                  f"{xi/ai:14.8f} {yi/ai:14.8f} {ei:18.10f}")
417
418    print("\n=== 2D ionic-lattice relaxation ===")
419    print(f"method       : {method_map[args.method]}")
420    print(f"success      : {result.success}")
421    print(f"message      : {result.message}")
422    print(f"iterations   : {result.nit}")
423    print(f"evaluations  : {result.nfev}")
424    print(f"elapsed [s]  : {elapsed:.6f}")
425    print(f"a            : {a:.10f}")
426    print(f"x, y         : {x:.10f}, {y:.10f}")
427    print(f"x/a, y/a     : {x/a:.10f}, {y/a:.10f}")
428    print(f"dx/a, dy/a   : {x/a-0.5:+.10f}, {y/a-0.5:+.10f}")
429    print(f"energy/cell  : {result.fun:.12f}")
430
431    if animator.enabled:
432        plt.ioff()
433        plt.show()
434
435
436if __name__ == "__main__":
437    main()