calphy package#

Submodules#

calphy.alchemy module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

Notes

  • swapping is strictly only performed between types 1 and 2 at the moment; this needs to be refined further

class calphy.alchemy.Alchemy(calculation=None, simfolder=None, log_to_screen=False)[source]#

Bases: Phase

Class for alchemical transformations

Parameters:
  • options (dict) – dict of input options

  • kernel (int) – the index of the calculation that should be run from the list of calculations in the input file

  • simfolder (string) – base folder for running calculations

__init__(calculation=None, simfolder=None, log_to_screen=False)[source]#
mass_integration(ref_mass, target_masses, target_counts)[source]#
run_averaging()[source]#

Run averaging routine

Parameters:

None

Return type:

None

Notes

Run averaging routine using LAMMPS. Starting from the initial lattice two different routines can be followed: If pressure is specified, MD simulations are run until the pressure converges within the given threshold value. Fix lattice option is not implemented at present. At the end of the run, the averaged box dimensions are calculated.

run_integration(iteration=1)[source]#

Run integration routine

Parameters:

iteration (int, optional) – iteration number for running independent iterations

Return type:

None

Notes

Run the integration routine where the initial and final systems are connected using the lambda parameter. See algorithm 4 in publication.

thermodynamic_integration()[source]#

Calculate free energy after integration step

Parameters:

None

Return type:

None

Notes

Calculates the final work, energy dissipation; In alchemical mode, there is reference system, the calculated free energy is the same as the work.

calphy.clitools module#

calphy.clitools.phase_diagram()[source]#

calphy.composition_swaps module#

calphy.composition_transformation module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

class calphy.composition_transformation.CompositionTransformation(calc)[source]#

Bases: object

Class for performing composition transformations and generating necessary pair styles for such transformations.

Parameters:
  • input_structure (ASE object, LAMMPS Data file or LAMMPS dump file) – input structure which is used for composition transformation

  • input_chemical_formula (dict) – dictionary of input chemical

  • output_chemical_formula (string) – the required chemical composition string

  • restrictions (list of strings, optional) – Can be used to specify restricted transformations

Notes

This class can be used to create compositional mappings to be used with alchemy mode. For example, assuming there is a structure file with 500 Atoms of Al in FCC structure, which needs to be transformed to the structure of 495 Al and 5 Li atoms:

` comp = CompositionTransformation(filename, {"Al":500}, {"Al":500, "Li":5}) ` Note that the atoms are chosen at random, that is, one cannot specify that only face centered lattice sites in Al can be transformed to Li.

More complex transformations can be done. For example {“Al”: 495, “Li”:5} to {“Al”: 494, “Li”: 2, “O”: 3, “C”:1}. The corresponding input is simply:

` comp = CompositionTransformation(filename, {"Al":500, "Li":5}, {"Al": 494, "Li": 2, "O": 3, "C":1}) `

Restrictions can be placed on the transformations. In the above example, one can specify that Al-O transformations should not take place. The code for this is:

``` comp = CompositionTransformation(filename, {“Al”:500, “Li”:5},

{“Al”: 494, “Li”: 2, “O”: 3, “C”:1}, restrictions=[“Al-O”])

```

If the restrictions are not satisfiable, an error will be raised.

The LAMMPS data file or dump files do not contain any information about the species except the type numbers. In general the number of atoms are respected, for example if the file has 10 atoms of type 1, 5 of type 2, and 1 of type 3. If the input_chemical_composition is {“Li”: 5, “Al”: 10, “O”: 1}, type 1 is assigned to Al, type 2 is assigned to Li and type 3 is assigned to O. This is done irrespective of the order in which input_chemical_composition is specified. However, if there are equal number of atoms, the order is respected. Therefore it is important to make sure that the input_chemical_composition is in the same order as that of types in structure file. For example, consider a NiAl structure of 10 Ni atoms and 10 Al atoms. Ni atoms are type 1 in LAMMPS terminology and Al atoms are type 2. In this case, to preserve the order, input_chemical_composition should be {“Ni”: 5, “Al”: 10}.

Once the calculation is done, there are two possible useful output options. The first one is to generate the necessary pair coefficient commands for LAMMPS. For the hypothetical transformation {“Li”:5, “Al”: 495} to {“Al”: 494, “Li”: 2, “O”: 3, “C”:1}, the pair style can be generated by:

` alc.update_pair_coeff("pair_coeff * * filename Al") `

An example pair coefficient needs to be provided. The output for the above command is,

` ('pair_coeff * * filename Al Al Li Li Li', 'pair_coeff * * filename Al O Li O C') `

These pair styles map the necessary transformation and can be used with alchemy mode. The next option is to output the structure where this pair styles can be employed. This can be done using,

` alc.write_structure(outfilename) ` The output is written in LAMMPS dump format.

__init__(calc)[source]#
compute_possible_mappings()[source]#
convert_to_pyscal()[source]#

Convert a given system to pyscal and give a dict of type mappings

property entropy_contribution#

Find the entropy entribution of the transformation. To get free energies, multiply by -T.

get_composition_transformation()[source]#

From the two given composition transformation, find the transformation dict

get_mappings()[source]#
get_random_index_of_species(species_name)[source]#

Get a random index of a given species by element name

get_swap_types(allow_all_swaps=False)[source]#

Get swapping types for configurational entropy calculation.

Returns two separate lists for forward and reverse passes to ensure proper ergodicity in thermodynamic integration.

Parameters:
  • allow_all_swaps (bool, optional) – If True, return all atom types for swapping (including fictitious ones). If False (default), filter types by element as described below.

  • pass (Reverse) – swap with each other (e.g., Mg types in Mg→Al enrichment)

  • pass – swap with each other (e.g., Al types in reverse Al→Mg)

Returns:

forward_swap_typeslist

Types to swap during forward integration (grouped by source element)

reverse_swap_typeslist

Types to swap during reverse integration (grouped by target element)

Return type:

tuple of (forward_swap_types, reverse_swap_types)

Examples

Enrichment (Mg→Al): Mappings [Al-Al(1), Mg-Al(2), Mg-Mg(3)]

forward: [2, 3] - swap Mg types (Mg being removed) reverse: [1, 2] - swap Al types (Al being added back) with allow_all_swaps=True: [1, 2, 3] for both forward and reverse

100% transformation (Mg→Al): Mappings [Mg-Al(1)]

forward: [] - only one type, no swapping possible reverse: [] - only one type, no swapping possible

Partial addition (Mg→Mg+Al): Mappings [Mg-Al(1), Mg-Mg(2)]

forward: [1, 2] - swap Mg types (Mg being removed) reverse: [] - only one Al type exists, no swapping possible

iselement(symbol)[source]#
mark_atoms()[source]#
prepare_mappings()[source]#
prepare_pair_lists()[source]#
update_mappings()[source]#
update_mark_atoms()[source]#
update_pair_coeff(pair_coeff)[source]#

Update pair_coeff command with new element specifications.

Handles both single-file formats (EAM alloy):

pair_coeff * * potential.eam.alloy El1 El2

And two-file formats (MEAM):

pair_coeff * * library.meam El1 El2 potential.meam El1 El2

For MEAM potentials, both element specifications are updated identically.

update_typedicts()[source]#
update_types()[source]#
write_structure(outfilename, for_fe_mode=False)[source]#

Write structure to LAMMPS data file with proper type declarations.

Parameters:
  • outfilename (str) – Path to write the LAMMPS data file.

  • for_fe_mode (bool, optional) – If True, write atom types reflecting the target element’s type number from typedict (e.g. Cu=1, Ni=2) and declare calc_element_count atom types in the header. This is required when the output file will be used as a structure input for a plain fe calculation where the pair_coeff enumerates all elements. If False (default), use the mappingdict type indices (one per unique transformation mapping) which is what the alchemy / composition_scaling LAMMPS routines expect for fix atom/swap.

calphy.errors module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

exception calphy.errors.CustomError[source]#

Bases: Exception

Base class for raising calphy specific exceptions

exception calphy.errors.LammpsExecutionError[source]#

Bases: RuntimeError

LAMMPS binary exited abnormally.

Carries the segment script path, the segment log path, and a short excerpt of the log (or stderr) so the failure can be diagnosed without re-running.

exception calphy.errors.MeltedError[source]#

Bases: CustomError

exception calphy.errors.PhaseTransitionError[source]#

Bases: CustomError

Raised when the pre-flight temperature-range scan flags a phase transition.

exception calphy.errors.RunnerStateError[source]#

Bases: RuntimeError

Invalid command sequence for segmented execution.

Raised for an unknown command, a dump left live across a segment boundary, an immediate-evaluation variable crossing a boundary, or a fix print being replayed – anything the ExecutableRunner cannot faithfully reproduce.

exception calphy.errors.SolidifiedError[source]#

Bases: CustomError

calphy.helpers module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

calphy.helpers.check_if_any_is_none(data)[source]#

Check if any elements of a list is None, if so return True

calphy.helpers.check_if_any_is_not_none(data)[source]#

Check if any element is not None

calphy.helpers.compute_msd(lmp, options)[source]#
calphy.helpers.create_object(calc, directory)[source]#

Create the LAMMPS runner backend selected by calc.execution_mode.

executable (the default) resolves the lmp (and, for cores > 1, mpirun) binary, runs the preflight capability check, and returns an ExecutableRunner. library returns a LibraryRunner driving a live pylammpsmpi session (optional dependency; imported lazily so the default mode never needs it). Both are primed with the same four init commands calphy has always emitted (with the md.init_commands override merge preserved verbatim).

Parameters:
  • calc (Calculation) – the validated calculation object

  • directory (string) – location of the work (sim) folder

Returns:

lmp – an ExecutableRunner or LibraryRunner

Return type:

BaseRunner

