CompositeFunction.cpp 31 KB
Newer Older
1
2
3
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4
5
//   NScD Oak Ridge National Laboratory, European Spallation Source,
//   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6
// SPDX - License - Identifier: GPL - 3.0 +
7
8
9
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
10
#include "MantidAPI/CompositeFunction.h"
11
#include "MantidAPI/FunctionFactory.h"
LamarMoore's avatar
LamarMoore committed
12
13
#include "MantidAPI/IConstraint.h"
#include "MantidAPI/ParameterTie.h"
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
14
15
#include "MantidKernel/Exception.h"
#include "MantidKernel/Logger.h"
16
#include "MantidKernel/Strings.h"
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
17

LamarMoore's avatar
LamarMoore committed
18
#include <algorithm>
19
#include <boost/lexical_cast.hpp>
20
#include <memory>
21
#include <sstream>
David Fairbrother's avatar
David Fairbrother committed
22
#include <utility>
23

24
25
namespace Mantid {
namespace API {
26

27
28
29
namespace {
/// static logger
Kernel::Logger g_log("CompositeFunction");
30
constexpr char *ATTNUMDERIV = "NumDeriv";
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
template <typename T>
void replaceVariableIndexRange(std::vector<T> &variableFunctionIndexList,
                               size_t oldSize, size_t newSize,
                               const T functionIndex) {
  auto itFun = std::find(variableFunctionIndexList.begin(),
                         variableFunctionIndexList.end(), functionIndex);
  if (itFun != variableFunctionIndexList.end()) {
    if (oldSize > newSize) {
      variableFunctionIndexList.erase(itFun, itFun + oldSize - newSize);
    } else if (oldSize < newSize) {
      variableFunctionIndexList.insert(itFun, newSize - oldSize, functionIndex);
    }
  } else if (newSize > 0) {
    using std::placeholders::_1;
    itFun = std::find_if(variableFunctionIndexList.begin(),
                         variableFunctionIndexList.end(),
                         std::bind(std::greater<size_t>(), _1, functionIndex));
    variableFunctionIndexList.insert(itFun, newSize, functionIndex);
  }
}

LamarMoore's avatar
LamarMoore committed
52
} // namespace
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
53

Peterson, Peter's avatar
Peterson, Peter committed
54
55
using std::size_t;

56
DECLARE_FUNCTION(CompositeFunction)
57

58
/// Default constructor
59
CompositeFunction::CompositeFunction()
60
61
    : IFunction(), m_nParams(0), m_nAttributes(0),
      m_iConstraintFunction(false) {
62
  createDefaultGlobalAttributes();
Stephen's avatar
Stephen committed
63
64
}

65
66
void CompositeFunction::createDefaultGlobalAttributes() {
  m_globalAttributeNames.clear();
67
  declareAttribute(ATTNUMDERIV, Attribute(false));
68
  m_nAttributes = 1;
69
70
}

71
/// Function initialization. Declare function parameters in this method.
72
void CompositeFunction::init() {}
73

74
/**
75
76
77
 * Writes itself into a string. Functions derived from CompositeFunction may
 * need to override this method with something like this:
 *   std::string NewFunction::writeToString()const
78
79
80
81
82
83
84
 *   {
 *      ostr << "composite=" << this->name() << ';';
 *      // write NewFunction's own attributes and parameters
 *      ostr << CompositeFunction::asString();
 *      // write NewFunction's own ties and constraints
 *      // ostr << ";constraints=(" << ... <<")";
 *   }
Roman Tolchenov's avatar
Roman Tolchenov committed
85
86
 * @param parentLocalAttributesStr :: A preformatted string with parent's local
 * attributes.
87
 *    Can be passed in by a CompositeFunction (eg MultiDomainFunction).
88
 * @return the string representation of the composite function
89
 */
Roman Tolchenov's avatar
Roman Tolchenov committed
90
91
std::string CompositeFunction::writeToString(
    const std::string &parentLocalAttributesStr) const {
92
  std::ostringstream ostr;
93

94
  // if empty just return function name
95
  if (nFunctions() == 0) {
96
97
98
    return "name=" + name();
  }

99
  if (name() != "CompositeFunction" || nAttributes() > nGlobalAttributes() ||
100
      getAttribute(ATTNUMDERIV).asBool() || !parentLocalAttributesStr.empty()) {
101
    ostr << "composite=" << name();
Stephen's avatar
Stephen committed
102
    std::vector<std::string> attr = m_globalAttributeNames;
103
104
    for (const auto &attName : attr) {
      std::string attValue = this->getAttribute(attName).value();
105
106
      if (!attValue.empty()) {
        ostr << ',' << attName << '=' << attValue;
107
108
      }
    }
109
    ostr << parentLocalAttributesStr << ';';
110
  }
111
  const auto localAttr = this->getLocalAttributeNames();
112
  for (size_t i = 0; i < nFunctions(); i++) {
113
    IFunction_sptr fun = getFunction(i);
114
    bool isComp = std::dynamic_pointer_cast<CompositeFunction>(fun) != nullptr;
115
116
    if (isComp)
      ostr << '(';
117
    std::ostringstream localAttributesStr;
118
119
120
121
122
    for (const auto &localAttName : localAttr) {
      const std::string localAttValue =
          this->getLocalAttribute(i, localAttName).value();
      if (!localAttValue.empty()) {
        // local attribute names are prefixed by dollar sign
Roman Tolchenov's avatar
Roman Tolchenov committed
123
124
        localAttributesStr << ',' << '$' << localAttName << '='
                           << localAttValue;
125
126
      }
    }
127
    ostr << fun->writeToString(localAttributesStr.str());
128
129
130
    if (isComp)
      ostr << ')';
    if (i < nFunctions() - 1) {
131
132
133
      ostr << ';';
    }
  }
134
135
136
137
138
139

  // collect non-default constraints
  std::string constraints = writeConstraints();
  // print constraints
  if (!constraints.empty()) {
    ostr << ";constraints=(" << constraints << ")";
140
  }
141
142
143
144

  // collect the non-default ties
  std::string ties = writeTies();
  // print the ties
145
  if (!ties.empty()) {
146
    ostr << ";ties=(" << ties << ")";
147
  }
148

149
150
151
  return ostr.str();
}

152
153
154
/**
 * @param ws A pointer to the workspace being fitted
 */
155
void CompositeFunction::setWorkspace(std::shared_ptr<const Workspace> ws) {
156
157
  // Pass it on to each member
  auto iend = m_functions.end();
158
  for (auto it = m_functions.begin(); it != iend; ++it) {
159
160
161
162
    (*it)->setWorkspace(ws);
  }
}

163
164
165
166
167
168
/**
 * @param workspace :: A workspace to fit to.
 * @param wi :: An index of a spectrum to fit to.
 * @param startX :: A start of the fitting region.
 * @param endX :: An end of the fitting region.
 */
169
void CompositeFunction::setMatrixWorkspace(
170
171
    std::shared_ptr<const MatrixWorkspace> workspace, size_t wi, double startX,
    double endX) {
172
173
174
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    m_functions[iFun]->setMatrixWorkspace(workspace, wi, startX, endX);
  }
175
176
}

177
/** Function you want to fit to.
178
 *  @param domain :: An instance of FunctionDomain with the function arguments.
179
180
 *  @param values :: A FunctionValues instance for storing the calculated
 * values.
181
 */
182
183
void CompositeFunction::function(const FunctionDomain &domain,
                                 FunctionValues &values) const {
184
  FunctionValues tmp(domain);
185
  values.zeroCalculated();
186
187
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    m_functions[iFun]->function(domain, tmp);
188
189
190
191
192
193
194
195
196
    values += tmp;
  }
}

