MultiDomainFunction.cpp 12 KB
Newer Older
1
2
3
4
5
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidAPI/MultiDomainFunction.h"
#include "MantidAPI/CompositeDomain.h"
6
7
#include "MantidAPI/FunctionFactory.h"
#include "MantidAPI/Expression.h"
8
9
10
11

#include <boost/lexical_cast.hpp>
#include <set>

12
13
namespace Mantid {
namespace API {
14

15
DECLARE_FUNCTION(MultiDomainFunction)
16

17
18
19
20
21
22
23
24
25
26
/**
 * Associate a member function and a domain. The function will only be applied
 * to this domain.
 * @param funIndex :: Index of a member function.
 * @param domainIndex :: Index of a domain to be associated with the function.
 */
void MultiDomainFunction::setDomainIndex(size_t funIndex, size_t domainIndex) {
  m_domains[funIndex] = std::vector<size_t>(1, domainIndex);
  countNumberOfDomains();
}
27

28
29
30
31
32
33
34
35
36
37
38
39
40
/**
 * Associate a member function and a list of domains. The function will only be
 * applied
 * to the listed domains.
 * @param funIndex :: Index of a member function.
 * @param domainIndices :: A vector with indices of domains to be associated
 * with the function.
 */
void MultiDomainFunction::setDomainIndices(
    size_t funIndex, const std::vector<size_t> &domainIndices) {
  m_domains[funIndex] = domainIndices;
  countNumberOfDomains();
}
41

42
43
44
45
46
/**
 * Counts number of the domains.
 */
void MultiDomainFunction::countNumberOfDomains() {
  std::set<size_t> dSet;
Hahn, Steven's avatar
Hahn, Steven committed
47
  for (auto &domain : m_domains) {
48
    if (!domain.second.empty()) {
Hahn, Steven's avatar
Hahn, Steven committed
49
      dSet.insert(domain.second.begin(), domain.second.end());
50
51
    }
  }
52
53
54
  m_nDomains = dSet.size();
  m_maxIndex = dSet.empty() ? 0 : *dSet.rbegin();
}
55

56
57
58
/**
 * Count value offsets for each member domain in a CompositeDomain.
 */
59
60
void MultiDomainFunction::countValueOffsets(
    const CompositeDomain &domain) const {
61
62
63
64
65
  m_valueOffsets.clear();
  m_valueOffsets.push_back(0);
  for (size_t i = 0; i < domain.getNParts(); ++i) {
    const FunctionDomain &d = domain.getDomain(i);
    m_valueOffsets.push_back(m_valueOffsets.back() + d.size());
66
  }
67
}
68

69
70
71
72
73
/// Clear all domain indices
void MultiDomainFunction::clearDomainIndices() {
  m_domains.clear();
  countNumberOfDomains();
}
74

75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * Populates a vector with domain indices assigned to function i.
 * @param i :: Index of a function to get the domain info about.
 * @param nDomains :: Maximum number of domains.
 * @param domains :: (Output) vector to collect domain indixes.
 */
void MultiDomainFunction::getDomainIndices(size_t i, size_t nDomains,
                                           std::vector<size_t> &domains) const {
  auto it = m_domains.find(i);
  if (it == m_domains.end()) { // apply to all domains
    domains.resize(nDomains);
    for (size_t i = 0; i < domains.size(); ++i) {
      domains[i] = i;
    }
  } else { // apply to selected domains
    domains.assign(it->second.begin(), it->second.end());
91
  }
92
}
93

94
95
96
97
98
99
100
101
102
103
104
105
106
/// Function you want to fit to.
/// @param domain :: The buffer for writing the calculated values. Must be big
/// enough to accept dataSize() values
void MultiDomainFunction::function(const FunctionDomain &domain,
                                   FunctionValues &values) const {
  // works only on CompositeDomain
  if (!dynamic_cast<const CompositeDomain *>(&domain)) {
    throw std::invalid_argument(
        "Non-CompositeDomain passed to MultiDomainFunction.");
  }
  const CompositeDomain &cd = dynamic_cast<const CompositeDomain &>(domain);
  // domain must not have less parts than m_maxIndex
  if (cd.getNParts() <= m_maxIndex) {
107
108
109
110
    throw std::invalid_argument("CompositeDomain has too few parts (" +
                                std::to_string(cd.getNParts()) +
                                ") for MultiDomainFunction (max index " +
                                std::to_string(m_maxIndex) + ").");
111
112
113
114
115
116
  }
  // domain and values must be consistent
  if (cd.size() != values.size()) {
    throw std::invalid_argument(
        "MultiDomainFunction: domain and values have different sizes.");
  }
117

118
119
120
121
122
123
124
  countValueOffsets(cd);
  // evaluate member functions
  values.zeroCalculated();
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    // find the domains member function must be applied to
    std::vector<size_t> domains;
    getDomainIndices(iFun, cd.getNParts(), domains);
125

126
    for (auto &domain : domains) {
127
      const FunctionDomain &d = cd.getDomain(domain);
128
129
      FunctionValues tmp(d);
      getFunction(iFun)->function(d, tmp);
130
      values.addToCalculated(m_valueOffsets[domain], tmp);
131
132
    }
  }
133
}
134

135
136
137
138
139
140
141
142
/// Derivatives of function with respect to active parameters
void MultiDomainFunction::functionDeriv(const FunctionDomain &domain,
                                        Jacobian &jacobian) {
  // works only on CompositeDomain
  if (!dynamic_cast<const CompositeDomain *>(&domain)) {
    throw std::invalid_argument(
        "Non-CompositeDomain passed to MultiDomainFunction.");
  }
143

144
145
146
147
148
149
  if (getAttribute("NumDeriv").asBool()) {
    calNumericalDeriv(domain, jacobian);
  } else {
    const CompositeDomain &cd = dynamic_cast<const CompositeDomain &>(domain);
    // domain must not have less parts than m_maxIndex
    if (cd.getNParts() < m_maxIndex) {
150
151
152
153
      throw std::invalid_argument("CompositeDomain has too few parts (" +
                                  std::to_string(cd.getNParts()) +
                                  ") for MultiDomainFunction (max index " +
                                  std::to_string(m_maxIndex) + ").");
154
    }
155

156
157
158
159
160
161
162
    countValueOffsets(cd);
    // evaluate member functions derivatives
    for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
      // find the domains member function must be applied to
      std::vector<size_t> domains;
      getDomainIndices(iFun, cd.getNParts(), domains);

163
      for (auto &domain : domains) {
164
165
        const FunctionDomain &d = cd.getDomain(domain);
        PartialJacobian J(&jacobian, m_valueOffsets[domain], paramOffset(iFun));
166
167
        getFunction(iFun)->functionDeriv(d, J);
      }
168
169
    }
  }
170
}
171

172
173
174
175
176
177
178
/**
 * Called at the start of each iteration. Call iterationStarting() of the
 * members.
 */
void MultiDomainFunction::iterationStarting() {
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    getFunction(iFun)->iterationStarting();
179
  }
180
}
181

182
183
184
185
186
187
/**
 * Called at the end of an iteration. Call iterationFinished() of the members.
 */
void MultiDomainFunction::iterationFinished() {
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    getFunction(iFun)->iterationFinished();
188
  }
189
}
190

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/// Return a value of attribute attName
IFunction::Attribute
MultiDomainFunction::getLocalAttribute(size_t i,
                                       const std::string &attName) const {
  if (attName != "domains") {
    throw std::invalid_argument("MultiDomainFunction does not have attribute " +
                                attName);
  }
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index is out of range.");
  }
  try {
    auto it = m_domains.at(i);
    if (it.size() == 1 && it.front() == i) {
      return IFunction::Attribute("i");
    } else if (!it.empty()) {
      auto out = std::to_string(it.front());
      for (auto i = it.begin() + 1; i != it.end(); ++i) {
        out += "," + std::to_string(*i);
      }
      return IFunction::Attribute(out);
    }
  } catch (const std::out_of_range &) {
    return IFunction::Attribute("All");
  }
  return IFunction::Attribute("");
}

219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/**
 * Set a value to a "local" attribute, ie an attribute related to a member
 *function.
 *
 * The only attribute that can be set here is "domains" which defines the
 * indices of domains a particular function is applied to. Possible values are
 *(strings):
 *
 *     1) "All" : the function is applied to all domains defined for this
 *MultiDomainFunction.
 *     2) "i"   : the function is applied to a single domain which index is
 *equal to the
 *                function's index in this MultiDomainFunction.
 *     3) "non-negative integer" : a domain index.
 *     4) "a,b,c,..." : a list of domain indices (a,b,c,.. are non-negative
 *integers).
 *     5) "a - b" : a range of domain indices (a,b are non-negative integers a
 *<= b).
 *
 * To be used with Fit algorithm at least one of the member functions must have
 *"domains" value
 * of type 2), 3), 4) or 5) because these values can tell Fit how many domains
 *need to be created.
 *
 * @param i :: Index of a function for which the attribute is being set.
 * @param attName :: Name of an attribute.
 * @param att :: Value of the attribute to set.
 */
