CompositeFunction.cpp 29.5 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");
Stephen's avatar
Stephen committed
30
constexpr char * ATTNUMDERIV = "NumDeriv";
LamarMoore's avatar
LamarMoore committed
31
} // namespace
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
32

Peterson, Peter's avatar
Peterson, Peter committed
33
34
using std::size_t;

35
DECLARE_FUNCTION(CompositeFunction)
36

37
/// Default constructor
38
CompositeFunction::CompositeFunction()
39
40
    : IFunction(), m_nParams(0), m_nAttributes(0),
      m_iConstraintFunction(false) {
Stephen's avatar
Stephen committed
41
42
43
44
  createGlobalAttributes();
}

void CompositeFunction::createGlobalAttributes() {
45
  declareAttribute(ATTNUMDERIV, Attribute(false));
Stephen's avatar
Stephen committed
46
47
48
  m_nGlobalAttributes = 1;
  m_globalAttributeNames.emplace_back(ATTNUMDERIV);
  m_nAttributes = m_nGlobalAttributes;
49
50
}

51
/// Function initialization. Declare function parameters in this method.
52
void CompositeFunction::init() {}
53

54
/**
55
56
57
 * Writes itself into a string. Functions derived from CompositeFunction may
 * need to override this method with something like this:
 *   std::string NewFunction::writeToString()const
58
59
60
61
62
63
64
 *   {
 *      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
65
66
 * @param parentLocalAttributesStr :: A preformatted string with parent's local
 * attributes.
67
 *    Can be passed in by a CompositeFunction (eg MultiDomainFunction).
68
 * @return the string representation of the composite function
69
 */
Roman Tolchenov's avatar
Roman Tolchenov committed
70
71
std::string CompositeFunction::writeToString(
    const std::string &parentLocalAttributesStr) const {
72
  std::ostringstream ostr;
73

74
  // if empty just return function name
75
  if (nFunctions() == 0) {
76
77
78
    return "name=" + name();
  }

Stephen's avatar
Stephen committed
79
  if (name() != "CompositeFunction" || nAttributes() > m_nGlobalAttributes ||
80
      getAttribute(ATTNUMDERIV).asBool() || !parentLocalAttributesStr.empty()) {
81
    ostr << "composite=" << name();
Stephen's avatar
Stephen committed
82
    std::vector<std::string> attr = m_globalAttributeNames;
83
84
    for (const auto &attName : attr) {
      std::string attValue = this->getAttribute(attName).value();
85
86
      if (!attValue.empty()) {
        ostr << ',' << attName << '=' << attValue;
87
88
      }
    }
89
    ostr << parentLocalAttributesStr << ';';
90
  }
91
  const auto localAttr = this->getLocalAttributeNames();
92
  for (size_t i = 0; i < nFunctions(); i++) {
93
    IFunction_sptr fun = getFunction(i);
94
    bool isComp = std::dynamic_pointer_cast<CompositeFunction>(fun) != nullptr;
95
96
    if (isComp)
      ostr << '(';
97
    std::ostringstream localAttributesStr;
98
99
100
101
102
    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
103
104
        localAttributesStr << ',' << '$' << localAttName << '='
                           << localAttValue;
105
106
      }
    }
107
    ostr << fun->writeToString(localAttributesStr.str());
108
109
110
    if (isComp)
      ostr << ')';
    if (i < nFunctions() - 1) {
111
112
113
      ostr << ';';
    }
  }
114
115
116
117
118
119

  // collect non-default constraints
  std::string constraints = writeConstraints();
  // print constraints
  if (!constraints.empty()) {
    ostr << ";constraints=(" << constraints << ")";
120
  }
121
122
123
124

  // collect the non-default ties
  std::string ties = writeTies();
  // print the ties
125
  if (!ties.empty()) {
126
    ostr << ";ties=(" << ties << ")";
127
  }
128

129
130
131
  return ostr.str();
}

132
133
134
/**
 * @param ws A pointer to the workspace being fitted
 */