/**
 * Derivatives of function with respect to active parameters
 * @param domain :: Function domain to get the arguments from.
 * @param jacobian :: A Jacobian to store the derivatives.
 */
197
198
void CompositeFunction::functionDeriv(const FunctionDomain &domain,
                                      Jacobian &jacobian) {
199
  if (getAttribute(ATTNUMDERIV).asBool()) {
200
    calNumericalDeriv(domain, jacobian);
201
202
203
204
  } else {
    for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
      PartialJacobian J(&jacobian, paramOffset(iFun));
      getFunction(iFun)->functionDeriv(domain, J);
205
    }
206
207
208
  }
}

209
/** Sets a new value to the i-th parameter.
210
211
 *  @param i :: The parameter index
 *  @param value :: The new value
212
213
 *  @param explicitlySet :: A boolean falgging the parameter as explicitly set
 * (by user)
214
 */
215
216
void CompositeFunction::setParameter(size_t i, const double &value,
                                     bool explicitlySet) {
217
  size_t iFun = functionIndex(i);
218
219
  m_functions[iFun]->setParameter(i - m_paramOffsets[iFun], value,
                                  explicitlySet);
220
221
}

222
223
224
225
/** Sets a new description to the i-th parameter.
 *  @param i :: The parameter index
 *  @param description :: The new description
 */
