ParameterTie.cpp 5.54 KB
Newer Older
1
#include "MantidAPI/CompositeFunction.h"
2
#include "MantidAPI/ParameterTie.h"
3
#include "MantidGeometry/muParser_Silent.h"
4

5
#include <boost/lexical_cast.hpp>
6
#include <boost/regex.hpp>
7

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace Mantid {
namespace API {

/** Constructor
 * @param funct :: A pointer to the function which parameter will be tied
 * @param parName :: The name of the parameter to be tied
 * @param expr :: A mathematical expression for the tie
 * @param isDefault :: Flag to mark as default the value of an object associated
 * with this reference: a tie or a constraint.
 */
ParameterTie::ParameterTie(IFunction *funct, const std::string &parName,
                           const std::string &expr, bool isDefault)
    : ParameterReference(funct, funct->parameterIndex(parName), isDefault),
      m_parser(new mu::Parser()), m_function1(funct) {
  m_parser->DefineNameChars("0123456789_."
                            "abcdefghijklmnopqrstuvwxyz"
                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  m_parser->SetVarFactory(AddVariable, this);
  if (!expr.empty()) {
    set(expr);
28
  }
29
30
31
32
33
34
35
36
}

/// Destructor
ParameterTie::~ParameterTie() {
  for (std::map<double *, ParameterReference>::const_iterator it =
           m_varMap.begin();
       it != m_varMap.end(); ++it) {
    delete it->first;
37
  }
38
39
40
41
42
43
44
45
46
  delete m_parser;
}

/** Static callback function used by MuParser to initialize variables implicitly
 * @param varName :: The name of a new variable
 * @param palg :: Pointer to this ParameterTie
 * @return pointer to added variable
 */
double *ParameterTie::AddVariable(const char *varName, void *palg) {
47
  ParameterTie &tie = *reinterpret_cast<ParameterTie *>(palg);
48
49
50
  ParameterReference ref(tie.m_function1,
                         tie.m_function1->parameterIndex(std::string(varName)));

51
  auto var = new double;
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  *var = 0;
  tie.m_varMap[var] = ref;

  return var;
}

/**
 * Set tie expression
 * @param expr :: A math expression
 */
void ParameterTie::set(const std::string &expr) {
  for (std::map<double *, ParameterReference>::const_iterator it =
           m_varMap.begin();
       it != m_varMap.end(); ++it) {
    delete it->first;
  }
68
  if (!m_varMap.empty()) {
69
70
71
72
73
74
75
76
77
78
79
80
    m_varMap.clear();
  }
  try { // Set the expression and initialize the variables
    m_parser->SetExpr(expr);
    m_parser->Eval();
  } catch (Kernel::Exception::NotImplementedError &) {
    throw std::invalid_argument(
        "Function index was not specified in a parameter name");
  } catch (std::exception &) {
    throw;
  } catch (...) {
    throw std::runtime_error("Error in expresseion " + expr);
81
82
  }

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  // Create the template m_expression
  boost::regex rx("\\b(([[:alpha:]]|_)([[:alnum:]]|_|\\.)*)\\b(?!(\\s*\\())");
  std::string input = expr;
  boost::smatch res;
  std::string::const_iterator start = input.begin();
  std::string::const_iterator end = input.end();

  std::map<std::string, int> varNames;
  int i = 0;
  for (std::map<double *, ParameterReference>::const_iterator it =
           m_varMap.begin();
       it != m_varMap.end(); ++it) {
    varNames[m_function1->parameterName(
        m_function1->getParameterIndex(it->second))] = i;
    i++;
  }
99

100
101
102
  m_expression = "";
  while (boost::regex_search(start, end, res, rx)) {
    m_expression.append(start, res[0].first);
103
    m_expression += "#" + std::to_string(varNames[res[1]]);
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    start = res[0].second;
  }
  m_expression.append(start, end);
}

double ParameterTie::eval() {
  double res = 0;
  try {
    for (std::map<double *, ParameterReference>::const_iterator it =
             m_varMap.begin();
         it != m_varMap.end(); ++it) {
      *(it->first) = it->second.getParameter();
    }
    res = m_parser->Eval();
  } catch (...) {
    throw std::runtime_error("Error in expresseion");
120
121
  }

122
  setParameter(res);
123

124
125
  return res;
}
126

127
128
129
130
131
132
133
134
/**
 * All parameters in the tie must be parameters of fun.
 * @param fun :: Function that can re-create the tie from the output string.
 * @return string representation of function
 */
std::string ParameterTie::asString(const IFunction *fun) const {
  if (!fun) {
    fun = m_function1;
135
  }
136
137
138
  std::string res_expression;
  try {
    res_expression = fun->parameterName(fun->getParameterIndex(*this)) + "=";
139

140
    if (m_varMap.empty()) { // constants
141
142
      return res_expression + m_expression;
      ;
143
144
    }

145
146
147
148
149
150
151
152
153
154
    boost::regex rx(std::string("#(\\d+)"));
    boost::smatch res;
    std::string::const_iterator start = m_expression.begin();
    std::string::const_iterator end = m_expression.end();

    while (boost::regex_search(start, end, res, rx)) {
      res_expression.append(start, res[0].first);

      int iTemp = boost::lexical_cast<int>(res[1]);
      int i = 0;
Hahn, Steven's avatar
Hahn, Steven committed
155
      for (const auto &var : m_varMap) {
156
157
        if (i == iTemp) {
          res_expression +=
Hahn, Steven's avatar
Hahn, Steven committed
158
              fun->parameterName(fun->getParameterIndex(var.second));
159
          break;
160
        }
161
        i++;
162
      }
163
164

      start = res[0].second;
165
    }
166
167
168
    res_expression.append(start, end);
  } catch (...) { // parameters are not from function fun
    res_expression = "";
169
  }
170
171
172
173
174
175
176
177
178
  return res_expression;
}

/** This method takes a list of double pointers and checks if any of them match
 * to the variables defined in the internal mu::Parser
 * @param fun :: A function
 * @return True if any of the parameters is used as a variable in the mu::Parser
 */
bool ParameterTie::findParametersOf(const IFunction *fun) const {
Hahn, Steven's avatar
Hahn, Steven committed
179
180
  for (const auto &varPair : m_varMap) {
    if (varPair.second.getFunction() == fun) {
181
      return true;
182
183
    }
  }
184

185
186
187
188
189
190
191
  return false;
}

/**
 * Check if the tie is a constant.
 */
bool ParameterTie::isConstant() const { return m_varMap.empty(); }
192

193
194
} // namespace CurveFitting
} // namespace Mantid