135
void CompositeFunction::setWorkspace(std::shared_ptr<const Workspace> ws) {
136
137
  // Pass it on to each member
  auto iend = m_functions.end();
138
  for (auto it = m_functions.begin(); it != iend; ++it) {
139
140
141
142
    (*it)->setWorkspace(ws);
  }
}

143
144
145
146
147
148
/**
 * @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.
 */
149
void CompositeFunction::setMatrixWorkspace(
150
151
    std::shared_ptr<const MatrixWorkspace> workspace, size_t wi, double startX,
    double endX) {
152
153
154
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    m_functions[iFun]->setMatrixWorkspace(workspace, wi, startX, endX);
  }
155
156
}

157
/** Function you want to fit to.
158
 *  @param domain :: An instance of FunctionDomain with the function arguments.
159
160
 *  @param values :: A FunctionValues instance for storing the calculated
 * values.
161
 */
162
163
void CompositeFunction::function(const FunctionDomain &domain,
                                 FunctionValues &values) const {
164
  FunctionValues tmp(domain);
165
  values.zeroCalculated();
166
167
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    m_functions[iFun]->function(domain, tmp);
168
169
170
171
172
173
174
175
176
    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.
 */
177
178
void CompositeFunction::functionDeriv(const FunctionDomain &domain,
                                      Jacobian &jacobian) {
179
  if (getAttribute(ATTNUMDERIV).asBool()) {
180
    calNumericalDeriv(domain, jacobian);
181
182
183
184
  } else {
    for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
      PartialJacobian J(&jacobian, paramOffset(iFun));
      getFunction(iFun)->functionDeriv(domain, J);
185
    }
186
187
188
  }
}

189
/** Sets a new value to the i-th parameter.
190
191
 *  @param i :: The parameter index
 *  @param value :: The new value
192
193
 *  @param explicitlySet :: A boolean falgging the parameter as explicitly set
 * (by user)
194
 */
195
196
void CompositeFunction::setParameter(size_t i, const double &value,
                                     bool explicitlySet) {
197
  size_t iFun = functionIndex(i);
198
199
  m_functions[iFun]->setParameter(i - m_paramOffsets[iFun], value,
                                  explicitlySet);
200
201
}

202
203
204
205
/** Sets a new description to the i-th parameter.
 *  @param i :: The parameter index
 *  @param description :: The new description
 */
206
207
void CompositeFunction::setParameterDescription(
    size_t i, const std::string &description) {
208
  size_t iFun = functionIndex(i);
209
210
  m_functions[iFun]->setParameterDescription(i - m_paramOffsets[iFun],
                                             description);
211
212
}

213
/** Get the i-th parameter.
214
 *  @param i :: The parameter index
215
 *  @return value of the requested parameter
216
 */
217
double CompositeFunction::getParameter(size_t i) const {
Peterson, Peter's avatar
Peterson, Peter committed
218
  size_t iFun = functionIndex(i);
219
  return m_functions[iFun]->getParameter(i - m_paramOffsets[iFun]);
220
221
}

222
223
224
225
/**
 * 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
226
 */
227
228
bool CompositeFunction::hasParameter(const std::string &name) const {
  try {
229
230
231
232
    auto [parameterName, index] = parseName(name);
    return index < m_functions.size()
               ? m_functions[index]->hasParameter(parameterName)
               : false;
233
234
235
236
237
  } catch (std::invalid_argument &) {
    return false;
  }
}

Stephen's avatar
Stephen committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**
 * 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);
    return index < m_functions.size()
               ? m_functions[index]->hasAttribute(attributeName)
               : false;
  } catch (std::invalid_argument &) {
    return false;
  }
}

258
259
/**
 * Sets a new value to a parameter by name.
260
261
 * @param name :: The name of the parameter.
 * @param value :: The new value
262
 * @param explicitlySet :: A boolean flagging the parameter as explicitly set
263
 * (by user)
264
 */
