CompositeFunction.cpp 26.1 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
21
22
#include <boost/shared_array.hpp>
#include <sstream>

23
24
namespace Mantid {
namespace API {
25

26
27
28
namespace {
/// static logger
Kernel::Logger g_log("CompositeFunction");
LamarMoore's avatar
LamarMoore committed
29
} // namespace
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
30

Peterson, Peter's avatar
Peterson, Peter committed
31
32
using std::size_t;

33
DECLARE_FUNCTION(CompositeFunction)
34

35
/// Default constructor
36
37
CompositeFunction::CompositeFunction()
    : IFunction(), m_nParams(0), m_iConstraintFunction(false) {
38
39
40
  declareAttribute("NumDeriv", Attribute(false));
}

41
/// Function initialization. Declare function parameters in this method.
42
void CompositeFunction::init() {}
43

44
/**
45
46
47
 * Writes itself into a string. Functions derived from CompositeFunction may
 * need to override this method with something like this:
 *   std::string NewFunction::writeToString()const
48
49
50
51
52
53
54
 *   {
 *      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
55
56
 * @param parentLocalAttributesStr :: A preformatted string with parent's local
 * attributes.
57
 *    Can be passed in by a CompositeFunction (eg MultiDomainFunction).
58
 * @return the string representation of the composite function
59
 */
Roman Tolchenov's avatar
Roman Tolchenov committed
60
61
std::string CompositeFunction::writeToString(
    const std::string &parentLocalAttributesStr) const {
62
  std::ostringstream ostr;
63

64
  // if empty just return function name
65
  if (nFunctions() == 0) {
66
67
68
    return "name=" + name();
  }

69
  if (name() != "CompositeFunction" || nAttributes() > 1 ||
70
      getAttribute("NumDeriv").asBool() || !parentLocalAttributesStr.empty()) {
71
    ostr << "composite=" << name();
72
    std::vector<std::string> attr = this->getAttributeNames();
73
74
    for (const auto &attName : attr) {
      std::string attValue = this->getAttribute(attName).value();
75
76
      if (!attValue.empty()) {
        ostr << ',' << attName << '=' << attValue;
77
78
      }
    }
79
    ostr << parentLocalAttributesStr << ';';
80
  }
81
  const auto localAttr = this->getLocalAttributeNames();
82
  for (size_t i = 0; i < nFunctions(); i++) {
83
    IFunction_sptr fun = getFunction(i);
Hahn, Steven's avatar
Hahn, Steven committed
84
85
    bool isComp =
        boost::dynamic_pointer_cast<CompositeFunction>(fun) != nullptr;
86
87
    if (isComp)
      ostr << '(';
88
    std::ostringstream localAttributesStr;
89
90
91
92
93
    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
94
95
        localAttributesStr << ',' << '$' << localAttName << '='
                           << localAttValue;
96
97
      }
    }
98
    ostr << fun->writeToString(localAttributesStr.str());
99
100
101
    if (isComp)
      ostr << ')';
    if (i < nFunctions() - 1) {
102
103
104
      ostr << ';';
    }
  }
105
106
107
108
109
110

  // collect non-default constraints
  std::string constraints = writeConstraints();
  // print constraints
  if (!constraints.empty()) {
    ostr << ";constraints=(" << constraints << ")";
111
  }
112
113
114
115

  // collect the non-default ties
  std::string ties = writeTies();
  // print the ties
116
  if (!ties.empty()) {
117
    ostr << ";ties=(" << ties << ")";
118
  }
119

120
121
122
  return ostr.str();
}

123
124
125
/**
 * @param ws A pointer to the workspace being fitted
 */
126
void CompositeFunction::setWorkspace(boost::shared_ptr<const Workspace> ws) {
127
128
  // Pass it on to each member
  auto iend = m_functions.end();
129
  for (auto it = m_functions.begin(); it != iend; ++it) {
130
131
132
133
    (*it)->setWorkspace(ws);
  }
}

134
135
136
137
138
139
/**
 * @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.
 */
140
141
142
143
144
145
void CompositeFunction::setMatrixWorkspace(
    boost::shared_ptr<const MatrixWorkspace> workspace, size_t wi,
    double startX, double endX) {
  for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
    m_functions[iFun]->setMatrixWorkspace(workspace, wi, startX, endX);
  }
146
147
}

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