226
227
void CompositeFunction::setParameterDescription(
    size_t i, const std::string &description) {
228
  size_t iFun = functionIndex(i);
229
230
  m_functions[iFun]->setParameterDescription(i - m_paramOffsets[iFun],
                                             description);
231
232
}

233
/** Get the i-th parameter.
234
 *  @param i :: The parameter index
235
 *  @return value of the requested parameter
236
 */
237
double CompositeFunction::getParameter(size_t i) const {
Peterson, Peter's avatar
Peterson, Peter committed
238
  size_t iFun = functionIndex(i);
239
  return m_functions[iFun]->getParameter(i - m_paramOffsets[iFun]);
240
241
}

242
243
244
245
/**
 * Check if function has a parameter with a particular name.
 * @param name :: A name of a parameter.
 * @return True if the parameter exists.
LamarMoore's avatar
LamarMoore committed
246
 */
247
248
bool CompositeFunction::hasParameter(const std::string &name) const {
  try {
249
250
251
252
    auto [parameterName, index] = parseName(name);
    return index < m_functions.size()
               ? m_functions[index]->hasParameter(parameterName)
               : false;
253
254
255
256
257
  } catch (std::invalid_argument &) {
    return false;
  }
}

Stephen's avatar
Stephen committed
258
259
260
261
262
263
264
265
266
267
268
269
/**
 * Check if function has a attribute with a particular name.
 * @param name :: A name of a attribute.
 * @return True if the parameter exists.
 */
bool CompositeFunction::hasAttribute(const std::string &name) const {
  try {
    if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(),
                  name) != m_globalAttributeNames.end()) {
      return true;
    }
    auto [attributeName, index] = parseName(name);
270
271
    return m_functions[index]->hasAttribute(attributeName);
  } catch (...) {
Stephen's avatar
Stephen committed
272
273
274
275
    return false;
  }
}

276
277
/**
 * Sets a new value to a parameter by name.
278
279
 * @param name :: The name of the parameter.
 * @param value :: The new value
280
 * @param explicitlySet :: A boolean flagging the parameter as explicitly set
281
 * (by user)
282
 */
283
284
void CompositeFunction::setParameter(const std::string &name,
                                     const double &value, bool explicitlySet) {
285
286
  auto [parameterName, index] = parseName(name);
  getFunction(index)->setParameter(parameterName, value, explicitlySet);
287
288
}

289
290
291
/**
 * Sets a new description to a parameter by name.
 * @param name :: The name of the parameter.
292
 * @param description :: The new description
293
 */
294
295
void CompositeFunction::setParameterDescription(
    const std::string &name, const std::string &description) {
296
297
  auto [parameterName, index] = parseName(name);
  getFunction(index)->setParameterDescription(parameterName, description);
298
299
}

300
301
/**
 * Parameters by name.
302
 * @param name :: The name of the parameter.
303
 * @return value of the requested named parameter
304
 */
305
double CompositeFunction::getParameter(const std::string &name) const {
306
307
  auto [parameterName, index] = parseName(name);
  return getFunction(index)->getParameter(parameterName);
308
309
}

