3#include "Utility/PAssert.h"
52namespace fs = std::filesystem;
54#define REGISTER_PARSE_TYPE(X) \
56 struct Fieldmap::TypeParseTraits<X> { \
57 static const char* name; \
59 const char* Fieldmap::TypeParseTraits<X>::name = #X
73 std::map<std::string, FieldmapDescription>::iterator position =
77 (*position).second.RefCounter++;
79 return (*position).second.Map;
82 std::pair<std::map<std::string, FieldmapDescription>::iterator,
bool> position;
99 return (*position.first).second.Map;
107 return (*position.first).second.Map;
121 return (*position.first).second.Map;
138 return (*position.first).second.Map;
143 "Fieldmap::getFieldmap()",
144 "Couldn't determine type of fieldmap in file \"" + Filename +
"\"");
150 std::vector<std::string> name_list;
151 for (std::map<std::string, FieldmapDescription>::const_iterator it =
FieldmapDictionary.begin();
153 name_list.push_back((*it).first);
163 delete it->second.Map;
164 it->second.Map =
nullptr;
175 char magicnumber[5] =
" ";
180 if (Filename ==
"1DPROFILE1-DEFAULT")
return T1DProfile1;
182 if (Filename.empty())
185 if (!fs::exists(Filename))
187 "Fieldmap::readHeader()",
"File '" + Filename +
"' doesn't exist");
189 std::ifstream File(Filename.c_str());
191 std::cerr <<
"could not open file " << Filename << std::endl;
196 std::istringstream interpreter(buffer, std::istringstream::in);
198 interpreter.read(magicnumber, 4);
200 if (std::strcmp(magicnumber,
"3DDy") == 0)
return T3DDynamic;
202 if (std::strcmp(magicnumber,
"3DMa") == 0) {
203 char tmpString[21] =
" ";
204 interpreter.read(tmpString, 20);
206 if (std::strcmp(tmpString,
"gnetoStatic_Extended") == 0)
214 if (std::strcmp(magicnumber,
"2DDy") == 0) {
220 if (std::strcmp(magicnumber,
"2DMa") == 0) {
226 if (std::strcmp(magicnumber,
"2DEl") == 0) {
232 if (std::strcmp(magicnumber,
"1DDy") == 0)
return T1DDynamic;
236 if (std::strcmp(magicnumber,
"1DPr") == 0) {
247 if (std::strcmp(magicnumber,
"\211HDF") == 0) {
248 h5_err_t h5err [[maybe_unused]] = 0;
250 h5_size_t len_name =
sizeof(name);
251 h5_prop_t props = H5CreateFileProp();
252 MPI_Comm comm = ippl::Comm->getCommunicator();
253 h5err = H5SetPropFileMPIOCollective(props, &comm);
254 PAssert(h5err != H5_ERR);
255 h5_file_t file = H5OpenFile(Filename.c_str(), H5_O_RDONLY, props);
256 PAssert(file != (h5_file_t)H5_ERR);
259 h5err = H5SetStep(file, 0);
260 PAssert(h5err != H5_ERR);
262 h5_int64_t num_fields = H5BlockGetNumFields(file);
263 PAssert(num_fields != H5_ERR);
266 for (h5_ssize_t i = 0; i < num_fields; ++i) {
267 h5err = H5BlockGetFieldInfo(
268 file, (h5_size_t)i, name, len_name,
nullptr,
nullptr,
nullptr,
nullptr);
269 PAssert(h5err != H5_ERR);
271 if (std::strcmp(name,
"Bfield") == 0) {
274 }
else if (std::strcmp(name,
"Hfield") == 0) {
279 h5err = H5CloseFile(file);
280 PAssert(h5err != H5_ERR);
281 if (maptype !=
UNKNOWN)
return maptype;
284 if (std::strcmp(magicnumber,
"Astr") == 0) {
285 char tmpString[3] =
" ";
286 interpreter.read(tmpString, 2);
287 if (std::strcmp(tmpString,
"aE") == 0) {
290 if (std::strcmp(tmpString,
"aM") == 0) {
293 if (std::strcmp(tmpString,
"aD") == 0) {
302 std::map<std::string, FieldmapDescription>::iterator position =
305 if (!(*position).second.read) {
306 (*position).second.Map->readMap();
307 (*position).second.read =
true;
312 std::map<std::string, FieldmapDescription>::iterator position =
318 if ((*position).second.RefCounter > 0) {
319 (*position).second.RefCounter--;
322 if ((*position).second.RefCounter == 0) {
323 delete (*position).second.Map;
324 (*position).second.Map =
nullptr;
331 unsigned int accuracy, std::pair<double, double> fieldDimensions,
double deltaZ,
332 const std::vector<double>& fourierCoefficients,
gsl_spline* splineCoefficients,
334 double length = fieldDimensions.second - fieldDimensions.first;
335 unsigned int sizeSampling = std::round(length / deltaZ);
336 std::vector<double> zSampling(sizeSampling);
337 zSampling[0] = fieldDimensions.first;
338 for (
unsigned int i = 1; i < sizeSampling; ++i) {
339 zSampling[i] = zSampling[i - 1] + deltaZ;
342 accuracy, length, zSampling, fourierCoefficients, splineCoefficients,
347 unsigned int accuracy,
double length,
const std::vector<double>& zSampling,
348 const std::vector<double>& fourierCoefficients,
gsl_spline* splineCoefficients,
351 double maxDiff = 0.0;
353 double ezSquare = 0.0;
354 size_t lastDot =
Filename_m.find_last_of(
".");
355 size_t lastSlash =
Filename_m.find_last_of(
"/");
356 lastSlash = (lastSlash == std::string::npos) ? 0 : lastSlash + 1;
360 if (ippl::Comm->rank() == 0 && !opal->isOptimizerRun()) {
362 {opal->getAuxiliaryOutputDirectory(),
363 Filename_m.substr(lastSlash, lastDot) +
".check"});
365 out <<
"# z original reproduced\n";
367 auto it = zSampling.begin();
368 auto end = zSampling.end();
369 for (; it != end; ++it) {
371 double onAxisFieldCheck = fourierCoefficients[0];
373 for (
unsigned int l = 1; l < accuracy; ++l, n += 2) {
374 double coskzl = std::cos(kz * l);
375 double sinkzl = std::sin(kz * l);
378 (fourierCoefficients[n] * coskzl - fourierCoefficients[n + 1] * sinkzl);
380 double ez =
gsl_spline_eval(splineCoefficients, *it, splineAccelerator);
381 double difference = std::abs(ez - onAxisFieldCheck);
382 maxDiff = difference > maxDiff ? difference : maxDiff;
383 ezMax = std::abs(ez) > ezMax ? std::abs(ez) : ezMax;
384 error += std::pow(difference, 2.0);
385 ezSquare += std::pow(ez, 2.0);
387 if (ippl::Comm->rank() == 0 && !opal->isOptimizerRun()) {
388 out << std::setw(16) << std::setprecision(8) << *it << std::setw(16)
389 << std::setprecision(8) << ez << std::setw(16) << std::setprecision(8)
390 << onAxisFieldCheck << std::endl;
395 if (std::sqrt(error / ezSquare) > 1e-1 || maxDiff > 1e-1 * ezMax) {
399 "Fieldmap::checkMap",
400 "Field map can't be reproduced properly with the given number of fourier "
403 if (std::sqrt(error / ezSquare) > 1e-2 || maxDiff > 1e-2 * ezMax) {
409 const double& ,
const double& ,
const double& ) {
424 size_t comment = buffer.find(
"#");
425 buffer = buffer.substr(0, comment);
429 }
while (!in.eof() && lastof == std::string::npos);
431 if (firstof != std::string::npos) {
432 buffer = buffer.substr(firstof, lastof - firstof + 1);
441 size_t comment = buffer.find_first_of(
"#");
442 buffer = buffer.substr(0, comment);
444 if (lasto != std::string::npos) {
453 const std::ios_base::iostate& state,
const bool& read_all,
const std::string& expecting,
454 const std::string& found) {
455 std::stringstream errormsg;
456 errormsg <<
"THERE SEEMS TO BE SOMETHING WRONG WITH YOUR FIELD MAP '" <<
Filename_m <<
"'.\n";
458 errormsg <<
"Didn't find enough values!" << std::endl;
459 }
else if (state & std::ios_base::eofbit) {
460 errormsg <<
"Found more values than expected!" << std::endl;
461 }
else if (state & std::ios_base::failbit) {
462 errormsg <<
"Found wrong type of values!"
464 <<
"expecting: '" << expecting <<
"' on line " <<
lines_read_m <<
",\n"
465 <<
"instead found: '" << found <<
"'." << std::endl;
471 std::stringstream errormsg;
472 errormsg <<
"THERE SEEMS TO BE SOMETHING WRONG WITH YOUR FIELD MAP '" <<
Filename_m <<
"'.\n"
473 <<
"There are only " <<
lines_read_m - 1 <<
" lines in the file, expecting more.\n"
474 <<
"Please check the section about field maps in the user manual.";
480 std::stringstream errormsg;
481 errormsg <<
"THERE SEEMS TO BE SOMETHING WRONG WITH YOUR FIELD MAP '" <<
Filename_m <<
"'.\n"
482 <<
"There are too many lines in the file, expecting only " <<
lines_read_m
484 <<
"Please check the section about field maps in the user manual.";
490 std::stringstream errormsg;
491 errormsg <<
"DISABLING FIELD MAP '" +
Filename_m +
"' DUE TO PARSING ERRORS.";
497 std::stringstream errormsg;
498 errormsg <<
"DISABLING FIELD MAP '" <<
Filename_m <<
"' SINCE FILE COULDN'T BE FOUND!";
504 std::stringstream errormsg;
505 errormsg <<
"IT SEEMS THAT YOU USE TOO FEW FOURIER COMPONENTS TO SUFFICIENTLY WELL\n"
506 <<
"RESOLVE THE FIELD MAP '" <<
Filename_m <<
"'.\n"
507 <<
"PLEASE INCREASE THE NUMBER OF FOURIER COMPONENTS!\n"
508 <<
"The ratio (e_i - E_i)^2 / E_i^2 is " << std::to_string(squareError) <<
" and\n"
509 <<
"the ratio (max_i(|e_i - E_i|) / max_i(|E_i|) is " << std::to_string(maxError)
511 <<
"Here E_i is the field as in the field map and e_i is the reconstructed field.\n"
512 <<
"The lower limit for the two ratios is 1e-2\n"
513 <<
"Have a look into the directory "
515 <<
" for a reconstruction of the field map.\n";
516 std::string errormsg_str =
typeset_msg(errormsg.str(),
"warning");
518 *ippl::Error << errormsg_str <<
"\n" << endl;
520 if (ippl::Comm->rank() == 0) {
521 std::ofstream omsg(
"errormsg.txt", std::ios_base::app);
522 omsg << errormsg.str() << std::endl;
528 static std::string frame(
529 "* ******************************************************************************\n");
530 static unsigned int frame_width = frame.length() - 5;
531 static std::string closure(
534 std::string return_string(
"\n" + frame);
536 int remaining_length = msg.length();
537 unsigned int current_position = 0;
540 for (; ii < title.length(); ++ii) {
543 return_string.replace(15 + 2 * ii, 1,
" ");
544 return_string.replace(16 + 2 * ii, 1, &c, 1);
546 return_string.replace(15 + 2 * ii, 1,
" ");
548 while (remaining_length > 0) {
549 size_t eol = msg.find(
"\n", current_position);
550 std::string next_to_process;
551 if (eol != std::string::npos) {
552 next_to_process = msg.substr(current_position, eol - current_position);
554 next_to_process = msg.substr(current_position);
558 if (eol - current_position < frame_width) {
559 return_string +=
"* " + next_to_process + closure.substr(eol - current_position + 2);
561 unsigned int last_space = next_to_process.rfind(
" ", frame_width);
562 if (last_space > 0) {
563 if (last_space < frame_width) {
564 return_string +=
"* " + next_to_process.substr(0, last_space)
565 + closure.substr(last_space + 2);
567 return_string +=
"* " + next_to_process.substr(0, last_space) +
" *\n";
569 if (next_to_process.length() - last_space + 1 < frame_width) {
570 return_string +=
"* " + next_to_process.substr(last_space + 1)
571 + closure.substr(next_to_process.length() - last_space + 1);
573 return_string +=
"* " + next_to_process.substr(last_space + 1) +
" *\n";
576 return_string +=
"* " + next_to_process +
" *\n";
580 current_position = eol + 1;
581 remaining_length = msg.length() - current_position;
583 return_string += frame;
585 return return_string;
591 std::vector<double>& , std::vector<double>& ) {}
598 double& ,
double& ,
double& ) {}
605 unsigned int nx,
unsigned int ny,
unsigned int nz,
const std::pair<double, double>& xrange,
606 const std::pair<double, double>& yrange,
const std::pair<double, double>& zrange,
608 const size_t numpoints = nx * ny * nz;
609 if (ippl::Comm->rank() != 0 || (ef.size() != numpoints && bf.size() != numpoints))
return;
616 PAssert(of.is_open());
619 const double hx = (xrange.second - xrange.first) / (nx - 1);
620 const double hy = (yrange.second - yrange.first) / (ny - 1);
621 const double hz = (zrange.second - zrange.first) / (nz - 1);
623 of <<
"# vtk DataFile Version 2.0" << std::endl;
624 of <<
"generated by 3D fieldmaps" << std::endl;
625 of <<
"ASCII" << std::endl << std::endl;
626 of <<
"DATASET RECTILINEAR_GRID" << std::endl;
627 of <<
"DIMENSIONS " << nx <<
" " << ny <<
" " << nz << std::endl;
629 of <<
"X_COORDINATES " << nx <<
" float" << std::endl;
631 for (
unsigned int i = 1; i < nx - 1; ++i) {
632 of <<
" " << xrange.first + i * hx;
634 of <<
" " << xrange.second << std::endl;
636 of <<
"Y_COORDINATES " << ny <<
" float" << std::endl;
638 for (
unsigned int i = 1; i < ny - 1; ++i) {
639 of <<
" " << yrange.first + i * hy;
641 of <<
" " << yrange.second << std::endl;
643 of <<
"Z_COORDINATES " << nz <<
" float" << std::endl;
645 for (
unsigned int i = 1; i < nz - 1; ++i) {
646 of <<
" " << zrange.first + i * hz;
648 of <<
" " << zrange.second << std::endl;
650 of <<
"POINT_DATA " << numpoints << std::endl;
652 if (ef.size() == numpoints) {
653 of <<
"VECTORS EField float" << std::endl;
655 for (
size_t i = 0; i < numpoints; ++i) {
656 of << ef[i](0) <<
" " << ef[i](1) <<
" " << ef[i](2) << std::endl;
661 if (bf.size() == numpoints) {
662 of <<
"VECTORS BField float" << std::endl;
664 for (
size_t i = 0; i < numpoints; ++i) {
665 of << bf[i](0) <<
" " << bf[i](1) <<
" " << bf[i](2) << std::endl;
677 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-+\211");
679 std::map<std::string, Fieldmap::FieldmapDescription>();
ippl::Vector< T, Dim > Vector_t
#define REGISTER_PARSE_TYPE(X)
#define READ_BUFFER_LENGTH
@ T3DMagnetoStatic_Extended
@ T3DMagnetoStaticH5Block
double gsl_spline_eval(const gsl_spline *spline, const double x, gsl_interp_accel *accel)
Evaluate a spline at x using an accelerator.
Accelerator caching last interval indices.
Base class for the linear and cubic interpolation spline classes.
Abstract base class for all field maps. It acts as a factory for creating specific field map types ba...
static Fieldmap * getFieldmap(std::string Filename, bool fast=false)
Get a field map instance. Use this factory method to obtain a field map. It checks the cache (Fieldma...
static void deleteFieldmap(std::string Filename)
Delete a specific field map from the cache and memory.
static std::string alpha_numeric
static std::map< std::string, FieldmapDescription > FieldmapDictionary
static MapType readHeader(std::string Filename)
Read the header of a field map file to determine its type.
bool interpreteEOF(std::ifstream &in)
virtual void setFieldLength(const double &)
virtual void freeMap()=0
Pure virtual method to free the map data.
void missingValuesWarning()
virtual void getOnaxisEz(std::vector< std::pair< double, double > > &onaxis)
virtual void get1DProfile1EntranceParam(double &entranceParameter1, double &entranceParameter2, double &entranceParameter3)
void checkMap(unsigned int accuracy, std::pair< double, double > fieldDimensions, double deltaZ, const std::vector< double > &fourierCoefficients, gsl_spline *splineCoefficients, gsl_interp_accel *splineAccelerator)
void lowResolutionWarning(double squareError, double maxError)
void interpretWarning(const std::ios_base::iostate &state, const bool &read_all, const std::string &error_msg, const std::string &found)
void disableFieldmapWarning()
static char buffer_m[256]
static std::vector< std::string > getListFieldmapNames()
Get a list of all loaded field map names.
static std::string typeset_msg(const std::string &msg, const std::string &title)
static void clearDictionary()
Clear the entire field map cache.
static void freeMap(std::string Filename)
Decrease reference count or delete field map if unused.
virtual double getFieldGap()
virtual void setEdgeConstants(const double &bendAngle, const double &entranceAngle, const double &exitAngle)
virtual void setFieldGap(double gap)
void exceedingValuesWarning()
virtual void get1DProfile1EngeCoeffs(std::vector< double > &engeCoeffsEntry, std::vector< double > &engeCoeffsExit)
void getLine(std::ifstream &in, std::string &buffer)
virtual void get1DProfile1ExitParam(double &exitParameter1, double &exitParameter2, double &exitParameter3)
static void readMap(std::string Filename)
Trigger the actual reading of the field map data.
void write3DField(unsigned int nx, unsigned int ny, unsigned int nz, const std::pair< double, double > &xrange, const std::pair< double, double > &yrange, const std::pair< double, double > &zrange, const std::vector< Vector_t< double, 3 > > &ef, const std::vector< Vector_t< double, 3 > > &bf)
static OpalData * getInstance()
std::string getAuxiliaryOutputDirectory() const
get the name of the the additional data directory
constexpr double two_pi
The value of.
std::string combineFilePath(std::initializer_list< std::string > ilist)