180
/** Sets a new value to the i-th parameter.
181
182
 *  @param i :: The parameter index
 *  @param value :: The new value
183
184
 *  @param explicitlySet :: A boolean falgging the parameter as explicitly set
 * (by user)
185
 */
186
187
void CompositeFunction::setParameter(size_t i, const double &value,
                                     bool explicitlySet) {
188
  size_t iFun = functionIndex(i);
189
190
  m_functions[iFun]->setParameter(i - m_paramOffsets[iFun], value,
                                  explicitlySet);
191
192
}

193
194
195
196
/** Sets a new description to the i-th parameter.
 *  @param i :: The parameter index
 *  @param description :: The new description
 */
197
198
void CompositeFunction::setParameterDescription(
    size_t i, const std::string &description) {
199
  size_t iFun = functionIndex(i);
200
201
  m_functions[iFun]->setParameterDescription(i - m_paramOffsets[iFun],
                                             description);
202
203
}

204
/** Get the i-th parameter.
205
 *  @param i :: The parameter index
206
 *  @return value of the requested parameter
207
 */
208
double CompositeFunction::getParameter(size_t i) const {
Peterson, Peter's avatar
Peterson, Peter committed
209
  size_t iFun = functionIndex(i);
210
  return m_functions[iFun]->getParameter(i - m_paramOffsets[iFun]);
211
212
}

213
214
215
216
/**
 * 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
217
 */
218
219
220
221
222
223
224
225
226
227
228
229
bool CompositeFunction::hasParameter(const std::string &name) const {
  try {
    std::string pname;
    size_t index;
    parseName(name, index, pname);
    return index < m_functions.size() ? m_functions[index]->hasParameter(pname)
                                      : false;
  } catch (std::invalid_argument &) {
    return false;
  }
}

230
231
/**
 * Sets a new value to a parameter by name.
232
233
 * @param name :: The name of the parameter.
 * @param value :: The new value
234
235
 * @param explicitlySet :: A boolean falgging the parameter as explicitly set
 * (by user)
236
 */
237
238
void CompositeFunction::setParameter(const std::string &name,
                                     const double &value, bool explicitlySet) {
239
  std::string pname;
240
  size_t index;
241
242
  parseName(name, index, pname);
  getFunction(index)->setParameter(pname, value, explicitlySet);
243
244
}

245
246
247
/**
 * Sets a new description to a parameter by name.
 * @param name :: The name of the parameter.
248
 * @param description :: The new description
249
 */
250
251
void CompositeFunction::setParameterDescription(
    const std::string &name, const std::string &description) {
252
  std::string pname;
253
  size_t index;
254
255
  parseName(name, index, pname);
  getFunction(index)->setParameterDescription(pname, description);
256
257
}

258
259
/**
 * Parameters by name.
260
 * @param name :: The name of the parameter.
261
 * @return value of the requested named parameter
262
 */
263
double CompositeFunction::getParameter(const std::string &name) const {
264
  std::string pname;
265
  size_t index;
266
  parseName(name, index, pname);
267
  return getFunction(index)->getParameter(pname);
268
269
270
}

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

273
/**
274
 *
275
 * @param name :: The name of a parameter
276
 * @return index of the requested named parameter
277
 */
278
size_t CompositeFunction::parameterIndex(const std::string &name) const {
279
  std::string pname;
280
  size_t index;
281
  parseName(name, index, pname);
282
  return getFunction(index)->parameterIndex(pname) + m_paramOffsets[index];
283
284
}

Nick Draper's avatar
re #100    
Nick Draper committed
285
/// Returns the name of parameter
286
/// @param i :: The index
Nick Draper's avatar
re #100    
Nick Draper committed
287
/// @return The name of the parameter
288
std::string CompositeFunction::parameterName(size_t i) const {
289
  size_t iFun = functionIndex(i);
290
  std::ostringstream ostr;
291
292
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->parameterName(i - m_paramOffsets[iFun]);
293
  return ostr.str();
294
295
}

296
297
298
/// Returns the description of parameter
/// @param i :: The index
/// @return The description of the parameter
299
std::string CompositeFunction::parameterDescription(size_t i) const {
300
  size_t iFun = functionIndex(i);
301
  std::ostringstream ostr;
302
  ostr << m_functions[iFun]->parameterDescription(i - m_paramOffsets[iFun]);
303
304
305
  return ostr.str();
}

306
/**
307
308
309
310
 * Get the fitting error for a parameter
 * @param i :: The index of a parameter
 * @return :: the error
 */
311
double CompositeFunction::getError(size_t i) const {
312
  size_t iFun = functionIndex(i);
313
  return m_functions[iFun]->getError(i - m_paramOffsets[iFun]);
314
315
}

316
/**
317
318
319
320
 * Set the fitting error for a parameter
 * @param i :: The index of a parameter
 * @param err :: The error value to set
 */
321
void CompositeFunction::setError(size_t i, double err) {
322
  size_t iFun = functionIndex(i);
323
  m_functions[iFun]->setError(i - m_paramOffsets[iFun], err);
324
325
}

326
327
328
/// Value of i-th active parameter. Override this method to make fitted
/// parameters different from the declared
double CompositeFunction::activeParameter(size_t i) const {
329
  size_t iFun = functionIndex(i);
330
  return m_functions[iFun]->activeParameter(i - m_paramOffsets[iFun]);
331
332
}

333
334
335
/// 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) {
336
  size_t iFun = functionIndex(i);
337
  m_functions[iFun]->setActiveParameter(i - m_paramOffsets[iFun], value);
338
339
340
}

/// Returns the name of active parameter i
341
std::string CompositeFunction::nameOfActive(size_t i) const {
342
  size_t iFun = functionIndex(i);
343
  std::ostringstream ostr;
344
345
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->nameOfActive(i - m_paramOffsets[iFun]);
346
347
348
349
  return ostr.str();
}

/// Returns the description of active parameter i
350
std::string CompositeFunction::descriptionOfActive(size_t i) const {
351
  size_t iFun = functionIndex(i);
352
  std::ostringstream ostr;
353
  ostr << m_functions[iFun]->descriptionOfActive(i - m_paramOffsets[iFun]);
354
  return ostr.str();
355
356
}

357
/// Change status of parameter
358
359
void CompositeFunction::setParameterStatus(size_t i,
                                           IFunction::ParameterStatus status) {
360
  size_t iFun = functionIndex(i);
361
  m_functions[iFun]->setParameterStatus(i - m_paramOffsets[iFun], status);
362
363
}

364
/// Get status of parameter
365
366
IFunction::ParameterStatus
CompositeFunction::getParameterStatus(size_t i) const {
367
  size_t iFun = functionIndex(i);
368
  return m_functions[iFun]->getParameterStatus(i - m_paramOffsets[iFun]);
369
370
}

371
/** Makes sure that the function is consistent.
372
 */
373
void CompositeFunction::checkFunction() {
374
375
  m_nParams = 0;
  m_paramOffsets.clear();
376
  m_IFunction.clear();
377

378
  std::vector<IFunction_sptr> functions(m_functions.begin(), m_functions.end());
379
380
  m_functions.clear();

Hahn, Steven's avatar
Hahn, Steven committed
381
  for (auto &f : functions) {
382
383
384
385
    CompositeFunction_sptr cf =
        boost::dynamic_pointer_cast<CompositeFunction>(f);
    if (cf)
      cf->checkFunction();
386
387
388
389
    addFunction(f);
  }
}

390
/**
391
392
393
394
395
396
397
398
399
 * Remove all member functions
 */
void CompositeFunction::clear() {
  m_nParams = 0;
  m_paramOffsets.clear();
  m_IFunction.clear();
  m_functions.clear();
}

400
/** Add a function
401
 * @param f :: A pointer to the added function
402
 * @return The function index
403
 */
404
405
size_t CompositeFunction::addFunction(IFunction_sptr f) {
  m_IFunction.insert(m_IFunction.end(), f->nParams(), m_functions.size());
406
  m_functions.emplace_back(f);
407
  //?f->init();
408
  if (m_paramOffsets.empty()) {
409
    m_paramOffsets.emplace_back(0);
410
    m_nParams = f->nParams();
411
  } else {
412
    m_paramOffsets.emplace_back(m_nParams);
413
414
    m_nParams += f->nParams();
  }
415
  return m_functions.size() - 1;
416
417
}

418
/** Remove a function
419
 * @param i :: The index of the function to remove
420
 */
421
void CompositeFunction::removeFunction(size_t i) {
422
423
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(i) +
424
425
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
426
  }
427

428
  IFunction_sptr fun = getFunction(i);
429
  // Reduction in parameters
430
  size_t dnp = fun->nParams();
431

432
433
434
  for (size_t j = 0; j < nParams();) {
    ParameterTie *tie = getTie(j);
    if (tie && tie->findParametersOf(fun.get())) {
435
      removeTie(j);
436
    } else {
437
438
439
440
441
      j++;
    }
  }

  // Shift down the function indeces for parameters
442
  for (auto it = m_IFunction.begin(); it != m_IFunction.end();) {
443

444
    if (*it == i) {
445
      it = m_IFunction.erase(it);
446
447
    } else {
      if (*it > i) {
448
449
        *it -= 1;
      }
450
      ++it;
451
452
453
454
    }
  }

  m_nParams -= dnp;
455
456
457
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
458
459
    m_paramOffsets[j] -= dnp;
  }
460
  m_paramOffsets.erase(m_paramOffsets.begin() + i);
461

462
  m_functions.erase(m_functions.begin() + i);
463
464
}

465
/** Replace a function with a new one. The old function is deleted.
466
 *  The new function must have already its workspace set.
467
 * @param f_old :: The pointer to the function to replace. If it's not
468
 *  a member of this composite function nothing happens
469
 * @param f_new :: A pointer to the new function
470
 */
471
472
473
474
475
476
void CompositeFunction::replaceFunctionPtr(const IFunction_sptr f_old,
                                           IFunction_sptr f_new) {
  std::vector<IFunction_sptr>::const_iterator it =
      std::find(m_functions.begin(), m_functions.end(), f_old);
  if (it == m_functions.end())
    return;
477
  std::vector<IFunction_sptr>::difference_type iFun = it - m_functions.begin();
478
  replaceFunction(iFun, f_new);
479
480
}

481
/** Replace a function with a new one. The old function is deleted.
482
483
 * @param i :: The index of the function to replace
 * @param f :: A pointer to the new function
484
 */
485
void CompositeFunction::replaceFunction(size_t i, IFunction_sptr f) {
486
487
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(i) +
488
489
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
490
  }
491

492
  IFunction_sptr fun = getFunction(i);
493
  size_t np_old = fun->nParams();
494

495
  size_t np_new = f->nParams();
496

497
498
  // Modify function indeces: The new function may have different number of
  // parameters
499
  {
500
    auto itFun = std::find(m_IFunction.begin(), m_IFunction.end(), i);
501
    if (itFun != m_IFunction.end()) // functions must have at least 1 parameter
502
    {
503
504
505
506
      if (np_old > np_new) {
        m_IFunction.erase(itFun, itFun + np_old - np_new);
      } else if (np_old < np_new) {
        m_IFunction.insert(itFun, np_new - np_old, i);
507
      }
508
509
    } else if (np_new > 0) // it could happen if the old function is an empty
                           // CompositeFunction
510
    {
511
      using std::placeholders::_1;
512
      itFun = std::find_if(m_IFunction.begin(), m_IFunction.end(),
513
                           std::bind(std::greater<size_t>(), _1, i));
514
      m_IFunction.insert(itFun, np_new, i);
515
    }
516
517
  }

518
  size_t dnp = np_new - np_old;
519
  m_nParams += dnp;
520
521
522
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
523
524
525
526
527
528
    m_paramOffsets[j] += dnp;
  }

  m_functions[i] = f;
}

529
/**
530
 * @param i :: The index of the function
531
 * @return function at the requested index
532
 */
