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