CompositeFunction.cpp 25.7 KB
Newer Older
1
2
3
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
4
5
#include "MantidAPI/CompositeFunction.h"
#include "MantidAPI/ParameterTie.h"
6
#include "MantidAPI/IConstraint.h"
7
#include "MantidAPI/FunctionFactory.h"
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
8
9
#include "MantidKernel/Exception.h"
#include "MantidKernel/Logger.h"
10
#include "MantidKernel/Strings.h"
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
11

12
#include <boost/lexical_cast.hpp>
13
14
#include <boost/shared_array.hpp>
#include <sstream>
15
#include <algorithm>
16

17
18
namespace Mantid {
namespace API {
19

20
21
22
23
namespace {
/// static logger
Kernel::Logger g_log("CompositeFunction");
}
Gigg, Martyn Anthony's avatar
Gigg, Martyn Anthony committed
24

Peterson, Peter's avatar
Peterson, Peter committed
25
26
using std::size_t;

27
DECLARE_FUNCTION(CompositeFunction)
28

29
/// Default constructor
30
31
CompositeFunction::CompositeFunction()
    : IFunction(), m_nParams(0), m_iConstraintFunction(false) {
32
33
34
  declareAttribute("NumDeriv", Attribute(false));
}

35
/// Function initialization. Declare function parameters in this method.
36
void CompositeFunction::init() {}
37

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

58
  // if empty just return function name
59
  if (nFunctions() == 0) {
60
61
62
    return "name=" + name();
  }

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

  // collect non-default constraints
  std::string constraints = writeConstraints();
  // print constraints
  if (!constraints.empty()) {
    ostr << ";constraints=(" << constraints << ")";
105
  }
106
107
108
109

  // collect the non-default ties
  std::string ties = writeTies();
  // print the ties
110
  if (!ties.empty()) {
111
    ostr << ";ties=(" << ties << ")";
112
  }
113

114
115
116
  return ostr.str();
}

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

128
129
130
131
132
133
/**
 * @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.
 */
134
135
136
137
138
139
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);
  }
140
141
}

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

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

187
188
189
190
/** Sets a new description to the i-th parameter.
 *  @param i :: The parameter index
 *  @param description :: The new description
 */
191
192
void CompositeFunction::setParameterDescription(
    size_t i, const std::string &description) {
193
  size_t iFun = functionIndex(i);
194
195
  m_functions[iFun]->setParameterDescription(i - m_paramOffsets[iFun],
                                             description);
196
197
}

198
/** Get the i-th parameter.
199
 *  @param i :: The parameter index
200
 *  @return value of the requested parameter
201
 */
202
double CompositeFunction::getParameter(size_t i) const {
Peterson, Peter's avatar
Peterson, Peter committed
203
  size_t iFun = functionIndex(i);
204
  return m_functions[iFun]->getParameter(i - m_paramOffsets[iFun]);
205
206
}

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/**
 * Check if function has a parameter with a particular name.
 * @param name :: A name of a parameter.
 * @return True if the parameter exists.
*/
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;
  }
}

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

239
240
241
/**
 * Sets a new description to a parameter by name.
 * @param name :: The name of the parameter.
242
 * @param description :: The new description
243
 */
244
245
void CompositeFunction::setParameterDescription(
    const std::string &name, const std::string &description) {
246
  std::string pname;
247
  size_t index;
248
249
  parseName(name, index, pname);
  getFunction(index)->setParameterDescription(pname, description);
250
251
}

252
253
/**
 * Parameters by name.
254
 * @param name :: The name of the parameter.
255
 * @return value of the requested named parameter
256
 */
257
double CompositeFunction::getParameter(const std::string &name) const {
258
  std::string pname;
259
  size_t index;
260
  parseName(name, index, pname);
261
  return getFunction(index)->getParameter(pname);
262
263
264
}

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

267
/**
268
 *
269
 * @param name :: The name of a parameter
270
 * @return index of the requested named parameter
271
 */
272
size_t CompositeFunction::parameterIndex(const std::string &name) const {
273
  std::string pname;
274
  size_t index;
275
  parseName(name, index, pname);
276
  return getFunction(index)->parameterIndex(pname) + m_paramOffsets[index];
277
278
}

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

290
291
292
/// Returns the description of parameter
/// @param i :: The index
/// @return The description of the parameter
293
std::string CompositeFunction::parameterDescription(size_t i) const {
294
  size_t iFun = functionIndex(i);
295
  std::ostringstream ostr;
296
  ostr << m_functions[iFun]->parameterDescription(i - m_paramOffsets[iFun]);
297
298
299
  return ostr.str();
}

300
/**
301
302
303
304
 * Get the fitting error for a parameter
 * @param i :: The index of a parameter
 * @return :: the error
 */
305
double CompositeFunction::getError(size_t i) const {
306
  size_t iFun = functionIndex(i);
307
  return m_functions[iFun]->getError(i - m_paramOffsets[iFun]);
308
309
}

310
/**
311
312
313
314
 * Set the fitting error for a parameter
 * @param i :: The index of a parameter
 * @param err :: The error value to set
 */
315
void CompositeFunction::setError(size_t i, double err) {
316
  size_t iFun = functionIndex(i);
317
  m_functions[iFun]->setError(i - m_paramOffsets[iFun], err);
318
319
}

320
321
322
/// Value of i-th active parameter. Override this method to make fitted
/// parameters different from the declared
double CompositeFunction::activeParameter(size_t i) const {
323
  size_t iFun = functionIndex(i);
324
  return m_functions[iFun]->activeParameter(i - m_paramOffsets[iFun]);
325
326
}

327
328
329
/// 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) {
330
  size_t iFun = functionIndex(i);
331
  m_functions[iFun]->setActiveParameter(i - m_paramOffsets[iFun], value);
332
333
334
}

/// Returns the name of active parameter i
335
std::string CompositeFunction::nameOfActive(size_t i) const {
336
  size_t iFun = functionIndex(i);
337
  std::ostringstream ostr;
338
339
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->nameOfActive(i - m_paramOffsets[iFun]);
340
341
342
343
  return ostr.str();
}

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

351
/// Change status of parameter
352
353
void CompositeFunction::setParameterStatus(size_t i,
                                           IFunction::ParameterStatus status) {
354
  size_t iFun = functionIndex(i);
355
  m_functions[iFun]->setParameterStatus(i - m_paramOffsets[iFun], status);
356
357
}

358
/// Get status of parameter
359
360
IFunction::ParameterStatus
CompositeFunction::getParameterStatus(size_t i) const {
361
  size_t iFun = functionIndex(i);
362
  return m_functions[iFun]->getParameterStatus(i - m_paramOffsets[iFun]);
363
364
}

365
/** Makes sure that the function is consistent.
366
 */
367
void CompositeFunction::checkFunction() {
368
369
  m_nParams = 0;
  m_paramOffsets.clear();
370
  m_IFunction.clear();
371

372
  std::vector<IFunction_sptr> functions(m_functions.begin(), m_functions.end());
373
374
  m_functions.clear();

Hahn, Steven's avatar
Hahn, Steven committed
375
  for (auto &f : functions) {
376
377
378
379
    CompositeFunction_sptr cf =
        boost::dynamic_pointer_cast<CompositeFunction>(f);
    if (cf)
      cf->checkFunction();
380
381
382
383
    addFunction(f);
  }
}

384
/**
385
386
387
388
389
390
391
392
393
 * Remove all member functions
 */
void CompositeFunction::clear() {
  m_nParams = 0;
  m_paramOffsets.clear();
  m_IFunction.clear();
  m_functions.clear();
}

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

412
/** Remove a function
413
 * @param i :: The index of the function to remove
414
 */
415
void CompositeFunction::removeFunction(size_t i) {
416
417
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(i) +
418
419
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
420
  }
421

422
  IFunction_sptr fun = getFunction(i);
423
  // Reduction in parameters
424
  size_t dnp = fun->nParams();
425

426
427
428
  for (size_t j = 0; j < nParams();) {
    ParameterTie *tie = getTie(j);
    if (tie && tie->findParametersOf(fun.get())) {
429
      removeTie(j);
430
    } else {
431
432
433
434
435
      j++;
    }
  }

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

438
    if (*it == i) {
439
      it = m_IFunction.erase(it);
440
441
    } else {
      if (*it > i) {
442
443
        *it -= 1;
      }
444
      ++it;
445
446
447
448
    }
  }

  m_nParams -= dnp;
449
450
451
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
452
453
    m_paramOffsets[j] -= dnp;
  }
454
  m_paramOffsets.erase(m_paramOffsets.begin() + i);
455

456
  m_functions.erase(m_functions.begin() + i);
457
458
}

459
/** Replace a function with a new one. The old function is deleted.
460
 *  The new function must have already its workspace set.
461
 * @param f_old :: The pointer to the function to replace. If it's not
462
 *  a member of this composite function nothing happens
463
 * @param f_new :: A pointer to the new function
464
 */