310
311
312
313
314
315
316
317
318
319
320
321
322
/**
 * Return a value of attribute attName
 * @param name :: Returns the named attribute
 */
API::IFunction::Attribute
CompositeFunction::getAttribute(const std::string &name) const {
  try {
    if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(),
                  name) != m_globalAttributeNames.end()) {
      return IFunction::getAttribute(name);
    }
    auto [attributeName, index] = parseName(name);
    return m_functions[index]->getAttribute(attributeName);
323
  } catch (std::invalid_argument &) {
324
325
326
327
328
329
    throw std::invalid_argument(
        "ParamFunctionAttributeHolder::getAttribute - Unknown attribute '" +
        name + "'");
  }
}

330
/**
Stephen's avatar
Stephen committed
331
 *  Set a value of a named attribute.
332
333
334
335
336
337
338
339
340
341
342
343
344
 *  @param name :: The name of the attribute
 *  @param value :: The value of the attribute
 */
void CompositeFunction::setAttribute(const std::string &name,
                                     const API::IFunction::Attribute &value) {
  if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(),
                name) != m_globalAttributeNames.end()) {
    return IFunction::setAttribute(name, value);
  }
  auto [attributeName, index] = parseName(name);
  return m_functions[index]->setAttribute(attributeName, value);
}

345
/// Total number of parameters
346
size_t CompositeFunction::nParams() const { return m_nParams; }
347

348
// Total number of attributes
349
350
351
352
353
354
355
size_t CompositeFunction::nAttributes() const {
  size_t numAttributes = nGlobalAttributes();
  for (const auto &func : m_functions) {
    numAttributes += func->nAttributes();
  }
  return numAttributes;
}
356
/**
357
 *
358
 * @param name :: The name of a parameter
359
 * @return index of the requested named parameter
360
 */
361
size_t CompositeFunction::parameterIndex(const std::string &name) const {
362
363
364
  auto [parameterName, index] = parseName(name);
  return getFunction(index)->parameterIndex(parameterName) +
         m_paramOffsets[index];
365
366
}

Nick Draper's avatar
re #100    
Nick Draper committed
367
/// Returns the name of parameter
368
/// @param i :: The index
Nick Draper's avatar
re #100    
Nick Draper committed
369
/// @return The name of the parameter
370
std::string CompositeFunction::parameterName(size_t i) const {
371
  size_t iFun = functionIndex(i);
372
  std::ostringstream ostr;
373
374
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->parameterName(i - m_paramOffsets[iFun]);
375
  return ostr.str();
376
377
}

378
379
380
381
/// Returns the name of the ith attribute
/// @param index :: The index of the attribute
/// @return The name of the attribute
std::string CompositeFunction::attributeName(size_t index) const {
382
  if (index < nGlobalAttributes())
Stephen's avatar
Stephen committed
383
    return IFunction::attributeName(index);
384
385
386
387

  // Offset the index by the number of global attributes
  auto offsetIndex = index - nGlobalAttributes();
  size_t functionIndex = attributeFunctionIndex(offsetIndex);
388
389
  std::ostringstream ostr;
  ostr << 'f' << functionIndex << '.'
Stephen's avatar
Stephen committed
390
       << m_functions[functionIndex]->attributeName(
391
              getAttributeOffset(offsetIndex));
392
393
394
  return ostr.str();
}

395
396
397
/// Returns the description of parameter
/// @param i :: The index
/// @return The description of the parameter
398
std::string CompositeFunction::parameterDescription(size_t i) const {
399
  size_t iFun = functionIndex(i);
400
  std::ostringstream ostr;
401
  ostr << m_functions[iFun]->parameterDescription(i - m_paramOffsets[iFun]);
402
403
  return ostr.str();
}
404
/**
405
406
407
408
 * Get the fitting error for a parameter
 * @param i :: The index of a parameter
 * @return :: the error
 */
409
double CompositeFunction::getError(size_t i) const {
410
  size_t iFun = functionIndex(i);
411
  return m_functions[iFun]->getError(i - m_paramOffsets[iFun]);
412
413
}

