Release notes¶
2.0.0a1¶
MDAPY 2.0 is a complete rewrite and is not compatible with MDAPY 1.x. The name
is written MDAPY, with mdapy for the package, the imports and the commands,
and it has a new logo.
The top level of mdapy holds the foundations: System, Box, Topology,
NeighborList, the threads, the versions and the modules. Everything else comes from its
module, as mdapy.io.read or from mdapy.build import build_crystal.
Columns of results are named by their method and options, as cna_structure, ptm_rmsd
or q6_average_voronoi, so that several analyses stay side by side;
with_columns(near=result) gives a prefix, and two values for a column in one call are an
error.
Structures¶
mdapy.System: one atomic configuration with a polars table of per-atom properties, a box, global information and an optional topology. Systems are immutable:with_*methods return new systems that share the columns they do not change and check only the ones they do; arrays given to a system are copied, its table is handed out as a copy, it takes no new attributes, andcopy.deepcopyreturns the system itself; systems, boxes, topologies and triangle meshes pickle, for other processes. Every column, the positions too, is read by name and changed withwith_columns; the positions are an (N, 3) array column read without copying,system["positions"]. A summary of a few lines shows the atoms, the box, the columns, the global information and the topology.select,dropandrenamechoose, remove and rename columns as polars does, andwith_info({})clears the global information. See Systems and Changing a system.System.filter,System.gatherandSystem.sortkeep atoms by a condition, take them by index and order them, as polars does with rows. Conditions are Python expressions over the columns, such as"positions.x**2 + positions.y**2 < 25 and element == 'Cu'", with the components of array columns by name or index, comparisons, logic, membership, arithmetic and common functions; keywords, masks and polars expressions work too.System.wheregives the atoms of the same conditions as a boolean mask.system["positions.z"]gives the values of a column, a component or such an expression as a read-only NumPy array, without a copy for columns and components. See Selecting and ordering atoms.mdapy.Topology: bonds, angles, dihedrals and impropers with types and labels, kept consistent when atoms are selected or reordered. See Topology.mdapy.Box: immutable simulation box with lattice vectors, origin and periodicity; fractional coordinates, wrapping with image flags, exact minimum images, and conversion to LAMMPS restricted triclinic form. See Simulation box.
Reading and writing¶
mdapy.io.readandmdapy.io.writeread one frame and write one or more frames, finding the format from the file name. Files compressed with gzip, bzip2, xz or zstd (Python 3.14) are read and written transparently.mdapy.io.formatsandmdapy.io.detect_formatlist and identify formats. See Reading and writing files.- Extended XYZ with the conventions of ASE and GPUMD: velocities from
vel(Å/fs) or ASEmomenta, stress in GPa, any per-atom column and any global value, written so that they read back unchanged. See Extended XYZ. - LAMMPS data files of the atom styles atomic, charge, bond, angle, molecular and full, following LAMMPS stable_30Sep2026: type labels, masses with element guessing, bonds to impropers as the topology, force-field coefficients kept unchanged, image flags, velocities, metal and real units, and restricted and general triclinic boxes. See LAMMPS data.
- LAMMPS text dumps of the atom and custom styles, with any number of frames:
units and time items, orthogonal, triclinic and general triclinic boxes,
scaled and unwrapped coordinates, elements and type labels, and every other
column, array columns such as
c_stress[1]toc_stress[6]kept together. See LAMMPS dump. - VASP POSCAR and CONTCAR: scaling factors, POTCAR labels, selective
dynamics as the
movablecolumn, Direct and Cartesian coordinates, and the velocity block of a CONTCAR. See VASP POSCAR. - The MDAPY file format
.mdapy: a ZIP archive of Parquet tables that keeps every column with its type, the box, the information and the topology of each frame, a table of frames with typed columns of the information, and recovery of files whose writing stopped early. See MDAPY files. mdapy.io.read_trajectoryopens the frames of any file lazily: frames are found and read when used, slices share the open file, and iteration starts at once; also the frames of several files, given as a pattern such asdump.*.lammpstrjor a list, each in the format of its name, and frames that move the atoms of a topology read from a data file, matched by id, with its bonds, charges and molecules, as OVITO's load trajectory;Trajectory.mapgives the frames through a function, each computed when it is used, for the analyses of trajectories. See Trajectories.Trajectory.file_ofgives the file that holds a frame.- Reading CIF files, crystals expanded by their symmetry operations as
pymatgen, ASE and OVITO read them, and PDB files, with atom names,
residues, models as frames and the bonds of
CONECT; VASP OUTCAR files, one frame per ionic step with the forces, the free energy TOTEN, the virial and whether the step converged, as ASE reads them. See CIF, PDB and VASP OUTCAR. - Damaged files give a
FileFormatErrorin every format: bytes that are not text, a.mdapyfile cut or changed anywhere, a file without atoms that read as an empty system before.
Neighbor search¶
mdapy.NeighborList.build(system, cutoff)andNeighborList.build(system, num_neighbors=k): every pair within a cutoff, or the k nearest neighbors of each atom, in any box, with periodic images enumerated so that small boxes work, in CSR form with int8 image shifts (15 bytes per pair);withinandsortedderive lists without a new search. Distances are computed by one formula in both, nearest neighbors are ordered exactly with ties by atom and image, and results are the same for any number of threads. A k-d tree finds nearest neighbors in clusters and slabs as fast as in crystals. A list serves every system with the same positions in the same box (fits), so it outliveswith_columns. A system whose atoms fill a tiny part of the space they span, which would take hours, is refused with an error. See Neighbor lists.mdapy.neighbor.expand_selection: a selection grown by the atoms within a cutoff, the nearest neighbors or the bonded atoms of the selected ones, step by step, as OVITO's expand selection. See Expanding a selection.mdapy.neighbor.find_overlapping: the atoms closer than a distance to another, the later atom of each such pair so that deleting them leaves none that close, or all of them, as OVITO's find overlapping particles. See Overlapping atoms.- Analyses given a list read it where it is, without a copy: those of the
k nearest neighbors put the k nearest pairs of each atom first in the
list itself, once, in parallel; those within a cutoff read the pairs
closer than theirs and stop at the first sorted pair beyond it. One list
within 5 Å serves every structure analysis of a metal; threads may share
a list. A list keeps 15 bytes per pair:
iandvectorsare computed when asked for. See Sharing neighbor lists. - Atoms far apart, up to 1e9 box lengths: a search along a direction without periods puts its cells over the body of the atoms, so that an atom that flew off leaves the others as fast as before (0.03 s, not 12 s, for 200 000 atoms), and the number of cells no longer overflows, which could crash the process.
- A list of Voronoi neighbors finds its distances in parallel and, in a periodic box, keeps the arrays of the cells without a copy: Steinhardt parameters over Voronoi faces take a quarter less time and 40 % less memory.
Calculators¶
mdapy.calculators.Calculator, the interface of every calculator, andCalculatorResultwith energies, forces, virials and stress.mdapy.calculators.testing.check_calculatortests any implementation. See Calculators.mdapy.calculators.EAMfor potentials in the LAMMPS eam/alloy format, agreeing with LAMMPS.mdapy.calculators.NEPfor neuroevolution potentials (nep4 and nep4_zbl files of GPUMD) with every form of ZBL and per-element cutoffs, agreeing with NEP_CPU in double precision;NEP.descriptorsgives the descriptors.EAM.writewrites potentials in the LAMMPS eam/alloy format;EAM.zhoubuilds the potentials of Zhou, Johnson and Wadley for 17 elements, as the LAMMPS database tool tabulates them;EAM.averagegives the average-atom potential of a random alloy.mdapy.calculators.LAMMPSmakes any interaction of LAMMPS a calculator, through the LAMMPS Python module.mdapy.calculators.VASPruns VASP for each calculation with a command, as in the job script of a cluster: it writes the inputs, keeps the wave functions between calls and reads the OUTCAR.CalculationFailedreports a run that stopped. See VASP.
Simulation¶
mdapy.simulation.minimize: FIRE 2.0 minimization of the positions, step for step as LAMMPSmin_style fire, and optionally of the box (cell="isotropic","axes"or"full", at apressure) to the minimum of LAMMPSfix box/relax; keeps a frame everysave_everysteps when asked, with the virial and the stress of each. Its steps use no BLAS, whose threads took the cores from the kernels under OpenBLAS (0.5 s against 3.5 s for 4000 atoms on 16 threads). See Energy minimization.mdapy.simulation.free_energy: the free energy of solids and liquids per atom from molecular dynamics in LAMMPS, by switching to springs or to the Uhlenbeck-Ford model and following the enthalpy to other temperatures;crossinggives where two phases meet. See Free energy.mdapy.simulation.melting_point: the melting point from a first guess, by the two-phase method.MolecularDynamics.runtakes the ensemble"nph". See Melting point.mdapy.simulation.binary_phase_diagramandplot.phase_diagram: the phase diagram of two elements from the free energies of their phases. See Phase diagrams.mdapy.simulation.pressure_temperature_diagramandplot.pressure_temperature: the phase diagram of one element against pressure and temperature, from the free energies of its phases at each pressure. See Pressure-temperature diagrams.mdapy.simulation.stacking_fault_free_energy: the free energy of a stacking fault at each temperature, from two crystals in one box. See Stacking faults at finite temperature.slip: an atom outside the box moves as its image in the box does; a layer of a relaxed crystal at the bottom of the box was split by rounding, and gave a stacking fault energy far too large.mdapy.lattice_dynamics.elastic_constants: the (6, 6) elastic constants from the stress under small strains, with relaxed positions, and Voigt, Reuss and Hill moduli. See Elastic constants.mdapy.lattice_dynamics.phonons: harmonic phonons from the forces on displaced atoms with any calculator, the force constants made symmetric and free of translations; frequencies and polarization vectors at any wave vector, band structures along standard or given paths, densities of states by the tetrahedron method or Gaussians, projected on the atoms, and the free energy, energy, entropy and heat capacity of the vibrations; the same dynamical matrix as LAMMPS.primitive_cellfinds the smallest cell of a crystal; supercells as integer matrices, by default the one nearest a cube; standard paths of any crystal with seekpath, and branches followed through crossings; imaginary frequencies in the density of states; band structures written and read as phonopy's band.dat;plot.band_structureandplot.phonon_dos.units.PLANCK. See Phonons.mdapy.lattice_dynamics.quasi_harmonic: the quasi-harmonic approximation from phonons at several volumes: the equilibrium volume, Gibbs energy, entropy, bulk modulus, thermal expansion and heat capacity at constant pressure against temperature, at any pressure, the shape of the box relaxed at each volume. See Quasi-harmonic approximation.mdapy.lattice_dynamics.thermal_elastic_constants: isothermal and adiabatic elastic constants at finite temperature, quasi-harmonic or quasi-static. See Elastic constants at finite temperature.- Sheets: a box periodic along two vectors in the x-y plane makes a system a
two-dimensional material.
elastic_constantsgives its constants in N/m as aSheetElasticResult, with Young's, shear and area moduli and Poisson's ratios;phononstakes supercells and meshes in the plane and band paths through it;primitive_celltakes it too;MolecularDynamics.runcontrols the pressure in the plane withbarostat="xy", and runs a flat sheet, which LAMMPS refused when its height shrank to nothing. See Sheets. mdapy.lattice_dynamics.thermal_phononsandphonons_from_frames: phonons at a temperature, from the forces on atoms in molecular dynamics, by the force constants that best give them. See Phonons at finite temperature.mdapy.lattice_dynamics.md_elastic_constants: isothermal elastic constants at a temperature from the mean stress of molecular dynamics in LAMMPS under small strains, with standard errors from block averages. See Elastic constants from molecular dynamics.- Symmetry with spglib (optional, the extra
symmetry):phonons,quasi_harmonic,elastic_constantsandthermal_elastic_constantsskip the displacements and strains that the symmetry of the crystal relates to others, by default whenever spglib is installed: one computation of forces instead of 6 for the primitive cell of fcc, 12 of the 73 strains of the elastic constants of a cubic crystal at finite temperature. The elastic constants take the rotations alone, in milliseconds also for cells of hundreds of atoms. See Space group. -
mdapy.simulation.MolecularDynamics: molecular dynamics in LAMMPS with the interaction of a LAMMPS calculator: random velocities, runs at constant energy, temperature or pressure with ramps, the thermodynamic state as a polars table, frames and the final system back in the orientation of the box, any LAMMPS command in between; the same trajectory as the same LAMMPS input. See Molecular dynamics. -
mdapy.simulation.vacancy_formation_energy,surface_energyandstacking_fault_energy(the generalized stacking fault energy, relaxed along the normal), agreeing with LAMMPS;minimizekeeps atoms still along the directions where amovablecolumn is False. See Defect energies.
Analyses¶
- Analyses are classes whose
compute(system)returns an immutable result;System.with_columns(result)adds its per-atom values. See Analyses. - Structure identification in
mdapy.identify:CommonNeighborAnalysis, adaptive or with a fixed cutoff, andAcklandJonesAnalysis, agreeing atom by atom with LAMMPS, for fcc, hcp, bcc and icosahedral atoms;DiamondStructurefor cubic and hexagonal diamond and their first and second neighbors, as OVITO;ChillPlusfor ice, hydrates and liquid water; and the centro-symmetry and common neighbor parameters. ChemicalSpecies: molecules and their Hill formulas by the bond rule of Jmol (covalent radii, the default) or of VMD and OVITO (van der Waals radii), radii given by hand or bond lengths per pair of elements, and the number of each along a trajectory; the same molecules as ASE and as OVITO.mdapy.elementshas the covalent and van der Waals radii, which pictures now read from it.SpaceGroup: the space group of a crystal, its symmetry operations and equivalent atoms, with spglib, for cells of up to 2000 atoms.PolyhedralTemplateMatching: the structure, orientation, elastic deformation and chemical ordering of each atom, for nine structures, implemented by MDAPY itself; the same as OVITO atom by atom.PlanarFaults: intrinsic and multilayer stacking faults and coherent twin boundaries of fcc crystals from the hcp-like atoms of polyhedral template matching, and their areas; the same as OVITO's Identify fcc planar faults atom by atom; optionally extrinsic stacking faults too.GrainSegmentation: the grains of a polycrystal from the lattice orientations of polyhedral template matching, by node pair sampling with an automatic threshold or along a minimum spanning tree, with stacking faults and twin boundaries joined to the grains around them and orphan atoms adopted; the grain of each atom, and the size, structure, mean orientation, center of mass and radii of each grain, the same as OVITO's Grain segmentation atom by atom.- Distributions and order parameters in
mdapy.analysis, agreeing with OVITO where it has them: theRadialDistributionFunctionand its partial functions;CoordinationNumberwith cutoffs per pair of elements; theStructureFactor, exact over the wave vectors of the box or by the Debye method, with Faber–Ziman partial factors; theSpatialCorrelationfunction of two properties of the atoms, by fast Fourier transforms on a grid and by a direct sum over neighbors, the same as OVITO's spatial correlation function; theBondAngleDistributionfor each triplet of elements; theBondLengthDistributionof the bonds of a topology, in total and for each pair of elements;RingStatistics, the shortest-path rings of a network of bonds up to 36 atoms, without the paths around the periodic box, drawn as polygons;WarrenCowleyshort-range order, over shells of neighbors by distance or by number;SteinhardtParametersup to degree 20, optionally averaged, and withsolid=Truethe solid-like bonds and atoms of ten Wolde, Ruiz-Montero and Frenkel, as freud'sSolidLiquid(MDAPY 1.xidentify_liquid); theEntropyFingerprint; and theVoronoiAnalysis, computed by mdapy's own code, with the volumes and coordination of the cells and, when asked for, their faces and Voronoi indices (faces=True), which otherwise are not kept, the face and edge thresholds of OVITO, boxes that are not periodic, and the shapes of the cells as polyhedra;NeighborList.build(system, voronoi=True)for the atoms that share a face, and Steinhardt parameters over them, optionally weighted by the face areas. - Dynamics in
mdapy.analysis: theMeanSquaredDisplacementof a trajectory, over every time origin or from the first frame, agreeing with LAMMPS and OVITO; theLindemannIndexof each atom and of the frames so far; both match the atoms of the frames by their ids and follow them through the periodic boundaries by their image flags or by the nearest image, unless the positions are already unwrapped. TheAtomicTemperatureof each atom and its neighbors, relative to their center of mass.TimeAverage: the mean of a column of the atoms, of the box or of anything computed from a frame over a trajectory, the atoms matched by id and their positions unwrapped, as OVITO's time averaging.trajectory_lines: the paths of the atoms, unwrapped by their image flags or the nearest image, drawn byrender(lines=...).mdapy.transform.remove_drift: the frames of a trajectory moved to keep the center of mass of all the atoms or of some where it is in a reference frame, read when they are used, as OVITO's center of mass correction.TimeSeries: a column reduced to one number, or anything computed, in every frame, as OVITO's time series;FrameDifference, the change of a column of each atom from a reference frame;mdapy.transform.freeze, the values of a column in a reference frame given to the atoms of another; andmdapy.transform.smooth_trajectory, the positions and other real numbers averaged over a window of frames; each as OVITO's modifier of the same name, the atoms matched by id. - Statistics of a column in
mdapy.analysis, agreeing with OVITO:Histogram, the counts of the values of a column, a component or an expression in bins, of all atoms or of a mask;reduce, one number from them: mean, sum, extremes, median, variance, standard deviation, the count of those not zero, or the atom of the lowest or highest, NaN values left out. - Defects and deformation in
mdapy.analysis, agreeing with OVITO:ClusterAnalysisfor clusters of bonded atoms and whether they span the box, and on request their unwrapped positions, centers of mass and gyration tensors;AtomicDisplacement, the displacement of each atom from a reference matched by id, with the minimum image and the affine mapping of OVITO's displacement vectors;SpatialBinning, a property in bins along one to three box vectors, its mean, sum, density, minimum or maximum, the values of OVITO's spatial binning; theisosurfaceof a grid of such values, by marching tetrahedra, across the periodic boundaries, and its cells as colors on the faces of the box bymdapy.visualization.voxel_faces;WignerSeitzfor vacancies and interstitials, the sites of the reference kept in a k-d tree for every configuration; andAtomicStrain, the von Mises and volumetric strains against a reference, its atoms matched by id, and on request the Green–Lagrange strain tensor and \(D^2_\text{min}\). As in OVITO, the results that cost more are computed only when asked for. ElasticStraininmdapy.analysis: the elastic strain of each atom of an fcc, hcp, bcc or diamond crystal against the ideal crystal of given lattice constants, in the spatial frame, with the structures of the dislocation analysis; the same as OVITO's elastic strain calculation atom by atom.SurfaceMeshinmdapy.analysis: the surface of the solid of atoms by the alpha-shape method of OVITO's Construct surface mesh, from a Delaunay tessellation of mdapy's own, with its area, the volume of the solid, the regions of solid and empty space and the voids among them, the atoms on the surface, and Taubin's smoothing; the same areas, volumes and atoms as OVITO. The surface is amdapy.analysis.TriangleMesh, a mesh of triangles across periodic boundaries.DislocationAnalysisinmdapy.analysis, experimental: the dislocation lines of fcc, hcp, bcc, cubic and hexagonal diamond crystals by OVITO's dislocation extraction algorithm, written anew: Burgers vectors in the lattice frame and in space, partials of stacking faults, junctions, loops, the defect mesh around grain boundaries and surfaces; the same structures atom by atom as OVITO, the same lines and lengths within a per cent on straight dislocations and loops, within several per cent in networks and at grain boundaries.
Structure builder¶
mdapy.build.build_crystal: perfect crystals of fifteen structures, cubic and hexagonal, of one element or ordered on their sublattices, along any crystal directions, with the shortest period along each; the same atoms as atomsk, ordered plane by plane without sorting them (2 million atoms in some 0.05 s). See Crystals.mdapy.build.random_alloy: elements at random in given fractions with exact counts. See Random alloys.mdapy.build.sqs_alloy: special quasirandom structures, the pairs of the nearest shells those of a random alloy. See SQS.- Defects in
mdapy.build:add_vacancies,add_interstitialsandsubstitute;slipfor stacking faults;add_vacuumfor surfaces;insert_dislocation, the isotropic screw and edge dislocations of atomsk, andedge_dislocationof two crystals. See Point defects and Dislocations. - Dislocations in anisotropic elasticity in
mdapy.build:insert_dislocation(..., elastic=), the displacements of Stroh, the same as atomsk with an elastic tensor;dislocation_cylinder, a cylinder around a dislocation with a fixed outer shell (movable), anddislocation_quadrupole, a periodic quadrupole in a box tilted by the plastic strain of the dipole;DISLOCATIONS, the common dislocations of bcc, fcc and diamond (glide set), or aDislocationof your own; fcc and diamond ones split into Shockley partials around an intrinsic stacking fault. Burgers vectors as the dislocation analysis and OVITO find them, the opposite of Hirth and Lothe's (and atomsk's). See Dislocations. mdapy.build.add_graphene: graphene on the grain boundaries of a polycrystal, one or more AB-stacked layers centered on each face between two grains, each face once, in a random orientation, cut to the face; a fraction of the boundary area covered by whole faces; the atoms of the grains too close to the carbon removed.build_polycrystalkeeps the seeds ininfo["seeds"]. See Graphene on grain boundaries.mdapy.build.build_polycrystal: Voronoi grains of any periodic unit, columnar when the box is thin,twin_lamellaefor twinned grains,rotations_aboutfor the turns of columns, andgradient_seedsfor grains whose size changes along one direction, from one side or both. See Polycrystals, which also builds grains of graphene, and Gamma surfaces.mdapy.transform.replicatecopies a system along its periodic directions as LAMMPSreplicatedoes, with the ids, molecules and topology of each copy and molecules kept whole through the image flags;wrapandunwrapmove atoms into the box or to their unwrapped positions. See Periodic copies and images.mdapy.transform.slice: the atoms on one side of any plane or in a slab about it, as the Slice of OVITO: a normal in Cartesian coordinates or as Miller indices of the box, at a distance or through a point, acting on all atoms or some;slice_maskthe same as a mask. See Slices.mdapy.transform.affine: moves, rotates, shears or scales the atoms, their velocities, forces and displacements, and the box, all atoms or a selection, as OVITO's affine transformation modifier. See Affine transformation.mdapy.transform.combine: the atoms of a second system added to a first, in its box, as OVITO's combine datasets: the columns of either, ids numbered on, molecules and topology terms offset. See Combining systems.mdapy.transform.create_bonds: bonds in the topology between the atoms closer than a cutoff, or covalent bonds, as OVITO's create bonds; drawn byrender(bonds="topology"). See Creating bonds.
MLIP¶
- Training sets from VASP: the ionic steps of OUTCAR files, read as trajectories with energies, forces, virials and convergence, written to extended XYZ. See Training sets from VASP.
mdapy.mlip.SOAP: the smooth overlap of atomic positions of each atom, the same values as DScribe's SOAP with Gaussian radial functions, in C++, for any structures whatever made them. See SOAP descriptors.mdapy.mlip.structure_descriptors,farthest_point_samplingandprincipal_components: frames chosen far from a training set and from each other in the space of NEP descriptors, and their projection on a plane. See Choosing frames.mdapy.mlip.perturb: copies of a structure with atoms displaced and the box strained at random. See Perturbed structures.mdapy.mlip.predictandread_gpumd: errors of any model against the labels of a training set, frame by frame, or read from the outputs of NEP training in GPUMD and of torchnep. See Errors of a model.mdapy.mlip.committeeandnovelty: the spread of the predictions of several models and the distance from a training set in the space of descriptors, to find frames worth labeling. See Uncertainty and novelty.mdapy.mlip.check_frames: atoms too close, net forces and missing labels in a training set. See Checking frames.- Training sets of many small frames:
predict,committeeandstructure_descriptorscompute NEP models and SOAP, andcheck_framesthe closest pairs, many frames at a time in C++, a frame on a thread, each as it would be alone: for the 105,464 frames of UNEP16 on an Apple M5, the NEP descriptors in 15 s rather than 26 s, its predictions in 24 s rather than 35 s, and the checks in 2 s rather than 8 s.noveltyscreens the pairs in float32 on threads and computes the distances of the candidates exactly: their novelty in 5 s rather than 30 s.
Visualization¶
mdapy.visualization.render: pictures of systems by ray tracing, with ambient occlusion, shadows and outlines in four styles: fast, lit as the viewports of OVITO; matte, as the Tachyon renderer of OVITO (the default); shiny, a metallic sheen after its OSPRay renderer, with light bouncing between the atoms; flat, plain colors outlined as ASE draws atoms; colored by element, structure, values or by hand, with bonds, the box, Voronoi cells, surface meshes and dislocation lines with arrows of their Burgers vectors, cut at the periodic faces of the box; arrows of any vector of the atoms, such as displacements or forces, as OVITO's vector display draws them; polylines such as the paths of atoms; coordination polyhedra, the convex hulls of the neighbors of atoms with their volumes, as OVITO builds them; molecules as balls and sticks, licorice or space filling, with covalent bonds found from the elements; aSceneof spheres, cylinders and polygons; the scene framed, or a given focus and span; depth of field and soft shadows; every setting of a style can be changed, including the direction of the highlights, metals and lighting in sRGB; a million atoms in under 5 s on the processor in the matte style, or in under a second on the GPU, with Metal on macOS, Vulkan on Linux or Direct3D 12 on Windows, which use the ray tracing units of the GPU where it has them;show_imageshows a picture in a notebook;legend=Truesays what the colors mean. See Rendering. A driver that runs on the processor does not count as a GPU.- Colors of atoms in
mdapy.visualization:color_coding,color_by_typeandassign_colorcolor all atoms or a mask and keep the colors in thecolorcolumn, whichrenderdraws by default, as OVITO's modifiers of these names;atom_colorsandatom_radiiwith colors and radii of elements chosen and a scale; colormaps rainbow, viridis, magma, jet, hot, blue_white_red and gray computed as OVITO computes them, besides plasma and coolwarm, and labels for discrete values. Atom types without elements, as in a LAMMPS dump of types only, are drawn each in a color of its own, those of OVITO (TYPE_COLORS), and all of one radius;atom_namesgives the names these colors go by, andread_trajectory(path, elements=[...])names the types, so that files written afterwards hold the elements. See Coloring atoms. mdapy.visualization.plot: matplotlib set up for journals, in notebooks too (widths of columns, Nature's artwork guide, Okabe–Ito colors, panel labels, saving as PDF, SVG and PNG) and plots of results: parity, g(r), S(q), bond angles, MSD with the diffusion coefficient, stacking fault energies, counts of structures, and two columns of the atoms against each other (scatter). See Plots.
Interoperability¶
mdapy.interop.to_aseandfrom_aseconvert to and fromase.Atoms, with velocities, charges, constraints, other numeric columns and the results of a calculation. See ASE.mdapy.interop.to_ase_calculatormakes any MDAPY calculator an ASE calculator, andfrom_ase_calculatorany ASE calculator, such as that of torchnep, an MDAPY calculator. See ASE calculators.mdapy.interop.to_ovitoandfrom_ovitoconvert to and from OVITO data collections, with types, standard properties, the topology and the attributes, so that results of OVITO pipelines come back as columns. See OVITO.mdapy.interop.to_pymatgenandfrom_pymatgenconvert to and from pymatgen structures and molecules. See pymatgen.mdapy.interop.to_freudgives the box and points of freud's analyses, for systems periodic in every direction, andfrom_freudtakes them back. See freud.- Pages on exchanging files and calculators with LAMMPS, VASP and GPUMD.
Performance¶
benchmarks/comparison.pytimes the analyses that MDAPY shares with OVITO and freud, on the same systems, where each program gives the result of MDAPY, each program in a process of its own with limits of memory and time. See MDAPY, OVITO and freud.- Extended XYZ files of many small frames read faster: the comment line is split at once in its common form, the element column comes from the categories kept for the file, and the box and the columns are checked with less work. The 105,464 frames of UNEP16 read in 15 s rather than 19 s on an Apple M5; small frames about 40 % faster.
Tutorials¶
- Learn MDAPY: six short lessons that run on their own, from a crystal as a table to a nanoparticle that melts and your own LAMMPS dumps, and a cheat sheet. See A crystal is a table.
- Worked examples that combine several parts of MDAPY: a polycrystal of fcc
and bcc grains, columnar grains on a hexagonal pattern with chosen
misorientations, the defect energies of copper with checks of their
convergence, when sharing neighbor lists pays, what a
Systemshares and copies, a machine-learned potential for CrCoNi: the phonons of Cr, Co and Ni against DFT and the elastic constants of the alloy from 0 to 1000 K against measurements, a high-throughput screen of alloys in many processes with the thread settings it needs, and a movie that flies through a crystal. See the Tutorials under Getting started. - Pictures with the examples: the pages of the structure builders and of
most analyses show what their example makes or finds, drawn by mdapy's
renderer or plotted with
mdapy.visualization.plot, from code on the page that the documentation tests run. - Surfaces and slip systems: the orientations of the common surfaces and slip systems of fcc, bcc, hcp and diamond, how to build their slabs and faults, their surface energies and generalized stacking fault energies, and the shuffle and glide planes of silicon.
Foundations¶
- Released under the Mozilla Public License 2.0: MDAPY may be used in any software, open or closed, and changes to its own files are shared under the same license. MDAPY 1.x is under the GPL 3.0 or later.
- Python 3.11 or newer; NumPy 2.3.1 or newer and polars 2 are the only required dependencies.
- All compiled code is one extension module, built as a single abi3 wheel per platform for Python 3.12 and newer, optimized for speed.
- Atom indices in results are 32-bit,
mdapy.index_dtype; a build with-Ccmake.define.MDAPY_INDEX64=ONuses 64-bit indices for more than 2,147,483,647 atoms. See Installation. - A thread pool of mdapy's own replaces OpenMP, so MDAPY can run in the same process as PyTorch and LAMMPS. Results are identical for any number of threads. The calling thread works too, idle threads wait for the next step briefly before they sleep, and a step of a few pieces wakes only as many threads, so small systems are not slowed down by many cores. See Parallelism.
mdapy.show_versionsprints the versions of MDAPY, Python and the packages it depends on, and the processor, memory and GPU of the machine, to paste into an issue. The bug report form of the issue tracker asks for it and for the shortest code that shows the problem.mdapy.set_num_threads,mdapy.get_num_threads,mdapy.num_threadsand theMDAPY_NUM_THREADSenvironment variable control the number of threads. The default is the logical CPUs the process may use, so that a job of a cluster on part of a node starts no thread for the rest of it (108 s against 6 s for the same relaxations on 2 of 16 CPUs). A forked process gets a warning: polars hangs in it once its parent has used its threads, so start processes withspawn. See Parallelism.mdapy.CancelToken,progresscallbacks and Ctrl-C stop or follow long computations.mdapy.visualization.write_moviewrites pictures as a movie with the FFmpeg of the user, taking them one by one from a generator. See Movies.renderrefuses pictures above 8192 pixels on a side or 16384 subpixels, andwrite_moviemovies above 8192 × 4320 pixels, as larger ones can use up the memory or play nowhere.mdapy.unitsdefines every physical constant and conversion factor. See Units and conventions.mdapy.errorsdefines the exception types.FileFormatErrorreports a malformed file with its name and line number.- Text files are parsed and written by compiled kernels in parallel. Numbers are read correctly rounded and written in the shortest form that reads back to the same value, whatever the locale of the process; unit conversions by powers of ten are exact.
- macOS wheels need macOS 14 or newer.
mdapy.elementsholds chemical symbols and IUPAC standard atomic weights, and identifies elements from masses. See Elements.