void ActivationFunctionsTestCase::linear()
{
  const int N = 1000;
  Eigen::MatrixXd a = Eigen::VectorXd::Random(N) * 10.0;
  Eigen::MatrixXd z = Eigen::VectorXd::Zero(N);
  OpenANN::linear(a, z);
  ASSERT_EQUALS(a.minCoeff(), z.minCoeff());
  ASSERT_EQUALS(a.maxCoeff(), z.maxCoeff());

  Eigen::MatrixXd gd = Eigen::VectorXd::Zero(N);
  Eigen::MatrixXd expected = Eigen::VectorXd::Ones(N);
  OpenANN::linearDerivative(gd);
  ASSERT_EQUALS(gd.sum(), expected.sum());
}
Eigen::MatrixXd caculateAlgebraicDistance(const Eigen::SparseMatrix<int,Eigen::RowMajor>& incidenceMatrix,
                                          const Eigen::SparseMatrix<double,Eigen::RowMajor>& updatedMatrix)
{
  Eigen::MatrixXd inc = Eigen::MatrixXd(incidenceMatrix);
  Eigen::MatrixXd update = Eigen::MatrixXd(updatedMatrix);
  int edgeNumber = inc.cols();
  int verticeNumber = inc.rows();
  Eigen::MatrixXd algebraicDistanceForEdge(edgeNumber,1);
  Eigen::VectorXd sumOfcolsVector(edgeNumber);
  sumOfcolsVector = inc.colwise().sum();
  for(int i = 0; i<edgeNumber;++i){
    int verticeNumberForEdge = sumOfcolsVector[i];
    Eigen::MatrixXd allEdgeMatrix(update.rows(),verticeNumberForEdge);
    int g=0;
    for(int j=0;j<verticeNumber;++j){
        if(inc(j,i)){
          ++g;
          for(int v = 0; v<update.rows();++v){
              allEdgeMatrix(v,g-1) = update(v,j);
          }
        }
    }

    if(g!=0){
      Eigen::MatrixXd maxValueOfEdge = getMaxDiffForeachEdge(allEdgeMatrix);
      maxValueOfEdge = maxValueOfEdge.transpose() * maxValueOfEdge;
      double edgeDistance = maxValueOfEdge.sum();
      edgeDistance = sqrt(edgeDistance);
      algebraicDistanceForEdge(i,0) = edgeDistance;

    }

  }
  return algebraicDistanceForEdge;
}
void ActivationFunctionsTestCase::rectifier()
{
  const int N = 1000;
  Eigen::MatrixXd a = Eigen::MatrixXd::Random(1, N) * 10.0;
  Eigen::MatrixXd z = Eigen::MatrixXd::Zero(1, N);
  OpenANN::rectifier(a, z);
  ASSERT_EQUALS(0.0, z.minCoeff());
  ASSERT_EQUALS(a.maxCoeff(), z.maxCoeff());

  Eigen::MatrixXd gd = Eigen::MatrixXd::Zero(1, N);
  Eigen::MatrixXd expected = Eigen::MatrixXd::Ones(1, N);
  for(int i = 0; i < N; i++)
    expected(i) *= (double)(z(i) > 0.0);
  OpenANN::rectifierDerivative(z, gd);
  ASSERT_EQUALS(gd.sum(), expected.sum());
}
void ActivationFunctionsTestCase::softmax()
{
  const int N = 1000;
  Eigen::MatrixXd a = Eigen::VectorXd::Random(N).transpose();
  OpenANN::softmax(a);
  ASSERT_EQUALS_DELTA(1.0, a.sum(), 1e-3);
  ASSERT_WITHIN(a.minCoeff(), 0.0, 1.0);
  ASSERT_WITHIN(a.maxCoeff(), 0.0, 1.0);
}
Eigen::MatrixXd localWeighting( const Eigen::MatrixXd &W, bool isFull, bool isSymmetric)
{
	int n = W.rows();
	double Ls = (W.count()-n)/2; //count number of edges of the graph

	Eigen::MatrixXd C = Eigen::MatrixXd::Zero(n,n);
	double Ws = 0.5*W.sum();

	Eigen::VectorXd D = W.colwise().sum();

	if (isFull)
	{
		if (isSymmetric)
		{
			computeC_symmetric_full(const_cast<Eigen::MatrixXd &>(W),C,D,n);
		}
		else
		{
			// this is a trick to ensure vectorizatoin and no cache misses! some tranpositions have to be made though
			const_cast<Eigen::MatrixXd &>(W).transposeInPlace();
			computeC_symmetric_full(const_cast<Eigen::MatrixXd &>(W),C,D,n);
			const_cast<Eigen::MatrixXd &>(W).transposeInPlace();
			C.transposeInPlace();
			// the original code use vertical access to rows, but is slower
			//compute_C_asymmetric_full(const_cast<Eigen::MatrixXd &>(W),C,D,n);
		}
	}
	else
	{
		if (isSymmetric)
		{
			computeC_symmetric_sparse(const_cast<Eigen::MatrixXd &>(W),C,D,n);
		}
		else
		{
			compute_C_asymmetric_sparse(const_cast<Eigen::MatrixXd &>(W),C,D,n);
		}
	}

	Eigen::MatrixXd G = ((Ls/Ws)*W).cwiseProduct(C);

	Eigen::VectorXd DG = G.colwise().sum();

	for (int i=0; i<n; i++)
	{
		G.row(i)/=DG(i);
	}
	
	return G;
}
Esempio n. 6
0
 inline Real stdDev(const Eigen::MatrixXd& input){
   return ::sqrt(((Eigen::MatrixXd)((input.array()-input.sum()/input.rows()).pow(2.0))).sum()/(input.rows()-1));
 }
