CompositeFunction.cpp 24.4 KB
Newer Older
1
2
3
4
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidKernel/Exception.h"
5
6
#include "MantidAPI/CompositeFunction.h"
#include "MantidAPI/ParameterTie.h"
7
#include "MantidAPI/IConstraint.h"
8

9
#include <boost/lexical_cast.hpp>
10
11
12
#include <boost/shared_array.hpp>
#include <sstream>
#include <iostream>
13
#include <algorithm>
14
15
16
17
18
19

namespace Mantid
{
namespace API
{

20
21
DECLARE_FUNCTION(CompositeFunction)

22
23
/// Copy contructor
CompositeFunction::CompositeFunction(const CompositeFunction& f)
24
:m_nActive(f.m_nParams),m_nParams(f.m_nParams),m_iConstraintFunction(0)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
{
  m_functions.assign(f.m_functions.begin(),f.m_functions.end());
  m_activeOffsets.assign(f.m_activeOffsets.begin(),f.m_activeOffsets.end());
  m_paramOffsets.assign(f.m_paramOffsets.begin(),f.m_paramOffsets.end());
}

///Assignment operator
CompositeFunction& CompositeFunction::operator=(const CompositeFunction& f)
{
  m_nActive = f.m_nActive;
  m_nParams = f.m_nParams;
  m_functions.assign(f.m_functions.begin(),f.m_functions.end());
  m_activeOffsets.assign(f.m_activeOffsets.begin(),f.m_activeOffsets.end());
  m_paramOffsets.assign(f.m_paramOffsets.begin(),f.m_paramOffsets.end());
39
  m_iConstraintFunction = f.m_iConstraintFunction;
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  return *this;
}

///Destructor
CompositeFunction::~CompositeFunction()
{
  for(int i=0;i<nFunctions();i++)
    if (m_functions[i]) delete m_functions[i];
}


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

56
57
58
59
60
61
62
63
64
65
66
67
/** 
 * 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=(" << ... <<")";
 *   }
 */
68
69
70
71
72
std::string CompositeFunction::asString()const
{
  std::ostringstream ostr;
  for(int i=0;i<nFunctions();i++)
  {
73
74
75
    IFunction* fun = getFunction(i);
    bool isComp = dynamic_cast<CompositeFunction*>(fun) != 0;
    if (isComp) ostr << '(';
76
    ostr << fun->asString();
77
    if (isComp) ostr << ')';
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    if (i < nFunctions() - 1)
    {
      ostr << ';';
    }
  }
  std::string ties;
  for(int i=0;i<nParams();i++)
  {
    const ParameterTie* tie = getTie(i);
    if (tie)
    {
      IFunction* fun = getFunction(functionIndex(i));
      std::string tmp = tie->asString(fun);
      if (tmp.empty())
      {
        tmp = tie->asString(this);
        if (!tmp.empty())
        {
          if (!ties.empty())
          {
            ties += ",";
          }
          ties += tmp;
        }
      }
    }
  }
  if (!ties.empty())
  {
    ostr << ";ties=(" << ties << ")";
108
109
110
111
  }
  return ostr.str();
}

112
/// Function you want to fit to.
113
void CompositeFunction::function(double* out, const double* xValues, const int& nData)const
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
{
  if (nData <= 0) return;
  boost::shared_array<double> tmpOut(new double[nData]);
  for(int i=0;i<nFunctions();i++)
  {
    if (i == 0)
      m_functions[i]->function(out,xValues,nData);
    else
    {
      m_functions[i]->function(tmpOut.get(),xValues,nData);
      std::transform(out,out+nData,tmpOut.get(),out,std::plus<double>());
    }
  }
}

/** A Jacobian for individual functions
 */
class PartialJacobian: public Jacobian
{
133
  Jacobian* m_J;  ///< pointer to the overall Jacobian
134
  int m_iP0;      ///< offset in the overall Jacobian for a particular function
135
  int m_iaP0;      ///< offset in the active Jacobian for a particular function
136
137
138
public:
  /** Constructor
   * @param J A pointer to the overall Jacobian
139
   * @param iP0 The parameter index (declared) offset for a particular function
140
   * @param iap0 The active parameter index (declared) offset for a particular function
141
   */
142
  PartialJacobian(Jacobian* J,int iP0, int iap0):m_J(J),m_iP0(iP0),m_iaP0(iap0)
143
  {}
144
145
146
147
  /**
   * Overridden Jacobian::set(...).
   * @param iY The index of the data point
   * @param iP The parameter index of an individual function.
148
   * @param value The derivative value
149
150
151
   */
  void set(int iY, int iP, double value)
  {
152
      m_J->set(iY,m_iP0 + iP,value);
153
  }
154
155
156
157
158
159
160
161
 /**  Add number to all iY (data) Jacobian elements for a given iP (parameter)
  *   @param value Value to add
  *   @param iActiveP The index of an active parameter.
  */
  virtual void addNumberToColumn(const double& value, const int& iActiveP) 
  {
    m_J->addNumberToColumn(value,m_iaP0+iActiveP);
  }
162
163
164
165
};

/// Derivatives of function with respect to active parameters
void CompositeFunction::functionDeriv(Jacobian* out, const double* xValues, const int& nData)
166
{
167
168
  for(int i=0;i<nFunctions();i++)
  {
169
    PartialJacobian J(out,m_paramOffsets[i],m_activeOffsets[i]);
170
171
172
173
174
175
176
177
178
179
    m_functions[i]->functionDeriv(&J,xValues,nData);
  }
}

/// Derivatives to be used in covariance matrix calculation. 
void CompositeFunction::calJacobianForCovariance(Jacobian* out, const double* xValues, const int& nData)
{
  if (nData <= 0) return;
  for(int i=0;i<nFunctions();i++)
  {
180
    PartialJacobian J(out,m_paramOffsets[i],m_activeOffsets[i]);
181
182
183
184
185
    m_functions[i]->calJacobianForCovariance(&J,xValues,nData);
  }
}


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

197
198
199
200
/** Get the i-th parameter.
 *  @param i The parameter index
 */
double CompositeFunction::getParameter(int i)const
201
{
202
  int iFun = functionIndex(i);
203
  return m_functions[ iFun ]->getParameter(i - m_paramOffsets[iFun]);
204
205
}

206
207
208
209
210
211
212
/**
 * Sets a new value to a parameter by name.
 * @param name The name of the parameter.
 * @param value The new value
 * @param explicitlySet A boolean falgging the parameter as explicitly set (by user)
 */
void CompositeFunction::setParameter(const std::string& name, const double& value, bool explicitlySet)
213
{
214
215
216
217
218
219
220
  std::string pname;
  int index;
  parseName(name,index,pname);
  if (index < 0)
    throw std::invalid_argument("CompositeFunction::getParameter: parameter name must contain function index");
  else
  {   
221
    getFunction(index)->setParameter(pname,value,explicitlySet);
222
  }
223
224
}

225
226
227
228
/**
 * Parameters by name.
 * @param name The name of the parameter.
 */
229
230
double CompositeFunction::getParameter(const std::string& name)const
{
231
232
233
234
235
236
237
238
239
  std::string pname;
  int index;
  parseName(name,index,pname);
  if (index < 0)
    throw std::invalid_argument("CompositeFunction::getParameter: parameter name must contain function index");
  else
  {   
    return getFunction(index)->getParameter(pname);
  }
240
241
242
243
244
245
246
247
}

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

248
/**
249
 * 
250
251
252
253
254
255
256
257
258
259
 * @param name The name of a parameter
 */
int CompositeFunction::parameterIndex(const std::string& name)const
{
  std::string pname;
  int index;
  parseName(name,index,pname);
  if (index < 0)
    throw std::invalid_argument("CompositeFunction::getParameter: parameter name must contain function index");

260
  return getFunction(index)->parameterIndex(pname) + m_paramOffsets[index];
261
262
}

263
264
265
/**
 * Checks that a pointer points to a parameter of this function and returns its index.
 * @param p A pointer to a double variable.
266
 * @return The index of the parameter or -1 if p is not a pointer to any of the function's parameters.
267
 */
268
269
270
271
272
273
274
275
276
277
278
279
//int CompositeFunction::parameterIndex(const double* p)const
//{
//  for(int iFun=0;iFun<nFunctions();iFun++)
//  {
//    int i = m_functions[iFun]->parameterIndex(p);
//    if (i >= 0)
//    {
//      return m_paramOffsets[iFun] + i;
//    }
//  }
//  return -1;
//}
280

281
282
283
/// Returns the name of parameter i
std::string CompositeFunction::parameterName(int i)const
{
284
  int iFun = functionIndex(i);
285
286
287
  std::ostringstream ostr;
  ostr << 'f' << iFun << '.' << m_functions[ iFun ]->parameterName(i - m_paramOffsets[iFun]);
  return ostr.str();
288
289
290
291
292
293
294
295
296
297
298
}

/// Number of active (in terms of fitting) parameters
int CompositeFunction::nActive()const
{
  return m_nActive;
}

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

/// Set new value of i-th active parameter. Override this method to make fitted parameters different from the declared
void CompositeFunction::setActiveParameter(int i, double value)
{
306
  int iFun = functionIndexActive(i);
307
308
309
310
311
312
313
314
315
316
  return m_functions[ iFun ]->setActiveParameter(i - m_activeOffsets[iFun],value);
}

/// Update parameters after a fitting iteration
void CompositeFunction::updateActive(const double* in)
{
  for(int iFun = 0; iFun < int(m_functions.size()); iFun++)
  {
    m_functions[ iFun ]->updateActive(in + m_activeOffsets[ iFun ]);
  }
317
  applyTies();
318
319
320
321
322
}

/// Returns "global" index of active parameter i
int CompositeFunction::indexOfActive(int i)const
{
323
  int iFun = functionIndexActive(i);
324
325
326
327
328
329
  return m_paramOffsets[ iFun ] + m_functions[ iFun ]->indexOfActive(i - m_activeOffsets[iFun]);
}

/// Returns the name of active parameter i
std::string CompositeFunction::nameOfActive(int i)const
{
330
  int iFun = functionIndexActive(i);
331
332
333
  std::ostringstream ostr;
  ostr << 'f' << iFun << '.' << m_functions[ iFun ]->nameOfActive(i - m_activeOffsets[iFun]);
  return ostr.str();
334
335
}

336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
 * Returns true if parameter i is active
 * @param i The index of a declared parameter
 */
bool CompositeFunction::isActive(int i)const
{
  int iFun = functionIndex(i);
  return m_functions[ iFun ]->isActive(i - m_paramOffsets[iFun]);
}

/**
 * @param i A declared parameter index to be removed from active
 */
void CompositeFunction::removeActive(int i)
{
351
  if (!isActive(i)) return;
352
353
354
355
356
  int iFun = functionIndex(i);
  int ia = m_activeOffsets[iFun] + m_functions[iFun]->activeIndex(i - m_paramOffsets[iFun]);
  m_iFunctionActive.erase(m_iFunctionActive.begin()+ia);
  m_functions[ iFun ]->removeActive(i - m_paramOffsets[iFun]);

357
  m_nActive--;
358
359
360
361
  for(int j=iFun+1;j<nFunctions();j++)
    m_activeOffsets[j] -= 1;
}

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/** Makes a parameter active again. It doesn't change the parameter's tie.
 * @param i A declared parameter index to be restored to active
 */
void CompositeFunction::restoreActive(int i)
{
  int iFun = functionIndex(i);
  int ia = m_activeOffsets[iFun] + m_functions[iFun]->activeIndex(i - m_paramOffsets[iFun]);

  std::vector<int>::iterator itFun = 
    std::find_if(m_iFunctionActive.begin(),m_iFunctionActive.end(),std::bind2nd(std::greater<int>(),i));

  m_iFunctionActive.insert(itFun,1,ia);
  m_functions[ iFun ]->restoreActive(i - m_paramOffsets[iFun]);

  m_nActive++;
  for(int j=iFun+1;j<nFunctions();j++)
    m_activeOffsets[j] += 1;
}

381
382
383
384
385
386
387
388
/**
 * @param i The index of a declared parameter
 * @return The index of declared parameter i in the list of active parameters or -1
 *         if the parameter is tied.
 */
int CompositeFunction::activeIndex(int i)const
{
  int iFun = functionIndex(i);
389
390
391
392
393
394
395
396
  int j = m_functions[iFun]->activeIndex(i - m_paramOffsets[iFun]);

  if (j == -1) 
  {
    return -1;
  }

  return m_activeOffsets[iFun] + j;
397
398
}

399
400
401
402
403
404
405
406
407
408
409
410
411
412
/** Makes sure that the function is consistent. 
 */
void CompositeFunction::checkFunction()
{
  m_nParams = 0;
  m_nActive = 0;
  m_paramOffsets.clear();
  m_activeOffsets.clear();
  m_iFunction.clear();
  m_iFunctionActive.clear();

  std::vector<IFunction*> functions(m_functions.begin(),m_functions.end());
  m_functions.clear();

413
  for(std::vector<IFunction*>::size_type i=0;i<functions.size();i++)
414
415
  {
    IFunction* f = functions[i];
416
417
    CompositeFunction* cf = dynamic_cast<CompositeFunction*>(f);
    if (cf) cf->checkFunction();
418
419
420
421
    addFunction(f);
  }
}

422
423
/** Add a function
 * @param f A pointer to the added function
424
 * @return The function index
425
 */
426
int CompositeFunction::addFunction(IFunction* f)
427
428
{
  m_iFunction.insert(m_iFunction.end(),f->nParams(),m_functions.size());
429
  m_iFunctionActive.insert(m_iFunctionActive.end(),f->nActive(),m_functions.size());
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
  m_functions.push_back(f);
  //?f->init();
  if (m_paramOffsets.size() == 0)
  {
    m_paramOffsets.push_back(0);
    m_activeOffsets.push_back(0);
    m_nParams = f->nParams();
    m_nActive = f->nActive();
  }
  else
  {
    m_paramOffsets.push_back(m_nParams);
    m_activeOffsets.push_back(m_nActive);
    m_nParams += f->nParams();
    m_nActive += f->nActive();
  }
446
  return m_functions.size()-1;
447
448
}

449
450
/** Remove a function
 * @param i The index of the function to remove
451
 * @param del The deletion flag. If true the function will be deleted otherwise - simply detached
452
 */
453
void CompositeFunction::removeFunction(int i, bool del)
454
455
456
457
458
459
460
461
462
463
464
465
{
  if ( i >= nFunctions() )
    throw std::out_of_range("Function index out of range.");

  IFunction* fun = getFunction(i);

  int dna = fun->nActive();
  int dnp = fun->nParams();

  for(int j=0;j<nParams();)
  {
    ParameterTie* tie = getTie(j);
466
    if (tie && tie->findParametersOf(fun))
467
468
469
470
471
472
473
474
475
476
    {
      removeTie(j);
    }
    else
    {
      j++;
    }
  }

  // Shift down the function indeces for parameters
477
  for(std::vector<int>::iterator it=m_iFunction.begin();it!=m_iFunction.end();)
478
  {
479

480
481
482
483
    if (*it == i)
    {
      it = m_iFunction.erase(it);
    }
484
    else
485
    {
486
487
488
489
490
      if (*it > i)
      {
        *it -= 1;
      }
      it++;
491
492
493
494
    }
  }

  // Shift down the function indeces for active parameters
495
  for(std::vector<int>::iterator it=m_iFunctionActive.begin();it!=m_iFunctionActive.end();)
496
497
498
499
500
  {
    if (*it == i)
    {
      it = m_iFunctionActive.erase(it);
    }
501
    else
502
    {
503
504
505
506
507
      if (*it > i)
      {
        *it -= 1;
      }
      it++;
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
    }
  }

  m_nActive -= dna;
  // Shift the active offsets down by the number of i-th function's active params
  for(int j=i+1;j<nFunctions();j++)
  {
    m_activeOffsets[j] -= dna;
  }
  m_activeOffsets.erase(m_activeOffsets.begin()+i);

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

  m_functions.erase(m_functions.begin()+i);
528
529
530
531
  if (del)
  {
    delete fun;
  }
532
533
}

534
535
536
537
538
539
540
541
542
543
/** Replace a function with a new one. The old function is deleted.
 * @param f_old The pointer to the function to replace. If it's not
 *  a member of this composite function nothing happens
 * @param f_new A pointer to the new function
 */
void CompositeFunction::replaceFunction(const IFunction* f_old,IFunction* f_new)
{
  std::vector<IFunction*>::const_iterator it = 
    std::find(m_functions.begin(),m_functions.end(),f_old);
  if (it == m_functions.end()) return;
544
  f_new->setWorkspace(f_old->getWorkspace(),f_old->getWorkspaceIndex(),-1,-1);
545
546
547
548
  int iFun = it - m_functions.begin();
  replaceFunction(iFun,f_new);
}

549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/** Replace a function with a new one. The old function is deleted.
 * @param i The index of the function to replace
 * @param f A pointer to the new function
 */
void CompositeFunction::replaceFunction(int i,IFunction* f)
{
  if ( i >= nFunctions() )
    throw std::out_of_range("Function index out of range.");

  IFunction* fun = getFunction(i);
  int na_old = fun->nActive();
  int np_old = fun->nParams();

  int na_new = f->nActive();
  int np_new = f->nParams();

  // Modify function indeces: The new function may have different number of parameters
  {
    std::vector<int>::iterator itFun = std::find(m_iFunction.begin(),m_iFunction.end(),i);
568
    if(itFun != m_iFunction.end()) // functions must have at least 1 parameter
569
    {
570
571
572
573
574
575
576
577
      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);
      }
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
    }
  }