265
266
void CompositeFunction::setParameter(const std::string &name,
                                     const double &value, bool explicitlySet) {
267
268
  auto [parameterName, index] = parseName(name);
  getFunction(index)->setParameter(parameterName, value, explicitlySet);
269
270
}

271
272
273
/**
 * Sets a new description to a parameter by name.
 * @param name :: The name of the parameter.
274
 * @param description :: The new description
275
 */
276
277
void CompositeFunction::setParameterDescription(
    const std::string &name, const std::string &description) {
278
279
  auto [parameterName, index] = parseName(name);
  getFunction(index)->setParameterDescription(parameterName, description);
280
281
}

282
283
/**
 * Parameters by name.
284
 * @param name :: The name of the parameter.
285
 * @return value of the requested named parameter
286
 */
287
double CompositeFunction::getParameter(const std::string &name) const {
288
289
  auto [parameterName, index] = parseName(name);
  return getFunction(index)->getParameter(parameterName);
290
291
292
}

/// Total number of parameters
293
size_t CompositeFunction::nParams() const { return m_nParams; }
294

295
296
// Total number of attributes
size_t CompositeFunction::nAttributes() const { return m_nAttributes; }
297
/**
298
 *
299
 * @param name :: The name of a parameter
300
 * @return index of the requested named parameter
301
 */
302
size_t CompositeFunction::parameterIndex(const std::string &name) const {
303
304
305
  auto [parameterName, index] = parseName(name);
  return getFunction(index)->parameterIndex(parameterName) +
         m_paramOffsets[index];
306
307
}

Nick Draper's avatar
re #100    
Nick Draper committed
308
/// Returns the name of parameter
309
/// @param i :: The index
Nick Draper's avatar
re #100    
Nick Draper committed
310
/// @return The name of the parameter
311
std::string CompositeFunction::parameterName(size_t i) const {
312
  size_t iFun = functionIndex(i);
313
  std::ostringstream ostr;
314
315
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->parameterName(i - m_paramOffsets[iFun]);
316
  return ostr.str();
317
318
}

319
320
321
322
/// 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 {
Stephen's avatar
Stephen committed
323
324
325
  if (index < m_nGlobalAttributes)
    return IFunction::attributeName(index);
  size_t functionIndex = attributeFunctionIndex(index - m_nGlobalAttributes);
326
327
  std::ostringstream ostr;
  ostr << 'f' << functionIndex << '.'
Stephen's avatar
Stephen committed
328
329
       << m_functions[functionIndex]->attributeName(
              getAttributeOffset(index - m_nGlobalAttributes));
330
331
332
  return ostr.str();
}

333
334
335
/// Returns the description of parameter
/// @param i :: The index
/// @return The description of the parameter
336
std::string CompositeFunction::parameterDescription(size_t i) const {
337
  size_t iFun = functionIndex(i);
338
  std::ostringstream ostr;
339
  ostr << m_functions[iFun]->parameterDescription(i - m_paramOffsets[iFun]);
340
341
342
  return ostr.str();
}

Stephen's avatar
Stephen committed
343
344
345
346
347
348
349
350
351
352
353
354
///// Returns a list of attribute names, including the attributes of the child
///// functions
// std::vector<std::string> CompositeFunction::getAttributeNames() const {
//  std::vector<std::string> attributeNames;
//  attributeNames.reserve(nAttributes() + 1);
//  // Add global numerical derivative attribute
//  attributeNames.insert(attributeNames.end(), ATTNUMDERIV);
//  // Add child attributes
//  auto names = IFunction::getAttributeNames();
//  attributeNames.insert(attributeNames.end(), names.begin(), names.end());
//  return attributeNames;
//}
355

356
/**
357
358
359
360
 * Get the fitting error for a parameter
 * @param i :: The index of a parameter
 * @return :: the error
 */
361
double CompositeFunction::getError(size_t i) const {
362
  size_t iFun = functionIndex(i);
363
  return m_functions[iFun]->getError(i - m_paramOffsets[iFun]);
364
365
}

366
/**
367
368
369
370
 * Set the fitting error for a parameter
 * @param i :: The index of a parameter
 * @param err :: The error value to set
 */
371
void CompositeFunction::setError(size_t i, double err) {
372
  size_t iFun = functionIndex(i);
373
  m_functions[iFun]->setError(i - m_paramOffsets[iFun], err);
374
375
}

376
377
378
/// Value of i-th active parameter. Override this method to make fitted
/// parameters different from the declared
double CompositeFunction::activeParameter(size_t i) const {
379
  size_t iFun = functionIndex(i);
380
  return m_functions[iFun]->activeParameter(i - m_paramOffsets[iFun]);
381
382
}

383
384
385
/// Set new value of i-th active parameter. Override this method to make fitted
/// parameters different from the declared
void CompositeFunction::setActiveParameter(size_t i, double value) {
386
  size_t iFun = functionIndex(i);
387
  m_functions[iFun]->setActiveParameter(i - m_paramOffsets[iFun], value);
388
389
390
}

/// Returns the name of active parameter i
391
std::string CompositeFunction::nameOfActive(size_t i) const {
392
  size_t iFun = functionIndex(i);
393
  std::ostringstream ostr;
394
395
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->nameOfActive(i - m_paramOffsets[iFun]);
396
397
398
399
  return ostr.str();
}

/// Returns the description of active parameter i
400
std::string CompositeFunction::descriptionOfActive(size_t i) const {
401
  size_t iFun = functionIndex(i);
402
  std::ostringstream ostr;
403
  ostr << m_functions[iFun]->descriptionOfActive(i - m_paramOffsets[iFun]);
404
  return ostr.str();
405
406
}

407
/// Change status of parameter
408
409
void CompositeFunction::setParameterStatus(size_t i,
                                           IFunction::ParameterStatus status) {
410
  size_t iFun = functionIndex(i);
411
  m_functions[iFun]->setParameterStatus(i - m_paramOffsets[iFun], status);
412
413
}

414
/// Get status of parameter
415
416
IFunction::ParameterStatus
CompositeFunction::getParameterStatus(size_t i) const {
417
  size_t iFun = functionIndex(i);
418
  return m_functions[iFun]->getParameterStatus(i - m_paramOffsets[iFun]);
419
420
}

421
/** Makes sure that the function is consistent.
422
 */
423
void CompositeFunction::checkFunction() {
424
  m_nParams = 0;
Stephen's avatar
Stephen committed
425
  m_nAttributes = m_nGlobalAttributes;
426
  m_paramOffsets.clear();
427
  m_IFunction.clear();
428
  m_attributeIndex.clear();
429

430
  std::vector<IFunction_sptr> functions(m_functions.begin(), m_functions.end());
431
432
  m_functions.clear();

Hahn, Steven's avatar
Hahn, Steven committed
433
  for (auto &f : functions) {
434
    CompositeFunction_sptr cf = std::dynamic_pointer_cast<CompositeFunction>(f);
435
436
    if (cf)
      cf->checkFunction();
437
438
439
440
    addFunction(f);
  }
}

441
/**
442
443
444
445
446
447
448
 * Remove all member functions
 */
void CompositeFunction::clear() {
  m_nParams = 0;
  m_paramOffsets.clear();
  m_IFunction.clear();
  m_functions.clear();
Stephen's avatar
Stephen committed
449
  m_attributeIndex.clear();
450
451
}

452
/** Add a function
453
 * @param f :: A pointer to the added function
454
 * @return The function index
455
 */
