第10回:ChatGPTが書いたFEMコードをどうデバッグするか

ChatGPTで作る有限要素プログラム入門 第10回

はじめに――FEMのdebuggingは「症状から原因を当てる」仕事ではない

ChatGPTに有限要素コードを書かせると,コードが実行できるところまでは比較的簡単に到達します. 難しいのはその後です.

例えば,

  • 解のplotはそれらしく見える,
  • linear solverのresidualも小さい,
  • patch testも通る,
  • しかし収束次数が出ない

ということがあります. 第4回では,実際に \[ J_T^{-\top} \] を \[ J_T^{-1} \] と誤って実装したコードが,symmetry testやlinear patch testを通過しながら, smooth solutionに対する収束試験で失敗する例を見ました.

FEM debuggingの原則
出力の見た目から原因を推測してコードを何度も書き換えるのではなく, 弱形式から数値解までの各段階が満たすべき数学的不変量を,上流から順に検査する.

1.最初に「正しいはずの問題」を固定する

debuggingを始める前に,仕様を一枚に固定します. 最低限,

\[ \boxed{ \text{PDE} \to \text{weak form} \to \text{finite-element space} \to \text{element map} \to \text{quadrature} \to \text{boundary treatment} \to \text{linear solver} } \tag{1} \]

を書き出します.

例えばPoisson問題なら, \[ -\Delta u=f \quad\text{in }\Omega, \qquad u=g \quad\text{on }\partial\Omega \tag{2} \] に対して,test spaceを \[ V_0=H_0^1(\Omega) \] とし, \[ \int_\Omega\nabla u\cdot\nabla v\,dx = \int_\Omega fv\,dx \qquad \forall v\in V_0 \tag{3} \] という弱形式を固定します.

この段階が曖昧なままコードだけ直すと, 「正しく実装された別の問題」 を作ってしまう可能性があります.

2.FEMのbugを五つの層に分ける

layer 典型的なbug 最初に見るtest
model / weak form符号,係数,境界項,test space手計算,energy identity,manufactured solution
geometry / mapping\(J^{-1}\) vs \(J^{-\top}\),determinant,orientationelement invariant,skew element,mesh certificate
discretisationlocal matrix,assembly,quadrature,boundary eliminationrow sum,symmetry,patch test
algebra / solversingularity,ill-conditioning,solver toleranceresidual,eigenvalue,condition number
verification誤ったexact solution,誤差積分,偽reference solutionsymbolic residual,independent quadrature,known rate

重要なのは,これらを一度に直そうとしないことです. 一つずつ上流から閉じます.

3.Step 1:弱形式をコードから独立に検査する

Poisson問題のbilinear formなら \[ a(v,v) = \int_\Omega|\nabla v|^2\,dx \ge0. \tag{4} \] 従って,Dirichlet条件を課したdiscrete matrixは対称正定値になります.

もし \[ a(u,v) = -\int_\Omega\nabla u\cdot\nabla v\,dx \] のように符号を誤れば,局所行列は対称のままでもenergy signが反転します. つまり symmetryだけではweak-form bugを検出できません.

manufactured solutionを使う場合には, 選んだ \(u\) から \[ f=-\Delta u \] をコードとは独立に計算し, PDE residualが0になることを確認します.

4.Step 2:geometryを局所要素だけで検査する

2次元三角形なら \[ J_T=[p_1-p_0,\ p_2-p_0], \qquad |T|=\frac{|\det J_T|}{2}, \tag{5} \] 3次元四面体なら \[ J_T=[p_1-p_0,\ p_2-p_0,\ p_3-p_0], \qquad |T|=\frac{|\det J_T|}{6}. \tag{6} \]

scalar P1 basisのphysical gradientは \[ \boxed{ \nabla\phi_i = J_T^{-\top} \widehat\nabla\widehat\phi_i. } \tag{7} \]