calphy.helpers.create_structure(lmp, calc)[source]#

Create structure using LAMMPS

Parameters:
  • lmp (BaseRunner) –

  • calc (dict) – calculation dict with the necessary input

Returns:

lmp

Return type:

BaseRunner

calphy.helpers.emit_init_commands(lmp, calc)[source]#

Emit the four init commands (units/boundary/atom_style/timestep), applying the md.init_commands override merge, onto lmp.

box tilt large was dropped upstream (ICAMS/calphy#262): the box command is deprecated in LAMMPS since 22Dec2022 and its arguments are ignored. The token stays in the runner vocabulary so older md.init_commands overrides that still emit one keep validating.

calphy.helpers.find_solid_fraction(file)[source]#
calphy.helpers.get_structures(file, species, index=None)[source]#
calphy.helpers.hybrid_pair_coeff_commands(options, repeat_index=0, total_repeats=1)[source]#
calphy.helpers.is_overlay_potential(options)[source]#
calphy.helpers.prepare_log(file, screen=False)[source]#
calphy.helpers.read_data(lmp, file)[source]#
calphy.helpers.real_pair_compute_commands(options, prefix='c_real', total_repeats=1, repeat_index=0)[source]#
calphy.helpers.remap_box(lmp, x, y, z)[source]#
calphy.helpers.replace_nones(data, replace_data, logger=None)[source]#

Replace Nones in the given array

calphy.helpers.scaled_pair_style_command(options, scale_names, extra_terms=None)[source]#
calphy.helpers.set_mass(lmp, options)[source]#
calphy.helpers.set_pair_coeff(lmp, options)[source]#
calphy.helpers.set_pair_style(lmp, options)[source]#
calphy.helpers.set_potential(lmp, options)[source]#

Set the interatomic potential

Parameters:
  • lmp (BaseRunner) –

  • options (dict) –

Returns:

lmp

Return type:

BaseRunner

calphy.helpers.validate_spring_constants(data, klo=0.0001, khi=1000.0, logger=None)[source]#

Validate spring constants and replace them if needed

calphy.helpers.write_data(lmp, file)[source]#

calphy.input module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

class calphy.input.Berendsen(*, thermostat_damping: float = 100.0, barostat_damping: float = 100.0)[source]#

Bases: _StrictInput

barostat_damping: float#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Specific input options for Berendsen thermostat'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

thermostat_damping: float#
class calphy.input.Calculation(*, monte_carlo: Optional[MonteCarlo] = MonteCarlo(n_steps=1, n_swaps=0, forward_swap_types=[], reverse_swap_types=[], allow_all_swaps=True, use_custom_lammps=False), composition_scaling: Optional[CompositionScaling] = CompositionScaling(output_chemical_composition={}, restrictions=[]), md: Optional[MD] = MD(timestep=0.001, n_small_steps=10000, n_every_steps=10, n_repeat_steps=10, n_cycles=100, thermostat_damping=0.1, barostat_damping=0.1, cmdargs='', init_commands=[], seed=None), nose_hoover: Optional[NoseHoover] = NoseHoover(thermostat_damping=0.1, barostat_damping=0.1), berendsen: Optional[Berendsen] = Berendsen(thermostat_damping=100.0, barostat_damping=100.0), quantum_thermal_bath: Optional[QuantumThermalBath] = QuantumThermalBath(thermostat_damping=0.1, barostat_damping=0.1, f_max=200.0, n_f=100), queue: Optional[Queue] = Queue(scheduler='local', cores=1, jobname='calphy', walltime='23:59:00', queuename='', memory='3GB', commands=[], options={}), tolerance: Optional[Tolerance] = Tolerance(lattice_constant=0.0002, spring_constant=0.1, solid_fraction=0.0, liquid_fraction=1.0, dissipation=0.001, pressure=10.0), phase_transition_detection: Optional[PhaseTransitionDetection] = PhaseTransitionDetection(mode='none', prescan_steps=20000, onset_fraction=0.85), uhlenbeck_ford_model: Optional[UFMP] = UFMP(p=50.0, sigma=1.5, single_sigma=None, single_p=None), melting_temperature: Optional[MeltingTemperature] = MeltingTemperature(guess=None, step=200, attempts=5), materials_project: Optional[MaterialsProject] = MaterialsProject(api_key='', conventional=True, target_natoms=1500), element: List[str] = [], n_elements: int = 0, mass: List[float] = [], kernel: int = 0, inputfile: str = '', mode: Optional[str] = None, lattice: str = '', file_format: str = 'lammps-data', pressure: Annotated[list[float], Len(min_length=3, max_length=3)]]] = 0, pressure_coupling: Optional[str] = None, temperature: Union[float, list[float]] = 0, temperature_high: float = 0.0, melting_cycle: bool = True, pair_style: Optional[List[str]] = None, pair_coeff: Optional[List[str]] = None, pair_mode: Optional[str] = None, potential_file: Optional[str] = None, fix_potential_path: bool = True, reference_phase: str = '', lattice_constant: float = 0, repeat: list[int] = [1, 1, 1], script_mode: bool = False, execution_mode: str = 'executable', lammps_executable: Optional[str] = None, mpi_executable: Optional[str] = None, npt: bool = True, n_equilibration_steps: int = 25000, n_switching_steps: Union[int, list[int]] = [50000, 50000], n_print_steps: int = 0, n_print_steps_equilibration: int = 0, alchemy_coupling: bool = False, n_iterations: int = 1, lambda_schedule: str = 'linear', equilibration_control: Optional[str] = None, folder_prefix: Optional[str] = None, spring_constants: Optional[List[float]] = None, phase_name: str = '', reference_composition: float = 0.0)[source]#

Bases: _StrictInput

alchemy_coupling: bool#
berendsen: Optional[Berendsen]#
composition_scaling: Optional[CompositionScaling]#
create_folders()[source]#

Create the necessary folder for calculation

Parameters:

calc (dict) – calculation block

Returns:

folder – create folder

Return type:

string

create_identifier()[source]#

Generate an identifier

Parameters:

calc (dict) – a calculation dict

Returns:

identistring – unique identification string

Return type:

string

element: List[str]#
equilibration_control: Optional[str]#
execution_mode: str#
file_format: str#
fix_paths(potlist)[source]#

Fix paths for potential files to complete ones.

Also expands environment variables (e.g. $USER, ${USER}) and the home-directory shortcut ~ in potential file paths before resolving them to absolute paths. This allows input files to contain portable paths such as /home/$USER/potentials/Cu.eam.

fix_potential_path: bool#
folder_prefix: Optional[str]#
get_folder_name()[source]#
inputfile: str#
kernel: int#
lambda_schedule: str#
lammps_executable: Optional[str]#
lattice: str#
lattice_constant: float#
mass: List[float]#
materials_project: Optional[MaterialsProject]#
md: Optional[MD]#
melting_cycle: bool#
melting_temperature: Optional[MeltingTemperature]#
mode: Optional[str]#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Main input class'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self – The BaseModel instance.

  • context – The context.

monte_carlo: Optional[MonteCarlo]#
mpi_executable: Optional[str]#
n_elements: int#
n_equilibration_steps: int#
n_iterations: int#
n_print_steps: int#
n_print_steps_equilibration: int#
n_switching_steps: Union[int, list[int]]#
nose_hoover: Optional[NoseHoover]#
npt: bool#
pair_coeff: Optional[List[str]]#
pair_mode: Optional[str]#
pair_style: Optional[List[str]]#
phase_name: str#
phase_transition_detection: Optional[PhaseTransitionDetection]#
potential_file: Optional[str]#
pressure: Annotated[list[float], Len(min_length=3, max_length=3)]]]#
pressure_coupling: Optional[str]#
quantum_thermal_bath: Optional[QuantumThermalBath]#
queue: Optional[Queue]#
reference_composition: float#
reference_phase: str#
repeat: list[int]#
script_mode: bool#
spring_constants: Optional[List[float]]#
temperature: Union[float, list[float]]#
temperature_high: float#
tolerance: Optional[Tolerance]#
uhlenbeck_ford_model: Optional[UFMP]#
class calphy.input.CompositionScaling(*, output_chemical_composition: dict = {}, restrictions: List[str] = [])[source]#

Bases: _StrictInput

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Composition scaling input options'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self – The BaseModel instance.

  • context – The context.

output_chemical_composition: dict#
restrictions: List[str]#
class calphy.input.MD(*, timestep: float = 0.001, n_small_steps: int = 10000, n_every_steps: int = 10, n_repeat_steps: int = 10, n_cycles: int = 100, thermostat_damping: float = 0.1, barostat_damping: float = 0.1, cmdargs: str = '', init_commands: List = [], seed: Optional[int] = None)[source]#

Bases: _StrictInput

barostat_damping: float#
cmdargs: str#
init_commands: List#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'MD specific input options'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

n_cycles: int#
n_every_steps: int#
n_repeat_steps: int#
n_small_steps: int#
seed: Optional[int]#
thermostat_damping: float#
timestep: float#
class calphy.input.MaterialsProject(*, api_key: str = '', conventional: bool = True, target_natoms: int = 1500)[source]#

Bases: _StrictInput

api_key: str#
conventional: bool#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Input options for materials project'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod resolve_api_key(v: str) str[source]#
target_natoms: int#
class calphy.input.MeltingTemperature(*, guess: Optional[float] = None, step: int = 200, attempts: int = 5)[source]#

Bases: _StrictInput

attempts: int#
guess: Optional[float]#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Input options for melting temperature mode'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

step: int#
class calphy.input.MonteCarlo(*, n_steps: int = 1, n_swaps: int = 0, forward_swap_types: List[int] = [], reverse_swap_types: List[int] = [], allow_all_swaps: bool = True, use_custom_lammps: bool = False)[source]#