456
457
size_t CompositeFunction::addFunction(IFunction_sptr f) {
  m_IFunction.insert(m_IFunction.end(), f->nParams(), m_functions.size());
458
459
  m_attributeIndex.insert(m_attributeIndex.end(), f->nAttributes(),
                          m_functions.size());
460
  m_functions.emplace_back(f);
461
  if (m_paramOffsets.empty()) {
462
    m_paramOffsets.emplace_back(0);
463
    m_nParams = f->nParams();
Stephen's avatar
Stephen committed
464
    m_nAttributes = f->nAttributes() + m_nGlobalAttributes;
465
  } else {
466
    m_paramOffsets.emplace_back(m_nParams);
467
    m_nParams += f->nParams();
468
    m_nAttributes += f->nAttributes();
469
  }
470
  return m_functions.size() - 1;
471
472
}

473
/** Remove a function
474
 * @param i :: The index of the function to remove
475
 */
476
void CompositeFunction::removeFunction(size_t i) {
477
478
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(i) +
479
480
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
481
  }
482

483
  IFunction_sptr fun = getFunction(i);
484
  // Remove ties which are no longer valid
485
486
487
  for (size_t j = 0; j < nParams();) {
    ParameterTie *tie = getTie(j);
    if (tie && tie->findParametersOf(fun.get())) {
488
      removeTie(j);
489
    } else {
490
491
492
493
      j++;
    }
  }

494
495
496
497
498
499
500
  // 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;
501
    } else {
502
      return false;
503
    }
504
  };
Stephen's avatar
Stephen committed
505

506
507
508
509
510
511
  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());
512

Stephen's avatar
Stephen committed
513
514
515
516
  // Reduction in parameters and attributes
  m_nParams -= fun->nParams();
  m_nAttributes -= fun->nAttributes();

517
518
519
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
520
    m_paramOffsets[j] -= fun->nParams();
521
  }
522
  m_paramOffsets.erase(m_paramOffsets.begin() + i);
523

524
  m_functions.erase(m_functions.begin() + i);
525
526
}

527
/** Replace a function with a new one. The old function is deleted.
528
 *  The new function must have already its workspace set.
529
 * @param f_old :: The pointer to the function to replace. If it's not
530
 *  a member of this composite function nothing happens
531
 * @param f_new :: A pointer to the new function
532
 */
David Fairbrother's avatar
David Fairbrother committed
533
534
void CompositeFunction::replaceFunctionPtr(const IFunction_sptr &f_old,
                                           const IFunction_sptr &f_new) {
535
536
537
538
  std::vector<IFunction_sptr>::const_iterator it =
      std::find(m_functions.begin(), m_functions.end(), f_old);
  if (it == m_functions.end())
    return;
539
  std::vector<IFunction_sptr>::difference_type iFun = it - m_functions.begin();
540
  replaceFunction(iFun, f_new);
541
542
}

543
/** Replace a function with a new one. The old function is deleted.
544
545
 * @param i :: The index of the function to replace
 * @param f :: A pointer to the new function
546
 */
547
548
549
550
void CompositeFunction::replaceFunction(size_t functionIndex,
                                        const IFunction_sptr &f) {
  if (functionIndex >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(functionIndex) +
551
552
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
553
  }
554

555
  IFunction_sptr fun = getFunction(functionIndex);
556
557
  size_t np_old = fun->nParams();
  size_t np_new = f->nParams();
Stephen's avatar
Stephen committed
558
559
  size_t at_old = fun->nAttributes();
  size_t at_new = f->nAttributes();
560

561
562
  // Modify function parameter and attribute indices:
  // The new function may have different number of
563
  {
564
565
566
    auto itFun =
        std::find(m_IFunction.begin(), m_IFunction.end(), functionIndex);

567
    if (itFun != m_IFunction.end()) // functions must have at least 1 parameter
568
    {
569
570
571
      if (np_old > np_new) {
        m_IFunction.erase(itFun, itFun + np_old - np_new);
      } else if (np_old < np_new) {
572
        m_IFunction.insert(itFun, np_new - np_old, functionIndex);
573
      }
574
575
    } else if (np_new > 0) // it could happen if the old function is an empty
                           // CompositeFunction
576
    {
577
      using std::placeholders::_1;
578
579
580
581
      itFun =
          std::find_if(m_IFunction.begin(), m_IFunction.end(),
                       std::bind(std::greater<size_t>(), _1, functionIndex));
      m_IFunction.insert(itFun, np_new, functionIndex);
582
    }
583
584
  }

585
  size_t dnp = np_new - np_old;
Stephen's avatar
Stephen committed
586
  size_t dna = at_new - at_old;
587
  m_nParams += dnp;
Stephen's avatar
Stephen committed
588
  m_nAttributes += dna;
589
590
  // Shift the parameter offsets down by the total number of i-th function's
  // params
591
  for (size_t j = functionIndex + 1; j < nFunctions(); j++) {
592
593
    m_paramOffsets[j] += dnp;
  }
594
  m_functions[functionIndex] = f;
595
596
}