  // Modify function indeces: The new function may have different number of active parameters
  {
    std::vector<int>::iterator itFun = std::find(m_iFunctionActive.begin(),m_iFunctionActive.end(),i);
    if (itFun != m_iFunctionActive.end())
    {
      if (na_old > na_new)
      {
        m_iFunctionActive.erase(itFun,itFun + na_old - na_new);
      }
      else if (na_old < na_new) 
      {
        m_iFunctionActive.insert(itFun,na_new - na_old,i);
      }
    }
    else if (na_new > 0)
    {
      itFun = std::find_if(m_iFunctionActive.begin(),m_iFunctionActive.end(),std::bind2nd(std::greater<int>(),i));
      m_iFunctionActive.insert(itFun,na_new,i);
    }
  }

  int dna = na_new - na_old;
  m_nActive += dna;
  // Recalc the active offsets 
  for(int j=i+1;j<nFunctions();j++)
  {
    m_activeOffsets[j] += dna;
  }

  int dnp = np_new - np_old;
  m_nParams += dnp;
  // Shift the parameter offsets down by the total number of i-th function's params
  for(int j=i+1;j<nFunctions();j++)
  {
    m_paramOffsets[j] += dnp;
  }

  m_functions[i] = f;
  delete fun;
}

622
623
624
625
/**
 * @param i The index of the function
 */
