Remove unnecessary includes of arrayref.h
[alexxy/gromacs.git] / src / gromacs / fileio / readinp.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7  * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 #include "gmxpre.h"
39
40 #include "readinp.h"
41
42 #include <cstdlib>
43 #include <cstring>
44
45 #include <algorithm>
46
47 #include "gromacs/fileio/warninp.h"
48 #include "gromacs/utility/arrayref.h"
49 #include "gromacs/utility/binaryinformation.h"
50 #include "gromacs/utility/cstringutil.h"
51 #include "gromacs/utility/exceptions.h"
52 #include "gromacs/utility/fatalerror.h"
53 #include "gromacs/utility/keyvaluetreebuilder.h"
54 #include "gromacs/utility/niceheader.h"
55 #include "gromacs/utility/programcontext.h"
56 #include "gromacs/utility/smalloc.h"
57 #include "gromacs/utility/stringutil.h"
58 #include "gromacs/utility/textreader.h"
59 #include "gromacs/utility/textwriter.h"
60
61 std::vector<t_inpfile> read_inpfile(gmx::TextInputStream* stream, const char* fn, warninp_t wi)
62 {
63     std::vector<t_inpfile> inp;
64
65     if (debug)
66     {
67         fprintf(debug, "Reading MDP file %s\n", fn);
68     }
69
70     int             indexOfLineReadFromFile = 0;
71     std::string     line;
72     gmx::TextReader reader(stream);
73     reader.setTrimTrailingWhiteSpace(true);
74     reader.setTrimTrailingComment(true, ';');
75     while (reader.readLine(&line))
76     {
77         indexOfLineReadFromFile++;
78         set_warning_line(wi, fn, indexOfLineReadFromFile);
79
80         if (line.empty())
81         {
82             continue;
83         }
84
85         auto tokens = gmx::splitAndTrimDelimitedString(line, '=');
86         if (tokens.size() < 2)
87         {
88             auto message = gmx::formatString(
89                     "No '=' to separate .mdp parameter key and value was found on line:\n'%s'",
90                     line.c_str());
91             warning_error(wi, message);
92             continue;
93         }
94         if (tokens.size() > 2)
95         {
96             // More than one equals symbol in the original line is
97             // valid if the RHS is a free string, and needed for
98             // "define = -DBOOLVAR -DVAR=VALUE".
99             //
100             // First, drop all the fields on the RHS of the first equals symbol.
101             tokens.resize(1);
102             // This find cannot return std::string::npos.
103             auto firstEqualsPos = line.find('=');
104             tokens.emplace_back(gmx::stripString(line.substr(firstEqualsPos + 1)));
105         }
106         GMX_RELEASE_ASSERT(tokens.size() == 2, "Must have tokens for key and value");
107         if (tokens[0].empty() && tokens[1].empty())
108         {
109             auto message = gmx::formatString(
110                     "No .mdp parameter name or value was found on line:\n'%s'", line.c_str());
111             warning_error(wi, message);
112             continue;
113         }
114         if (tokens[0].empty())
115         {
116             auto message = gmx::formatString(
117                     "No .mdp parameter name was found on the left-hand side of '=' on line:\n'%s'",
118                     line.c_str());
119             warning_error(wi, message);
120             continue;
121         }
122         if (tokens[1].empty())
123         {
124             // Users are probably using this for lines like
125             //   tcoupl = ;v-rescale
126             //   comm-grps =
127             // so we accept their intent to use the default behavior.
128             continue;
129         }
130
131         /* Now finally something sensible; check for duplicates */
132         int found_index = search_einp(inp, tokens[0].c_str());
133
134         if (found_index == -1)
135         {
136             /* add a new item */
137             inp.emplace_back(0, 1, false, false, false, tokens[0], tokens[1]);
138         }
139         else
140         {
141             auto message = gmx::formatString("Parameter \"%s\" doubly defined\n", tokens[0].c_str());
142             warning_error(wi, message);
143         }
144     }
145     /* This preserves the behaviour of the old code, which issues some
146        warnings after completing parsing. Regenerating regressiontest
147        warning files is not worth the effort. */
148     indexOfLineReadFromFile++;
149     set_warning_line(wi, fn, indexOfLineReadFromFile);
150
151     if (debug)
152     {
153         fprintf(debug, "Done reading MDP file, there were %zu entries in there\n", inp.size());
154     }
155
156     return inp;
157 }
158
159 gmx::KeyValueTreeObject flatKeyValueTreeFromInpFile(gmx::ArrayRef<const t_inpfile> inp)
160 {
161     gmx::KeyValueTreeBuilder builder;
162     auto                     root = builder.rootObject();
163     for (auto& local : inp)
164     {
165         root.addValue<std::string>(local.name_, !local.value_.empty() ? local.value_ : "");
166     }
167     return builder.build();
168 }
169
170
171 struct inp_comp
172 {
173     bool operator()(t_inpfile const& a, t_inpfile const& b) { return a.count_ < b.count_; }
174 };
175
176 static void sort_inp(std::vector<t_inpfile>* inp)
177 {
178     std::vector<t_inpfile>& inpRef = *inp;
179     int                     mm;
180
181     mm = -1;
182     for (const auto& local : inpRef)
183     {
184         mm = std::max(mm, local.count_);
185     }
186     for (auto& local : inpRef)
187     {
188         if (local.count_ == 0)
189         {
190             local.count_ = mm++;
191         }
192     }
193     std::sort(inpRef.begin(), inpRef.end(), inp_comp());
194 }
195
196 void write_inpfile(gmx::TextOutputStream*  stream,
197                    const char*             fn,
198                    std::vector<t_inpfile>* inp,
199                    gmx_bool                bHaltOnUnknown,
200                    WriteMdpHeader          writeHeader,
201                    warninp_t               wi)
202 {
203     using gmx::formatString;
204
205     sort_inp(inp);
206
207     gmx::TextWriter writer(stream);
208     if (writeHeader == WriteMdpHeader::yes)
209     {
210         gmx::niceHeader(&writer, fn, ';');
211
212         gmx::BinaryInformationSettings settings;
213         settings.generatedByHeader(true);
214         settings.linePrefix(";\t");
215         gmx::printBinaryInformation(&writer, gmx::getProgramContext(), settings);
216     }
217     for (const auto& local : *inp)
218     {
219         if (local.bHandledAsKeyValueTree_) {}
220         else if (local.bSet_)
221         {
222             if (local.name_[0] == ';' || (local.name_.length() > 2 && local.name_[1] == ';'))
223             {
224                 writer.writeLine(formatString("%-24s", local.name_.c_str()));
225             }
226             else
227             {
228                 writer.writeLine(formatString("%-24s = %s", local.name_.c_str(),
229                                               !local.value_.empty() ? local.value_.c_str() : ""));
230             }
231         }
232         else if (!local.bObsolete_)
233         {
234             auto message =
235                     formatString("Unknown left-hand '%s' in parameter file\n", local.name_.c_str());
236             if (bHaltOnUnknown)
237             {
238                 warning_error(wi, message.c_str());
239             }
240             else
241             {
242                 warning(wi, message.c_str());
243             }
244         }
245     }
246
247     check_warning_error(wi, FARGS);
248 }
249
250 void replace_inp_entry(gmx::ArrayRef<t_inpfile> inp, const char* old_entry, const char* new_entry)
251 {
252     for (auto& local : inp)
253     {
254         if (gmx_strcasecmp_min(old_entry, local.name_.c_str()) == 0)
255         {
256             if (new_entry)
257             {
258                 fprintf(stderr, "Replacing old mdp entry '%s' by '%s'\n", local.name_.c_str(), new_entry);
259
260                 int foundIndex = search_einp(inp, new_entry);
261                 if (foundIndex >= 0)
262                 {
263                     gmx_fatal(FARGS,
264                               "A parameter is present with both the old name '%s' and the new name "
265                               "'%s'.",
266                               local.name_.c_str(), inp[foundIndex].name_.c_str());
267                 }
268
269                 local.name_.assign(new_entry);
270             }
271             else
272             {
273                 fprintf(stderr, "Ignoring obsolete mdp entry '%s'\n", local.name_.c_str());
274                 local.bObsolete_ = TRUE;
275             }
276         }
277     }
278 }
279
280 int search_einp(gmx::ArrayRef<const t_inpfile> inp, const char* name)
281 {
282     if (inp.empty())
283     {
284         return -1;
285     }
286     for (gmx::index i = 0; i < inp.ssize(); i++)
287     {
288         if (gmx_strcasecmp_min(name, inp[i].name_.c_str()) == 0)
289         {
290             return i;
291         }
292     }
293     return -1;
294 }
295
296 void mark_einp_set(gmx::ArrayRef<t_inpfile> inp, const char* name)
297 {
298     int i = search_einp(inp, name);
299     if (i != -1)
300     {
301         inp[i].count_ = inp.front().inp_count_++;
302         inp[i].bSet_  = TRUE;
303         /* Prevent mdp lines being written twice for
304            options that are handled via key-value trees. */
305         inp[i].bHandledAsKeyValueTree_ = TRUE;
306     }
307 }
308
309 static int get_einp(std::vector<t_inpfile>* inp, const char* name)
310 {
311     std::vector<t_inpfile>& inpRef   = *inp;
312     bool                    notfound = false;
313
314     int i = search_einp(inpRef, name);
315
316     if (i == -1)
317     {
318         notfound = true;
319         inpRef.emplace_back(0, 0, false, true, false, name, "");
320         i = inpRef.size() - 1;
321         if (inpRef.size() == 1)
322         {
323             inpRef.front().inp_count_ = 1;
324         }
325     }
326     inpRef[i].count_ = inpRef.front().inp_count_++;
327     inpRef[i].bSet_  = TRUE;
328     if (debug)
329     {
330         fprintf(debug, "Inp %d = %s\n", inpRef[i].count_, inpRef[i].name_.c_str());
331     }
332
333     if (notfound)
334     {
335         return -1;
336     }
337     else
338     {
339         return i;
340     }
341 }
342
343 /* Note that sanitizing the trailing part of inp[ii].value was the responsibility of read_inpfile() */
344 int get_eint(std::vector<t_inpfile>* inp, const char* name, int def, warninp_t wi)
345 {
346     std::vector<t_inpfile>& inpRef = *inp;
347     char                    buf[32], *ptr, warn_buf[STRLEN];
348
349     int ii = get_einp(inp, name);
350
351     if (ii == -1)
352     {
353         sprintf(buf, "%d", def);
354         inpRef.back().value_.assign(buf);
355
356         return def;
357     }
358     else
359     {
360         int ret = std::strtol(inpRef[ii].value_.c_str(), &ptr, 10);
361         if (*ptr != '\0')
362         {
363             sprintf(warn_buf,
364                     "Right hand side '%s' for parameter '%s' in parameter file is not an integer "
365                     "value\n",
366                     inpRef[ii].value_.c_str(), inpRef[ii].name_.c_str());
367             warning_error(wi, warn_buf);
368         }
369
370         return ret;
371     }
372 }
373
374 int get_eint(std::vector<t_inpfile>* inp, const std::string& name, int def, warninp_t wi)
375 {
376     return get_eint(inp, name.c_str(), def, wi);
377 }
378
379 /* Note that sanitizing the trailing part of inp[ii].value was the responsibility of read_inpfile() */
380 int64_t get_eint64(std::vector<t_inpfile>* inp, const char* name, int64_t def, warninp_t wi)
381 {
382     std::vector<t_inpfile>& inpRef = *inp;
383     char                    buf[32], *ptr, warn_buf[STRLEN];
384
385     int ii = get_einp(inp, name);
386
387     if (ii == -1)
388     {
389         sprintf(buf, "%" PRId64, def);
390         inpRef.back().value_.assign(buf);
391
392         return def;
393     }
394     else
395     {
396         int64_t ret = str_to_int64_t(inpRef[ii].value_.c_str(), &ptr);
397         if (*ptr != '\0')
398         {
399             sprintf(warn_buf,
400                     "Right hand side '%s' for parameter '%s' in parameter file is not an integer "
401                     "value\n",
402                     inpRef[ii].value_.c_str(), inpRef[ii].name_.c_str());
403             warning_error(wi, warn_buf);
404         }
405
406         return ret;
407     }
408 }
409
410 int64_t get_eint64(std::vector<t_inpfile>* inp, const std::string& name, int64_t def, warninp_t wi)
411 {
412     return get_eint64(inp, name.c_str(), def, wi);
413 }
414
415 /* Note that sanitizing the trailing part of inp[ii].value was the responsibility of read_inpfile() */
416 double get_ereal(std::vector<t_inpfile>* inp, const char* name, double def, warninp_t wi)
417 {
418     std::vector<t_inpfile>& inpRef = *inp;
419     char                    buf[32], *ptr, warn_buf[STRLEN];
420
421     int ii = get_einp(inp, name);
422
423     if (ii == -1)
424     {
425         sprintf(buf, "%g", def);
426         inpRef.back().value_.assign(buf);
427
428         return def;
429     }
430     else
431     {
432         double ret = strtod(inpRef[ii].value_.c_str(), &ptr);
433         if (*ptr != '\0')
434         {
435             sprintf(warn_buf,
436                     "Right hand side '%s' for parameter '%s' in parameter file is not a real "
437                     "value\n",
438                     inpRef[ii].value_.c_str(), inpRef[ii].name_.c_str());
439             warning_error(wi, warn_buf);
440         }
441
442         return ret;
443     }
444 }
445
446 double get_ereal(std::vector<t_inpfile>* inp, const std::string& name, double def, warninp_t wi)
447 {
448     return get_ereal(inp, name.c_str(), def, wi);
449 }
450
451 /* Note that sanitizing the trailing part of inp[ii].value was the responsibility of read_inpfile() */
452 const char* get_estr(std::vector<t_inpfile>* inp, const char* name, const char* def)
453 {
454     std::vector<t_inpfile>& inpRef = *inp;
455     char                    buf[32];
456
457     int ii = get_einp(inp, name);
458
459     if (ii == -1)
460     {
461         if (def)
462         {
463             sprintf(buf, "%s", def);
464             inpRef.back().value_.assign(buf);
465         }
466         else
467         {
468             inpRef.back().value_.clear();
469         }
470
471         return def;
472     }
473     else
474     {
475         return inpRef[ii].value_.c_str();
476     }
477 }
478
479 const char* get_estr(std::vector<t_inpfile>* inp, const std::string& name, const char* def)
480 {
481     return get_estr(inp, name.c_str(), def);
482 }
483
484 /* Note that sanitizing the trailing part of inp[ii].value was the responsibility of read_inpfile() */
485 int get_eeenum(std::vector<t_inpfile>* inp, const char* name, const char** defs, warninp_t wi)
486 {
487     std::vector<t_inpfile>& inpRef = *inp;
488     int                     n      = 0;
489     char                    buf[STRLEN];
490
491     int ii = get_einp(inp, name);
492
493     if (ii == -1)
494     {
495         inpRef.back().value_.assign(defs[0]);
496
497         return 0;
498     }
499     int i = 0;
500     for (i = 0; (defs[i] != nullptr); i++)
501     {
502         if (gmx_strcasecmp_min(defs[i], inpRef[ii].value_.c_str()) == 0)
503         {
504             break;
505         }
506     }
507
508     if (defs[i] == nullptr)
509     {
510         n += sprintf(buf, "Invalid enum '%s' for variable %s, using '%s'\n",
511                      inpRef[ii].value_.c_str(), name, defs[0]);
512         n += sprintf(buf + n, "Next time use one of:");
513         int j = 0;
514         while (defs[j])
515         {
516             n += sprintf(buf + n, " '%s'", defs[j]);
517             j++;
518         }
519         if (wi != nullptr)
520         {
521             warning_error(wi, buf);
522         }
523         else
524         {
525             fprintf(stderr, "%s\n", buf);
526         }
527
528         inpRef[ii].value_ = gmx_strdup(defs[0]);
529
530         return 0;
531     }
532
533     return i;
534 }
535
536 int get_eeenum(std::vector<t_inpfile>* inp, const std::string& name, const char** defs, warninp_t wi)
537 {
538     return get_eeenum(inp, name.c_str(), defs, wi);
539 }
540
541 int get_eenum(std::vector<t_inpfile>* inp, const char* name, const char** defs)
542 {
543     return get_eeenum(inp, name, defs, nullptr);
544 }
545
546 void printStringNewline(std::vector<t_inpfile>* inp, const char* line)
547 {
548     std::string tmp("\n; ");
549     tmp.append(line);
550     get_estr(inp, tmp.c_str(), nullptr);
551 }
552
553 void printStringNoNewline(std::vector<t_inpfile>* inp, const char* line)
554 {
555     std::string tmp("; ");
556     tmp.append(line);
557     get_estr(inp, tmp.c_str(), nullptr);
558 }
559 void setStringEntry(std::vector<t_inpfile>* inp, const char* name, char* newName, const char* def)
560 {
561     const char* found = nullptr;
562     found             = get_estr(inp, name, def);
563     if (found != nullptr)
564     {
565         std::strcpy(newName, found);
566     }
567 }