Pycalphad
K-DenseCommunityCreated by K-Dense Inc.
- Skill
- Workflow
- Science and research
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured workflow for computing finite-temperature CALPHAD equilibria, including phase fractions and compositions. It leverages the pycalphad library to process thermodynamic TDB databases, enabling users to perform equilibrium temperature sweeps, tie-line analysis, and lever-rule checks. The workflow emphasizes reproducible calculations by requiring explicit component mole fractions and pressure conditions, while providing robust numerical validation through mass-balance and sampling-density checks.
What it does
- Computes equilibrium phase fractions and compositions at specified temperatures and pressures.
- Validates results using mass-balance checks and sampling density refinement.
- Exports detailed equilibrium reports including Gibbs energy and phase-specific data.
- Supports analysis of miscibility gaps and phase stability within defined thermodynamic models.
- Provides a standardized interface for TDB-based thermodynamic modeling.
When to use it
- When you need to determine stable phase fractions for an alloy at specific temperatures.
- When performing equilibrium temperature sweeps to identify phase transition points.
- When verifying thermodynamic consistency of a TDB model through common-tangent or lever-rule checks.
- When you require a reproducible, automated pipeline for phase-constitution analysis.
Advantages
- Ensures reproducible results through explicit condition handling and numerical validation.
- Integrates directly with pycalphad for reliable thermodynamic equilibrium calculations.
- Provides comprehensive output including system Gibbs energy and phase-specific compositions.
- Includes automated checks for mass balance and sampling stability.
Usage examples
- “Calculate the equilibrium phase fractions for a Cu-Ni alloy at 1100 K using the provided TDB file.”
- The agent executes the equilibrium script, returning the molar phase fractions for FCC_A1 and LIQUID phases along with their respective compositions.
- “Perform a temperature sweep from 900 K to 1300 K for a specific bulk composition.”
- The agent runs the calculation across the requested temperature range, generating a report with stable phase vertices and mass-balance verification for each step.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/k-dense-ai/pycalphad/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip pycalphad.zip -d .agents/skills
Documentation by K-Dense Inc.
pycalphad: TDB equilibrium calculations
When to use
Use for equilibrium phase fractions and compositions at a fixed bulk elemental mole composition, specified pressure, and a list of finite temperatures. The bundled helper executes real pycalphad equilibria, checks mass balance, repeats at greater sampling density, and exports each stable composition set separately.
Equilibrium is constrained by the selected database, components, phases, and conditions. It does not predict precipitation rates, retained metastable microstructures, or properties of phases missing from the database. Successful numerical checks do not establish the database's experimental accuracy.
Workflow
Identify the TDB's source, license, assessment/publication, valid temperature/pressure and composition range, and required elements. Use the user's database for real alloys. The bundled assets/ideal-cu-ni.tdb is an original hypothetical teaching model, not an assessed Cu-Ni database.
Inspect database elements and phases. Select the relevant phases deliberately; record exclusions because they can turn the calculation into a metastable constrained result. Include
VAwhere required by sublattice models. Vacancies are not an independent bulk mole fraction. Keep coupled order/disorder definitions in the TDB, but do not select both partners as separate candidates when the ordered model already includes the disordered contribution; the helper rejects such filtered candidate lists.Copy assets/equilibrium.json. Specify exactly N-1 elemental mole fractions and one dependent non-vacancy element. The dependent fraction is
1 - sum(independent fractions); fractions are not silently normalized. Set K and Pa. Convert weight percentages or mass fractions before using this helper.Declare the database temperature interval from its assessment if known, or set
database_temperature_range_kto null if unknown. This is user-supplied evidence, not a range automatically inferred from every TDB function. Requests outside a declared interval fail. Check pressure and composition validity separately.Run the calculation. Check finite Gibbs energies, phase fractions summing to one, reconstructed bulk composition, and stability to doubled
pdens(phase-constitution sampling density). Near transitions, refine temperatures and sampling density further.Deliver phase fractions with their molar basis, phase compositions, database hash, conditions, excluded phases, and any numerical or assessment limitations.
Read references/model-and-validation.md for the analytic example, basis conversion, native Model/Workspace/property/plot contracts, miscibility-gap handling, and convergence limits.
Execute the tested example
From the collection root:
uv run --no-project --python 3.12 --with pycalphad==0.11.2 --with numpy==2.5.3 \
python skills/pycalphad/scripts/equilibrate.py \
skills/pycalphad/assets/ideal-cu-ni.tdb \
skills/pycalphad/assets/equilibrium.json equilibrium-resultTested on Python 3.12, pycalphad 0.11.2, and NumPy 2.5.3. Use a new output directory. All thermodynamic calculations are local; the script does not upload a TDB.
For the supplied hypothetical model at X(Ni)=0.5 and 101325 Pa:
| Temperature | Equilibrium result |
|---|---|
| 900 K | FCC_A1 only |
| 1100 K | 0.5 FCC_A1 + 0.5 LIQUID; X(Ni) approximately 0.527307 and 0.472693 respectively |
| 1300 K | LIQUID only |
The suite verifies analytic common-tangent compositions, a noncentral lever-rule case, Gibbs energy, mass balance, both single-phase limits, and actual same-phase miscibility gap vertices. These validate the computational workflow, not real Cu-Ni metallurgy.
Outputs and acceptance
report.json: settings and versions, TDB/settings SHA-256, excluded database phases, requested, solver-imposed, and reconstructed bulk compositions, per-temperature baseline/refined results, and checks. Experimental validity is not evaluated by the helper.phase-equilibria.csv: one row per stable vertex per temperature and sampling run, including phase name, molar phase fraction, and elemental mole fractions. Its Gibbs energy column is the whole-system molar Gibbs energy, repeated for each vertex; it is not the individual phase energy.
Unused pycalphad vertices have blank names and NaN values; those are omitted. Named vertices with invalid values cause failure. Multiple vertices with the same phase name are retained because a miscibility gap can contain two composition sets of one phase. Vertex indices do not track the same physical phase continuously across temperatures.
In stable 0.11.2, pycalphad clips independent mole fractions to [1e-10, 1-1e-10].
Each result records solver_bulk_mole_fractions and the largest absolute difference
from the requested bulk in composition_condition_adjustment_absolute_error.
Mass-balance checks still compare against the requested composition; a tighter
tolerance can therefore fail at an endpoint. Do not claim exact pure-component or
ultratrace results from a clipped multicomponent calculation.
all_checks_passed requires each run's phase-sum and bulk-composition residuals within
mass_balance_tolerance, phase totals stable within phase_fraction_tolerance, and
system Gibbs energy stable within gibbs_energy_tolerance_j_per_mol when pdens doubles.
This comparison does not certify the global minimum or track individual composition-set
movement within a same-phase miscibility gap; inspect their exported compositions too.
Failed checks remain visible in the report rather than being relabeled as convergence.
Boundaries and upstream contracts
The helper handles elemental mole fractions, one composition, one pressure, and up to 1000 explicit positive temperatures. It validates selected phases through pycalphad's phase-compatibility rules; incompatible or automatically filtered order/disorder phase sets produce an explicit error. It does not silently remove requested phases.
Charged-species constraints, externally imposed chemical potentials, custom models, activity reference-state changes, and database optimization require additional modeling and are outside this helper's tested scope. Do not extrapolate the pedagogical asset to real material selection or heat-treatment decisions.
Upstream latest documentation currently describes 0.11.3 development builds. The
bundled helper and the reference's native examples were exercised against stable
0.11.2 on 2026-10-01; the release's source was checked against the installed wheel.
No remote thermodynamic calculation or database-fetch API is used. Database loads a
local path, file-like object, or TDB text; a URL is not a supported download shortcut.
Files
- ATTRIBUTION.mdAdded by AutoGineer913 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md8.0 KiB
- assets/equilibrium.json443 B
- assets/ideal-cu-ni.tdb702 B
- references/model-and-validation.md9.8 KiB
- scripts/equilibrate.pyScript10.9 KiB
references/model-and-validation.md
Composition basis and equilibrium validation
Original pedagogical database
assets/ideal-cu-ni.tdb was written for this skill and is released under the skill's
MIT license. Cu and Ni are labels for a hypothetical ideal binary; there are no fitted
experimental data. The file defines one substitutional sublattice in FCC_A1 and LIQUID,
with no excess mixing terms or pressure dependence. Its functions span 298.15–2000 K.
With x = X(Ni), energies in J/mol, and R in J/(mol K):
G(FCC_A1) = R T [x ln x + (1-x) ln(1-x)].
G(LIQUID) = G(FCC_A1) + (1-x)(10000-10T) + x(12000-10T).
At T=1100 K the liquid endmember offsets are -1000 and +1000 J/mol. Equality of both component chemical potentials gives x_liquid = 1/(1+exp(1000/(RT))) and x_solid = 1-x_liquid. The phase fraction of solid at bulk x between those endpoints is (x_bulk-x_liquid)/(x_solid-x_liquid). This is an independent analytic check of the numerical common tangent, phase compositions, and lever rule. The tests use pycalphad's R=8.3145 J/(mol K); the listed decimal values are package/model-specific regression values.
The database intentionally lacks realistic heat capacities, lattice stabilities, excess mixing, magnetic terms, and pressure effects. Its apparent transitions are synthetic. Do not fit a real experiment to it or replace an assessed database with this example.
Basis conversions
For measured elemental mass fractions w_i and molar masses M_i, calculate
x_i = (w_i/M_i) / sum_j(w_j/M_j), including the dependent element. Weight percent is
first divided by 100. Store the original composition, molar masses, and converted values
with the run. The helper accepts only the resulting mole fractions and rejects a
mass_fraction basis instead of treating weight percent as atomic fraction.
NP is a molar phase fraction at total N=1. A mass phase fraction requires each phase's
composition-weighted molar mass: w_phase = NP_phaseM_phase / sum(NP_jM_j).
Volume fractions require appropriate phase densities or molar volumes as well. Do not
compare molar fractions directly to microscopy area fractions without explaining the
conversion and sampling assumptions.
For this elemental workflow, molar energies and amounts use a mole of non-vacancy
atoms, not a mole of an arbitrary compound formula unit. Model.GM is normalized on
that basis; Model.G is formula energy and can differ with sublattice site ratios.
Site fractions v.Y(phase, sublattice_index, species) are internal degrees of freedom,
not bulk mole fractions. Sublattice indices are zero-based.
The tested conversion API is v.get_mole_fractions({v.W('NI'): 0.5}, 'CU', db);
it uses the TDB elemental masses and returns a condition mapping keyed by v.X('NI').
For the bundled masses, 50 wt% Ni is X(Ni)=0.5198487558, not 0.5. No conversion is
performed by the JSON helper itself.
Native model, property, and plotting contracts
These examples were executed with pycalphad 0.11.2. Paths below are relative to the
collection root. Database(path) parses local thermodynamic data; successful parsing
does not establish that the assessment or every model feature is suitable. Review TDB
warnings rather than suppressing all warnings. db.elements, db.phases, and each
phase's constituents, sublattices, and model_hints expose the modeled system.
Model(db, components, phase) builds a symbolic energy model, not an equilibrium.
calculate(..., output='GM', T=..., P=..., pdens=...) samples its phase-constitution
surface. Its points columns are ordered internal site fractions: use the model's
site_fractions order; do not pass overall alloy compositions as points for a
multisublattice model. In the one-sublattice teaching FCC model only, [0.5, 0.5]
coincides with 50:50 bulk composition. calculate does not minimize across phases.
Pass sampling options to equilibrium or Workspace through calc_opts, not as
top-level pdens; unused equilibrium keyword arguments merely produce a warning.
import numpy as np
from pycalphad import Database, Workspace, variables as v
db = Database('skills/pycalphad/assets/ideal-cu-ni.tdb')
components = ['CU', 'NI', 'VA']
phases = ['FCC_A1', 'LIQUID']
conditions = {v.T: [900, 1100, 1300], v.P: 101325, v.N: 1, v.X('NI'): 0.5}
wks = Workspace(db, components, phases, conditions, calc_opts={'pdens': 500})
temperature = wks.get(v.T)
phase_amounts = wks.get_dict('NP(*)')
gm = wks.get('GM') # system molar Gibbs energy, J/mol
x_solid = wks.get(v.X('FCC_A1', 'NI'))
assert np.allclose(temperature, [900, 1100, 1300])
assert np.isfinite(gm).all()
assert np.isnan(x_solid[-1]) # absent solid; NaN is not a failed equilibriumUse get_dict when phase multiplicity can change. A request such as NP(FCC_A1)
or X(FCC_A1,NI) expands to #1, #2, ... properties for a miscibility gap; get
can consequently return a list of arrays rather than one array. Preserve those sets
and only sum their amounts when a total phase-name fraction is intended. Suffixes
identify solver composition sets, not permanent ordered/disordered identities.
Inspect compositions and site fractions before assigning physical labels. Property
arrays squeeze singleton condition axes; use wks.condition_axis_order for grids.
GM and HM are J/mol; SM and CPM are J/(mol K). A phase-qualified property,
such as GM(FCC_A1), is that stable composition set's property, whereas unqualified
GM is phase-amount-weighted. CPM differentiates the model at fixed constitution;
wks.get('HM.T') differentiates equilibrium enthalpy as temperature changes, including
phase amounts and internal relaxation. They need not agree. At 1100 K the hypothetical
two-phase example has CPM=0 but HM.T approximately 1005.08 J/(mol K), matching a
small central difference of equilibrium enthalpy. Derivatives at phase boundaries or
invariant points require special care; a finite derivative is not a latent-heat integral.
For a small binary phase diagram, the current top-level binplot uses the mapping API:
import matplotlib.pyplot as plt
from pycalphad import binplot
ax, strategy = binplot(
db, components, phases,
{v.T: (900, 1300, 100), v.P: 101325, v.N: 1, v.X('NI'): (0.3, 0.7, 0.1)},
return_strategy=True,
)
ax.set_title('Hypothetical ideal binary; not assessed Cu-Ni')
ax.figure.savefig('hypothetical-binary.png', dpi=150, bbox_inches='tight')
plt.close(ax.figure)The default return is an Axes; return_strategy=True returns (Axes, BinaryStrategy).
Pass plot options in plot_kwargs; other keywords configure the mapper. binplot
requires one varying composition and one varying potential coordinate. A fixed-bulk
temperature sweep is better plotted directly from Workspace properties or the CSV.
For equilibrium/Workspace, a tuple is (start, stop, step) with an excluded stop;
a list is explicit values. Mapping uses tuple bounds and increments to follow phase
boundaries, not just a Cartesian equilibrium grid. A smooth plot alone does not
validate all stable fields; check representative points and refine difficult boundaries.
Official sources checked for these contracts:
Phase selection and solver checks
VA supports vacancy sublattices and is omitted from overall elemental mass balance.
Select actual elements present in the database. A required vacancy or other constituent
missing from every active species in one sublattice can make a phase unavailable.
The helper rejects phase lists that pycalphad filters, including redundant coupled
order/disorder selections, so the agent can review rather than silently alter them.
Excluding a phase can lower the number of stable phases and change apparent solubility. An excluded phase list is therefore scientific provenance. Preserve each composition set in miscibility gaps: summing fractions by phase name is useful for totals but loses the two distinct tie-line endpoints. Never use a vertex index as a persistent phase ID.
Mass balance, phase-sum checks, and finite Gibbs energy are necessary but not sufficient.
Doubled pdens only tests one initialization-density change. Repeat with more density,
inspect nearby conditions, compare alternative candidate phase sets, or use a trusted
reference calculation when the result affects a scientific conclusion. Degenerate phase
fractions at invariant points may be nonunique even when Gibbs energies agree. The
helper's flags should be interpreted with that thermodynamic context.
The native regression suite also loads the small alni_dupin_2001.tdb shipped in
pycalphad 0.11.2, checks order/disorder filtering, and verifies an Al-Ni equilibrium
point at 1000 K and X(Al)=0.25. That is a release integration check, not independent
experimental validation of the database. No proprietary database is bundled or used.
Parameter uncertainty is separate from numerical sampling sensitivity. Without an
assessment's covariance/posterior or another justified uncertainty model, doubled
pdens cannot yield confidence intervals. Database coverage, omitted phases, reference
states, and extrapolation can dominate errors even when two numerical runs agree.
Preserve the actual TDB with the output under its licensing terms. A SHA-256 identifies bytes but does not document assessment quality, reference-state conventions, or the validity range. Include the database authors' citation and uncertainty/coverage limits in the final scientific report.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
The author says: Requires Python 3.12+, pycalphad 0.11.2, and NumPy. Installation needs network access; calculations run locally without credentials. Real-material predictions require a suitable licensed thermodynamic database.
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- K-Dense Inc.
- Publisher
- K-Dense (Community)
- Source
- K-Dense-AI/scientific-agent-skills · skills/pycalphad · commit a25cf9e
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download pycalphad.zip