Implementing a Parametrizable class

From Bio++ Wiki
Jump to: navigation, search

In order to create a class with parameters, you need not implement all functions from the Parametrizable interface . The AbstractParametrizable abstract class offers a basic implementation that should fit a majority of cases. One therefore only need to extend the class by public inheritence: <source lang="cpp"> using namespace bpp;

class MyClassWithParameters :

 public AbstractParametrizable

{

 public:
   MyClassWithParameters(double alpha = 1, double beta = 0);
 //...

}; </source>

The AbstractParametrizable class maintains a ParameterList with all parameters. Parameters available for your class can be declared in the construtor of the new class: <source lang="cpp"> using namespace bpp;

MyClassWithParameters::MyClassWithParameters(double alpha, double beta) :

 AbstractParametrizable("")

{

  addParameter_(Parameter("alpha", alpha, &Parameter::R_PLUS_STAR));
  addParameter_(Parameter("beta", beta));

}; </source> This will create and add to the list two parameters names "alpha" and "beta", the first one taking only positive values.

Parameter values can be assessed lately by the getParameter method. The AbstractParametrizable class will ensure that parameters are updated when the appropriate methods are called. It uses events to notify the class that a parameter as changed, by calling the fireParameterChanged(ParameterList) virtual method. This method should thus be implemented in the derived class, be it left empty. In the following example, we will use this method to compute a quantity of interest that depends on alpha and beta: <source lang="cpp"> using namespace bpp;

class MyClassWithParameters :

 public AbstractParametrizable

{

 private:
   double exp_;
 public:
   MyClassWithParameters(double alpha = 1, double beta = 0);
 
 public:
   double getExp() const { return exp_; }
   void fireParameterChanged(const ParameterList& params) {
     double alpha = getParameterValue("alpha");
     double beta  = getParameterValue("beta");
     exp_ = alpha + exp(2*beta);
   }

}; </source> And that's it! The "exp_" quantity will be updated every time, and only when at least one of the parameters is modified by calling one of the Parametrizable method.