Bases: _StrictInput

allow_all_swaps: bool#
forward_swap_types: List[int]#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Options for Monte Carlo moves during particle swap moves'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

n_steps: int#
n_swaps: int#
reverse_swap_types: List[int]#
use_custom_lammps: bool#
class calphy.input.NoseHoover(*, thermostat_damping: float = 0.1, barostat_damping: float = 0.1)[source]#

Bases: _StrictInput

barostat_damping: float#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Specific input options for Nose-Hoover thermostat'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

thermostat_damping: float#
class calphy.input.PhaseTransitionDetection(*, mode: Literal['none', 'adapt', 'warn', 'stop'] = 'none', prescan_steps: int = 20000, onset_fraction: float = 0.85)[source]#

Bases: _StrictInput

mode: Literal['none', 'adapt', 'warn', 'stop']#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Settings for the pre-flight temperature-range scan'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

onset_fraction: float#
prescan_steps: int#
class calphy.input.QuantumThermalBath(*, thermostat_damping: float = 0.1, barostat_damping: float = 0.1, f_max: float = 200.0, n_f: int = 100)[source]#

Bases: _StrictInput

Colored-noise Langevin thermostat that injects quantum statistics into classical MD (Dammak et al., Phys. Rev. Lett. 103, 190601, 2009). Active when mode: fe-qtb is set at the top level. The QTB thermostat is paired with fix nph (NPT) or fix nve (NVT) inside calphy; do NOT also pair with Nose-Hoover or Langevin.

barostat_damping: float#
f_max: float#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Dammak quantum thermal bath (LAMMPS fix qtb)'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

n_f: int#
thermostat_damping: float#
class calphy.input.Queue(*, scheduler: str = 'local', cores: int = 1, jobname: str = 'calphy', walltime: str = '23:59:00', queuename: str = '', memory: str = '3GB', commands: List = [], options: Dict[str, str] = {})[source]#

Bases: _StrictInput

commands: List#
cores: int#
jobname: str#
memory: str#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Options for configuring queue'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

options: Dict[str, str]#
queuename: str#
scheduler: str#
walltime: str#
class calphy.input.Tolerance(*, lattice_constant: float = 0.0002, spring_constant: float = 0.1, solid_fraction: float = 0.0, liquid_fraction: float = 1.0, dissipation: float = 0.001, pressure: float = 10.0)[source]#

Bases: _StrictInput

dissipation: float#
lattice_constant: float#
liquid_fraction: float#
model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'Tolerance settings for convergence'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

pressure: float#
solid_fraction: float#
spring_constant: float#
class calphy.input.UFMP(*, p: float = 50.0, sigma: Union[float, Dict[str, float]] = 1.5, single_sigma: Optional[float] = None, single_p: Optional[float] = None)[source]#

Bases: _StrictInput

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'title': 'UFM potential input options'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

p: float#
sigma: Union[float, Dict[str, float]]#
single_p: Optional[float]#
single_sigma: Optional[float]#
calphy.input.generate_metadata()[source]#
calphy.input.read_inputfile(file, validate=True)[source]#

Read input file and parse calculations.

Parameters:
  • file (str) – Path to input YAML file

  • validate (bool, optional) – If True, perform full Pydantic validation (structure creation, etc.). If False, skip expensive validation (faster, for job submission). Default is True for backward compatibility and to ensure tests pass.

Returns:

List of Calculation objects

Return type:

list

calphy.input.to_list(v: Any) List[Any][source]#

calphy.integrators module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

calphy.integrators.calculate_entropy_mix(conc)[source]#

Calculate the entropy of mixing

Parameters:

conc (float) – concentration

Returns:

s – entropy

Return type:

float

calphy.integrators.calculate_fe_impurity(temp, natoms, fepure, feimpure)[source]#

Calculate energy change of mixing, imput energies are in eV/atom

Parameters:
  • temp (float) – temperature

  • natoms (int) – number of atoms

  • fepure (float) – free energy of pure phase

  • feimpure (float) – free energy of impure phase

Returns:

dg – entropy of mixing

Return type:

float

calphy.integrators.calculate_fe_mix(temp, fepure, feimpure, concs, natoms=4000)[source]#

Calculate energy of mixing

Parameters:
  • temp (float) – temperature

  • fepure (float) – free energy of the pure phase

  • feimpure (float) – energy due to impurity

  • concs (list of floats) – concentration array

  • natoms (int) – number of atoms

Returns:

fes – free energy with concentration

Return type:

list of floats

calphy.integrators.fe(x, coef, sum_spline, index)[source]#

Fe inbuilt method

calphy.integrators.find_fe(p, x)[source]#

Find free energy of UF system

Parameters:
  • x (float) – x value of system

  • coef (list of floats) – Coefficients of system

Returns:

fe – free energy of UF system

Return type:

float

calphy.integrators.find_w(mainfolder, calc, full=False, solid=True, prefix='')[source]#

Integrate the irreversible work and dissipation for independent simulations

Parameters:
  • mainfolder (string) – main simulation folder

  • nsims (int, optional) – number of independent simulations, default 5

  • full (bool, optional) – If True return error values, default False

  • usecols (tuple, optional) – Columns to read in from data file. Default (0, 1)

  • prefix (str, optional) – infix inserted into the switching-data filenames, e.g. “leg1” reads forward_leg1_%d.dat / backward_leg1_%d.dat. Empty string (default) reads the original forward_%d.dat / backward_%d.dat.

Returns:

  • ws (float) – average irreversible work

  • qs (float) – average energy dissipation, only returned if full is True

  • err (float) – Error in free energy, only returned if full is True

calphy.integrators.get_einstein_crystal_fe(calc, vol, k, cm_correction=True, return_contributions=False, quantum=False)[source]#

Get the free energy of einstein crystal

Parameters:
  • calc (Calculation object) – contains all input parameters

  • vol (float) – converged volume per atom

  • k (spring constant, float) – units - eV/Angstrom^2

  • cm_correction (bool, optional, default - True) – add the centre of mass correction to free energy

  • return_contributions (bool, optional, default - True) – If True, return individual contributions to the reference free energy.

  • quantum (bool, optional, default - False) – If True, evaluate the quantum harmonic-oscillator free energy of the Einstein crystal. This is the reference required when the switching MD is driven by the Dammak quantum thermal bath, which samples a quantum-statistical distribution rather than the classical Boltzmann one. In the high-temperature limit (k_B T >> hbar omega) this reduces to the classical expression.

Returns:

  • F_tot (float) – total free energy of reference crystal

  • F_e (float) – Free energy of Einstein crystal without centre of mass correction. Only if return_contributions is True.

  • F_cm (float) – centre of mass correction. Only if return_contributions is True.

Notes

The classical equations for free energy of Einstein crystal and centre of mass correction are from https://doi.org/10.1063/5.0044833.

Quantum branch: each Cartesian mode i has angular frequency omega_i = sqrt(k_i / m_i), and the quantum harmonic-oscillator free energy per mode is

f_i = (1/2) hbar omega_i + k_B T ln(1 - exp(-hbar omega_i / k_B T)).

The reported F_e is sum_i f_i / N_atoms (3 modes per atom). The CM correction is retained in its classical form: it is a phase-space integration correction that does not change form under the QTB sampling at leading order.

calphy.integrators.get_ideal_gas_fe(temp, rho, natoms, mass, concentration)[source]#

Get the free energy of an single/binary ideal gas

Parameters:
  • temp (temperature, float) – the reference temperature in K

  • rho (number density, float) – units - no of atoms/ angstrom^3

  • natoms (int) – total number of atoms

  • mass (atomic mass, float) – units - g/mol

  • xa (concentration of species a, float, optional) – default 1

  • xb (concentration of species b, float, optional) – default 0

Returns:

fe – free energy/atom of ideal gas system

Return type:

float

calphy.integrators.get_uhlenbeck_ford_fe(temp, rho, p, sigma)[source]#

Get the excess free energy of Uhlenbeck-Ford model

Parameters:
  • temp (temperature, float) – units - K

  • rho (density, float) – units - no of atoms/ angstrom^3

  • p (uf scale, float) –

  • sigma (uf length scale, float) –

Returns:

fe – excess free energy/atom of uf system

Return type:

float

calphy.integrators.integrate_mass(ref_mass, target_masses, target_counts, temperature, natoms)[source]#
calphy.integrators.integrate_path(calc, fwdfilename, bkdfilename, solid=True)[source]#

Get a filename with columns du and dlambda and integrate

Parameters:
  • fwdfilename (string) – name of fwd integration file

  • bkdfilename (string) – name of bkd integration file

  • usecols (list) – column numbers to be used from input file

Returns:

  • w (float) – irreversible work in switching the system

  • q (float) – heat dissipation during switching of system

calphy.integrators.integrate_ps(simfolder, f0, natoms, pi, pf, nsims=1, return_values=False)[source]#

Carry out the reversible scaling integration

Parameters:
  • simfolder (string) – main simulation folder

  • f0 (float) – initial free energy for integration

  • nsims (int, optional) – number of independent switching

Return type:

None

Notes

Writes the output in a file pressure_sweep.dat

calphy.integrators.integrate_rs(simfolder, f0, t, natoms, p=0, nsims=5, scale_energy=False, return_values=False)[source]#

Carry out the reversible scaling integration

Parameters:
  • simfolder (string) – main simulation folder

  • f0 (float) – initial free energy for integration

  • t (float) – initial temperature

  • nsims (int, optional) – number of independent switching

  • scale_energy (bool, optional) – if True, scale energy with switching parameter

Return type:

None

Notes

Writes the output in a file reversible_scaling.dat

calphy.integrators.press(x, coef)[source]#

Find pressure of system

Parameters:
  • x (float) – x value for UF system

  • coef (list of floats) – coefficients

