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