Files
musrfit/src/tests/spirit/PFunctionHandler.cpp
Andreas Suter e4ff8ca7d5
All checks were successful
Build and Deploy Documentation / build-and-deploy (push) Successful in 19s
added doxygen docu to spirit X3 under tests.
2025-12-27 13:57:14 +01:00

457 lines
16 KiB
C++

/***************************************************************************
PFunctionHandler.cpp
Author: Andreas Suter
e-mail: andreas.suter@psi.ch
***************************************************************************/
/***************************************************************************
* Copyright (C) 2007-2026 by Andreas Suter *
* andreas.suter@psi.c *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <string>
#include <cassert>
#include <algorithm>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include "PFunctionHandler.h"
//-------------------------------------------------------------
/**
* @brief Constructs a PFunctionHandler from a file.
*
* Reads the specified file to extract parameter values (PAR block),
* map indices (MAP block), and function definitions (FUNCTIONS block).
* Validates that all required blocks are present and that map indices
* are within parameter bounds.
*
* @param fln Filename containing the function definitions
* @param debug Enable debug output showing parsing details
*/
//-------------------------------------------------------------
PFunctionHandler::PFunctionHandler(char *fln, bool debug) : fDebug(debug), fFileName(fln)
{
fValid = true;
std::cout << std::endl << "in PFunctionHandler(char *fln)";
std::cout << std::endl << "fFileName = " << fFileName;
fValid = ReadFile();
if (fValid)
fValid = MapsAreValid();
}
//-------------------------------------------------------------
/**
* @brief Constructs a PFunctionHandler from a vector of input lines.
*
* Parses the provided lines to extract PAR, MAP, and FUNCTIONS blocks.
* This constructor is useful for testing or when input comes from
* sources other than files. Validates that all required blocks are
* present and that map indices are within parameter bounds.
*
* @param lines Vector of strings containing the input (PAR, MAP, FUNCTIONS blocks)
*/
//-------------------------------------------------------------
PFunctionHandler::PFunctionHandler(std::vector<std::string> lines)
{
fValid = true;
fFileName = "";
std::cout << std::endl << "in PFunctionHandler(std::vector<std::string> lines)";
if (lines.size() == 0) {
fValid = false;
return;
}
// analyze input
bool done = false;
int status;
int val[10];
double dval[10];
bool inFcnBlock = false;
for (unsigned int i=0; i<lines.size(); i++) {
if (lines[i].find("#") == 0) // comment hence ignore
continue;
boost::to_upper(lines[i]);
if (lines[i].find("PAR") == 0) {
std::cout << std::endl << "this is a parameter line ...";
status = sscanf(lines[i].c_str(), "PAR %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&dval[0], &dval[1], &dval[2], &dval[3], &dval[4],
&dval[5], &dval[6], &dval[7], &dval[8], &dval[9]);
std::cout << std::endl << "status=" << status;
if (status < 0) {
done = true;
fValid = false;
std::cout << std::endl << "invalid PAR line, sorry ...";
} else { // fill par
std::cout << std::endl << "PAR line, status = " << status;
for (int i=0; i<status; i++)
fParam.push_back(dval[i]);
std::cout << std::endl << "fParam.size()=" << fParam.size() << std::endl;
for (unsigned int i=0; i<fParam.size(); i++)
std::cout << std::endl << "Par" << i+1 << " = " << fParam[i];
std::cout << std::endl;
}
} else if (lines[i].find("MAP") == 0) {
std::cout << std::endl << "this is a map line ...";
status = sscanf(lines[i].c_str(), "MAP %d %d %d %d %d %d %d %d %d %d",
&val[0], &val[1], &val[2], &val[3], &val[4],
&val[5], &val[6], &val[7], &val[8], &val[9]);
if (status < 0) {
done = true;
fValid = false;
std::cout << std::endl << "invalid MAP line, sorry ...";
} else { // fill map
std::cout << std::endl << "MAP line, status = " << status;
for (int i=0; i<status; i++)
fMap.push_back(val[i]);
}
} else if (lines[i].find("FUNCTIONS") == 0) {
std::cout << std::endl << "the functions block start ...";
inFcnBlock = true;
} else if (lines[i].find("END") == 0) {
std::cout << std::endl << "end tag found; rest will be ignored";
done = true;
} else if (inFcnBlock) {
fLines.push_back(lines[i]);
}
}
// check if all blocks are given
if ((fMap.size() == 0) || (fParam.size() == 0) || (fLines.size() == 0)) {
if (fMap.size() == 0)
std::cout << std::endl << "MAP block is missing ...";
if (fParam.size() == 0)
std::cout << std::endl << "PAR block is missing ...";
if (fLines.size() == 0)
std::cout << std::endl << "FUNCTION block is missing ...";
fValid = false;
}
fValid = MapsAreValid();
if (fValid) {
std::cout << std::endl << "Functions: ";
for (unsigned int i=0; i<fLines.size(); i++)
std::cout << std::endl << fLines[i];
}
}
//-------------------------------------------------------------
/**
* @brief Destructor - releases all resources.
*
* Clears parameter, map, line, and function vectors to free memory.
*/
//-------------------------------------------------------------
PFunctionHandler::~PFunctionHandler()
{
std::cout << std::endl << "in ~PFunctionHandler()" << std::endl << std::endl;
fParam.clear();
fMap.clear();
fLines.clear();
fFuncs.clear();
}
//-------------------------------------------------------------
/**
* @brief Parses all function definitions using the X3 grammar.
*
* Iterates through all function lines, parsing each with the Spirit X3
* grammar to create PFunction objects. Performs validation checks:
* - All functions parse successfully
* - Parameter and map indices are within bounds
* - Function numbers are unique (no duplicates)
*
* @return true if all functions parsed and validated successfully
*/
//-------------------------------------------------------------
bool PFunctionHandler::DoParse()
{
std::cout << std::endl << "in PFunctionHandler::DoParse() ...";
bool success = true;
for (unsigned int i=0; i<fLines.size(); i++) {
std::cout << std::endl << "fLines[" << i << "] = '" << fLines[i] << "'";
// Convert to uppercase (grammar expects uppercase tokens)
std::string line = fLines[i];
std::transform(line.begin(), line.end(), line.begin(), ::toupper);
// Use new Qi-based PFunction constructor
PFunction func(line, fParam, fMap, fDebug);
if (func.IsValid()) {
std::cout << std::endl << "parse successfull ..." << std::endl;
fFuncs.push_back(func);
} else {
std::cout << std::endl << "parse failed ... (" << i << ")" << std::endl;
success = false;
break;
}
}
// check that all functions are valid. It could be that parsing was fine but
// the parameter index, or map index was out of range
if (success) {
for (unsigned int i=0; i<fFuncs.size(); i++) {
if (!fFuncs[i].IsValid()) {
std::cout << std::endl << "**ERROR**: function fun" << fFuncs[i].GetFuncNo();
std::cout << " has a problem with either parameter or map out of range!";
success = false;
break;
}
}
}
// check that the function numbers are unique
if (success) {
for (unsigned int i=0; i<fFuncs.size(); i++) {
for (unsigned int j=i+1; j<fFuncs.size(); j++) {
if (fFuncs[i].GetFuncNo() == fFuncs[j].GetFuncNo()) {
std::cout << std::endl << "**ERROR**: function number " << fFuncs[i].GetFuncNo();
std::cout << " is at least twice present! Fix this first.";
success = false;
}
}
}
}
if (success) {
for (unsigned int i=0; i<fFuncs.size(); i++)
std::cout << std::endl << "func number = " << fFuncs[i].GetFuncNo();
}
return success;
}
//-------------------------------------------------------------
/**
* @brief Evaluates a function by its function number.
*
* Looks up the function in the internal vector using its function number
* (from the FUN# declaration) and evaluates it with current parameter values.
*
* @param i Function number to evaluate
* @return The evaluation result, or 0.0 if function not found
*/
//-------------------------------------------------------------
double PFunctionHandler::Eval(int i)
{
if (GetFuncIndex(i) == -1) {
std::cout << std::endl << "**ERROR**: Couldn't find FUN" << i << " for evaluation";
return 0.0;
}
return fFuncs[GetFuncIndex(i)].Eval();
}
//-------------------------------------------------------------
/**
* @brief Gets the function number of the i-th parsed function.
*
* @param i Index into the internal function vector (0-based)
* @return The function number (from FUN#), or -1 if index out of bounds
*/
//-------------------------------------------------------------
unsigned int PFunctionHandler::GetFuncNo(unsigned int i)
{
if (i > fFuncs.size())
return -1;
return fFuncs[i].GetFuncNo();
}
//-------------------------------------------------------------
/**
* @brief Reads and parses the input file.
*
* Opens the file specified in fFileName and extracts:
* - PAR block: parameter values (up to 10 per line)
* - MAP block: map indices (up to 10 per line)
* - FUNCTIONS block: function definition lines
*
* Lines starting with # are treated as comments and ignored.
* Processing stops when END tag is encountered.
* Converts all input to uppercase for case-insensitive parsing.
*
* @return true if file was successfully read and all required blocks found
*/
//-------------------------------------------------------------
bool PFunctionHandler::ReadFile()
{
std::cout << std::endl << "in ~PFunctionHandler::ReadFile()";
if (fFileName.length() == 0) {
std::cout << std::endl << "PFunctionHandler::ReadFile(): **ERROR**";
std::cout << std::endl << " no file name given :-(. Will quit";
return false;
}
std::ifstream f;
f.open(fFileName.c_str(), std::ifstream::in);
if (!f.is_open()) {
std::cout << std::endl << "PFunctionHandler::ReadFile(): **ERROR**";
std::cout << std::endl << " File '" << fFileName.c_str() << "' couldn't being opened.";
return false;
}
std::string line;
char c_line[128];
bool done = false;
bool success = true;
int status;
int val[10];
double dval[10];
bool inFcnBlock = false;
while ( !f.eof() && !done) {
f.getline(c_line, 128); // line of text excluding '\n'
line = c_line;
size_t pos = line.find('\r');
line.resize(pos);
if (line.find("#") == 0) // comment hence ignore
continue;
boost::to_upper(line);
if (line.find("PAR") == 0) {
std::cout << std::endl << "this is a parameter line ...";
status = sscanf(line.c_str(), "PAR %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&dval[0], &dval[1], &dval[2], &dval[3], &dval[4],
&dval[5], &dval[6], &dval[7], &dval[8], &dval[9]);
if (status < 0) {
done = true;
success = false;
std::cout << std::endl << "invalid PAR line, sorry ...";
} else { // fill map
std::cout << std::endl << "PAR line, status = " << status;
for (int i=0; i<status; i++)
fParam.push_back(dval[i]);
for (unsigned int i=0; i<fParam.size(); i++)
std::cout << std::endl << "Par" << i+1 << " = " << fParam[i];
std::cout << std::endl;
}
} else if (line.find("MAP") == 0) {
std::cout << std::endl << "this is a map line ...";
status = sscanf(line.c_str(), "MAP %d %d %d %d %d %d %d %d %d %d",
&val[0], &val[1], &val[2], &val[3], &val[4],
&val[5], &val[6], &val[7], &val[8], &val[9]);
if (status < 0) {
done = true;
success = false;
std::cout << std::endl << "invalid MAP line, sorry ...";
} else { // fill map
std::cout << std::endl << "MAP line, status = " << status;
for (int i=0; i<status; i++)
fMap.push_back(val[i]);
}
} else if (line.find("FUNCTIONS") == 0) {
std::cout << std::endl << "the functions block start ...";
inFcnBlock = true;
} else if (line.find("END") == 0) {
std::cout << std::endl << "end tag found; rest will be ignored";
done = true;
} else if (inFcnBlock) {
fLines.push_back(line);
}
}
f.close();
// check if all blocks are given
if ((fMap.size() == 0) || (fParam.size() == 0) || (fLines.size() == 0)) {
if (fMap.size() == 0)
std::cout << std::endl << "MAP block is missing ...";
if (fParam.size() == 0)
std::cout << std::endl << "PAR block is missing ...";
if (fLines.size() == 0)
std::cout << std::endl << "FUNCTION block is missing ...";
success = false;
}
if (success) {
std::cout << std::endl << "Functions: ";
for (unsigned int i=0; i<fLines.size(); i++)
std::cout << std::endl << fLines[i];
}
return success;
}
//-------------------------------------------------------------
/**
* @brief Validates that all map indices are within parameter bounds.
*
* Checks that each value in the MAP block is a valid parameter index.
* Map values use 1-based indexing, so valid values are 1 to fParam.size().
* This validation prevents out-of-bounds access during function evaluation.
*
* @return true if all map indices are valid, false otherwise
*/
//-------------------------------------------------------------
bool PFunctionHandler::MapsAreValid()
{
bool success = true;
int maxParam = fParam.size();
for (unsigned int i=0; i<fMap.size(); i++)
if (fMap[i] > maxParam)
success = false;
if (!success)
std::cout << std::endl << "invalid MAP found ...";
return success;
}
//-------------------------------------------------------------
/**
* @brief Finds the internal vector index for a function by its number.
*
* Searches the fFuncs vector for a function with the specified function
* number. This maps from the user-visible function number (FUN#) to the
* internal 0-based vector index.
*
* @param funcNo Function number to search for (from FUN# declaration)
* @return Index in fFuncs vector (0-based), or -1 if not found
*/
//-------------------------------------------------------------
int PFunctionHandler::GetFuncIndex(int funcNo)
{
int index = -1;
for (unsigned int i=0; i<fFuncs.size(); i++) {
if (fFuncs[i].GetFuncNo() == funcNo) {
index = i;
break;
}
}
return index;
}