Sympy is a Python package used for solving equations using symbolic math.
Let's solve the following problem with SymPy.
The density of two different polymer samples $\rho_1$ and $\rho_2$ are measured.
$$ \rho_1 = 0.904 \ g/cm^3 $$$$ \rho_2 = 0.895 \ g/cm^3 $$The percent crystalinity of the two samples ($\%c_1 $ and $\%c_2$) is known.
$$ \%c_1 = 62.8 \% $$$$ \%c_2 = 54.4 \% $$The percent crystalinity of a polymer sample is related to the density of 100% amorphus regions ($\rho_a$) and 100% crystaline regions ($\rho_c$) according to:
$$ \%crystallinity = \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% $$
In [1]:
from sympy import symbols, nonlinsolve
We need to define six different symbols: $$\rho_c, \rho_a, \rho_1, \rho_2, c_1, c_2$$
In [2]:
pc, pa, p1, p2, c1, c2 = symbols('pc pa p1 p2 c1 c2')
Next we'll create two expressions for our two equations. We can subtract the %crystallinity from the left side of the equation to set the equation to zero.
$$ \%crystallinity = \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% $$$$ \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% - \%crystallinity = 0 $$Sub in $\rho_s = \rho_1$ and $\rho_s = \rho_2$ to each of the expressions.
In [3]:
expr1 = ( (pc*(p1-pa) ) / (p1*(pc-pa)) - c1)
expr2 = ( (pc*(p2-pa) ) / (p2*(pc-pa)) - c2)
Now we'll substitue in the values of $\rho_1 = 0.904$ and $c_1 = 0.628$ into our first expression.
In [4]:
expr1 = expr1.subs(p1, 0.904)
In [5]:
expr1 = expr1.subs(c1, 0.628)
In [6]:
expr1
Out[6]:
Now we'll substitue our the values of $\rho_2 = 0.895$ and $c_2 = 0.544$ into our second expression.
In [7]:
expr2 = expr2.subs(p2, 0.895)
In [8]:
expr2 = expr2.subs(c2, 0.544)
In [9]:
expr2
Out[9]:
To solve the two equations for the to unknows $\rho_a$ and $\rho_b$, use SymPy's nonlinsolve()
function. Pass in a list of the two expressions and followed by a list of the two variables to solve for.
In [10]:
nonlinsolve([expr1,expr2],[pa,pc])
Out[10]:
We see that the value of $\rho_a = 0.840789$ and $\rho_c = 0.94613431$.
The solution is a SymPy FiniteSet
object. To pull the values of $\rho_a$ and $\rho_c$ out of the FiniteSet
, use the syntax sol.args[0][<var num>]
.
In [11]:
sol = nonlinsolve([expr1,expr2],[pa,pc])
In [12]:
type(sol)
Out[12]:
In [13]:
sol.args
Out[13]:
In [14]:
sol.args[0]
Out[14]:
In [15]:
sol.args[0][0]
Out[15]:
In [16]:
pa = sol.args[0][0]
pc = sol.args[0][1]
print(f' Density of 100% amorphous polymer, pa = {round(pa,2)} g/cm3')
print(f' Density of 100% crystaline polymer, pc = {round(pc,2)} g/cm3')
In [ ]: