【发布时间】:2021-01-05 06:10:18
【问题描述】:
每个时间步我需要计算几千次以下积分:
到目前为止,我已经在 Julia 中实现了:
using StaticArrays
function interactiontensor(C, a1, a2, a3, ϕ, θ)
n1,n2 = 100,50
T = fill(0.0,3,3,3,3)
Av = zeros(4,4)
invAv = similar(Av)
xi = Vector{Float64}(undef, 3)
@inbounds for p ∈ 1:n1
sinθp = sind(θ[p])
cosθp = cosd(θ[p])
for q ∈ 1:n2
sinϕq = sind(ϕ[q])
cosϕq = cosd(ϕ[q])
# -- Director cosines
xi[1] = sinθp*cosϕq/a1
xi[2] = sinθp*sinϕq/a2
xi[3] = cosθp/a3
Christoffel!(Av,C,xi)
fillAv!(Av, xi)
invAv = inv(SMatrix{4,4}(Av))
tensorT!(T,invAv,xi,sinθp)
surface += sinθp
end
end
return T ./= surface
end
@inline function Christoffel!(Av,C,xi)
@inbounds for t ∈ 1:3, r ∈ 1:3
aux = zero(eltype(C))
for u ∈ 1:3, s ∈ 1:3
aux += C[r, s, t, u] * xi[s] * xi[u]
end
Av[r, t] = aux
end
end
@inline function tensorT!(T,invAv,xi,sinθp)
@inbounds for k ∈ 1:3, i ∈ 1:3
aux = invAv[i, k]
for l ∈ 1:3, j ∈ 1:3
T[i, j, k, l] += aux * xi[j] * xi[l] * sinθp
end
end
end
@inline function fillAv!(Av, xi)
@inbounds for i ∈ 1:3
xi0 = xi[i]
Av[i, 4] = xi0
Av[4, i] = xi0
end
end
与
n1,n2 = 100,100
step = π/n1
dθ,dϕ = π/n1, 2π/n2
θ = rad2deg.(range(dθ, stop = pi, length = n1))
ϕ = rad2deg.(range(dϕ, stop = 2pi, length = n2))
C = @SArray rand(3,3,3,3)
@btime interactiontensor($C, $10.0, $5.0, $1.0, $ϕ, $θ);
# 544.795 μs (4 allocations: 1.08 KiB)
考虑到理想情况下我需要计算这个积分的次数,我的实现是否有任何优化或替代方法,以显着降低计算成本?
【问题讨论】:
-
根本不是你的瓶颈,但你可以写得更快
sinθp, cosθp = sincosd(θ[p])。 -
由于您明确写出缩写,您可能想尝试
@simd。或者,尝试使用 Einsum 包,如 github.com/mcabbott/Tullio.jl、github.com/Jutho/TensorOperations.jl 或 github.com/under-Peter/OMEinsum.jl。 -
是否可以解析地计算
A(θ,ϕ)的倒数? -
您是否尝试过避免显式计算
inv,而是在tensorT!中使用\? -
你可以通过
xi = @SVector zeros(3)然后使用 github.com/jw3126/Setfield.jl 设置 xi 的组件,即@set x[1] = sinθp*cosϕq/a1来加快速度(在我的机器上约为 30%)
标签: julia integration