BDSIM
BDSIM is a Geant4 extension toolkit for simulation of particle transport in accelerator beamlines.
Loading...
Searching...
No Matches
SelectionLoader.cc
1/*
2Beam Delivery Simulation (BDSIM) Copyright (C) Royal Holloway,
3University of London 2001 - 2023.
4
5This file is part of BDSIM.
6
7BDSIM is free software: you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published
9by the Free Software Foundation version 3 of the License.
10
11BDSIM is distributed in the hope that it will be useful, but
12WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with BDSIM. If not, see <http://www.gnu.org/licenses/>.
18*/
19#include "SelectionLoader.hh"
20
21#include <algorithm>
22#include <fstream>
23#include <iostream>
24#include <regex>
25#include <stdexcept>
26#include <string>
27#include <vector>
28
29std::string RBDS::LoadSelection(const std::string& selectionFile)
30{
31 std::ifstream f(selectionFile.c_str());
32 if(!f)
33 {throw std::invalid_argument("LoadSelection> could not open file " + selectionFile);}
34
35 int lineCounter = 0;
36 std::string line;
37
38 // unique patterns to match
39 // match a line starting with #
40 std::regex comment("^\\#.*");
41
42 std::string selection;
43 while(std::getline(f, line))
44 {
45 lineCounter++;
46 if (std::all_of(line.begin(), line.end(), isspace))
47 {continue;} // skip empty lines
48 else if (std::regex_search(line, comment))
49 {continue;} // skip lines starting with '#'
50 else
51
52 {
53 if (!selection.empty())
54 {throw std::invalid_argument("Multiple selections (non-empty lines) found in file - only one should be specified.");}
55 std::vector<std::string> results;
56 std::regex wspace("\\s+"); // any whitespace
57 // -1 here makes it point to the suffix, ie the word rather than the wspace
58 std::sregex_token_iterator iter(line.begin(), line.end(), wspace, -1);
59 std::sregex_token_iterator end;
60 for (; iter != end; ++iter)
61 {
62 std::string res = (*iter).str();
63 if (res.empty())
64 {continue;}
65 results.push_back(res);
66 }
67 if (results.size() != 1)
68 {
69 std::cerr << "Error on line " << lineCounter << "\"" << line << "\"" << std::endl;
70 throw std::invalid_argument("More than one word on line -> no white space allowed");
71 }
72 else
73 {selection = results[0];}
74 }
75 }
76
77 f.close();
78
79 return selection;
80}
std::string LoadSelection(const std::string &selectionFile)
Load a selection from a text file.