CompositeFunction.cpp 25.2 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
std::string
55
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
/**
 * Sets a new value to a parameter by name.
209
210
 * @param name :: The name of the parameter.
 * @param value :: The new value
211
212
 * @param explicitlySet :: A boolean falgging the parameter as explicitly set
 * (by user)
213
 */
214
215
void CompositeFunction::setParameter(const std::string &name,
                                     const double &value, bool explicitlySet) {
216
  std::string pname;
217
  size_t index;
218
219
  parseName(name, index, pname);
  getFunction(index)->setParameter(pname, value, explicitlySet);
220
221
}

222
223
224
/**
 * Sets a new description to a parameter by name.
 * @param name :: The name of the parameter.
225
 * @param description :: The new description
226
 */
227
228
void CompositeFunction::setParameterDescription(
    const std::string &name, const std::string &description) {
229
  std::string pname;
230
  size_t index;
231
232
  parseName(name, index, pname);
  getFunction(index)->setParameterDescription(pname, description);
233
234
}

235
236
/**
 * Parameters by name.
237
 * @param name :: The name of the parameter.
238
 * @return value of the requested named parameter
239
 */
240
double CompositeFunction::getParameter(const std::string &name) const {
241
  std::string pname;
242
  size_t index;
243
  parseName(name, index, pname);
244
  return getFunction(index)->getParameter(pname);
245
246
247
}

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

250
/**
251
 *
252
 * @param name :: The name of a parameter
253
 * @return index of the requested named parameter
254
 */
255
size_t CompositeFunction::parameterIndex(const std::string &name) const {
256
  std::string pname;
257
  size_t index;
258
  parseName(name, index, pname);
259
  return getFunction(index)->parameterIndex(pname) + m_paramOffsets[index];
260
261
}

Nick Draper's avatar
re #100    
Nick Draper committed
262
/// Returns the name of parameter
263
/// @param i :: The index
Nick Draper's avatar
re #100    
Nick Draper committed
264
/// @return The name of the parameter
265
std::string CompositeFunction::parameterName(size_t i) const {
266
  size_t iFun = functionIndex(i);
267
  std::ostringstream ostr;
268
269
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->parameterName(i - m_paramOffsets[iFun]);
270
  return ostr.str();
271
272
}

273
274
275
/// Returns the description of parameter
/// @param i :: The index
/// @return The description of the parameter
276
std::string CompositeFunction::parameterDescription(size_t i) const {
277
  size_t iFun = functionIndex(i);
278
  std::ostringstream ostr;
279
  ostr << m_functions[iFun]->parameterDescription(i - m_paramOffsets[iFun]);
280
281
282
  return ostr.str();
}

283
/**
284
285
286
287
 * Get the fitting error for a parameter
 * @param i :: The index of a parameter
 * @return :: the error
 */
288
double CompositeFunction::getError(size_t i) const {
289
  size_t iFun = functionIndex(i);
290
  return m_functions[iFun]->getError(i - m_paramOffsets[iFun]);
291
292
}

293
/**
294
295
296
297
 * Set the fitting error for a parameter
 * @param i :: The index of a parameter
 * @param err :: The error value to set
 */
298
void CompositeFunction::setError(size_t i, double err) {
299
  size_t iFun = functionIndex(i);
300
  m_functions[iFun]->setError(i - m_paramOffsets[iFun], err);
301
302
}

303
304
305
/// Value of i-th active parameter. Override this method to make fitted
/// parameters different from the declared
double CompositeFunction::activeParameter(size_t i) const {
306
  size_t iFun = functionIndex(i);
307
  return m_functions[iFun]->activeParameter(i - m_paramOffsets[iFun]);
308
309
}

310
311
312
/// 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) {
313
  size_t iFun = functionIndex(i);
314
  m_functions[iFun]->setActiveParameter(i - m_paramOffsets[iFun], value);
315
316
317
}

/// Returns the name of active parameter i
318
std::string CompositeFunction::nameOfActive(size_t i) const {
319
  size_t iFun = functionIndex(i);
320
  std::ostringstream ostr;
321
322
  ostr << 'f' << iFun << '.'
       << m_functions[iFun]->nameOfActive(i - m_paramOffsets[iFun]);
323
324
325
326
  return ostr.str();
}

/// Returns the description of active parameter i
327
std::string CompositeFunction::descriptionOfActive(size_t i) const {
328
  size_t iFun = functionIndex(i);
329
  std::ostringstream ostr;
330
  ostr << m_functions[iFun]->descriptionOfActive(i - m_paramOffsets[iFun]);
331
  return ostr.str();
332
333
}