void MultiDomainFunction::setLocalAttribute(size_t i,
                                            const std::string &attName,
                                            const IFunction::Attribute &att) {
  if (attName != "domains") {
    throw std::invalid_argument("MultiDomainFunction does not have attribute " +
                                attName);
  }
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index is out of range.");
  }
  std::string value = att.asString();
  auto it = m_domains.find(i);

  if (value == "All") { // fit to all domains
    if (it != m_domains.end()) {
      m_domains.erase(it);
263
    }
264
265
266
267
268
269
270
271
272
    return;
  } else if (value ==
             "i") { // fit to domain with the same index as the function
    setDomainIndex(i, i);
    return;
  } else if (value.empty()) { // do not fit to any domain
    setDomainIndices(i, std::vector<size_t>());
    return;
  }
273

274
275
276
277
278
279
280
281
  // fit to a selection of domains
  std::vector<size_t> indx;
  Expression list;
  list.parse(value);
  if (list.name() == "+") {
    if (list.size() != 2 || list.terms()[1].operator_name() != "-") {
      throw std::runtime_error("MultiDomainFunction: attribute \"domains\" "
                               "expects two integers separated by a \"-\"");
282
    }
283
284
285
286
287
288
289
    // value looks like "a - b". a and b must be ints and define a range of
    // domain indices
    size_t start = boost::lexical_cast<size_t>(list.terms()[0].str());
    size_t end = boost::lexical_cast<size_t>(list.terms()[1].str()) + 1;
    if (start >= end) {
      throw std::runtime_error(
          "MultiDomainFunction: attribute \"domains\": wrong range limits.");
290
    }
291
292
293
    indx.resize(end - start);
    for (size_t i = start; i < end; ++i) {
      indx[i - start] = i;
294
    }
295
296
297
  } else {
    // value must be either an int or a list of ints: "a,b,c,..."
    list.toList();
298
299
    for (const auto &k : list) {
      indx.push_back(boost::lexical_cast<size_t>(k.name()));
300
    }
301
  }
302
303
  setDomainIndices(i, indx);
}
304

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/**
 * Split this function into independent functions. The number of functions in
 * the
 * returned vector must be equal to the number
 * of domains. The result of evaluation of the i-th function on the i-th domain
 * must be
 * the same as if this MultiDomainFunction was evaluated.
 */
std::vector<IFunction_sptr>
MultiDomainFunction::createEquivalentFunctions() const {
  size_t nDomains = m_maxIndex + 1;
  std::vector<CompositeFunction_sptr> compositeFunctions(nDomains);
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    // find the domains member function must be applied to
    std::vector<size_t> domains;
    getDomainIndices(iFun, nDomains, domains);
321

Hahn, Steven's avatar
Hahn, Steven committed
322
323
    for (auto domainIndex : domains) {
      CompositeFunction_sptr cf = compositeFunctions[domainIndex];
324
325
326
      if (!cf) {
        // create a composite function for each domain
        cf = CompositeFunction_sptr(new CompositeFunction());
Hahn, Steven's avatar
Hahn, Steven committed
327
        compositeFunctions[domainIndex] = cf;
328
      }
329
330
331
332
      // add copies of all functions applied to j-th domain to a single
      // compositefunction
      cf->addFunction(FunctionFactory::Instance().createInitialized(
          getFunction(iFun)->asString()));
333
    }
334
335
336
337
338
339
340
341
  }
  std::vector<IFunction_sptr> outFunctions(nDomains);
  // fill in the output vector
  // check functions containing a single member and take it out of the composite
  for (size_t i = 0; i < compositeFunctions.size(); ++i) {
    auto fun = compositeFunctions[i];
    if (!fun || fun->nFunctions() == 0) {
      throw std::runtime_error("There is no function for domain " +
342
                               std::to_string(i));
343
344
345
346
347
    }
    if (fun->nFunctions() > 1) {
      outFunctions[i] = fun;
    } else {
      outFunctions[i] = fun->getFunction(0);
348
349
    }
  }
350
351
  return outFunctions;
}
352

353
354
} // namespace API
} // namespace Mantid