Returns:

result – result pressure

Return type:

float, optional

calphy.kernel module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

calphy.kernel.main()[source]#

Main method to parse arguments and run jobs

Paramaters#

None

rtype:

None

calphy.kernel.run_jobs(inputfile, validate=False)[source]#

Spawn jobs which are submitted to cluster

Parameters:
  • options (dict) – dict containing input options

  • validate (bool) – if True, perform full validation during parsing (slower). if False, uses fast parsing with dict-like access.

Return type:

None

calphy.liquid module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

class calphy.liquid.Liquid(calculation=None, simfolder=None, log_to_screen=False)[source]#

Bases: Phase

Class for free energy calculation with liquid as the reference state

Parameters:
  • options (dict) – dict of input options

  • kernel (int) – the index of the calculation that should be run from the list of calculations in the input file

  • simfolder (string) – base folder for running calculations

__init__(calculation=None, simfolder=None, log_to_screen=False)[source]#

Set up class

melt_structure(lmp)[source]#
rattle_structure(lmp)[source]#

Disorder the structure using random displacements followed by a controlled NVT cool-down before liquid equilibration.

This is a lightweight alternative to melt_structure():

run_averaging()[source]#

Run averaging routine

Parameters:

None

Return type:

None

Notes

Run averaging routine using LAMMPS. Starting from the initial lattice two different routines can be followed: If pressure is specified, MD simulations are run until the pressure converges within the given threshold value. If fix_lattice option is True, then the input structure is used as it is and the corresponding pressure is calculated. At the end of the run, the averaged box dimensions are calculated.

run_integration(iteration=1)[source]#

Run integration routine

Parameters:

iteration (int, optional) – iteration number for running independent iterations

Return type:

None

Notes

Run the integration routine where the initial and final systems are connected using the lambda parameter. See algorithm 4 in publication.

thermodynamic_integration()[source]#

Calculate free energy after integration step

Parameters:

None

Return type:

None

Notes

Calculates the final work, energy dissipation and free energy by matching with UFM model

calphy.phase module#

calphy: a Python library and command line interface for automated free energy calculations.

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

class calphy.phase.Phase(calculation=None, simfolder=None, log_to_screen=False)[source]#

Bases: object

Class for free energy calculation.

Parameters:
  • input (Calculation class) – input options

  • simfolder (string) – base folder for running calculations

__init__(calculation=None, simfolder=None, log_to_screen=False)[source]#
check_dissipation(value, stage)[source]#

Judge the irreversibility of a switching path and log the verdict.

Dissipation is the work the path threw away by not staying in equilibrium, and it enters the free energy directly. A path that is merely fast dissipates a little; a path whose structure changed partway (a solid that melted at the top of a ts sweep, say) dissipates orders of magnitude more, because the forward and backward integrals no longer describe the same system. The free energy is then wrong in a way no amount of averaging fixes, so it is worth saying out loud.

Parameters:
  • value (float) – Dissipation in eV/atom.

  • stage (str) – Human-readable name of the path, used in the message.

Returns:

True if the dissipation exceeds tolerance.dissipation. False when it does not, and whenever the check is disabled.

Return type:

bool

check_if_melted(lmp, filename)[source]#

Check whether the solid has melted, using a structural solid-fraction criterion.

The solid fraction is computed from the trajectory snapshot in filename; if it drops below tolerance.solid_fraction the run is aborted with a MeltedError. Detection can be turned off by setting tolerance.solid_fraction: 0.

check_if_solidfied(lmp, filename)[source]#

Check whether the liquid has solidified, using a structural solid-fraction criterion.

If the solid fraction in filename exceeds tolerance.liquid_fraction the run is aborted with a SolidifiedError.

clean_up()[source]#

Run a clean up job

dump_current_snapshot(lmp, filename)[source]#
ediss#

Max energy dissipation along a ts/tscale reversible-scaling sweep [eV/atom]; written to report.yaml as results.ts_dissipation.

ediss_high#

Whether that sweep exceeded tolerance.dissipation, i.e. whether the path was irreversible enough to doubt the free energy it produced. Written to report.yaml as results.ts_dissipation_high.

finalise_pressure(lmp)[source]#
fix_berendsen(lmp, temp_start_factor=1.0, temp_end_factor=1.0, press_start_factor=1.0, press_end_factor=1.0, stage=0, ensemble='npt')[source]#

Fix Nose-Hoover thermostat and barostat

Parameters:

None

Return type:

None

fix_nose_hoover(lmp, temp_start_factor=1.0, temp_end_factor=1.0, press_start_factor=1.0, press_end_factor=1.0, stage=0, ensemble='npt')[source]#

Fix Nose-Hoover thermostat and barostat

Parameters:

None

Return type:

None

fix_qtb(lmp, temp_start_factor=1.0, temp_end_factor=1.0, press_start_factor=1.0, press_end_factor=1.0, stage=0, ensemble='npt')[source]#

Apply the Dammak quantum thermal bath as a thermostat.

QTB only thermostats — it must be paired with an integrator. We use fix nph for NPT (pressure-controlled) and fix nve for NVT (canonical). Temperature endpoints are read but only the start value is used: LAMMPS fix qtb takes a single temperature, so any ramping must be implemented externally.

get_structures(stage='fe', direction='forward', n_iteration=1)[source]#
integrate_pressure_scaling(return_values=False)[source]#

Perform integration after reversible scaling

Parameters:
  • scale_energy (bool, optional) – If True, scale the energy during reversible scaling.

  • return_values (bool, optional) – If True, return integrated values

Returns:

res – Only returned if return_values is True.

Return type:

list of lists of shape 1x3

integrate_reversible_scaling(scale_energy=True, return_values=False)[source]#

Perform integration after reversible scaling

Parameters:
  • scale_energy (bool, optional) – If True, scale the energy during reversible scaling.

  • return_values (bool, optional) – If True, return integrated values

Returns:

res – Only returned if return_values is True.

Return type:

list of lists of shape 1x3

lammps_close(lmp)[source]#
pressure_scaling(iteration=1)[source]#

Perform pressure scaling calculation in NPT

Parameters:

iteration (int, optional) – iteration of the calculation. Default 1

Return type:

None

process_pressure(lmp)[source]#
qdiss#

Mean switching dissipation q = 0.5*(W_fwd + W_bwd) [eV/atom]; a measure of the irreversibility of the fe-mode switching (0 for a perfectly reversible path). Written to report.yaml as results.dissipation.

reversible_scaling(iteration=1)[source]#

Perform reversible scaling calculation in NPT.

Calls _reversible_scaling_forward() (initial equilibration + forward sweep, saves conf.ts.forward_{iteration}.data) followed by _reversible_scaling_backward() (middle equilibration at Tf + backward sweep).

Parameters:

iteration (int, optional) – Iteration of the calculation. Default 1.

run_constrained_pressure_convergence(lmp)[source]#
run_finite_pressure_equilibration(lmp)[source]#

Run a finite pressure equilibration

Parameters:

lmp (LAMMPS object) –

Return type:

None

Notes

Each method should close all the fixes. Run a equilibration routine to reach the given finite pressure. The pressure is implemented in one fix, while temperature is gradually ramped. The thermostat can work faster than barostat, which means that the structure will melt before the pressure is scaled, this ramping can prevent the issue.

run_pressure_convergence(lmp)[source]#

Run a pressure convergence routine

Parameters:

lmp (LAMMPS object) –

Return type:

None

Notes

Take the equilibrated structure and rigorously check for pressure convergence.

Full-length NPT cycles are run throughout. The first cycle is excluded from the running average to discard the initial transient. After n_fit_warmup cycles (default 5), a linear P-V fit is used to predict the equilibrium volume and rescale the box, accelerating convergence. The mean pressure (over all post-transient data) must fall within tolerance.pressure of the target to declare convergence.

run_zero_pressure_equilibration(lmp)[source]#

Run a zero pressure equilibration

Parameters:

lmp (LAMMPS object) –

Return type:

None

Notes

Each method should close all the fixes. Run a small eqbr routine to achieve zero pressure

scan_temperature_range()[source]#

Pre-flight temperature-range scan for a reversible-scaling (ts) run.

Runs a single fast real-thermostat temperature ramp (T0 -> Tf under NPT) and analyses the fluctuation response functions to find the onset of a phase transition. Depending on phase_transition_detection.mode the requested temperature range is then left as-is, reduced to the clean sub-range, or the run is aborted:

‘none’ — never called (the caller gates on mode != ‘none’). ‘adapt’ — on detection, reduce calc._temperature_stop to the

detected clean onset (the number of switching steps is left unchanged); a clean scan leaves the range untouched.

‘warn’ — log the detected clean range without modifying anything. ‘stop’ — on detection, raise PhaseTransitionError.

Unlike the production sweep, this ramp uses a measured temperature (the thermostat genuinely ramps), so the response functions are the plain NPT fluctuation expressions with no lambda reduction — see calphy.range_scan.

Return type:

None

start_equilibration_dump(lmp, filename='traj.equilibration.dat')[source]#

Continuous every-n-th-step dump through the equilibration stages (pressure convergence onward), enabled by n_print_steps_equilibration > 0. Off by default: behavior is then identical to unpatched calphy. Dump id deq avoids the id 2 used by dump_current_snapshot.

stop_equilibration_dump(lmp)[source]#
submit_report(extra_dict=None)[source]#

Submit final report containing results

Parameters:

extra_dict (dict) – extra information to be written out

Return type:

None

temperature_scaling(iteration=1)[source]#

Perform temperature scaling calculation in NPT

Parameters:

iteration (int, optional) – iteration of the calculation. Default 1

Return type:

None

ufm_pair_coeff_commands(eps, sigma_scalar, sigma_by_type, substyle='')[source]#

Build the pair_coeff command(s) for a UFM interaction.

