{ "cells": [ { "cell_type": "markdown", "id": "0ae04add", "metadata": {}, "source": [ "# Fortran code generation\n", "\n", "Thermodiff can turn a `DiffPlz` instance into a **free-form Fortran\n", "subroutine** that evaluates the original function together with all its\n", "available derivatives. The generated code uses `intent(in)` inputs and\n", "`intent(out)` outputs, expands the summations into `do` loops and turns the\n", "`Piecewise` expressions produced by the Kronecker-delta handling into\n", "`if`/`else` blocks." ] }, { "cell_type": "code", "execution_count": 1, "id": "dc08e53b", "metadata": { "execution": { "iopub.execute_input": "2026-10-15T21:02:47.498582Z", "iopub.status.busy": "2026-10-15T21:02:47.498191Z", "iopub.status.idle": "2026-10-15T21:02:47.506644Z", "shell.execute_reply": "2026-10-15T21:02:47.504343Z" } }, "outputs": [], "source": [ "# Install if you are in Google Colab\n", "import sys\n", "\n", "if \"google.colab\" in sys.modules:\n", " !pip install git+https://github.com/ipqa-research/thermodiff" ] }, { "cell_type": "code", "execution_count": 2, "id": "d25889a3", "metadata": { "execution": { "iopub.execute_input": "2026-10-15T21:02:47.510017Z", "iopub.status.busy": "2026-10-15T21:02:47.509692Z", "iopub.status.idle": "2026-10-15T21:02:48.075355Z", "shell.execute_reply": "2026-10-15T21:02:48.073577Z" } }, "outputs": [], "source": [ "import thermodiff as td\n", "\n", "from thermodiff import (\n", " DiffPlz,\n", " T,\n", " V,\n", " idx_function,\n", " k,\n", " l,\n", " n,\n", " sum_components,\n", ")" ] }, { "cell_type": "markdown", "id": "f0adcddd", "metadata": {}, "source": [ "## A simple explicit model\n", "\n", "As a first example we use a function that depends on composition and volume,\n", "and linearly on temperature:\n", "\n", "$$\n", "f(\\mathbf{n}, V, T) = T \\sum_{k=1}^{N_c} n_k^2 + V \\sum_{k=1}^{N_c} n_k\n", "$$\n", "\n", "We build the derivatives with the usual `DiffPlz` interface and then ask\n", "Thermodiff for the Fortran code." ] }, { "cell_type": "code", "execution_count": 3, "id": "a4005ac8", "metadata": { "execution": { "iopub.execute_input": "2026-10-15T21:02:48.078681Z", "iopub.status.busy": "2026-10-15T21:02:48.078249Z", "iopub.status.idle": "2026-10-15T21:02:48.235478Z", "shell.execute_reply": "2026-10-15T21:02:48.233837Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "subroutine f_derivs(nc, V, T, n, f, dfdT, dfdV, dfdn, dfdndn, dfdndT, dfdndV)\n", " implicit none\n", " integer, intent(in) :: nc\n", " real(8), intent(in) :: V\n", " real(8), intent(in) :: T\n", " real(8), intent(in) :: n(:)\n", " real(8), intent(out) :: f\n", " real(8), intent(out) :: dfdT\n", " real(8), intent(out) :: dfdV\n", " real(8), intent(out) :: dfdn(:)\n", " real(8), intent(out) :: dfdndn(:, :)\n", " real(8), intent(out) :: dfdndT(:)\n", " real(8), intent(out) :: dfdndV\n", " real(8) :: res, t1, t2, t3, t4\n", " integer :: i, j, k\n", "\n", " t1 = 0.0d0\n", " do k = 1, nc\n", " t1 = t1 + n(k)\n", " end do\n", " t2 = 0.0d0\n", " do k = 1, nc\n", " t2 = t2 + n(k)**2\n", " end do\n", " res = T*t2 + V*t1\n", " f = res\n", "\n", " t3 = 0.0d0\n", " do k = 1, nc\n", " t3 = t3 + n(k)**2\n", " end do\n", " res = t3\n", " dfdT = res\n", "\n", " t4 = 0.0d0\n", " do k = 1, nc\n", " t4 = t4 + n(k)\n", " end do\n", " res = t4\n", " dfdV = res\n", "\n", " do i = 1, nc\n", " res = 2*T*n(i) + V\n", " dfdn(i) = res\n", " end do\n", "\n", " do i = 1, nc\n", " do j = 1, nc\n", " res = 2*T*merge(1.0d0, 0.0d0, i == j)\n", " dfdndn(i, j) = res\n", " end do\n", " end do\n", "\n", " do i = 1, nc\n", " res = 2*n(i)\n", " dfdndT(i) = res\n", " end do\n", "\n", " res = 1\n", " dfdndV = res\n", "\n", "end subroutine f_derivs\n", "\n" ] } ], "source": [ "expr = T * sum_components(n[k] ** 2, k) + V * sum_components(n[k], k)\n", "\n", "diff = DiffPlz(expr, internal_functions=None, indexes=[k], name=\"f\")\n", "\n", "print(td.to_fortran(diff))" ] }, { "cell_type": "markdown", "id": "9f0143fe", "metadata": {}, "source": [ "A few things to notice in the generated code:\n", "\n", "* Every sum became a `do` loop over the components (the loop bound is the\n", " `nc` argument).\n", "* The function value and its derivatives are returned as separate\n", " `intent(out)` arguments. Vector derivatives such as `dfdn` are declared\n", " with the component dimension.\n", "* The default subroutine name is `f_derivs`, because in Fortran the\n", " subroutine and the value argument cannot share the same name." ] }, { "cell_type": "markdown", "id": "08f92521", "metadata": {}, "source": [ "## Choosing which derivatives to emit\n", "\n", "By default every non-zero derivative is emitted. You can restrict the output\n", "with the `derivatives` argument." ] }, { "cell_type": "code", "execution_count": 4, "id": "417e4189", "metadata": { "execution": { "iopub.execute_input": "2026-10-15T21:02:48.239037Z", "iopub.status.busy": "2026-10-15T21:02:48.238720Z", "iopub.status.idle": "2026-10-15T21:02:48.253393Z", "shell.execute_reply": "2026-10-15T21:02:48.251718Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "subroutine f_derivs(nc, V, T, n, f, dfdT, dfdn)\n", " implicit none\n", " integer, intent(in) :: nc\n", " real(8), intent(in) :: V\n", " real(8), intent(in) :: T\n", " real(8), intent(in) :: n(:)\n", " real(8), intent(out) :: f\n", " real(8), intent(out) :: dfdT\n", " real(8), intent(out) :: dfdn(:)\n", " real(8) :: res, t1, t2, t3\n", " integer :: i, k\n", "\n", " t1 = 0.0d0\n", " do k = 1, nc\n", " t1 = t1 + n(k)\n", " end do\n", " t2 = 0.0d0\n", " do k = 1, nc\n", " t2 = t2 + n(k)**2\n", " end do\n", " res = T*t2 + V*t1\n", " f = res\n", "\n", " t3 = 0.0d0\n", " do k = 1, nc\n", " t3 = t3 + n(k)**2\n", " end do\n", " res = t3\n", " dfdT = res\n", "\n", " do i = 1, nc\n", " res = 2*T*n(i) + V\n", " dfdn(i) = res\n", " end do\n", "\n", "end subroutine f_derivs\n", "\n" ] } ], "source": [ "print(td.to_fortran(diff, derivatives=[\"dt\", \"dni\"]))" ] }, { "cell_type": "markdown", "id": "d66c166e", "metadata": {}, "source": [ "The same result can be obtained with the method on the instance:\n", "\n", "```python\n", "diff.to_fortran(derivatives=[\"dt\", \"dni\"])\n", "```" ] }, { "cell_type": "markdown", "id": "5d0a87d4", "metadata": {}, "source": [ "## Compositional derivatives and `if`/`else`\n", "\n", "When differentiating with respect to the mole numbers, Kronecker deltas\n", "appear. Thermodiff replaces them with `Piecewise` expressions, which are\n", "printed as `if`/`else` blocks. Consider the mole fraction\n", "\n", "$$\n", "x_k = \\frac{n_k}{\\sum_{l=1}^{N_c} n_l}\n", "$$" ] }, { "cell_type": "code", "execution_count": 5, "id": "f9fc40af", "metadata": { "execution": { "iopub.execute_input": "2026-10-15T21:02:48.256938Z", "iopub.status.busy": "2026-10-15T21:02:48.256606Z", "iopub.status.idle": "2026-10-15T21:02:48.409337Z", "shell.execute_reply": "2026-10-15T21:02:48.407803Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "subroutine x_k_derivs(nc, n, x_k, dx_kdn)\n", " implicit none\n", " integer, intent(in) :: nc\n", " real(8), intent(in) :: n(:)\n", " real(8), intent(out) :: x_k(:)\n", " real(8), intent(out) :: dx_kdn(:, :)\n", " real(8) :: res, t1, t2\n", " integer :: i, k, l\n", "\n", " do k = 1, nc\n", " t1 = 0.0d0\n", " do l = 1, nc\n", " t1 = t1 + n(l)\n", " end do\n", " res = n(k)/t1\n", " x_k(k) = res\n", " end do\n", "\n", " do i = 1, nc\n", " do k = 1, nc\n", " t2 = 0.0d0\n", " do l = 1, nc\n", " t2 = t2 + n(l)\n", " end do\n", " if (i == k) then\n", " res = 1d0/t2 - n(i)/t2**2\n", " else\n", " res = -n(k)/t2**2\n", " end if\n", " dx_kdn(i, k) = res\n", " end do\n", " end do\n", "\n", "end subroutine x_k_derivs\n", "\n" ] } ], "source": [ "nt = sum_components(n[l], l)\n", "x_k = DiffPlz(\n", " n[k] / nt, internal_functions=None, indexes=[k, l], name=\"x_k\"\n", ")\n", "\n", "print(td.to_fortran(x_k, derivatives=[\"dni\"]))" ] }, { "cell_type": "markdown", "id": "6f528c20", "metadata": {}, "source": [ "Notice the `if (i == k) then ... else ... end if` block coming from the\n", "Kronecker delta, and that the output `dx_kdn` is a two dimensional array\n", "indexed by the derivative index `i` and the function index `k`." ] }, { "cell_type": "markdown", "id": "68fc063c", "metadata": {}, "source": [ "## Internal functions as arguments\n", "\n", "Models are usually written in terms of internal functions created with\n", "`idx_function`. These functions (and their derivatives) are unknown to the\n", "code generator, so by default they are **exposed as additional input\n", "arguments** with automatically generated names." ] }, { "cell_type": "code", "execution_count": 9, "id": "24cbdde1", "metadata": { "execution": { "iopub.execute_input": "2026-10-15T21:02:48.413297Z", "iopub.status.busy": "2026-10-15T21:02:48.412941Z", "iopub.status.idle": "2026-10-15T21:02:48.604615Z", "shell.execute_reply": "2026-10-15T21:02:48.603128Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "subroutine f_derivs(nc, n, dphidi, dphididj, dphidj, dtaudT, phi, tau, f, dfdT, dfdn, dfdndn)\n", " implicit none\n", " integer, intent(in) :: nc\n", " real(8), intent(in) :: n(:)\n", " real(8), intent(in) :: dphidi(:, :)\n", " real(8), intent(in) :: dphididj(:, :, :)\n", " real(8), intent(in) :: dphidj(:, :)\n", " real(8), intent(in) :: dtaudT(:, :)\n", " real(8), intent(in) :: phi(:)\n", " real(8), intent(in) :: tau(:, :)\n", " real(8), intent(out) :: f(:)\n", " real(8), intent(out) :: dfdT(:)\n", " real(8), intent(out) :: dfdn(:, :)\n", " real(8), intent(out) :: dfdndn(:, :, :)\n", " real(8) :: res, t1, t2, t3, t4\n", " integer :: i, j, k, l\n", "\n", " do l = 1, nc\n", " t1 = 0.0d0\n", " do k = 1, nc\n", " t1 = t1 + n(k)*phi(k)*tau(l, k)\n", " end do\n", " res = t1\n", " f(l) = res\n", " end do\n", "\n", " do l = 1, nc\n", " t2 = 0.0d0\n", " do k = 1, nc\n", " t2 = t2 + dtaudT(l, k)*n(k)*phi(k)\n", " end do\n", " res = t2\n", " dfdT(l) = res\n", " end do\n", "\n", " do i = 1, nc\n", " do l = 1, nc\n", " t3 = 0.0d0\n", " do k = 1, nc\n", " t3 = t3 + dphidi(k, i)*n(k)*tau(l, k)\n", " end do\n", " res = t3 + phi(i)*tau(l, i)\n", " dfdn(i, l) = res\n", " end do\n", " end do\n", "\n", " do i = 1, nc\n", " do j = 1, nc\n", " do l = 1, nc\n", " t4 = 0.0d0\n", " do k = 1, nc\n", " t4 = t4 + dphididj(k, i, j)*n(k)*tau(l, k)\n", " end do\n", " res = t4 + dphidi(j, i)*tau(l, j) + dphidj(i, j)*tau(l, i)\n", " dfdndn(i, j, l) = res\n", " end do\n", " end do\n", " end do\n", "\n", "end subroutine f_derivs\n", "\n" ] } ], "source": [ "phi_k = idx_function(r\"\\phi\")(n[k])\n", "tau_lk = idx_function(r\"\\tau\")(l, k, T)\n", "\n", "expr2 = sum_components(n[k] * phi_k * tau_lk, k)\n", "diff2 = DiffPlz(\n", " expr2, internal_functions=[phi_k, tau_lk], indexes=[k, l], name=\"f\"\n", ")\n", "\n", "print(td.to_fortran(diff2, derivatives=[\"dt\", \"dni\", \"dnidnj\"]))" ] }, { "cell_type": "markdown", "id": "b5a1a0ba", "metadata": {}, "source": [ "The placeholders became `phi`, `tau` and `dtaudT`, `dphidi` arrays that the\n", "caller must supply. If you would rather get an error instead of silently\n", "exposing arguments, ask for `strict` mode." ] }, { "cell_type": "code", "execution_count": 7, "id": "f8de5675", "metadata": { "execution": { "iopub.execute_input": "2026-10-15T21:02:48.609245Z", "iopub.status.busy": "2026-10-15T21:02:48.608900Z", "iopub.status.idle": "2026-10-15T21:02:48.615809Z", "shell.execute_reply": "2026-10-15T21:02:48.613964Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ValueError: Expression contains unresolved functions or derivatives (strict mode): \\phi(n[k]), \\tau(l, k, T)\n" ] } ], "source": [ "try:\n", " td.to_fortran(diff2, strict=True)\n", "except ValueError as exc:\n", " print(\"ValueError:\", exc)" ] }, { "cell_type": "markdown", "id": "593cd456", "metadata": {}, "source": [ "## Notes\n", "\n", "* The subroutine is named after the `DiffPlz` name with a `_derivs` suffix\n", " (`f_derivs`, `x_k_derivs`, ...). Use the `subroutine_name` argument to\n", " change it.\n", "* The independent variables appear as `n(:)`, `V`, `P`, `T`; free symbols\n", " become individual `real(8)` parameters, and free `IndexedBase` objects\n", " become `real(8)` arrays.\n", "* Free indices of the expression become extra array dimensions of the\n", " outputs, so index-based models yield vector, matrix or higher-rank\n", " derivatives.\n", "* Sums whose value does not depend on the free indices are recomputed inside\n", " the loops (correct, but not yet optimised)." ] } ], "metadata": { "kernelspec": { "display_name": "thermodiff", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.7" } }, "nbformat": 4, "nbformat_minor": 5 }