Clean up some gmxapi sources and tests.
[alexxy/gromacs.git] / python_packaging / src / test / conftest.py
1 #
2 # This file is part of the GROMACS molecular simulation package.
3 #
4 # Copyright (c) 2019,2020,2021, 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.
8 #
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.
13 #
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.
18 #
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.
23 #
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.
31 #
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.
34
35 """Configuration and fixtures for pytest."""
36
37 import json
38 import logging
39 import os
40
41 import pytest
42
43 pytest_plugins = ('gmxapi.testsupport',)
44
45
46 @pytest.fixture(scope='session')
47 def spc_water_box_collection(gmxcli, remove_tempdir):
48     """Provide a collection of simulation input items for a simple simulation.
49
50     Prepare the MD input in a freshly created working directory.
51     Solvate a 5nm cubic box with spc water. Return a dictionary of the artifacts produced.
52     """
53     import gmxapi as gmx
54     # TODO: Remove this import when the the spc_water_box fixture is migrated to gmxapi.testsupport
55     from gmxapi.testsupport import _cleandir
56
57     # TODO: (#2896) Fetch MD input from package / library data.
58     # Example:
59     #     import pkg_resources
60     #     # Note: importing pkg_resources means setuptools is required for running this test.
61     #     # Get or build TPR file from data bundled via setup(package_data=...)
62     #     # Ref https://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files
63     #     from gmx.data import tprfilename
64
65     with _cleandir(remove_tempdir) as tempdir:
66
67         testdir = os.path.dirname(__file__)
68         with open(os.path.join(testdir, 'testdata.json'), 'r') as fh:
69             testdata = json.load(fh)
70
71         # TODO: (#2756) Don't rely on so many automagical behaviors (as described in comments below)
72
73         structurefile = os.path.join(tempdir, 'structure.gro')
74         # We let `gmx solvate` use the default solvent. Otherwise, we would do
75         #     gro_input = testdata['solvent_structure']
76         #     with open(structurefile, 'w') as fh:
77         #         fh.write('\n'.join(gro_input))
78         #         fh.write('\n')
79
80         topfile = os.path.join(tempdir, 'topology.top')
81         top_input = testdata['solvent_topology']
82         # `gmx solvate` will append a line to the provided file with the molecule count,
83         # so we strip the last line from the input topology.
84         with open(topfile, 'w') as fh:
85             fh.write('\n'.join(top_input[:-1]))
86             fh.write('\n')
87
88         assert os.path.exists(topfile)
89         solvate = gmx.commandline_operation(gmxcli,
90                                             arguments=['solvate', '-box', '5', '5', '5'],
91                                             # We use the default solvent instead of specifying one.
92                                             # input_files={'-cs': structurefile},
93                                             output_files={'-p': topfile,
94                                                           '-o': structurefile,
95                                                           }
96                                             )
97         assert os.path.exists(topfile)
98
99         if solvate.output.returncode.result() != 0:
100             logging.debug(solvate.output.stderr.result())
101             raise RuntimeError('solvate failed in spc_water_box testing fixture.')
102
103         # Choose an exactly representable dt of 2^-9 ps (approximately 0.002)
104         dt = 2. ** -9.
105         mdp_input = [('integrator', 'md'),
106                      ('dt', dt),
107                      ('cutoff-scheme', 'Verlet'),
108                      ('nsteps', 2),
109                      ('nstxout', 1),
110                      ('nstvout', 1),
111                      ('nstfout', 1),
112                      ('tcoupl', 'v-rescale'),
113                      ('tc-grps', 'System'),
114                      ('tau-t', 1),
115                      ('ref-t', 298)]
116         mdp_input = '\n'.join([' = '.join([str(item) for item in kvpair]) for kvpair in mdp_input])
117         mdpfile = os.path.join(tempdir, 'md.mdp')
118         with open(mdpfile, 'w') as fh:
119             fh.write(mdp_input)
120             fh.write('\n')
121         tprfile = os.path.join(tempdir, 'topol.tpr')
122         # We don't use mdout_mdp, but if we don't specify it to grompp,
123         # it will be created in the current working directory.
124         mdout_mdp = os.path.join(tempdir, 'mdout.mdp')
125
126         grompp = gmx.commandline_operation(gmxcli, 'grompp',
127                                            input_files={
128                                                '-f': mdpfile,
129                                                '-p': solvate.output.file['-p'],
130                                                '-c': solvate.output.file['-o'],
131                                                '-po': mdout_mdp,
132                                            },
133                                            output_files={'-o': tprfile})
134         tprfilename = grompp.output.file['-o'].result()
135         if grompp.output.returncode.result() != 0:
136             logging.debug(grompp.output.stderr.result())
137             raise RuntimeError('grompp failed in spc_water_box testing fixture.')
138
139         # TODO: more inspection of grompp errors...
140         assert os.path.exists(tprfilename)
141         collection = {
142             'tpr_filename': tprfilename,
143             'mdp_input_filename': mdpfile,
144             'mdp_output_filename': mdout_mdp,
145             'topology_filename': solvate.output.file['-p'].result(),
146             'gro_filename': solvate.output.file['-o'].result(),
147             'mdp_input_list': mdp_input
148         }
149         yield collection
150
151
152 @pytest.fixture(scope='session')
153 def spc_water_box(spc_water_box_collection):
154     """Provide a TPR input file for a simple simulation."""
155     yield spc_water_box_collection['tpr_filename']