Parameters:
  • eps (float) – UFM energy scale.

  • sigma_scalar (float) – length scale to use when sigma_by_type is None (single-component).

  • sigma_by_type (dict or None) – mapping (type_i, type_j) -> sigma for the multi-component case.

  • substyle (str) – hybrid/scaled substyle token to insert after the type pair, e.g. “ufm”, “ufm 1”, “ufm 2”. Empty string for a plain (non-hybrid) pair_style ufm where no style keyword is allowed.

Return type:

list of str

unfix_berendsen(lmp)[source]#

Fix Nose-Hoover thermostat and barostat

Parameters:

None

Return type:

None

unfix_nose_hoover(lmp)[source]#

Fix Nose-Hoover thermostat and barostat

Parameters:

None

Return type:

None

unfix_qtb(lmp)[source]#

calphy.phase_diagram module#

class calphy.phase_diagram.CScale[source]#

Bases: object

__init__()[source]#
property input_chemical_composition#
property output_chemical_composition#
class calphy.phase_diagram.PhaseDiagram(folders, reference_element, composition_intervals=None, smooth=True)[source]#

Bases: object

High-level class for computing and plotting a binary phase diagram.

Wraps the full workflow — data gathering, cleaning, free-energy fitting, common-tangent construction, and plotting — into a single object.

Parameters:
  • folders (dict) –

    Mapping of phase name → folder path (or list of folder paths). Pass a list to merge multiple simulation folders into a single phase — the raw data is combined before any fitting, so there are no cross-folder inconsistencies:

    # single folder per phase
    {'cufcc': 'cufcc', 'agfcc': 'agfcc', 'lqd': 'lqd'}
    
    # aufcc and cufcc merged into one 'fcc' phase
    {'fcc': ['aufcc_folder', 'cufcc_folder'], 'lqd': 'lqd'}
    

  • reference_element (str) – The element whose fraction is used as the composition axis (e.g. 'Ag').

  • composition_intervals (dict, optional) – Per-phase composition bounds, e.g. {'fcc': (0, 1), 'lqd': (0, 1)}. Phases not listed are auto-detected from the data: the interval is set to the (min, max) of available compositions for that phase.

  • smooth (bool) – If True (default), smooth F(T) data with thermodynamic basis during the clean_df step.

Examples

>>> pd = PhaseDiagram(
...     folders={'fcc': ['aufcc', 'cufcc'], 'lqd': 'lqd'},
...     reference_element='Au',
... )
>>> pd.calculate(T_range=(400, 1400), T_step=5, fit_order=4,
...              method='redlich-kister')
>>> fig, ax = pd.plot()
__init__(folders, reference_element, composition_intervals=None, smooth=True)[source]#
build_calphad_surface(rk_order=3, endpoint_tol=0.05)[source]#

Fit a CALPHAD-decomposed Gibbs energy surface G(x, T) for each phase.

The model mirrors the pycalphad/TDB representation:

G(x, T) = (1-x)·G_A(T) + x·G_B(T)
          + k_B·T·[x·ln x + (1-x)·ln(1-x)]
          + x·(1-x)·Σ_k L_k·(1-2x)^k

G_A(T) and G_B(T) are six-term CALPHAD polynomials fitted to the pure-endpoint calphy data. L_k are Redlich-Kister interaction parameters fitted to temperature-averaged excess free energies at intermediate compositions (T-independent RK approximation).

Because G(x, T) is a smooth analytic surface in both x and T, phase boundaries computed from it via calculate() (with calphad_surface=True) are substantially smoother and more physically consistent than those from the per-temperature polynomial fits in the default mode. This is the root reason why the pycalphad/TDB route yields better phase diagrams: it decomposes G into physically motivated components rather than fitting a raw polynomial slice-by-slice in composition at each T.

Call this method before calculate(calphad_surface=True), or pass calphad_surface=True directly to calculate() (which will call this automatically).

Parameters:
  • rk_order (int) – Number of Redlich-Kister parameters to fit (default 3).

  • endpoint_tol (float) – Composition window for locating pure endpoints: rows with composition <= endpoint_tol are candidates for the A endpoint and rows with composition >= 1 - endpoint_tol for the B endpoint (default 0.05).

Returns:

Keyed by phase name. Each value is either None (surface could not be built) or a dict with keys 'coeffs_A', 'coeffs_B', 'L_coeffs', 'x_data', 'G_xs_data', 'rk_order'.

Return type:

dict

calculate(T_range=(400, 1400), T_step=5, fit_order=4, method='polynomial', boundary_trim=0.1, remove_self_tangents_for=None, ideal_configurational_entropy=True, end_weight=3, end_indices=4, calphad_surface=True, rk_order=3, composition_grid=10000, peak_cutoff=0.003)[source]#

Compute common-tangent constructions across a temperature range.

Parameters:
  • T_range (tuple) – (T_min, T_max) in Kelvin.

  • T_step (float) – Temperature increment.

  • fit_order (int) – Polynomial / Redlich-Kister order for F(x) fits.

  • method (str) – 'polynomial' or 'redlich-kister'.

  • boundary_trim (float) – Amount to trim from partial-range phase boundaries. 'auto' (default) computes 2× the average composition spacing per phase.

  • remove_self_tangents_for (list of str, optional) – Phase names for which same-phase tangent constructions should be discarded.

  • ideal_configurational_entropy (bool) – Include ideal configurational entropy in the free energies. Defaults to True. Set to False to remove the ideal configurational-entropy contribution (e.g. for ordered phases or when no swap moves were performed).

  • end_weight (int) – Weight for endpoints in the fit.

  • end_indices (int) – Number of endpoint indices to weight.

  • calphad_surface (bool) –

    If True, use a CALPHAD-decomposed G(x, T) surface for the phase boundary calculation instead of the default per-temperature polynomial fits. The surface is:

    G(x,T) = (1-x)·G_A(T) + x·G_B(T)
              + k_B·T·[x ln x + (1-x) ln(1-x)]
              + x(1-x)·Σ_k L_k·(1-2x)^k
    

    This mirrors the pycalphad/TDB approach and yields smoother, more physically consistent phase boundaries because G is smooth in both x and T simultaneously. If build_calphad_surface() has not been called yet it is invoked automatically using rk_order. Default True. Set to False to revert to the legacy per-temperature polynomial mode.

  • rk_order (int) – Number of Redlich-Kister parameters for the CALPHAD surface. Only used when calphad_surface is True and the surface has not been pre-built. Default 3.

  • composition_grid (int) – Number of composition points on the evaluation grid when calphad_surface is True. Default 10000.

  • peak_cutoff (float) – Minimum composition-gap width required to report a two-phase coexistence region from the convex-hull construction. Reduce this to catch narrow coexistence regions near pure endpoints (e.g. the fcc-liquid window close to the melting point of a pure component). Default 0.003.

classmethod from_df(df, reference_element, phases=None, composition_intervals=None)[source]#

Construct a PhaseDiagram directly from a DataFrame.

This bypasses folder reading and all pre-processing (gather_results, clean_df, etc.). Use it when you already have a tidy DataFrame — e.g. one previously obtained from PhaseDiagram.df or assembled manually.

Parameters:
  • df (pandas.DataFrame) –

    Must contain at least the columns:

    • phase — str, phase label (e.g. 'fcc', 'lqd').

    • composition — float, reference-element mole fraction.

    • temperature — array-like of floats (one per row).

    • free_energy — array-like of floats (one per row).

    Any additional columns are preserved unchanged.

  • reference_element (str) – The element whose fraction defines the composition axis (e.g. 'Ag').

  • phases (list of str, optional) – Ordered list of phase names. Defaults to the unique values of df['phase'] in the order they first appear.

  • composition_intervals (dict, optional) – {phase: (x_lo, x_hi)} bounds for each phase. Phases not supplied are auto-detected from the data.

Return type:

PhaseDiagram

static from_parquet(filename)[source]#

Load a PhaseDiagram previously saved with to_parquet().

The original folder structure is not required; only the processed DataFrame and metadata stored inside the Parquet file are used.

Parameters:

filename (str) – Path to the Parquet file.

Return type:

PhaseDiagram

static from_pickle(filename)[source]#

Load a PhaseDiagram object previously saved with to_pickle().

Parameters:

filename (str) – Path to the pickle file.

Return type:

PhaseDiagram

static from_tdb(filename)[source]#

Load a PhaseDiagram from a TDB file written by to_tdb().

Parses the file using the embedded $ CALPHY_TDB_METADATA JSON header, the FUNCTION blocks (GHSER and any other inlined functions), and the PARAMETER expressions. Solution and limited-range phases are stored in _calphad_surfaces; line compounds are stored in _line_compound_fits (mirrors the output of _fit_line_compound_phase()). Legacy CEF compounds are stored in _compound_2sl_fits for backwards compatibility. Units are converted from J/mol-atoms back to eV/atom.

The returned object can drive calculate() (with calphad_surface=True) and plot() because those code paths only need _calphad_surfaces, not raw data.

Parameters:

filename (str) – Path to a TDB file produced by to_tdb().

