diff --git a/AGENTS.md b/AGENTS.md index cdf49da596c..cad229cdb4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -196,6 +196,12 @@ When splitting a function into a new `.cpp`, if its callers span LCAO and PW, pu - Extract a base-class nested-vector member in three steps (hold + forward, switch writers, delete legacy) so no commit mixes old-storage writes with new-storage reads. +- Keep MD geometry output separate from restart checkpoints. A restart STRU + must retain atomic velocities and a step marker matching Restart_md.txt; + ordinary MD STRU files carry per-atom forces and velocities for analysis. +- Sort distributed trajectory output by stable atom identity, not MPI rank or + local storage order; check for duplicate and missing atom indices before + writing each frame. ## Local Commands diff --git a/docs/advanced/input_files/stru.md b/docs/advanced/input_files/stru.md index 885a1e833fc..8618606a326 100644 --- a/docs/advanced/input_files/stru.md +++ b/docs/advanced/input_files/stru.md @@ -252,7 +252,7 @@ For general usage requirements, the APNSv1.0 pseudopotential and orbital set is Several other parameters could be defined after the atom position using key words : - `m` or NO key word: three numbers, which take value in 0 or 1, control how the atom move in geometry relaxation calculations. In example below, the numbers `0 0 0` following the coordinates of the first atom means this atom are *not allowed* to move in all three directions, and the numbers `1 1 1` following the coordinates of the second atom means this atom *can* move in all three directions. - - `v` or `vel` or `velocity`: set the three components of initial velocity of atoms, used only for restarting MD calculations (e.g., `v 1.0 1.0 1.0`). + - `v` or `vel` or `velocity`: set the three components of atomic velocity in atomic units (1 a.u. is about 21.877 Angstrom/fs). MD structure and restart output include this field so the velocities can be read back (e.g., `v 1.0 1.0 1.0`). - `mag` or `magmom` : set the start magnetization for each atom. In colinear case only one number should be given. In non-colinear case one have two choice:either set one number for the norm of magnetization here and specify two polar angle later(e. g. see below), or set three number for the xyz commponent of magnetization here (e. g. `mag 0.0 0.0 1.0`). Note that if this parameter is set, the initial magnetic moment setting in the second line will be overrided. - `angle1`: in non-colinear case, specify the angle between z-axis and real spin, in angle measure instead of radian measure - `angle2`: in non-colinear case, specify angle between x-axis and real spin in projection in xy-plane , in angle measure instead of radian measure @@ -326,7 +326,7 @@ For general usage requirements, the APNSv1.0 pseudopotential and orbital set is - `sc`: set the spin constraint target magnetization for each atom. Can specify one value (z-component) or three values for x, y, z components (e.g., `sc 1.0` or `sc 0.5 0.5 1.0`). Used with spin-constrained DFT (enable with `sc_mag_switch` in INPUT file). - - `f` or `force` or `forces`: three numbers giving the per-atom force (fx, fy, fz) in **eV/Angstrom**. This field is *output-only*: it is written into structure files (STRU{istep}, STRU_NOW, STRU_FINAL) when [`out_stru`](input-main.md#out_stru) is enabled, [`cal_force`](input-main.md#cal_force) is true, and the geometry has been evaluated. When such a file is read back as an input STRU, the `f` values are consumed but ignored -- they are informational only and do not affect the calculation. + - `f` or `force` or `forces`: three numbers giving the per-atom force (fx, fy, fz) in **eV/Angstrom**. This field is *output-only*: it is written into evaluated structure files when [`out_stru`](input-main.md#out_stru) is enabled; MD ordinary frames include it, but `STRU_restart` omits it. When such a file is read back as an input STRU, the `f` values are consumed but ignored -- they are informational only and do not affect the calculation. ### Important Notes for ATOMIC_POSITIONS diff --git a/docs/advanced/interface/candela.md b/docs/advanced/interface/candela.md index 753b305aee2..759ae823f21 100644 --- a/docs/advanced/interface/candela.md +++ b/docs/advanced/interface/candela.md @@ -10,9 +10,9 @@ For Detailed usage of CANDELA, please refer to the [official document](https://c There are two things which need special attention in using CANDELA with ABACUS. First, the input file of CANDELA only takes the name of `INPUT`, the same as ABACUS input file, so you should not run CANDELA in the same folder where you run ABACUS. Second, to use CANDELA to postprocess ABACUS MD trajectory, the following parameters have to be specified in the `INPUT` file of CANDELA in addition to other required parameters: -1. `geo_in_type` has to be set to `ABACUS`; +1. For current ABACUS MD output, convert the STRU trajectory to a CANDELA-supported format and set `geo_in_type` to that format, such as `LAMMPS`. The older `ABACUS` setting applies only to legacy MD dump files; 2. `msd_dt` has to be specified in unit of picosecond, especially in the case of `calculation` = `msd`; -3. `geo_directory` has to be set to the path to the `MD_dump` file in the `OUT.xxx` folder. +3. `geo_directory` has to point to the converted trajectory. CANDELA's older `geo_in_type ABACUS` reader does not read current STRU trajectories directly. As a result, a CANDELA `INPUT` file for calculating PDF from ABACUS should be something like this: ``` calculation pdf # Pair Distribution Function. @@ -36,4 +36,4 @@ struf_dgx 0.05 struf_ng 200 ``` -More examples of CANDELA `INPUT` with ABACUS can be found in the [test](https://github.com/MCresearch/Candela/tree/main/test) directory. \ No newline at end of file +More examples of CANDELA `INPUT` with ABACUS can be found in the [test](https://github.com/MCresearch/Candela/tree/main/test) directory. diff --git a/docs/advanced/md.md b/docs/advanced/md.md index a7d346095db..628f92efd52 100644 --- a/docs/advanced/md.md +++ b/docs/advanced/md.md @@ -28,11 +28,15 @@ When [md_type](./input_files/input-main.md#md_type) is set to npt, [md_pmode](./ Furthermore, ABACUS also provides a [list of keywords](./input_files/input-main.md#molecular-dynamics) to control relevant parmeters used in MD simulations. -The MD output information will be written into the file `MD_dump`, in which the atomic forces, atomic velocities, and lattice virial are controlled by keyword [dump_force](./input_files/input-main.md#dump_force), [dump_vel](./input_files/input-main.md#dump_vel), and [dump_virial](./input_files/input-main.md#dump_virial), respectively. +MD structure output is controlled by [`out_stru`](./input_files/input-main.md#out_stru), [`out_freq_ion`](./input_files/input-main.md#out_freq_ion), and [`out_app_flag`](./input_files/input-main.md#out_app_flag). Set `out_stru 1`, `out_freq_ion 1`, and `out_app_flag 1` to keep every MD step in the appended `STRU` trajectory. With `out_freq_ion 0`, only `STRU_FINAL` is written. Mode 0 overwrites the periodic `STRU`; mode 2 writes numbered files and `STRU_FINAL` under `STRUC/`. -Use `md_thermo_freq` to set the output interval for MD step, energy, temperature, and pressure information in `running_md.log` and on screen. The default is 1; set it to 0 to disable this thermodynamic output. The interval counts MD steps from 0, so a value of 10 selects steps 0, 10, 20, and so on, including after a restart. +Use `out_thermo_freq` to set the output interval for MD step, energy, temperature, and pressure information in `running_md.log` and on screen. The default is 1; set it to 0 to disable this thermodynamic output. The interval counts MD steps from 0, so a value of 10 selects steps 0, 10, 20, and so on, including after a restart. -The `md_out_force` INPUT keyword has been removed. An INPUT file that still contains it will fail to parse. For MDCell simulations, per-atom forces are no longer printed in `running_md.log`; use `dump_force 1` to include them in `MD_dump`, and use `md_dumpfreq` to set the trajectory output interval. +For MDCell simulations, per-atom forces are in ordinary STRU frames rather than `running_md.log`. The `md_out_force`, `md_dumpfreq`, `dump_force`, `dump_vel`, and `dump_virial` INPUT keywords have been removed; an INPUT file using them will fail to parse. + +MDCell structure output (`STRU`, `STRU_FINAL`, and `STRU_restart`) lists atoms by element and then by their original index within that element. This order remains stable when atoms migrate between MPI processes. In an appended `STRU` trajectory, the same row within each element therefore refers to the same atom in every frame. + +Ordinary MD structure frames include per-atom `f` forces in eV/Angstrom and `v` velocities in atomic units; `STRU_restart` retains `v` for restarting and omits `f`. When `cal_stress=1`, the thermodynamic block in `running_md.log` includes the complete 3-by-3 virial and total stress tensors in kbar at the `out_thermo_freq` cadence. This frequency affects MD only; SCF and relaxation output are unchanged. [Examples](https://github.com/deepmodeling/abacus-develop/tree/develop/examples/18_md/01_LCAO_NVE_Si8) of MD simulations are also provided. There are eight INPUT files corresponding to eight different MD evolution methods in the directory. diff --git a/examples/18_md/01_LCAO_NVE_Si8/README b/examples/18_md/01_LCAO_NVE_Si8/README index daabb0c3b20..3dfe48a2d80 100644 --- a/examples/18_md/01_LCAO_NVE_Si8/README +++ b/examples/18_md/01_LCAO_NVE_Si8/README @@ -32,7 +32,7 @@ Furthermore, ABACUS also provides a [list of keywords](./input_files/input-main. To employ CMD calculations, `esolver_type` should be set to be `lj` or `dp`. If DP model is selected, the filename of DP model is specified by keyword `pot_file`. -The MD output information will be written into the file `MD_dump`, in which the atomic forces, atomic velocities, and lattice virial are controlled by keyword `dump_force`, `dump_vel`, and `dump_virial`, respectively. +MD trajectories are written to STRU files when `out_stru=1` and `out_freq_ion>0`. Each ordinary frame contains positions, forces, and velocities. The full virial tensor is written to `running_md.log` when stress is calculated. Note: 1) When doing md calculations, turn off `symmetry`. diff --git a/examples/35_tdofdft/01_Al_proton_ESP/02_td/INPUT b/examples/35_tdofdft/01_Al_proton_ESP/02_td/INPUT index 1a33f282846..c904bdd9665 100644 --- a/examples/35_tdofdft/01_Al_proton_ESP/02_td/INPUT +++ b/examples/35_tdofdft/01_Al_proton_ESP/02_td/INPUT @@ -36,7 +36,9 @@ md_restart 0 md_type nve md_nstep 4500 md_dt 0.0005 -md_dumpfreq 1 +out_stru 1 +out_freq_ion 1 +out_app_flag 1 # Total charge: 256 Al * 3 valence electrons = 768 # (proton contributes +1 charge, no valence electrons) diff --git a/examples/35_tdofdft/README b/examples/35_tdofdft/README index 1a0ea93bb53..cdac0f4712d 100644 --- a/examples/35_tdofdft/README +++ b/examples/35_tdofdft/README @@ -24,7 +24,7 @@ computational cost of KS-DFT becomes prohibitive. 2. Copy `chg.cube` from `01_gs/OUT.autotest/` to `02_td/` 3. Run `02_td/` for the time-dependent proton dynamics 4. Use `get_kinetic.py` from `tools/02_postprocessing/tdofdft-tools/` to extract the - proton kinetic energy curve from `OUT.autotest/MD_dump` + proton kinetic energy curve from the appended `OUT.autotest/STRU` trajectory ## Input Files diff --git a/interfaces/ASE_interface/DEVELOP.md b/interfaces/ASE_interface/DEVELOP.md index acb1f1384b4..a655472a935 100644 --- a/interfaces/ASE_interface/DEVELOP.md +++ b/interfaces/ASE_interface/DEVELOP.md @@ -55,7 +55,7 @@ This directory contains the input/output (I/O) functions for extracting informat |lattice constant|'lattice constant \(Angstrom\)\s*=\s*(-?\d+(\.\d+)?)'|`lattice constant (Angstrom) = 0.529177`|| |lattice vectors|'^Lattice vectors: \(Cartesian coordinate: in unit of a_0\)$'|` Lattice vectors: (Cartesian coordinate: in unit of a_0)`|| |coordinate system|'^(DIRECT\|CARTESIAN) COORDINATES'|`DIRECT COORDINATES`|| -|atomic positions|'atom\s+x\s+y\s+z\s+mag‘|` atom x y z mag`|"tauc/taud" suffix has been removed, therefore the way to read the coordinates changes to find the head of the table, then read the following `number of atoms` lines. On the other hand, if the `calculation` is set to `md`, ABACUS will not dump the atomic positions to running log anymore, instead, will read from the MD_dump file| +|atomic positions|'atom\s+x\s+y\s+z\s+mag‘|` atom x y z mag`|"tauc/taud" suffix has been removed, therefore the way to read the coordinates changes to find the head of the table, then read the following `number of atoms` lines. For `calculation=md`, the reader uses periodic STRU frames or STRU_FINAL; legacy runs may still be read from MD_dump.| |eigenvalues|'spin=(\d)\s+k-point=(\d+)/(\d+)\s+Cartesian=\s*(-?\d(\.\d+)?(e-\d+)?)\s+(-?\d(\.\d+)?(e-\d+)?)\s+(-?\d(\.\d\|+)?(e-\d+)?)\s+\(\d+\s+plane wave\)'| spin=1 k-point=1/1 Cartesian=0.0000000 0.0000000 0.0000000 (1837 plane wave)|eigenvalues information has been removed from the running log, the file istate.info is renamed as eig_occ.txt, where the eigenvalues are read| |atomic forces|'#\s\*TOTAL\-FORCE\s*\(eV\s*/Angstrom\)\s\*#'|` #TOTAL-FORCE (eV/Angstrom)#`|| |total stress|'#\s\*TOTAL\-STRESS\s*\(kbar\)\s\*#'|` #TOTAL-STRESS (kbar)# `|| @@ -87,4 +87,4 @@ This module contains the wrapper of k-point sampling functions and helper functi ## xtest.sh -This script can run all the unittests that programmed in all Python source files. \ No newline at end of file +This script can run all the unittests that programmed in all Python source files. diff --git a/interfaces/ASE_interface/abacuslite/io/latestio.py b/interfaces/ASE_interface/abacuslite/io/latestio.py index 43dd96c9758..7ab269a88f0 100644 --- a/interfaces/ASE_interface/abacuslite/io/latestio.py +++ b/interfaces/ASE_interface/abacuslite/io/latestio.py @@ -26,6 +26,77 @@ ) +def read_traj_from_md_stru(directory: Path, + running_log_lines: Optional[List[str]] = None) -> List[Dict[str, np.ndarray]]: + """Read MD frames from appended, numbered, or final STRU output.""" + periodic = directory / 'STRU' + numbered = sorted((directory / 'STRUC').glob('STRU[0-9]*'), + key=lambda path: int(path.name[4:])) + sources = [periodic] if periodic.is_file() else numbered + final = directory / 'STRU_FINAL' + if not final.is_file(): + final = directory / 'STRUC' / 'STRU_FINAL' + if final.is_file(): + sources.append(final) + if running_log_lines is not None: + announced = [] + for line in running_log_lines: + match = re.search(r'Write file:\s+(.+?)\s*$', line) + if match is None: + continue + path = Path(match.group(1)) + if path.name in ('STRU', 'STRU_FINAL') or re.fullmatch(r'STRU[0-9]+', path.name): + path = directory / 'STRUC' / path.name if path.parent.name == 'STRUC' else directory / path.name + if path.is_file() and path not in announced: + announced.append(path) + if announced: + sources = announced + frames = {} + for source in sources: + step = None + lines = [] + for raw in source.read_text().splitlines() + ['# MD step END']: + if raw.startswith('# MD step '): + if step is not None: + data = [line.split('#', 1)[0].strip() for line in lines] + data = [line for line in data if line] + lat0 = float(data[data.index('LATTICE_CONSTANT') + 1]) + lattice_index = data.index('LATTICE_VECTORS') + 1 + cell = np.array([list(map(float, row.split())) + for row in data[lattice_index:lattice_index + 3]]) + cell *= lat0 * 0.529177 + index = data.index('ATOMIC_POSITIONS') + 1 + coordinate = data[index] + assert coordinate == 'Cartesian_angstrom', coordinate + index += 1 + labels = [] + coords = [] + forces = [] + while index < len(data): + label = data[index] + count = int(data[index + 2]) + index += 3 + for atom in data[index:index + count]: + fields = atom.split() + labels.append(label) + coords.append([float(value) for value in fields[:3]]) + if 'f' in fields: + force_index = fields.index('f') + forces.append([float(value) for value in fields[force_index + 1:force_index + 4]]) + index += count + frames[step] = {'step': step, 'coordinate': coordinate, + 'cell': cell, 'elem': labels, 'coords': np.array(coords), + 'forces': np.array(forces) if len(forces) == len(labels) else None} + if raw != '# MD step END': + step = int(raw.split()[3]) + lines = [] + else: + step = None + elif step is not None: + lines.append(raw) + return [frames[step] for step in sorted(frames)] + + def find_eig_occ_files(directory: Path, running_log_lines: Optional[List[str]] = None) -> List[Path]: '''Discover eigenvalue/occupation files in the output directory. @@ -125,7 +196,7 @@ def read_esolver_type_from_running_log(src: str | Path | List[str]) \ ---------- fn : str The path to the ABACUS running log file. - + Returns ------- str @@ -561,12 +632,22 @@ def read_abacus_out(fileobj, # FIXME: implement read_ksdft_esolver_out instead of read_abacus_out to # make flexible esolver support - # read the structure, with the cell, elem, etc. (nframe) - # if it is MD run, the trajectories will be in the file MD_dump, instead - # of the running log - trajectory = read_traj_from_running_log(abacus_lines) \ - if fileobj.name != 'running_md.log' else \ - read_traj_from_md_dump(fileobj.parent / 'MD_dump') + # New MD output uses STRU frames. Keep the legacy reader for existing + # calculation directories written by older ABACUS versions. + announced_structure = any(re.search(r'Write file: .*[/\\]STRU(?:_FINAL|[0-9]+)?\s*$', line) + for line in abacus_lines) + has_stru_files = ((fileobj.parent / 'STRU').is_file() + or (fileobj.parent / 'STRU_FINAL').is_file() + or (fileobj.parent / 'STRUC' / 'STRU_FINAL').is_file() + or any((fileobj.parent / 'STRUC').glob('STRU[0-9]*'))) + new_md_output = (fileobj.name == 'running_md.log' and + (announced_structure or (has_stru_files and not (fileobj.parent / 'MD_dump').is_file()))) + if new_md_output: + trajectory = read_traj_from_md_stru(fileobj.parent, abacus_lines) + elif fileobj.name == 'running_md.log': + trajectory = read_traj_from_md_dump(fileobj.parent / 'MD_dump') + else: + trajectory = read_traj_from_running_log(abacus_lines) # read the eigenvalues (nframe, nk, nbnd) written by the current run eig_files = find_eig_occ_files(fileobj.parent, abacus_lines) @@ -582,7 +663,9 @@ def read_abacus_out(fileobj, for ion_move, _ in iter_header: if ion_move not in step_ids: step_ids.append(ion_move) - if len(step_ids) != len(trajectory): + if new_md_output: + step_ids = [frame['step'] for frame in trajectory] + elif len(step_ids) != len(trajectory): step_ids = list(range(1, len(trajectory) + 1)) elecstate = align_eig_frames(elecstate, step_ids) @@ -608,10 +691,26 @@ def read_abacus_out(fileobj, read_energies_from_running_log(abacus_lines)[1], iter_header ) - - # read the magmom magmom = read_magmom_from_running_log(abacus_lines) + if new_md_output: + log_steps = [] + for ion_move, _ in iter_header: + if ion_move not in log_steps: + log_steps.append(ion_move) + if len(log_steps) != len(energies): + log_steps = list(range(1, len(energies) + 1)) + selected = [log_steps.index(step) for step in step_ids] + energies = [energies[i] for i in selected] + if len(forces) == len(log_steps): + forces = [forces[i] for i in selected] + if len(stress) == len(log_steps): + stress = [stress[i] for i in selected] + if len(magmom) == len(log_steps): + magmom = [magmom[i] for i in selected] + if all(frame['forces'] is not None for frame in trajectory): + forces = [frame['forces'] for frame in trajectory] + # roughly check the integrity of data from their length consistency assert len(trajectory) == len(energies), \ f'Inconsistent length: {len(trajectory)} != {len(energies)}' @@ -672,6 +771,67 @@ class TestLatestIO(unittest.TestCase): here = Path(__file__).parent testfiles = here / 'testfiles' + def test_read_md_stru_frames_and_force(self): + import tempfile + + def frame(step, position, force): + return (f'# MD step {step}\n\nATOMIC_SPECIES\nH 1.0 auto auto\n' + 'LATTICE_CONSTANT\n1.8897270000\nLATTICE_VECTORS\n' + '4 0 0\n0 4 0\n0 0 4\nATOMIC_POSITIONS\nCartesian_angstrom\n' + f'H\n0.0\n1\n{position} 0 0 m 1 1 1 v 0.1 0 0 f {force} 0 0\n') + + with tempfile.TemporaryDirectory() as scratch: + directory = Path(scratch) + (directory / 'STRU').write_text(frame(1, 1.0, 2.0) + frame(2, 1.5, 3.0)) + (directory / 'STRU_FINAL').write_text(frame(2, 1.5, 3.0)) + trajectory = read_traj_from_md_stru(directory) + self.assertEqual([item['step'] for item in trajectory], [1, 2]) + self.assertTrue(np.allclose(trajectory[1]['coords'], [[1.5, 0, 0]])) + self.assertTrue(np.allclose(trajectory[1]['forces'], [[3.0, 0, 0]])) + self.assertTrue(np.allclose(trajectory[1]['cell'], np.eye(3) * 4.0, atol=1e-5)) + + (directory / 'STRU').unlink() + numbered = directory / 'STRUC' + numbered.mkdir() + (numbered / 'STRU1').write_text(frame(1, 1.0, 2.0)) + (numbered / 'STRU3').write_text(frame(3, 1.8, 4.0)) + (directory / 'STRU_FINAL').unlink() + (numbered / 'STRU_FINAL').write_text(frame(4, 2.0, 5.0)) + self.assertEqual([item['step'] for item in read_traj_from_md_stru(directory)], [1, 3, 4]) + (directory / 'STRU').write_text(frame(99, 9.0, 9.0)) + announcements = [f'Write file: {numbered / name}' + for name in ('STRU1', 'STRU3', 'STRU_FINAL')] + self.assertEqual([item['step'] for item in read_traj_from_md_stru(directory, announcements)], + [1, 3, 4]) + (directory / 'STRU').unlink() + (numbered / 'STRU1').unlink() + (numbered / 'STRU3').unlink() + self.assertEqual([item['step'] for item in read_traj_from_md_stru(directory)], [4]) + + def test_read_abacus_out_from_new_md_stru(self): + import tempfile + + with tempfile.TemporaryDirectory() as scratch: + directory = Path(scratch) + shutil.copy(self.testfiles / 'pw-symm0-nspin4-gamma-md', directory / 'running_md.log') + shutil.copy(self.testfiles / 'nspin4-gamma-eigocc', directory / 'eig_occ.txt') + header = ('ATOMIC_SPECIES\nAs 1 auto auto\nGa 1 auto auto\n' + 'LATTICE_CONSTANT\n1.8897270000\nLATTICE_VECTORS\n' + '4 0 0\n0 4 0\n0 0 4\nATOMIC_POSITIONS\nCartesian_angstrom\n') + def frame(step, x, force): + return (f'# MD step {step}\n' + header + + f'As\n0.0\n1\n1 1 1 m 1 1 1 v 0 0 0 f {force} 0 0\n' + + f'Ga\n0.0\n1\n{x} 0 0 m 1 1 1 v 0 0 0 f {-force} 0 0\n') + (directory / 'STRU').write_text(frame(1, 0.0, 1.0) + frame(2, 0.1, 2.0)) + (directory / 'STRU_FINAL').write_text(frame(2, 0.1, 2.0)) + images = read_abacus_out(directory / 'running_md.log') + (directory / 'STRU').unlink() + final_only = read_abacus_out(directory / 'running_md.log') + self.assertEqual(len(images), 2) + self.assertTrue(np.allclose(images[-1].get_forces(), [[2.0, 0, 0], [-2.0, 0, 0]])) + self.assertEqual(len(final_only), 1) + self.assertTrue(np.allclose(final_only[0].get_forces(), [[2.0, 0, 0], [-2.0, 0, 0]])) + def test_read_abacus_out_reorders_calculator_magmoms(self): import tempfile from unittest.mock import patch diff --git a/interfaces/PLUMED_interface/example01/INPUT b/interfaces/PLUMED_interface/example01/INPUT index 527fcdf7eb9..e96c686d10d 100644 --- a/interfaces/PLUMED_interface/example01/INPUT +++ b/interfaces/PLUMED_interface/example01/INPUT @@ -34,7 +34,8 @@ md_dt 0.6 md_tfirst 600 md_tlast 600 md_thermostat nhc -md_dumpfreq 100 +out_freq_ion 100 +out_app_flag 1 md_restartfreq 100 #Parameters (8.PLUMED) diff --git a/source/source_cell/mdcell_reader.cpp b/source/source_cell/mdcell_reader.cpp index f9c11ee41f0..b4f57c4b27f 100644 --- a/source/source_cell/mdcell_reader.cpp +++ b/source/source_cell/mdcell_reader.cpp @@ -290,6 +290,17 @@ std::vector read_owned_atoms(std::ifstream& ifs, parse_double(vy, "velocity y"), parse_double(vz, "velocity z")); } + else if (token == "f" || token == "force" || token == "forces") + { + std::string fx; + std::string fy; + std::string fz; + iss >> fx >> fy >> fz; + if (!iss) throw std::runtime_error("Invalid force record in STRU."); + parse_double(fx, "force x"); + parse_double(fy, "force y"); + parse_double(fz, "force z"); + } } for (int ix = begin[0]; ix < end[0]; ++ix) diff --git a/source/source_cell/module_neighlist/unittests/test_mdcell_reader.cpp b/source/source_cell/module_neighlist/unittests/test_mdcell_reader.cpp index 825fe1c516f..f4918b563d4 100644 --- a/source/source_cell/module_neighlist/unittests/test_mdcell_reader.cpp +++ b/source/source_cell/module_neighlist/unittests/test_mdcell_reader.cpp @@ -10,6 +10,8 @@ #include "source_base/parallel_cell.h" #include "source_base/global_variable.h" +#include +#include #include #include #include @@ -17,6 +19,7 @@ #include #include #include +#include #include #include @@ -43,7 +46,7 @@ void write_cartesian_stru_case(const std::string& stru_file) ofs << "He\n"; ofs << "0.0\n"; ofs << "4\n"; - ofs << "0.40 0.40 0.40 m 1 1 1 v 0.01 0.00 0.00\n"; + ofs << "0.40 0.40 0.40 m 1 1 1 v 0.01 0.00 0.00 f 1.0 2.0 3.0\n"; ofs << "2.40 0.40 0.40 m 1 0 1 v 0.02 0.00 0.00\n"; ofs << "0.40 2.40 0.40 m 0 1 1 v 0.03 0.00 0.00\n"; ofs << "2.40 2.40 0.40 m 1 1 0 v 0.04 0.00 0.00\n"; @@ -348,13 +351,14 @@ TEST(MDCellReaderTest, RestartStruPreservesAtomRecordsAcrossRanks) StruMeta metadata; metadata.species.resize(2); const std::string output_file = "distributed_mdcell_restart.STRU"; - mdcell::print_stru_file(mdcell, metadata, output_file, "", false); + mdcell::print_stru_file(mdcell, metadata, output_file, "", false, false); DomainDecomposition reader_decomp; MDCell round_trip = MDCellReader::read_stru(output_file, std::vector{1, 1, 1}, 0.0, ModuleBase::world_comm_domain(), reader_decomp); + EXPECT_NEAR(round_trip.lat0() * round_trip.latvec().e11, 20.0, 1.0e-8); double local_positions[4] = {0.0, 0.0, 0.0, 0.0}; double local_velocities[4] = {0.0, 0.0, 0.0, 0.0}; int local_mbl_x[4] = {0, 0, 0, 0}; @@ -362,9 +366,10 @@ TEST(MDCellReaderTest, RestartStruPreservesAtomRecordsAcrossRanks) for (std::size_t iat = 0; iat < round_trip.owned_atoms().size(); ++iat) { const LocalAtom& atom = round_trip.owned_atoms()[iat]; - const int index = atom.type == 0 ? static_cast(atom.cart.x) - : 2 + static_cast(atom.cart.x) - 10; - local_positions[index] = atom.cart.x; + const double position_bohr = atom.cart.x * round_trip.lat0(); + const int index = atom.type == 0 ? static_cast(std::lround(position_bohr)) + : 2 + static_cast(std::lround(position_bohr)) - 10; + local_positions[index] = position_bohr; local_velocities[index] = atom.vel.x; local_mbl_x[index] = atom.mbl.x; local_owners[index] = 1; @@ -379,9 +384,9 @@ TEST(MDCellReaderTest, RestartStruPreservesAtomRecordsAcrossRanks) MPI_Allreduce(local_owners, global_owners, 4, MPI_INT, MPI_SUM, MPI_COMM_WORLD); for (int iat = 0; iat < 4; ++iat) EXPECT_EQ(global_owners[iat], 1); EXPECT_DOUBLE_EQ(global_positions[0], 0.0); - EXPECT_DOUBLE_EQ(global_positions[1], 1.0); - EXPECT_DOUBLE_EQ(global_positions[2], 10.0); - EXPECT_DOUBLE_EQ(global_positions[3], 11.0); + EXPECT_NEAR(global_positions[1], 1.0, 1.0e-8); + EXPECT_NEAR(global_positions[2], 10.0, 1.0e-8); + EXPECT_NEAR(global_positions[3], 11.0, 1.0e-8); EXPECT_DOUBLE_EQ(global_velocities[0], 0.0); EXPECT_DOUBLE_EQ(global_velocities[1], 0.01); EXPECT_DOUBLE_EQ(global_velocities[2], 0.10); @@ -431,10 +436,13 @@ TEST(MDCellReaderTest, RestartStruPreservesAtomRecordsAcrossRanks) } ASSERT_EQ(coordinates_a.size(), 2U); ASSERT_EQ(coordinates_b.size(), 2U); - std::set expected_a = {0.0, 1.0}; - std::set expected_b = {10.0, 11.0}; - EXPECT_EQ(std::set(coordinates_a.begin(), coordinates_a.end()), expected_a); - EXPECT_EQ(std::set(coordinates_b.begin(), coordinates_b.end()), expected_b); + std::sort(coordinates_a.begin(), coordinates_a.end()); + std::sort(coordinates_b.begin(), coordinates_b.end()); + const double scale = ModuleBase::BOHR_TO_A; + EXPECT_NEAR(coordinates_a[0], 0.0, 1.0e-8); + EXPECT_NEAR(coordinates_a[1], scale, 1.0e-8); + EXPECT_NEAR(coordinates_b[0], 10.0 * scale, 1.0e-8); + EXPECT_NEAR(coordinates_b[1], 11.0 * scale, 1.0e-8); } MPI_Barrier(MPI_COMM_WORLD); if (rank == 0) std::remove(output_file.c_str()); @@ -449,7 +457,9 @@ TEST(MDCellReaderTest, STRUAppendWithFrameComment) const int rank = world_domain.rank(); std::vector owned_atoms; - owned_atoms.push_back(LocalAtom(ModuleBase::Vector3(0.0, 0.0, 0.0), + if (rank == 0) + { + owned_atoms.push_back(LocalAtom(ModuleBase::Vector3(0.0, 0.0, 0.0), ModuleBase::Vector3(0.0, 0.0, 0.0), ModuleBase::Vector3(0.0, 0.0, 0.0), ModuleBase::Vector3(0.0, 0.0, 0.0), @@ -458,6 +468,7 @@ TEST(MDCellReaderTest, STRUAppendWithFrameComment) 0, 0, rank)); + } ModuleBase::Matrix3 lattice = make_lattice(); MDCell mdcell; @@ -474,14 +485,14 @@ TEST(MDCellReaderTest, STRUAppendWithFrameComment) ModuleBase::world_comm_domain()); StruMeta metadata; metadata.species.resize(1); - const std::string output_file = "mdcell_append_test.STRU"; + const std::string output_file = testing::TempDir() + "mdcell_append_test.STRU"; // First frame: append=false, frame comment set. mdcell::print_stru_file(mdcell, metadata, output_file, - "# MD step 1\n\n", /*append=*/false); + "# MD step 1\n\n", /*append=*/false, /*include_force=*/false); // Second frame: append=true with a different comment. mdcell::print_stru_file(mdcell, metadata, output_file, - "# MD step 2\n\n", /*append=*/true); + "# MD step 2\n\n", /*append=*/true, /*include_force=*/false); if (rank == 0) { @@ -501,6 +512,8 @@ TEST(MDCellReaderTest, STRUAppendWithFrameComment) pos += 14; } EXPECT_EQ(occurrences, 2); + EXPECT_THAT(str, testing::HasSubstr("Cartesian_angstrom")); + EXPECT_THAT(str, testing::HasSubstr(" v ")); std::remove(output_file.c_str()); } } @@ -516,7 +529,9 @@ TEST(MDCellReaderTest, STRUFreshRunTruncatesPreviousFrames) const int rank = world_domain.rank(); std::vector owned_atoms; - owned_atoms.push_back(LocalAtom(ModuleBase::Vector3(0.0, 0.0, 0.0), + if (rank == 0) + { + owned_atoms.push_back(LocalAtom(ModuleBase::Vector3(0.0, 0.0, 0.0), ModuleBase::Vector3(0.0, 0.0, 0.0), ModuleBase::Vector3(0.0, 0.0, 0.0), ModuleBase::Vector3(0.0, 0.0, 0.0), @@ -525,6 +540,7 @@ TEST(MDCellReaderTest, STRUFreshRunTruncatesPreviousFrames) 0, 0, rank)); + } ModuleBase::Matrix3 lattice = make_lattice(); const ModuleBase::Matrix3 inverse = lattice.Inverse(); @@ -550,9 +566,9 @@ TEST(MDCellReaderTest, STRUFreshRunTruncatesPreviousFrames) // Previous run: frames 1 and 2 accumulate. mdcell::print_stru_file(mdcell, metadata, output_file, - "# MD step 1\n\n", /*append=*/false); + "# MD step 1\n\n", /*append=*/false, /*include_force=*/false); mdcell::print_stru_file(mdcell, metadata, output_file, - "# MD step 2\n\n", /*append=*/true); + "# MD step 2\n\n", /*append=*/true, /*include_force=*/false); // The extraction runs on rank zero only; broadcast its result so every // rank takes the same (collective-safe) return decision. Later @@ -577,7 +593,7 @@ TEST(MDCellReaderTest, STRUFreshRunTruncatesPreviousFrames) // Fresh run: the first frame truncates the fixed-name file (append=false) // and starts numbering from step 1 again. mdcell::print_stru_file(mdcell, metadata, output_file, - "# MD step 1\n\n", /*append=*/false); + "# MD step 1\n\n", /*append=*/false, /*include_force=*/false); if (rank == 0) { @@ -602,6 +618,108 @@ TEST(MDCellReaderTest, STRUFreshRunTruncatesPreviousFrames) } } +TEST(MDCellReaderTest, STRUAtomOrderStaysStableAcrossOwnerChanges) +{ + const ModuleBase::CommunicationDomain world = ModuleBase::world_comm_domain(); + if (world.size() != 4) + { + GTEST_SKIP() << "This test requires four MPI ranks."; + } + + ModuleBase::Matrix3 lattice = make_lattice(); + lattice.e11 = 20.0; + lattice.e22 = 20.0; + lattice.e33 = 20.0; + StruMeta metadata; + metadata.species.resize(1); + const std::string filename = testing::TempDir() + "mdcell_stable_order.STRU"; + for (int frame = 0; frame < 2; ++frame) + { + const int index = frame == 0 ? 3 - world.rank() : world.rank(); + const double position = index + 1.0; + const double fractional_position = position / 20.0; + const double velocity = index + 0.125; + const ModuleBase::Vector3 cart(position, 0.0, 0.0); + const ModuleBase::Vector3 frac(fractional_position, 0.0, 0.0); + const ModuleBase::Vector3 vel(velocity, 0.0, 0.0); + const ModuleBase::Vector3 force(index + 0.25, 0.0, 0.0); + const ModuleBase::Vector3 move(1, 1, 1); + std::vector atoms; + atoms.push_back(LocalAtom(cart, frac, vel, force, move, 1.0, 0, index, world.rank())); + MDCell cell; + cell.initialize_from_owned_atoms(lattice, lattice.Inverse(), 1.0, 1.0, 4, + atoms, std::vector{"A"}, + std::vector{1.0}, std::vector{4}, + 0.0, world); + cell.owned_atoms()[0].force = force; + const bool append = frame != 0; + mdcell::print_stru_file(cell, metadata, filename, "", append, true); + } + + if (world.rank() == 0) + { + std::ifstream input(filename.c_str()); + std::string line; + int frames = 0; + while (std::getline(input, line)) + { + if (line != "Cartesian_angstrom") + { + continue; + } + ++frames; + for (int header_line = 0; header_line < 4; ++header_line) + { + ASSERT_TRUE(static_cast(std::getline(input, line))); + } + for (int index = 0; index < 4; ++index) + { + ASSERT_TRUE(static_cast(std::getline(input, line))); + std::istringstream record(line); + double x = 0.0; + double y = 0.0; + double z = 0.0; + std::string marker; + int mx = 0; + int my = 0; + int mz = 0; + double vx = 0.0; + double vy = 0.0; + double vz = 0.0; + double fx = 0.0; + double fy = 0.0; + double fz = 0.0; + record >> x >> y >> z >> marker >> mx >> my >> mz >> marker >> vx >> vy >> vz; + record >> marker >> fx >> fy >> fz; + ASSERT_FALSE(record.fail()); + EXPECT_NEAR(x, (index + 1.0) * ModuleBase::BOHR_TO_A, 1.0e-9); + EXPECT_DOUBLE_EQ(vx, index + 0.125); + const double expected_force = (index + 0.25) * ModuleBase::Hartree_to_eV + * ModuleBase::ANGSTROM_AU; + EXPECT_NEAR(fx, expected_force, 1.0e-9); + } + } + EXPECT_EQ(frames, 2); + std::remove(filename.c_str()); + } +} + +TEST(MDCellReaderTest, STRUTextGatherRejectsOversizedBatchesCollectively) +{ + const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); + const int local_bytes = domain.rank() == 0 ? 17 : 0; + const std::string oversized(local_bytes, 'x'); + EXPECT_THROW(domain.gather_text(oversized, 16), std::length_error); + if (domain.size() > 2) + { + const std::string local(8, 'x'); + EXPECT_THROW(domain.gather_text(local, 16), std::length_error); + } + const std::string empty; + const std::string gathered = domain.gather_text(empty, 1); + EXPECT_TRUE(gathered.empty()); +} + int main(int argc, char** argv) { MPI_Init(&argc, &argv); diff --git a/source/source_cell/print_cell.cpp b/source/source_cell/print_cell.cpp index 250895d3fbc..38875217a7e 100644 --- a/source/source_cell/print_cell.cpp +++ b/source/source_cell/print_cell.cpp @@ -1,16 +1,16 @@ #include #include -#include -#include -#include +#include +#include +#include +#include #include #include -#include #include "print_cell.h" #include "source_cell/mdcell.h" #include "source_base/formatter.h" -#include "source_base/parallel_common.h" +#include "source_base/parallel_cell.h" #include "source_base/tool_title.h" #include "source_base/tool_quit.h" #include "source_base/global_variable.h" @@ -295,12 +295,14 @@ std::string mdcell_stru_header(const MDCell& cell, const StruMeta& metadata) output << metadata.species[it].orbital_file << "\n"; } if (!metadata.descriptor_file.empty()) output << "\nNUMERICAL_DESCRIPTOR\n" << metadata.descriptor_file << "\n"; - output << "\nLATTICE_CONSTANT\n" << cell.lat0() << "\n\nLATTICE_VECTORS\n"; + const double lat0_angstrom = 1.0 / ModuleBase::BOHR_TO_A; + const double lat_scale = cell.lat0() * ModuleBase::BOHR_TO_A; + output << "\nLATTICE_CONSTANT\n" << lat0_angstrom << "\n\nLATTICE_VECTORS\n"; const ModuleBase::Matrix3& lattice = cell.latvec(); - output << lattice.e11 << " " << lattice.e12 << " " << lattice.e13 << "\n"; - output << lattice.e21 << " " << lattice.e22 << " " << lattice.e23 << "\n"; - output << lattice.e31 << " " << lattice.e32 << " " << lattice.e33 << "\n"; - output << "\nATOMIC_POSITIONS\nCartesian\n"; + output << lattice.e11 * lat_scale << " " << lattice.e12 * lat_scale << " " << lattice.e13 * lat_scale << "\n"; + output << lattice.e21 * lat_scale << " " << lattice.e22 * lat_scale << " " << lattice.e23 * lat_scale << "\n"; + output << lattice.e31 * lat_scale << " " << lattice.e32 * lat_scale << " " << lattice.e33 * lat_scale << "\n"; + output << "\nATOMIC_POSITIONS\nCartesian_angstrom\n"; return output.str(); } @@ -314,44 +316,53 @@ std::string mdcell_type_header(const MDCell& cell, const StruMeta& metadata, con return output.str(); } -std::string local_mdcell_atoms(const MDCell& cell, const std::size_t type) +std::string format_mdcell_atom(const MDCell& cell, const LocalAtom& atom, const bool include_force) { - std::string output; - for (std::size_t iat = 0; iat < cell.owned_atoms().size(); ++iat) + std::ostringstream output; + const double position_scale = cell.lat0() * ModuleBase::BOHR_TO_A; + output << std::fixed << std::setprecision(10) + << atom.cart.x * position_scale << " " << atom.cart.y * position_scale << " " + << atom.cart.z * position_scale + << " m " << atom.mbl.x << " " << atom.mbl.y << " " << atom.mbl.z; + output << " v " << atom.vel.x << " " << atom.vel.y << " " << atom.vel.z; + if (include_force) { - const LocalAtom& atom = cell.owned_atoms()[iat]; - if (atom.type == static_cast(type)) - { - std::ostringstream atom_output; - atom_output << std::fixed << std::setprecision(10) - << atom.cart.x << " " << atom.cart.y << " " << atom.cart.z - << " m " << atom.mbl.x << " " << atom.mbl.y << " " << atom.mbl.z - << " v " << atom.vel.x << " " << atom.vel.y << " " << atom.vel.z << "\n"; - output += atom_output.str(); - } + const double force_scale = ModuleBase::Hartree_to_eV * ModuleBase::ANGSTROM_AU; + output << " f " << atom.force.x * force_scale << " " << atom.force.y * force_scale + << " " << atom.force.z * force_scale; } - return output; + return output.str(); } -#ifdef __MPI -bool write_at(const int file, const std::string& data, MPI_Offset offset) +void write_mdcell_rows(std::ostream& output, const std::string& text, + const std::int64_t begin, const std::int64_t end) { - std::size_t written = 0; - while (written < data.size()) + std::map rows; + std::istringstream input(text); + std::string line; + while (std::getline(input, line)) { - const ssize_t count = pwrite(file, - data.data() + written, - data.size() - written, - static_cast(offset + written)); - if (count <= 0) + std::istringstream record(line); + std::int64_t index = -1; + if (!(record >> index) || index < begin || index >= end) { - return false; + throw std::runtime_error("Invalid MDCell STRU atom index."); } - written += static_cast(count); + const std::size_t separator = line.find('\t'); + if (separator == std::string::npos || !rows.emplace(index, line.substr(separator + 1)).second) + { + throw std::runtime_error("Duplicate or malformed MDCell STRU atom row."); + } + } + if (rows.size() != static_cast(end - begin)) + { + throw std::runtime_error("Missing MDCell STRU atoms."); + } + for (const auto& row : rows) + { + output << row.second << '\n'; } - return true; } -#endif } namespace unitcell @@ -376,7 +387,7 @@ StruMeta make_stru_meta(const UnitCell& ucell) namespace mdcell { void print_stru_file(const MDCell& cell, const StruMeta& stru_meta, const std::string& fn, - const std::string& frame_comment, const bool append) + const std::string& frame_comment, const bool append, const bool include_force) { if (stru_meta.species.size() != cell.type_labels().size() || stru_meta.species.size() != cell.type_masses().size() @@ -385,111 +396,107 @@ void print_stru_file(const MDCell& cell, const StruMeta& stru_meta, const std::s throw std::runtime_error("MDCell STRU metadata does not match the MDCell type data."); } const std::string header = frame_comment + mdcell_stru_header(cell, stru_meta); + ModuleBase::CommunicationDomain domain; #ifdef __MPI - int rank = 0; - const MPI_Comm comm = cell.communicator(); - MPI_Comm_rank(comm, &rank); - int header_ok = 1; - MPI_Offset base_offset = 0; - // Write position of the first species block. Only rank 0 knows it, since - // only rank 0 observed the end of the pre-existing file before writing - // the header; the value is shared by broadcast below. - MPI_Offset offset = 0; - if (rank == 0) + domain.initialize(cell.communicator()); +#endif + std::vector > > local_rows(stru_meta.species.size()); + int invalid_identity = 0; + int local_row_bytes = 0; + for (const LocalAtom& atom : cell.owned_atoms()) { - // No O_APPEND: on Linux pwrite() ignores the given offset when the - // file was opened with O_APPEND. Truncate unless appending, then - // seek to the current end to learn the base offset. - const int open_flags = O_CREAT | O_WRONLY | (append ? 0 : O_TRUNC); - const int header_file = open(fn.c_str(), open_flags, 0666); - if (header_file < 0) + if (atom.type < 0 || static_cast(atom.type) >= stru_meta.species.size() + || atom.type_index < 0 || atom.type_index >= cell.type_atom_counts()[atom.type]) { - header_ok = 0; + invalid_identity = 1; + continue; } - else + const std::string row = std::to_string(atom.type_index) + "\t" + + format_mdcell_atom(cell, atom, include_force) + "\n"; + if (row.size() > static_cast(std::numeric_limits::max())) { - const off_t end_pos = lseek(header_file, 0, SEEK_END); - base_offset = end_pos >= 0 ? static_cast(end_pos) : 0; - const bool header_written = end_pos >= 0 && write_at(header_file, header, base_offset); - const bool header_closed = close(header_file) == 0; - header_ok = header_written && header_closed; - // The header occupies [base_offset, base_offset + header.size()), - // so this is where the first species header goes. - offset = base_offset + static_cast(header.size()); + invalid_identity = 1; + continue; } + local_row_bytes = std::max(local_row_bytes, static_cast(row.size())); + local_rows[atom.type].push_back(std::make_pair(atom.type_index, row)); } - MPI_Bcast(&header_ok, 1, MPI_INT, 0, comm); - if (header_ok == 0) + if (domain.max(invalid_identity) != 0) { - throw std::runtime_error("Unable to create MDCell restart STRU file: " + fn + ": " + std::strerror(errno)); + throw std::runtime_error("Invalid MDCell STRU atom identity or row size."); } - // Every rank must agree on the write position. Learning it from a local - // lseek(SEEK_END) is unsafe: MPI_Allreduce is a collective, not a barrier, - // so rank 0 may resume afterwards and write the first species header before - // another rank has seeked. That rank would then observe a larger EOF and - // place its atoms at a base offset shifted by the species header, corrupting - // the frame. Broadcast rank 0's value instead, so the position has a single - // authoritative source. - Parallel_Common::bcast_mpi_offset(offset, comm); - MPI_Barrier(comm); - - const int file = open(fn.c_str(), O_WRONLY); - int file_ok = file >= 0 ? 1 : 0; - int all_files_ok = 0; - MPI_Allreduce(&file_ok, &all_files_ok, 1, MPI_INT, MPI_MIN, comm); - if (all_files_ok == 0) + for (auto& rows : local_rows) { - if (file >= 0) close(file); - throw std::runtime_error("Unable to open MDCell restart STRU file: " + fn + ": " + std::strerror(errno)); + std::sort(rows.begin(), rows.end(), + [](const std::pair& left, + const std::pair& right) { return left.first < right.first; }); } - for (std::size_t it = 0; it < stru_meta.species.size(); ++it) + const int row_bytes = std::max(domain.max(local_row_bytes), 1); + const int batch_bytes = std::max(1024 * 1024, row_bytes); + const std::int64_t batch_atoms = batch_bytes / row_bytes; + std::ofstream output; + if (domain.rank() == 0) { - const std::string type_header = mdcell_type_header(cell, stru_meta, it); - int type_header_ok = 1; - if (rank == 0) type_header_ok = write_at(file, type_header, offset) ? 1 : 0; - MPI_Bcast(&type_header_ok, 1, MPI_INT, 0, comm); - if (type_header_ok == 0) + const std::ios_base::openmode mode = append ? std::ios::out | std::ios::app : std::ios::out; + output.open(fn.c_str(), mode); + if (output) { - close(file); - throw std::runtime_error("Unable to write MDCell restart STRU type header: " + fn + ": " + std::strerror(errno)); + output << header; } - offset += static_cast(type_header.size()); - const std::string local_atoms = local_mdcell_atoms(cell, it); - const MPI_Offset local_size = static_cast(local_atoms.size()); - MPI_Offset type_size = 0; - MPI_Offset rank_offset = 0; - MPI_Allreduce(&local_size, &type_size, 1, MPI_OFFSET, MPI_SUM, comm); - MPI_Exscan(&local_size, &rank_offset, 1, MPI_OFFSET, MPI_SUM, comm); - if (rank == 0) rank_offset = 0; - int atom_data_ok = 1; - if (local_size > 0) + } + const int open_failed = domain.rank() == 0 && !output ? 1 : 0; + if (domain.max(open_failed) != 0) + { + throw std::runtime_error("Unable to open MDCell STRU file: " + fn); + } + for (std::size_t it = 0; it < stru_meta.species.size(); ++it) + { + const std::string type_header = mdcell_type_header(cell, stru_meta, it); + if (domain.rank() == 0) { - atom_data_ok = write_at(file, local_atoms, offset + rank_offset) ? 1 : 0; + output << type_header; } - int all_atom_data_ok = 0; - MPI_Allreduce(&atom_data_ok, &all_atom_data_ok, 1, MPI_INT, MPI_MIN, comm); - if (all_atom_data_ok == 0) + std::size_t local_index = 0; + const std::vector >& rows = local_rows[it]; + for (std::int64_t begin = 0; begin < cell.type_atom_counts()[it];) { - close(file); - throw std::runtime_error("Unable to write MDCell restart STRU atom data: " + fn + ": " + std::strerror(errno)); + const std::int64_t remaining = cell.type_atom_counts()[it] - begin; + const std::int64_t count = std::min(batch_atoms, remaining); + const std::int64_t end = begin + count; + std::string local_text; + while (local_index < rows.size() && rows[local_index].first < end) + { + local_text += rows[local_index].second; + ++local_index; + } + const std::string gathered = domain.gather_text(local_text, batch_bytes); + int invalid_rows = 0; + if (domain.rank() == 0) + { + try + { + write_mdcell_rows(output, gathered, begin, end); + } + catch (const std::runtime_error&) + { + invalid_rows = 1; + } + } + if (domain.max(invalid_rows) != 0) + { + throw std::runtime_error("Duplicate, missing or malformed MDCell STRU atom index."); + } + begin = end; } - MPI_Barrier(comm); - offset += type_size; } - if (close(file) != 0) + if (domain.rank() == 0) { - throw std::runtime_error("Unable to close MDCell restart STRU file: " + fn + ": " + std::strerror(errno)); + output.close(); } -#else - std::ios_base::openmode mode = std::ios::out; - if (append) + const int write_failed = domain.rank() == 0 && !output ? 1 : 0; + if (domain.max(write_failed) != 0) { - mode |= std::ios::app; + throw std::runtime_error("Unable to write MDCell STRU file: " + fn); } - std::ofstream output(fn.c_str(), mode); - output << header; - for (std::size_t it = 0; it < stru_meta.species.size(); ++it) - output << mdcell_type_header(cell, stru_meta, it) << local_mdcell_atoms(cell, it); -#endif } } diff --git a/source/source_cell/print_cell.h b/source/source_cell/print_cell.h index ab39ddcf0dc..862e147219d 100644 --- a/source/source_cell/print_cell.h +++ b/source/source_cell/print_cell.h @@ -92,12 +92,14 @@ namespace mdcell * (e.g. "# MD step N\n\n"); pass an empty string for no marker [in] * @param append true to append the frame to an existing file * (out_app_flag == 1 multi-step runs); false truncates [in] + * @param include_force true to write forces in eV/Angstrom [in] */ void print_stru_file(const MDCell& mdcell, const StruMeta& stru_meta, const std::string& fn, const std::string& frame_comment, - const bool append); + const bool append, + const bool include_force); } #endif diff --git a/source/source_io/module_output/frame_append.h b/source/source_io/module_output/frame_append.h index 186ca95a6a4..6375203d781 100644 --- a/source/source_io/module_output/frame_append.h +++ b/source/source_io/module_output/frame_append.h @@ -33,6 +33,17 @@ inline bool frame_appends(const int out_app_flag, const int istep) return out_app_flag == 1 && istep > 0; } +/// Fixed STRU for overwrite/append modes; numbered STRU for mode 2. +inline std::string stru_frame_filename(const std::string& directory, const int out_app_flag, const int istep) +{ + frame_appends(out_app_flag, istep); + if (out_app_flag == 2) + { + return directory + "STRU" + std::to_string(istep + 1); + } + return directory + "STRU"; +} + } // namespace ModuleIO #endif // FRAME_APPEND_H diff --git a/source/source_io/module_output/output_log.cpp b/source/source_io/module_output/output_log.cpp index 9abc4aae88d..c400afc0a4c 100644 --- a/source/source_io/module_output/output_log.cpp +++ b/source/source_io/module_output/output_log.cpp @@ -232,6 +232,12 @@ void print_force(std::ofstream& ofs_running, const ModuleBase::matrix& force, bool ry) { + const auto& input = PARAM.inp; + // MD writes forces with its STRU frames, independently of solver type. + if (input.calculation == "md") + { + return; + } // this is a magic number, mohan note 2025-06-22 const double output_acc = 1.0e-8; double fac = 1.0; @@ -278,7 +284,7 @@ void print_force(std::ofstream& ofs_running, table = fmt.str(); ofs_running << table; - if (PARAM.inp.test_force) + if (input.test_force) { std::cout << table; } @@ -287,6 +293,11 @@ void print_force(std::ofstream& ofs_running, void print_stress(const std::string& name, const ModuleBase::matrix& scs, const bool screen, const bool ry, std::ofstream &ofs) { + // MD prints virial and total stress on the thermodynamic cadence. + if (PARAM.inp.calculation == "md") + { + return; + } const double output_acc = 1.0e-8; double unit_transform = 1; std::string title = name; @@ -332,7 +343,7 @@ void print_stress(const std::string& name, const ModuleBase::matrix& scs, fmt << stress_x << stress_y << stress_z; table = fmt.str(); ofs << table; - if (name == "TOTAL-STRESS" && PARAM.inp.calculation != "md") + if (name == "TOTAL-STRESS") { ofs << " #TOTAL-PRESSURE# (EXCLUDE KINETIC PART OF IONS): " << std::fixed << std::setprecision(6) << pressure << unit diff --git a/source/source_io/module_parameter/md_parameter.h b/source/source_io/module_parameter/md_parameter.h index f4045202015..5c7849e49be 100644 --- a/source/source_io/module_parameter/md_parameter.h +++ b/source/source_io/module_parameter/md_parameter.h @@ -18,8 +18,7 @@ struct MD_para double md_dt = 1.0; ///< Time increment (hbar/E_hartree) double md_tfirst = -1.0; ///< Temperature (in Hartree, 1 Hartree ~ 3E5 K) double md_tlast = -1.0; ///< Target temperature - int md_dumpfreq = 1; ///< The period to dump MD information - int md_thermo_freq = 1; ///< The period to output MD thermodynamic information + int out_thermo_freq = 1; ///< The period to output MD thermodynamic information double md_neighbor_skin = 0.0; ///< Extra neighbor-list radius in Angstrom for MDCell solvers int md_restartfreq = 5; ///< The period to output MD restart information int md_seed = -1; ///< random seed for MD @@ -70,12 +69,6 @@ struct MD_para ///< sampling (requires ABACUS compiled with PLUMED) std::string plumed_file = "plumed.dat"; ///< input file of PLUMED - bool dump_force = true; ///< output atomic forces into the file MD_dump or - ///< not. liuyu 2023-03-01 - bool dump_vel = true; ///< output atomic velocities into the file MD_dump or - ///< not. liuyu 2023-03-01 - bool dump_virial = true; ///< output lattice virial into the file MD_dump or - ///< not. liuyu 2023-03-01 }; #endif // MD_PARA_H diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 5b66f054b10..50666453462 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -15,9 +15,9 @@ void ReadInput::item_output() item.annotation = "print information every few ionic steps"; item.category = "Output information"; item.type = "Integer"; - item.description = "Controls the output interval in ionic steps. When set to a positive integer, information such as charge density, local potential, electrostatic potential, Hamiltonian matrix, overlap matrix, density matrix, Mulliken population analysis, and structure files (STRU{istep} or STRU{istep}.cif, when out_stru is 1 or 2) is printed every n ionic steps." + item.description = "Controls the output interval in ionic steps. When set to a positive integer, information such as charge density, local potential, electrostatic potential, Hamiltonian matrix, overlap matrix, density matrix, Mulliken population analysis, and periodic structure files (when out_stru is positive) is printed every n ionic steps." "\n\nThis parameter only controls how often a write happens, not how many files are kept: with out_app_flag = 0 each write overwrites the same fixed filename, with out_app_flag = 1 records are appended to one fixed filename, and with out_app_flag = 2 each written step gets its own g{step} file." - "\n\nIn molecular dynamics calculations, out_freq_ion controls the cadence of the structure frames written when out_stru is positive; when out_freq_ion is 0, md_restartfreq is used as the structure-output frequency. The MD restart file Restart_md.txt always follows md_restartfreq and is independent of out_freq_ion." + "\n\nIn molecular dynamics calculations, positive out_freq_ion selects periodic STRU frames starting at the first step. Zero disables periodic frames; STRU_FINAL is still written when out_stru=1. MD checkpoints STRU_restart and Restart_md.txt follow md_restartfreq independently." "\n\nFor DFT+U calculations with out_occ_mat = 1, a separate occupation-matrix file occ_matg{geom_step}.txt is created for every output ionic step. The converged (or final, if not converged) electronic step is always recorded in that file; when out_freq_elec is set smaller than scf_nmax, additional electronic steps are appended as separate sections, each labelled only with the electronic-step number." "\n\nIn RT-TDDFT calculations, this parameter counts completed electronic evolution steps (`STEP OF ELECTRON EVOLVE`) instead, because one ionic step contains `estep_per_md` electronic steps. To write once per ionic step, set it to `estep_per_md`."; item.default_value = "0"; @@ -497,11 +497,11 @@ The LDOS is evaluated once after all ionic steps finish; the cube header records item.annotation = "output the structure files per ion step"; item.category = "Output information"; item.type = "Integer"; - item.description = "Controls the output of structure files per ionic step. The files are written to the OUT.{suffix}/ directory (or the OUT.{suffix}/STRUC/ subdirectory when out_app_flag is 2). Each file corresponds to the structure at the current ionic step; in the relaxation path the header comment records the ABACUS version, timestamp, energy, and stress tensor, while MD frames written to a cumulative file are prefixed with a one-based \"# MD step N\" marker. When out_freq_ion is positive and out_app_flag is not 0, the numbered files STRU{istep} (or STRU{istep}.cif) are written every out_freq_ion steps; when out_freq_ion is 0 or out_app_flag is 0, no numbered files are output (with out_app_flag = 0 the latest structure is still kept in STRU_NOW / STRU_NOW.cif). This parameter is effective for scf/nscf/relax/cell-relax and md; for md only values 0 and 1 are supported, because MD structure frames are written in ABACUS STRU format and read back by the restart logic, so value 2 (CIF) is rejected. For scf/nscf only STRU_FINAL (or STRU_FINAL.cif) is written.\n" - " - 0: No structure files are output.\n" - " - 1: ABACUS STRU format files are output. In scf/nscf/relax/cell-relax the latest structure is written to STRU_NOW (overwritten each step), the numbered file STRU{istep} (e.g., STRU1, STRU2) is written every out_freq_ion steps (when out_freq_ion is positive), and the final converged structure is written to STRU_FINAL. No CIF files are output. When out_app_flag is 1, the numbered STRU{istep} files are replaced by a single fixed-name STRU file that appends one structure block (with a one-based \"# Ionic_Step N\" or \"# MD step N\" comment) per written step.\n" + item.description = "Controls ordinary structure output in scf/nscf/relax/cell-relax and md calculations. Files are written to OUT.{suffix}/, or to STRUC/ when out_app_flag=2. The relaxation header records version, time, energy and stress; MD frames use a one-based \"# MD step N\" marker. In relax, STRU_NOW is overwritten each step, STRU_FINAL is written at completion, and positive out_freq_ion selects additional periodic files when out_app_flag is 1 or 2. In MD, STRU_FINAL is written at completion and positive out_freq_ion selects periodic STRU frames for all three output modes. MD supports only values 0 and 1 because CIF is not supported. For scf/nscf only STRU_FINAL (or STRU_FINAL.cif) is written.\n\n" + " - 0: No ordinary structure files are output. MD restart checkpoints remain controlled by md_restartfreq.\n" + " - 1: ABACUS STRU format files are output. In relax/cell-relax the latest structure is written to STRU_NOW (overwritten each step), periodic STRU files are written when out_freq_ion is positive and out_app_flag is 1 or 2, and the final structure is written to STRU_FINAL. For scf/nscf only STRU_FINAL is written. In MD, positive out_freq_ion selects periodic STRU files in modes 0, 1 and 2; STRU_FINAL is always written at completion. Mode 1 appends one structure block per selected step to fixed-name STRU.\n" " - 2: CIF format files are output. The latest structure is written to STRU_NOW.cif (overwritten each step), the numbered file STRU{istep}.cif (e.g., STRU1.cif, STRU2.cif) is written every out_freq_ion steps (when out_freq_ion is positive), and the final converged structure is written to STRU_FINAL.cif. No non-CIF files are output. When out_app_flag is 1, the numbered files are replaced by a fixed-name STRU.cif overwritten each written step. Not supported for calculation = md, which always writes ABACUS STRU frames.\n" - "[NOTE] MD structure output differs from the ionic-relaxation path: frames are written every out_freq_ion steps, falling back to md_restartfreq when out_freq_ion is 0; out_app_flag = 0 keeps the numbered STRU{istep} files (STRU1 is the initial geometry) and no STRU_NOW is written; out_app_flag = 2 writes the numbered files under STRUC/; out_app_flag = 1 writes one cumulative STRU file that is truncated on the first frame of a fresh run and appended with a \"# MD step N\" marker afterwards. MD never writes STRU_NOW or STRU_FINAL. When a legacy STRU/ directory exists in the output directory, MD falls back to numbered STRU{istep} files inside that directory even if out_app_flag = 1.\n" + "[NOTE] MD writes STRU_FINAL at the end when out_stru=1. With out_freq_ion>0 it also writes periodic frames from the first step: out_app_flag=0 overwrites STRU, mode 1 appends marked frames to STRU, and mode 2 writes numbered STRU{istep} files under STRUC/. With out_freq_ion=0 only STRU_FINAL is written. MD does not write STRU_NOW. Ordinary MD structures include forces in eV/Angstrom and velocities in atomic units; STRU_restart keeps velocities but omits forces, and is written with Restart_md.txt according to md_restartfreq even when out_stru=0.\n" "[NOTE] For backward compatibility, true/false (case insensitive) are accepted and converted to 1/0."; item.default_value = "1"; item.unit = ""; @@ -1589,11 +1589,11 @@ The circle order of the charge density on real space grids is: x is the outer lo item.category = "Output information"; item.type = "Integer"; item.description = R"(Controls output file organization during multi-step calculations (MD, relax, RT-TDDFT). The directory routing applies to both LCAO and PW basis calculations. -* 0: Write directly to the OUT directory under a fixed filename. Every write truncates the previous content, so only the most recently written step is kept on disk. out_freq_ion only controls how often a write happens; it does not change the number of fixed-name files (default, disk-friendly). Exception: MD structure frames are still written as numbered STRU{istep} files, so their count follows out_freq_ion. +* 0: Write directly to the OUT directory under a fixed filename. Every write truncates the previous content, so only the most recently written step is kept on disk. out_freq_ion only controls how often a write happens; it does not change the number of fixed-name files (default, disk-friendly). MD periodic structure frames overwrite STRU in this mode. * 1: Reuse fixed filenames across steps: text outputs append new records, cube outputs accumulate one frame per written step In mode 1 the first output step of a fresh (non-restart) run truncates the fixed-name file so a rerun does not keep stale records from a previous run; later steps and restarted runs keep appending. * 2: Write to subdirectory (STRUC/ for structure files, PSI/, CHG/, POT/, ELF/, DOS/, DIP/, MAT/, BANDS/), output data files carry a g{step} suffix (structures use STRU{istep}) -For MD structure frames specifically, mode 0 keeps the numbered STRU{istep} files (STRU1 is the initial geometry) and writes no STRU_NOW, mode 1 writes one cumulative STRU file, and mode 2 writes the numbered files under STRUC/; see out_stru. +For MD periodic structure frames, modes 0 and 1 both use STRU (overwritten or appended respectively), while mode 2 writes numbered files under STRUC/. MD also writes STRU_FINAL when out_stru=1 and a separate STRU_restart checkpoint according to md_restartfreq; see out_stru. The legacy Boolean spellings (true/false, yes/no, on/off, t/f, y/n, and the dotted forms) are still accepted: true maps to mode 1 and preserves the old append behavior; false maps to mode 0, which now overwrites a fixed file instead of the old g{step} per-step files, so use mode 2 to reproduce that old behavior. For more information, refer to the documentation of out_mat_r, out_hsr, out_mat_t, out_mat_dh, out_hsk, out_wfc_lcao, out_chg, out_pot, out_elf, out_dos, out_dipole, out_stru.)"; item.default_value = "0"; diff --git a/source/source_io/module_parameter/read_input_item_md.cpp b/source/source_io/module_parameter/read_input_item_md.cpp index b9bf109acf1..ef93588da23 100644 --- a/source/source_io/module_parameter/read_input_item_md.cpp +++ b/source/source_io/module_parameter/read_input_item_md.cpp @@ -159,8 +159,8 @@ Note that md_tlast is only used in NVT/NPT simulations. If md_tlast is unset or item.category = "Molecular dynamics"; item.type = "Boolean"; item.description = R"(Control whether to restart molecular dynamics calculations and time-dependent density functional theory calculations. -* True: ABACUS will read in {md_step}, then read in the corresponding structure file automatically (STRU{istep} from the STRUC/ output directory when out_app_flag=2; older releases wrote STRU_MD_{istep} into a STRU/ subdirectory, which is still recognized). For tddft, ABACUS will also read in the LCAO wavefunction file of the last step (OUT.{suffix}/PSI/wf{k-point index}{spin?}g{step}_nao.txt). You need to set out_wfc_lcao=1 and out_app_flag=2 to obtain this per-step snapshot (modes 0 and 1 write fixed-name files without a step suffix, which cannot be mapped to a specific restart step and are therefore not accepted for istep>0). -A structure frame is required for {istep}. Because out_freq_ion sets the structure-frame cadence independently of md_restartfreq, keep out_freq_ion unset (0) or equal to md_restartfreq when you intend to restart, and make sure out_stru is positive. +* True: ABACUS reads the step in Restart_md.txt and the matching structure from STRU_restart in read_file_dir. If STRU_restart is absent, legacy numbered or cumulative MD STRU frames with velocities are accepted when the recorded step matches. For tddft, ABACUS will also read in the LCAO wavefunction file of the last step (OUT.{suffix}/PSI/wf{k-point index}{spin?}g{step}_nao.txt). You need to set out_wfc_lcao=1 and out_app_flag=2 to obtain this per-step wavefunction snapshot (modes 0 and 1 write fixed-name files without a step suffix, which cannot be mapped to a specific restart step and are therefore not accepted for istep>0). +A structure frame with velocities is required for {istep}. New runs write it to STRU_restart whenever Restart_md.txt is updated, regardless of out_stru and out_freq_ion. Older outputs using cumulative or numbered STRU frames are still accepted when the matching frame exists. * False: ABACUS will start molecular dynamics calculations normally from the first step.)"; item.default_value = "False"; item.unit = ""; @@ -174,35 +174,23 @@ A structure frame is required for {istep}. Because out_freq_ion sets the structu item.type = "Integer"; item.description = "The period (in ionic steps) of writing the MD restart file " "(Restart_md.txt). This cadence is independent of out_freq_ion: " - "restart files are written every md_restartfreq steps regardless of " - "the STRU output cadence. Set to 0 to disable restart-file output. " - "When out_freq_ion is not set (0), it also falls back to md_restartfreq " - "as the STRU output frequency for backward compatibility."; + "Restart_md.txt and STRU_restart are overwritten every md_restartfreq steps " + "regardless of out_stru and out_freq_ion. STRU_restart contains the atomic " + "velocities needed to resume MD. Set to 0 to disable checkpoint output."; item.default_value = "5"; item.unit = ""; read_sync_int(input.mdp.md_restartfreq); this->add_item(item); } { - Input_Item item("md_dumpfreq"); - item.annotation = "The period to dump MD information"; - item.category = "Molecular dynamics"; - item.type = "Integer"; - item.description = "The output frequency of OUT.${suffix}/MD_dump in molecular dynamics calculations, which includes lattice and atomic information. Set to 0 to disable MD_dump output."; - item.default_value = "1"; - item.unit = ""; - read_sync_int(input.mdp.md_dumpfreq); - this->add_item(item); - } - { - Input_Item item("md_thermo_freq"); + Input_Item item("out_thermo_freq"); item.annotation = "The period to output MD thermodynamic information"; item.category = "Molecular dynamics"; item.type = "Integer"; - item.description = "The output frequency of MD step, energy, temperature, and pressure information in OUT.${suffix}/running_md.log and on screen. Set to 0 to disable this output."; + item.description = "The output frequency of MD step, energy, temperature, and pressure information in OUT.${suffix}/running_md.log and on screen. When cal_stress is enabled, the virial and total stress tensors are written to the running log at this frequency. This parameter only affects MD. Set to 0 to disable these summaries; force and stress calculations continue every step."; item.default_value = "1"; item.unit = ""; - read_sync_int(input.mdp.md_thermo_freq); + read_sync_int(input.mdp.out_thermo_freq); this->add_item(item); } { @@ -219,39 +207,6 @@ A structure frame is required for {istep}. Because out_freq_ion sets the structu read_sync_double(input.mdp.md_neighbor_skin); this->add_item(item); } - { - Input_Item item("dump_force"); - item.annotation = "output atomic forces into the file MD_dump or not"; - item.category = "Molecular dynamics"; - item.type = "Boolean"; - item.description = "Whether to output atomic forces into the file OUT.${suffix}/MD_dump."; - item.default_value = "True"; - item.unit = ""; - read_sync_bool(input.mdp.dump_force); - this->add_item(item); - } - { - Input_Item item("dump_vel"); - item.annotation = "output atomic velocities into the file MD_dump or not"; - item.category = "Molecular dynamics"; - item.type = "Boolean"; - item.description = "Whether to output atomic velocities into the file OUT.${suffix}/MD_dump."; - item.default_value = "True"; - item.unit = ""; - read_sync_bool(input.mdp.dump_vel); - this->add_item(item); - } - { - Input_Item item("dump_virial"); - item.annotation = "output lattice virial into the file MD_dump or not"; - item.category = "Molecular dynamics"; - item.type = "Boolean"; - item.description = "Whether to output lattice virials into the file OUT.${suffix}/MD_dump."; - item.default_value = "True"; - item.unit = ""; - read_sync_bool(input.mdp.dump_virial); - this->add_item(item); - } { Input_Item item("md_seed"); item.annotation = "random seed for MD"; diff --git a/source/source_io/module_parameter/read_set_globalv.cpp b/source/source_io/module_parameter/read_set_globalv.cpp index 2ab5e45269c..214e677a4f2 100644 --- a/source/source_io/module_parameter/read_set_globalv.cpp +++ b/source/source_io/module_parameter/read_set_globalv.cpp @@ -5,15 +5,59 @@ #include "source_cell/stru_frame_io.h" #include "source_io/module_parameter/parameter.h" +#include +#include +#include #include +#include namespace { -/// @brief Find the structure file for restarting a molecular dynamics run. +void log_read_file(const std::string& filename) +{ + char cwd[PATH_MAX]; + std::string full_path = filename; + if (!filename.empty() && filename[0] != '/' && getcwd(cwd, sizeof(cwd)) != nullptr) + { + full_path = std::string(cwd) + "/" + filename; + } + const std::string confirmation = "Read file: " + full_path; + std::cout << confirmation << std::endl; + GlobalV::ofs_running << confirmation << std::endl; +} + +bool has_md_velocities(const std::string& filename) +{ + std::ifstream file(filename.c_str()); + std::string line; + while (std::getline(file, line)) + { + std::istringstream record(line); + double x = 0.0; + double y = 0.0; + double z = 0.0; + if (!(record >> x >> y >> z)) + { + continue; + } + std::string field; + while (record >> field) + { + if (field == "v" || field == "vel" || field == "velocity") + { + return true; + } + } + } + return false; +} + +/// @brief Find a legacy structure file for restarting a molecular dynamics run. /// @param stru_dir directory where the previous run wrote its structure files /// @param istep number of completed ionic steps recorded in Restart_md.txt /// @return path of the first existing structure file, empty if none exists -/// @details Three naming schemes are accepted, in order: +/// @details New runs use STRU_restart. Three older naming schemes are +/// accepted as fallbacks, in order: /// - "STRU": fixed-name cumulative file written in out_app_flag == 1 mode. /// Unlike an earlier implementation that blindly took the last frame (and thus /// risked mixing geometry from a later step with Restart_md.txt metadata from @@ -30,31 +74,29 @@ namespace std::string find_md_restart_stru(const std::string& stru_dir, const int istep) { // Prefer the fixed-name cumulative STRU when its marker exactly matches - // the step this restart resumes from. Walking the cumulative file picks - // the frame that belongs to Restart_md.txt even when the user configured - // out_freq_ion and md_restartfreq to different values: run_md guarantees - // a checkpoint frame on every md_restartfreq step, so the marker must be - // present whenever the restart file was written. + // the step this legacy restart resumes from. New runs use STRU_restart; + // old output may contain a matching cumulative frame. const std::string stru_cumulative = stru_dir + "STRU"; std::ifstream file_cumulative(stru_cumulative.c_str()); if (file_cumulative.good()) { file_cumulative.close(); const std::string frame_path = stru_dir + "STRU_restart_frame"; - if (stru_frame_io::extract_frame_by_step(stru_cumulative, istep + 1, frame_path)) + if (stru_frame_io::extract_frame_by_step(stru_cumulative, istep + 1, frame_path) + && has_md_velocities(frame_path)) { return frame_path; } } const std::string stru_new = stru_dir + "STRU" + std::to_string(istep + 1); std::ifstream file_new(stru_new.c_str()); - if (file_new.good()) + if (file_new.good() && has_md_velocities(stru_new)) { return stru_new; } const std::string stru_old = stru_dir + "STRU_MD_" + std::to_string(istep); std::ifstream file_old(stru_old.c_str()); - if (file_old.good()) + if (file_old.good() && has_md_velocities(stru_old)) { return stru_old; } @@ -195,8 +237,25 @@ void ReadInput::set_global_dir(const Input_para& inp, System_para& sys) if (inp.calculation == "md" && inp.mdp.md_restart) { const int istep = current_md_step(sys.global_readin_dir); - - if (inp.read_file_dir == to_dir("OUT." + inp.suffix)) + const std::string checkpoint = sys.global_readin_dir + "STRU_restart"; + std::ifstream checkpoint_file(checkpoint.c_str()); + if (checkpoint_file.good()) + { + checkpoint_file.close(); + const int checkpoint_step = stru_frame_io::last_frame_step(checkpoint); + if (checkpoint_step != istep + 1) + { + const std::string message = "STRU_restart step " + std::to_string(checkpoint_step) + + " does not match Restart_md.txt step " + std::to_string(istep + 1); + ModuleBase::WARNING_QUIT("ReadInput::set_global_dir", message); + } + if (!has_md_velocities(checkpoint)) + { + ModuleBase::WARNING_QUIT("ReadInput::set_global_dir", "STRU_restart lacks atomic velocities"); + } + sys.global_in_stru = checkpoint; + } + else if (inp.read_file_dir == to_dir("OUT." + inp.suffix)) { // Restart from the default output directory: search the current // STRU output directory, which follows out_app_flag. @@ -226,14 +285,12 @@ void ReadInput::set_global_dir(const Input_para& inp, System_para& sys) + "; Restart_md.txt reports step " + std::to_string(istep) + " but no matching structure frame is present. " - "run_md writes a checkpoint STRU frame on every md_restartfreq " - "step (independent of out_stru) since the decoupling fix, so " - "this usually means the restart directory was produced by an " - "older ABACUS release or is missing both the numbered STRU{step+1} " - "/ STRU_MD_{step} file and a cumulative STRU with a matching " - "\"# MD step N\" marker."; + "the directory is missing STRU_restart and any matching legacy " + "STRU{step+1}, STRU_MD_{step}, or cumulative STRU frame " + "containing atomic velocities."; ModuleBase::WARNING_QUIT("ReadInput::set_global_dir", message); } + log_read_file(sys.global_in_stru); } else { diff --git a/source/source_io/unittests/support/INPUT b/source/source_io/unittests/support/INPUT index 0a244fd613a..dd40deb5a19 100644 --- a/source/source_io/unittests/support/INPUT +++ b/source/source_io/unittests/support/INPUT @@ -186,8 +186,7 @@ md_dt 1 #time step md_tchain 1 #number of Nose-Hoover chains md_tfirst -1 #temperature first md_tlast -1 #temperature last -md_dumpfreq 1 #The period to dump MD information -md_thermo_freq 1 #The period to output MD thermodynamic information +out_thermo_freq 1 #The period to output MD thermodynamic information md_restartfreq 5 #The period to output MD restart information md_seed -1 #random seed for MD md_prec_level 2 #precision level for vc-md @@ -219,9 +218,6 @@ md_pchain 1 #num of thermostats coupled with barostat md_pfirst -1 #initial target pressure md_plast -1 #final target pressure md_pfreq 0 #oscillation frequency, used to determine qmass of thermostats coupled with barostat -dump_force 0 #output atomic forces into the file MD_dump or not. -dump_vel 0 #output atomic velocities into the file MD_dump or not -dump_virial 0 #output lattice virial into the file MD_dump or not #Parameters (10.Electric field and dipole correction) efield_flag 0 #add electric field diff --git a/source/source_io/unittests/test_frame_append.cpp b/source/source_io/unittests/test_frame_append.cpp index 1901366d9a8..731d94e1e19 100644 --- a/source/source_io/unittests/test_frame_append.cpp +++ b/source/source_io/unittests/test_frame_append.cpp @@ -25,3 +25,11 @@ TEST(FrameAppend, RejectsInvalidArguments) EXPECT_THROW(ModuleIO::frame_appends(3, 1), std::invalid_argument); EXPECT_THROW(ModuleIO::frame_appends(1, -1), std::invalid_argument); } + +TEST(FrameAppend, StructureFilenamesFollowTheThreeOutputModes) +{ + EXPECT_EQ(ModuleIO::stru_frame_filename("OUT/", 0, 0), "OUT/STRU"); + EXPECT_EQ(ModuleIO::stru_frame_filename("OUT/", 1, 3), "OUT/STRU"); + EXPECT_EQ(ModuleIO::stru_frame_filename("OUT/STRUC/", 2, 3), "OUT/STRUC/STRU4"); + EXPECT_THROW(ModuleIO::stru_frame_filename("OUT/", 3, 0), std::invalid_argument); +} diff --git a/source/source_io/unittests/test_io_sys_var.cpp b/source/source_io/unittests/test_io_sys_var.cpp index fd7dcb62248..cdd4946e608 100644 --- a/source/source_io/unittests/test_io_sys_var.cpp +++ b/source/source_io/unittests/test_io_sys_var.cpp @@ -131,7 +131,7 @@ TEST_F(InputTest, SetGlobalDirMdRestart) restart_file.close(); const std::string stru_legacy = legacy_dir + "STRU_MD_5"; std::ofstream stru_file_legacy(stru_legacy.c_str()); - stru_file_legacy << "ATOMIC_SPECIES" << std::endl; + stru_file_legacy << "ATOMIC_SPECIES\n0 0 0 v 0 0 0\n"; stru_file_legacy.close(); input.suffix = "autotest"; @@ -141,8 +141,8 @@ TEST_F(InputTest, SetGlobalDirMdRestart) TestParameters::set_global_dir(readinput, input, sys); EXPECT_EQ(sys.global_in_stru, stru_legacy); - // Restart from a read_file_dir holding the current "STRU{istep + 1}" - // naming written by run_md (1-based, unified with relax). + // Restart from a read_file_dir holding the older "STRU{istep + 1}" + // naming (1-based, unified with relax). const std::string newnaming_dir = case_dir + "newnaming/"; ModuleBase::make_directory(newnaming_dir); const std::string restart_txt_new = newnaming_dir + "Restart_md.txt"; @@ -152,7 +152,7 @@ TEST_F(InputTest, SetGlobalDirMdRestart) restart_file_new.close(); const std::string stru_new = newnaming_dir + "STRU6"; std::ofstream stru_file_new(stru_new.c_str()); - stru_file_new << "ATOMIC_SPECIES" << std::endl; + stru_file_new << "ATOMIC_SPECIES\n0 0 0 v 0 0 0\n"; stru_file_new.close(); input.read_file_dir = newnaming_dir; @@ -166,6 +166,8 @@ TEST_F(InputTest, SetGlobalDirMdRestart) // resuming from step 2 corresponds to the frame tagged "# MD step 3". const std::string cumulative_dir = case_dir + "cumulative/"; ModuleBase::make_directory(cumulative_dir); + const std::string checkpoint = cumulative_dir + "STRU_restart"; + std::remove(checkpoint.c_str()); const std::string restart_txt_cum = cumulative_dir + "Restart_md.txt"; std::ofstream restart_file_cum(restart_txt_cum.c_str()); restart_file_cum << 2 << std::endl; @@ -175,7 +177,7 @@ TEST_F(InputTest, SetGlobalDirMdRestart) std::ofstream stru_file_cum(stru_cumulative.c_str()); stru_file_cum << "# MD step 1\n\nATOMIC_SPECIES\nSi 28.0855\n" << std::endl; stru_file_cum << "# MD step 2\n\nATOMIC_SPECIES\nSi 28.0855\n\nLATTICE_CONSTANT\n10.2\n" << std::endl; - stru_file_cum << "# MD step 3\n\nATOMIC_SPECIES\nSi 28.0855\n\nLATTICE_CONSTANT\n10.5\n" << std::endl; + stru_file_cum << "# MD step 3\n\nATOMIC_SPECIES\nSi 28.0855\n\nLATTICE_CONSTANT\n10.5\n0 0 0 v 0 0 0\n" << std::endl; stru_file_cum.close(); input.read_file_dir = cumulative_dir; @@ -188,6 +190,13 @@ TEST_F(InputTest, SetGlobalDirMdRestart) EXPECT_TRUE(frame_ifs.good()); frame_ifs.close(); + // A dedicated checkpoint takes priority over ordinary trajectory frames. + std::ofstream checkpoint_file(checkpoint.c_str()); + checkpoint_file << "# MD step 3\n\nATOMIC_SPECIES\nSi 28.0855\n0 0 0 v 0 0 0\n"; + checkpoint_file.close(); + TestParameters::set_global_dir(readinput, input, sys); + EXPECT_EQ(sys.global_in_stru, checkpoint); + // Regression: a stale number-named file from an earlier run must not // shadow the cumulative STRU of the run being restarted. Here the fixed // name holds the frame of step 1 that Restart_md.txt resumes from, while @@ -201,7 +210,7 @@ TEST_F(InputTest, SetGlobalDirMdRestart) restart_file_stale.close(); const std::string stru_stale = stale_dir + "STRU"; std::ofstream stru_file_stale(stru_stale.c_str()); - stru_file_stale << "# MD step 1\n\nATOMIC_SPECIES\nSi 28.0855\n" << std::endl; + stru_file_stale << "# MD step 1\n\nATOMIC_SPECIES\nSi 28.0855\n0 0 0 v 0 0 0\n" << std::endl; stru_file_stale.close(); const std::string stru_leftover = stale_dir + "STRU1"; std::ofstream stru_file_leftover(stru_leftover.c_str()); @@ -211,6 +220,7 @@ TEST_F(InputTest, SetGlobalDirMdRestart) input.read_file_dir = stale_dir; TestParameters::set_global_dir(readinput, input, sys); EXPECT_EQ(sys.global_in_stru, stale_dir + "STRU_restart_frame"); + std::remove(checkpoint.c_str()); // restore the shared input state so other tests are not affected input.calculation = "scf"; diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 62051fc3652..64ad454c1d4 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -129,6 +129,23 @@ TEST_F(InputTest, InvalidExplicitDomainDoesNotReachReadOrResetHooks) EXPECT_FALSE(reset_called); } +TEST_F(InputTest, MdThermoFrequencyUsesOnlyOutName) +{ + ModuleIO::ReadInput reader(0); + EXPECT_NE(find_label("out_thermo_freq", reader.input_lists), reader.input_lists.end()); + EXPECT_EQ(find_label("md_thermo_freq", reader.input_lists), reader.input_lists.end()); + + const std::string filename = testing::TempDir() + "abacus_md_thermo_frequency_INPUT"; + { + std::ofstream input(filename.c_str()); + input << "INPUT_PARAMETERS\nmd_thermo_freq 2\n"; + } + Parameter param; + const std::string error = reader.read_txt_input(param, filename); + EXPECT_THAT(error, testing::HasSubstr("Unknown INPUT parameter 'md_thermo_freq'")); + std::remove(filename.c_str()); +} + TEST_F(InputTest, RelaxMethod) { ModuleIO::ReadInput readinput(0); @@ -2667,12 +2684,12 @@ TEST_F(InputTest, Item_test2) it->second.reset_value(it->second, param); EXPECT_EQ(TestParameters::input(param).mdp.md_nstep, 50); } - { // md_thermo_freq + { // out_thermo_freq std::vector>::iterator it - = find_label("md_thermo_freq", readinput.input_lists); + = find_label("out_thermo_freq", readinput.input_lists); it->second.str_values = {"100"}; it->second.read_value(it->second, param); - EXPECT_EQ(TestParameters::input(param).mdp.md_thermo_freq, 100); + EXPECT_EQ(TestParameters::input(param).mdp.out_thermo_freq, 100); } { // md_prec_level auto it = find_label("md_prec_level", readinput.input_lists); diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index 252df3cc8fa..edaf068137e 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -404,8 +404,7 @@ TEST_F(InputParaTest, ParaRead) EXPECT_NEAR(param.inp.mdp.lj_sigma[0], 3.405, 1e-7); EXPECT_EQ(param.inp.mdp.md_damp, 1); EXPECT_EQ(param.inp.mdp.md_dt, 1); - EXPECT_EQ(param.inp.mdp.md_dumpfreq, 1); - EXPECT_EQ(param.inp.mdp.md_thermo_freq, 1); + EXPECT_EQ(param.inp.mdp.out_thermo_freq, 1); EXPECT_EQ(param.inp.mdp.md_nraise, 1); EXPECT_EQ(param.inp.cal_syns[0], 0); EXPECT_EQ(param.inp.cal_syns[1], 8); @@ -444,9 +443,6 @@ TEST_F(InputParaTest, ParaRead) EXPECT_DOUBLE_EQ(param.inp.mdp.dp_fparam[1], 1.1); EXPECT_DOUBLE_EQ(param.inp.mdp.dp_aparam[0], 1.0); EXPECT_DOUBLE_EQ(param.inp.mdp.dp_aparam[1], 1.2); - EXPECT_FALSE(param.inp.mdp.dump_force); - EXPECT_FALSE(param.inp.mdp.dump_vel); - EXPECT_FALSE(param.inp.mdp.dump_virial); EXPECT_EQ(param.inp.sc_mag_switch, 0); EXPECT_TRUE(param.inp.decay_grad_switch); EXPECT_DOUBLE_EQ(param.inp.sc_thr, 1e-4); diff --git a/source/source_lcao/force_stress_assemble.cpp b/source/source_lcao/force_stress_assemble.cpp index 331b75d39f3..91f7734a4c5 100644 --- a/source/source_lcao/force_stress_assemble.cpp +++ b/source/source_lcao/force_stress_assemble.cpp @@ -245,6 +245,7 @@ void assemble_print_force(const UnitCell& ucell, ModuleBase::matrix& fcs) { const int nat = ucell.nat; + const auto& input = PARAM.inp; //--------------------------------- // sum all parts of force! //--------------------------------- @@ -257,7 +258,7 @@ void assemble_print_force(const UnitCell& ucell, } } - if (PARAM.inp.gate_flag || PARAM.inp.efield_flag) + if (input.gate_flag || input.efield_flag) { GlobalV::ofs_running << "Atomic forces are not shifted if gate_flag or efield_flag == true!" << std::endl; } @@ -283,19 +284,23 @@ void assemble_print_force(const UnitCell& ucell, } net_force[i] = sum; } - if (!(PARAM.inp.gate_flag || PARAM.inp.efield_flag)) + if (!(input.gate_flag || input.efield_flag)) { ModuleBase::remove_net_force(nat, fcs); } // compute forces using the DeePKS model - DeePKS_domain::write_forces(fcs, parts.fvnl_dalpha, dpks_out_type, PARAM.inp); + DeePKS_domain::write_forces(fcs, parts.fvnl_dalpha, dpks_out_type, input); - if (istestf) + if (istestf && input.calculation != "md") { print_force_parts(ucell, vdw_result, parts); } + if (input.calculation == "md") + { + return; + } GlobalV::ofs_running << std::setiosflags(std::ios::left); // this->printforce_total(ry, istestf, fcs); @@ -318,6 +323,7 @@ void assemble_print_stress(const UnitCell& ucell, const LCAOStressParts& sparts, ModuleBase::matrix& scs) { + const auto& input = PARAM.inp; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) @@ -336,7 +342,7 @@ void assemble_print_stress(const UnitCell& ucell, bool ry = false; // test stress each terms if needed - if (istests) + if (istests && input.calculation != "md") { // test ModuleBase::matrix svlocal; @@ -352,7 +358,7 @@ void assemble_print_stress(const UnitCell& ucell, } } - const bool screen = PARAM.inp.test_stress; + const bool screen = input.test_stress; GlobalV::ofs_running << "\n PARTS OF STRESS: " << std::endl; GlobalV::ofs_running << std::setiosflags(std::ios::showpos); @@ -388,11 +394,14 @@ void assemble_print_stress(const UnitCell& ucell, ModuleIO::print_stress("TOTAL STRESS", scs, screen, ry, GlobalV::ofs_running); } // end of test - GlobalV::ofs_running << std::setiosflags(std::ios::left); + if (input.calculation != "md") + { + GlobalV::ofs_running << std::setiosflags(std::ios::left); - // print total stress - bool screen_normal = true; - ModuleIO::print_stress("TOTAL-STRESS", scs, screen_normal, ry, GlobalV::ofs_running); + // print total stress + bool screen_normal = true; + ModuleIO::print_stress("TOTAL-STRESS", scs, screen_normal, ry, GlobalV::ofs_running); + } double unit_transform = 0.0; unit_transform = ModuleBase::RYDBERG_SI / pow(ModuleBase::BOHR_RADIUS_SI, 3) * 1.0e-8; diff --git a/source/source_md/md_base.cpp b/source/source_md/md_base.cpp index fc477153d6b..12be76b7f86 100644 --- a/source/source_md/md_base.cpp +++ b/source/source_md/md_base.cpp @@ -57,7 +57,7 @@ void MD_base::setup( } const int md_step = step_ + step_rst_; - const bool print_thermo = mdp.md_thermo_freq > 0 && md_step % mdp.md_thermo_freq == 0; + const bool print_thermo = mdp.out_thermo_freq > 0 && md_step % mdp.out_thermo_freq == 0; if (print_thermo) { const int stress_step = 0; @@ -229,6 +229,8 @@ void MD_base::print_md(std::ofstream &ofs, const bool &cal_stress) // running_log output ofs.unsetf(std::ios::fixed); ofs << std::setprecision(8); + const int output_step = step_ + step_rst_ + 1; + ofs << " MD STEP: " << output_step << std::endl; if (cal_stress) { diff --git a/source/source_md/md_func.cpp b/source/source_md/md_func.cpp index 3b80b422503..b3e338ccb82 100644 --- a/source/source_md/md_func.cpp +++ b/source/source_md/md_func.cpp @@ -8,11 +8,8 @@ #include #include -#include -#include #include #include -#include namespace MD_func { @@ -445,6 +442,21 @@ void print_stress(std::ofstream &ofs, const ModuleBase::matrix &virial, const Mo << std::endl; ofs << " MD PRESSURE (ELECTRONS+IONS) : " << stress_scalar * unit_transform << " kbar" << std::endl; + ofs << " VIRIAL (kbar):" << std::endl; + ofs << std::setprecision(12); + for (int i = 0; i < 3; ++i) + { + ofs << " " << virial(i, 0) * unit_transform << " " << virial(i, 1) * unit_transform + << " " << virial(i, 2) * unit_transform << std::endl; + } + ofs << " MD TOTAL STRESS (kbar):" << std::endl; + for (int i = 0; i < 3; ++i) + { + ofs << " " << stress(i, 0) * unit_transform << " " << stress(i, 1) * unit_transform + << " " << stress(i, 2) * unit_transform << std::endl; + } + ofs << std::setprecision(8); + // one should use 'print_stress' function in ../source/source_io/output_log.cpp /* ofs.unsetf(std::ios::fixed); @@ -461,207 +473,6 @@ void print_stress(std::ofstream &ofs, const ModuleBase::matrix &virial, const Mo return; } -namespace -{ -void write_dump_rows( - std::ostream &output, - const std::string &text, - const std::int64_t begin, - const std::int64_t end) -{ - // Spatial ownership is unrelated to the stable type-major atom index. - std::map rows; - std::istringstream input(text); - std::string line; - while (std::getline(input, line)) - { - std::istringstream record(line); - std::int64_t index = 0; - if (!(record >> index) || index < begin || index >= end) - { - ModuleBase::WARNING_QUIT("MD_func::dump_info", "invalid MD_dump atom index."); - } - const bool inserted = rows.emplace(index, line).second; - if (!inserted) - { - ModuleBase::WARNING_QUIT("MD_func::dump_info", "duplicate MD_dump atom index."); - } - } - const std::size_t expected_count = static_cast(end - begin); - if (rows.size() != expected_count) - { - ModuleBase::WARNING_QUIT("MD_func::dump_info", "missing MD_dump atoms."); - } - for (const auto &row : rows) - { - output << row.second << "\n"; - } -} -} // namespace - -void dump_info( - const int &step, - const std::string &global_out_dir, - const MDCell &mdcell, - const MD_para &mdp, - const bool cal_stress, - const ModuleBase::matrix &virial) -{ - const int max_batch_bytes = 1024 * 1024; - dump_info(step, global_out_dir, mdcell, mdp, cal_stress, virial, max_batch_bytes); -} - -void dump_info( - const int &step, - const std::string &global_out_dir, - const MDCell &mdcell, - const MD_para &mdp, - const bool cal_stress, - const ModuleBase::matrix &virial, - const int max_batch_bytes) -{ - if (max_batch_bytes <= 0) - { - throw std::invalid_argument("MD_dump batch budget must be positive."); - } - std::stringstream file; - file << global_out_dir << "MD_dump"; - const double unit_pos = mdcell.lat0() / ModuleBase::ANGSTROM_AU; - const double unit_vel = 1.0 / ModuleBase::ANGSTROM_AU / ModuleBase::AU_to_FS; - const double unit_virial = ModuleBase::HARTREE_SI / pow(ModuleBase::BOHR_RADIUS_SI, 3) * 1.0e-8; - const double unit_force = ModuleBase::Hartree_to_eV * ModuleBase::ANGSTROM_AU; - std::ostringstream header; - header << "MDSTEP: " << step << "\n" << std::fixed << std::setprecision(12); - header << "LATTICE_CONSTANT: " << mdcell.lat0() * ModuleBase::BOHR_TO_A << " Angstrom\nLATTICE_VECTORS\n"; - header << " " << mdcell.latvec().e11 << " " << mdcell.latvec().e12 << " " << mdcell.latvec().e13 << "\n"; - header << " " << mdcell.latvec().e21 << " " << mdcell.latvec().e22 << " " << mdcell.latvec().e23 << "\n"; - header << " " << mdcell.latvec().e31 << " " << mdcell.latvec().e32 << " " << mdcell.latvec().e33 << "\n"; - if (cal_stress && mdp.dump_virial) - { - header << "VIRIAL (kbar)\n"; - for (int i = 0; i < 3; ++i) - { - header << " " << virial(i, 0) * unit_virial << " " << virial(i, 1) * unit_virial << " " - << virial(i, 2) * unit_virial << "\n"; - } - } - header << "INDEX LABEL POSITION (Angstrom)"; - if (mdp.dump_force) - { - header << " FORCE (eV/Angstrom)"; - } - if (mdp.dump_vel) - { - header << " VELOCITY (Angstrom/fs)"; - } - header << "\n"; - std::vector type_offsets(mdcell.type_atom_counts().size() + 1, 0); - for (std::size_t it = 0; it < mdcell.type_atom_counts().size(); ++it) - { - type_offsets[it + 1] = type_offsets[it] + mdcell.type_atom_counts()[it]; - } - const auto format_atom = [&](const LocalAtom &atom) -> std::string - { - std::ostringstream row; - row << std::fixed << std::setprecision(12); - row << " " << type_offsets[atom.type] + atom.type_index << " " << mdcell.type_labels()[atom.type] << " " - << atom.cart.x * unit_pos << " " << atom.cart.y * unit_pos << " " << atom.cart.z * unit_pos; - if (mdp.dump_force) - { - row << " " << atom.force.x * unit_force << " " << atom.force.y * unit_force << " " - << atom.force.z * unit_force; - } - if (mdp.dump_vel) - { - row << " " << atom.vel.x * unit_vel << " " << atom.vel.y * unit_vel << " " << atom.vel.z * unit_vel; - } - row << "\n"; - return row.str(); - }; - std::vector> ordered_atoms; - const std::size_t local_atom_count = mdcell.owned_atoms().size(); - ordered_atoms.reserve(local_atom_count); - int local_row_bytes = 0; - int local_overflow = 0; - const std::size_t maximum_count = std::numeric_limits::max(); - for (const LocalAtom &atom : mdcell.owned_atoms()) - { - const std::int64_t index = type_offsets[atom.type] + atom.type_index; - const LocalAtom *atom_pointer = &atom; - ordered_atoms.emplace_back(index, atom_pointer); - const std::string row = format_atom(atom); - if (row.size() > maximum_count) - { - local_overflow = 1; - } - else - { - const int row_bytes = static_cast(row.size()); - local_row_bytes = std::max(local_row_bytes, row_bytes); - } - } - std::sort( - ordered_atoms.begin(), ordered_atoms.end(), - [](const std::pair &left, - const std::pair &right) { return left.first < right.first; }); - ModuleBase::CommunicationDomain domain; -#ifdef __MPI - domain.initialize(mdcell.communicator()); -#endif - if (domain.max(local_overflow) != 0) - { - throw std::length_error("A single MD_dump row exceeds the MPI count range."); - } - const int maximum_row_bytes = domain.max(local_row_bytes); - const int row_bytes = std::max(maximum_row_bytes, 1); - const int batch_bytes = std::max(max_batch_bytes, row_bytes); - const std::int64_t batch_atoms = batch_bytes / row_bytes; - std::ofstream ofs; - if (domain.rank() == 0) - { - const std::string filename = file.str(); - const std::ios_base::openmode mode = step == 0 ? std::ios::trunc : std::ios::app; - ofs.open(filename.c_str(), mode); - if (!ofs) - { - ModuleBase::WARNING_QUIT("MD_func::dump_info", "cannot open MD_dump."); - } - ofs << header.str(); - } - std::size_t local_index = 0; - for (std::int64_t begin = 0; begin < type_offsets.back();) - { - // Each global-index range contains at most batch_atoms rows across all ranks. - // Counts and displacements are bounded per batch, independent of frame size. - const std::int64_t remaining = type_offsets.back() - begin; - const std::int64_t count = std::min(batch_atoms, remaining); - const std::int64_t end = begin + count; - std::ostringstream local; - while (local_index < ordered_atoms.size() && ordered_atoms[local_index].first < end) - { - const LocalAtom &atom = *ordered_atoms[local_index].second; - local << format_atom(atom); - ++local_index; - } - const std::string local_text = local.str(); - const std::string gathered = domain.gather_text(local_text, batch_bytes); - if (domain.rank() == 0) - { - write_dump_rows(ofs, gathered, begin, end); - } - begin = end; - } - if (domain.rank() == 0) - { - ofs << "\n\n"; - ofs.close(); - if (!ofs) - { - ModuleBase::WARNING_QUIT("MD_func::dump_info", "cannot write MD_dump."); - } - } -} - void get_mass_mbl( const UnitCell &unit_in, double *allmass, diff --git a/source/source_md/md_func.h b/source/source_md/md_func.h index 0074b82a679..03604a3a553 100644 --- a/source/source_md/md_func.h +++ b/source/source_md/md_func.h @@ -137,37 +137,6 @@ void compute_stress( */ void print_stress(std::ofstream &ofs, const ModuleBase::matrix &virial, const ModuleBase::matrix &stress); -/** - * @brief dump the md information - * - * including md step, lattice constant, lattice vectors, lattice virial tensor, ion index, ion positions, - * ion velocities, ion forces - * - * @param step current md step - * @param global_out_dir directory of output files - * @param mdcell MD cell information - * @param mdp the md input parameters - * @param cal_stress whether stress is calculated - * @param virial lattice virial tensor - */ -void dump_info( - const int &step, - const std::string &global_out_dir, - const MDCell &mdcell, - const MD_para &mdp, - const bool cal_stress, - const ModuleBase::matrix &virial); - -/// Explicit buffer budget for bounded dump collectives; one row is the minimum batch. -void dump_info( - const int &step, - const std::string &global_out_dir, - const MDCell &mdcell, - const MD_para &mdp, - const bool cal_stress, - const ModuleBase::matrix &virial, - const int max_batch_bytes); - /** * @brief obtain the atomic mass and whether the freedom is fixed * diff --git a/source/source_md/run_md.cpp b/source/source_md/run_md.cpp index 698ae7dbcda..75baf5117b2 100644 --- a/source/source_md/run_md.cpp +++ b/source/source_md/run_md.cpp @@ -17,11 +17,13 @@ #include "nhchain.h" #include "source_cell/print_cell.h" #include "source_cell/update_cell.h" +#include "source_io/module_output/frame_append.h" #include "source_io/module_output/print_info.h" #include "source_md/module_plumed/plumed_interface.h" #include "verlet.h" -#include +#include +#include #include #ifdef __MPI #include @@ -99,61 +101,39 @@ void md_line( } }; - // An unset out_freq_ion uses the restart cadence for regular output. - const int eff_output_freq = - (param_in.inp.out_freq_ion > 0) ? param_in.inp.out_freq_ion : param_in.mdp.md_restartfreq; - + const int output_freq = param_in.inp.out_freq_ion; const int restart_freq = param_in.mdp.md_restartfreq; + const std::string stru_out_dir = param_in.globalv.global_stru_dir; + const std::string restart_stru = param_in.globalv.global_out_dir + "STRU_restart"; - // Preserve numbered frames if a legacy STRU/ directory occupies the fixed-name path. - const bool append_stru_allowed = (param_in.inp.out_app_flag == 1); - bool has_legacy_stru_dir = false; - std::string stru_out_dir = PARAM.globalv.global_stru_dir; - if (append_stru_allowed) + auto log_written_file = [&](const std::string &filename) { - struct stat stru_path; - if (stat((stru_out_dir + "STRU").c_str(), &stru_path) == 0 && S_ISDIR(stru_path.st_mode)) + if (my_rank != 0) { - has_legacy_stru_dir = true; - stru_out_dir += "STRU/"; + return; } - } + char cwd[PATH_MAX]; + std::string full_path = filename; + if (!filename.empty() && filename[0] != '/' && getcwd(cwd, sizeof(cwd)) != nullptr) + { + full_path = std::string(cwd) + "/" + filename; + } + GlobalV::ofs_running << "Write file: " << full_path << '\n'; + }; - /// Write one STRU frame for `current_step`. Cadence frames and the final - /// frame share the same naming/append rules, so both call sites use this - /// lambda. `current_step == 0` marks the first frame of a fresh run, which - /// truncates the fixed-name file instead of appending to it. - auto write_stru_frame = [&](const int current_step) + auto write_stru_frame = [&](const int current_step, const std::string &filename, const bool append, + const bool include_force) { if (mdcell.has_backing_unitcell()) { const bool positions_updated = false; mdcell.sync_backing_unitcell(positions_updated); } - // Mode-2 STRUC/ subdirectory is created lazily at write time. - ModuleBase::ensure_directory(stru_out_dir); const int stru_step = current_step + 1; - // File-name selection and append/truncate are two independent - // decisions. The file name is fixed to "STRU" whenever mode 1 - // accumulation is allowed (and no legacy STRU/ directory is in - // the way); modes 0/2 keep the numbered STRU{stru_step} files. - // Whether to append depends on whether this is the very first - // step of a fresh (non-restart) run: a fresh first frame - // truncates the fixed-name file so it does not keep frames - // from a previous run, while later steps and restarted runs - // append one frame each, introduced by a one-based - // "# MD step N" comment line. - const bool use_fixed_name = append_stru_allowed && !has_legacy_stru_dir; - const bool is_first_step_of_fresh_run = (current_step == 0); - const bool append_stru = use_fixed_name && !is_first_step_of_fresh_run; - const std::string frame_comment = use_fixed_name ? "# MD step " + std::to_string(stru_step) + "\n\n" : ""; - std::stringstream file; - file << stru_out_dir << "STRU"; - if (!use_fixed_name) - { - file << stru_step; - } - mdcell::print_stru_file(mdcell, mdcell.stru_meta(), file.str(), frame_comment, append_stru); + const std::string frame_comment = "# MD step " + std::to_string(stru_step) + "\n\n"; + mdcell::print_stru_file(mdcell, mdcell.stru_meta(), filename, frame_comment, + append, include_force); + log_written_file(filename); }; /// md cycle, mohan update 2026-01-04, change '<=' to '<' @@ -169,7 +149,7 @@ void md_line( { mdcell.backing_unitcell().last_ion_step = is_final_step; } - bool print_thermo = param_in.mdp.md_thermo_freq > 0 && md_step % param_in.mdp.md_thermo_freq == 0; + bool print_thermo = param_in.mdp.out_thermo_freq > 0 && md_step % param_in.mdp.out_thermo_freq == 0; #ifdef __JSON // Start the UnitCell-backed JSON record before the solver writes SCF data. if (mdcell.has_backing_unitcell()) @@ -184,7 +164,7 @@ void md_line( // setup() may change step_rst_ when resuming a run. const int restart_step = mdrun->step_ + mdrun->step_rst_; - print_thermo = param_in.mdp.md_thermo_freq > 0 && restart_step % param_in.mdp.md_thermo_freq == 0; + print_thermo = param_in.mdp.out_thermo_freq > 0 && restart_step % param_in.mdp.out_thermo_freq == 0; if (param_in.mdp.plumed) { @@ -244,43 +224,43 @@ void md_line( { mdrun->print_md(GlobalV::ofs_running, param_in.inp.cal_stress); } - if (param_in.mdp.md_dumpfreq > 0 && (mdrun->step_ + mdrun->step_rst_) % param_in.mdp.md_dumpfreq == 0) - { - MD_func::dump_info( - mdrun->step_ + mdrun->step_rst_, PARAM.globalv.global_out_dir, mdcell, mdp, cal_stress, mdrun->virial); - } - const int current_step = mdrun->step_ + mdrun->step_rst_; - const bool do_output_step = eff_output_freq > 0 && current_step % eff_output_freq == 0; - const bool do_restart_step = restart_freq > 0 && current_step % restart_freq == 0; - const bool write_any_frame = (do_output_step && param_in.inp.out_stru > 0) || do_restart_step; + const bool do_output_step = is_structure_output_step(current_step, output_freq, param_in.inp.out_stru > 0); + const bool do_restart_step = is_cadence_step(current_step, restart_freq); - // Every restart step needs a matching STRU frame, even when out_stru=0. - // A step on both cadences writes only one frame. - if (write_any_frame) + if (do_output_step) { - write_stru_frame(current_step); + ModuleBase::ensure_directory(stru_out_dir); + const std::string filename = ModuleIO::stru_frame_filename( + stru_out_dir, param_in.inp.out_app_flag, current_step); + const bool append = ModuleIO::frame_appends(param_in.inp.out_app_flag, current_step); + const bool include_force = true; + write_stru_frame(current_step, filename, append, include_force); } last_processed_step = current_step; if (do_restart_step) { - mdrun->write_restart(PARAM.globalv.global_out_dir); + const bool append = false; + const bool include_force = false; + write_stru_frame(current_step, restart_stru, append, include_force); + mdrun->write_restart(param_in.globalv.global_out_dir); + const std::string restart_metadata = param_in.globalv.global_out_dir + "Restart_md.txt"; + log_written_file(restart_metadata); } mdrun->step_++; } - /// Supplementary final frame. When the last step is off both the output - /// and the restart cadences the loop above never writes its STRU, so write - /// it here to guarantee the final geometry is persisted. Steps already - /// covered by a cadence are not written twice. out_stru=0 keeps the - /// existing contract of silencing regular per-step geometry output, so the - /// final frame is skipped as well. - if (last_processed_step >= 0 && param_in.inp.out_stru > 0 && - !is_frame_write_step(last_processed_step, param_in.inp.out_freq_ion, restart_freq, true)) + // Final geometry is a separate output and is written even when the last + // step was also selected for periodic output. + if (last_processed_step >= 0 && param_in.inp.out_stru > 0) { - write_stru_frame(last_processed_step); + ModuleBase::ensure_directory(stru_out_dir); + const std::string filename = stru_out_dir + "STRU_FINAL"; + const bool append = false; + const bool include_force = true; + write_stru_frame(last_processed_step, filename, append, include_force); } /// flush the COLVAR and other PLUMED output files diff --git a/source/source_md/run_md.h b/source/source_md/run_md.h index ed8cdacf27c..47281064a72 100644 --- a/source/source_md/run_md.h +++ b/source/source_md/run_md.h @@ -22,25 +22,10 @@ namespace Run_MD /// their independence directly unit-testable. inline bool is_cadence_step(const int current_step, const int freq) { return freq > 0 && current_step % freq == 0; } -/// Returns true when the MD loop should write a STRU frame at -/// `current_step`. A frame is produced on every md_restartfreq step (so -/// Restart_md.txt can always be resumed from a matching structure) and -/// additionally on output cadence steps when out_stru > 0. Effective output -/// frequency follows out_freq_ion with md_restartfreq fallback, matching -/// md_line(). This predicate exists so the "checkpoint frame tracks -/// Restart_md.txt" invariant stays unit-testable. -inline bool is_frame_write_step( - const int current_step, - const int out_freq_ion, - const int md_restartfreq, - const bool out_stru) +/// Periodic structure output is independent of the MD restart cadence. +inline bool is_structure_output_step(const int current_step, const int out_freq_ion, const bool out_stru) { - const int eff_output_freq = (out_freq_ion > 0) ? out_freq_ion : md_restartfreq; - const bool do_output_step = is_cadence_step(current_step, eff_output_freq); - const bool do_restart_step = is_cadence_step(current_step, md_restartfreq); - const bool want_output_frame = do_output_step && out_stru; - const bool want_checkpoint_frame = do_restart_step; - return want_output_frame || want_checkpoint_frame; + return out_stru && is_cadence_step(current_step, out_freq_ion); } /// Returns true when `current_step` is the final ionic step of the run. diff --git a/source/source_md/unittests/CMakeLists.txt b/source/source_md/unittests/CMakeLists.txt index 1e36657408d..512eeeec5b6 100644 --- a/source/source_md/unittests/CMakeLists.txt +++ b/source/source_md/unittests/CMakeLists.txt @@ -191,7 +191,7 @@ addtest( LIBS parameter psi device SOURCES test_langevin.cpp ../md_base.cpp ../langevin.cpp ${depend_files}) -# Header-only MD loop predicates (is_last_step / is_frame_write_step). Kept in +# Header-only MD loop predicates (is_last_step / is_structure_output_step). Kept in # its own translation unit so this target links without the heavy MD/cell stack. addtest( TARGET MODULE_MD_final_step @@ -219,17 +219,6 @@ if(ENABLE_MPI) set_tests_properties(MODULE_MD_lj_forcefield_mpi_np4 PROPERTIES ENVIRONMENT "OMP_NUM_THREADS=1;MKL_NUM_THREADS=1;I_MPI_PIN=0" TIMEOUT 60) - addtest( - TARGET MODULE_MD_dump_mpi - KEEP_FEATURE_DEFINITIONS __MPI - LIBS parameter psi device - SOURCES test_md_func.cpp ../../source_base/parallel_common.cpp - ../../source_cell/magnetism.cpp ${depend_files}) - add_test( - NAME MODULE_MD_dump_mpi_np4 - COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 ${MPIEXEC_PREFLAGS} - $ ${MPIEXEC_POSTFLAGS} - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) addtest( TARGET MODULE_MD_base_mpi KEEP_FEATURE_DEFINITIONS __MPI @@ -243,7 +232,7 @@ if(ENABLE_MPI) $ ${MPIEXEC_POSTFLAGS} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) set_tests_properties( - MODULE_MD_dump_mpi MODULE_MD_dump_mpi_np4 MODULE_MD_base_mpi + MODULE_MD_base_mpi MODULE_MD_base_mpi_np4 PROPERTIES ENVIRONMENT "OMP_NUM_THREADS=1;MKL_NUM_THREADS=1;I_MPI_PIN=0" TIMEOUT 60) diff --git a/source/source_md/unittests/setcell.h b/source/source_md/unittests/setcell.h index e2dd24b45f0..57fb9888c32 100644 --- a/source/source_md/unittests/setcell.h +++ b/source/source_md/unittests/setcell.h @@ -107,9 +107,6 @@ class Setcell input.search_radius = 8.5 * ModuleBase::ANGSTROM_AU; input.esolver_type = "lj"; - input.mdp.dump_virial = true; - input.mdp.dump_force = true; - input.mdp.dump_vel = true; input.cal_stress = true; input.mdp.md_restart = false; diff --git a/source/source_md/unittests/test_md_base.cpp b/source/source_md/unittests/test_md_base.cpp index c1cca62620f..5ccbacc8513 100644 --- a/source/source_md/unittests/test_md_base.cpp +++ b/source/source_md/unittests/test_md_base.cpp @@ -10,7 +10,10 @@ #include #include +#include #include +#include +#include #include namespace @@ -154,6 +157,32 @@ class MdBoundaryTest : public testing::Test } }; +TEST_F(MdBoundaryTest, PrintMdStepWithoutStress) +{ + const int rank = domain.rank(); + MD_base integrator(parameters, false, true, rank, cell); + integrator.step_ = 2; + integrator.step_rst_ = 3; + const std::string filename = testing::TempDir() + "md_step_without_stress.log"; + std::ofstream output; + if (rank == 0) + { + output.open(filename.c_str()); + EXPECT_TRUE(output.is_open()); + } + integrator.print_md(output, false); + if (rank == 0) + { + output.close(); + std::ifstream input(filename.c_str()); + const std::string log((std::istreambuf_iterator(input)), std::istreambuf_iterator()); + EXPECT_NE(log.find("MD STEP: 6"), std::string::npos); + EXPECT_NE(log.find("Energy (Ry)"), std::string::npos); + EXPECT_EQ(log.find("VIRIAL (kbar)"), std::string::npos); + std::remove(filename.c_str()); + } +} + TEST_F(MdBoundaryTest, MatchesLegacyWrappingThroughMigrationAndRepeatedSync) { const int rank = domain.rank(); diff --git a/source/source_md/unittests/test_md_func.cpp b/source/source_md/unittests/test_md_func.cpp index 7d24cb48f42..c2474e65cca 100644 --- a/source/source_md/unittests/test_md_func.cpp +++ b/source/source_md/unittests/test_md_func.cpp @@ -1,247 +1,3 @@ -#ifdef __MPI -#include "source_base/parallel_cell.h" -#include "source_base/parallel_common.h" -#include "source_base/parallel_global.h" -#include "source_md/md_func.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace -{ -std::string make_dump_directory(const ModuleBase::CommunicationDomain &domain) -{ - std::string directory; - if (domain.rank() == 0) - { - std::string pattern = testing::TempDir() + "abacus-md-dump-XXXXXX"; - char *created = mkdtemp(&pattern[0]); - if (created != nullptr) - { - directory = created; - directory += "/"; - } - } - Parallel_Common::bcast_string(directory); - return directory; -} - -class MdDumpBatchTest : public testing::TestWithParam -{ -}; - -TEST_P(MdDumpBatchTest, OrdersAtomsAcrossRanksAndAppendsCompleteFrames) -{ - const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); - ModuleBase::Matrix3 lattice; - lattice.e11 = 1.0; - lattice.e22 = 1.0; - lattice.e33 = 1.0; - const ModuleBase::Matrix3 inverse = lattice.Inverse(); - const int owner_count = std::min(domain.size(), 3); - std::vector atoms; - const int total_atoms = 13; - for (int index = total_atoms - 1; index >= 0; --index) - { - const int owner = (2 * index + 1) % owner_count; - if (owner != domain.rank()) - { - continue; - } - LocalAtom atom; - atom.type = index < 6 ? 0 : 1; - atom.type_index = index - 6 * atom.type; - const double x = 0.01 * (index + 1); - atom.frac.set(x, 0.5, 0.5); - atom.cart = atom.frac; - atoms.push_back(atom); - } - const std::vector labels = {"A", "B"}; - const std::vector masses(2, 1.0); - const std::vector counts = {6, 7}; - MDCell cell; - cell.initialize_from_owned_atoms( - lattice, inverse, 1.0, 1.0, total_atoms, atoms, labels, masses, counts, 0.0, domain); - const std::string directory = make_dump_directory(domain); - ASSERT_FALSE(directory.empty()); - MD_para parameters; - ModuleBase::matrix virial(3, 3); - MD_func::dump_info(0, directory, cell, parameters, false, virial); - const int batch_bytes = GetParam(); - MD_func::dump_info(1, directory, cell, parameters, false, virial, batch_bytes); - if (domain.rank() == 0) - { - const std::string filename = directory + "MD_dump"; - std::ifstream input(filename.c_str()); - ASSERT_TRUE(input); - std::string line; - int frame_count = 0; - int atom_count = 0; - std::size_t frame_bytes = 0; - std::vector rank_bytes(domain.size(), 0); - std::vector first_frame; - bool reading_atoms = false; - while (std::getline(input, line)) - { - if (line.find("MDSTEP:") == 0) - { - if (frame_count > 0) - { - EXPECT_EQ(atom_count, total_atoms); - } - ++frame_count; - atom_count = 0; - frame_bytes = 0; - std::fill(rank_bytes.begin(), rank_bytes.end(), 0); - reading_atoms = false; - } - else if (line.find("INDEX") == 0) - { - reading_atoms = true; - } - else if (reading_atoms && line.empty()) - { - EXPECT_EQ(atom_count, total_atoms); - if (batch_bytes == 512) - { - // The whole frame exceeds the injected collective count limit. - EXPECT_GT(frame_bytes, 512u); - } - if (batch_bytes == 1024) - { - EXPECT_GT(frame_bytes, 1024u); - if (domain.size() > 2) - { - // Reproduce the aggregate-only overflow: each rank fits on its own. - for (const std::size_t bytes : rank_bytes) - { - EXPECT_LE(bytes, 1024u); - } - } - } - reading_atoms = false; - } - else if (reading_atoms) - { - std::istringstream row(line); - int index = -1; - std::string label; - double x = 0.0; - row >> index >> label >> x; - ASSERT_TRUE(row); - EXPECT_EQ(index, atom_count); - const std::string expected_label = atom_count < 6 ? "A" : "B"; - EXPECT_EQ(label, expected_label); - const double expected_x = 0.01 * (atom_count + 1) / ModuleBase::ANGSTROM_AU; - EXPECT_NEAR(x, expected_x, 1.0e-12); - if (frame_count == 1) - { - first_frame.push_back(line); - } - else - { - ASSERT_LT(atom_count, first_frame.size()); - EXPECT_EQ(line, first_frame[atom_count]); - } - frame_bytes += line.size() + 1; - const int owner = (2 * index + 1) % owner_count; - rank_bytes[owner] += line.size() + 1; - ++atom_count; - } - } - EXPECT_EQ(frame_count, 2); - EXPECT_EQ(atom_count, total_atoms); - input.close(); - std::remove(filename.c_str()); - rmdir(directory.c_str()); - } -} - -// One-row, several-row, and normal budgets must produce identical complete frames. -INSTANTIATE_TEST_SUITE_P(BufferBudgets, MdDumpBatchTest, testing::Values(1, 512, 1024, 1048576)); - -TEST(MdDumpMpiTest, BoundedGatherRejectsOversizedBatchesCollectively) -{ - const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); - const int local_bytes = domain.rank() == 0 ? 17 : 0; - const std::string oversized(local_bytes, 'x'); - EXPECT_THROW(domain.gather_text(oversized, 16), std::length_error); - if (domain.size() > 2) - { - // Every rank fits individually; their aggregate must also be checked on all ranks. - const std::string local(8, 'x'); - EXPECT_THROW(domain.gather_text(local, 16), std::length_error); - } - const std::string empty; - const std::string gathered = domain.gather_text(empty, 1); - EXPECT_TRUE(gathered.empty()); -} - -TEST(MdDumpMpiTest, EmptyRanksCanWriteAnEmptyFrame) -{ - const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); - ModuleBase::Matrix3 lattice; - lattice.e11 = 1.0; - lattice.e22 = 1.0; - lattice.e33 = 1.0; - const ModuleBase::Matrix3 inverse = lattice.Inverse(); - const std::vector atoms; - const std::vector labels(1, "X"); - const std::vector masses(1, 1.0); - const std::vector counts(1, 0); - MDCell cell; - cell.initialize_from_owned_atoms(lattice, inverse, 1.0, 1.0, 0, atoms, labels, masses, counts, 0.0, domain); - const std::string directory = make_dump_directory(domain); - ASSERT_FALSE(directory.empty()); - MD_para parameters; - ModuleBase::matrix virial(3, 3); - MD_func::dump_info(0, directory, cell, parameters, false, virial); - if (domain.rank() == 0) - { - const std::string filename = directory + "MD_dump"; - std::ifstream input(filename.c_str()); - ASSERT_TRUE(input); - const std::string contents((std::istreambuf_iterator(input)), std::istreambuf_iterator()); - EXPECT_NE(contents.find("MDSTEP: 0"), std::string::npos); - EXPECT_NE(contents.find("INDEX"), std::string::npos); - input.close(); - std::remove(filename.c_str()); - rmdir(directory.c_str()); - } -} -} // namespace - -int main(int argc, char **argv) -{ - int process_count = 1; - int thread_count = 1; - int rank = 0; - Parallel_Global::read_pal_param(argc, argv, process_count, thread_count, rank); - // These application communicators are not created by this focused test. - POOL_WORLD = MPI_COMM_NULL; - KP_WORLD = MPI_COMM_NULL; - INT_BGROUP = MPI_COMM_NULL; - BP_WORLD = MPI_COMM_NULL; - GRID_WORLD = MPI_COMM_NULL; - DIAG_WORLD = MPI_COMM_NULL; - ::testing::InitGoogleTest(&argc, argv); - const int local_result = RUN_ALL_TESTS(); - const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); - const int result = domain.max(local_result); - Parallel_Global::finalize_mpi(); - return result; -} - -#endif #ifndef __MPI #include "source_cell/dom_decomp.h" @@ -304,9 +60,6 @@ void initialize_mdcell_from_ucell(MDCell &mdcell, UnitCell &ucell, DomainDecompo * - MD_func::compute_stress * - calculate the contribution of classical kinetic energy of atoms to stress * - * - MD_func::dump_info - * - output MD dump information - * * - MD_func::print_stress * - output stress * @@ -395,172 +148,12 @@ TEST_F(MD_func_test, compute_stress) EXPECT_DOUBLE_EQ(stress(2, 2), 26.215470600896506); } -TEST_F(MD_func_test, dump_info) -{ - std::string pattern = testing::TempDir() + "abacus-md-func-XXXXXX"; - char *directory = mkdtemp(&pattern[0]); - ASSERT_NE(directory, nullptr); - const std::string out_dir = pattern + "/"; - const std::string dump_path = out_dir + "MD_dump"; - MDCell mdcell; - DomainDecomposition decomp; - initialize_mdcell_from_ucell(mdcell, ucell, decomp); - for (LocalAtom &atom : mdcell.owned_atoms()) - { - atom.vel = ModuleBase::Vector3(0.0, 0.0, 0.0); - } - MD_func::dump_info(0, out_dir, mdcell, inp.mdp, inp.cal_stress, virial); - std::ifstream ifs(dump_path.c_str()); - std::string output_str; - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("MDSTEP: 0")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("LATTICE_CONSTANT: 0.529177000000 Angstrom")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("LATTICE_VECTORS")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 10.000000000000 0.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 10.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 10.000000000000")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("VIRIAL (kbar)")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT( - output_str, - testing::HasSubstr("INDEX LABEL POSITION (Angstrom) FORCE (eV/Angstrom) VELOCITY (Angstrom/fs)")); - getline(ifs, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 0 Ar 0.000000000000 0.000000000000 0.000000000000 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 1 Ar 2.751720222021 2.751720222021 0.000000000000 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 2 Ar 2.698802525444 0.000000000000 2.645884828867 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 3 Ar 0.000000000000 2.804637918599 2.645884828867 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - ifs.close(); - - // append - MD_func::dump_info(1, out_dir, mdcell, inp.mdp, inp.cal_stress, virial); - std::ifstream ifs2(dump_path.c_str()); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("MDSTEP: 0")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("LATTICE_CONSTANT: 0.529177000000 Angstrom")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("LATTICE_VECTORS")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 10.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 10.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 10.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("VIRIAL (kbar)")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, - testing::HasSubstr("INDEX LABEL POSITION (Angstrom) FORCE (eV/Angstrom) VELOCITY (Angstrom/fs)")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 0 Ar 0.000000000000 0.000000000000 0.000000000000 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 1 Ar 2.751720222021 2.751720222021 0.000000000000 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 2 Ar 2.698802525444 0.000000000000 2.645884828867 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 3 Ar 0.000000000000 2.804637918599 2.645884828867 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - getline(ifs2, output_str); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("MDSTEP: 1")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("LATTICE_CONSTANT: 0.529177000000 Angstrom")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("LATTICE_VECTORS")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 10.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 10.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 10.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr("VIRIAL (kbar)")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT(output_str, testing::HasSubstr(" 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, - testing::HasSubstr("INDEX LABEL POSITION (Angstrom) FORCE (eV/Angstrom) VELOCITY (Angstrom/fs)")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 0 Ar 0.000000000000 0.000000000000 0.000000000000 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 1 Ar 2.751720222021 2.751720222021 0.000000000000 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 2 Ar 2.698802525444 0.000000000000 2.645884828867 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - getline(ifs2, output_str); - EXPECT_THAT( - output_str, testing::HasSubstr( - " 3 Ar 0.000000000000 2.804637918599 2.645884828867 0.000000000000 " - "0.000000000000 0.000000000000 0.000000000000 0.000000000000 0.000000000000")); - ifs2.close(); - - std::remove(dump_path.c_str()); - rmdir(pattern.c_str()); -} - TEST_F(MD_func_test, print_stress) { const std::string log_path = testing::TempDir() + "abacus-md-print-stress.log"; std::ofstream running_log(log_path.c_str()); + virial(0, 1) = 1.0; + stress(0, 1) = 2.0; MD_func::print_stress(running_log, virial, stress); running_log.close(); @@ -572,6 +165,35 @@ TEST_F(MD_func_test, print_stress) EXPECT_THAT(output_str, testing::HasSubstr("IONIC (KINETIC) PART OF STRESS: 0 kbar")); getline(ifs, output_str); EXPECT_THAT(output_str, testing::HasSubstr("MD PRESSURE (ELECTRONS+IONS) : 0 kbar")); + getline(ifs, output_str); + EXPECT_EQ(output_str, " VIRIAL (kbar):"); + getline(ifs, output_str); + std::istringstream first_virial_row(output_str); + double vxx = 0.0; + double vxy = 0.0; + double vxz = 0.0; + first_virial_row >> vxx >> vxy >> vxz; + ASSERT_FALSE(first_virial_row.fail()); + const double kbar_per_atomic_unit = ModuleBase::HARTREE_SI + / std::pow(ModuleBase::BOHR_RADIUS_SI, 3) * 1.0e-8; + EXPECT_DOUBLE_EQ(vxx, 0.0); + EXPECT_NEAR(vxy, kbar_per_atomic_unit, 1.0e-6); + EXPECT_DOUBLE_EQ(vxz, 0.0); + getline(ifs, output_str); + getline(ifs, output_str); + getline(ifs, output_str); + EXPECT_EQ(output_str, " MD TOTAL STRESS (kbar):"); + getline(ifs, output_str); + std::istringstream first_stress_row(output_str); + double sxx = 0.0; + double sxy = 0.0; + double sxz = 0.0; + first_stress_row >> sxx >> sxy >> sxz; + ASSERT_FALSE(first_stress_row.fail()); + EXPECT_DOUBLE_EQ(sxx, 0.0); + const double expected_sxy = 2.0 * kbar_per_atomic_unit; + EXPECT_NEAR(sxy, expected_sxy, 1.0e-6); + EXPECT_DOUBLE_EQ(sxz, 0.0); /* getline(ifs, output_str); getline(ifs, output_str); diff --git a/source/source_md/unittests/test_run_md_final_step.cpp b/source/source_md/unittests/test_run_md_final_step.cpp index 49c07428bf8..903e8bf452a 100644 --- a/source/source_md/unittests/test_run_md_final_step.cpp +++ b/source/source_md/unittests/test_run_md_final_step.cpp @@ -29,22 +29,18 @@ TEST(RunMdFinalStepTest, IdentifiesTheFinalIonicStep) } /** - * @brief The supplementary final frame must not duplicate a frame that the - * MD loop already wrote on the output or restart cadence. + * @brief Ordinary structure cadence must be independent of restart output. */ -TEST(RunMdFinalStepTest, SupplementaryFinalFrameSkipsStepsAlreadyOnCadence) +TEST(RunMdFinalStepTest, StructureOutputRequiresItsOwnPositiveCadence) { - // Final step off the output cadence: the loop skips it, a frame is needed. - EXPECT_FALSE(Run_MD::is_frame_write_step(3, 2, 0, true)); - // Final step on the output cadence: already written by the loop. - EXPECT_TRUE(Run_MD::is_frame_write_step(4, 2, 0, true)); - // Final step on the restart cadence: already written by the loop. - EXPECT_TRUE(Run_MD::is_frame_write_step(4, 2, 4, true)); - // md_nstep=1: step 0 is final and is inherently a cadence step. - EXPECT_TRUE(Run_MD::is_last_step(0, 1)); - EXPECT_TRUE(Run_MD::is_frame_write_step(0, 2, 0, true)); - // Both frequencies disabled: the loop writes nothing, a final frame is needed. - EXPECT_FALSE(Run_MD::is_frame_write_step(0, 0, 0, true)); + EXPECT_FALSE(Run_MD::is_structure_output_step(0, 0, true)); + EXPECT_FALSE(Run_MD::is_structure_output_step(0, 3, false)); + EXPECT_TRUE(Run_MD::is_structure_output_step(0, 3, true)); + EXPECT_FALSE(Run_MD::is_structure_output_step(2, 3, true)); + EXPECT_TRUE(Run_MD::is_structure_output_step(3, 3, true)); + EXPECT_TRUE(Run_MD::is_cadence_step(0, 5)); + EXPECT_FALSE(Run_MD::is_cadence_step(0, 0)); + EXPECT_FALSE(Run_MD::is_cadence_step(3, 5)); } } // namespace diff --git a/source/source_pw/module_ofdft/of_stress_pw.cpp b/source/source_pw/module_ofdft/of_stress_pw.cpp index f66e2db2b86..651039ba588 100644 --- a/source/source_pw/module_ofdft/of_stress_pw.cpp +++ b/source/source_pw/module_ofdft/of_stress_pw.cpp @@ -115,7 +115,8 @@ void OF_Stress_PW::cal_stress(const int nspin, } const bool ry = false; - const bool screen = PARAM.inp.test_stress; + const auto& input = PARAM.inp; + const bool screen = input.test_stress && input.calculation != "md"; ModuleIO::print_stress("TOTAL-STRESS", sigmatot, true, ry, GlobalV::ofs_running); if (screen) diff --git a/source/source_pw/module_pwdft/stress_pw.cpp b/source/source_pw/module_pwdft/stress_pw.cpp index 350c8f89087..919d5956b85 100644 --- a/source/source_pw/module_pwdft/stress_pw.cpp +++ b/source/source_pw/module_pwdft/stress_pw.cpp @@ -166,7 +166,8 @@ void Stress_PW::cal_stress(const int nspin, } const bool ry = false; - const bool screen = PARAM.inp.test_stress; + const auto& input = PARAM.inp; + const bool screen = input.test_stress && input.calculation != "md"; const bool screen_normal = true; ModuleIO::print_stress("TOTAL-STRESS", sigmatot, screen_normal, ry, GlobalV::ofs_running); diff --git a/source/source_pw/module_stodft/sto_stress_pw.cpp b/source/source_pw/module_stodft/sto_stress_pw.cpp index 100f6eed4fe..2e8660e94a6 100644 --- a/source/source_pw/module_stodft/sto_stress_pw.cpp +++ b/source/source_pw/module_stodft/sto_stress_pw.cpp @@ -84,7 +84,8 @@ void Sto_Stress_PW::cal_stress(const int nspin, } bool ry = false; - const bool screen = PARAM.inp.test_stress; + const auto& input = PARAM.inp; + const bool screen = input.test_stress && input.calculation != "md"; ModuleIO::print_stress("TOTAL-STRESS", sigmatot, true, ry, GlobalV::ofs_running); if (screen) diff --git a/source/source_relax/relax_driver.cpp b/source/source_relax/relax_driver.cpp index 09d76f440b9..62833142fb7 100644 --- a/source/source_relax/relax_driver.cpp +++ b/source/source_relax/relax_driver.cpp @@ -9,6 +9,7 @@ #include "source_base/module_out/read_exit_file.h" #include "source_io/module_json/output_info.h" #include "source_io/module_output/output_log.h" +#include "source_io/module_output/frame_append.h" #include "source_io/module_output/print_info.h" #include "source_io/module_output/write_notice.h" #include "source_io/module_parameter/parameter.h" @@ -279,9 +280,8 @@ void Relax_Driver::stru_out( // numbered STRU{istep+1} files. Mode 0 only writes STRU_NOW, which is // already overwritten each step above. const bool append_stru = (inp.out_app_flag == 1) && (inp.out_stru == 1) && (istep > 0); - const std::string step_file = - (inp.out_app_flag == 1) ? out_dir_ + (inp.out_stru == 1 ? "STRU" : "STRU.cif") - : out_dir_ + "STRU" + std::to_string(istep + 1) + (inp.out_stru == 1 ? "" : ".cif"); + const std::string stru_filename = ModuleIO::stru_frame_filename(out_dir_, inp.out_app_flag, istep); + const std::string step_file = stru_filename + (inp.out_stru == 1 ? "" : ".cif"); relax_stru_io::write_stru( ucell, inp, step_file, header, force, need_orb, deepks_setorb_, my_rank_, inp.cal_force, append_stru); if (my_rank_ == 0) diff --git a/source/source_relax/unittests/CMakeLists.txt b/source/source_relax/unittests/CMakeLists.txt index 895c5a07071..155b15a270a 100644 --- a/source/source_relax/unittests/CMakeLists.txt +++ b/source/source_relax/unittests/CMakeLists.txt @@ -73,6 +73,7 @@ addtest( ../../source_base/intarray.cpp ../../source_base/tool_title.cpp ../../source_base/global_function.cpp + ../../source_base/parallel_cell.cpp ../../source_base/matrix.cpp ../../source_base/complexarray.cpp ../../source_base/realarray.cpp diff --git a/tests/04_FF/101_NEP_HfO2/INPUT b/tests/04_FF/101_NEP_HfO2/INPUT index 391b4ae66c2..27d25b602a1 100644 --- a/tests/04_FF/101_NEP_HfO2/INPUT +++ b/tests/04_FF/101_NEP_HfO2/INPUT @@ -15,7 +15,8 @@ md_type npt md_dt 1 md_tfirst 300 md_thermostat nhc -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_seed 1 init_vel 1 diff --git a/tests/04_FF/50_DP_Al/INPUT b/tests/04_FF/50_DP_Al/INPUT index f982962b564..c4fb8f60f4b 100644 --- a/tests/04_FF/50_DP_Al/INPUT +++ b/tests/04_FF/50_DP_Al/INPUT @@ -14,7 +14,8 @@ md_nstep 4 md_type msst md_dt 1 md_tfirst 200 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_restartfreq 1 msst_qmass 200 diff --git a/tests/04_FF/CMakeLists.txt b/tests/04_FF/CMakeLists.txt index 381a3b05999..3cc933cc8c3 100644 --- a/tests/04_FF/CMakeLists.txt +++ b/tests/04_FF/CMakeLists.txt @@ -13,8 +13,8 @@ else() WORKING_DIRECTORY ${ABACUS_TEST_DIR}/04_FF) endif() -# Autotest checks numerical results but cannot assert the exact frame inventory -# for independent output and restart cadences. +# Autotest checks numerical results; this existing driver also asserts the +# structure-file inventory for independent output and restart cadences. find_program(ABACUS_CADENCE_PYTHON python3) if(ABACUS_CADENCE_PYTHON AND NOT ENABLE_ASAN) add_test( diff --git a/tests/05_rtTDDFT/06_NO_dir_TDDFT/INPUT b/tests/05_rtTDDFT/06_NO_dir_TDDFT/INPUT index 01e6af7a49a..d40a9eb0f6e 100644 --- a/tests/05_rtTDDFT/06_NO_dir_TDDFT/INPUT +++ b/tests/05_rtTDDFT/06_NO_dir_TDDFT/INPUT @@ -32,7 +32,8 @@ estep_per_md 2 md_dt 0.05 td_dt 0.025 md_tfirst -1 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_restartfreq 1 init_vel 1 diff --git a/tests/05_rtTDDFT/10_NO_MD_boundary_shift/INPUT b/tests/05_rtTDDFT/10_NO_MD_boundary_shift/INPUT index 6ba92a2a4e5..e276cdc0c0b 100644 --- a/tests/05_rtTDDFT/10_NO_MD_boundary_shift/INPUT +++ b/tests/05_rtTDDFT/10_NO_MD_boundary_shift/INPUT @@ -24,7 +24,8 @@ td_dt 0.05 init_vel 1 # Keep the supplied sub-roundoff velocity rather than rescaling to zero. md_tfirst -1 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_restartfreq 1 # Keep the early-time fields weak to preserve the boundary regression. diff --git a/tests/05_rtTDDFT/18_NO_hyb_TDDFT/INPUT b/tests/05_rtTDDFT/18_NO_hyb_TDDFT/INPUT index eef00dd0998..9256b3120ec 100644 --- a/tests/05_rtTDDFT/18_NO_hyb_TDDFT/INPUT +++ b/tests/05_rtTDDFT/18_NO_hyb_TDDFT/INPUT @@ -48,5 +48,6 @@ mixing_gg0 0.0 md_dt 0.05 init_vel 1 symmetry -1 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 out_vecpot 1 diff --git a/tests/07_OFDFT/25_OF_MD_LDA/INPUT b/tests/07_OFDFT/25_OF_MD_LDA/INPUT index 89c049d33ba..af595f1b944 100644 --- a/tests/07_OFDFT/25_OF_MD_LDA/INPUT +++ b/tests/07_OFDFT/25_OF_MD_LDA/INPUT @@ -27,7 +27,8 @@ md_type nvt md_nstep 3 md_dt 0.25 md_tfirst 58022.52706 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_tfreq 1.08 md_tchain 1 nbspline 10 # be sure fft dimension is odd diff --git a/tests/07_OFDFT/26_OF_MD_LibxcPBE/INPUT b/tests/07_OFDFT/26_OF_MD_LibxcPBE/INPUT index aa24f0a20db..f642c4e4d5d 100644 --- a/tests/07_OFDFT/26_OF_MD_LibxcPBE/INPUT +++ b/tests/07_OFDFT/26_OF_MD_LibxcPBE/INPUT @@ -27,7 +27,8 @@ md_type nvt md_nstep 3 md_dt 0.25 md_tfirst 58022.52706 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_tfreq 1.08 md_tchain 1 nbspline 10 # be sure fft dimension is odd diff --git a/tests/07_OFDFT/30_TDOFDFT_Al/INPUT b/tests/07_OFDFT/30_TDOFDFT_Al/INPUT index aef827fc7e8..8fa529f640e 100644 --- a/tests/07_OFDFT/30_TDOFDFT_Al/INPUT +++ b/tests/07_OFDFT/30_TDOFDFT_Al/INPUT @@ -30,7 +30,8 @@ md_type nve md_nstep 51 # initial state plus 50 advances: final time = 0.05 fs md_dt 0.001 # fs; the electronic RK4 uses this step without subcycling md_tfirst 58022.52706 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_tfreq 1.08 md_tchain 1 nbspline 10 # be sure fft dimension is odd diff --git a/tests/07_OFDFT/31_TDOFDFT_Al_CD/INPUT b/tests/07_OFDFT/31_TDOFDFT_Al_CD/INPUT index 885e0f80072..537e1f332ae 100644 --- a/tests/07_OFDFT/31_TDOFDFT_Al_CD/INPUT +++ b/tests/07_OFDFT/31_TDOFDFT_Al_CD/INPUT @@ -31,7 +31,8 @@ md_type nve md_nstep 3 md_dt 0.25 md_tfirst 58022.52706 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_tfreq 1.08 md_tchain 1 nbspline 10 # be sure fft dimension is odd diff --git a/tests/07_OFDFT/32_TDOFDFT_Al_mCD/INPUT b/tests/07_OFDFT/32_TDOFDFT_Al_mCD/INPUT index c6fccd263fd..dee361de7e4 100644 --- a/tests/07_OFDFT/32_TDOFDFT_Al_mCD/INPUT +++ b/tests/07_OFDFT/32_TDOFDFT_Al_mCD/INPUT @@ -31,7 +31,8 @@ md_type nve md_nstep 3 md_dt 0.25 md_tfirst 58022.52706 -md_dumpfreq 1 +out_freq_ion 1 +out_app_flag 2 md_tfreq 1.08 md_tchain 1 nbspline 10 # be sure fft dimension is odd diff --git a/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT b/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT index 52c1da78378..19765d2c93a 100644 --- a/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT +++ b/tests/08_RI/rt_tddft_hse_current_spin2_up/INPUT @@ -28,7 +28,6 @@ symmetry -1 suffix autotest fixed_atoms 1 cal_force 0 -dump_force 0 scf_thr 1e-6 scf_nmax 150 md_restartfreq 1 diff --git a/tests/08_RI/rt_tddft_hse_spin2/INPUT b/tests/08_RI/rt_tddft_hse_spin2/INPUT index aef889cceef..11fc35e8c9b 100644 --- a/tests/08_RI/rt_tddft_hse_spin2/INPUT +++ b/tests/08_RI/rt_tddft_hse_spin2/INPUT @@ -28,7 +28,6 @@ symmetry -1 suffix autotest fixed_atoms 1 cal_force 0 -dump_force 0 scf_thr 1e-7 scf_nmax 100 md_restartfreq 1 diff --git a/tests/integrate/validation_tools/check_md_output_cadence.py b/tests/integrate/validation_tools/check_md_output_cadence.py index 9e5b0ecee20..1cde81fb619 100644 --- a/tests/integrate/validation_tools/check_md_output_cadence.py +++ b/tests/integrate/validation_tools/check_md_output_cadence.py @@ -1,4 +1,4 @@ -"""Check numbered MD structure frames against unequal output cadences.""" +"""Check MD structure output and restart cadences independently.""" import argparse from pathlib import Path @@ -7,12 +7,16 @@ import tempfile -def run_case(executable, fixture, out_stru, expected): +def run_case(executable, fixture, out_stru, out_freq_ion, out_app_flag, expected, thermo_freq=1): with tempfile.TemporaryDirectory(prefix="abacus-md-cadence-") as scratch: work = Path(scratch) shutil.copyfile(fixture / "STRU", work / "STRU") input_text = (fixture / "INPUT").read_text() input_text = input_text.replace("out_stru 0", "out_stru " + str(out_stru)) + input_text = input_text.replace("out_freq_ion 2", "out_freq_ion " + str(out_freq_ion)) + input_text = input_text.replace("out_app_flag 0", "out_app_flag " + str(out_app_flag)) + input_text += "\ncal_stress 1\n" + input_text += "out_thermo_freq {}\n".format(thermo_freq) (work / "INPUT").write_text(input_text) result = subprocess.run( [executable], cwd=str(work), stdout=subprocess.PIPE, @@ -22,10 +26,22 @@ def run_case(executable, fixture, out_stru, expected): raise AssertionError("ABACUS failed:\n" + result.stdout) output = work / "OUT.cadence" - frames = {path.name for path in output.glob("STRU[0-9]*")} + if (output / "MD_dump").exists(): + raise AssertionError("Removed MD_dump was written") + running_log = (output / "running_md.log").read_text() + expected_thermo = 0 if thermo_freq == 0 else len(range(0, 5, thermo_freq)) + if running_log.count("VIRIAL (kbar):") != expected_thermo: + raise AssertionError("Unexpected virial output cadence") + if running_log.count("MD TOTAL STRESS (kbar):") != expected_thermo: + raise AssertionError("Unexpected total stress output cadence") + if "#TOTAL-STRESS" in running_log or "#TOTAL-FORCE" in running_log: + raise AssertionError("Solver wrote per-step force or stress outside MD output") + structure_dir = output / "STRUC" if out_app_flag == 2 else output + frames = {path.name for path in structure_dir.glob("STRU*")} + frames.discard("STRU_restart") if frames != expected: - raise AssertionError("out_stru={} produced {}, expected {}\n{}".format( - out_stru, sorted(frames), sorted(expected), result.stdout)) + raise AssertionError("out_stru={}, out_freq_ion={}, out_app_flag={} produced {}, expected {}\n{}".format( + out_stru, out_freq_ion, out_app_flag, sorted(frames), sorted(expected), result.stdout)) restart = output / "Restart_md.txt" if not restart.is_file() or restart.stat().st_size == 0: raise AssertionError("Missing MD restart for out_stru={}".format(out_stru)) @@ -33,6 +49,32 @@ def run_case(executable, fixture, out_stru, expected): if restart_step != "3": raise AssertionError("out_stru={} restart step is {}, expected 3".format( out_stru, restart_step)) + checkpoint = output / "STRU_restart" + if not checkpoint.is_file(): + raise AssertionError("Missing STRU_restart") + checkpoint_text = checkpoint.read_text() + if "# MD step 4" not in checkpoint_text or " v " not in checkpoint_text or " f " in checkpoint_text: + raise AssertionError("Restart structure lacks matching step or velocities") + for filename in expected: + frame_text = (structure_dir / filename).read_text() + if "Cartesian_angstrom" not in frame_text or " v " not in frame_text or " f " not in frame_text: + raise AssertionError("Ordinary structure lacks coordinates, velocities or forces: " + filename) + + if out_stru == 0: + restart_input = input_text.replace("md_nstep 5", "md_nstep 7") + restart_input = restart_input.replace("init_vel 0", "init_vel 1") + restart_input += "\nmd_restart 1\n" + (work / "INPUT").write_text(restart_input) + continuation = subprocess.run( + [executable], cwd=str(work), stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, universal_newlines=True, timeout=120, + check=False) + if continuation.returncode: + raise AssertionError("MD restart failed:\n" + continuation.stdout) + if restart.read_text().splitlines()[0] != "6": + raise AssertionError("MD continuation did not reach restart step 6") + if "# MD step 7" not in checkpoint.read_text(): + raise AssertionError("MD continuation did not update STRU_restart") def main(): @@ -40,9 +82,15 @@ def main(): parser.add_argument("executable") parser.add_argument("fixture", type=Path) args = parser.parse_args() - run_case(args.executable, args.fixture, 0, {"STRU1", "STRU4"}) - run_case(args.executable, args.fixture, 1, - {"STRU1", "STRU3", "STRU4", "STRU5"}) + run_case(args.executable, args.fixture, 0, 2, 0, set()) + run_case(args.executable, args.fixture, 1, 0, 0, {"STRU_FINAL"}) + run_case(args.executable, args.fixture, 1, 0, 1, {"STRU_FINAL"}) + run_case(args.executable, args.fixture, 1, 0, 2, {"STRU_FINAL"}) + run_case(args.executable, args.fixture, 1, 2, 0, {"STRU", "STRU_FINAL"}) + run_case(args.executable, args.fixture, 1, 2, 1, {"STRU", "STRU_FINAL"}) + run_case(args.executable, args.fixture, 1, 2, 2, {"STRU1", "STRU3", "STRU5", "STRU_FINAL"}) + run_case(args.executable, args.fixture, 1, 2, 1, {"STRU", "STRU_FINAL"}, thermo_freq=3) + run_case(args.executable, args.fixture, 1, 2, 1, {"STRU", "STRU_FINAL"}, thermo_freq=0) if __name__ == "__main__": diff --git a/tests/integrate/validation_tools/props_basic.sh b/tests/integrate/validation_tools/props_basic.sh index 25529af50cc..c38a5428b90 100644 --- a/tests/integrate/validation_tools/props_basic.sh +++ b/tests/integrate/validation_tools/props_basic.sh @@ -52,11 +52,16 @@ run_basic_props() { echo "[ERROR] Invalid atom count for force collection: $natom" >&2 return 1 fi - # MDCell forces are in MD_dump; older MD and non-MD logs may still - # contain a TOTAL-FORCE table. Both paths require a complete last frame. - if [ "$calculation" = "md" ] && [ -f OUT.autotest/MD_dump ]; then - force_source=OUT.autotest/MD_dump - force_format=dump + # The final MD structure contains the evaluated force on every atom. + if [ "$calculation" = "md" ]; then + force_source=$(awk '/Write file: .*STRU_FINAL$/ {sub(/^.*Write file: /, ""); path=$0} END {print path}' "$running_path") + if [ -z "$force_source" ] || [ ! -f "$force_source" ]; then + force_source=OUT.autotest/STRU_FINAL + if [ ! -f "$force_source" ] && [ -f OUT.autotest/STRUC/STRU_FINAL ]; then + force_source=OUT.autotest/STRUC/STRU_FINAL + fi + fi + force_format=stru else force_source=$running_path force_format=log @@ -73,16 +78,25 @@ run_basic_props() { delete force_y delete force_z } - format == "dump" && /^MDSTEP:/ { reset_frame(); next } - format == "dump" && /^INDEX[[:space:]]+LABEL[[:space:]]+POSITION.*FORCE/ { - in_atoms = 1 - next - } + format == "stru" && /^ATOMIC_POSITIONS/ { reset_frame(); in_atoms = 1; next } format == "log" && /TOTAL-FORCE/ { reset_frame(); in_atoms = 1; next } - in_atoms && ((format == "dump" && $1 ~ /^[0-9]+$/ && NF >= 8) || (format == "log" && NF == 4 && $1 != "Atoms")) { - x = format == "dump" ? $6 : $2 - y = format == "dump" ? $7 : $3 - z = format == "dump" ? $8 : $4 + in_atoms && ((format == "stru" && NF >= 3 && number($1) && number($2) && number($3)) || (format == "log" && NF == 4 && $1 != "Atoms")) { + x = $2 + y = $3 + z = $4 + if (format == "stru") { + found_force = 0 + for (field = 4; field <= NF; ++field) { + if ($field == "f") { + found_force = 1 + x = $(field + 1) + y = $(field + 2) + z = $(field + 3) + break + } + } + if (!found_force) invalid = 1 + } if (!number(x) || !number(y) || !number(z)) invalid = 1 atom_count++ force_x[atom_count] = x @@ -110,7 +124,45 @@ run_basic_props() { # stress information #------------------------------- if ! test -z "$has_stress" && [ $has_stress == 1 ]; then - grep -A6 "TOTAL-STRESS" $running_path | awk 'NF==3' | tail -3 >stress.txt + if [ "$calculation" = "md" ]; then + # The MD virial is the electronic stress after external pressure is + # subtracted. Reconstruct the solver's former TOTAL-STRESS value so + # existing reference data continue to compare the same quantity. + press1=$(get_input_key_value press1 INPUT) + press2=$(get_input_key_value press2 INPUT) + press3=$(get_input_key_value press3 INPUT) + if [ "$esolver_type" = "ofdft" ] || [ "$esolver_type" = "sdft" ]; then + # These solvers return their electronic stress without subtracting + # the requested external pressure. + press1=0 + press2=0 + press3=0 + fi + if ! awk -v p1="$press1" -v p2="$press2" -v p3="$press3" ' + /VIRIAL \(kbar\):/ { rows = 3; count = 0; next } + rows > 0 { + if (NF != 3) exit 1 + count++ + value[count] = $1 " " $2 " " $3 + rows-- + } + END { + if (count != 3 || rows != 0) exit 1 + split(value[1], first) + split(value[2], second) + split(value[3], third) + print first[1] + p1, first[2], first[3] + print second[1], second[2] + p2, second[3] + print third[1], third[2], third[3] + p3 + } + ' "$running_path" >stress.txt; then + echo "[ERROR] Failed to extract the MD virial from $running_path" >&2 + rm -f stress.txt + return 1 + fi + else + grep -A6 "TOTAL-STRESS" "$running_path" | awk 'NF==3' | tail -3 >stress.txt + fi total_stress=$(sum_file stress.txt) rm stress.txt echo "totalstressref $total_stress" >>$props_result_file diff --git a/tests/integrate/validation_tools/test_props_basic.py b/tests/integrate/validation_tools/test_props_basic.py index 4014869afe3..3971ca713fb 100644 --- a/tests/integrate/validation_tools/test_props_basic.py +++ b/tests/integrate/validation_tools/test_props_basic.py @@ -13,39 +13,83 @@ class ForceCollectionTest(unittest.TestCase): - def run_collector(self, calculation, atom_count, dump=None, log_force=""): + def run_collector(self, calculation, atom_count, stru=None, log_force="", mode2=False, + stale_stru=None, log_stress="", has_force=1, has_stress=0, + input_text="INPUT_PARAMETERS\n"): with tempfile.TemporaryDirectory(prefix="abacus-force-collector-") as scratch: case = Path(scratch) (case / "OUT.autotest").mkdir() - if dump is not None: - (case / "OUT.autotest/MD_dump").write_text(dump, encoding="utf-8") - (case / "running.log").write_text("ETOT_ 1.0\n" + log_force, encoding="utf-8") + if stru is not None: + structure_dir = case / "OUT.autotest/STRUC" if mode2 else case / "OUT.autotest" + structure_dir.mkdir(exist_ok=True) + (structure_dir / "STRU_FINAL").write_text(stru, encoding="utf-8") + if stale_stru is not None: + (case / "OUT.autotest/STRU_FINAL").write_text(stale_stru, encoding="utf-8") + (case / "running.log").write_text("ETOT_ 1.0\n" + log_force + log_stress, encoding="utf-8") + (case / "INPUT").write_text(input_text, encoding="utf-8") command = ( 'source "$1"; source "$2"; calculation="$3"; natom="$4"; ' - 'is_lr=0; has_force=1; nspin=1; running_path=running.log; ' + 'is_lr=0; has_force="$5"; has_stress="$6"; esolver_type="$7"; ' + 'nspin=1; running_path=running.log; ' 'props_result_file=result.out; run_basic_props' ) result = subprocess.run( ["bash", "-c", command, "force-test", str(TOOLS / "props_common.sh"), - str(TOOLS / "props_basic.sh"), calculation, str(atom_count)], + str(TOOLS / "props_basic.sh"), calculation, str(atom_count), + str(has_force), str(has_stress), + "ofdft" if "esolver_type ofdft" in input_text else ""], cwd=case, capture_output=True, text=True, check=False, ) output = (case / "result.out").read_text(encoding="utf-8") if (case / "result.out").exists() else "" return result, output - def test_last_dump_frame_requires_all_force_rows(self): + def test_md_stress_uses_virial_and_restores_external_pressure(self): + virial = " VIRIAL (kbar):\n 1 2 3\n 4 5 6\n 7 8 9\n" + result, output = self.run_collector( + "md", 2, log_stress=virial, has_force=0, has_stress=1, + input_text="INPUT_PARAMETERS\npress1 10\npress2 20\npress3 30\n") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("totalstressref 105.000000", output) + + result, output = self.run_collector( + "md", 2, log_stress=virial, has_force=0, has_stress=1, + input_text="INPUT_PARAMETERS\nesolver_type ofdft\npress1 10\npress2 20\npress3 30\n") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("totalstressref 45.000000", output) + + result, output = self.run_collector("md", 2, has_force=0, has_stress=1) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("totalstressref", output) + + def test_non_md_stress_still_uses_total_stress(self): + table = "#TOTAL-STRESS (kbar)#\nStress_x Stress_y Stress_z\n1 2 3\n4 5 6\n7 8 9\n" + result, output = self.run_collector("scf", 2, log_stress=table, has_force=0, has_stress=1) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("totalstressref 45.000000", output) + + def test_final_stru_requires_all_force_rows(self): good = ( - "MDSTEP: 0\nINDEX LABEL POSITION (Angstrom) FORCE (eV/Angstrom)\n" - "0 H 0 0 0 1 2 3\n1 H 0 0 0 4 5 6\n" + "ATOMIC_POSITIONS\nCartesian_angstrom\n\nH\n0.0\n2\n" + "0 0 0 m 1 1 1 v 0 0 0 f 1 2 3\n" + "0 0 0 m 1 1 1 v 0 0 0 f 4 5 6\n" ) result, output = self.run_collector("md", 2, good) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("totalforceref 21.000000", output) + result, output = self.run_collector("md", 2, good, mode2=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("totalforceref 21.000000", output) + announcement = "Write file: OUT.autotest/STRUC/STRU_FINAL\n" + stale = good.replace("f 1 2 3", "f 9 9 9") + result, output = self.run_collector("md", 2, good, log_force=announcement, + mode2=True, stale_stru=stale) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("totalforceref 21.000000", output) - for dump in (good + "MDSTEP: 1\n", good.split("1 H")[0], - "MDSTEP: 0\nINDEX LABEL POSITION (Angstrom)\n0 H 0 0 0\n"): - with self.subTest(dump=dump): - result, output = self.run_collector("md", 2, dump) + for stru in (good.split("0 0 0 m")[0], good.rsplit("0 0 0 m", 1)[0], + good.replace("f 4 5 6", "")): + with self.subTest(stru=stru): + result, output = self.run_collector("md", 2, stru) self.assertNotEqual(result.returncode, 0) self.assertNotIn("totalforceref", output) diff --git a/tools/02_postprocessing/tdofdft-tools/get_kinetic.py b/tools/02_postprocessing/tdofdft-tools/get_kinetic.py index 23fa5a265da..8c5eeea0b77 100644 --- a/tools/02_postprocessing/tdofdft-tools/get_kinetic.py +++ b/tools/02_postprocessing/tdofdft-tools/get_kinetic.py @@ -1,79 +1,75 @@ #!/usr/bin/env python3 -""" -Extract proton kinetic energy from TDOFDFT MD_dump output. - -Usage: - python3 get_kinetic.py [md_dump_file] [output_file] - -Default: - md_dump_file = OUT.autotest/MD_dump - output_file = kinetic.txt +"""Extract the last proton's kinetic energy from MD STRU frames. -Output format: - time(fs) kinetic_energy(eV) +Usage: python3 get_kinetic.py [stru_file] [output_file] +Default input: OUT.autotest/STRU (out_stru=1, out_freq_ion=1, out_app_flag=1). """ import sys -import os +from pathlib import Path -# ========== Parameters ========== -md_dump_file = "OUT.autotest/MD_dump" -output_file = "kinetic.txt" -md_dt = 0.0005 # fs, must match md_dt in INPUT -m_H = 1.008 # amu, proton mass -# ================================ -if len(sys.argv) >= 2: - md_dump_file = sys.argv[1] -if len(sys.argv) >= 3: - output_file = sys.argv[2] +stru_file = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("OUT.autotest/STRU") +output_file = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("kinetic.txt") +md_dt = 0.0005 # fs; must match md_dt in INPUT +m_H = 1.008 # amu -# Conversion factor: E_k(eV) = 0.5 * m(amu) * v(Ang/fs)^2 * factor +# Match the constants used by ABACUS to convert STRU atomic-unit velocities. +angstrom_au = 1.8897270 +au_to_fs = 2.418884326505e-2 +au_velocity_to_ang_fs = 1.0 / angstrom_au / au_to_fs amu_to_kg = 1.66053906660e-27 -ang_fs_to_m_s = 1e5 # 1 Ang/fs = 10^5 m/s +ang_fs_to_m_s = 1e5 eV_to_J = 1.602176634e-19 -factor = amu_to_kg * ang_fs_to_m_s**2 / eV_to_J # ≈ 103.6427 +kinetic_factor = amu_to_kg * ang_fs_to_m_s**2 / eV_to_J -if not os.path.exists(md_dump_file): - print(f"Error: {md_dump_file} not found!") - sys.exit(1) -with open(md_dump_file, "r") as f: - lines = f.readlines() +def proton_velocity(frame): + data = [line.split("#", 1)[0].strip() for line in frame] + data = [line for line in data if line] + position_index = data.index("ATOMIC_POSITIONS") + 2 + last_velocity = None + while position_index < len(data): + label = data[position_index] + count = int(data[position_index + 2]) + position_index += 3 + for atom_line in data[position_index:position_index + count]: + fields = atom_line.split() + if label == "H" and "v" in fields: + velocity_index = fields.index("v") + last_velocity = tuple(float(value) for value in fields[velocity_index + 1:velocity_index + 4]) + position_index += count + if last_velocity is None: + raise ValueError("Frame has no H atom velocity") + return last_velocity -kinetic_data = [] -i = 0 -while i < len(lines): - line = lines[i].strip() - if line.startswith("MDSTEP:"): - step = int(line.split(":")[1].strip()) - time_fs = step * md_dt - i += 1 - # Skip lattice + virial + header lines to reach atom data - while i < len(lines) and "INDEX" not in lines[i] and "MDSTEP:" not in lines[i]: - i += 1 - i += 1 # skip INDEX header +if not stru_file.is_file(): + raise SystemExit(f"Error: {stru_file} not found") - # Atom data: INDEX LABEL x y z Fx Fy Fz Vx Vy Vz - # Find the last H atom (proton) - last_vx = last_vy = last_vz = 0.0 - while i < len(lines) and not lines[i].strip().startswith("MDSTEP:"): - parts = lines[i].split() - if len(parts) >= 11 and parts[1] == "H": - last_vx = float(parts[8]) - last_vy = float(parts[9]) - last_vz = float(parts[10]) - i += 1 +frames = [] +step = None +frame = [] +for line in stru_file.read_text().splitlines(): + if line.startswith("# MD step "): + if step is not None: + frames.append((step, frame)) + step = int(line.split()[3]) + frame = [] + elif step is not None: + frame.append(line) +if step is not None: + frames.append((step, frame)) - v_sq = last_vx**2 + last_vy**2 + last_vz**2 - ek_eV = 0.5 * m_H * v_sq * factor - kinetic_data.append((time_fs, ek_eV)) - continue - i += 1 +if not frames: + raise ValueError(f"No MD frames found in {stru_file}") -with open(output_file, "w") as f: - for t, ek in kinetic_data: - f.write(f"{t:.4f}\t{ek:.10f}\n") +with output_file.open("w") as output: + for step, frame in frames: + velocity = proton_velocity(frame) + velocity_squared = sum((value * au_velocity_to_ang_fs) ** 2 for value in velocity) + time_fs = (step - 1) * md_dt + energy = 0.5 * m_H * velocity_squared * kinetic_factor + output.write(f"{time_fs:.4f}\t{energy:.10f}\n") -print(f"Done! {len(kinetic_data)} steps written to {output_file}") +print(f"Done! {len(frames)} steps written to {output_file}")