CompositeFunction.cpp 26.2 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
#include <boost/shared_array.hpp>
#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");
LamarMoore's avatar
LamarMoore committed
30
} // namespace
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
31

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

34
DECLARE_FUNCTION(CompositeFunction)
35

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

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

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

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

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

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

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

121
122
123
  return ostr.str();
}

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

135
136
137
138
139
140
/**
 * @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.
 */
141
142
143
144
145
146
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);
  }
147
148
}

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

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

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

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

214
215
216
217
/**
 * 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
218
 */
219
220
221
222
223
224
225
226
227
228
229
230
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;
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  m_functions[i] = f;
}

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

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

/**
LamarMoore's avatar
LamarMoore committed
558
559
560
561
562
 * @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
 */
563
564
void CompositeFunction::parseName(const std::string &varName, size_t &index,
                                  std::string &name) {
565
  size_t i = varName.find('.');
566
  if (i == std::string::npos) {
567
    throw std::invalid_argument("Parameter " + varName + " not found.");
568
  } else {
569
    if (varName[0] != 'f')
570
571
      throw std::invalid_argument(
          "External function parameter name must start with 'f'");
572

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

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

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

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

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

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

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

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

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

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

688
689
690
/**
 * Prepare the function for a fit.
 */
691
void CompositeFunction::setUpForFit() {
692
  IFunction::setUpForFit();
693
  // set up the member functions
694
  for (size_t i = 0; i < nFunctions(); i++) {
695
    getFunction(i)->setUpForFit();
696
  }
697
698
699
700
  // 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
  //
701
  // if parameters have non-constant ties enable numerical derivatives
702
  // for(size_t i = 0; i < nParams(); ++i)
703
704
705
706
707
708
709
710
711
712
713
  //{
  //  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
714
715
716
717
718
  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 "
719
                           "non-constant ties defined.\n";
720
721
        break;
      }
722
    }
723
724
725
  }
}

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

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

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

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

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

799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
/// 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