Returns:

  • PhaseDiagram

  • Limitations and caveats

  • ———————–

  • 1. Requires the ``$ CALPHY_TDB_METADATA`` header. Arbitrary – TDBs from external sources (COST507, solders.tdb, etc.) are not supported — phase classification (solution / line compound / limited range / CEF), stoichiometries and the host phase identity all come from that JSON header. Raises ValueError if the header is missing.

  • 2. The returned ``df`` is empty. The raw F(x,T) MD data is – not stored in the TDB and cannot be recovered. Methods that need the dataframe will fail or produce empty output:

    Use from_parquet() if you need the raw data.

  • 3. The round-trip is lossy. to_tdb() applies a – Tikhonov-regularised linear-T refit to full-range solution phases’ L_k coefficients, so the surfaces recovered here are the regularised versions, not the original 6-term fits returned by build_calphad_surface(). Typical per-point G(x, T) drift inside the data T range is O(1 mJ/mol) for solid solutions and up to ~40 meV/atom for noisy liquids.

  • 4. **Limited-range phase diagrams differ from the original.** – When the source PhaseDiagram had raw data, calculate() for narrow phases fell back to per-T polynomial fits of the data. Without raw data, the loaded object uses the bounded-fit surface only — producing somewhat narrower / differently-shaped solubility windows in the pycalphad or calphy-rendered diagram than the original.

  • 5. **Composition intervals are preserved verbatim* from the* – metadata header, even though the polynomial fit may not perfectly respect them outside the constrained sample points.

plot(fill=True, alpha=0.2, border_lw=2, smooth_boundary=11, color_phases=False, figsize=None, ax=None, **kwargs)[source]#

Plot the full phase diagram.

Parameters:
  • color_phases (bool) – If True, fill single-phase regions with per-phase colours instead of filling two-phase coexistence regions. Default False.

  • to (All other keyword arguments are forwarded) –

:param plot_phase_diagram().:

Returns:

  • fig (matplotlib Figure)

  • ax (matplotlib Axes)

plot_calphad_surface_fit(figsize=None)[source]#

Diagnostic plot for the CALPHAD surface fit.

Shows two subplots per phase:

  • Left: fitted CALPHAD G(T) polynomials for the pure endpoints (A and B) overlaid on the raw calphy data.

  • Right: Redlich-Kister excess G_xs(x) fitted curve overlaid on the temperature-averaged excess data points.

Requires build_calphad_surface() to have been called first.

Parameters:

figsize (tuple or None) –

Returns:

  • fig (matplotlib Figure)

  • axes (ndarray of Axes)

plot_convergence(figsize=None)[source]#

Show which (phase, composition, temperature) calculations succeeded. Each phase gets a subplot with temperature on the y-axis and composition on the x-axis. Successful runs are shown as filled circles; missing data as open circles.

Returns:

  • fig (matplotlib Figure)

  • axes (array of matplotlib Axes)

plot_data_vs_fit(phase, T, figsize=None, ax=None)[source]#

Compare raw free-energy data points with the fitted curve for a single phase at temperature T.

Returns:

  • fig (matplotlib Figure)

  • ax (matplotlib Axes)

plot_free_energy(T, show_data=False, figsize=None, ax=None)[source]#

Plot free-energy curves F(x) for all phases at temperature T.

Parameters:
  • T (float) – Temperature in Kelvin.

  • show_data (bool) – If True, overlay the raw data points on each phase curve.

  • figsize (tuple, optional) –

  • ax (matplotlib Axes, optional) –

Returns:

  • fig (matplotlib Figure)

  • ax (matplotlib Axes)

plot_free_energy_mixing(T, show_data=False, figsize=None, ax=None)[source]#

Plot free energy of mixing F_mix(x) with common-tangent lines at temperature T.

Parameters:
  • T (float) – Temperature in Kelvin.

  • show_data (bool) – If True, overlay the raw data points on each phase curve.

Returns:

  • fig (matplotlib Figure)

  • ax (matplotlib Axes)

to_df(filename)[source]#

Save the merged, reference-corrected DataFrame to a pickle file.

This captures the data after gathering, cleaning, and reference correction but before any F(x) fitting, making it the ideal checkpoint for inspecting or re-using raw data across sessions.

The DataFrame can be reloaded with pandas.read_pickle(filename).

Parameters:

filename (str) – Path to the output file (e.g. 'raw_data.pkl').

to_parquet(filename)[source]#

Save the processed DataFrame to a Parquet file (version-independent).

Columns that hold numpy arrays (temperature, free_energy) are flattened to one row per temperature point; a row_id column tracks which rows belong together. Object-level metadata (reference_element, phases, composition_intervals) is embedded in the Parquet schema so the full object can be reconstructed by from_parquet().

Parameters:

filename (str) – Output path (e.g. 'phase_diagram.parquet').

to_pickle(filename)[source]#

Save the PhaseDiagram object to a file using pickle.

Parameters:

filename (str) – Path to the output file (e.g. 'phase_diagram.pkl').

to_tdb(filename, elements=None, line_compounds=None, rk_order=3, T_min=298.15, T_max=None, L_temperature_form='poly6', limited_rk_order=None, limited_L_n_terms=3, limited_fit_order=4, full_range_ridge_lambda=100.0, compound_anti_site_penalty=80000.0, compound_pure_sublattice_penalty=80000.0)[source]#

Write a TDB file representing this phase diagram in SGTE/CALPHAD convention so pycalphad (or Thermo-Calc / OpenCalphad) can read it.

TDB structure#

  • Header: TEMP_LIM, DEFINE_SYSTEM_DEFAULT, DEFAULT_COMMAND DEFINE_SYS_ELEMENT VA, TYPE_DEFINITION.

  • FUNCTION GHSER<EL> blocks for each element, taken from the host phase’s pure-element 6-term polynomial.

  • The host phase (full-range solid solution containing both pure endpoints; e.g. fcc) and limited-range phases are written as 2-sublattice (A,B):VA solid solutions referencing GHSER (the universal SGTE convention seen in COST507/solders.tdb).

  • Non-host full-range phases (e.g. lqd) keep an independent six-term polynomial for their pure-element G — the linear GHSER + a + b·T offset is too lossy for noisy MD liquid data (drops melting points by hundreds of K).

  • Phases listed in line_compounds are 2-sublattice A:B with a single 6-term polynomial G(T) per formula unit.

  • Full-range phases’ Redlich-Kister L parameters are written with the temperature dependence chosen by L_temperature_form: the exact six-term polynomials from build_calphad_surface() ("poly6", default — the TDB then reproduces calphy’s G(x,T) surface exactly inside the validity range) or a ridge-regularised a + b·T refit ("linear", the standard SGTE convention). Limited-range phases always use a + b·T from the bounded fit.

A JSON metadata comment ($ CALPHY_TDB_METADATA) is embedded in the header so from_tdb() can recover phase classification and stoichiometry without trying to infer it from the TDB content.

param filename:

Output TDB path.

type filename:

str

param elements:

Binary element pair. B should be reference_element. If omitted, the pair is inferred from phase names.

type elements:

tuple of (A, B), optional

param line_compounds:

Phase names to treat as line compounds (single stoichiometry, single G(T) polynomial). Default: [].

type line_compounds:

list of str, optional

param rk_order:

Number of Redlich-Kister terms (default 3).

type rk_order:

int

param T_min:

Temperature validity range written in PARAMETER blocks. T_max defaults to the max temperature found in self.df — pycalphad extrapolates blindly beyond this, so leaving it tight to the actual MD range is the conservative choice.

type T_min:

float

param T_max:

Temperature validity range written in PARAMETER blocks. T_max defaults to the max temperature found in self.df — pycalphad extrapolates blindly beyond this, so leaving it tight to the actual MD range is the conservative choice.

type T_max:

float

param L_temperature_form:

Temperature form for full-range solution phases’ L_k(T) parameters.

"poly6" (default)

Write the six-term CALPHAD polynomials fitted by build_calphad_surface() verbatim. The TDB free energy of every full-range phase is then identical to calphy’s own CALPHAD surface, so a pycalphad phase diagram computed from the TDB matches calculate(calphad_surface=True) inside the validity range. Do not evaluate the TDB outside [T_min, T_max] — the polynomial tails are unbounded.

"linear"

Legacy SGTE-style refit of each L_k as a + b·T with Tikhonov ridge regularisation (full_range_ridge_lambda). Smoother extrapolation but drifts up to tens of meV/atom from the calphy surface, visibly narrowing e.g. the solid–liquid lens.

type L_temperature_form:

str

param limited_rk_order:

RK order for limited-range phases’ bounded fit. By default the order is auto-selected per phase: the lowest of (3, 4, 5, 6) that fits the phase’s pseudo-data to better than ~1 meV/atom RMS (wider composition windows need more terms — an underfit well overstabilises the phase and pushes its dissolution temperature up by ~100 K, an overfit one adds interior wiggle). Pass an integer to force a fixed order instead.

type limited_rk_order:

int, optional

param limited_L_n_terms:

T-basis terms per L_k in the bounded fit: 2 → a + b·T, 3 → a + b·T + c·T·lnT (default). Three terms follow the curvature of the stability window in T.

type limited_L_n_terms:

int

param limited_fit_order:

Polynomial order of the per-temperature smoothing fit used to generate dense pseudo-data for limited-range phases (default 4 — the same default calculate() uses for narrow phases). The RK model is fit against these smooth per-T curves rather than the raw composition points, which keeps the well-minimum location — and hence the shape of the single-phase window near the dome top — faithful to calphy’s own construction.

type limited_fit_order:

int

param full_range_ridge_lambda:

Tikhonov ridge weight used in refitting full-range solution phases’ L_k(T) as a + b·T when L_temperature_form="linear". Plain LSQ on noisy liquid data gives unstable huge cancelling magnitudes that produce wavy liquidi and spurious miscibility gaps on extrapolation; the ridge bounds the magnitudes. Default 100 — increase for smoother (and less data-faithful) L; decrease for more data-faithful (and possibly less stable) L.

type full_range_ridge_lambda:

float

param compound_anti_site_penalty:

Reserved for the 2-sublattice CEF (A,B):(A,B) compound code path (_fit_compound_two_sublattice). Not exercised under the current default settings — limited-range phases use the 1-sublattice bounded fit instead.

type compound_anti_site_penalty:

float

param compound_pure_sublattice_penalty:

Reserved for the 2-sublattice CEF (A,B):(A,B) compound code path (_fit_compound_two_sublattice). Not exercised under the current default settings — limited-range phases use the 1-sublattice bounded fit instead.

type compound_pure_sublattice_penalty:

float

param Limitations and caveats:

param ———————–:

param The TDB is a lossy projection of the calphy MD data:

param 1. Full-range phases are exact only in poly6 mode. With the:

default L_temperature_form="poly6" the full-range solution phases’ G(x,T) in the TDB equals calphy’s CALPHAD surface exactly (same 6-term pure-element G and L_k polynomials). With "linear", L_k are refit as a + b·T with Tikhonov ridge regularisation (full_range_ridge_lambda), trading data-fit accuracy for smoother T extrapolation: the per-point G(x,T) drift is a few meV/atom for well-sampled phases (FCC) and up to ~20-40 meV/atom for noisy ones (LQD), which visibly distorts the solid-liquid lens.

param 2. Limited-range phases use a bounded SLSQP fit:

original build_calphad_surface (which has no surface for narrow phases anyway). The bounded fit shares the host’s pure-element G_A/G_B and fits L_k(T) only to data inside the composition window, with the constraint G_phase(x,T) G_host(x,T) enforced at sample points outside the window to prevent the polynomial from making the phase spuriously stable far from its data. This usually produces narrower stability windows in the pycalphad diagram than calphy’s own per-T polynomial common-tangent gives.

param not the:

original build_calphad_surface (which has no surface for narrow phases anyway). The bounded fit shares the host’s pure-element G_A/G_B and fits L_k(T) only to data inside the composition window, with the constraint G_phase(x,T) G_host(x,T) enforced at sample points outside the window to prevent the polynomial from making the phase spuriously stable far from its data. This usually produces narrower stability windows in the pycalphad diagram than calphy’s own per-T polynomial common-tangent gives.

param 3. Plot only inside the data T range. T_max defaults to:

the MD data’s actual maximum; extrapolating beyond — even by 100 K — frequently exposes wild 6-term polynomial tails (visible as spurious LQD/FCC lenses). Set the plot range to T_max or below.

param 4. **The raw F(x:

if you need a lossless round-trip.

:param T) data is not stored.** Use to_parquet(): if you need a lossless round-trip. :param 5. Pycalphad’s TDB parser rejects inline ``REF:`` tags in: PARAMETER and FUNCTION blocks (despite Thermo-Calc accepting

them in COST507 etc.), so traceability is emitted as $ REF: calphy-MD-<date> comment lines instead.

class calphy.phase_diagram.SimpleCalculation(lattice, element, input_chemical_composition, output_chemical_composition)[source]#

Bases: object

Simple calc class

__init__(lattice, element, input_chemical_composition, output_chemical_composition)[source]#
calphy.phase_diagram.create_color_list(phases)[source]#
calphy.phase_diagram.fix_data_file(datafile, nelements)[source]#

Change the atom types keyword in the structure file

calphy.phase_diagram.get_common_tangents(dict_list, peak_cutoff=0.003, plot=False, remove_self_tangents_for=[])[source]#

Get common tangent constructions using convex hull method

calphy.phase_diagram.get_free_energy_mixing(dict_list, threshold=0.001, boundary_trim=0.1)[source]#

Input is a list of dictionaries

Get free energy of mixing by subtracting end member values. End members are chosen automatically.

Parameters:
  • dict_list (list of dict) – Phase free-energy dictionaries (output of get_phase_free_energy).

  • threshold (float) – Tolerance for matching end-member compositions (default 1e-3).

  • boundary_trim (float) – Composition width to trim from the boundaries of partial-range phases. A partial-range phase is one whose composition range does not reach the global minimum or maximum. Trimming removes the edge region where the global linear reference can produce artefactual dips in F_mix. Set to 0 to disable.

calphy.phase_diagram.get_phase_free_energy(df, phase, temp, composition_interval=(0, 1), ideal_configurational_entropy=False, entropy_correction=0.0, fit_order=5, composition_grid=10000, composition_cutoff=None, reset_value=1, plot=False, end_weight=3, end_indices=4, method='polynomial')[source]#

Get the free energy of a phase as a function of composition.

Parameters:
  • df (Pandas dataframe) – Dataframe consisting of values from simulation. Should contain at least columns composition, phase, free_energy and temperature. energy_free and temperature should be arrays of equal length, generally an output from reversible scaling calculation.

  • phase (str) – phase for which calculation is to be done. Should be present in df.

  • temp (float) – temperature at which the free energy curves are to be calculated.

  • composition_interval (tuple, optional) – If provided, this composition interval is considered. Default (0, 1)

  • ideal_configuration_entropy (bool, optional If True, add the ideal configurational entropy. See Notes. Default False.) –

  • entropy_correction (float, optional.) – The composition of the ordered phase. See Notes. Default None.

  • fit_order (int, optional) – Order of the polynomial fit used for fitting free energy as a function of composition. Default 5.

  • composition_grid (int, optional) – Number of composition points to be used for fitting. Default 10000.

  • composition_cutoff (float, optional) – term for correcting incomplete data. If two consecutive composition values are separated by more than composition_cutoff, it is reset to reset_value. Default None.

  • reset_value (float, optional) – see above. Default 1.

  • plot (bool, optional) – If True, plot the calculated free energy curves.

  • method (str, optional) – Fitting method for F(x). “polynomial” (default) uses np.polyfit; “redlich-kister” uses the Redlich-Kister expansion F_excess = x(1-x) * sum_k L_k*(1-2x)^k.

Returns:

result_dict – contains keys: “phase”, “temperature”, “composition”, “free_energy”, and “entropy”.

Return type:

dict

Notes

To be added

calphy.phase_diagram.get_tangent_type(dict_list, tangent, energy)[source]#
calphy.phase_diagram.plot_pd(ax, pd_obj, phase_colors=None, two_phase_alpha=0.35, boundary_lw=1.2, boundary_color='k')[source]#

Plot a phase diagram onto an existing matplotlib Axes.

Only two-phase regions are colored; single-phase regions are uncolored.

Parameters:
  • ax (matplotlib.axes.Axes) –

  • pd_obj (PhaseDiagram) – After calculate() has been called.

  • phase_colors (dict, optional) – Mapping from tangent-type string 'phaseA-phaseB' to a colour. Regions not listed fall back to '#cccccc'.

  • two_phase_alpha (float) – Alpha for the two-phase fill regions.

  • boundary_lw (float) – Line width of the two-phase boundary lines.

  • boundary_color (str) – Colour of the two-phase boundary lines.

calphy.phase_diagram.plot_phase_diagram(tangents, temperature, tangent_types, phases, edgecolor='#37474f', linewidth=1, linestyle='-', fill=True, alpha=0.35, border_lw=2, smooth_boundary=0, color_phases=False, figsize=None, ax=None)[source]#

Plot a binary phase diagram.

Parameters:
  • tangents (list of arrays) – Tangent composition pairs at each temperature, output of the phase-diagram loop.

  • temperature (list) – Temperature value for each entry in tangents.

  • tangent_types (list of arrays) – Phase-pair labels (e.g. "cufcc-lqd") for every tangent.

  • phases (list of str) – Ordered phase names used to build the colour palette.

  • edgecolor (str) – Colour for polygon borders and the figure frame.

  • linewidth (float) – Line width when fill is False (legacy horizontal-line mode).

  • linestyle (str) – Line style when fill is False.

  • fill (bool) – If True (default), render two-phase regions as filled polygons with coloured borders. If False, fall back to horizontal lines.

  • alpha (float) – Fill opacity for polygons (0–1).

  • border_lw (float) – Line width of the polygon borders.

  • smooth_boundary (int) – Savitzky-Golay window size (odd integer) for smoothing polygon boundaries. Set to 0 (default) to disable. A value of 11 is a good starting point.

  • color_phases (bool) – If True, fill single-phase regions with per-phase colours instead of filling two-phase coexistence regions. Two-phase regions are left uncoloured (white background), and the legend lists each phase individually. Default False (coexistence-region colouring).

  • figsize (tuple or None) – Figure size. Defaults to (7, 5).

  • ax (matplotlib Axes or None) – If given, draw on this axes instead of creating a new figure.

Returns:

  • fig (matplotlib Figure)

  • ax (matplotlib Axes)

calphy.phase_diagram.prepare_inputs_for_phase_diagram(inputyamlfile, calculation_base_name=None)[source]#
calphy.phase_diagram.read_structure_composition(lattice_file, element_list)[source]#

Read a LAMMPS data file and determine the input chemical composition.

Parameters:
  • lattice_file (str) – Path to the LAMMPS data file

  • element_list (list) – List of element symbols in order (element[0] = type 1, element[1] = type 2, etc.)

Returns:

Dictionary mapping element symbols to atom counts Elements not present in the structure will have count 0

Return type:

dict

calphy.postprocessing module#

calphy.postprocessing.clean_df(df, reference_element, combine_direct_calculations=False, smooth=False)[source]#

Clean a parsed dataframe and drop unnecessary columns. This gets it ready for further processing Note that gather_results should be run with reduce_composition and extract_phase_name for this to work.

Parameters:
  • df (DataFrame) – dataframe parsed by gather_results with reduce_composition=True.

  • reference_element (str) – reference element from the compositions, which will be renamed to composition

  • combine_direct_calculations (bool, optional) – If True, combine direct calculations by fitting to produce temperature and free energy arrays If used, an extra column error with RMSE of the fitting is also created

  • smooth (bool, optional) – If True, smooth the F(T) data using the thermodynamic basis [1, T, T ln T, T²]. If False (default), return the raw data points without smoothing.

Returns:

df – combined, finished DataFrame

Return type:

DataFrame

calphy.postprocessing.find_transition_temperature(folder1, folder2, fit_order=4, plot=True)[source]#

