2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2013,2014, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
46 #include "../../external/tng_io/include/tng_io.h"
49 #include "gromacs/legacyheaders/copyrite.h"
50 #include "gromacs/legacyheaders/types/ifunc.h"
52 #include "gromacs/fileio/gmxfio.h"
53 #include "gromacs/math/units.h"
54 #include "gromacs/math/utilities.h"
55 #include "gromacs/topology/topology.h"
56 #include "gromacs/utility/basenetwork.h"
57 #include "gromacs/utility/common.h"
58 #include "gromacs/utility/fatalerror.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/programcontext.h"
62 static const char *modeToVerb(char mode)
76 gmx_fatal(FARGS, "Invalid file opening mode %c", mode);
81 void gmx_tng_open(const char *filename,
83 tng_trajectory_t *tng)
86 /* First check whether we have to make a backup,
87 * only for writing, not for read or append.
92 /* only make backups for normal gromacs */
93 make_backup(filename);
97 /* tng must not be pointing at already allocated memory.
98 * Memory will be allocated by tng_util_trajectory_open() and must
99 * later on be freed by tng_util_trajectory_close(). */
100 if (TNG_SUCCESS != tng_util_trajectory_open(filename, mode, tng))
102 /* TNG does return more than one degree of error, but there is
103 no use case for GROMACS handling the non-fatal errors
106 "%s while opening %s for %s",
107 gmx_strerror("file"),
112 if (mode == 'w' || mode == 'a')
114 /* FIXME in TNG: When adding data to the header, subsequent blocks might get
115 * overwritten. This could be solved by moving the first trajectory
116 * frame set(s) to the end of the file. Could that cause other problems,
117 * e.g. when continuing a simulation? */
119 gmx_gethostname(hostname, 256);
122 tng_first_computer_name_set(*tng, hostname);
124 /* TODO: This should be implemented when the above fixme is done (adding data to
128 // tng_last_computer_name_set(*tng, hostname);
131 char programInfo[256];
132 const char *precisionString = "";
134 precisionString = " (double precision)";
136 sprintf(programInfo, "%.100s, %.128s%.24s",
137 gmx::getProgramContext().displayName(),
138 GromacsVersion(), precisionString);
141 tng_first_program_name_set(*tng, programInfo);
143 /* TODO: This should be implemented when the above fixme is done (adding data to
147 // tng_last_program_name_set(*tng, programInfo);
152 getlogin_r(username, 256);
155 tng_first_user_name_set(*tng, username);
157 /* TODO: This should be implemented when the above fixme is done (adding data to
161 // tng_last_user_name_set(*tng, username);
166 gmx_file("GROMACS was compiled without TNG support, cannot handle this file type");
167 GMX_UNUSED_VALUE(filename);
168 GMX_UNUSED_VALUE(mode);
169 GMX_UNUSED_VALUE(tng);
173 void gmx_tng_close(tng_trajectory_t *tng)
175 /* We have to check that tng is set because
176 * tng_util_trajectory_close wants to return a NULL in it, and
177 * gives a fatal error if it is NULL. */
181 tng_util_trajectory_close(tng);
184 GMX_UNUSED_VALUE(tng);
189 static void addTngMoleculeFromTopology(tng_trajectory_t tng,
190 const char *moleculeName,
191 const t_atoms *atoms,
192 gmx_int64_t numMolecules,
193 tng_molecule_t *tngMol)
195 if (tng_molecule_add(tng, moleculeName, tngMol) != TNG_SUCCESS)
197 gmx_file("Cannot add molecule to TNG molecular system.");
200 /* FIXME: The TNG atoms should contain mass and atomB info (for free
201 * energy calculations), i.e. in when it's available in TNG (2.0). */
202 for (int atomIndex = 0; atomIndex < atoms->nr; atomIndex++)
204 const t_atom *at = &atoms->atom[atomIndex];
205 /* FIXME: Currently the TNG API can only add atoms belonging to a
206 * residue and chain. Wait for TNG 2.0*/
209 const t_resinfo *resInfo = &atoms->resinfo[at->resind];
210 char chainName[2] = {resInfo->chainid, 0};
211 tng_chain_t tngChain = NULL;
212 tng_residue_t tngRes = NULL;
213 tng_atom_t tngAtom = NULL;
215 if (tng_molecule_chain_find (tng, *tngMol, chainName,
216 (gmx_int64_t)-1, &tngChain) !=
219 tng_molecule_chain_add (tng, *tngMol, chainName,
223 /* FIXME: When TNG supports both residue index and residue
224 * number the latter should be used. Wait for TNG 2.0*/
225 if (tng_chain_residue_find(tng, tngChain, *resInfo->name,
226 at->resind + 1, &tngRes)
229 tng_chain_residue_add(tng, tngChain, *resInfo->name, &tngRes);
231 tng_residue_atom_add(tng, tngRes, *(atoms->atomname[atomIndex]), *(atoms->atomtype[atomIndex]), &tngAtom);
234 tng_molecule_cnt_set(tng, *tngMol, numMolecules);
237 void gmx_tng_add_mtop(tng_trajectory_t tng,
238 const gmx_mtop_t *mtop)
241 const t_ilist *ilist;
246 /* No topology information available to add. */
250 for (int molIndex = 0; molIndex < mtop->nmolblock; molIndex++)
252 tng_molecule_t tngMol = NULL;
253 const gmx_moltype_t *molType =
254 &mtop->moltype[mtop->molblock[molIndex].type];
256 /* Add a molecule to the TNG trajectory with the same name as the
257 * current molecule. */
258 addTngMoleculeFromTopology(tng,
261 mtop->molblock[molIndex].nmol,
264 /* Bonds have to be deduced from interactions (constraints etc). Different
265 * interactions have different sets of parameters. */
266 /* Constraints are specified using two atoms */
267 for (i = 0; i < F_NRE; i++)
271 ilist = &molType->ilist[i];
275 while (j < ilist->nr)
277 tng_molecule_bond_add(tng, tngMol, ilist->iatoms[j], ilist->iatoms[j+1], &tngBond);
283 /* Settle is described using three atoms */
284 ilist = &molType->ilist[F_SETTLE];
288 while (j < ilist->nr)
290 tng_molecule_bond_add(tng, tngMol, ilist->iatoms[j], ilist->iatoms[j+1], &tngBond);
291 tng_molecule_bond_add(tng, tngMol, ilist->iatoms[j], ilist->iatoms[j+2], &tngBond);
298 /*! \libinternal \brief Compute greatest common divisor of n1 and n2
299 * if they are positive.
301 * If only one of n1 and n2 is positive, then return it.
302 * If neither n1 or n2 is positive, then return -1. */
304 greatest_common_divisor_if_positive(int n1, int n2)
308 return (0 >= n2) ? -1 : n2;
315 /* We have a non-trivial greatest common divisor to compute. */
316 return gmx_greatest_common_divisor(n1, n2);
319 /* By default try to write 100 frames (of actual output) in each frame set.
320 * This number is the number of outputs of the most frequently written data
321 * type per frame set.
322 * TODO for 5.1: Verify that 100 frames per frame set is efficient for most
323 * setups regarding compression efficiency and compression time. Make this
324 * a hidden command-line option? */
325 const int defaultFramesPerFrameSet = 100;
327 /*! \libinternal \brief Set the number of frames per frame
328 * set according to output intervals.
329 * The default is that 100 frames are written of the data
330 * that is written most often. */
331 static void tng_set_frames_per_frame_set(tng_trajectory_t tng,
332 const gmx_bool bUseLossyCompression,
333 const t_inputrec *ir)
337 /* Set the number of frames per frame set to contain at least
338 * defaultFramesPerFrameSet of the lowest common denominator of
339 * the writing interval of positions and velocities. */
340 /* FIXME after 5.0: consider nstenergy also? */
341 if (bUseLossyCompression)
343 gcd = ir->nstxout_compressed;
347 gcd = greatest_common_divisor_if_positive(ir->nstxout, ir->nstvout);
348 gcd = greatest_common_divisor_if_positive(gcd, ir->nstfout);
355 tng_num_frames_per_frame_set_set(tng, gcd * defaultFramesPerFrameSet);
358 /*! \libinternal \brief Set the data-writing intervals, and number of
359 * frames per frame set */
360 static void set_writing_intervals(tng_trajectory_t tng,
361 const gmx_bool bUseLossyCompression,
362 const t_inputrec *ir)
364 /* Define pointers to specific writing functions depending on if we
365 * write float or double data */
366 typedef tng_function_status (*set_writing_interval_func_pointer)(tng_trajectory_t,
374 set_writing_interval_func_pointer set_writing_interval = tng_util_generic_write_interval_double_set;
376 set_writing_interval_func_pointer set_writing_interval = tng_util_generic_write_interval_set;
378 int xout, vout, fout;
379 // int gcd = -1, lowest = -1;
382 tng_set_frames_per_frame_set(tng, bUseLossyCompression, ir);
384 if (bUseLossyCompression)
386 xout = ir->nstxout_compressed;
389 compression = TNG_TNG_COMPRESSION;
396 compression = TNG_GZIP_COMPRESSION;
400 set_writing_interval(tng, xout, 3, TNG_TRAJ_POSITIONS,
401 "POSITIONS", TNG_PARTICLE_BLOCK_DATA,
403 /* The design of TNG makes it awkward to try to write a box
404 * with multiple periodicities, which might be co-prime. Since
405 * the use cases for the box with a frame consisting only of
406 * velocities seem low, for now we associate box writing with
407 * position writing. */
408 set_writing_interval(tng, xout, 9, TNG_TRAJ_BOX_SHAPE,
409 "BOX SHAPE", TNG_NON_PARTICLE_BLOCK_DATA,
410 TNG_GZIP_COMPRESSION);
411 /* TODO: if/when we write energies to TNG also, reconsider how
412 * and when box information is written, because GROMACS
413 * behaviour pre-5.0 was to write the box with every
414 * trajectory frame and every energy frame, and probably
415 * people depend on this. */
417 /* TODO: If we need to write lambda values at steps when
418 * positions (or other data) are not also being written, then
419 * code in mdoutf.c will need to match however that is
421 set_writing_interval(tng, xout, 1, TNG_GMX_LAMBDA,
422 "LAMBDAS", TNG_NON_PARTICLE_BLOCK_DATA,
423 TNG_GZIP_COMPRESSION);
425 /* FIXME: gcd and lowest currently not used. */
426 // gcd = greatest_common_divisor_if_positive(gcd, xout);
427 // if (lowest < 0 || xout < lowest)
434 set_writing_interval(tng, ir->nstvout, 3, TNG_TRAJ_VELOCITIES,
435 "VELOCITIES", TNG_PARTICLE_BLOCK_DATA,
438 /* FIXME: gcd and lowest currently not used. */
439 // gcd = greatest_common_divisor_if_positive(gcd, vout);
440 // if (lowest < 0 || vout < lowest)
447 set_writing_interval(tng, ir->nstfout, 3, TNG_TRAJ_FORCES,
448 "FORCES", TNG_PARTICLE_BLOCK_DATA,
449 TNG_GZIP_COMPRESSION);
451 /* FIXME: gcd and lowest currently not used. */
452 // gcd = greatest_common_divisor_if_positive(gcd, fout);
453 // if (lowest < 0 || fout < lowest)
458 /* FIXME: See above. gcd interval for lambdas is disabled. */
461 // /* Lambdas written at an interval of the lowest common denominator
462 // * of other output */
463 // set_writing_interval(tng, gcd, 1, TNG_GMX_LAMBDA,
464 // "LAMBDAS", TNG_NON_PARTICLE_BLOCK_DATA,
465 // TNG_GZIP_COMPRESSION);
467 // if (gcd < lowest / 10)
469 // gmx_warning("The lowest common denominator of trajectory output is "
470 // "every %d step(s), whereas the shortest output interval "
471 // "is every %d steps.", gcd, lowest);
477 void gmx_tng_prepare_md_writing(tng_trajectory_t tng,
478 const gmx_mtop_t *mtop,
479 const t_inputrec *ir)
482 gmx_tng_add_mtop(tng, mtop);
483 set_writing_intervals(tng, FALSE, ir);
484 tng_time_per_frame_set(tng, ir->delta_t * PICO);
486 GMX_UNUSED_VALUE(tng);
487 GMX_UNUSED_VALUE(mtop);
488 GMX_UNUSED_VALUE(ir);
493 /* Check if all atoms in the molecule system are selected
494 * by a selection group of type specified by gtype. */
495 static gmx_bool all_atoms_selected(const gmx_mtop_t *mtop,
498 const gmx_moltype_t *molType;
499 const t_atoms *atoms;
501 /* Iterate through all atoms in the molecule system and
502 * check if they belong to a selection group of the
504 for (int molIndex = 0, i = 0; molIndex < mtop->nmoltype; molIndex++)
506 molType = &mtop->moltype[mtop->molblock[molIndex].type];
508 atoms = &molType->atoms;
510 for (int j = 0; j < mtop->molblock[molIndex].nmol; j++)
512 for (int atomIndex = 0; atomIndex < atoms->nr; atomIndex++, i++)
514 if (ggrpnr(&mtop->groups, gtype, i) != 0)
524 /* Create TNG molecules which will represent each of the selection
525 * groups for writing. But do that only if there is actually a
526 * specified selection group and it is not the whole system.
527 * TODO: Currently the only selection that is taken into account
528 * is egcCompressedX, but other selections should be added when
529 * e.g. writing energies is implemented.
531 static void add_selection_groups(tng_trajectory_t tng,
532 const gmx_mtop_t *mtop)
534 const gmx_moltype_t *molType;
535 const t_atoms *atoms;
537 const t_resinfo *resInfo;
538 const t_ilist *ilist;
541 tng_molecule_t mol, iterMol;
549 /* TODO: When the TNG molecules block is more flexible TNG selection
550 * groups should not need all atoms specified. It should be possible
551 * just to specify what molecules are selected (and/or which atoms in
552 * the molecule) and how many (if applicable). */
554 /* If no atoms are selected we do not need to create a
555 * TNG selection group molecule. */
556 if (mtop->groups.ngrpnr[egcCompressedX] == 0)
561 /* If all atoms are selected we do not have to create a selection
562 * group molecule in the TNG molecule system. */
563 if (all_atoms_selected(mtop, egcCompressedX))
568 /* The name of the TNG molecule containing the selection group is the
569 * same as the name of the selection group. */
570 nameIndex = *mtop->groups.grps[egcCompressedX].nm_ind;
571 groupName = *mtop->groups.grpname[nameIndex];
573 tng_molecule_alloc(tng, &mol);
574 tng_molecule_name_set(tng, mol, groupName);
575 tng_molecule_chain_add(tng, mol, "", &chain);
576 for (int molIndex = 0, i = 0; molIndex < mtop->nmoltype; molIndex++)
578 molType = &mtop->moltype[mtop->molblock[molIndex].type];
580 atoms = &molType->atoms;
582 for (int j = 0; j < mtop->molblock[molIndex].nmol; j++)
584 bool bAtomsAdded = FALSE;
585 for (int atomIndex = 0; atomIndex < atoms->nr; atomIndex++, i++)
590 if (ggrpnr(&mtop->groups, egcCompressedX, i) != 0)
594 at = &atoms->atom[atomIndex];
597 resInfo = &atoms->resinfo[at->resind];
598 /* FIXME: When TNG supports both residue index and residue
599 * number the latter should be used. */
600 res_name = *resInfo->name;
601 res_id = at->resind + 1;
605 res_name = (char *)"";
608 if (tng_chain_residue_find(tng, chain, res_name, res_id, &res)
611 /* Since there is ONE chain for selection groups do not keep the
612 * original residue IDs - otherwise there might be conflicts. */
613 tng_chain_residue_add(tng, chain, res_name, &res);
615 tng_residue_atom_w_id_add(tng, res, *(atoms->atomname[atomIndex]),
616 *(atoms->atomtype[atomIndex]),
617 atom_offset + atomIndex, &atom);
623 for (int k = 0; k < F_NRE; k++)
627 ilist = &molType->ilist[k];
631 while (l < ilist->nr)
634 atom1 = ilist->iatoms[l] + atom_offset;
635 atom2 = ilist->iatoms[l+1] + atom_offset;
636 if (ggrpnr(&mtop->groups, egcCompressedX, atom1) == 0 &&
637 ggrpnr(&mtop->groups, egcCompressedX, atom2) == 0)
639 tng_molecule_bond_add(tng, mol, ilist->iatoms[l],
640 ilist->iatoms[l+1], &tngBond);
647 /* Settle is described using three atoms */
648 ilist = &molType->ilist[F_SETTLE];
652 while (l < ilist->nr)
654 int atom1, atom2, atom3;
655 atom1 = ilist->iatoms[l] + atom_offset;
656 atom2 = ilist->iatoms[l+1] + atom_offset;
657 atom3 = ilist->iatoms[l+2] + atom_offset;
658 if (ggrpnr(&mtop->groups, egcCompressedX, atom1) == 0)
660 if (ggrpnr(&mtop->groups, egcCompressedX, atom2) == 0)
662 tng_molecule_bond_add(tng, mol, atom1,
665 if (ggrpnr(&mtop->groups, egcCompressedX, atom3) == 0)
667 tng_molecule_bond_add(tng, mol, atom1,
675 atom_offset += atoms->nr;
678 tng_molecule_existing_add(tng, &mol);
679 tng_molecule_cnt_set(tng, mol, 1);
680 tng_num_molecule_types_get(tng, &nMols);
681 for (gmx_int64_t k = 0; k < nMols; k++)
683 tng_molecule_of_index_get(tng, k, &iterMol);
688 tng_molecule_cnt_set(tng, iterMol, 0);
693 void gmx_tng_set_compression_precision(tng_trajectory_t tng,
697 tng_compression_precision_set(tng, prec);
699 GMX_UNUSED_VALUE(tng);
700 GMX_UNUSED_VALUE(prec);
704 void gmx_tng_prepare_low_prec_writing(tng_trajectory_t tng,
705 const gmx_mtop_t *mtop,
706 const t_inputrec *ir)
709 gmx_tng_add_mtop(tng, mtop);
710 add_selection_groups(tng, mtop);
711 set_writing_intervals(tng, TRUE, ir);
712 tng_time_per_frame_set(tng, ir->delta_t * PICO);
713 gmx_tng_set_compression_precision(tng, ir->x_compression_precision);
715 GMX_UNUSED_VALUE(tng);
716 GMX_UNUSED_VALUE(mtop);
717 GMX_UNUSED_VALUE(ir);
721 void gmx_fwrite_tng(tng_trajectory_t tng,
722 const gmx_bool bUseLossyCompression,
724 real elapsedPicoSeconds,
733 typedef tng_function_status (*write_data_func_pointer)(tng_trajectory_t,
743 static write_data_func_pointer write_data = tng_util_generic_with_time_double_write;
745 static write_data_func_pointer write_data = tng_util_generic_with_time_write;
747 double elapsedSeconds = elapsedPicoSeconds * PICO;
748 gmx_int64_t nParticles;
754 /* This function might get called when the type of the
755 compressed trajectory is actually XTC. So we exit and move
760 tng_num_particles_get(tng, &nParticles);
761 if (nAtoms != (int)nParticles)
763 tng_implicit_num_particles_set(tng, nAtoms);
766 if (bUseLossyCompression)
768 compression = TNG_TNG_COMPRESSION;
772 compression = TNG_GZIP_COMPRESSION;
775 /* The writing is done using write_data, which writes float or double
776 * depending on the GROMACS compilation. */
779 GMX_ASSERT(box, "Need a non-NULL box if positions are written");
781 if (write_data(tng, step, elapsedSeconds,
782 reinterpret_cast<const real *>(x),
783 3, TNG_TRAJ_POSITIONS, "POSITIONS",
784 TNG_PARTICLE_BLOCK_DATA,
785 compression) != TNG_SUCCESS)
787 gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?");
789 /* TNG-MF1 compression only compresses positions and velocities. Use lossless
790 * compression for box shape regardless of output mode */
791 if (write_data(tng, step, elapsedSeconds,
792 reinterpret_cast<const real *>(box),
793 9, TNG_TRAJ_BOX_SHAPE, "BOX SHAPE",
794 TNG_NON_PARTICLE_BLOCK_DATA,
795 TNG_GZIP_COMPRESSION) != TNG_SUCCESS)
797 gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?");
803 if (write_data(tng, step, elapsedSeconds,
804 reinterpret_cast<const real *>(v),
805 3, TNG_TRAJ_VELOCITIES, "VELOCITIES",
806 TNG_PARTICLE_BLOCK_DATA,
807 compression) != TNG_SUCCESS)
809 gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?");
815 /* TNG-MF1 compression only compresses positions and velocities. Use lossless
816 * compression for forces regardless of output mode */
817 if (write_data(tng, step, elapsedSeconds,
818 reinterpret_cast<const real *>(f),
819 3, TNG_TRAJ_FORCES, "FORCES",
820 TNG_PARTICLE_BLOCK_DATA,
821 TNG_GZIP_COMPRESSION) != TNG_SUCCESS)
823 gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?");
827 /* TNG-MF1 compression only compresses positions and velocities. Use lossless
828 * compression for lambdas regardless of output mode */
829 if (write_data(tng, step, elapsedSeconds,
830 reinterpret_cast<const real *>(&lambda),
831 1, TNG_GMX_LAMBDA, "LAMBDAS",
832 TNG_NON_PARTICLE_BLOCK_DATA,
833 TNG_GZIP_COMPRESSION) != TNG_SUCCESS)
835 gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?");
838 GMX_UNUSED_VALUE(tng);
839 GMX_UNUSED_VALUE(bUseLossyCompression);
840 GMX_UNUSED_VALUE(step);
841 GMX_UNUSED_VALUE(elapsedPicoSeconds);
842 GMX_UNUSED_VALUE(lambda);
843 GMX_UNUSED_VALUE(box);
844 GMX_UNUSED_VALUE(nAtoms);
851 void fflush_tng(tng_trajectory_t tng)
858 tng_frame_set_premature_write(tng, TNG_USE_HASH);
860 GMX_UNUSED_VALUE(tng);
864 float gmx_tng_get_time_of_final_frame(tng_trajectory_t tng)
871 tng_num_frames_get(tng, &nFrames);
872 tng_util_time_of_frame_get(tng, nFrames - 1, &time);
877 GMX_UNUSED_VALUE(tng);