597
/**
598
 * @param i :: The index of the function
599
 * @return function at the requested index
600
 */
601
602
IFunction_sptr CompositeFunction::getFunction(std::size_t i) const {
  if (i >= nFunctions()) {
603
    throw std::out_of_range("Function index (" + std::to_string(i) +
604
605
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
606
  }
607
608
609
  return m_functions[i];
}

610
611
/**
 * Get the index of the function to which parameter i belongs
612
 * @param i :: The parameter index
613
 * @return function index of the requested parameter
614
 */
615
616
size_t CompositeFunction::functionIndex(std::size_t i) const {
  if (i >= nParams()) {
617
    throw std::out_of_range("Function parameter index (" + std::to_string(i) +
618
619
                            ") out of range (" + std::to_string(nParams()) +
                            ").");
620
  }
621
  return m_IFunction[i];
622
}
623
624
625
626
627
628
629
630
631
632
633
634
635
/**
 * 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];
}
636
637

/**
LamarMoore's avatar
LamarMoore committed
638
639
640
 * @param varName :: The variable name which may contain function index (
 * [f<index.>]name )
 * @param index :: Receives function index or throws std::invalid_argument
641
 * @param name :: Receives the variable name
LamarMoore's avatar
LamarMoore committed
642
 */
643
644
std::pair<std::string, size_t>
CompositeFunction::parseName(const std::string &varName) {
645
  size_t i = varName.find('.');
646
  if (i == std::string::npos) {
647
    throw std::invalid_argument("Parameter " + varName + " not found.");
648
  } else {
649
    std::string name;
650
    if (varName[0] != 'f')
651
652
      throw std::invalid_argument(
          "External function parameter name must start with 'f'");
653

654
    std::string sindex = varName.substr(1, i - 1);
655
    size_t index = boost::lexical_cast<size_t>(sindex);
656
657
658
659

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

660
    return std::make_pair(varName.substr(i + 1), index);
661
  }
662
663
}

664
/** Returns the index of parameter i as it declared in its function
665
 * @param i :: The parameter index
666
 * @param recursive :: If true call parameterLocalName recursively until
667
 *    a non-composite function is reached.
668
669
 * @return The local index of the parameter
 */
670
size_t CompositeFunction::parameterLocalIndex(size_t i, bool recursive) const {
671
  size_t iFun = functionIndex(i);
672
673
  auto localIndex = i - m_paramOffsets[iFun];
  if (recursive) {
674
    auto cf = dynamic_cast<const CompositeFunction *>(m_functions[iFun].get());
675
676
677
678
679
    if (cf) {
      return cf->parameterLocalIndex(localIndex, recursive);
    }
  }
  return localIndex;
680
681
}

682
/** Returns the name of parameter i as it declared in its function
683
 * @param i :: The parameter index
684
 * @param recursive :: If true call parameterLocalName recursively until
685
 *    a non-composite function is reached.
686
687
 * @return The pure parameter name (without the function identifier f#.)
 */
688
689
std::string CompositeFunction::parameterLocalName(size_t i,
                                                  bool recursive) const {
690
  size_t iFun = functionIndex(i);
691
692
693
  auto localIndex = i - m_paramOffsets[iFun];
  auto localFunction = m_functions[iFun].get();
  if (recursive) {
694
    auto cf = dynamic_cast<const CompositeFunction *>(localFunction);
695
696
697
698
699
    if (cf) {
      return cf->parameterLocalName(localIndex, recursive);
    }
  }
  return localFunction->parameterName(localIndex);
700
701
}

702
/**
703
 * Apply the ties.
704
 */
705
void CompositeFunction::applyTies() {
706
707
708
709
710
711
712
  if (hasOrderedTies()) {
    applyOrderedTies();
  } else {
    for (size_t i = 0; i < nFunctions(); i++) {
      getFunction(i)->applyTies();
    }
    IFunction::applyTies();
713
714
715
716
  }
}

/**
717
 * Clear the ties.
718
 */
719
void CompositeFunction::clearTies() {
720
  IFunction::clearTies();
721
  for (size_t i = 0; i < nFunctions(); i++) {
722
723
724
725
726
    getFunction(i)->clearTies();
  }
}

/** Removes i-th parameter's tie if it is tied or does nothing.
727
 * @param i :: The index of the tied parameter.
728
 * @return True if successful
729
 */
730
bool CompositeFunction::removeTie(size_t i) {
731
732
733
734
735
736
737
  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;
738
739
740
}

/** Get the tie of i-th parameter
741
 * @param i :: The parameter index
742
 * @return A pointer to the tie.
743
 */
744
ParameterTie *CompositeFunction::getTie(size_t i) const {
745
746
747
748
749
750
  auto tie = IFunction::getTie(i);
  if (tie == nullptr) {
    size_t iFun = functionIndex(i);
    tie = m_functions[iFun]->getTie(i - m_paramOffsets[iFun]);
  }
  return tie;
751
752
753
}

/**
754
 * Declare a new parameter. To used in the implementation's constructor.
755
756
 * @param name :: The parameter name.
 * @param initValue :: The initial value for the parameter
757
 * @param description :: Parameter documentation
758
 */
759
760
761
762
763
764
765
766
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.");
767
768
}