ここではuniformな直角要素だけでtestしない方がよいです. 対称性の高い要素では,誤った変換が偶然見えにくいことがあります. 例えば2次元なら \[ (0,0)^{\top}, \quad (1,0)^{\top}, \quad (0.3,0.8)^{\top} \] のようなskew triangleもunit testに入れます.

5.Step 3:局所剛性行列の不変量を調べる

nondegenerate simplex上のP1 Laplace stiffness matrix \(K^{(T)}\) は,

\[ (K^{(T)})^{\top}=K^{(T)}, \tag{8} \] \[ K^{(T)}\mathbf1=0, \tag{9} \] \[ z^{\top}K^{(T)}z\ge0 \tag{10} \]

を満たします. さらにnullspaceは定数だけなので,2次元三角形ではrank 2, 3次元四面体ではrank 3です.

ただし異方性要素ではmatrix scaleが極端になることがあります. 固定した 1e-12 だけで判定するより,matrix normに応じたscale-aware toleranceを使う方が安全です.

def local_stiffness_audit(Ke):
    scale = max(
        1.0,
        np.linalg.norm(Ke, ord=np.inf)
    )

    tol = (
        100.0
        * np.finfo(float).eps
        * scale
    )

    symmetry = np.linalg.norm(
        Ke - Ke.T,
        ord=np.inf
    )

    row_sum = np.linalg.norm(
        Ke @ np.ones(Ke.shape[0]),
        ord=np.inf
    )

    eigenvalues = np.linalg.eigvalsh(
        0.5 * (Ke + Ke.T)
    )

    return {
        "symmetry": symmetry,
        "row_sum": row_sum,
        "min_eigenvalue": eigenvalues[0],
        "tolerance": tol,
        "pass_symmetry": symmetry <= tol,
        "pass_row_sum": row_sum <= tol,
        "pass_psd":
            eigenvalues[0] >= -tol
    }

6.Step 4:assemblyをfull matrixの段階で止めて調べる

Dirichlet条件をまだ入れていないfull stiffness matrixを \[ A_{\mathrm{full}} \] とします. connected meshのpure Laplace operatorなら,

\[ A_{\mathrm{full}}\mathbf1=0, \tag{11} \] \[ A_{\mathrm{full}} = A_{\mathrm{full}}^{\top}. \tag{12} \]

が成立します.

ここで重要なのは,boundary conditionを入れる前のmatrixを保存することです. 境界行・列を上書きした後では, 本来のassembly invariantが見えなくなります.

局所行列が正しくてもglobal row sumが壊れているなら, local-to-global numberingまたはassembly loopを疑います.

7.Step 5:境界条件はhomogeneous testだけでは不十分

同次Dirichlet条件 \[ u=0 \] だけで開発していると,boundary eliminationのbugを見逃すことがあります. 非同次境界値 \(U_B\) を与える場合,内部自由度は

\[ \boxed{ A_{II}U_I = b_I-A_{IB}U_B. } \tag{13} \]

を解かなければなりません.

したがって,boundary-debug用には \[ u(x,y)=1+2x-3y \tag{14} \] のような非同次affine solutionを必ず入れます. この場合 \[ -\Delta u=0 \] なので,P1 finite elementは理論上 \[ u_h=u \] を厳密に再現します.

homogeneous manufactured solutionとnonhomogeneous patch testは役割が違う
前者はsmooth-solution convergenceを見る.
後者はboundary eliminationとpolynomial reproductionを直接検査する.

8.Step 6:quadratureをdiscretisationから分離する

「FEMが間違っている」のではなく,quadratureだけが間違っている場合もあります. reference element上のweightについて,まず

\[ \sum_q w_q = |\widehat T| \tag{15} \]

を確認します. 三角形なら \(1/2\),四面体なら \(1/6\) です.