414
/**
415
416
417
418
 * Set the fitting error for a parameter
 * @param i :: The index of a parameter
 * @param err :: The error value to set
 */
419
void CompositeFunction::setError(size_t i, double err) {
420
  size_t iFun = functionIndex(i);
421
  m_functions[iFun]->setError(i - m_paramOffsets[iFun], err);
422
423
}

424
425
426
/// Value of i-th active parameter. Override this method to make fitted
/// parameters different from the declared
double CompositeFunction::activeParameter(size_t i) const {
427
  size_t iFun = functionIndex(i);
428
  return m_functions[iFun]->activeParameter(i - m_paramOffsets[iFun]);
429
430
}

431
432
/// Set new value of i-th active parameter. Override this method to make
/// fitted parameters different from the declared
433
void CompositeFunction::setActiveParameter(size_t i, double value) {
434
  size_t iFun = functionIndex(i);
435
  m_functions[iFun]->setActiveParameter(i - m_paramOffsets[iFun], value);
436
437
438
}

/// Returns the name of active parameter i
439
std::string CompositeFunction::nameOfActive(size_t i) const {
440
  size_t iFun = functionIndex(i);
441
  std::ostringstream ostr;
442
443
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->nameOfActive(i - m_paramOffsets[iFun]);
444
445
446
447
  return ostr.str();
}

/// Returns the description of active parameter i
448
std::string CompositeFunction::descriptionOfActive(size_t i) const {
449
  size_t iFun = functionIndex(i);
450
  std::ostringstream ostr;
451
  ostr << m_functions[iFun]->descriptionOfActive(i - m_paramOffsets[iFun]);
452
  return ostr.str();
453
454
}

455
/// Change status of parameter
456
457
void CompositeFunction::setParameterStatus(size_t i,
                                           IFunction::ParameterStatus status) {
458
  size_t iFun = functionIndex(i);
459
  m_functions[iFun]->setParameterStatus(i - m_paramOffsets[iFun], status);
460
461
}

462
/// Get status of parameter
463
464
IFunction::ParameterStatus
CompositeFunction::getParameterStatus(size_t i) const {
465
  size_t iFun = functionIndex(i);
466
  return m_functions[iFun]->getParameterStatus(i - m_paramOffsets[iFun]);
467
468
}

469
/** Makes sure that the function is consistent.
470
 */
471
void CompositeFunction::checkFunction() {
472
  m_nParams = 0;
473
  m_nAttributes = nGlobalAttributes();
474
  m_paramOffsets.clear();
475
  m_IFunction.clear();
476
  m_attributeIndex.clear();
477

478
  std::vector<IFunction_sptr> functions(m_functions.begin(), m_functions.end());
479
480
  m_functions.clear();

Hahn, Steven's avatar
Hahn, Steven committed
481
  for (auto &f : functions) {
482
    CompositeFunction_sptr cf = std::dynamic_pointer_cast<CompositeFunction>(f);
483
484
    if (cf)
      cf->checkFunction();
485
486
487
488
    addFunction(f);
  }
}

489
/**
490
491
492
493
 * Remove all member functions
 */
void CompositeFunction::clear() {
  m_nParams = 0;
494
  m_nAttributes = nGlobalAttributes();
495
496
497
  m_paramOffsets.clear();
  m_IFunction.clear();
  m_functions.clear();
Stephen's avatar
Stephen committed
498
  m_attributeIndex.clear();
499
500
}

501
/** Add a function
502
 * @param f :: A pointer to the added function
503
 * @return The function index
504
 */
505
506
size_t CompositeFunction::addFunction(IFunction_sptr f) {
  m_IFunction.insert(m_IFunction.end(), f->nParams(), m_functions.size());
507
508
  m_attributeIndex.insert(m_attributeIndex.end(), f->nAttributes(),
                          m_functions.size());
509
  m_functions.emplace_back(f);
510
  if (m_paramOffsets.empty()) {
511
    m_paramOffsets.emplace_back(0);
512
    m_nParams = f->nParams();
513
    m_nAttributes = f->nAttributes() + nGlobalAttributes();
514
  } else {
515
    m_paramOffsets.emplace_back(m_nParams);
516
    m_nParams += f->nParams();
517
    m_nAttributes += f->nAttributes();
518
  }
519
  return m_functions.size() - 1;
520
521
}