Esempio n. 7
0
SEXP cleancolZ(SEXP X,SEXP Z,SEXP bic_vide_vect,SEXP methode_BIC,SEXP plot,SEXP bla,SEXP Rstar)
{
  BEGIN_RCPP
  //declaration des variables
  const Map<MatrixXd> matZ(as<Map<MatrixXd> >(Z));//Z
  const Map<MatrixXd> matX(as<Map<MatrixXd> >(X));//X
  const Map<VectorXd> Bic_vide_vect(as<Map<VectorXd> >(bic_vide_vect));//bic_vide_vect
  bool star = Rcpp::as<bool>(Rstar);     // BICstar

  Rcpp::NumericVector met_BIC(methode_BIC),Plot(plot),Bla(bla);
  typedef Rcpp::NumericVector::iterator vec_iterator;
  vec_iterator imet_BIC=met_BIC.begin(),iplot=Plot.begin(),ibla=Bla.begin();
  int p=matZ.cols();//nombre de colonne de la matrice Z
  Eigen::MatrixXd Zopt;//meilleur Z obtenu
  double Bicbest;//BIC associe au meilleur modele
  Eigen::VectorXd bicvect;//vecteur BIC des matrices Z retenues
  Eigen::MatrixXd newZ;//matrice Z modifie a chaque etapes
  Eigen::VectorXd list_cand;//vecteur qui contient les indices des colonnes candidates (liste candidats)
  int compte=0;//permet de cree la matrice liste en designant le numero du candidat (liste candidats)
  int nbcand;//nombre de candidats
  int numcand;//numero du candidat
  int i_loc;//premiere coordonnee du candidat (modification Z)
  Eigen::MatrixXd Zcand;//matrice Z du candidat (modification Z)
  Eigen::ArrayXXd SumCol(1,p);//SumCol est un vecteur qui contient la somme de chaque colonne de Zcand (modification Z)
  Eigen::VectorXd BIC_cand;//vecteur qui contient les BIC de chaque colonne des la matrice Zcand (calcul du BIC)
  double Sum_BIC_cand;//somme des BIC de BIC_cand (calcul BIC)
  Eigen::VectorXd stock_BIC;//vecteur qui contient le BIC de tout les candidats (stock)
  double sumbic;//BIC de chaque etapes
  double BIC_min;
  bool minimum;
  int i;
  int iret=1;
  Eigen::VectorXd bic_etape;//vecteur qui stock le BIC de chaque etapes
  Eigen::VectorXd complexite_etape;//vecteur qui stock la complexite de Z a chaque etapes
  Eigen::VectorXd BIC_step;//vecteur qui stock le BIC de chaque etapes
  Eigen::VectorXd complexite_step ;//vecteur qui stock la complexite de Z a chaque etapes
  //initialisation
  bicvect=BicZ_cpp2(matX,matZ,Bic_vide_vect,imet_BIC[0]);
//somme a la main
  sumbic=bicvect.sum();
  if(star)
  {
      sumbic=sumbic-ProbaZ_cpp(matZ);
   }
  if (ibla[0]>0)
  {
    Rcout<<sumbic<<"\n";
  }
  Bicbest =sumbic;
  Zopt=matZ;
  newZ=matZ;
  
  int step =0;
  SumCol=matZ.colwise().sum();//nombre d'elements dans chaque colonne
  nbcand=(SumCol>0).count();//nombre de colonnes candidates (quand il y'a au moins 1 element dans une colonne)
  list_cand.resize(nbcand);//le nombre de candidats est la complexite du modele
  bic_etape.resize(nbcand);
  complexite_etape.resize(nbcand);
  while(step<nbcand)  
  {
    compte=0;//initialisation du vecteur liste designe le numero du candidat
    
  //liste candidats (couples [i,j])
    for(int n=0;n<p;n++)//parcours les colonnes
    {
      if(newZ.col(n).sum()>0)//on cherche les candidats
      {
        list_cand(compte)=n;//stock la colonne du candidat
        compte=compte+1;//passage au candidat suivant
      }
    }
    
    stock_BIC.resize(compte);
    //pour chaque candidat
    for (numcand=0;numcand<compte;numcand++)
    {
    //modification (calcul du Z)    (Zcand avec methode (rejet ou relax)   Z,i,j,methode="relax", p2max=inf,rmax=inf)
      
      Zcand=newZ;
      for(i_loc=0;i_loc<p;i_loc++)//parcours des lignes
      {
        Zcand(i_loc,list_cand(numcand))=0;//modification de Z par rapport a la colonne candidate
      }
      
    //calcul du bic (du nouveau Z genere)
      BIC_cand=BicZ_cpp(matX,Zcand,Bic_vide_vect,bicvect,imet_BIC[0],newZ);//calcul du vecteur BIC du candidat
      Sum_BIC_cand=BIC_cand.sum();
      if (star)
      {
         Sum_BIC_cand=Sum_BIC_cand-ProbaZ_cpp(Zcand);
      }
    //stockage du BIC
      
      stock_BIC(numcand)=Sum_BIC_cand;
    }
    //on regarde la meilleur candidat
    BIC_min=Bicbest;//initialisation BIC_min
    minimum=false;
    for(i=0;i<compte;i++)
    {
      if(stock_BIC(i)<Bicbest)//si on a trouve un minimum
      {
        iret=i;//on retient sa position
        minimum=true;
        Bicbest=stock_BIC(i);//on modifie Bicbest
      }
    }
    if (minimum==true)//si il y a un minimum, on y va
    {
      Zopt=newZ;//initialisation a la stationarite
      for(int i_opt=0;i_opt<p;i_opt++)//on met la colonne a 0
      {
        Zopt(i_opt,list_cand(iret))=0;
      }
      bicvect=BicZ_cpp(matX,Zopt,Bic_vide_vect,bicvect,imet_BIC[0],newZ);//calcul du vecteur BIC du nouveau Zopt

      newZ=Zopt;
      
      //partie commentaires
      if (ibla[0]>0)
      {
        Rcout<<"etape : "<<step<<"\n";
        Rcout<<" Bicbest: "<<Bicbest<<" complexite: "<<newZ.sum()<<"\n";
        if (ibla[0]==2)
        {
          Rcout<<"nb_cand "<<compte<<"BIC min "<<BIC_min<<"\n";
        }
      }
      
      //partie graphiques
      if(iplot[0]==1)//si on veut des graphiques on mets a jour les vecteurs
      {
        bic_etape(step)=Bicbest;
        complexite_etape(step)=newZ.sum();
      }
      
    step=step+1;//passage a l'etape suivante s'il y a eu un minimum
    }
    else//pas de minimum
    {
      if (ibla[0]>0){
        Rcout<<"nettoyage fini";
      }      
      step=nbcand+1;//arret des etapes
    }
  }//fin des étapes
  
  if(iplot[0]==1)//si on veut des graphiques on mets a jour les vecteurs
  {
    BIC_step.resize(nbcand-compte);//on redimensionne pour les plot
    complexite_step.resize(nbcand-compte);
    if(nbcand-compte>0)//si il y'a eu au moins une etape
    {
      for(int k=0;k<nbcand-compte;k++)
      {
        BIC_step(k)=bic_etape(k);
        complexite_step(k)=complexite_etape(k);
      }
    }
    return List::create(
      Named("Z")=  newZ,
 //     Named("Z_opt")=  Zopt,
      Named("bic_opt")=  Bicbest,
      Named("bic_step")=  BIC_step,
      Named("complexity_step")=  complexite_step
    );
  }
  else
  {
  return List::create(
      Named("Z")=  newZ,
 //     Named("Z_opt")=  Zopt,
      Named("bic_opt")=  Bicbest
    );
  }
  END_RCPP
}  
Esempio n. 8
0
/** unittest for oapackage
 *
 * Returns UNITTEST_SUCCESS if all tests are ok.
 *
 */