IFunction* CompositeFunction::getFunction(int i)const
626
{
627
628
  if ( i >= nFunctions()  || i < 0)
  {
629
    throw std::out_of_range("Function index out of range.");
630
  }
631
632
633
  return m_functions[i];
}

634
635
636
637
638
639
/**
 * Get the index of the function to which parameter i belongs
 * @param i The parameter index
 */
int CompositeFunction::functionIndex(int i)const
{
640
641
  if (i >= nParams() || i < 0)
  {
642
    throw std::out_of_range("Function parameter index out of range.");
643
  }
644
645
646
647
648
649
650
651
652
  return m_iFunction[i];
}

/**
 * Get the index of the function to which parameter i belongs
 * @param i The active parameter index
 */
int CompositeFunction::functionIndexActive(int i)const
{
653
  if (i >= nParams() || i < 0)
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
    throw std::out_of_range("Function parameter index out of range.");
  return m_iFunctionActive[i];
}

/**
* @param varName The variable name which may contain function index ( [f<index.>]name )
* @param index Receives function index or -1 
* @param name Receives the parameter name
*/
void CompositeFunction::parseName(const std::string& varName,int& index, std::string& name)
{
  size_t i = varName.find('.');
  if (i == std::string::npos)
  {
    name = varName;
    index = -1;
    return;
  }
  else
  {
    if (varName[0] != 'f')
      throw std::invalid_argument("External function parameter name must start with 'f'");

    std::string sindex = varName.substr(1,i-1);
    index = boost::lexical_cast<int>(sindex);

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

    name = varName.substr(i+1);
  }
}