533
534
IFunction_sptr CompositeFunction::getFunction(std::size_t i) const {
  if (i >= nFunctions()) {
535
    throw std::out_of_range("Function index (" + std::to_string(i) +
536
537
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
538
  }
539
540
541
  return m_functions[i];
}

542
543
/**
 * Get the index of the function to which parameter i belongs
544
 * @param i :: The parameter index
545
 * @return function index of the requested parameter
546
 */
547
548
size_t CompositeFunction::functionIndex(std::size_t i) const {
  if (i >= nParams()) {
549
    throw std::out_of_range("Function parameter index (" + std::to_string(i) +
550
551
                            ") out of range (" + std::to_string(nParams()) +
                            ").");
552
  }
553
  return m_IFunction[i];
554
555
556
}

/**
LamarMoore's avatar
LamarMoore committed
557
558
559
560
561
 * @param varName :: The variable name which may contain function index (
 * [f<index.>]name )
 * @param index :: Receives function index or throws std::invalid_argument
 * @param name :: Receives the parameter name
 */
562
563
void CompositeFunction::parseName(const std::string &varName, size_t &index,
                                  std::string &name) {
564
  size_t i = varName.find('.');
565
  if (i == std::string::npos) {
566
    throw std::invalid_argument("Parameter " + varName + " not found.");
567
  } else {
568
    if (varName[0] != 'f')
569
570
      throw std::invalid_argument(
          "External function parameter name must start with 'f'");
571

572
    std::string sindex = varName.substr(1, i - 1);
573
574
575
576
577
    index = boost::lexical_cast<int>(sindex);

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

578
    name = varName.substr(i + 1);
579
  }
580
581
}

582
/** Returns the index of parameter i as it declared in its function
583
 * @param i :: The parameter index
584
585
 * @param recursive :: If true call parameterLocalName recusively until
 *    a non-composite function is reached.
586
587
 * @return The local index of the parameter
 */
588
size_t CompositeFunction::parameterLocalIndex(size_t i, bool recursive) const {
589
  size_t iFun = functionIndex(i);
590
591
  auto localIndex = i - m_paramOffsets[iFun];
  if (recursive) {
592
    auto cf = dynamic_cast<const CompositeFunction *>(m_functions[iFun].get());
593
594
595
596
597
    if (cf) {
      return cf->parameterLocalIndex(localIndex, recursive);
    }
  }
  return localIndex;
598
599
}

600
/** Returns the name of parameter i as it declared in its function
601
 * @param i :: The parameter index
602
603
 * @param recursive :: If true call parameterLocalName recusively until
 *    a non-composite function is reached.
604
605
 * @return The pure parameter name (without the function identifier f#.)
 */
606
607
std::string CompositeFunction::parameterLocalName(size_t i,
                                                  bool recursive) const {
608
  size_t iFun = functionIndex(i);
609
610
611
  auto localIndex = i - m_paramOffsets[iFun];
  auto localFunction = m_functions[iFun].get();
  if (recursive) {
612
    auto cf = dynamic_cast<const CompositeFunction *>(localFunction);
613
614
615
616
617
    if (cf) {
      return cf->parameterLocalName(localIndex, recursive);
    }
  }
  return localFunction->parameterName(localIndex);
618
619
}

620
/**
621
 * Apply the ties.
622
 */
623
void CompositeFunction::applyTies() {
624
625
626
627
628
629
630
  if (hasOrderedTies()) {
    applyOrderedTies();
  } else {
    for (size_t i = 0; i < nFunctions(); i++) {
      getFunction(i)->applyTies();
    }
    IFunction::applyTies();
631
632
633
634
  }
}

/**
635
 * Clear the ties.
636
 */
637
void CompositeFunction::clearTies() {
638
  IFunction::clearTies();
639
  for (size_t i = 0; i < nFunctions(); i++) {
640
641
642
643
644
    getFunction(i)->clearTies();
  }
}

/** Removes i-th parameter's tie if it is tied or does nothing.
645
 * @param i :: The index of the tied parameter.
646
647
 * @return True if successfull
 */
648
bool CompositeFunction::removeTie(size_t i) {
649
650
651
652
653
654
655
  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;
656
657
658
}

/** Get the tie of i-th parameter
659
 * @param i :: The parameter index
660
 * @return A pointer to the tie.
661
 */
662
ParameterTie *CompositeFunction::getTie(size_t i) const {
663
664
665
666
667
668
  auto tie = IFunction::getTie(i);
  if (tie == nullptr) {
    size_t iFun = functionIndex(i);
    tie = m_functions[iFun]->getTie(i - m_paramOffsets[iFun]);
  }
  return tie;
669
670
671
672
}

/**
 * Declare a new parameter. To used in the implementation'c constructor.
673
674
 * @param name :: The parameter name.
 * @param initValue :: The initial value for the parameter
675
 * @param description :: Parameter documentation
676
 */
677
678
679
680
681
682
683
684
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.");
685
686
}

687
688
689
/**
 * Prepare the function for a fit.
 */
690
void CompositeFunction::setUpForFit() {
691
  IFunction::setUpForFit();
692
  // set up the member functions
693
  for (size_t i = 0; i < nFunctions(); i++) {
694
    getFunction(i)->setUpForFit();
695
  }
696
697
698
699
  // unfortuately the code below breaks some system tests (IRISFuryAndFuryFit)
  // it looks as if using numeric derivatives can give different fit results
  // to fit with analytical ones
  //
700
  // if parameters have non-constant ties enable numerical derivatives
701
  // for(size_t i = 0; i < nParams(); ++i)
702
703
704
705
706
707
708
709
710
711
712
  //{
  //  ParameterTie* tie = getTie( i );
  //  if ( tie && !tie->isConstant() )
  //  {
  //    useNumericDerivatives( true );
  //    break;
  //  }
  //}

  // instead of automatically switching to numeric derivatives
  // log a warning about a danger of not using it
713
714
715
716
717
  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 "
718
                           "non-constant ties defined.\n";
719
720
        break;
      }
721
    }
722
723
724
  }
}

Nick Draper's avatar
re #100    
Nick Draper committed
725
/// Get constraint
726
/// @param i :: the index
Nick Draper's avatar
re #100    
Nick Draper committed
727
/// @return A pointer to the constraint
728
IConstraint *CompositeFunction::getConstraint(size_t i) const {
729
730
731
732
733
734
  auto constraint = IFunction::getConstraint(i);
  if (constraint == nullptr) {
    size_t iFun = functionIndex(i);
    constraint = m_functions[iFun]->getConstraint(i - m_paramOffsets[iFun]);
  }
  return constraint;
735
736
}

737
/** Remove a constraint
738
 * @param parName :: The name of a parameter which constarint to remove.
739
 */
740
void CompositeFunction::removeConstraint(const std::string &parName) {
741
742
743
744
745
746
747
748
749
  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));
  }
750
751
}

752
/** Checks if a constraint has been explicitly set
753
 *  @param i :: The parameter index
754
 *  @return true if the function is explicitly set
755
 */
756
bool CompositeFunction::isExplicitlySet(size_t i) const {
757
  size_t iFun = functionIndex(i);
758
  return m_functions[iFun]->isExplicitlySet(i - m_paramOffsets[iFun]);
759
760
}

761
/**
762
763
 * Returns the index of parameter if the ref points to one of the member
 * function
764
 * @param ref :: A reference to a parameter
765
 * @return Parameter index or number of nParams() if parameter not found
766
 */
767
768
size_t
CompositeFunction::getParameterIndex(const ParameterReference &ref) const {
769
770
  if (ref.getLocalFunction() == this && ref.getLocalIndex() < nParams()) {
    return ref.getLocalIndex();
771
  }
772
  for (size_t iFun = 0; iFun < nFunctions(); iFun++) {
773
    IFunction_sptr fun = getFunction(iFun);
774
    size_t iLocalIndex = fun->getParameterIndex(ref);
775
    if (iLocalIndex < fun->nParams()) {
776
777
778
      return m_paramOffsets[iFun] + iLocalIndex;
    }
  }
779
  return nParams();
780
781
}

782
/**
783
 * Returns the shrared pointer to the function conataining a parameter
784
 * @param ref :: The reference
785
786
 * @return A function containing parameter pointed to by ref
 */
787
788
789
IFunction_sptr
CompositeFunction::getContainingFunction(const ParameterReference &ref) const {
  for (size_t iFun = 0; iFun < nFunctions(); iFun++) {
790
    IFunction_sptr fun = getFunction(iFun);
791
    if (fun->getParameterIndex(ref) < fun->nParams()) {
792
      return fun;
793
794
    }
  }
795
796
797
  return IFunction_sptr();
}

798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
/// Get number of domains required by this function
size_t CompositeFunction::getNumberDomains() const {
  auto n = nFunctions();
  if (n == 0) {
    return 1;
  }
  size_t nd = getFunction(0)->getNumberDomains();
  for (size_t iFun = 1; iFun < n; ++iFun) {
    if (getFunction(0)->getNumberDomains() != nd) {
      throw std::runtime_error("CompositeFunction has members with "
                               "inconsistent domain numbers.");
    }
  }
  return nd;
}

/// Split this function (if needed) into a list of independent functions.
/// The number of functions must be the number of domains this function is
/// working on (== getNumberDomains()). The result of evaluation of the
/// created functions on their domains must be the same as if this function
/// was evaluated on the composition of those domains.
Roman Tolchenov's avatar
Roman Tolchenov committed
819
820
std::vector<IFunction_sptr>
CompositeFunction::createEquivalentFunctions() const {
821
822
823