int oaunittest (int verbose, int writetests = 0, int randval = 0) {
        double t0 = get_time_ms ();
        const char *bstr = "OA unittest";
        cprintf (verbose, "%s: start\n", bstr);

        srand (randval);

        int allgood = UNITTEST_SUCCESS;

        Combinations::initialize_number_combinations (20);

        /* constructors */
        {
                cprintf (verbose, "%s: interaction matrices\n", bstr);

                array_link al = exampleArray (2);
                Eigen::MatrixXd m1 = array2xfeigen (al);
                Eigen::MatrixXd m2 = arraylink2eigen (array2xf (al));

                Eigen::MatrixXd dm = m1 - m2;
                int sum = dm.sum ();

                myassert (sum == 0, "unittest error: construction of interaction matrices\n");
        }

		cprintf(verbose, "%s: reduceConferenceTransformation\n", bstr);
		myassert(unittest_reduceConferenceTransformation()==0, "unittest unittest_reduceConferenceTransformation failed");

        /* constructors */
        {
                cprintf (verbose, "%s: array manipulation operations\n", bstr);

                test_array_manipulation (verbose);
        }

        /* double conference matrices */
        {
                cprintf (verbose, "%s: double conference matrices\n", bstr);

                array_link al = exampleArray (36, verbose);
                myassert (al.is_conference (2), "check on double conference design type");

                myassert (testLMC0checkDC (al, verbose >= 2), "testLMC0checkDC");

        }

        /* conference matrices */
        {
                cprintf (verbose, "%s: conference matrices\n", bstr);

                int N = 4;
                conference_t ctype (N, N, 0);

                arraylist_t kk;
                array_link al = ctype.create_root ();
                kk.push_back (al);

                for (int extcol = 2; extcol < N; extcol++) {
                        kk = extend_conference (kk, ctype, 0);
                }
                myassert (kk.size () == 1, "unittest error: conference matrices for N=4\n");
        }

        {
                cprintf (verbose, "%s: generators for conference matrix extensions\n", bstr);
                test_conference_candidate_generators (verbose);
        }

        {
                cprintf (verbose, "%s: conference matrix Fvalues\n", bstr);
                array_link al = exampleArray (22, 0);
                if (verbose >= 2)
                        al.show ();
                if (0) {
                        std::vector< int > f3 = al.FvaluesConference (3);
                        if (verbose >= 2) {
                                printf ("F3: ");
                                display_vector (f3);
                                printf ("\n");
                        }
                }

                const int N = al.n_rows;
                jstructconference_t js (N, 4);
                std::vector< int > f4 = al.FvaluesConference (4);
                std::vector< int > j4 = js.Jvalues ();

                if (verbose >= 2) {
                        printf ("j4: ");
                        display_vector (j4);
                        printf ("\n");
                        printf ("F4: ");
                        display_vector (f4);
                        printf ("\n");
                }

                myassert (j4[0] == 28, "unittest error: conference matricex F values: j4[0]\n");
                myassert (f4[0] == 0, "unittest error: conference matricex F values: f4[0] \n");
                myassert (f4[1] == 0, "unittest error: conference matricex F values: j4[1]\n");
        }

        {
                cprintf (verbose, "%s: LMC0 check for arrays in C(4, 3)\n", bstr);

                array_link al = exampleArray (28, 1);
                if (verbose >= 2)
                        al.showarray ();
                lmc_t r = LMC0check (al, verbose);
                if (verbose >= 2)
                        printf ("LMC0check: result %d\n", r);
                myassert (r >= LMC_EQUAL, "LMC0 check\n");

                al = exampleArray (29, 1);
                if (verbose >= 2)
                        al.showarray ();
                r = LMC0check (al, verbose);
                if (verbose >= 2)
                        printf ("LMC0check: result %d (LMC_LESS %d)\n", r, LMC_LESS);
                myassert (r == LMC_LESS, "LMC0 check of example array 29\n");
        }

        {
                cprintf (verbose, "%s: LMC0 check\n", bstr);

                array_link al = exampleArray (31, 1);
                if (verbose >= 2)
                        al.showarray ();
                conference_transformation_t T (al);

                for (int i = 0; i < 80; i++) {
                        T.randomize ();
                        array_link alx = T.apply (al);

                        lmc_t r = LMC0check (alx, verbose);

                        if (verbose >= 2) {
                                printfd ("%d: transformed array: r %d\n", i, r);
                                alx.showarray ();
                        }
                        if (alx == al)
                                myassert (r >= LMC_EQUAL, "result should be LMC_MORE\n");
                        else {
                                myassert (r == LMC_LESS, "result should be LMC_LESS\n");
                        }
                }
        }

        {
                cprintf (verbose, "%s: random transformation for conference matrices\n", bstr);

                array_link al = exampleArray (19, 1);
                conference_transformation_t T (al);
                // T.randomizerowflips();
                T.randomize ();

                conference_transformation_t Ti = T.inverse ();
                array_link alx = Ti.apply (T.apply (al));

                if (0) {
                        printf ("input array:\n");
                        al.showarray ();
                        T.show ();
                        printf ("transformed array:\n");
                        T.apply (al).showarray ();
                        Ti.show ();
                        alx.showarray ();
                }

                myassert (alx == al, "transformation of conference matrix\n");
        }

        /* constructors */
        {
                cprintf (verbose, "%s: constructors\n", bstr);

                array_transformation_t t;
                conference_transformation_t ct;
        }

        /* J-characteristics */
        {
                cprintf (verbose, "%s: J-characteristics\n", bstr);

                array_link al = exampleArray (8, 1);

                const int mm[] = {-1, -1, 0, 0, 8, 16, 0, -1};

                for (int jj = 2; jj < 7; jj++) {
                        std::vector< int > jx = al.Jcharacteristics (jj);
                        int j5max = vectormax (jx, 0);
                        if (verbose >= 2) {
                                printf ("oaunittest: jj %d: j5max %d\n", jj, j5max);
                        }

                        if (j5max != mm[jj]) {
                                printfd ("j5max %d (should be %d)\n", j5max, mm[jj]);
                                allgood = UNITTEST_FAIL;
                                return allgood;
                        }
                }
        }
        {
                cprintf (verbose, "%s: array transformations\n", bstr);

                const int N = 9;
                const int t = 3;
                arraydata_t adataX (3, N, t, 4);

                array_link al (adataX.N, adataX.ncols, -1);
                al.create_root (adataX);

                if (checkTransformationInverse (al))
                        allgood = UNITTEST_FAIL;

                if (checkTransformationComposition (al, verbose >= 2))
                        allgood = UNITTEST_FAIL;

                al = exampleArray (5, 1);
                if (checkTransformationInverse (al))
                        allgood = UNITTEST_FAIL;

                if (checkTransformationComposition (al))
                        allgood = UNITTEST_FAIL;

                for (int i = 0; i < 15; i++) {
                        al = exampleArray (18, 0);
                        if (checkConferenceComposition (al))
                                allgood = UNITTEST_FAIL;
                        if (checkConferenceInverse (al))
                                allgood = UNITTEST_FAIL;
                        al = exampleArray (19, 0);
                        if (checkConferenceComposition (al))
                                allgood = UNITTEST_FAIL;
                        if (checkConferenceInverse (al))
                                allgood = UNITTEST_FAIL;
                }
        }

        {
                cprintf (verbose, "%s: rank \n", bstr);

                const int idx[10] = {0, 1, 2, 3, 4, 6, 7, 8, 9};
                const int rr[10] = {4, 11, 13, 18, 16, 4, 4, 29, 29};
                for (int ii = 0; ii < 9; ii++) {
                        array_link al = exampleArray (idx[ii], 0);
                        myassert (al.is2level (), "unittest error: input array is not 2-level\n");

                        int r = arrayrankColPivQR (array2xf (al));

                        int r3 = (array2xf (al)).rank ();
                        myassert (r == r3, "unittest error: rank of array");

                        if (verbose >= 2) {
                                al.showarray ();
                                printf ("unittest: rank of array %d: %d\n", idx[ii], r);
                        }

                        myassert (rr[ii] == r, "unittest error: rank of example matrix\n");
                }
        }

        {
                cprintf (verbose, "%s: Doptimize \n", bstr);
                const int N = 40;
                const int t = 0;
                arraydata_t arrayclass (2, N, t, 6);
                std::vector< double > alpha (3);
                alpha[0] = 1;
                alpha[1] = 1;
                alpha[2] = 0;
                int niter = 5000;
                double t00 = get_time_ms ();
                DoptimReturn rr = Doptimize (arrayclass, 10, alpha, 0, DOPTIM_AUTOMATIC, niter);

                array_t ss[7] = {3, 3, 2, 2, 2, 2, 2};
                arraydata_t arrayclassmixed (ss, 36, t, 5);
                rr = Doptimize (arrayclassmixed, 10, alpha, 0, DOPTIM_AUTOMATIC, niter);

                cprintf (verbose, "%s: Doptimize time %.3f [s] \n", bstr, get_time_ms () - t00);
        }

        {
                cprintf (verbose, "%s: J-characteristics for conference matrix\n", bstr);

                array_link al = exampleArray (19, 0);
                std::vector< int > j2 = Jcharacteristics_conference (al, 2);
                std::vector< int > j3 = Jcharacteristics_conference (al, 3);

                myassert (j2[0] == 0, "j2 value incorrect");
                myassert (j2[1] == 0, "j2 value incorrect");
                myassert (std::abs (j3[0]) == 1, "j3 value incorrect");

                if (verbose >= 2) {
                        al.showarray ();
                        printf ("j2: ");
                        display_vector (j2);
                        printf ("\n");
                        printf ("j3: ");
                        display_vector (j3);
                        printf ("\n");
                }
        }

        {
                // test PEC sequence
                cprintf (verbose, "%s: PEC sequence\n", bstr);
                for (int ii = 0; ii < 5; ii++) {
                        array_link al = exampleArray (ii, 0);
                        std::vector< double > pec = PECsequence (al);
                        printf ("oaunittest: PEC for array %d: ", ii);
                        display_vector (pec);
                        printf (" \n");
                }
        }

        {
                cprintf (verbose, "%s: D-efficiency test\n", bstr);
                //  D-efficiency near-zero test
                {
                        array_link al = exampleArray (14);
                        double D = al.Defficiency ();
                        std::vector< double > dd = al.Defficiencies ();
                        printf ("D %f, D (method 2) %f\n", D, dd[0]);
                        assert (fabs (D - dd[0]) < 1e-4);
                }
                {
                        array_link al = exampleArray (15);
                        double D = al.Defficiency ();
                        std::vector< double > dd = al.Defficiencies ();
                        printf ("D %f, D (method 2) %f\n", D, dd[0]);
                        assert (fabs (D - dd[0]) < 1e-4);
                        assert (fabs (D - 0.335063) < 1e-3);
                }
        }

        arraydata_t adata (2, 20, 2, 6);
        OAextend oaextendx;
        oaextendx.setAlgorithm ((algorithm_t)MODE_ORIGINAL, &adata);

        std::vector< arraylist_t > aa (adata.ncols + 1);
        printf ("OA unittest: create root array\n");
        create_root (&adata, aa[adata.strength]);

        /** Test extend of arrays **/
        {
                cprintf (verbose, "%s: extend arrays\n", bstr);

                setloglevel (SYSTEM);

                for (int kk = adata.strength; kk < adata.ncols; kk++) {
                        aa[kk + 1] = extend_arraylist (aa[kk], adata, oaextendx);
                        printf ("  extend: column %d->%d: %ld->%ld arrays\n", kk, kk + 1, aa[kk].size (),
                                aa[kk + 1].size ());
                }

                if (aa[adata.ncols].size () != 75) {
                        printf ("extended ?? to %d arrays\n", (int)aa[adata.ncols].size ());
                }
                myassert (aa[adata.ncols].size () == 75, "number of arrays is incorrect");

                aa[adata.ncols].size ();
                setloglevel (QUIET);
        }

        {
                cprintf (verbose, "%s: test LMC check\n", bstr);

                array_link al = exampleArray (1, 1);

                lmc_t r = LMCcheckOriginal (al);

                myassert (r != LMC_LESS, "LMC check of array in normal form");

                for (int i = 0; i < 20; i++) {
                        array_link alx = al.randomperm ();
                        if (alx == al)
                                continue;
                        lmc_t r = LMCcheckOriginal (alx);

                        myassert (r == LMC_LESS, "randomized array cannot be in minimal form");
                }
        }

        {
                /** Test dof **/
                cprintf (verbose, "%s: test delete-one-factor reduction\n", bstr);

                array_link al = exampleArray (4);
                cprintf (verbose >= 2, "LMC: \n");
                al.reduceLMC ();
                cprintf (verbose >= 2, "DOP: \n");
                al.reduceDOP ();
        }

        arraylist_t lst;

        {
                /** Test different methods **/
                cprintf (verbose, "%s: test 2 different methods\n", bstr);

                const int s = 2;
                arraydata_t adata (s, 32, 3, 10);
                arraydata_t adata2 (s, 32, 3, 10);
                OAextend oaextendx;
                oaextendx.setAlgorithm ((algorithm_t)MODE_ORIGINAL, &adata);
                OAextend oaextendx2;
                oaextendx2.setAlgorithm ((algorithm_t)MODE_LMC_2LEVEL, &adata2);

                printf ("OA unittest: test 2-level algorithm on %s\n", adata.showstr ().c_str ());
                std::vector< arraylist_t > aa (adata.ncols + 1);
                create_root (&adata, aa[adata.strength]);
                std::vector< arraylist_t > aa2 (adata.ncols + 1);
                create_root (&adata, aa2[adata.strength]);

                setloglevel (SYSTEM);

                for (int kk = adata.strength; kk < adata.ncols; kk++) {
                        aa[kk + 1] = extend_arraylist (aa[kk], adata, oaextendx);
                        aa2[kk + 1] = extend_arraylist (aa2[kk], adata2, oaextendx2);
                        printf ("  extend: column %d->%d: %ld->%ld arrays, 2-level method %ld->%ld arrays\n", kk,
                                kk + 1, (long) aa[kk].size (), (long)aa[kk + 1].size (), aa2[kk].size (), aa2[kk + 1].size ());

                        if (aa[kk + 1] != aa2[kk + 1]) {
                                printf ("oaunittest: error: 2-level algorithm unequal to original algorithm\n");
                                exit (1);
                        }
                }
                setloglevel (QUIET);

                lst = aa[8];
        }

        {
                cprintf (verbose, "%s: rank calculation using rankStructure\n", bstr);

                for (int i = 0; i < 27; i++) {
                        array_link al = exampleArray (i, 0);
                        if (al.n_columns < 5)
                                continue;
                        al = exampleArray (i, 1);

                        rankStructure rs;
                        rs.verbose = 0;
                        int r = array2xf (al).rank ();
                        int rc = rs.rankxf (al);
                        if (verbose >= 2) {
                                printf ("rank of example array %d: %d %d\n", i, r, rc);
                                if (verbose >= 3) {
                                        al.showproperties ();
                                }
                        }
                        myassert (r == rc, "rank calculations");
                }
        }
        {
                cprintf (verbose, "%s: test dtable creation\n", bstr);

                for (int i = 0; i < 4; i++) {
                        array_link al = exampleArray (5);
                        array_link dtable = createJdtable (al);
                }
        }

        {
                cprintf (verbose, "%s: test Pareto calculation\n", bstr);
                double t0x = get_time_ms ();

                int nn = lst.size ();
                for (int k = 0; k < 5; k++) {
                        for (int i = 0; i < nn; i++) {
                                lst.push_back (lst[i]);
                        }
                }
                Pareto< mvalue_t< long >, long > r = parsePareto (lst, 1);
                cprintf (verbose, "%s: test Pareto %d/%d: %.3f [s]\n", bstr, r.number (), r.numberindices (),
                         (get_time_ms () - t0x));
        }

        {
                cprintf (verbose, "%s: check reduction transformation\n", bstr);
                array_link al = exampleArray (6).reduceLMC ();

                arraydata_t adata = arraylink2arraydata (al);
                LMCreduction_t reduction (&adata);
                reduction.mode = OA_REDUCE;

                reduction.init_state = COPY;
                OAextend oaextend;
                oaextend.setAlgorithm (MODE_ORIGINAL, &adata);
                array_link alr = al.randomperm ();

                array_link al2 = reduction.transformation->apply (al);

                lmc_t tmp = LMCcheck (alr, adata, oaextend, reduction);

                array_link alx = reduction.transformation->apply (alr);

                bool c = alx == al;
                if (!c) {
                        printf ("oaunittest: error: reduction of randomized array failed!\n");
                        printf ("-- al \n");
                        al.showarraycompact ();
                        printf ("-- alr \n");
                        alr.showarraycompact ();
                        printf ("-- alx \n");
                        alx.showarraycompact ();
                        allgood = UNITTEST_FAIL;
                }
        }

        {
                cprintf (verbose, "%s: reduce randomized array\n", bstr);
                array_link al = exampleArray (3);

                arraydata_t adata = arraylink2arraydata (al);
                LMCreduction_t reduction (&adata);

                for (int ii = 0; ii < 50; ii++) {
                        reduction.transformation->randomize ();
                        array_link al2 = reduction.transformation->apply (al);

                        array_link alr = al2.reduceLMC ();
                        if (0) {
                                printf ("\n reduction complete:\n");
                                al2.showarray ();
                                printf ("	--->\n");
                                alr.showarray ();
                        }
                        bool c = (al == alr);
                        if (!c) {
                                printf ("oaunittest: error: reduction of randomized array failed!\n");
                                allgood = UNITTEST_FAIL;
                        }
                }
        }

        /* Calculate symmetry group */
        {
                cprintf (verbose, "%s: calculate symmetry group\n", bstr);

                array_link al = exampleArray (2);
                symmetry_group sg = al.row_symmetry_group ();
                assert (sg.permsize () == sg.permsize_large ().toLong ());

                // symmetry_group
                std::vector< int > vv;
                vv.push_back (0);
                vv.push_back (0);
                vv.push_back (1);
                symmetry_group sg2 (vv);
                assert (sg2.permsize () == 2);
                if (verbose >= 2)
                        printf ("sg2: %ld\n", sg2.permsize ());
                assert (sg2.ngroups == 2);
        }

        /* Test efficiencies */
        {
                cprintf (verbose, "%s: efficiencies\n", bstr);

                std::vector< double > d;
                int vb = 1;

                array_link al;
                if (1) {
                        al = exampleArray (9, vb);
                        al.showproperties ();
                        d = al.Defficiencies (0, 1);
                        if (verbose >= 2)
                                printf ("  efficiencies: D %f Ds %f D1 %f Ds0 %f\n", d[0], d[1], d[2], d[3]);
                        if (fabs (d[0] - al.Defficiency ()) > 1e-10) {
                                printf ("oaunittest: error: Defficiency not good!\n");
                                allgood = UNITTEST_FAIL;
                        }
                }
                al = exampleArray (8, vb);
                al.showproperties ();
                d = al.Defficiencies ();
                if (verbose >= 2)
                        printf ("  efficiencies: D %f Ds %f D1 %f\n", d[0], d[1], d[2]);
                if (fabs (d[0] - al.Defficiency ()) > 1e-10) {
                        printf ("oaunittest: error: Defficiency of examlple array 8 not good!\n");
                }

                al = exampleArray (13, vb);
                if (verbose >= 3) {
                        al.showarray ();
                        al.showproperties ();
                }
                d = al.Defficiencies (0, 1);
                if (verbose >= 2)
                        printf ("  efficiencies: D %f Ds %f D1 %f\n", d[0], d[1], d[2]);

                if ((fabs (d[0] - 0.939014) > 1e-4) || (fabs (d[3] - 0.896812) > 1e-4) || (fabs (d[2] - 1) > 1e-4)) {
                        printf ("ERROR: D-efficiencies of example array 13 incorrect! \n");
                        d = al.Defficiencies (2, 1);
                        printf ("  efficiencies: D %f Ds %f D1 %f Ds0 %f\n", d[0], d[1], d[2], d[3]);

                        allgood = UNITTEST_FAIL;
                        exit (1);
                }

                for (int ii = 11; ii < 11; ii++) {
                        printf ("ii %d: ", ii);
                        al = exampleArray (ii, vb);
                        al.showarray ();
                        al.showproperties ();

                        d = al.Defficiencies ();
                        if (verbose >= 2)
                                printf ("  efficiencies: D %f Ds %f D1 %f\n", d[0], d[1], d[2]);
                }
        }
        {
                cprintf (verbose, "%s: test robustness\n", bstr);

                array_link A (0, 8, 0);
                printf ("should return an error\n  ");
                A.Defficiencies ();

                A = array_link (1, 8, 0);
                printf ("should return an error\n  ");
                A.at (0, 0) = -2;
                A.Defficiencies ();
        }

        {
                cprintf (verbose, "%s: test nauty\n", bstr);

                array_link alr = exampleArray (7, 0);
                if (unittest_nautynormalform (alr, 1) == 0) {
                        printf ("oaunittest: error: unittest_nautynormalform returns an error!\n");
                }
        }

#ifdef HAVE_BOOST
        if (writetests) {
                cprintf (verbose, "OA unittest: reading and writing of files\n");

                boost::filesystem::path tmpdir = boost::filesystem::temp_directory_path ();
                boost::filesystem::path temp = boost::filesystem::unique_path ("test-%%%%%%%.oa");

                const std::string tempstr = (tmpdir / temp).native (); 

                if (verbose >= 2)
                        printf ("generate text OA file: %s\n", tempstr.c_str ());

                int nrows = 16;
                int ncols = 8;
                int narrays = 10;
                arrayfile_t afile (tempstr.c_str (), nrows, ncols, narrays, ATEXT);
                for (int i = 0; i < narrays; i++) {
                        array_link al (nrows, ncols, array_link::INDEX_DEFAULT);                        
                        afile.append_array (al);
                }
                afile.closefile ();

                arrayfile_t af (tempstr.c_str (), 0);
                std::cout << "  " << af.showstr () << std::endl;
                af.closefile ();

                // check read/write of binary file

                arraylist_t ll0;
                ll0.push_back (exampleArray (7));
                ll0.push_back (exampleArray (7).randomcolperm ());
                writearrayfile (tempstr.c_str (), ll0, ABINARY);
                arraylist_t ll = readarrayfile (tempstr.c_str ());
                myassert (ll0.size () == ll.size (), "read and write of arrays: size of list");
                for (size_t i = 0; i < ll0.size (); i++) {
                        myassert (ll0[i] == ll[i], "read and write of arrays: array unequal");
                }

                ll0.resize (0);
                ll0.push_back (exampleArray (24));
                writearrayfile (tempstr.c_str (), ll0, ABINARY_DIFFZERO);
                ll = readarrayfile (tempstr.c_str ());
                myassert (ll0.size () == ll.size (), "read and write of arrays: size of list");
                for (size_t i = 0; i < ll0.size (); i++) {
                        myassert (ll0[i] == ll[i], "read and write of arrays: array unequal");
                }
        }

#endif

        {
                cprintf (verbose, "OA unittest: test nauty\n");
                array_link al = exampleArray (5, 2);
                arraydata_t arrayclass = arraylink2arraydata (al);

                for (int i = 0; i < 20; i++) {
                        array_link alx = al;
                        alx.randomperm ();
                        array_transformation_t t1 = reduceOAnauty (al);
                        array_link alr1 = t1.apply (al);

                        array_transformation_t t2 = reduceOAnauty (alx);
                        array_link alr2 = t2.apply (alx);

                        if (alr1 != alr2)
                                printf ("oaunittest: error: Nauty reductions unequal!\n");
                        allgood = UNITTEST_FAIL;
                }
        }

        cprintf (verbose, "OA unittest: complete %.3f [s]!\n", (get_time_ms () - t0));
        cprintf (verbose, "OA unittest: also run ptest.py to perform checks!\n");

        if (allgood) {
                printf ("OA unittest: all tests ok\n");
                return UNITTEST_SUCCESS;
        } else {
                printf ("OA unittest: ERROR!\n");
                return UNITTEST_FAIL;
        }
}
Esempio n. 9
0
SEXP rechercheZ_relax(SEXP X,SEXP Z,SEXP bic_vide_vect,SEXP methode_tirage,SEXP methode_BIC,SEXP Rmax,SEXP p2max,SEXP Maxiter,SEXP plot,SEXP best,SEXP better,SEXP random,SEXP bla,SEXP nb_opt_max,SEXP Rexact,SEXP Rstar)
{
 
  BEGIN_RCPP
  //déclaration des varibles
  const Map<MatrixXd> matZ(as<Map<MatrixXd> >(Z));//Z
  const Map<MatrixXd> matX(as<Map<MatrixXd> >(X));//X
  const Map<VectorXd> Bic_vide_vect(as<Map<VectorXd> >(bic_vide_vect));//bic_vide_vect
  bool Exact = Rcpp::as<bool>(Rexact);     // length vector 
  bool star = Rcpp::as<bool>(Rstar);     // BICstar

  Rcpp::NumericVector met_tirage(methode_tirage),met_BIC(methode_BIC),rmax(Rmax),P2max(p2max),maxiter(Maxiter),Plot(plot),Best(best),Better(better),Random(random),Bla(bla),Nb_opt_max(nb_opt_max);
  typedef Rcpp::NumericVector::iterator vec_iterator;
  vec_iterator imet_tirage = met_tirage.begin(),imet_BIC=met_BIC.begin(),irmax=rmax.begin(),ip2max=P2max.begin(),imaxiter=maxiter.begin(),iplot=Plot.begin(),ibest=Best.begin(),ibetter=Better.begin(),irandom=Random.begin(),ibla=Bla.begin(),inb_opt_max=Nb_opt_max.begin();
  int p=matZ.cols();//nombre de colonne de la matrice Z
  Eigen::MatrixXd Zopt;//meilleur Z obtenu
  double Bicbest;//BIC associé au meilleur modèle
  Eigen::VectorXd bicvect;//vecteur BIC des matrices Z retenues
  Eigen::MatrixXd newZ;//matrice Z modifié à chaque étapes
  Eigen::MatrixXd list_cand;//matrice qui contient les coordonnées des candidats
  int nbcand=0;//nombre de candidats
  int nb_opt;//nombre de fois ou on a retrouve bicbest
  int step_opt=0;//étape où l'on découvre BIC_opt
  int sumZ=0;
  int k;//nombre du tirage aleatoire (liste candidats)
  int compte;//permet de cree la matrice liste en désignant le numéro du candidat (liste candidats)
  int i;//coordonnée (x ou y) des candidats (liste candidats)
  int rand1;//nombre aleatoire pour la 3ème méthode de tirage des candidats (liste candidats)
  int rand2;//nombre aleatoire pour la 3ème méthode de tirage des candidats (liste candidats)
  int numcand;//numero du candidat
  int i_loc;//premiere coordonnée du candidat (modification Z)
  int j_loc;//duexième coordonnée du candidat (modification Z)
  int realisable;//booléen qui permet de savoir si on peut effectuer un changement dans Z (modification Z)
  Eigen::MatrixXd Zcand;//matrice Z du candidat (modification Z)
  Eigen::ArrayXXd SumCol(1,Zcand.cols());//SumCol est un vecteur qui contient la somme de chaque colonne de Zcand (modification Z)
  int val;//permet de mettre une colonne et une ligne a 0 (modification Z)
  Eigen::VectorXd BIC_cand;//vecteur qui contient les BIC de chaque colonne des la matrice Zcand (calcul du BIC)
  double Sum_BIC_cand;//somme des BIC de BIC_cand (calcul BIC)
  Eigen::VectorXd stock_bool;//vecteur qui permet de savoir si un candidat peut etre choisi (stock)
  Eigen::VectorXd stock_BIC;//vecteur qui contient le BIC de tout les candidats (stock)
  double sumbic;//BIC de chaque etapes
  
  Eigen::VectorXd bic_etape (imaxiter[0]);//vecteur qui stock le BIC de chaque etapes
  Eigen::VectorXd complexite_etape (imaxiter[0]);//vecteur qui stock la compléxité de Z a chaque etapes
  Eigen::VectorXd etape (imaxiter[0]);//vecteur qui stock le type de changement de chaque etapes
  bool station;//permet de savoir si on est stationnaire ou non
    
  //initialisation
  Zopt = MatrixXd::Zero(p,p);
//somme a la main
  Bicbest = Bic_vide_vect.sum();
  bicvect=BicZ_cpp(matX,matZ,Bic_vide_vect,Bic_vide_vect,imet_BIC[0],Zopt);
//somme a la main
  sumbic=bicvect.sum();
  if(star){
      sumbic=sumbic-ProbaZ_cpp(matZ);
   }
  if (ibla[0]>0)
  {
    Rcout<<sumbic<<"\n";
  }
  if (sumbic<Bicbest)
  {
    Bicbest =sumbic;
    Zopt=matZ;
  }
  newZ=matZ;
  
  int step =0;
  
  if (imet_tirage[0]==0)//methode de changement de la ligne et de la colonne
  {
    nbcand=2*p-2;
    list_cand.resize(nbcand,2);//2p-2 candidats
  }
  else if(imet_tirage[0]==-1)
  {
    nbcand=p-1;
    list_cand.resize(nbcand,2);//p-1 candidats (colonne uniquement)
  }
  else if(imet_tirage[0]==-2)
  {
    nbcand=p*(p-1);
    list_cand.resize(nbcand,2);//p-1 candidats (colonne uniquement)
  }
  else if(imet_tirage[0]>0)//methode de tirage aléatoire
  {
    nbcand=imet_tirage[0];
    list_cand.resize(nbcand,2);//le nombre de candidats est determine pas l'utilisateur
  }
  else if(imet_tirage[0]!=-3) //si methode a une valeur aberante
  {
    throw std::range_error("methode de tirage incorrecte");
  }
  
  if (irandom[0]==0)
  {
    ibetter[0]=1;
    ibest[0]=1;
  }
  else if (ibetter[0]==1)
  {
    ibest[0]=1;
  }
  
  nb_opt=0;
  
  while(step<imaxiter[0])
  // initialisation des variables
  
  {
    compte=0;//initialisation du vecteur liste désigne le numéro du candidat 
  //liste candidats (couples [i,j])
    if (imet_tirage[0]==0)//methode de changement de la ligne et de la colonne
    {
      k=int(p*runif(1)[0]);//on tire un numero aleatoire pour savoir quel est la ligne et la colonne de candidats
      for(i=0;i<p;i++)
      {
        if(i!=k)//on ne veut pas avoir de 1 sur la diagonale
        {
          list_cand(compte,0)=i;
          list_cand(compte,1)=k;
          compte=compte+1;
          list_cand(compte,0)=k;
          list_cand(compte,1)=i;
          compte=compte+1;
        }
      }    
    }
    else if (imet_tirage[0]==-1)//seulement la colonne
    {
      k=int(p*runif(1)[0]);
      for(i=0;i<p;i++)
      {
        if(i!=k)
          {
            list_cand(compte,0)=i;
            list_cand(compte,1)=k;
            compte=compte+1;
          }
      }
    }
    else if (imet_tirage[0]==-2)//tout le monde sauf la diagonale
    {
      for(k=0;k<p;k++)
      {
        for(i=0;i<p;i++)
        {
          if(i!=k)
          {
            list_cand(compte,0)=i;
            list_cand(compte,1)=k;
            compte=compte+1;
          }
        }
      }
    }
      else if (imet_tirage[0]==-3)//tout le monde sauf la diagonale
    {
      nbcand=0;
      sumZ=newZ.sum();
      if(sumZ!=0)
      {
        list_cand.resize(newZ.sum(),2);//autant de candidats que de points
      }
      for(k=0;k<p;k++)
      {
        for(i=0;i<p;i++)
        {
          if(i!=k)
          {
            if(newZ(i,k)!=0)
            {
              list_cand(compte,0)=i;
              list_cand(compte,1)=k;
              compte=compte+1;
              nbcand++;
            }
          }
        }
      }
      if(nbcand==0)//aucun candidat donc on arrête
      {
        step=imaxiter[0]+10;
      }
    }
    else if (imet_tirage[0]>0)//methode de tirage aléatoire
    {
      for(i=0;i<nbcand;i++)
      {
        rand1=int(p*runif(1)[0]);//nombres aleatoire pour avoir le numero de la ligne
        rand2=int(p*runif(1)[0]);//nombres aleatoire pour avoir le numero de la colonne
        if (rand1==rand2)//on ne veut pas de 1 sur la diagonale
        {
          if(rand1<p-1)
          {
            rand2=rand1+1;
          }
          else
          {
            rand2=rand1-1;
          }
        }
        list_cand(i,0)=rand1;
        list_cand(i,1)=rand2;            
      }
    }
  
    
    //pour chaque candidat
    for (numcand=0;numcand<nbcand;numcand++)
    {
    //modification (calcul du Z)    (Zcand avec methode (rejet ou relax)   Z,i,j,methode="relax", p2max=inf,rmax=inf)
      i_loc=list_cand(numcand,0);
      j_loc=list_cand(numcand,1);
      realisable=1;//le changement est vrai par defaut
      Zcand=newZ;
      Zcand(i_loc,j_loc)=1-Zcand(i_loc,j_loc);
      for(val=0;val<Zcand.cols();val++)//la ligne et la colonne deviennent 0 car on est en mode rejet
      { 
        Zcand(val,i_loc)=0;
        Zcand(j_loc,val)=0;
      }
      if (Zcand.col(j_loc).sum()>irmax[0])
      {
        realisable=0;
      }
      else
      {
        SumCol=Zcand.colwise().sum();//SumCol est un vecteur qui contient la somme de chaque colonne de Zcand
        if ((SumCol > 0).count()>ip2max[0])//si SumCol a plus de p2max valeur > 0 alors on ne modifiera pas la matrice
        {
          realisable=0;
        }
      }    
      
      //calcul du bic (du nouveau Z généré)      (bicZ)
      if (realisable==0)
      {
        Sum_BIC_cand=0;
      }
      else
      {
        BIC_cand=BicZ_cpp(matX,Zcand,Bic_vide_vect,bicvect,imet_BIC[0],newZ);
        if(Exact){             
          for(val=0;val<BIC_cand.size();val++){
            if(BIC_cand(val)==0){
             Rcout <<val+1<< " depends on";
              //on recherche l'emplacement des 1 dans le vecteur colonne (variables a droite)
              for(int i=0;i<=p-1;i++)
              {
                if (Zcand(i,val)==1)
                {
                 Rcout<< " "<< i+1 << " ";
                }//fin if
              }//fin for i
              Rcout<<"\n";
              step=imaxiter[0];            
            }
          }
        }
        Sum_BIC_cand=BIC_cand.sum();
        if(star){
           Sum_BIC_cand=Sum_BIC_cand-ProbaZ_cpp(Zcand);
        }
      }
    //stockage des valeurs (bic,changement)
      stock_bool.resize(nbcand);
      stock_bool(numcand)=realisable;
      stock_BIC.resize(nbcand);
      stock_BIC(numcand)=Sum_BIC_cand;
    }
    //choix du candidat retenu (tirage au sort ou meilleur selon le cas)
    

    int nb_cand_retenu=stock_bool.sum()+1;//nombre de candidats retenu (certain ne peuvent pas etre pri en compte)
// à faire à la main

    Eigen::VectorXd ind_stock_bool1(nb_cand_retenu-1);//vecteur contenant les numeros des individus retenus
    Eigen::VectorXd stockBIC1(nb_cand_retenu);//vecteur contenant les bic des individus retenus
    int compteur=0;//compteur permattant de remplir stockBIC1 et ind_stock_bool1
    int bettercand=0;
    int iret,jret;//coordonnees du candidat ayant le meilleur bic depuis le debut
    double sumcum=0;
    int cha;
    int w;
    NumericVector ran;
    Eigen::VectorXd bicweight(nb_cand_retenu);
    double sumexp=0;
    double BIC_min=sumbic;
    station=false;
    stockBIC1(0)=sumbic;
    for (i=0;i<stock_BIC.size();i++)//on garde que les individus retunus
    {
      if(stock_bool(i,0)==1)
      {
        ind_stock_bool1(compteur)=i;//seulement les individus possibles
        stockBIC1(compteur+1)=stock_BIC(i);
        if(stockBIC1(compteur+1)<BIC_min)//on cherche le plus petit BIC
        {
          BIC_min=stockBIC1(compteur+1);
          bettercand=compteur+1;
        }
        compteur=compteur+1;
      }     
    } 
    
    //prise de décision
    if(BIC_min<Bicbest) //regarde s'il y'a un BIC meilleur que le meuilleur rencontré
    {
      step_opt=step;
      nb_opt=0;//il y a un nouveau bicbest donc le compteur revient a 0
      Bicbest=BIC_min;
      iret=list_cand(ind_stock_bool1(bettercand-1),0);//-1 a cause de la stationarité
      jret=list_cand(ind_stock_bool1(bettercand-1),1);
      Zopt=newZ;//initialisation à la stationarité
      Zopt(iret,jret)=1-Zopt(iret,jret);
      if (Zopt(iret,jret)==1)//si on a ajouter
      {
        for(cha=0;cha<p;cha++)
        { 
            Zopt(cha,iret)=0;
            Zopt(jret,cha)=0;
        }
      }
      
      if (ibla[0]>0)
      {
        Rcout<<step<<" Bicbest: "<<Bicbest<<" complexite: "<<Zopt.sum()<<"\n";
        if (ibla[0]==2)
        {
          Rcout<<"nb_cand "<<nb_cand_retenu<<"BIC min "<<BIC_min<<"\n";
        }
      }
     
      
      if(ibest[0]==1)//on a vu le meilleur absolu donc si on veut y aller, on y va
      { 
        bicvect=BicZ_cpp(matX,Zopt,Bic_vide_vect,bicvect,imet_BIC[0],newZ);
        newZ=Zopt;
        sumbic=Bicbest;
      }
      else //tirage au sort
      {
        bicweight=stockBIC1;
        for (int v=0;v<nb_cand_retenu;v++)
        {
          bicweight(v)=bicweight(v)-BIC_min;
          bicweight(v)=exp(-bicweight(v)/2);
          sumexp=sumexp+bicweight(v);
        }
        w=-1;//initialisation candidat choisi (il est a -1 car on va rajouter un "+1" avec le while)
        ran=runif(1);
        sumcum=0;
        while (ran[0]>=sumcum)//choix du candidat
        { 
          w++;
          bicweight(w)=bicweight(w)/sumexp;
          sumcum=sumcum+bicweight(w);
        }
        if(w==0)
        {
         station=true;
        }
        else
        {
          iret=list_cand(ind_stock_bool1(w-1),0);//-1 car stationarité en premier dans bicweight
          jret=list_cand(ind_stock_bool1(w-1),1);
          Zcand=newZ;
          Zcand(iret,jret)=1-Zcand(iret,jret);
          if (Zcand(iret,jret)==1)//si on a ajouter
          {
            for(cha=0;cha<p;cha++)
            { 
              Zcand(cha,iret)=0;
              Zcand(jret,cha)=0;
            }
          }
          bicvect=BicZ_cpp(matX,Zcand,Bic_vide_vect,bicvect,imet_BIC[0],newZ);
          newZ=Zcand;
          sumbic=stockBIC1(w);
        }
      }
    } 
    else if(nb_cand_retenu==1) //si la stationarité est le seul candidat
    {
      station=true;
    }
    else if(ibetter[0]==1 && bettercand!=0)//si on a un meilleur local et qu'on veut y aller, on y va
    {
      iret=list_cand(ind_stock_bool1(bettercand-1),0);//-1 a cause de la stationarité
      jret=list_cand(ind_stock_bool1(bettercand-1),1);
      Zcand=newZ;
      Zcand(iret,jret)=1-Zcand(iret,jret);
      if (Zcand(iret,jret)==1)//si on a ajouter
      {
        for(cha=0;cha<p;cha++)
        { 
          Zcand(cha,iret)=0;
          Zcand(jret,cha)=0;
        }
      }
      bicvect=BicZ_cpp(matX,Zcand,Bic_vide_vect,bicvect,imet_BIC[0],newZ);
      newZ=Zcand;
      sumbic=BIC_min;
    }
    else if (irandom[0]==0)
    {
      station=true;
    }
    else//tirage au sort (on a pas de saut systématique)
    {
      bicweight=stockBIC1;
      for (int v=0;v<nb_cand_retenu;v++)
      {
        bicweight(v)=bicweight(v)-BIC_min;
        bicweight(v)=exp(-bicweight(v)/2);
        sumexp=sumexp+bicweight(v);
      }
      
      w=-1;//initialisation candidat choisi (il est a -1 car on va rajouter un "+1" avec le while)
      ran=runif(1);
      sumcum=0;
      while (ran[0]>=sumcum)//choix du candidat
      { 
        w++;
        bicweight(w)=bicweight(w)/sumexp;
        sumcum=sumcum+bicweight(w);
      }
      if(w==0)
      {
       station=true;
      }
      else
      {
        iret=list_cand(ind_stock_bool1(w-1),0);//-1 car stationarité en premier dans bicweight
        jret=list_cand(ind_stock_bool1(w-1),1);
        Zcand=newZ;
        Zcand(iret,jret)=1-Zcand(iret,jret);
        if (Zcand(iret,jret)==1)//i we have added
        {
          for(cha=0;cha<p;cha++)
          { 
            Zcand(cha,iret)=0;
            Zcand(jret,cha)=0;
          }
        }
        bicvect=BicZ_cpp(matX,Zcand,Bic_vide_vect,bicvect,imet_BIC[0],newZ);
        newZ=Zcand;
        sumbic=stockBIC1(w);
      }
    }
    
    if(sumbic==Bicbest)//on regarde si le le BIC est le meme que le BIC optimal
    {
      nb_opt=nb_opt+1;//si c'est le cas alors on a retrouve une fois de plus BICbest
      if(nb_opt==inb_opt_max[0])//si on a atteint le nombre maximum de fois ou on a retrouvé BICbest
      {
        imaxiter[0]=step;//alors on sort du while
        Rcout<<"convergence atteinte";
      }
    }
    
    
    if(iplot[0]==1)//si on veut des graphiques on mets à jour les vecteurs
    {
      bic_etape (step)=sumbic;
      complexite_etape (step)=newZ.sum();

      if (station==true)
      {
        etape (step)=2;//stationarité
      }
      else if(newZ(iret,jret)==0)
      {
        etape (step)=0;//suppression
      }
      else
      {
        etape (step)=1;//ajout
      }
    }
    if(ibla[0]>2)
    {
      Rcout<<step<<" BIC local: "<<sumbic<<" compléxité local: "<<newZ.sum()<<"\n";
    }
    step=step+1; 
  }//fin des étapes (while)
  
  if(iplot[0]==1)
  {
    Eigen::VectorXd BIC_step(step);//on met les vecteurs sorti de bonne dimension
    Eigen::VectorXd complexite_step(step);
    if(step>1)//s'il y'a eu au moins une etape alors on tranfert les donnees des vecteurs
    {
      for(int k=0;k<step;k++)
      {
        BIC_step(k)=bic_etape(k);
        complexite_step(k)=complexite_etape(k);
      }
    }
    return List::create(
      Named("Z")=  newZ,
      Named("bic_loc")=  sumbic,
      Named("Z_opt")=  Zopt,
      Named("bic_opt")=  Bicbest,
      Named("bic_step")=  BIC_step,
      Named("complexity_step")=  complexite_step,
      Named("step")=  etape,
      Named("step_opt")=  step_opt
    );
  }
  else
  {
  return List::create(
      Named("Z")=  newZ,
      Named("bic_loc")=  sumbic,
      Named("Z_opt")=  Zopt,
      Named("bic_opt")=  Bicbest,
      Named("step_opt")=  step_opt
    );
  }
  END_RCPP
}
Esempio n. 10
0
SEXP cleanZ(SEXP X,SEXP Z,SEXP bic_vide_vect,SEXP methode_BIC,SEXP plot,SEXP bla,SEXP Rstar)
{
 
  BEGIN_RCPP
  //déclaration des varibles
  const Map<MatrixXd> matZ(as<Map<MatrixXd> >(Z));//Z
  const Map<MatrixXd> matX(as<Map<MatrixXd> >(X));//X
  const Map<VectorXd> Bic_vide_vect(as<Map<VectorXd> >(bic_vide_vect));//bic_vide_vect
  bool star = Rcpp::as<bool>(Rstar);     // BICstar

  Rcpp::NumericVector met_BIC(methode_BIC),Plot(plot),Bla(bla);
  typedef Rcpp::NumericVector::iterator vec_iterator;
  vec_iterator imet_BIC=met_BIC.begin(),iplot=Plot.begin(),ibla=Bla.begin();
  int p=matZ.cols();//nombre de colonne de la matrice Z
  Eigen::MatrixXd Zopt;//meilleur Z obtenu
  double Bicbest;//BIC associe au meilleur modèle
  Eigen::VectorXd bicvect;//vecteur BIC des matrices Z retenues
  Eigen::MatrixXd newZ;//matrice Z modifie a chaque etapes
  Eigen::MatrixXd list_cand;//matrice qui contient les coordonnées des candidats (liste candidats)
  int compte;//permet de cree la matrice liste en désignant le numéro du candidat (liste candidats)
  int nbcand;//nombre de candidats
  int numcand;//numero du candidat
  int i_loc;//premiere coordonnee du candidat (modification Z)
  int j_loc;//duexieme coordonnee du candidat (modification Z)
  Eigen::MatrixXd Zcand;//matrice Z du candidat (modification Z)
  Eigen::VectorXd BIC_cand;//vecteur qui contient les BIC de chaque colonne des la matrice Zcand (calcul du BIC)
  double Sum_BIC_cand;//somme des BIC de BIC_cand (calcul BIC)
  Eigen::VectorXd stock_bool;//vecteur qui permet de savoir si un candidat peut etre choisi (stock)
  Eigen::VectorXd stock_BIC;//vecteur qui contient le BIC de tout les candidats (stock)
  double sumbic;//BIC de chaque etapes
  double BIC_min;
  bool minimum;
  int i;
  int iret;
  nbcand=matZ.sum();
  Eigen::VectorXd bic_etape(nbcand);//vecteur qui stock le BIC de chaque etapes
  Eigen::VectorXd complexite_etape(nbcand);//vecteur qui stock la complexite de Z a chaque etapes
  Eigen::VectorXd BIC_step;//vecteur qui stock le BIC de chaque etapes
  Eigen::VectorXd complexite_step ;//vecteur qui stock la compléxité de Z a chaque etapes
//  Eigen::ArrayXXd SumCol(1,p);//SumCol est un vecteur qui contient la somme de chaque colonne de Zcand (modification Z)

    
  //initialisation
  bicvect=BicZ_cpp2(matX,matZ,Bic_vide_vect,imet_BIC[0]);
//somme a la main
  sumbic=bicvect.sum();
  if (star)
  {
      sumbic=sumbic-ProbaZ_cpp(matZ);
  }
  if (ibla[0]>0)
  {
    Rcout<<sumbic<<"\n";
  }
  Bicbest =sumbic;
  Zopt=matZ;
  newZ=matZ;
  compte=nbcand+1;
  int step =0;
  
  while(step<nbcand)  
  {
    list_cand.resize(compte-1,2);//le nombre de candidats est la complexite du modele
    compte=0;//initialisation du vecteur liste designe le numero du candidat
  //liste candidats (couples [i,j])
//    list_cand.resize(nbcand,2);//le nombre de candidats est la complexite du modele
    
    for(int m=0;m<p;m++)//parcours ligne
    {
      for(int n=0;n<p;n++)//parcours colonne
      {
        if(newZ(m,n)==1)//on cherche les candidats
        {
          list_cand(compte,0)=m;//stock la ligne du candidat
          list_cand(compte,1)=n;//stock la colonne du candidat
          compte=compte+1;//passage au candidat suivant
        }
      }
    }
    //pour chaque candidat
    for (numcand=0;numcand<compte;numcand++)
    {
    //modification (calcul du Z)    (Zcand avec methode (rejet ou relax)   Z,i,j,methode="relax", p2max=inf,rmax=inf)
      i_loc=list_cand(numcand,0);
      j_loc=list_cand(numcand,1);
      Zcand=newZ;
      Zcand(i_loc,j_loc)=1-Zcand(i_loc,j_loc);//modification de Z par rapport au candidat selectionne
      
    //calcul du bic (du nouveau Z genere)      (bicZ)
      BIC_cand=BicZ_cpp(matX,Zcand,Bic_vide_vect,bicvect,imet_BIC[0],newZ);//calcul du vecteur BIC du candidat
      Sum_BIC_cand=BIC_cand.sum();
      if (star)
      {
        Sum_BIC_cand=Sum_BIC_cand-ProbaZ_cpp(Zcand);
      }
    //stockage du BIC
      stock_BIC.resize(compte);
      stock_BIC(numcand)=Sum_BIC_cand;
    }
    //choix du candidat retenu (tirage au sort ou meilleur selon le cas)
    BIC_min=Bicbest;
    minimum=false;
    for(i=0;i<compte;i++)
    {
      if(stock_BIC(i)<Bicbest)//si on a trouve un minimum
      {
        iret=i;//on retient sa position
        minimum=true;
        Bicbest=stock_BIC(i);//on modifie Bicbest
      }
    }
    if (minimum==true)//si il y a un minimum, on y va
    {
      Zopt=newZ;//initialisation a la stationarite
      Zopt(list_cand(iret,0),list_cand(iret,1))=1-Zopt(list_cand(iret,0),list_cand(iret,1));//modification du Zopt
      bicvect=BicZ_cpp(matX,Zopt,Bic_vide_vect,bicvect,imet_BIC[0],newZ);//calcul du vecteur BIC du nouveau Zopt
      newZ=Zopt;
      
      //partie commentaires
      if (ibla[0]>0)
      {
        Rcout<<"etape : "<<step<<"\n";
        Rcout<<" Bicbest: "<<Bicbest<<" complexite: "<<newZ.sum()<<"\n";
        if (ibla[0]==2)
        {
          Rcout<<"nb_cand "<<compte<<"BIC min "<<BIC_min<<"\n";
        }
      }
      
      //partie graphiques
      if(iplot[0]==1)//si on veut des graphiques on mets a jour les vecteurs
      {
        bic_etape (step)=Bicbest;
        complexite_etape (step)=newZ.sum();
      }
      
      
      step=step+1;//passage a l'etape suivante s'il y a eu un minimum
    }
    else//pas de minimum
    {  
      if (ibla[0]>0){
        Rcout<<"nettoyage fini";
      }
      step=nbcand+1;//arret des etapes
    }
  }//fin des etapes
  
  if(iplot[0]==1)
  {
    BIC_step.resize(nbcand-compte);//on met les vecteurs sorti de bonne dimension
    complexite_step.resize(nbcand-compte);
    if(nbcand-compte>0)//s'il y'a eu au moins une etape alors on tranfert les donnees des vecteurs
    {
      for(int k=0;k<nbcand-compte;k++)
      {
        BIC_step(k)=bic_etape(k);
        complexite_step(k)=complexite_etape(k);
      }
    }
    return List::create(
      Named("Z")=  newZ,
      Named("Z_opt")=  Zopt,
      Named("bic_opt")=  Bicbest,
      Named("bic_step")=  BIC_step,
      Named("complexity_step")=  complexite_step
    );
  }
  else
  {
  return List::create(
      Named("Z")=  newZ,
      Named("Z_opt")=  Zopt,
      Named("bic_opt")=  Bicbest
    );
  }
  END_RCPP
}