522
/** Remove a function
523
 * @param i :: The index of the function to remove
524
 */
525
void CompositeFunction::removeFunction(size_t i) {
526
527
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(i) +
528
529
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
530
  }
531

532
  IFunction_sptr fun = getFunction(i);
533
  // Remove ties which are no longer valid
534
535
536
  for (size_t j = 0; j < nParams();) {
    ParameterTie *tie = getTie(j);
    if (tie && tie->findParametersOf(fun.get())) {
537
      removeTie(j);
538
    } else {
539
540
541
542
      j++;
    }
  }

543
544
545
546
547
548
549
  // Shift down the function indices for parameters and attributes
  auto shiftDown = [&](auto &functionIndex) {
    if (functionIndex == i) {
      return true;
    } else if (functionIndex > i) {
      functionIndex -= 1;
      return false;
550
    } else {
551
      return false;
552
    }
553
  };
Stephen's avatar
Stephen committed
554

555
556
557
558
559
560
  m_IFunction.erase(
      std::remove_if(m_IFunction.begin(), m_IFunction.end(), shiftDown),
      m_IFunction.end());
  m_attributeIndex.erase(std::remove_if(m_attributeIndex.begin(),
                                        m_attributeIndex.end(), shiftDown),
                         m_attributeIndex.end());
561

Stephen's avatar
Stephen committed
562
563
564
565
  // Reduction in parameters and attributes
  m_nParams -= fun->nParams();
  m_nAttributes -= fun->nAttributes();

566
567
568
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
569
    m_paramOffsets[j] -= fun->nParams();
570
  }
571
  m_paramOffsets.erase(m_paramOffsets.begin() + i);
572

573
  m_functions.erase(m_functions.begin() + i);
574
575
}

576
/** Replace a function with a new one. The old function is deleted.
577
 *  The new function must have already its workspace set.
578
 * @param f_old :: The pointer to the function to replace. If it's not
579
 *  a member of this composite function nothing happens
580
 * @param f_new :: A pointer to the new function
581
 */
David Fairbrother's avatar
David Fairbrother committed
582
583
void CompositeFunction::replaceFunctionPtr(const IFunction_sptr &f_old,
                                           const IFunction_sptr &f_new) {
584
585
586
587
  std::vector<IFunction_sptr>::const_iterator it =
      std::find(m_functions.begin(), m_functions.end(), f_old);
  if (it == m_functions.end())
    return;
588
  std::vector<IFunction_sptr>::difference_type iFun = it - m_functions.begin();
589
  replaceFunction(iFun, f_new);
590
591
}

592
/** Replace a function with a new one. The old function is deleted.
593
 * @param functionIndex :: The index of the function to replace
594
 * @param f :: A pointer to the new function
595
 */
596
597
598
599
void CompositeFunction::replaceFunction(size_t functionIndex,
                                        const IFunction_sptr &f) {
  if (functionIndex >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(functionIndex) +
600
601
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
602
  }
603

604
  IFunction_sptr fun = getFunction(functionIndex);
605
606
  size_t np_old = fun->nParams();
  size_t np_new = f->nParams();
Stephen's avatar
Stephen committed
607
608
  size_t at_old = fun->nAttributes();
  size_t at_new = f->nAttributes();
609

610
  // Modify function parameter and attribute indices:
611
612
  replaceVariableIndexRange(m_IFunction, np_old, np_new, functionIndex);
  replaceVariableIndexRange(m_attributeIndex, at_old, at_new,functionIndex);
613

614
  // Decrement attribute and parameter counts
615
  size_t dnp = np_new - np_old;
Stephen's avatar
Stephen committed
616
  size_t dna = at_new - at_old;
617
  m_nParams += dnp;
Stephen's avatar
Stephen committed
618
  m_nAttributes += dna;
619

620
621
  // Shift the parameter offsets down by the total number of i-th function's
  // params
622
  for (size_t j = functionIndex + 1; j < nFunctions(); j++) {
623
624
    m_paramOffsets[j] += dnp;
  }
625
  m_functions[functionIndex] = f;
626
627
}