465
466
467
468
469
470
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;
471
  std::vector<IFunction_sptr>::difference_type iFun = it - m_functions.begin();
472
  replaceFunction(iFun, f_new);
473
474
}

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

486
  IFunction_sptr fun = getFunction(i);
487
  size_t np_old = fun->nParams();
488

489
  size_t np_new = f->nParams();
490

491
492
  // Modify function indeces: The new function may have different number of
  // parameters
493
  {
494
    auto itFun = std::find(m_IFunction.begin(), m_IFunction.end(), i);
495
    if (itFun != m_IFunction.end()) // functions must have at least 1 parameter
496
    {
497
498
499
500
      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);
501
      }
502
503
    } else if (np_new > 0) // it could happen if the old function is an empty
                           // CompositeFunction
504
    {
505
506
507
      itFun = std::find_if(m_IFunction.begin(), m_IFunction.end(),
                           std::bind2nd(std::greater<size_t>(), i));
      m_IFunction.insert(itFun, np_new, i);
508
    }
509
510
  }

511
  size_t dnp = np_new - np_old;
512
  m_nParams += dnp;
513
514
515
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
516
517
518
519
520
521
    m_paramOffsets[j] += dnp;
  }

  m_functions[i] = f;
}

522
/**
523
 * @param i :: The index of the function
524
 * @return function at the requested index
525
 */
526
527
IFunction_sptr CompositeFunction::getFunction(std::size_t i) const {
  if (i >= nFunctions()) {
528
    throw std::out_of_range("Function index (" + std::to_string(i) +
529
530
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
531
  }
532
533
534
  return m_functions[i];
}

535
536
/**
 * Get the index of the function to which parameter i belongs
537
 * @param i :: The parameter index
538
 * @return function index of the requested parameter
539
 */
540
541
size_t CompositeFunction::functionIndex(std::size_t i) const {
  if (i >= nParams()) {
542
    throw std::out_of_range("Function parameter index (" + std::to_string(i) +
543
544
                            ") out of range (" + std::to_string(nParams()) +
                            ").");
545
  }
546
  return m_IFunction[i];
547
548
549
}

/**
550
551
* @param varName :: The variable name which may contain function index (
* [f<index.>]name )
552
* @param index :: Receives function index or throws std::invalid_argument
553
* @param name :: Receives the parameter name
554
*/
555
556
void CompositeFunction::parseName(const std::string &varName, size_t &index,
                                  std::string &name) {
557
  size_t i = varName.find('.');
558
  if (i == std::string::npos) {
559
    throw std::invalid_argument("Parameter " + varName + " not found.");
560
  } else {
561
    if (varName[0] != 'f')
562
563
      throw std::invalid_argument(
          "External function parameter name must start with 'f'");
564

565
    std::string sindex = varName.substr(1, i - 1);
566
567
568
569
570
    index = boost::lexical_cast<int>(sindex);

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

571
    name = varName.substr(i + 1);
572
  }
573
574
}

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

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

613
/**
614
 * Apply the ties.
615
 */
616
617
void CompositeFunction::applyTies() {
  for (size_t i = 0; i < nFunctions(); i++) {
618
619
    getFunction(i)->applyTies();
  }
620
  IFunction::applyTies();
621
622
623
}

/**
624
 * Clear the ties.
625
 */
626
void CompositeFunction::clearTies() {
627
  IFunction::clearTies();
628
  for (size_t i = 0; i < nFunctions(); i++) {
629
630
631
632
633
    getFunction(i)->clearTies();
  }
}

/** Removes i-th parameter's tie if it is tied or does nothing.
634
 * @param i :: The index of the tied parameter.
635
636
 * @return True if successfull
 */
637
bool CompositeFunction::removeTie(size_t i) {
638
639
640
641
642
643
644
  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;
645
646
647
}

/** Get the tie of i-th parameter
648
 * @param i :: The parameter index
649
 * @return A pointer to the tie.
650
 */
651
ParameterTie *CompositeFunction::getTie(size_t i) const {
652
653
654
655
656
657
  auto tie = IFunction::getTie(i);
  if (tie == nullptr) {
    size_t iFun = functionIndex(i);
    tie = m_functions[iFun]->getTie(i - m_paramOffsets[iFun]);
  }
  return tie;
658
659
660
661
}

/**
 * Declare a new parameter. To used in the implementation'c constructor.
662
663
 * @param name :: The parameter name.
 * @param initValue :: The initial value for the parameter
664
 * @param description :: Parameter documentation
665
 */
666
667
668
669
670
671
672
673
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.");
674
675
}

