BDSIM
BDSIM is a Geant4 extension toolkit for simulation of particle transport in accelerator beamlines.
Loading...
Searching...
No Matches
BinLoader.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 "BinLoader.hh"
20#include "RBDSException.hh"
21
22#include <algorithm>
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <stdexcept>
27#include <string>
28#include <vector>
29
30std::vector<double>* RBDS::LoadBins(const std::string& fileName)
31{
32 std::ifstream file;
33 file.open(fileName);
34 bool validFile = file.is_open();
35
36 if (!validFile)
37 {throw RBDSException("Cannot open file \"" + fileName + "\"");}
38 else
39 {std::cout << "LoadBins> loading \"" << fileName << "\"" << std::endl;}
40
41 std::string line;
42 std::vector<double>* result = new std::vector<double>();
43 int lineNum = 1;
44 while (std::getline(file, line))
45 { // read a line only if it's not a blank one
46 std::istringstream liness(line);
47
48 // skip a line if it's only whitespace
49 if (std::all_of(line.begin(), line.end(), isspace))
50 {continue;}
51
52 double binEdge;
53 if (!(liness >> binEdge))
54 {throw RBDSException("invalid bin edge on line " + std::to_string(lineNum) + "\n\"" + line + "\"\nCannot convert to a double.");}
55 result->push_back(binEdge);
56
57 if (!liness.eof())
58 {
59 std::string remainder;
60 liness >> remainder;
61 std::string message = "Error: extra text \"" + remainder + "\" on line " + std::to_string(lineNum) + " of bin edges file \"" + fileName + "\"";
62 throw RBDSException(message);
63 }
64
65 lineNum += 1;
66 }
67
68 if (result->size() < 2)
69 {throw RBDSException("insufficient number of bins in file - must be at least 2");}
70
71 file.close();
72 return result;
73}
General exception with possible name of object and message.
std::vector< double > * LoadBins(const std::string &fileName)
Method to load a single column text file and return vector of values.
Definition: BinLoader.cc:30