687
688
689
690
691
692
693
694
695
696
/** Returns the index of parameter i as it declared in its function
 * @param i The parameter index
 * @return The local index of the parameter
 */
int CompositeFunction::parameterLocalIndex(int i)const
{
  int iFun = functionIndex(i);
  return i - m_paramOffsets[iFun];
}

697
698
699
700
701
702
703
704
705
706
/** Returns the name of parameter i as it declared in its function
 * @param i The parameter index
 * @return The pure parameter name (without the function identifier f#.)
 */
std::string CompositeFunction::parameterLocalName(int i)const
{
  int iFun = functionIndex(i);
  return m_functions[ iFun ]->parameterName(i - m_paramOffsets[iFun]);
}

707
708
709
710
711
712
/** Initialize the function providing it the workspace
 * @param workspace The shared pointer to a workspace to which the function will be fitted
 * @param spec The number of a spectrum for fitting
 * @param xMin The minimum bin index of spectrum spec that will be used in fitting
 * @param xMax The maximum bin index of spectrum spec that will be used in fitting
 */
713
void CompositeFunction::setWorkspace(boost::shared_ptr<const API::MatrixWorkspace> workspace,int spec,int xMin,int xMax)
714
{
715
  IFunction::setWorkspace(workspace,spec,xMin,xMax);
716
  for(int i=0;i<nFunctions();i++)
717
    getFunction(i)->setWorkspace(workspace,spec,xMin,xMax);
718
719
}

720
/**
721
 * Apply the ties.
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
 */
void CompositeFunction::applyTies()
{
  for(int i=0;i<nFunctions();i++)
  {
    getFunction(i)->applyTies();
  }
}

/**
 * Clear the ties. 
 */
void CompositeFunction::clearTies()
{
  for(int i=0;i<nFunctions();i++)
  {
    getFunction(i)->clearTies();
  }
}

/** Removes i-th parameter's tie if it is tied or does nothing.
 * @param i The index of the tied parameter.
 * @return True if successfull
 */
bool CompositeFunction::removeTie(int i)
{
  int iFun = functionIndex(i);
  bool res = m_functions[ iFun ]->removeTie(i - m_paramOffsets[iFun]);
  if (res)
  {
    m_nActive++;
  }
  return res;
}

/** Get the tie of i-th parameter
758
759
 * @param i The parameter index
 * @return A pointer to the tie.
760
761
762
763
764
765
766
767
768
769
770
771
772
 */
ParameterTie* CompositeFunction::getTie(int i)const
{
  int iFun = functionIndex(i);
  return m_functions[ iFun ]->getTie(i - m_paramOffsets[iFun]);
}

/**
 * Attaches a tie to this function. The attached tie is owned by the function.
 * @param tie A pointer to a new tie
 */
void CompositeFunction::addTie(ParameterTie* tie)
{
773
  int i = getParameterIndex(*tie);
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
  if (i < 0)
  {
    throw std::logic_error("Trying to use a tie on a parameter not belonging to this function");
  }
  int iFun = functionIndex(i);
  m_functions[iFun]->addTie(tie);
}

/**
 * Declare a new parameter. To used in the implementation'c constructor.
 * @param name The parameter name.
 * @param initValue The initial value for the parameter
 */
void CompositeFunction::declareParameter(const std::string& name,double initValue )
{
  throw Kernel::Exception::NotImplementedError("CompositeFunction cannot not have its own parameters.");
}

/** Add a constraint
 *  @param ic Pointer to a constraint.
 */
void CompositeFunction::addConstraint(IConstraint* ic)
{
797
798
799
  int i = getParameterIndex(*ic);
  int iFun = functionIndex(i);
  getFunction(iFun)->addConstraint(ic);
800
801
}

802
803
804
805
806
807
808
809
void CompositeFunction::setParametersToSatisfyConstraints()
{
  for(int i=0;i<nFunctions();i++)
  {
    getFunction(i)->setParametersToSatisfyConstraints();
  }
}

810
/// Get first constraint
811
IConstraint* CompositeFunction::firstConstraint()const
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
{
  m_iConstraintFunction = 0;
  if (nFunctions() == 0) 
  {
    return 0;
  }
  IConstraint* c = 0;
  while(m_iConstraintFunction < nFunctions()
    && !(c = getFunction(m_iConstraintFunction)->firstConstraint()) )
  {
    m_iConstraintFunction++;
  }
  return c;
}

/// Get next constraint
828
IConstraint* CompositeFunction::nextConstraint()const
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
{
  if (nFunctions() == 0) 
  {
    return 0;
  }
  if (m_iConstraintFunction >= nFunctions()-1)
  {
    return getFunction(m_iConstraintFunction)->nextConstraint();
  }
  IConstraint* c = getFunction(m_iConstraintFunction)->nextConstraint();
  if (c)
  {
    return c;
  }
  ++m_iConstraintFunction;
  return getFunction(m_iConstraintFunction)->firstConstraint();
}

847
848
849
850
851
852
853
854
855
856
/** Remove a constraint
 * @param parName The name of a parameter which constarint to remove.
 */
void CompositeFunction::removeConstraint(const std::string& parName)
{
  int iPar = parameterIndex(parName);
  int iFun = functionIndex(iPar);
  getFunction(iFun)->removeConstraint(parameterLocalName(iPar));
}

857
858
859
860
861
862
863
864
865
/** 
 *  @param i The parameter index
 */
bool CompositeFunction::isExplicitlySet(int i)const
{
  int iFun = functionIndex(i);
  return m_functions[ iFun ]->isExplicitlySet(i - m_paramOffsets[iFun]);
}

866
867
868
869
870
871
872
/**
 * Returns the index of parameter if the ref points to one of the member function or -1
 * @param ref A reference to a parameter
 * @return Parameter index or -1
 */
int CompositeFunction::getParameterIndex(const ParameterReference& ref)const
{
873
  if (ref.getFunction() == this && ref.getIndex() < nParams())
874
875
876
  {
    return ref.getIndex();
  }
877
878
879
880
881
882
883
884
  for(int iFun=0;iFun<nFunctions();iFun++)
  {
    int iLocalIndex = getFunction(iFun)->getParameterIndex(ref);
    if (iLocalIndex >= 0)
    {
      return m_paramOffsets[iFun] + iLocalIndex;
    }
  }
885
886
887
  return -1;
}

888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
/**
 * @param ref The reference
 * @return A function containing parameter pointed to by ref
 */
IFunction* CompositeFunction::getContainingFunction(const ParameterReference& ref)const
{
  if (ref.getFunction() == this && ref.getIndex() < nParams())
  {
    return ref.getFunction();
  }
  for(int iFun=0;iFun<nFunctions();iFun++)
  {
    IFunction* fun = getFunction(iFun)->getContainingFunction(ref);
    if (fun)
    {
      return getFunction(iFun);
    }
  }
  return NULL;
}
908

909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
/**
 * @param fun The searched function
 * @return A function containing the argument function fun
 */
IFunction* CompositeFunction::getContainingFunction(const IFunction* fun)
{
  if (fun == this)
  {
    return this;
  }
  for(int iFun=0;iFun<nFunctions();iFun++)
  {
    IFunction* f = getFunction(iFun)->getContainingFunction(fun);
    if (f)
    {
      return getFunction(iFun);
    }
  }
  return NULL;
}

930
931
} // namespace API
} // namespace Mantid