676
677
678
/**
 * Prepare the function for a fit.
 */
679
void CompositeFunction::setUpForFit() {
680
  IFunction::setUpForFit();
681
  // set up the member functions
682
  for (size_t i = 0; i < nFunctions(); i++) {
683
    getFunction(i)->setUpForFit();
684
  }
685
686
687
688
  // 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
  //
689
  // if parameters have non-constant ties enable numerical derivatives
690
  // for(size_t i = 0; i < nParams(); ++i)
691
692
693
694
695
696
697
698
699
700
701
  //{
  //  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
702
703
704
705
706
  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 "
707
                           "non-constant ties defined.\n";
708
709
        break;
      }
710
    }
711
712
713
  }
}

Nick Draper's avatar
re #100    
Nick Draper committed
714
/// Get constraint
715
/// @param i :: the index
Nick Draper's avatar
re #100    
Nick Draper committed
716
/// @return A pointer to the constraint
717
IConstraint *CompositeFunction::getConstraint(size_t i) const {
718
719
720
721
722
723
  auto constraint = IFunction::getConstraint(i);
  if (constraint == nullptr) {
    size_t iFun = functionIndex(i);
    constraint = m_functions[iFun]->getConstraint(i - m_paramOffsets[iFun]);
  }
  return constraint;
724
725
}

726
/** Remove a constraint
727
 * @param parName :: The name of a parameter which constarint to remove.
728
 */
729
void CompositeFunction::removeConstraint(const std::string &parName) {
730
731
732
733
734
735
736
737
738
  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));
  }
739
740
}

741
/** Checks if a constraint has been explicitly set
742
 *  @param i :: The parameter index
743
 *  @return true if the function is explicitly set
744
 */
745
bool CompositeFunction::isExplicitlySet(size_t i) const {
746
  size_t iFun = functionIndex(i);
747
  return m_functions[iFun]->isExplicitlySet(i - m_paramOffsets[iFun]);
748
749
}

750
/**
751
752
 * Returns the index of parameter if the ref points to one of the member
 * function
753
 * @param ref :: A reference to a parameter
754
 * @return Parameter index or number of nParams() if parameter not found
755
 */
756
757
size_t
CompositeFunction::getParameterIndex(const ParameterReference &ref) const {
758
759
  if (ref.getLocalFunction() == this && ref.getLocalIndex() < nParams()) {
    return ref.getLocalIndex();
760
  }
761
  for (size_t iFun = 0; iFun < nFunctions(); iFun++) {
762
    IFunction_sptr fun = getFunction(iFun);
763
    size_t iLocalIndex = fun->getParameterIndex(ref);
764
    if (iLocalIndex < fun->nParams()) {
765
766
767
      return m_paramOffsets[iFun] + iLocalIndex;
    }
  }
768
  return nParams();
769
770
}

771
/**
772
 * Returns the shrared pointer to the function conataining a parameter
773
 * @param ref :: The reference
774
775
 * @return A function containing parameter pointed to by ref
 */
776
777
778
IFunction_sptr
CompositeFunction::getContainingFunction(const ParameterReference &ref) const {
  for (size_t iFun = 0; iFun < nFunctions(); iFun++) {
779
    IFunction_sptr fun = getFunction(iFun);
780
    if (fun->getParameterIndex(ref) < fun->nParams()) {
781
      return fun;
782
783
    }
  }
784
785
786
  return IFunction_sptr();
}

787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
/// 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
808
809
std::vector<IFunction_sptr>
CompositeFunction::createEquivalentFunctions() const {
810
811
812
813
814
815
816
817
818
  auto nd = getNumberDomains();
  if (nd == 1) {
    return std::vector<IFunction_sptr>(
        1, FunctionFactory::Instance().createInitialized(asString()));
  }

  auto nf = nFunctions();
  std::vector<std::vector<IFunction_sptr>> equiv;
  equiv.reserve(nf);
Roman Tolchenov's avatar
Roman Tolchenov committed
819
  for (size_t i = 0; i < nf; ++i) {
820
821
822
823
824
    equiv.push_back(getFunction(i)->createEquivalentFunctions());
  }

  std::vector<IFunction_sptr> funs;
  funs.reserve(nd);
Roman Tolchenov's avatar
Roman Tolchenov committed
825
  for (size_t i = 0; i < nd; ++i) {
826
827
    auto comp = new CompositeFunction;
    funs.push_back(IFunction_sptr(comp));