I am writing a Gibbs sampler using Rcpp. I’m sampling many parameters in various structure: scalar, vector, matrix, so I defined a class “Model” to save all objects at each state. The class contains a member function to initialize, and a member function to update the current state according to data and the previous state.
However, when I run the following trunk, the members cpre
, z
, nu1mu
, nu2mu
, nu1sigma
, nu2sigma
were coupled. For example, these members of M0
was mistakenly updated when I call M1.update() and M2.update().
//[[Rcpp::export]]
int test1( int x,IntegerVector Data_i,IntegerVector Data_k,NumericVector Data_Y){
Model M0;
M0.initialize(x);
Rcout<<"----------------Initialize-------------------"<<endl;
M0.print();
Model M1=M0;
M1.update(Data_i,Data_k,Data_Y);
Rcout<<"----------------Initialize after update-------------------"<<endl;
M0.print();
Model M2=M1;
M2.update(Data_i,Data_k,Data_Y);
Rcout<<"----------------Initialize after 2 update-------------------"<<endl;
M0.print();
return 0;
}
I have prevented coupling by redefining the “=” where each member was copied using clone() .
class Model{
public:
int s;
NumericMatrix cpre; //??
double mu;
NumericVector alpha;
NumericVector rho;
int nu1q;
int nu2q;
NumericVector nu1w;
NumericVector nu2w;
IntegerVector nu1z; //??
IntegerVector nu2z; //??
List nu1Omega;
List nu2Omega;
IntegerVector nu1m;
IntegerVector nu2m;
double nu1tau;
double nu2tau;
NumericVector nu1mu; //??
NumericVector nu2mu; //??
NumericVector nu1sigma; //??
NumericVector nu2sigma; //??
NumericMatrix nu;
void initialize(int nbmk);
void update( const IntegerVector & Data_i, const IntegerVector& Data_k, const NumericVector& Data_Y);
void print();
Model &operator=(const Model& Mprev){
if (this!=&Mprev){
//copy Mprev
this->s = (Mprev.s);
this->cpre = clone(Mprev.cpre);
this->mu = (Mprev.mu);
this->alpha = clone(Mprev.alpha);
this->rho = clone(Mprev.rho);
this->nu1q = (Mprev.nu1q);
this->nu2q = (Mprev.nu2q);
this->nu1w = clone(Mprev.nu1w);
this->nu2w = clone(Mprev.nu2w);
this->nu1z = clone(Mprev.nu1z);
this->nu2z = clone(Mprev.nu2z);
this->nu1Omega = clone(Mprev.nu1Omega);
this->nu2Omega = clone(Mprev.nu2Omega);
this->nu1m = clone(Mprev.nu1m);
this->nu2m = clone(Mprev.nu2m);
this->nu1tau = (Mprev.nu1tau);
this->nu2tau = (Mprev.nu2tau);
this->nu1mu = clone(Mprev.nu1mu);
this->nu2mu = clone(Mprev.nu2mu);
this->nu1sigma = clone(Mprev.nu1sigma);
this->nu2sigma = clone(Mprev.nu2sigma);
this->nu = clone(Mprev.nu);
}
return*this;
}
};
I dont understand how this could happen to these members. Do you have any ideas about how to prevent that?