affine P1 simplexでPoisson stiffnessを作る場合, \[ \nabla\phi_i\cdot\nabla\phi_j \] は要素内で定数なので,stiffness integrationは非常に単純です. 一方, \[ \int_T f\phi_i\,dx \] は \(f\) に依存します. 三角関数をmanufactured forcingに使えば,有限点Gauss公式は一般に数学的なexact integrationではありません.

debuggingではquadrature orderを変えて, 解・誤差・observed rateがどう変化するかを比較します. quadratureを上げても結果が変わらなければ,別の層を疑います.

9.Step 7:solver residualは「最後の方程式」を解いた証拠にすぎない

内部systemについて \[ r_I=A_{II}U_I-b_I^{\mathrm{eff}} \tag{16} \] を計算し, \[ \frac{\|r_I\|} {\|b_I^{\mathrm{eff}}\|+\|A_{II}\|\|U_I\|} \tag{17} \] のようなscaled residualを確認します.

しかしresidualが \(10^{-14}\) でも, \(A_{II}\) 自体を間違えて組み立てていれば有限要素解は間違っています.

第7回では,semi-regularな強異方性meshでもglobal stiffness matrixのcondition numberが大きくなることを確認しました. 従って \[ \text{small residual} \not\Longrightarrow \text{small solution error} \tag{18} \] です.

10.Step 8:patch testは必要だが十分ではない

P1要素なら,2次元では \[ u(x,y)=a+bx+cy, \] 3次元では \[ u(x,y,z)=a+bx+cy+dz \tag{19} \] を非同次Dirichlet dataとして与えます. 正しいP1 discretisationならexact arithmeticで \[ u_h=u. \tag{20} \]

ただし第4回で見たように,誤った \[ J_T^{-1} \] を使ったコードでもpatch testを通過する場合があります.

従ってpatch testは 「一次式再現性が壊れていない」 ことを確認するtestであって, 「すべての実装が正しい」 ことを証明するtestではありません.

11.Step 9:manufactured solutionと収束次数で最終確認する

smooth solutionとして \[ u(x,y)=\sin(\pi x)\sin(\pi y) \tag{21} \] を使えば,regularなP1 mesh上で \[ \|u-u_h\|_{L^2}=O(h^2), \qquad |u-u_h|_{H^1}=O(h) \tag{22} \] が期待されます.

第4回のintentional bugでは, \(J_T^{-\top}\) を \(J_T^{-1}\) に変えたコードがpatch testを通ったにもかかわらず, \(n=32\) でも相対誤差が概ね \[ E_{L^2}^{\mathrm{rel}} \approx2.99\times10^{-1}, \qquad E_{H^1}^{\mathrm{rel}} \approx3.59\times10^{-1} \] に留まり,期待収束が現れませんでした.

このため収束試験は, 理論上のerror estimateを実装仕様として使うverification test だと考えることができます.

12.Step 10:異方性stress testを別に行う

uniform meshで正しく見えたコードも,異方性meshで壊れることがあります. 第6–9回で導入したgeometry auditを使い,

\[ \kappa_2(J_T), \qquad \frac{H_T}{h_T}, \qquad Q_T, \qquad \kappa_2(A_{II}) \tag{23} \]

を分けて記録します.

ここで \[ \kappa_2(J_T)\gg1 \] だから直ちにbad elementと判定してはいけません. 第7回のthin right trianglesのように, \[ H_T/h_T \] が一様有界な強異方性meshは存在します.

3次元では第9回のsliverのように, edge ratioがほぼ2でも体積が潰れて semi-regularity certificateが発散する場合があります.

13.bugの症状と疑う場所

symptom 最初に疑う場所 切り分けtest
local matrixが非対称gradient変換,index order一要素の手計算
local row sum \(\neq0\)basis gradient,local matrix formula\(\sum_i\nabla\phi_i=0\)
localは正しいがglobal row sumが壊れるassembly,connectivitysingle-element → two-element test
homogeneous BCは動くがnonhomogeneous BCで失敗RHS correctionaffine patch test
residualは小さいが誤差が大きいdiscretisation / weak formmanufactured convergence
patch testは通るが収束しないmapping,quadrature,wrong operatorskew-element test + smooth convergence
uniform meshだけ正しいgeometry assumptionanisotropic / skew mesh stress test
fine mesh同士では差が減るがexact errorは減らないreference solutionmanufactured exact solution / independent certificate

