Fortran code generation¶
Thermodiff can turn a DiffPlz instance into a free-form Fortran subroutine that evaluates the original function together with all its available derivatives. The generated code uses intent(in) inputs and intent(out) outputs, expands the summations into do loops and turns the Piecewise expressions produced by the Kronecker-delta handling into if/else blocks.
[1]:
# Install if you are in Google Colab
import sys
if "google.colab" in sys.modules:
!pip install git+https://github.com/ipqa-research/thermodiff
[2]:
import thermodiff as td
from thermodiff import (
DiffPlz,
T,
V,
idx_function,
k,
l,
n,
sum_components,
)
A simple explicit model¶
As a first example we use a function that depends on composition and volume, and linearly on temperature:
We build the derivatives with the usual DiffPlz interface and then ask Thermodiff for the Fortran code.
[3]:
expr = T * sum_components(n[k] ** 2, k) + V * sum_components(n[k], k)
diff = DiffPlz(expr, internal_functions=None, indexes=[k], name="f")
print(td.to_fortran(diff))
subroutine f_derivs(nc, V, T, n, f, dfdT, dfdV, dfdn, dfdndn, dfdndT, dfdndV)
implicit none
integer, intent(in) :: nc
real(8), intent(in) :: V
real(8), intent(in) :: T
real(8), intent(in) :: n(:)
real(8), intent(out) :: f
real(8), intent(out) :: dfdT
real(8), intent(out) :: dfdV
real(8), intent(out) :: dfdn(:)
real(8), intent(out) :: dfdndn(:, :)
real(8), intent(out) :: dfdndT(:)
real(8), intent(out) :: dfdndV
real(8) :: res, t1, t2, t3, t4
integer :: i, j, k
t1 = 0.0d0
do k = 1, nc
t1 = t1 + n(k)
end do
t2 = 0.0d0
do k = 1, nc
t2 = t2 + n(k)**2
end do
res = T*t2 + V*t1
f = res
t3 = 0.0d0
do k = 1, nc
t3 = t3 + n(k)**2
end do
res = t3
dfdT = res
t4 = 0.0d0
do k = 1, nc
t4 = t4 + n(k)
end do
res = t4
dfdV = res
do i = 1, nc
res = 2*T*n(i) + V
dfdn(i) = res
end do
do i = 1, nc
do j = 1, nc
res = 2*T*merge(1.0d0, 0.0d0, i == j)
dfdndn(i, j) = res
end do
end do
do i = 1, nc
res = 2*n(i)
dfdndT(i) = res
end do
res = 1
dfdndV = res
end subroutine f_derivs
A few things to notice in the generated code:
Every sum became a
doloop over the components (the loop bound is thencargument).The function value and its derivatives are returned as separate
intent(out)arguments. Vector derivatives such asdfdnare declared with the component dimension.The default subroutine name is
f_derivs, because in Fortran the subroutine and the value argument cannot share the same name.
Choosing which derivatives to emit¶
By default every non-zero derivative is emitted. You can restrict the output with the derivatives argument.
[4]:
print(td.to_fortran(diff, derivatives=["dt", "dni"]))
subroutine f_derivs(nc, V, T, n, f, dfdT, dfdn)
implicit none
integer, intent(in) :: nc
real(8), intent(in) :: V
real(8), intent(in) :: T
real(8), intent(in) :: n(:)
real(8), intent(out) :: f
real(8), intent(out) :: dfdT
real(8), intent(out) :: dfdn(:)
real(8) :: res, t1, t2, t3
integer :: i, k
t1 = 0.0d0
do k = 1, nc
t1 = t1 + n(k)
end do
t2 = 0.0d0
do k = 1, nc
t2 = t2 + n(k)**2
end do
res = T*t2 + V*t1
f = res
t3 = 0.0d0
do k = 1, nc
t3 = t3 + n(k)**2
end do
res = t3
dfdT = res
do i = 1, nc
res = 2*T*n(i) + V
dfdn(i) = res
end do
end subroutine f_derivs
The same result can be obtained with the method on the instance:
diff.to_fortran(derivatives=["dt", "dni"])
Compositional derivatives and if/else¶
When differentiating with respect to the mole numbers, Kronecker deltas appear. Thermodiff replaces them with Piecewise expressions, which are printed as if/else blocks. Consider the mole fraction
[5]:
nt = sum_components(n[l], l)
x_k = DiffPlz(
n[k] / nt, internal_functions=None, indexes=[k, l], name="x_k"
)
print(td.to_fortran(x_k, derivatives=["dni"]))
subroutine x_k_derivs(nc, n, x_k, dx_kdn)
implicit none
integer, intent(in) :: nc
real(8), intent(in) :: n(:)
real(8), intent(out) :: x_k(:)
real(8), intent(out) :: dx_kdn(:, :)
real(8) :: res, t1, t2
integer :: i, k, l
do k = 1, nc
t1 = 0.0d0
do l = 1, nc
t1 = t1 + n(l)
end do
res = n(k)/t1
x_k(k) = res
end do
do i = 1, nc
do k = 1, nc
t2 = 0.0d0
do l = 1, nc
t2 = t2 + n(l)
end do
if (i == k) then
res = 1d0/t2 - n(i)/t2**2
else
res = -n(k)/t2**2
end if
dx_kdn(i, k) = res
end do
end do
end subroutine x_k_derivs
Notice the if (i == k) then ... else ... end if block coming from the Kronecker delta, and that the output dx_kdn is a two dimensional array indexed by the derivative index i and the function index k.
Internal functions as arguments¶
Models are usually written in terms of internal functions created with idx_function. These functions (and their derivatives) are unknown to the code generator, so by default they are exposed as additional input arguments with automatically generated names.
[9]:
phi_k = idx_function(r"\phi")(n[k])
tau_lk = idx_function(r"\tau")(l, k, T)
expr2 = sum_components(n[k] * phi_k * tau_lk, k)
diff2 = DiffPlz(
expr2, internal_functions=[phi_k, tau_lk], indexes=[k, l], name="f"
)
print(td.to_fortran(diff2, derivatives=["dt", "dni", "dnidnj"]))
subroutine f_derivs(nc, n, dphidi, dphididj, dphidj, dtaudT, phi, tau, f, dfdT, dfdn, dfdndn)
implicit none
integer, intent(in) :: nc
real(8), intent(in) :: n(:)
real(8), intent(in) :: dphidi(:, :)
real(8), intent(in) :: dphididj(:, :, :)
real(8), intent(in) :: dphidj(:, :)
real(8), intent(in) :: dtaudT(:, :)
real(8), intent(in) :: phi(:)
real(8), intent(in) :: tau(:, :)
real(8), intent(out) :: f(:)
real(8), intent(out) :: dfdT(:)
real(8), intent(out) :: dfdn(:, :)
real(8), intent(out) :: dfdndn(:, :, :)
real(8) :: res, t1, t2, t3, t4
integer :: i, j, k, l
do l = 1, nc
t1 = 0.0d0
do k = 1, nc
t1 = t1 + n(k)*phi(k)*tau(l, k)
end do
res = t1
f(l) = res
end do
do l = 1, nc
t2 = 0.0d0
do k = 1, nc
t2 = t2 + dtaudT(l, k)*n(k)*phi(k)
end do
res = t2
dfdT(l) = res
end do
do i = 1, nc
do l = 1, nc
t3 = 0.0d0
do k = 1, nc
t3 = t3 + dphidi(k, i)*n(k)*tau(l, k)
end do
res = t3 + phi(i)*tau(l, i)
dfdn(i, l) = res
end do
end do
do i = 1, nc
do j = 1, nc
do l = 1, nc
t4 = 0.0d0
do k = 1, nc
t4 = t4 + dphididj(k, i, j)*n(k)*tau(l, k)
end do
res = t4 + dphidi(j, i)*tau(l, j) + dphidj(i, j)*tau(l, i)
dfdndn(i, j, l) = res
end do
end do
end do
end subroutine f_derivs
The placeholders became phi, tau and dtaudT, dphidi arrays that the caller must supply. If you would rather get an error instead of silently exposing arguments, ask for strict mode.
[7]:
try:
td.to_fortran(diff2, strict=True)
except ValueError as exc:
print("ValueError:", exc)
ValueError: Expression contains unresolved functions or derivatives (strict mode): \phi(n[k]), \tau(l, k, T)
Notes¶
The subroutine is named after the
DiffPlzname with a_derivssuffix (f_derivs,x_k_derivs, …). Use thesubroutine_nameargument to change it.The independent variables appear as
n(:),V,P,T; free symbols become individualreal(8)parameters, and freeIndexedBaseobjects becomereal(8)arrays.Free indices of the expression become extra array dimensions of the outputs, so index-based models yield vector, matrix or higher-rank derivatives.
Sums whose value does not depend on the free indices are recomputed inside the loops (correct, but not yet optimised).