Find transition temperature where free energy of two phases are equal.

Parameters:
  • folder1 (string) – directory with temperature scale calculation

  • folder2 (string) – directory with temperature scale calculation

  • fit_order (int, optional) – default 4. Order for polynomial fit of temperature vs free energy

  • plot (bool, optional) – default True. Plot the results.

calphy.postprocessing.fix_composition_scaling(dfdict, correct_entropy=True, add_ideal_entropy=False)[source]#

Correct composition-scaling free energies by adding the reference free energy and (optionally) subtracting the ideal-entropy term.

Parameters:
  • dfdict (dict of DataFrame) – Output from clean_df.

  • correct_entropy (bool) – If True and add_ideal_entropy is True, subtract T * S_ideal from the free energy.

  • add_ideal_entropy (bool) – Controls whether the ideal-entropy correction is applied.

calphy.postprocessing.gather_results(mainfolder, reduce_composition=True, extract_phase_prefix=False, include_sweep_data=False, sweep_data_stride=1)[source]#

Gather results from all subfolders in a given folder into a Pandas DataFrame

Parameters:
  • mainfolder (string) – folder where calculations are stored

  • reduce_composition (bool) – If True, per species composition arrays are added. Might be redundant.

  • extract_phase_prefix (bool) – Should be used in conjuction with phase diagram mode. Extracts the prefix and add it as a phase_name column.

  • include_sweep_data (bool, optional, default False) – Load the raw per-lambda switching data of every reversible-scaling replica into the frame. Off by default because it is expensive: ts.forward_*.dat / ts.backward_*.dat are written by fix print 1, i.e. one row per MD step, so a sweep of n_switching_steps keeps roughly n_switching_steps * 32 bytes per replica per calculation resident in the frame (~1.6 MB per calculation for a 50000-step sweep, scaling with n_iterations). Enable it when diagnosing where along a sweep forward and backward diverge; leave it off to gather free energies.

  • sweep_data_stride (int, optional, default 1) – Keep only every n-th sample of the sweep data. Only meaningful with include_sweep_data=True; a stride of 10–100 preserves the shape of the hysteresis while cutting the memory cost proportionally.

Returns:

df – DataFrame with results. In addition to the columns produced previously, this also includes:

  • free_energy_error: array (ts/tscale, from temperature_sweep.dat) or 0.0 (fe/alchemy/composition_scaling); the statistical standard error of the mean free energy, not a hysteresis check.

  • dissipation: mean switching dissipation (fe/alchemy) or NaN (ts/tscale)

  • ts_dissipation: max hysteresis over a ts/tscale sweep, or NaN otherwise

  • ts_dissipation_high: True where that hysteresis exceeded tolerance.dissipation, i.e. the sweep did not stay reversible and the free energy it produced should not be trusted; False when it was within tolerance, NaN where no verdict was recorded

  • forward_energy_diff / backward_energy_diff: list of arrays, one per reversible-scaling replica (ts/tscale only, else None); the raw per-lambda energy differential, useful to see where along the sweep forward/backward diverge (phase-transition diagnostic). Populated only when include_sweep_data is True, else None.

  • forward_lambda / backward_lambda: matching lambda arrays for the above (ts/tscale only, else None)

Return type:

pandas DataFrame

Notes

A calculation whose sweep files are unreadable (a job killed mid-sweep leaves a ragged final row) does not abort the gather: its sweep columns stay None and the reason is recorded in error_code.

calphy.postprocessing.read_report(folder)[source]#

Read the finished calculation report

Parameters:

folder (string) – folder from which calculation is to be read

Returns:

data – dictionary with results

Return type:

dict

calphy.queuekernel module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

calphy.queuekernel.main()[source]#
calphy.queuekernel.run_calculation(job)[source]#

Run calphy calculation

Parameters:

job (Phase class) –

Returns:

job

Return type:

Phase class

calphy.queuekernel.setup_calculation(calc)[source]#

Set up a calculation

Parameters:
  • options (dict) – options object

  • kernel (int) – index of the calculation to be run

Returns:

job – job class

Return type:

Phase class

calphy.routines module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

class calphy.routines.MeltingTemp(calculation=None, simfolder=None, log_to_screen=False)[source]#

Bases: object

Class for automated melting temperature calculation.

Parameters:
  • options (dict) – dict of input options

  • kernel (int) – the index of the calculation that should be run from the list of calculations in the input file

  • simfolder (string) – base folder for running calculations

CROSSING_STENCIL = 50#
DETECTION_LIQUID_FRACTION = 0.05#
DETECTION_SOLID_FRACTION = 0.7#
__init__(calculation=None, simfolder=None, log_to_screen=False)[source]#
calculate_tm()[source]#
extrapolate_tm(arg)[source]#

Extrapolate Tm

find_tm()[source]#

Find melting temperature

Parameters:

None

Return type:

None

get_trange()[source]#

Get temperature range for calculations

Parameters:

None

Return type:

None

prepare_calcs()[source]#

Prepare calculations list from given object

Parameters:

None

Return type:

None

run_jobs()[source]#

Run calculations

Parameters:

None

Return type:

None

start_calculation()[source]#

Start calculation

Parameters:

None

Return type:

None

calphy.routines.routine_alchemy(job)[source]#

Perform an FE calculation routine

calphy.routines.routine_composition_scaling(job)[source]#

Perform a compositional scaling routine

calphy.routines.routine_fe(job)[source]#

Perform an FE calculation routine

calphy.routines.routine_pscale(job)[source]#

Perform pscale routine

calphy.routines.routine_ts(job)[source]#

Perform ts routine

calphy.routines.routine_tscale(job)[source]#

Perform tscale routine

calphy.scheduler module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

class calphy.scheduler.Local(options, cores=1, directory='/home/runner/work/calphy/calphy')[source]#

Bases: object

Local submission script

__init__(options, cores=1, directory='/home/runner/work/calphy/calphy')[source]#
submit()[source]#

Submit the job

write_script(outfile)[source]#

Write the script file

class calphy.scheduler.SGE(options, cores=1, directory='/home/runner/work/calphy/calphy')[source]#

Bases: object

Slurm class for writing submission script

__init__(options, cores=1, directory='/home/runner/work/calphy/calphy')[source]#

Create class

submit()[source]#

Submit the job

write_script(outfile)[source]#

Write the script file

class calphy.scheduler.SLURM(options, cores=1, directory='/home/runner/work/calphy/calphy')[source]#

Bases: object

Slurm class for writing submission script

__init__(options, cores=1, directory='/home/runner/work/calphy/calphy')[source]#

Create class

submit()[source]#

Submit the job

write_script(outfile)[source]#

Write the script file

calphy.solid module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

class calphy.solid.Solid(calculation=None, simfolder=None, log_to_screen=False)[source]#

Bases: Phase

Class for free energy calculation with solid as the reference state

Parameters:
  • options (dict) – dict of input options

  • kernel (int) – the index of the calculation that should be run from the list of calculations in the input file

  • simfolder (string) – base folder for running calculations

__init__(calculation=None, simfolder=None, log_to_screen=False)[source]#
analyse_spring_constants(lmp)[source]#

Analyse spring constant routine

assign_spring_constants(k)[source]#

Here the spring constants are finalised, add added to the class

run_averaging()[source]#

Run averaging routine

Parameters:

None

Return type:

None

Notes

Run averaging routine using LAMMPS. Starting from the initial lattice two different routines can be followed: If pressure is specified, MD simulations are run until the pressure converges within the given threshold value. If fix_lattice option is True, then the input structure is used as it is and the corresponding pressure is calculated. At the end of the run, the averaged box dimensions are calculated.

run_integration(iteration=1)[source]#

Run integration routine

Parameters:

iteration (int, optional) – iteration number for running independent iterations

Return type:

None

Notes

Run the integration routine where the initial and final systems are connected using the lambda parameter. See algorithm 4 in publication.

run_spring_constant_convergence(lmp)[source]#
thermodynamic_integration()[source]#

Calculate free energy after integration step

Parameters:

None

Return type:

None

Notes

Calculates the final work, energy dissipation and free energy by matching with Einstein crystal

calphy.splines module#

calphy: a Python library and command line interface for automated free energy calculations.

Copyright 2021 (c) Sarath Menon^1, Yury Lysogorskiy^2, Ralf Drautz^2 ^1: Max Planck Institut für Eisenforschung, Dusseldorf, Germany ^2: Ruhr-University Bochum, Bochum, Germany

calphy is published and distributed under the Academic Software License v1.0 (ASL). calphy is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. calphy API is published and distributed under the BSD 3-Clause “New” or “Revised” License See the LICENSE FILE for more details.

More information about the program can be found in: Menon, Sarath, Yury Lysogorskiy, Jutta Rogal, and Ralf Drautz. “Automated Free Energy Calculation from Atomistic Simulations.” Physical Review Materials 5(10), 2021 DOI: 10.1103/PhysRevMaterials.5.103801

For more information contact: sarath.menon@ruhr-uni-bochum.de/yury.lysogorskiy@icams.rub.de

The splines are from:

# Supplemental Material for The Uhlenbeck-Ford model: Exact virial coefficients and application as a reference system in fluid-phase free-energy calculations” # Authors: Rodolfo Paula Leite(1), Rodrigo Freitas(2), Rodolfo Azevedo(3), and Maurice de Koning(1) # 1 - Instituto de Física “Gleb Wataghin”, Universidade Estadual de Campinas, UNICAMP, 13083-859, Campinas, São Paulo, Brazil # 2 - Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, U.S.A. # 3 - Instituto de Computação, Universidade Estadual de Campinas, UNICAMP, 13083-852, Campinas, São Paulo, Brazil

calphy.utils module#

Module contents#

calphy.addtest(a, b)[source]#