14.「一要素 → 小mesh → 本番mesh」の順でdebugする

大きなmeshを最初からdebugする必要はありません. むしろ,

\[ \boxed{ \text{one element} \to \text{two or few elements} \to \text{structured coarse mesh} \to \text{anisotropic stress mesh} \to \text{production mesh} } \tag{24} \]

と段階を分けます.

一要素ではJacobianとlocal matrixを確認し, 二要素ではshared nodeへのassemblyを確認し, 小meshではboundary eliminationとglobal SPDを確認します. その後にconvergenceとanisotropyへ進みます.

この順番なら,bugが現れた最初のscaleが原因の候補をかなり限定してくれます.

15.小規模mesh用のdiagnostic report

debug時だけ使う小規模なdiagnostic functionを用意しておくと便利です. 以下はdense化しても問題ない小meshを想定しています.

def fem_debug_report(
    A_full,
    b,
    uh,
    interior,
    boundary,
    effective_rhs
):
    A_dense = (
        A_full.toarray()
        if hasattr(A_full, "toarray")
        else np.asarray(A_full)
    )

    AII = A_dense[
        np.ix_(interior, interior)
    ]

    symmetry_full = np.linalg.norm(
        A_dense - A_dense.T,
        ord=np.inf
    )

    constant_residual = np.linalg.norm(
        A_dense @ np.ones(A_dense.shape[0]),
        ord=np.inf
    )

    eig = np.linalg.eigvalsh(
        0.5 * (AII + AII.T)
    )

    linear_residual = (
        AII @ uh[interior]
        - effective_rhs
    )

    return {
        "global_symmetry":
            symmetry_full,
        "A_full_times_one":
            constant_residual,
        "lambda_min_AII":
            eig[0],
        "lambda_max_AII":
            eig[-1],
        "cond_AII":
            eig[-1] / eig[0],
        "solver_residual_inf":
            np.linalg.norm(
                linear_residual,
                ord=np.inf
            ),
        "boundary_value_max":
            np.max(
                np.abs(uh[boundary])
            )
    }

非同次Dirichlet条件なら boundary_value_max の代わりに \[ \max_{i\in B}|U_i-g(x_i)| \] を確認します.

16.assertionは「証明」ではなくearly warningである

コード中の assert は非常に有効ですが, 全assertionを通過したから数学的正しさが証明されたわけではありません.

第4回の \(J^{-1}\) bugのように,

\[ \text{symmetry}, \quad \text{row sum}, \quad \text{patch test} \]

を同時に通過する誤実装もあります.

従ってverification suiteは少なくとも,

  1. local algebraic invariants,
  2. nonhomogeneous polynomial patch test,
  3. smooth manufactured-solution convergence,
  4. geometry stress test

という異なる原理のtestを組み合わせます.

17.reference solutionそのものを疑う

exact solutionがない問題では,fine-mesh solutionをreferenceにしたくなります. しかし,同じ誤ったコード,同じ不適切なmesh familyで細分化すると, 粗い解とfine solutionの差だけが小さくなり, 「収束しているように見える」可能性があります.

この問題は 「有限要素解は収束しているのに正解へ収束しない――最大角条件とBabuška–Aziz反例」 で扱ったfalse convergenceと同じ警告です.

debugging段階では,可能な限りmanufactured exact solutionを使います. exact solutionが使えない場合には, 別method,verified bound,equilibrated flux,mesh-independent quantityなど, 独立なreferenceを用意することが重要です.

18.ChatGPTには「直して」ではなく「原因を一つずつ切り分けて」と頼む