334
/// Change status of parameter
335
336
void CompositeFunction::setParameterStatus(size_t i,
                                           IFunction::ParameterStatus status) {
337
  size_t iFun = functionIndex(i);
338
  m_functions[iFun]->setParameterStatus(i - m_paramOffsets[iFun], status);
339
340
}

341
/// Get status of parameter
342
343
IFunction::ParameterStatus
CompositeFunction::getParameterStatus(size_t i) const {
344
  size_t iFun = functionIndex(i);
345
  return m_functions[iFun]->getParameterStatus(i - m_paramOffsets[iFun]);
346
347
}

348
/** Makes sure that the function is consistent.
349
 */
350
void CompositeFunction::checkFunction() {
351
352
  m_nParams = 0;
  m_paramOffsets.clear();
353
  m_IFunction.clear();
354

355
  std::vector<IFunction_sptr> functions(m_functions.begin(), m_functions.end());
356
357
  m_functions.clear();

Hahn, Steven's avatar
Hahn, Steven committed
358
  for (auto &f : functions) {
359
360
361
362
    CompositeFunction_sptr cf =
        boost::dynamic_pointer_cast<CompositeFunction>(f);
    if (cf)
      cf->checkFunction();
363
364
365
366
    addFunction(f);
  }
}

367
/**
368
369
370
371
372
373
374
375
376
 * Remove all member functions
 */
void CompositeFunction::clear() {
  m_nParams = 0;
  m_paramOffsets.clear();
  m_IFunction.clear();
  m_functions.clear();
}

377
/** Add a function
378
 * @param f :: A pointer to the added function
379
 * @return The function index
380
 */
381
382
size_t CompositeFunction::addFunction(IFunction_sptr f) {
  m_IFunction.insert(m_IFunction.end(), f->nParams(), m_functions.size());
383
384
  m_functions.push_back(f);
  //?f->init();
385
  if (m_paramOffsets.empty()) {
386
387
    m_paramOffsets.push_back(0);
    m_nParams = f->nParams();
388
  } else {
389
390
391
    m_paramOffsets.push_back(m_nParams);
    m_nParams += f->nParams();
  }
392
  return m_functions.size() - 1;
393
394
}

395
/** Remove a function
396
 * @param i :: The index of the function to remove
397
 */
398
void CompositeFunction::removeFunction(size_t i) {
399
400
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(i) +
401
402
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
403
  }
404

405
  IFunction_sptr fun = getFunction(i);
406
  // Reduction in parameters
407
  size_t dnp = fun->nParams();
408

409
410
411
  for (size_t j = 0; j < nParams();) {
    ParameterTie *tie = getTie(j);
    if (tie && tie->findParametersOf(fun.get())) {
412
      removeTie(j);
413
    } else {
414
415
416
417
418
      j++;
    }
  }

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

421
    if (*it == i) {
422
      it = m_IFunction.erase(it);
423
424
    } else {
      if (*it > i) {
425
426
        *it -= 1;
      }
427
      ++it;
428
429
430
431
    }
  }

  m_nParams -= dnp;
432
433
434
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
435
436
    m_paramOffsets[j] -= dnp;
  }
437
  m_paramOffsets.erase(m_paramOffsets.begin() + i);
438

439
  m_functions.erase(m_functions.begin() + i);
440
441
}

442
/** Replace a function with a new one. The old function is deleted.
443
 *  The new function must have already its workspace set.
444
 * @param f_old :: The pointer to the function to replace. If it's not
445
 *  a member of this composite function nothing happens
446
 * @param f_new :: A pointer to the new function
447
 */
448
449
450
451
452
453
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;
454
  std::vector<IFunction_sptr>::difference_type iFun = it - m_functions.begin();
455
  replaceFunction(iFun, f_new);
456
457
}

458
/** Replace a function with a new one. The old function is deleted.
459
460
 * @param i :: The index of the function to replace
 * @param f :: A pointer to the new function
461
 */
462
void CompositeFunction::replaceFunction(size_t i, IFunction_sptr f) {
463
464
  if (i >= nFunctions()) {
    throw std::out_of_range("Function index (" + std::to_string(i) +
465
466
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
467
  }
468

469
  IFunction_sptr fun = getFunction(i);
470
  size_t np_old = fun->nParams();
471

472
  size_t np_new = f->nParams();
473

474
475
  // Modify function indeces: The new function may have different number of
  // parameters
476
  {
477
    auto itFun = std::find(m_IFunction.begin(), m_IFunction.end(), i);
478
    if (itFun != m_IFunction.end()) // functions must have at least 1 parameter
479
    {
480
481
482
483
      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);
484
      }
485
486
    } else if (np_new > 0) // it could happen if the old function is an empty
                           // CompositeFunction
487
    {
488
489
490
      itFun = std::find_if(m_IFunction.begin(), m_IFunction.end(),
                           std::bind2nd(std::greater<size_t>(), i));
      m_IFunction.insert(itFun, np_new, i);
491
    }
492
493
  }

