Tutorial: the basics¶
First Example: Mole Fraction¶
As a first example, we will compute all derivatives of a function that depends only on composition.
A natural choice for this purpose is the mole fraction.
[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
# You can also do: "import thermodiff as td", and access to all this things.
from thermodiff import idx_function # Index based functions
from thermodiff import sum_components # Sympy summation over component number
from thermodiff import sum_custom # Sympy summation over custom limits
from thermodiff import n # Mole number vector
from thermodiff import T # Temperature
from thermodiff import P # Pressure
from thermodiff import V # Volume
from thermodiff import R # Ideal gas constant
from thermodiff import nc # Number of components in the mixture
from thermodiff import k, l, m # indexes for summations
from thermodiff import DiffPlz # Class that makes the derivatives
# We may still need sympy for some things.
import sympy as sp
# To display latext code in the notebook.
from IPython.display import display, Math
The mole fraction is an index-based function of the mole number vector:
In all expressions, we use \(k\), \(l\), and \(m\) as indices, while \(i\) and \(j\) are reserved for differentiation.
Thermodiff provides a convenient way to define an index-based function:
[2]:
# index based function with lazy derivatives function of mole numbers n
xk = idx_function("x")(n[k])
xk
[2]:
This is how we define an index-based function in Thermodiff that depends on mole composition. In this case:
Yes, this is not exactly the same as the full definition above—but it is a convenient way to keep track of the index and preserve the ¿derivability? of the function.
Now, let’s see what “lazy derivatives” actually mean:
[3]:
diff = DiffPlz(xk, [xk], [k], "x")
The arguments of the DiffPlz class are:
expression : sympy expression The thermodynamic expression to differentiate.
internal_functions : list of sympy functions List of sympy functions that are used in the expression.
indexes : list of sympy Idx List of sympy Idx that are used in the expression. These are usually the indexes for the number of moles, like [k, l, m].
name : str, optional Name of the DiffClass instance, by default “f”. It could be for example the name of the thermodynamic function you are working with, like “G^E” or “A^r”.
We can check the derivatives results by the object attributes:
[4]:
diff.dni
[4]:
[5]:
diff.dnidnj
[5]:
[6]:
diff.dt
[6]:
As you can see, index-based functions with their “lazy derivatives” represent derivatives symbolically, indicating how the function should be differentiated rather than evaluating them immediately.
For example, in the case of \(dt\) (the temperature derivative), the result is \(0\), as expected. You can verify this yourself for the volume and pressure derivatives, \(dv\) and \(dp\).
This approach is useful when you want to include functions in your expressions that do not have an explicit form. You can later compute the derivatives of those functions separately.
Before trully differentiating any expression, let’s examine what the latex_readable_plz method does:
[7]:
latex = diff.latex_readable_plz()
latex
[7]:
{'dT': '0',
'dV': '0',
'dP': '0',
'dT2': '0',
'dV2': '0',
'dP2': '0',
'dn2': '\\frac{\\partial^2 x_{k}}{\\partial n_i \\partial n_j}',
'dTn': '0',
'dVn': '0',
'dPn': '0',
'dTV': '0',
'dTP': '0',
'dVP': '0',
'dni': '\\frac{\\partial x_{k}}{\\partial n_i}'}
The method returns a dictionary containing the LaTeX representation of the function derivatives.
It attempts to simplify the expressions as much as possible, although results may vary. Since this is mainly a personal-use tool, the method was heavily vibe-coded, so don’t be surprised if some expressions refuse to simplify all the way.
[8]:
display(Math(latex["dni"]))
As you can see, the method tries its best to return a more expected result, ready to be displayed in a notebook or a report.
After that, let’s compute the actual derivatives of the mole fraction. For this, we can use a Thermodiff shortcut for summations:
[9]:
expr = n[k] / sum_components(n[l], l)
expr
[9]:
Now we plz differentiate:
[10]:
diff_plz = DiffPlz(expr, internal_functions=None, indexes=[k, l], name="x_k")
[11]:
diff_plz.dni
[11]:
[12]:
diff_plz.dnidnj
[12]:
As you can see, Thermodiff automatically handles the ugly Kronecker delta functions. In this case, those Kronecker deltas turn into piecewise functions, which are much readable.
Second Example: Summation of indexed functions¶
Let’s analyze what happens when we have a summation involving index-based functions. Consider a term like:
where \(\phi_k\) and \(\tau_{lk}\) are index-based functions.
For example, \(\phi_k\) could be a function of the mole number vector:
Something similar to the UNIQUAC terms (where \(r_k\) is a constant parameter):
On the other hand, \(\tau_{lk}\) could be defined as:
Here, the indices \(l\) and \(k\) refer to binary interaction parameters between components \(l\) and \(k\).
The key difference between these functions is the following:
\(\phi_k\) depends on the mole number vector, and its index represents component \(k\).
\(\tau_{lk}\) depends only on temperature, but its indices represent a pair of components.
Since \(\tau_{lk}\) is not a function of the mole number vector, its derivative with respect to \(\mathbf{n}\) is zero. Because of this, we need to construct these functions differently:
[13]:
phi_k = idx_function(r"\phi")(n[k])
phi_k
[13]:
Check how \(\phi_k\) is defined (just like we did before with the mole fraction). The function symbol is simply \(\phi\), and it is defined as a function of the mole number of component \(k\).
This way, the subscript of the function naturally follows the subscript of its argument (or this is the way I want you to read it, at least).
We will clean up this representation later, don’t worry.
[14]:
tau_lk = idx_function(r"\tau")(l, k, T)
tau_lk
[14]:
Notice that for the function \(\tau_{lk}\), the symbol is simply \(\tau\). It is defined as a function of temperature, while \(l\) and \(k\) are treated as indices.
This way, the subscripts of the function are tracked through the arguments:
However, unlike \(\phi_k\), this function does not depend on \(\mathbf{n}\) vector.
Now, let’s build our expression:
[15]:
expr = sum_components(n[k] * phi_k * tau_lk, k)
expr
[15]:
You can also use the sum_custom function for more custom summation scenarios. In this case to recreate the same expression with that function:
[16]:
sum_custom(
n[k] * phi_k * tau_lk,
idx=k,
start=1,
end=nc
)
[16]:
I’m used to reading these expressions by mentally moving the subscripts from the arguments back to the function symbols. Not perfect, but it gets the job done.
Now, let’s differentiate:
[17]:
diff = DiffPlz(expr, internal_functions=[phi_k, tau_lk], indexes=[k, l], name="f")
[18]:
diff.dni
[18]:
Pay attention to how the subscripts take the values \(i\) and \(j\) when differentiating with respect to \(n_i\) and \(n_j\).
[19]:
diff.dnidnj
[19]:
[20]:
# Temperature derivative:
diff.dt
[20]:
[21]:
diff.dt2
[21]:
[22]:
diff.dtdni
[22]:
Now let’s use latex_readable_plz to obtain a more readable version of the derivatives:
[23]:
latex = diff.latex_readable_plz()
latex
[23]:
{'dT': '\\sum_{k=1}^{N_{c}} \\frac{\\partial \\tau_{lk}}{\\partial T} \\phi_{k} {n}_{k}',
'dV': '0',
'dP': '0',
'dT2': '\\sum_{k=1}^{N_{c}} \\frac{\\partial^2 \\tau_{lk}}{\\partial T^2} \\phi_{k} {n}_{k}',
'dV2': '0',
'dP2': '0',
'dn2': '\\frac{\\partial \\phi_{i}}{\\partial n_j} \\tau_{li} + \\frac{\\partial \\phi_{j}}{\\partial n_i} \\tau_{lj} + \\sum_{k=1}^{N_{c}} \\frac{\\partial^2 \\phi_{k}}{\\partial n_i \\partial n_j} \\tau_{lk} {n}_{k}',
'dTn': '\\frac{\\partial \\tau_{li}}{\\partial T} \\phi_{i} + \\sum_{k=1}^{N_{c}} \\frac{\\partial \\phi_{k}}{\\partial n_i} \\frac{\\partial \\tau_{lk}}{\\partial T} {n}_{k}',
'dVn': '0',
'dPn': '0',
'dTV': '0',
'dTP': '0',
'dVP': '0',
'dni': '\\phi_{i} \\tau_{li} + \\sum_{k=1}^{N_{c}} \\frac{\\partial \\phi_{k}}{\\partial n_i} \\tau_{lk} {n}_{k}'}
[24]:
derivs = ["dT", "dT2", "dni", "dn2", "dTn"]
for d in derivs:
print(f"Derivative {d}:")
display(Math(latex[d]))
Derivative dT:
Derivative dT2:
Derivative dni:
Derivative dn2:
Derivative dTn:
Third Example: Specific simplification case¶
Check the following expression (from UNIQUAC model):
In this case I want the derivatives of \(\tau_{lk}\) (of course \(a_{lk}\), \(b_{lk}\), etc. are just binary interaction parameters). In this case, we don’t care about compositional derivatives, so i’m going to define the parameters as normal variables (not SimPy index-based variables):
[25]:
a_lk = sp.Symbol("a_{lk}")
b_lk = sp.Symbol("b_{lk}")
c_lk = sp.Symbol("c_{lk}")
d_lk = sp.Symbol("d_{lk}")
e_lk = sp.Symbol("e_{lk}")
tau_lk_expr = sp.exp(
a_lk + b_lk / T + c_lk * sp.ln(T) + d_lk * T + e_lk * T**2
)
tau_lk_expr
[25]:
Now, let’s differentiate:
[26]:
diff = DiffPlz(tau_lk_expr, internal_functions=None, indexes=[l, k], name=r"\tau_{lk}")
[27]:
diff.dt
[27]:
[28]:
diff.dt2
[28]:
You will quickly notice that these temperature derivatives are quite messy. Since they come from derivatives of an exponential function, they typically have the form:
We can use the clean_plz method so that the DiffPlz instance attempts to simplify these expressions. This will not always succeed, but in this case, it works well.
[29]:
help(diff.clean_plz)
Help on method clean_plz in module thermodiff.diffplz:
clean_plz(derivs_to_clean: list[str] | None = None) method of thermodiff.diffplz.DiffPlz instance
Clean the DiffPlz instance.
This method applies known simplification patterns to the differentiated
expressions in the DiffPlz instance.
Parameters
----------
derivs_to_clean : list[str], optional
List of derivative keys to clean. If None, all derivatives will be
cleaned. The possible keys are: "dT", "dV", "dP", "dni", "dT2",
"dV2", "dP2", "dnidnj", "dTn", "dVn", "dPn", "dTV", "dTP", "dVP".
By reading the documentation of the method, we have to provide the derivatives that we want to “clean”. In this case we are only interested in the temperature derivatives, so we will provide the keys: dT and dT2. The method will then attempt to simplify the expressions for only these derivatives and then the attributes dt and dt2 will be updated with the simplified expressions. The other derivatives will remain unchanged. If you do not provide any keys, the method will attempt to
simplify all derivatives (not recommended).
[30]:
diff.clean_plz(["dT", "dT2"])
[31]:
diff.dt
[31]:
[32]:
diff.dt2
[32]:
As you can see, a basic “cleaning” pattern is to detect whether the original function (in this case \(\tau_{lk}\)) appears in the “dirty” derivatives. The method then replaces those occurrences with the function’s symbolic name.
Now, lets make our readable LaTeX version of the derivatives as before:
[33]:
latex = diff.latex_readable_plz()
display(Math(latex["dT"]))
display(Math(latex["dT"]))
OH NO! Why didn’t it simplify the \((T)\) in \(\tau_{lk}(T)\)?
That’s because latex_readable_plz doesn’t know that \(\tau_{lk}(T)\) is an internal function of the expression (we passed None to the DiffPlz instance).
Yeah… kind of a dumb thing. The previous expressions are fine, but if you really want latex_readable_plz to behave properly, you need to explicitly include \(\tau_{lk}(T)\) as an internal function in the DiffPlz instance.
This ends up being a bit of an iterative process: you notice that clean_plz produces something like this, then you go back and improve your instance definition.
[ ]:
# We add the symbol for the function that will appear in the derivatives after
# cleaning
tau_symbol = sp.Function(r"\tau_{lk}")(T)
diff = DiffPlz(tau_lk_expr, internal_functions=[tau_symbol], indexes=[l, k], name=r"\tau_{lk}")
diff.clean_plz(["dT", "dT2"])
latex = diff.latex_readable_plz()
display(Math(latex["dT"]))
display(Math(latex["dT2"]))
That’s pretty much all the tricks you need to keep in mind when working with DiffPlz instances. The rest is just practice… and a bit of messing around.
For a more complete and realistic example, check the MHV differentiation notebook, where DiffPlz is used in a more complex setting.