Debug prompt
この有限要素コードを一度に書き換えないでください. まず現在の実装を,
(1) PDEとweak form,
(2) reference-to-physical mapping,
(3) local basis gradients,
(4) local stiffness/load,
(5) local-to-global assembly,
(6) Dirichlet boundary elimination,
(7) quadrature,
(8) linear solver,
(9) error computation
に分解してください. 各段階について,成立すべき数学的不変量と最小unit testを一つずつ提示してください. 一つの段階がpassしたら次へ進み, 複数の箇所を同時に変更しないでください. 最後にnonhomogeneous affine patch test,smooth manufactured-solution convergence, anisotropic/skew mesh stress testを行ってください.

ChatGPTに「全部直して」と頼むと, 元のbugを消す代わりに別の部分まで書き換え, 原因が分からなくなることがあります. debuggingでは変更量を小さく保つ方がよいです.

19.ChatGPTが出しやすい危険なdebugging pattern

patternなぜ危険か代わりにすること
plotが滑らかなので正しいと判断wrong PDEでもsmooth solutionは出るerror normとrateを見る
residualだけ確認wrong discrete systemも高精度で解けるindependent verificationを追加
複数箇所を同時修正原因が特定できないone change, one test
uniform meshだけで確認geometry bugが隠れるskew / anisotropic meshを加える
aspect ratioが大きいのでmeshを拒否good anisotropyまで排除する\(H_T/h_T\),volume,目的別条件を見る
fine mesh solutionを無条件に真値扱いfalse convergenceを見逃すindependent referenceを使う

20.最終debugging protocol

以上を一つの順番にまとめると,

\[ \boxed{ \begin{array}{c} \text{specification}\\ \downarrow\\ \text{weak form}\\ \downarrow\\ \text{geometry / Jacobian}\\ \downarrow\\ \text{local element invariants}\\ \downarrow\\ \text{assembly}\\ \downarrow\\ \text{boundary condition}\\ \downarrow\\ \text{quadrature}\\ \downarrow\\ \text{solver residual / conditioning}\\ \downarrow\\ \text{patch test}\\ \downarrow\\ \text{manufactured convergence}\\ \downarrow\\ \text{anisotropic stress test} \end{array} } \tag{25} \]

です.

bugを見つけるというより, 正しさを段階的に狭い範囲で確認していくと考えた方がよいです.

21.第10回の結論

ChatGPTはFEMコードを速く生成できます. しかし,生成されたコードの正しさを ChatGPT自身の説明だけで保証することはできません.

有限要素法には,

\[ \text{partition of unity}, \quad \text{symmetry}, \quad \text{energy positivity}, \quad \text{polynomial exactness}, \quad \text{convergence rate}, \quad \text{geometry conditions} \]

という多数の数学的不変量があります. これらをunit testとして利用すれば, AI生成コードをかなり系統的に監査できます.

AIにFEMをデバッグしてもらうときの最重要原則
AIの「修正案」を信用するのではなく, 修正後のコードが満たすべき数学をtest specificationにする.

次回はP1要素を離れ, CR・RTなど,P1の次に何を見るか を扱います. ここでは自由度そのものが頂点値から辺平均・fluxへ変わり, mappingとdebuggingの考え方も一段進みます.

参考文献・関連ノート

  1. P. G. Ciarlet, The Finite Element Method for Elliptic Problems, North-Holland, 1978.
  2. S. C. Brenner and L. R. Scott, The Mathematical Theory of Finite Element Methods, 3rd ed., Springer, 2008.
  3. A. Ern and J.-L. Guermond, Finite Elements I: Approximation and Interpolation, Springer, 2021.
  4. 第4回:2次元P1有限要素コードを数学的に監査する
  5. 第7回:異方性P1要素は本当に正しく動くか
  6. 第9回:3次元異方性四面体 — Type (i), Type (ii), sliver
  7. 有限要素解は収束しているのに正解へ収束しない――最大角条件とBabuška–Aziz反例

ページの先頭へ