494
  size_t dnp = np_new - np_old;
495
  m_nParams += dnp;
496
497
498
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
499
500
501
502
503
504
    m_paramOffsets[j] += dnp;
  }

  m_functions[i] = f;
}

505
/**
506
 * @param i :: The index of the function
507
 * @return function at the requested index
508
 */
509
510
IFunction_sptr CompositeFunction::getFunction(std::size_t i) const {
  if (i >= nFunctions()) {
511
    throw std::out_of_range("Function index (" + std::to_string(i) +
512
513
                            ") out of range (" + std::to_string(nFunctions()) +
                            ").");
514
  }
515
516
517
  return m_functions[i];
}

518
519
/**
 * Get the index of the function to which parameter i belongs
520
 * @param i :: The parameter index
521
 * @return function index of the requested parameter
522
 */
523
524
size_t CompositeFunction::functionIndex(std::size_t i) const {
  if (i >= nParams()) {
525
    throw std::out_of_range("Function parameter index (" + std::to_string(i) +
526
527
                            ") out of range (" + std::to_string(nParams()) +
                            ").");
528
  }
529
  return m_IFunction[i];
530
531
532
}

/**
533
534
* @param varName :: The variable name which may contain function index (
* [f<index.>]name )
535
* @param index :: Receives function index or throws std::invalid_argument
536
* @param name :: Receives the parameter name
537
*/
538
539
void CompositeFunction::parseName(const std::string &varName, size_t &index,
                                  std::string &name) {
540
  size_t i = varName.find('.');
541
  if (i == std::string::npos) {
542
    throw std::invalid_argument("Parameter " + varName + " not found.");
543
  } else {
544
    if (varName[0] != 'f')
545
546
      throw std::invalid_argument(
          "External function parameter name must start with 'f'");
547

548
    std::string sindex = varName.substr(1, i - 1);
549
550
551
552
553
    index = boost::lexical_cast<int>(sindex);

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

554
    name = varName.substr(i + 1);
555
  }
556
557
}

558
/** Returns the index of parameter i as it declared in its function
559
 * @param i :: The parameter index
560
561
 * @param recursive :: If true call parameterLocalName recusively until
 *    a non-composite function is reached.
562
563
 * @return The local index of the parameter
 */
564
size_t CompositeFunction::parameterLocalIndex(size_t i, bool recursive) const {
565
  size_t iFun = functionIndex(i);
566
567
  auto localIndex = i - m_paramOffsets[iFun];
  if (recursive) {
568
    auto cf = dynamic_cast<const CompositeFunction *>(m_functions[iFun].get());
569
570
571
572
573
    if (cf) {
      return cf->parameterLocalIndex(localIndex, recursive);
    }
  }
  return localIndex;
574
575
}

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

596
/**
597
 * Apply the ties.
598
 */
599
600
void CompositeFunction::applyTies() {
  for (size_t i = 0; i < nFunctions(); i++) {
601
602
    getFunction(i)->applyTies();
  }
603
  IFunction::applyTies();
604
605
606
}

/**
607
 * Clear the ties.
608
 */
609
void CompositeFunction::clearTies() {
610
  IFunction::clearTies();
611
  for (size_t i = 0; i < nFunctions(); i++) {
612
613
614
615
616
    getFunction(i)->clearTies();
  }
}

/** Removes i-th parameter's tie if it is tied or does nothing.
617
 * @param i :: The index of the tied parameter.
618
619
 * @return True if successfull
 */
620
bool CompositeFunction::removeTie(size_t i) {
621
622
623
624
625
626
627
  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;
628
629
630
}

/** Get the tie of i-th parameter
631
 * @param i :: The parameter index
632
 * @return A pointer to the tie.
633
 */
634
ParameterTie *CompositeFunction::getTie(size_t i) const {
635
636
637
638
639
640
  auto tie = IFunction::getTie(i);
  if (tie == nullptr) {
    size_t iFun = functionIndex(i);
    tie = m_functions[iFun]->getTie(i - m_paramOffsets[iFun]);
  }
  return tie;
641
642
643
644
}

