This page was generated from docs/Examples/PhaseDiagrams/PhaseDiagram_example.ipynb. Interactive online version: Binder badge.

Python Notebook Download

Phase Diagram calculations

  • Given a set composition we can use ptt to assess the phase stability at different P-T conditions to construct a phase diagram.

  • These calculations can be performed with either the MELTS or Holland & Powell family of thermodynamic models (through MAGEMin).

  • Also use outputs to assess the variability in key geochemical parameters across P-T space (e.g., phase proportions or chemistry).

Before any calculations can be run users need to download the alphaMELTS for MATLAB files and/or install the MAGEMinCalc and juliacall packages. Please see the installation guide on ReadTheDocs.

[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# If the alphaMELTS for Python files have not been added to your Python path (see installation guide) then use the two lines below to add
# the location of the alphaMELTS files here.
# import sys
# sys.path.append(r'C:\Users\penny\Box\Berkeley_new\MELTS_Installation\alphamelts_py\alphamelts-py-2.3.1-win64')


import petthermotools as ptt

ptt.__version__

# %matplotlib widget
alphaMELTS for Python files successfully located.
If you are planning on using the Green et al. (2025) or Weller et al. (2024) thermodynamic models through MAGEMin for crystallization, melting, or phase diagram calculations
you will need to run `ptt.activate_petthermotools_env()` at the start of each notebook, prior to any calculations, every time you restart the kernel.
This step establishes the python-julia connection and sets up the julia workers. Expect it to take about 20-40s on most machines.
[1]:
'1.3.4'
[2]:
ptt.activate_petthermotools_env()
Initializing MAGEMin environment and workers...
Julia environment detected.
Detected IPython. Loading juliacall extension. See https://juliapy.github.io/PythonCall.jl/stable/compat/#IPython
  Activating project at `~/.petthermotools_julia_env`
Using libMAGEMin.dylib from MAGEMin_jll
  Activating project at `~/.petthermotools_julia_env`
      From worker 5:      Activating project at `~/.petthermotools_julia_env`
      From worker 3:      Activating project at `~/.petthermotools_julia_env`
      From worker 2:      Activating project at `~/.petthermotools_julia_env`
      From worker 4:      Activating project at `~/.petthermotools_julia_env`
      From worker 3:    Using libMAGEMin.dylib from MAGEMin_jll
      From worker 4:    Using libMAGEMin.dylib from MAGEMin_jll
      From worker 5:    Using libMAGEMin.dylib from MAGEMin_jll
      From worker 2:    Using libMAGEMin.dylib from MAGEMin_jll
Julia Environment and Workers Ready.
MAGEMinCalc v0.6.4, MAGEMin_C v2.2.6

As in all examples we will import the key packages including ptt. The only difference here is that we will also use %matplotlib widget to make the phase diagram plots interactive (more explanation later).

Calculations using MELTS

For simplicity we’re going to use one of the ‘in-built’ compostiions from ptt, specifically the composition of the KLB-1 peridotite. For the purposes of the MELTS calculations below we will set the K2O content to 0.0 wt% (otherwise the system will always stabilize melt as it doesn’t have an alternative option for where to place the K2O). The calculations here will be performed using the “pMELTS” thermodynamic model as it is the most appropriate for mantle conditions and compositions.

[3]:
KLB1 = ptt.Compositions['KLB-1']
KLB1['K2O_Liq'] = 0.0

We can now run ptt.phaseDiagram_calc which takes an array of pressure and temperature conditions and evaluates the equilibrium assemblage at each combination of values. The import parameters to tweak are:

  1. The i_max parameters determines the maximum number of iterations that the code will loop through (a new loop is started if one calculation fails) unless every point either has a solution or hits a failure point. Smaller i_max, more likely to have holes in the phase diagram (as if one calculation kills a subprocess with 7 more calculations to run, you will get 7 holes until you have i_max>1). 15 is generally a good value to use.

  2. The refine = 2 parameter helps refine the phase boundaries. Consider that your 25 pressure and temperature points creates the grid shown below. Initially, the phase boundary between olivine and liquid is put at the midpoint between the solved values. Refinement.png What the first refine step does is insert a new calculation anywhere two neighbouring points have a different phase assemble (the red dots). These are then solved, and the position of the phase boundary is obtained at a higher precision. To ensure that the matrix has a constant point spacing, new points are inserted between existing points with the same phase (e.g. the point between Ol - Ol is filled with olivine - in this diagram, these are the smaller circles in panel c). refine=2 would do this again after the first refinement stage.

[4]:
Res = ptt.phaseDiagram_calc(Model = "pMELTS", bulk = KLB1,
                            P_bar = np.linspace(2000.0,40000.0, 25),
                            T_C = np.linspace(1200.0, 1800.0, 25),
                            i_max = 15, refine = 2)
Attempt 0
Attempt 1
Performing another 405 calculations with interpolation used to calculate 1371 points.
Attempt 0
Performing another 873 calculations with interpolation used to calculate 6135 points.
Attempt 0
Attempt 1
[5]:
Res
[5]:
T_C P_bar mass_g H_J S_J/K V_cm^3 rho_kg/m^3 log10(fO2) dVdP_cm^3/bar SiO2_Cpx ... H_J_Plag S_J/K_Plag Cp_J/(kg.K^2)_Plag dCpdT_J/(kg.K^2)_Plag dVdT_cm^3/K_Plag dPdT_bar/K_Plag d2VdT2_cm^3/K^2_Plag d2VdTdP_cm^3/(bar.K)_Plag d2VdP2_cm^3/bar^2_Plag molwt_Plag
0 1200.0 2000.00 100.0 -1.290945e+06 248.342444 32.721388 3056.105045 -7.000864 0.001123 53.484436 ... -1643.520239 0.286940 1231.080171 0.000014 9.888264e-07 NaN 3.528732e-10 0.0 2.980342e-13 275.839027
1 1200.0 2395.83 100.0 -1.292750e+06 246.251607 32.287103 3097.772331 -6.544221 0.001238 53.047499 ... -50200.409522 8.887601 1231.969632 0.000414 3.248555e-05 NaN 1.061085e-08 0.0 9.703500e-12 274.939946
2 1200.0 2791.67 100.0 -1.294556e+06 244.160770 31.852818 3139.439617 -6.087578 0.001352 52.610562 ... -98757.298805 17.488262 1232.859093 0.000813 6.398227e-05 NaN 2.086884e-08 0.0 1.910897e-11 274.040864
3 1200.0 3187.50 100.0 -1.294396e+06 243.415724 31.703066 3154.269062 -7.582062 0.001390 52.194557 ... -112614.894727 20.022410 1233.255137 0.000923 7.438672e-05 NaN 2.370653e-08 0.0 2.216671e-11 273.567056
4 1200.0 3583.33 100.0 -1.293229e+06 243.356610 31.676304 3156.934015 -7.605815 0.001390 52.115851 ... -109307.670290 19.461739 1233.180196 0.000895 7.249435e-05 NaN 2.301585e-08 0.0 2.159498e-11 273.489008
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
9404 1800.0 38416.67 100.0 -1.040323e+06 321.357411 32.587702 3068.642279 -3.660584 -0.000073 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
9405 1800.0 38812.50 100.0 -1.039199e+06 321.278668 32.557315 3071.514369 -3.642297 -0.000073 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
9406 1800.0 39208.33 100.0 -1.038075e+06 321.199925 32.526929 3074.386458 -3.624010 -0.000072 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
9407 1800.0 39604.17 100.0 -1.036951e+06 321.121183 32.496542 3077.258547 -3.605723 -0.000072 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
9408 1800.0 40000.00 100.0 -1.035826e+06 321.042440 32.466155 3080.130636 -3.587436 -0.000071 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

9409 rows × 219 columns

The result is a DataFrame with 97 equally spaced temperature and pressure values (so total size of 97*97). Why 97 you ask? Well initially its 25 in x and 25 in y. The refine then adds 24 points (one inbetween each point), so 49X49. The refine again adds another 48 points so (49+48) = 97 X 97. For cases where the phase assemblage of 2 neighboring points was identical the phase proportions and phase chemistry is estimated through simply linear interpolation between the two neighbors. To view the phase diagram results we can use the plot_phaseDiagram function in ptt. This will create a phase diagram labelled by number, with each number corresponding to a phase assemblage listed on the right. By using %matplotlib widget above you should be able to hover over the plot and see which number (and therefore phase assemblage) is present at each P-T condition.

[6]:
ptt.plot_phaseDiagram(Combined = Res)
../../_images/Examples_PhaseDiagrams_PhaseDiagram_example_10_0.png
[6]:
(<Figure size 1000x600 with 2 Axes>,
 array([<Axes: xlabel='Temperature ($\\degree$C)', ylabel='Pressure (bar)'>,
        <Axes: >], dtype=object))

Calculations using MAGEMin

For calculations with MAGEMin it is important to note that this is one of the major purposes for which the original MAGEMin code was developed, so it will likely always be straightforward to create phase diagrams using the MAGEMinApp (https://github.com/ComputationalThermodynamics/MAGEMinApp.jl). The point of this code is not to try and replace MAGEMin, but to provide Python users with the ability to perform calcualtions with a range of different thermodynamic models. In the cells below we repeat the calculations above with a few minor differences: (i) MAGEMin (and the Green et al. 2025 thermodynamic model) does not have the same issue as pMELTS when small amounts of K2O are included in the bulk composition; (ii) the Model kwarg is changed to Green2025 which will initiate the calculation in julia via MAGEMin

[7]:
KLB1 = ptt.Compositions['KLB-1']
KLB1
[7]:
{'SiO2_Liq': 44.48,
 'TiO2_Liq': 0.16,
 'Al2O3_Liq': 3.59,
 'FeOt_Liq': 8.1,
 'MgO_Liq': 39.22,
 'CaO_Liq': 3.44,
 'Na2O_Liq': 0.3,
 'K2O_Liq': 0.0,
 'Cr2O3_Liq': 0.42,
 'H2O_Liq': 0.0,
 'Fe3Fet_Liq': 0.04}
[8]:
Res_green = ptt.phaseDiagram_calc(Model = "Green2025", bulk = KLB1,
                            P_bar = np.linspace(2000.0,40000.0, 25),
                            T_C = np.linspace(1200.0, 1800.0, 25),
                            i_max = 15, refine=2)
Computing 157 points... 100%|████████████████████████████| Time: 0:00:15
Computing 156 points... 100%|████████████████████████████| Time: 0:00:17
Computing 156 points... 100%|████████████████████████████| Time: 0:00:20
Computing 156 points... 100%|████████████████████████████| Time: 0:00:21
Performing another 395 calculations with interpolation used to calculate 1381 points.
Computing 99 points... 100%|█████████████████████████████| Time: 0:00:08
Computing 99 points... 100%|█████████████████████████████| Time: 0:00:09
Computing 98 points... 100%|█████████████████████████████| Time: 0:00:10
Computing 99 points... 100%|█████████████████████████████| Time: 0:00:10
Performing another 881 calculations with interpolation used to calculate 6127 points.
Computing 220 points... 100%|████████████████████████████| Time: 0:00:24
Computing 221 points... 100%|████████████████████████████| Time: 0:00:27
Computing 220 points... 100%|████████████████████████████| Time: 0:00:28
Computing 220 points... 100%|████████████████████████████| Time: 0:00:29
[9]:
ptt.plot_phaseDiagram_multi({"Green et al. (2025)": Res_green, "pMELTS (Ghiorso et al. 2002)": Res})
[9]:
(<Figure size 1200x1200 with 3 Axes>,
 [<Axes: title={'center': 'Green et al. (2025)'}, xlabel='Temperature ($\\degree$C)', ylabel='Pressure (bar)'>,
  <Axes: title={'center': 'pMELTS (Ghiorso et al. 2002)'}, xlabel='Temperature ($\\degree$C)', ylabel='Pressure (bar)'>,
  <Axes: >])
../../_images/Examples_PhaseDiagrams_PhaseDiagram_example_14_1.png
[10]:
f, a = ptt.plot_phaseDiagram(Combined = Res_green)
../../_images/Examples_PhaseDiagrams_PhaseDiagram_example_15_0.png

Extracting more information from the phase diagram calculations

In addition to the phase diagrams shown above it is relatively simple to extract additional information from the calculations. For example, it is trivial to extract the mass of liquid (mass fraction) at each point and reshape this array into a P-T grid so that we can visualize this data as contours.

The function make_grid_variables_from_phase_diagram takes your dataframe output, and puts it into a PT grid. This allows for easier plotting.

[11]:
X, Y, Z = ptt.make_grid_variables_from_phase_diagram(
    Results = Res_green,
    x_col = "T_C",
    y_col = "P_bar",
)

liq = Z["mass_g_Liq"]

From here we can use the plt.contourf function to visualize the mass fraction of melt at each P-T value:

[12]:
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(
    1, 2, figsize=(10, 4), sharex=True, sharey=True
)

# ------------------------------------------------
# Panel 1: mass_g_Liq (red colormap)
# ------------------------------------------------
pcm1 = ax1.pcolormesh(
    X, Y, Z["mass_g_Liq"],
    shading="auto",
    cmap="Reds"
)
ax1.set_title("mass_g_Liq")
ax1.set_xlabel("T (°C)")
ax1.set_ylabel("P (bar)")
fig.colorbar(pcm1, ax=ax1, label="mass_g_Liq")

# ------------------------------------------------
# Panel 2: SiO2_Liq (same red colormap)
# ------------------------------------------------
pcm2 = ax2.pcolormesh(
    X, Y, Z["SiO2_Liq"],
    shading="auto",
    cmap="Reds"
)
ax2.set_title("SiO$_2$ (liq)")
ax2.set_xlabel("T (°C)")
fig.colorbar(pcm2, ax=ax2, label="SiO$_2$ (wt %)")

plt.tight_layout()
plt.show()

../../_images/Examples_PhaseDiagrams_PhaseDiagram_example_19_0.png
[13]:
Res_green.columns
[13]:
Index(['T_C', 'P_bar', 'mass_g', 'H_J', 'S_J/K', 'V_cm^3', 'rho_kg/m^3',
       'log10(fO2)', 'mass_per_mole_g/mol', 'eta_Pa.s',
       ...
       'mass_g_Plag', 'rho_kg/m^3_Plag', 'V_cm^3_Plag', 'H_J_Plag',
       'S_J/K_Plag', 'Cp_J/(kg.K^2)_Plag', 'mass%_Plag', 'mol%_Plag',
       'vol%_Plag', 'alpha_1/K_Plag'],
      dtype='str', length=160)

Alternatively we could assess the proportion of garnet and spinel in the system, examining the position of the garnet-spinel transition.

[14]:
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(
    1, 2, figsize=(10, 4), sharex=True, sharey=True
)

# ------------------------------------------------
# Panel 1: mass_g_Grt (red colormap)
# ------------------------------------------------
pcm1 = ax1.pcolormesh(
    X, Y, Z['mass_g_Grt'],
    shading="auto",
    cmap="Reds"
)
ax1.set_title("mass_g_Grt")
ax1.set_xlabel("T (°C)")
ax1.set_ylabel("P (bar)")
fig.colorbar(pcm1, ax=ax1, label="mass_g_Grt")

# ------------------------------------------------
# Panel 2: mass_g_Sp (blue colormap)
# ------------------------------------------------
pcm2 = ax2.pcolormesh(
    X, Y, Z['mass_g_Sp'],
    shading="auto",
    cmap="Blues"
)
ax2.set_title("mass_g_Sp")
ax2.set_xlabel("T (°C)")
fig.colorbar(pcm2, ax=ax2, label="mass_g_Sp")

plt.tight_layout()
plt.show()

../../_images/Examples_PhaseDiagrams_PhaseDiagram_example_22_0.png

Phase Diagram of pyroxenite lithologies

Alternatively we could create phase diagram for other, potential mantle lithologies. Shown as an example here is a phase diagram calculation for the KG1 pyroxenite.

[15]:
KG1 = ptt.Compositions['KG1']
[16]:
KG1_green = ptt.phaseDiagram_calc(Model = "Green2025", bulk = KG1,
                            P_bar = np.linspace(2000.0,40000.0, 25),
                            T_C = np.linspace(1200.0, 1800.0, 25),
                            i_max = 15, refine = 2)
Computing 157 points... 100%|████████████████████████████| Time: 0:00:22
Computing 156 points... 100%|████████████████████████████| Time: 0:00:25
Computing 156 points... 100%|████████████████████████████| Time: 0:00:28
Computing 156 points... 100%|████████████████████████████| Time: 0:00:28
Performing another 425 calculations with interpolation used to calculate 1351 points.
Computing 106 points... 100%|████████████████████████████| Time: 0:00:15
Computing 106 points... 100%|████████████████████████████| Time: 0:00:15
Computing 106 points... 100%|████████████████████████████| Time: 0:00:16
Computing 107 points... 100%|████████████████████████████| Time: 0:00:17
Performing another 969 calculations with interpolation used to calculate 6039 points.
Computing 242 points... 100%|████████████████████████████| Time: 0:00:34
Computing 242 points... 100%|████████████████████████████| Time: 0:00:35
Computing 242 points... 100%|████████████████████████████| Time: 0:00:37
Computing 243 points... 100%|████████████████████████████| Time: 0:00:39
[17]:
f, a = ptt.plot_phaseDiagram(Combined = KG1_green)
../../_images/Examples_PhaseDiagrams_PhaseDiagram_example_26_0.png
[ ]: