SYCL: Avoid using no_init read accessor in rocFFT
[alexxy/gromacs.git] / src / gromacs / options / filenameoption.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016 by the GROMACS development team.
5  * Copyright (c) 2017,2019,2020,2021, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \internal \file
37  * \brief
38  * Implements classes in filenameoption.h and filenameoptionstorage.h.
39  *
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  * \ingroup module_options
42  */
43 #include "gmxpre.h"
44
45 #include "filenameoption.h"
46
47 #include <cstring>
48
49 #include <string>
50 #include <vector>
51
52 #include "gromacs/fileio/filetypes.h"
53 #include "gromacs/options/filenameoptionmanager.h"
54 #include "gromacs/options/optionmanagercontainer.h"
55 #include "gromacs/utility/arrayref.h"
56 #include "gromacs/utility/enumerationhelpers.h"
57 #include "gromacs/utility/exceptions.h"
58 #include "gromacs/utility/gmxassert.h"
59 #include "gromacs/utility/stringutil.h"
60
61 #include "filenameoptionstorage.h"
62
63 namespace gmx
64 {
65
66 namespace
67 {
68
69 //! \addtogroup module_options
70 //! \{
71
72 /*! \brief
73  * Mapping from OptionFileType to a file type in filetypes.h.
74  */
75 struct FileTypeMapping
76 {
77     //! OptionFileType value to map.
78     OptionFileType optionType;
79     //! Corresponding file type from filetypes.h.
80     int fileType;
81 };
82
83 //! Mappings from OptionFileType to file types in filetypes.h.
84 constexpr EnumerationArray<OptionFileType, int> sc_fileTypeMapping = { efTPS, efTPR, efTRX, efEDR,
85                                                                        efPDB, efNDX, efXVG, efDAT,
86                                                                        efCSV, efQMI };
87
88 /********************************************************************
89  * FileTypeHandler
90  */
91
92 /*! \internal
93  * \brief
94  * Handles a single file type known to FileNameOptionStorage.
95  *
96  * Methods in this class do not throw, except for a possible std::bad_alloc
97  * when constructing std::string return values.
98  */
99 class FileTypeHandler
100 {
101 public:
102     /*! \brief
103      * Returns a handler for a single file type.
104      *
105      * \param[in] fileType  File type (from filetypes.h) to use.
106      */
107     explicit FileTypeHandler(int fileType);
108
109     //! Returns the number of acceptable extensions for this file type.
110     int extensionCount() const;
111     //! Returns the extension with the given index.
112     const char* extension(int i) const;
113
114     //! Returns whether \p fileType (from filetypes.h) is accepted for this type.
115     bool isValidType(int fileType) const;
116
117 private:
118     /*! \brief
119      * File type (from filetypes.h) represented by this handler.
120      *
121      * -1 represents an unknown file type.
122      */
123     int fileType_;
124     //! Number of different extensions this type supports.
125     int extensionCount_;
126     /*! \brief
127      * List of simple file types that are included in this type.
128      *
129      * If `fileType_` represents a generic type in filetypes.h, i.e., a type
130      * that accepts multiple different types of files, then this is an
131      * array of `extensionCount_` elements, each element specifying one
132      * non-generic file type that this option accepts.
133      * `NULL` for single-extension types.
134      */
135     const int* genericTypes_;
136 };
137
138 FileTypeHandler::FileTypeHandler(int fileType) :
139     fileType_(fileType), extensionCount_(0), genericTypes_(nullptr)
140 {
141     if (fileType_ >= 0)
142     {
143         const int genericTypeCount = ftp2generic_count(fileType_);
144         if (genericTypeCount > 0)
145         {
146             extensionCount_ = genericTypeCount;
147             genericTypes_   = ftp2generic_list(fileType_);
148         }
149         else if (ftp2ext_with_dot(fileType_)[0] != '\0')
150         {
151             extensionCount_ = 1;
152         }
153     }
154 }
155
156 int FileTypeHandler::extensionCount() const
157 {
158     return extensionCount_;
159 }
160
161 const char* FileTypeHandler::extension(int i) const
162 {
163     GMX_ASSERT(i >= 0 && i < extensionCount_, "Invalid extension index");
164     if (genericTypes_ != nullptr)
165     {
166         return ftp2ext_with_dot(genericTypes_[i]);
167     }
168     return ftp2ext_with_dot(fileType_);
169 }
170
171 bool FileTypeHandler::isValidType(int fileType) const
172 {
173     if (genericTypes_ != nullptr)
174     {
175         for (int i = 0; i < extensionCount(); ++i)
176         {
177             if (fileType == genericTypes_[i])
178             {
179                 return true;
180             }
181         }
182         return false;
183     }
184     else
185     {
186         return fileType == fileType_;
187     }
188 }
189
190 //! \}
191
192 } // namespace
193
194 /********************************************************************
195  * FileNameOptionStorage
196  */
197
198 FileNameOptionStorage::FileNameOptionStorage(const FileNameOption& settings, FileNameOptionManager* manager) :
199     MyBase(settings),
200     info_(this),
201     manager_(manager),
202     fileType_(-1),
203     defaultExtension_(""),
204     bRead_(settings.bRead_),
205     bWrite_(settings.bWrite_),
206     bLibrary_(settings.bLibrary_),
207     bAllowMissing_(settings.bAllowMissing_)
208 {
209     GMX_RELEASE_ASSERT(!hasFlag(efOption_MultipleTimes),
210                        "allowMultiple() is not supported for file name options");
211     if (settings.optionType_ == OptionFileType::Count && settings.legacyType_ >= 0)
212     {
213         fileType_ = settings.legacyType_;
214     }
215     else
216     {
217         for (auto i : keysOf(sc_fileTypeMapping))
218         {
219             if (i == settings.optionType_)
220             {
221                 fileType_ = sc_fileTypeMapping[i];
222                 break;
223             }
224         }
225     }
226     FileTypeHandler typeHandler(fileType_);
227     if (settings.defaultType_ >= 0 && settings.defaultType_ < efNR)
228     {
229         // This also assures that the default type is not a generic type.
230         GMX_RELEASE_ASSERT(typeHandler.isValidType(settings.defaultType_),
231                            "Default type for a file option is not an accepted "
232                            "type for the option");
233         FileTypeHandler defaultHandler(settings.defaultType_);
234         defaultExtension_ = defaultHandler.extension(0);
235     }
236     else if (typeHandler.extensionCount() > 0)
237     {
238         defaultExtension_ = typeHandler.extension(0);
239     }
240     if (settings.defaultBasename_ != nullptr)
241     {
242         std::string defaultValue(settings.defaultBasename_);
243         int         type = fn2ftp(settings.defaultBasename_);
244         GMX_RELEASE_ASSERT(type == efNR || type == settings.defaultType_,
245                            "Default basename has an extension that does not "
246                            "match the default type");
247         if (type == efNR)
248         {
249             defaultValue.append(defaultExtension());
250         }
251         setDefaultValueIfSet(defaultValue);
252         if (isRequired() || settings.bLegacyOptionalBehavior_)
253         {
254             setDefaultValue(defaultValue);
255         }
256     }
257 }
258
259 std::string FileNameOptionStorage::typeString() const
260 {
261     FileTypeHandler typeHandler(fileType_);
262     std::string     result;
263     int             count;
264     for (count = 0; count < 2 && count < typeHandler.extensionCount(); ++count)
265     {
266         if (count > 0)
267         {
268             result.append("/");
269         }
270         result.append(typeHandler.extension(count));
271     }
272     if (count < typeHandler.extensionCount())
273     {
274         result.append("/...");
275     }
276     if (result.empty())
277     {
278         if (isDirectoryOption())
279         {
280             result = "dir";
281         }
282         else
283         {
284             result = "file";
285         }
286     }
287     return result;
288 }
289
290 std::string FileNameOptionStorage::formatExtraDescription() const
291 {
292     FileTypeHandler typeHandler(fileType_);
293     std::string     result;
294     if (typeHandler.extensionCount() > 2)
295     {
296         result.append(":");
297         for (int i = 0; i < typeHandler.extensionCount(); ++i)
298         {
299             result.append(" [REF]");
300             // Skip the dot.
301             result.append(typeHandler.extension(i) + 1);
302             result.append("[ref]");
303         }
304     }
305     return result;
306 }
307
308 std::string FileNameOptionStorage::formatSingleValue(const std::string& value) const
309 {
310     return value;
311 }
312
313 void FileNameOptionStorage::initConverter(ConverterType* /*converter*/) {}
314
315 std::string FileNameOptionStorage::processValue(const std::string& value) const
316 {
317     if (manager_ != nullptr)
318     {
319         std::string processedValue = manager_->completeFileName(value, info_);
320         if (!processedValue.empty())
321         {
322             // If the manager returns a value, use it without further checks,
323             // except for sanity checking.
324             if (!isDirectoryOption())
325             {
326                 const int fileType = fn2ftp(processedValue.c_str());
327                 if (fileType == efNR)
328                 {
329                     // If the manager returned an invalid file name, assume
330                     // that it knows what it is doing.  But assert that it
331                     // only does that for the only case that it is currently
332                     // required for: VMD plugins.
333                     GMX_ASSERT(isInputFile() && isTrajectoryOption(),
334                                "Manager returned an invalid file name");
335                 }
336                 else
337                 {
338                     GMX_ASSERT(isValidType(fileType), "Manager returned an invalid file name");
339                 }
340             }
341             return processedValue;
342         }
343     }
344     // Currently, directory options are simple, and don't need any
345     // special processing.
346     // TODO: Consider splitting them into a separate DirectoryOption.
347     if (isDirectoryOption())
348     {
349         return value;
350     }
351     const int fileType = fn2ftp(value.c_str());
352     if (fileType == efNR)
353     {
354         std::string message = formatString(
355                 "File '%s' cannot be used by GROMACS because it "
356                 "does not have a recognizable extension.\n"
357                 "The following extensions are possible for this option:\n  %s",
358                 value.c_str(),
359                 joinStrings(extensions(), ", ").c_str());
360         GMX_THROW(InvalidInputError(message));
361     }
362     else if (!isValidType(fileType))
363     {
364         std::string message = formatString(
365                 "File name '%s' cannot be used for this option.\n"
366                 "Only the following extensions are possible:\n  %s",
367                 value.c_str(),
368                 joinStrings(extensions(), ", ").c_str());
369         GMX_THROW(InvalidInputError(message));
370     }
371     return value;
372 }
373
374 void FileNameOptionStorage::processAll()
375 {
376     if (manager_ != nullptr && hasFlag(efOption_HasDefaultValue))
377     {
378         ArrayRef<std::string> valueList = values();
379         GMX_RELEASE_ASSERT(valueList.size() == 1, "There should be only one default value");
380         if (!valueList[0].empty())
381         {
382             const std::string& oldValue = valueList[0];
383             GMX_ASSERT(endsWith(oldValue, defaultExtension()),
384                        "Default value does not have the expected extension");
385             const std::string prefix   = stripSuffixIfPresent(oldValue, defaultExtension());
386             const std::string newValue = manager_->completeDefaultFileName(prefix, info_);
387             if (!newValue.empty() && newValue != oldValue)
388             {
389                 GMX_ASSERT(isValidType(fn2ftp(newValue.c_str())),
390                            "Manager returned an invalid default value");
391                 valueList[0] = newValue;
392             }
393         }
394     }
395 }
396
397 bool FileNameOptionStorage::isDirectoryOption() const
398 {
399     return fileType_ == efRND;
400 }
401
402 bool FileNameOptionStorage::isTrajectoryOption() const
403 {
404     return fileType_ == efTRX;
405 }
406
407 const char* FileNameOptionStorage::defaultExtension() const
408 {
409     return defaultExtension_;
410 }
411
412 std::vector<const char*> FileNameOptionStorage::extensions() const
413 {
414     FileTypeHandler          typeHandler(fileType_);
415     std::vector<const char*> result;
416     result.reserve(typeHandler.extensionCount());
417     for (int i = 0; i < typeHandler.extensionCount(); ++i)
418     {
419         result.push_back(typeHandler.extension(i));
420     }
421     return result;
422 }
423
424 bool FileNameOptionStorage::isValidType(int fileType) const
425 {
426     FileTypeHandler typeHandler(fileType_);
427     return typeHandler.isValidType(fileType);
428 }
429
430 ArrayRef<const int> FileNameOptionStorage::fileTypes() const
431 {
432     if (fileType_ < 0)
433     {
434         return ArrayRef<const int>();
435     }
436     const int genericTypeCount = ftp2generic_count(fileType_);
437     if (genericTypeCount > 0)
438     {
439         return constArrayRefFromArray<int>(ftp2generic_list(fileType_), genericTypeCount);
440     }
441     return constArrayRefFromArray<int>(&fileType_, 1);
442 }
443
444 /********************************************************************
445  * FileNameOptionInfo
446  */
447
448 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage* option) : OptionInfo(option) {}
449
450 const FileNameOptionStorage& FileNameOptionInfo::option() const
451 {
452     return static_cast<const FileNameOptionStorage&>(OptionInfo::option());
453 }
454
455 bool FileNameOptionInfo::isInputFile() const
456 {
457     return option().isInputFile();
458 }
459
460 bool FileNameOptionInfo::isOutputFile() const
461 {
462     return option().isOutputFile();
463 }
464
465 bool FileNameOptionInfo::isInputOutputFile() const
466 {
467     return option().isInputOutputFile();
468 }
469
470 bool FileNameOptionInfo::isLibraryFile() const
471 {
472     return option().isLibraryFile();
473 }
474
475 bool FileNameOptionInfo::allowMissing() const
476 {
477     return option().allowMissing();
478 }
479
480 bool FileNameOptionInfo::isDirectoryOption() const
481 {
482     return option().isDirectoryOption();
483 }
484
485 bool FileNameOptionInfo::isTrajectoryOption() const
486 {
487     return option().isTrajectoryOption();
488 }
489
490 const char* FileNameOptionInfo::defaultExtension() const
491 {
492     return option().defaultExtension();
493 }
494
495 FileNameOptionInfo::ExtensionList FileNameOptionInfo::extensions() const
496 {
497     return option().extensions();
498 }
499
500 bool FileNameOptionInfo::isValidType(int fileType) const
501 {
502     return option().isValidType(fileType);
503 }
504
505 ArrayRef<const int> FileNameOptionInfo::fileTypes() const
506 {
507     return option().fileTypes();
508 }
509
510 /********************************************************************
511  * FileNameOption
512  */
513
514 AbstractOptionStorage* FileNameOption::createStorage(const OptionManagerContainer& managers) const
515 {
516     return new FileNameOptionStorage(*this, managers.get<FileNameOptionManager>());
517 }
518
519 } // namespace gmx