628
/**
629
 * @param i :: The index of the function
630
 * @return function at the requested index
631
 */
632
633
IFunction_sptr CompositeFunction::getFunction(std::size_t i) const {
  if (i >= nFunctions()) {
634
    throw std::out_of_range("Function index (" + std::to_string(i) +
635
636
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
637
  }
638
639
640
  return m_functions[i];
}

641
642
/**
 * Get the index of the function to which parameter i belongs
643
 * @param i :: The parameter index
644
 * @return function index of the requested parameter
645
 */
646
647
size_t CompositeFunction::functionIndex(std::size_t i) const {
  if (i >= nParams()) {
648
    throw std::out_of_range("Function parameter index (" + std::to_string(i) +
649
650
                            ") out of range (" + std::to_string(nParams()) +
                            ").");
651
  }
652
  return m_IFunction[i];
653
}
654
655
656
657
658
659
660
661
662
663
664
665
666
/**
 * Get the index of the function to which parameter i belongs
 * @param i :: The parameter index
 * @return function index of the requested parameter
 */
size_t CompositeFunction::attributeFunctionIndex(std::size_t i) const {
  if (i >= nAttributes()) {
    throw std::out_of_range("Function attribute index (" + std::to_string(i) +
                            ") out of range (" + std::to_string(nAttributes()) +
                            ").");
  }
  return m_attributeIndex[i];
}
667
668

/**
LamarMoore's avatar
LamarMoore committed
669
670
 * @param varName :: The variable name which may contain function index (
 * [f<index.>]name )
671
 * @return pair containing the unprefixed variable name and functionIndex
LamarMoore's avatar
LamarMoore committed
672
 */
673
674
std::pair<std::string, size_t>
CompositeFunction::parseName(const std::string &varName) {
675
  size_t i = varName.find('.');
676
  if (i == std::string::npos) {
677
    throw std::invalid_argument("Variable " + varName + " not found.");
678
  } else {
679
    if (varName[0] != 'f')
680
      throw std::invalid_argument(
681
          "External function variable name must start with 'f'");
682

683
    std::string sindex = varName.substr(1, i - 1);
684
    size_t index = boost::lexical_cast<size_t>(sindex);
685
686
687
688

    if (i == varName.size() - 1)
      throw std::invalid_argument("Name cannot be empty");

689
    return std::make_pair(varName.substr(i + 1), index);
690
  }
691
692
}

693
/** Returns the index of parameter i as it declared in its function
694
 * @param i :: The parameter index
695
 * @param recursive :: If true call parameterLocalName recursively until
696
 *    a non-composite function is reached.
697
698
 * @return The local index of the parameter
 */
699
size_t CompositeFunction::parameterLocalIndex(size_t i, bool recursive) const {
700
  size_t iFun = functionIndex(i);
701
702
  auto localIndex = i - m_paramOffsets[iFun];
  if (recursive) {
703
    auto cf = dynamic_cast<const CompositeFunction *>(m_functions[iFun].get());
704
705
706
707
708
    if (cf) {
      return cf->parameterLocalIndex(localIndex, recursive);
    }
  }
  return localIndex;
709
710
}

711
/** Returns the name of parameter i as it declared in its function
712
 * @param i :: The parameter index
713
 * @param recursive :: If true call parameterLocalName recursively until
714
 *    a non-composite function is reached.
715
716
 * @return The pure parameter name (without the function identifier f#.)
 */
717
718
std::string CompositeFunction::parameterLocalName(size_t i,
                                                  bool recursive) const {
719
  size_t iFun = functionIndex(i);
720
721
722
  auto localIndex = i - m_paramOffsets[iFun];
  auto localFunction = m_functions[iFun].get();
  if (recursive) {
723
    auto cf = dynamic_cast<const CompositeFunction *>(localFunction);
724
725
726
727
728
    if (cf) {
      return cf->parameterLocalName(localIndex, recursive);
    }
  }
  return localFunction->parameterName(localIndex);
729
730
}

731
/**
732
 * Apply the ties.
733
 */
734
void CompositeFunction::applyTies() {
735
736
737
738
739
740
741
  if (hasOrderedTies()) {
    applyOrderedTies();
  } else {
    for (size_t i = 0; i < nFunctions(); i++) {
      getFunction(i)->applyTies();
    }
    IFunction::applyTies();
742
743
744
745
  }
}

/**
746
 * Clear the ties.
747
 */
748
void CompositeFunction::clearTies() {
749
  IFunction::clearTies();
750
  for (size_t i = 0; i < nFunctions(); i++) {
751
752
753
754
755
    getFunction(i)->clearTies();
  }
}

/** Removes i-th parameter's tie if it is tied or does nothing.
756
 * @param i :: The index of the tied parameter.
757
 * @return True if successful
758
 */
759
bool CompositeFunction::removeTie(size_t i) {
760
761
762
763
764
765
766
  bool foundAndRemovedTie = IFunction::removeTie(i);
  if (!foundAndRemovedTie) {
    size_t iFun = functionIndex(i);
    bool res = m_functions[iFun]->removeTie(i - m_paramOffsets[iFun]);
    return res;
  }
  return foundAndRemovedTie;
767
768
769
}

/** Get the tie of i-th parameter
770
 * @param i :: The parameter index
771
 * @return A pointer to the tie.
772
 */
773
ParameterTie *CompositeFunction::getTie(size_t i) const {
774
775
776
777
778
779
  auto tie = IFunction::getTie(i);
  if (tie == nullptr) {
    size_t iFun = functionIndex(i);
    tie = m_functions[iFun]->getTie(i - m_paramOffsets[iFun]);
  }
  return tie;
780
781
782
}

/**
783
 * Declare a new parameter. To used in the implementation's constructor.
784
785
 * @param name :: The parameter name.
 * @param initValue :: The initial value for the parameter
786
 * @param description :: Parameter documentation
787
 */
788
789
790
791
792
793
794
795
void CompositeFunction::declareParameter(const std::string &name,
                                         double initValue,
                                         const std::string &description) {
  (void)name;        // Avoid compiler warning
  (void)initValue;   // Avoid compiler warning
  (void)description; // Avoid compiler warning
  throw Kernel::Exception::NotImplementedError(
      "CompositeFunction cannot not have its own parameters.");
796
}
797
798
799
800
801
802
803
804
805
806
/**
 * Declares a single (global) attribute on the composite function
 * @param name :: The name of the attribute
 * @param defaultValue :: A default value
 */
void CompositeFunction::declareAttribute(
    const std::string &name, const API::IFunction::Attribute &defaultValue) {
  m_globalAttributeNames.emplace_back(name);
  IFunction::declareAttribute(name, defaultValue);
}
807

808
809
810
/**
 * Prepare the function for a fit.
 */
811
void CompositeFunction::setUpForFit() {
812
  IFunction::setUpForFit();
813
  // set up the member functions
814
  for (size_t i = 0; i < nFunctions(); i++) {
815
    getFunction(i)->setUpForFit();
816
  }
817
818

  // Instead of automatically switching to numeric derivatives
819
  // log a warning about a danger of not using it
820
821
822
823
824
  if (!getAttribute("NumDeriv").asBool()) {
    for (size_t i = 0; i < nParams(); ++i) {
      ParameterTie *tie = getTie(i);
      if (tie && !tie->isConstant()) {
        g_log.warning() << "Numeric derivatives should be used when "
825
                           "non-constant ties defined.\n";
826
827
        break;
      }
828
    }
829
830
831
  }
}

Nick Draper's avatar
re #100    
Nick Draper committed
832
/// Get constraint
Janik Zikovsky's avatar