CompositeFunction.cpp 25.1 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
42
43
44
45
46
47
48
 * Writes itself into a string. Functions derived from CompositeFunction must
 * override this method with something like this:
 *   std::string NewFunction::asString()const
 *   {
 *      ostr << "composite=" << this->name() << ';';
 *      // write NewFunction's own attributes and parameters
 *      ostr << CompositeFunction::asString();
 *      // write NewFunction's own ties and constraints
 *      // ostr << ";constraints=(" << ... <<")";
 *   }
49
50
 * @param parentLocalAttributesStr :: A preformatted string with parent's local attributes.
 *    Can be passed in by a CompositeFunction (eg MultiDomainFunction).
51
 * @return the string representation of the composite function
52
 */
53
std::string CompositeFunction::asString(const std::string &parentLocalAttributesStr) const {
54
  std::ostringstream ostr;
55

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

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

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

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

111
112
113
  return ostr.str();
}

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

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

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

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

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

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

204
205
/**
 * Sets a new value to a parameter by name.
206
207
 * @param name :: The name of the parameter.
 * @param value :: The new value
208
209
 * @param explicitlySet :: A boolean falgging the parameter as explicitly set
 * (by user)
210
 */
211
212
void CompositeFunction::setParameter(const std::string &name,
                                     const double &value, bool explicitlySet) {
213
  std::string pname;
214
  size_t index;
215
216
  parseName(name, index, pname);
  getFunction(index)->setParameter(pname, value, explicitlySet);
217
218
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

352
  std::vector<IFunction_sptr> functions(m_functions.begin(), m_functions.end());
353
354
  m_functions.clear();

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

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

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

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

402
  IFunction_sptr fun = getFunction(i);
403
  // Reduction in parameters
404
  size_t dnp = fun->nParams();
405

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

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

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

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

436
  m_functions.erase(m_functions.begin() + i);
437
438
}

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

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

466
  IFunction_sptr fun = getFunction(i);
467
  size_t np_old = fun->nParams();
468

469
  size_t np_new = f->nParams();
470

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

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

  m_functions[i] = f;
}

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

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

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

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

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

551
    name = varName.substr(i + 1);
552
  }
553
554
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

815
816
} // namespace API
} // namespace Mantid