/**
 * Declare a new parameter. To used in the implementation'c constructor.
645
646
 * @param name :: The parameter name.
 * @param initValue :: The initial value for the parameter
647
 * @param description :: Parameter documentation
648
 */
649
650
651
652
653
654
655
656
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.");
657
658
}

659
660
661
/**
 * Prepare the function for a fit.
 */
662
void CompositeFunction::setUpForFit() {
663
  IFunction::setUpForFit();
664
  // set up the member functions
665
  for (size_t i = 0; i < nFunctions(); i++) {
666
    getFunction(i)->setUpForFit();
667
  }
668
669
670
671
  // 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
  //
672
  // if parameters have non-constant ties enable numerical derivatives
673
  // for(size_t i = 0; i < nParams(); ++i)
674
675
676
677
678
679
680
681
682
683
684
  //{
  //  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
685
686
687
688
689
  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 "
690
                           "non-constant ties defined.\n";
691
692
        break;
      }
693
    }
694
695
696
  }
}

Nick Draper's avatar
re #100    
Nick Draper committed
697
/// Get constraint
698
/// @param i :: the index
Nick Draper's avatar
re #100    
Nick Draper committed
699
/// @return A pointer to the constraint
700
IConstraint *CompositeFunction::getConstraint(size_t i) const {
701
702
703
704
705
706
  auto constraint = IFunction::getConstraint(i);
  if (constraint == nullptr) {
    size_t iFun = functionIndex(i);
    constraint = m_functions[iFun]->getConstraint(i - m_paramOffsets[iFun]);
  }
  return constraint;
707
708
}

709
/** Remove a constraint
710
 * @param parName :: The name of a parameter which constarint to remove.
711
 */
712
void CompositeFunction::removeConstraint(const std::string &parName) {
713
714
715
716
717
718
719
720
721
  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));
  }
722
723
}

724
/** Checks if a constraint has been explicitly set
725
 *  @param i :: The parameter index
726
 *  @return true if the function is explicitly set
727
 */
728
bool CompositeFunction::isExplicitlySet(size_t i) const {
729
  size_t iFun = functionIndex(i);
730
  return m_functions[iFun]->isExplicitlySet(i - m_paramOffsets[iFun]);
731
732
}

733
/**
734
735
 * Returns the index of parameter if the ref points to one of the member
 * function
736
 * @param ref :: A reference to a parameter
737
 * @return Parameter index or number of nParams() if parameter not found
738
 */
739
740
size_t
CompositeFunction::getParameterIndex(const ParameterReference &ref) const {
741
742
  if (ref.getLocalFunction() == this && ref.getLocalIndex() < nParams()) {
    return ref.getLocalIndex();
743
  }
744
  for (size_t iFun = 0; iFun < nFunctions(); iFun++) {
745
    IFunction_sptr fun = getFunction(iFun);
746
    size_t iLocalIndex = fun->getParameterIndex(ref);
747
    if (iLocalIndex < fun->nParams()) {
748
749
750
      return m_paramOffsets[iFun] + iLocalIndex;
    }
  }
751
  return nParams();
752
753
}

754
/**
755
 * Returns the shrared pointer to the function conataining a parameter
756
 * @param ref :: The reference
757
758
 * @return A function containing parameter pointed to by ref
 */
759
760
761
IFunction_sptr
CompositeFunction::getContainingFunction(const ParameterReference &ref) const {
  for (size_t iFun = 0; iFun < nFunctions(); iFun++) {
762
    IFunction_sptr fun = getFunction(iFun);
763
    if (fun->getParameterIndex(ref) < fun->nParams()) {
764
      return fun;
765
766
    }
  }
767
768
769
  return IFunction_sptr();
}

770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/// 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
791
792
std::vector<IFunction_sptr>
CompositeFunction::createEquivalentFunctions() const {
793
794
795
796
797
798
799
800
801
  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
802
  for (size_t i = 0; i < nf; ++i) {
803
804
805
806
807
    equiv.push_back(getFunction(i)->createEquivalentFunctions());
  }

  std::vector<IFunction_sptr> funs;
  funs.reserve(nd);
Roman Tolchenov's avatar
Roman Tolchenov committed
808
  for (size_t i = 0; i < nd; ++i) {
809
810
    auto comp = new CompositeFunction;
    funs.push_back(IFunction_sptr(comp));
Roman Tolchenov's avatar
Roman Tolchenov committed
811
    for (size_t j = 0; j < nf; ++j) {
812
813
814
815
816
817
      comp->addFunction(equiv[j][i]);
    }
  }
  return funs;
}

818
819