769
770
771
/**
 * Prepare the function for a fit.
 */
772
void CompositeFunction::setUpForFit() {
773
  IFunction::setUpForFit();
774
  // set up the member functions
775
  for (size_t i = 0; i < nFunctions(); i++) {
776
    getFunction(i)->setUpForFit();
777
  }
778
779

  // Instead of automatically switching to numeric derivatives
780
  // log a warning about a danger of not using it
781
782
783
784
785
  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 "
786
                           "non-constant ties defined.\n";
787
788
        break;
      }
789
    }
790
791
792
  }
}

Nick Draper's avatar
re #100    
Nick Draper committed
793
/// Get constraint
794
/// @param i :: the index
Nick Draper's avatar
re #100    
Nick Draper committed
795
/// @return A pointer to the constraint
796
IConstraint *CompositeFunction::getConstraint(size_t i) const {
797
798
799
800
801
802
  auto constraint = IFunction::getConstraint(i);
  if (constraint == nullptr) {
    size_t iFun = functionIndex(i);
    constraint = m_functions[iFun]->getConstraint(i - m_paramOffsets[iFun]);
  }
  return constraint;
803
804
}

805
/** Remove a constraint
806
 * @param parName :: The name of a parameter which constraint to remove.
807
 */
808
void CompositeFunction::removeConstraint(const std::string &parName) {
809
810
811
812
813
814
815
816
817
  auto i = parameterIndex(parName);
  auto constraint = IFunction::getConstraint(i);
  if (constraint != nullptr) {
    IFunction::removeConstraint(parName);
  } else {
    size_t iPar = parameterIndex(parName);
    size_t iFun = functionIndex(iPar);
    getFunction(iFun)->removeConstraint(parameterLocalName(iPar));
  }
818
819
}

820
/** Checks if a constraint has been explicitly set
821
 *  @param i :: The parameter index
822
 *  @return true if the function is explicitly set