// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
cv::Mat
Affine2DFactorizedProblem::computeSigmaMatrix
(
    cv::Mat& params
)
{
    assert(params.rows == 6);
    assert(params.cols == 1);

    MAT_TYPE tx  = params.at<MAT_TYPE>(0, 0);
    MAT_TYPE ty  = params.at<MAT_TYPE>(1, 0);
    MAT_TYPE a   = params.at<MAT_TYPE>(2, 0);
    MAT_TYPE b   = params.at<MAT_TYPE>(3, 0);
    MAT_TYPE c   = params.at<MAT_TYPE>(4, 0);
    MAT_TYPE d   = params.at<MAT_TYPE>(5, 0);

    cv::Mat A    = (cv::Mat_<MAT_TYPE>(2,2) << a, c,
                    b, d);
    cv::Mat invA = A.inv();

    cv::Mat Sigma     = cv::Mat::zeros(6, 6, cv::DataType<MAT_TYPE>::type);
    cv::Mat Sigma_roi = Sigma(cv::Range(0,2), cv::Range(0,2));
    invA.copyTo(Sigma_roi);
    Sigma_roi = Sigma(cv::Range(2,4), cv::Range(2,4));
    invA.copyTo(Sigma_roi);
    Sigma_roi = Sigma(cv::Range(4,6), cv::Range(4,6));
    invA.copyTo(Sigma_roi);

    return Sigma;
};
Exemple #2
0
int main(int argc, char *argv[]) {

    std::cout << std::endl;
    std::cout << "            Abstract Binary Search Algorithm           " << std::endl;
    std::cout << "Copyright (c) 2015+ Oscar Riveros. All rights reserved." << std::endl;
    std::cout << std::endl;

    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " universe<path> log<0|1>" << std::endl;
        return EXIT_FAILURE;
    }

    nInt log = nInt(std::atoi(argv[2]));
    std::chrono::time_point<std::chrono::system_clock> start, end;
    Int t;
    Int u;
    std::vector<Int> U;
    try {
        std::ifstream file(argv[1], std::ifstream::in);
        while (file.good()) {
            file >> t;
            while (file >> u) {
                U.push_back(u);
            }
        }
        std::sort(U.begin(), U.end());
    } catch (...) {
        std::cout << "Something is wrong..." << std::endl;
        exit(EXIT_FAILURE);
    }

    std::cout << std::endl;
    std::cout << "(<" << t << ", " << Sigma(U) - t << ">, [ ";
    for (auto u : U) std::cout << u << " ";
    std::cout << "])" << std::endl;
    std::cout << std::endl;

    start = std::chrono::system_clock::now();
    auto S = ABS(U, t, log);
    end = std::chrono::system_clock::now();

    std::cout << std::endl;
    std::cout << "(<" << Sigma(S) << ", " << Sigma(U) - Sigma(S) << ">, [ ";
    for (auto u : S) std::cout << u << " ";
    std::cout << "])" << std::endl;
    std::cout << std::endl;

    std::chrono::duration<double> seconds = end - start;
    std::cout << "Time   : " << seconds.count() << std::endl;
    std::cout << "Cycles : " << cycles << std::endl;
    std::cout << std::endl;


    return EXIT_SUCCESS;
}
Exemple #3
0
// Normalized score
static double Sigma_N(const MSA &msa, unsigned SeqIndex1, unsigned SeqIndex2)
	{
	unsigned Length = UINT_MAX;
	double Score = Sigma(msa, SeqIndex1, SeqIndex2, &Length);
	double RandomScore = Length*BLOSUM62_Expected;
	return Score - RandomScore;
	}
matrix network::sigma_vector(const matrix &Z_vector,int layer) const
{
	int nraws=layers_sizes[layer];
	matrix Sigma(1,nraws);
	for (int j=0; j<nraws; j++)
		Sigma.put_val(j,0)=sigmoid(Z_vector.get_val(j,0));

	return Sigma;
}
 double ZMMCIS::logpri()const {
   const SpdMatrix & Sigma(model_->Sigma());
   double ans = 0;
   for (int i = 0; i < Sigma.nrow(); ++i) {
     if (samplers_[i].sigma_max() > 0) {
       ans += priors_[i]->logp(1.0 / Sigma(i, i));
     }
   }
   return ans;
 }
Exemple #6
0
std::vector<Int> ABS(std::vector<Int> U, Int t, nInt log) {
    std::vector<Int> S(U);
    std::sort(U.begin(), U.end());
    t = iMin(t, Sigma(U) - t);
    if (!t) return U;
    if (std::binary_search(U.begin(), U.end(), t)) return std::vector<Int>({t});
    for (nInt k = 0; k < U.size(); k++) {
        if (U.at(k) > t) {
            U.erase(U.begin() + k, U.end());
        }
    }
    if (U.size() == 1) return U;
    Int L = iMin(iPow(U.size(), 4), iPow(2, U.size() - 1));
    Int i, j, s, d, n, e = 0;
    Int k = 0;
    Int l = iPow(2, U.size() - 1);
    while (k < L) {
        i = k;
        j = l;
        e = (i + j) / 2;
        while (i < j) {
            cycles++;
            n = (i + j) / 2;
            S = Phi(U, n + e);
            s = Sigma(S);
            d = s - t;
            if (log) {
                std::cout << "(<" << Sigma(S) << ", " << Sigma(U) - Sigma(S) << ">, [ ";
                for (auto u : S) std::cout << u << " ";
                std::cout << "])" << std::endl;
            }
            if (d == 0) return S;
            if (d < 0) i = n + 1;
            if (d > 0) j = n;
            e++;
        }
        k++;
        l++;
    }

    return std::vector<Int>();
}
Exemple #7
0
void MHMM_EM::CheckMatrixSize(const MatrixXf& data) {
	size_t O = (size_t)data.rows();
	size_t Q = (size_t)Transmat.rows();
	size_t M = (size_t)Mixmat.cols();


	//check mu

	if (isempty<MultiD>(Mu))
		throw  std::runtime_error("Mu matrix must be not empty");

	if((size_t)Mu.rows() != M )
		throw  std::runtime_error("Wrong size Mu matrix");


	//check sigma
	if (isempty<MultiD>(Sigma))
		throw  std::runtime_error("Mu matrix must be not empty");

	if((size_t)Sigma.cols() != M || (size_t)Sigma.rows() != Q)
		throw  std::runtime_error("Wrong size Mu matrix");

	if((size_t)Sigma(0,0).cols() != O || (size_t)Sigma(0,0).rows() != O)
		throw  std::runtime_error("Wrong size Sigma matrix");

	//check prior
	if (isempty<MatrixXf>(Prior))
		throw  std::runtime_error("Prior matrix must be not empty");

	/*
	O - Dimension of the data point
	M - Number of mixture components used to model the data point distribution
	Q - Number of states in an HMM

	prior0 has size Q x 1
	transmat0 has size Q x Q
	mu0 has size O x Q x M
	Sigma0 has size O x O x Q x M
	mixmat0 has size Q x M; */

}
Exemple #8
0
double DiskSCFPotentialEval(double R,double Z, double phi,
			    double t,
			    struct potentialArg * potentialArgs){
  double * args= potentialArgs->args;
  //Get args
  int nsigma_args= (int) *args;
  double * Sigma_args= args+1;
  double * hz_args= args+1+nsigma_args;
  //Calculate Rforce
  double r= sqrt( R * R + Z * Z );
  return Sigma(r,Sigma_args) * Hz(Z,hz_args);
}
Exemple #9
0
TEST(ProbDistributionsLkjCorr,testHalf) {
  unsigned int K = 4;
  Eigen::MatrixXd Sigma(K,K);
  Sigma.setConstant(0.5);
  Sigma.diagonal().setOnes();
  double eta = rand() / double(RAND_MAX) + 0.5;
  double f = stan::prob::do_lkj_constant(eta, K);
  EXPECT_FLOAT_EQ(f + (eta - 1.0) * log(0.3125), stan::prob::lkj_corr_log(Sigma, eta));
  eta = 1.0;
  f = stan::prob::do_lkj_constant(eta, K);
  EXPECT_FLOAT_EQ(f, stan::prob::lkj_corr_log(Sigma, eta));
}
Exemple #10
0
 Vec ArModel::simulate(int n) const {
   int p = number_of_lags();
   Vec acf = autocovariance(p);
   Spd Sigma(p);
   Sigma.diag() = acf[0];
   for(int i = 1; i < p; ++i) {
     Sigma.subdiag(i) = acf[i];
     Sigma.superdiag(i) = acf[i];
   }
   Vec zero(p, 0.0);
   Vec y0 = rmvn(zero, Sigma);
   return simulate(n, y0);
 }
// -----------------------------------------------------------------------------
//
// Purpose and Method: 
// Inputs: 
// Outputs: 
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------  
cv::Mat
Homography2DFactorizedProblem::computeSigmaMatrix
  (
  cv::Mat& params
  )
{ 
  assert(params.rows == 9);
  assert(params.cols == 1);

  cv::Mat H            = params.reshape(1, 3).t();
  cv::Mat invH         = H.inv();
  
  cv::Mat Sigma     = cv::Mat::zeros(9, 9, cv::DataType<MAT_TYPE>::type);
  cv::Mat Sigma_roi = Sigma(cv::Range(0,3), cv::Range(0,3));
  invH.copyTo(Sigma_roi);
  Sigma_roi         = Sigma(cv::Range(3,6), cv::Range(3,6));
  invH.copyTo(Sigma_roi);
  Sigma_roi         = Sigma(cv::Range(6,9), cv::Range(6,9));
  invH.copyTo(Sigma_roi);
      
  return Sigma;
};
Exemple #12
0
 Vector ArModel::simulate(int n, RNG &rng) const {
   int p = number_of_lags();
   Vector acf = autocovariance(p);
   SpdMatrix Sigma(p);
   Sigma.diag() = acf[0];
   for (int i = 1; i < p; ++i) {
     Sigma.subdiag(i) = acf[i];
     Sigma.superdiag(i) = acf[i];
   }
   Vector zero(p, 0.0);
   Vector y0 = rmvn(zero, Sigma);
   return simulate(n, y0, rng);
 }
Exemple #13
0
void plot()
{
    gROOT->LoadMacro("tdrstyle.C");
    gROOT->LoadMacro("Sigma.C++");
    setTDRStyle();
    version=8;
    TString str("SigmaNew_v");
    str+=version;
    Sigma()->Print(str+".png");
    //Sigma()->Print(str+".eps");
    //Sigma()->Print(str+".pdf");
    return;
}
Exemple #14
0
TEST(ProbDistributionsLkjCorr,testIdentity) {
  unsigned int K = 4;
  Eigen::MatrixXd Sigma(K,K);
  Sigma.setZero();
  Sigma.diagonal().setOnes();
  srand(time(0));
  double eta = rand() / double(RAND_MAX) + 0.5;
  double f = stan::prob::do_lkj_constant(eta, K);
  EXPECT_FLOAT_EQ(f, stan::prob::lkj_corr_log(Sigma, eta));
  eta = 1.0;
  f = stan::prob::do_lkj_constant(eta, K);
  EXPECT_FLOAT_EQ(f, stan::prob::lkj_corr_log(Sigma, eta));
}
Exemple #15
0
 virtual std::ostream& Print (std::ostream& os) const {
     Operator<T>::Print(os);
     os << "    image size: rank(" << Rank() << ") side(" <<
        ImageSize() << ") nodes(" << KSpaceSize() << ")" << std::endl;
     os << "    nfft: maxit(" << Maxit() << ") eps(" << Epsilon() <<	") alpha("
        << Alpha() << ") m("<< m_m <<") sigma(" << Sigma() << ")" << std::endl;
     os << "    have_kspace(" << m_have_kspace << ") have_weights(" <<
        m_have_weights << ") have_b0(" << m_have_b0 << ")" << std::endl;
     os << "    ft-threads(" << m_np << ")";
     if (m_3rd_dim_cart)
         os << " 3rd dimension (" << m_ncart << ") is Cartesian.";
     return os;
 }
Exemple #16
0
std::vector<Int> ABS(std::vector<Int> U, Int t, nInt log) {
    Int z = iPow(t, U.size() / 2);
    std::vector<Int> S(U);
    std::sort(U.begin(), U.end());
    Int L = iMin(iPow(U.size(), 4), iPow(2, U.size() - 1));
    Int i, j, s, d, n, e = 0;
    Int k = 0;
    Int l = iPow(2, U.size() - 1);
    while (k < L) {
        i = k;
        j = l;
        e = (i + j) / 2;
        while (i < j) {
            cycles++;
            n = (i + j) / 2;
            S = Phi(U, n + e);
            s = iPow(Sigma(S), S.size());
            d = s - z;
            if (log) {
                std::vector<Int> C;
                std::set_difference(U.begin(), U.end(), S.begin(), S.end(), std::back_inserter(C));
                std::cout << "(<" << Sigma(S) << ", " << Sigma(U) - Sigma(S) << ">, [ ";
                for (auto u : S) std::cout << u << " ";
                std::cout << "]  [";
                for (auto u : C) std::cout << u << " ";
                std::cout << "])" << std::endl;
            }
            if (d == 0) return S;
            if (d < 0) i = n + 1;
            if (d > 0) j = n;
            e++;
        }
        k++;
        l++;
    }

    return std::vector<Int>();
}
Exemple #17
0
TEST(ProbDistributionsLkjCorr,Sigma) {
  unsigned int K = 4;
  Eigen::MatrixXd Sigma(K,K);
  Sigma.setZero();
  Sigma.diagonal().setOnes();
  double eta = rand() / double(RAND_MAX) + 0.5;
  EXPECT_NO_THROW (stan::prob::lkj_corr_log(Sigma, eta));
  
  EXPECT_THROW (stan::prob::lkj_corr_log(Sigma, -eta), std::domain_error);
  
  Sigma = Sigma * -1.0;
  EXPECT_THROW (stan::prob::lkj_corr_log(Sigma, eta), std::domain_error);
  Sigma = Sigma * (0.0 / 0.0);
  EXPECT_THROW (stan::prob::lkj_corr_log(Sigma, eta), std::domain_error);
}
Exemple #18
0
static void myF(myu64 *state, const myu64 *w, int k_index)
{
  myu64 t, t1, t2;
  unsigned char i;
  Ch(&t, state+4, state+5, state+6);
  Sigma(&t1, state+4, 14, 18, 23);
  bigint_add64(t1.v, t1.v, (state+7)->v);  
  bigint_add64(t1.v, t1.v, t.v);  
  for(i=0;i<8;i++)
    t.v[i] = pgm_read_byte((unsigned char *)roundconstants_pgm+k_index*8+i);
  bigint_add64(t1.v, t1.v, t.v);  
  bigint_add64(t1.v, t1.v, w->v);  
  Sigma(&t2, state+0, 28, 34, 5);
  Maj(&t,state+0,state+1,state+2);
  bigint_add64(t2.v, t2.v, t.v);    
  *(state+7) = *(state+6);
  *(state+6) = *(state+5);
  *(state+5) = *(state+4);
  bigint_add64((state+4)->v, (state+3)->v, t1.v);  
  *(state+3) = *(state+2);
  *(state+2) = *(state+1);
  *(state+1) = *(state+0);
  bigint_add64((state+0)->v, t1.v, t2.v);
}
  //======================================================================
  SpdMatrix ArStateModel::initial_state_variance()const{
    if (initial_state_variance_.nrow() != state_dimension()) {
      report_error("Sigma_.nrow() != state_dimension() in "
                   "ArStateModel::initial_state_mean()");
    }
    SpdMatrix & Sigma(const_cast<SpdMatrix &>(initial_state_variance_));

    if (stationary_initial_distribution_) {
      Vector gamma = autocovariance(state_dimension());
      Sigma.diag() = gamma[0];
      for(int i = 1; i < state_dimension(); ++i){
        Sigma.superdiag(i) = gamma[i];
      }
      Sigma.reflect();
    }
    return initial_state_variance_;
  }
Exemple #20
0
Type objective_function<Type>::operator() ()
{
  DATA_STRING(distr);
  DATA_INTEGER(n);
  Type ans = 0;

  if (distr == "norm") {
    PARAMETER(mu);
    PARAMETER(sd);
    vector<Type> x = rnorm(n, mu, sd);
    ans -= dnorm(x, mu, sd, true).sum();
  }
  else if (distr == "gamma") {
    PARAMETER(shape);
    PARAMETER(scale);
    vector<Type> x = rgamma(n, shape, scale);
    ans -= dgamma(x, shape, scale, true).sum();
  }
  else if (distr == "pois") {
    PARAMETER(lambda);
    vector<Type> x = rpois(n, lambda);
    ans -= dpois(x, lambda, true).sum();
  }
  else if (distr == "compois") {
    PARAMETER(mode);
    PARAMETER(nu);
    vector<Type> x = rcompois(n, mode, nu);
    ans -= dcompois(x, mode, nu, true).sum();
  }
  else if (distr == "compois2") {
    PARAMETER(mean);
    PARAMETER(nu);
    vector<Type> x = rcompois2(n, mean, nu);
    ans -= dcompois2(x, mean, nu, true).sum();
  }
  else if (distr == "nbinom") {
    PARAMETER(size);
    PARAMETER(prob);
    vector<Type> x = rnbinom(n, size, prob);
    ans -= dnbinom(x, size, prob, true).sum();
  }
  else if (distr == "nbinom2") {
    PARAMETER(mu);
    PARAMETER(var);
    vector<Type> x = rnbinom2(n, mu, var);
    ans -= dnbinom2(x, mu, var, true).sum();
  }
  else if (distr == "exp") {
    PARAMETER(rate);
    vector<Type> x = rexp(n, rate);
    ans -= dexp(x, rate, true).sum();
  }
  else if (distr == "beta") {
    PARAMETER(shape1);
    PARAMETER(shape2);
    vector<Type> x = rbeta(n, shape1, shape2);
    ans -= dbeta(x, shape1, shape2, true).sum();
  }
  else if (distr == "f") {
    PARAMETER(df1);
    PARAMETER(df2);
    vector<Type> x = rf(n, df1, df2);
    ans -= df(x, df1, df2, true).sum();
  }
  else if (distr == "logis") {
    PARAMETER(location);
    PARAMETER(scale);
    vector<Type> x = rlogis(n, location, scale);
    ans -= dlogis(x, location, scale, true).sum();
  }
  else if (distr == "t") {
    PARAMETER(df);
    vector<Type> x = rt(n, df);
    ans -= dt(x, df, true).sum();
  }
  else if (distr == "weibull") {
    PARAMETER(shape);
    PARAMETER(scale);
    vector<Type> x = rweibull(n, shape, scale);
    ans -= dweibull(x, shape, scale, true).sum();
  }
  else if (distr == "AR1") {
    PARAMETER(phi);
    vector<Type> x(n);
    density::AR1(phi).simulate(x);
    ans += density::AR1(phi)(x);
  }
  else if (distr == "ARk") {
    PARAMETER_VECTOR(phi);
    vector<Type> x(n);
    density::ARk(phi).simulate(x);
    ans += density::ARk(phi)(x);
  }
  else if (distr == "MVNORM") {
    PARAMETER(phi);
    matrix<Type> Sigma(5,5);
    for(int i=0; i<Sigma.rows(); i++)
      for(int j=0; j<Sigma.rows(); j++)
        Sigma(i,j) = exp( -phi * abs(i - j) );
    density::MVNORM_t<Type> nldens = density::MVNORM(Sigma);
    for(int i = 0; i<n; i++) {
      vector<Type> x = nldens.simulate();
      ans += nldens(x);
    }
  }
  else if (distr == "SEPARABLE") {
    PARAMETER(phi1);
    PARAMETER_VECTOR(phi2);
    array<Type> x(100, 200);
    SEPARABLE( density::ARk(phi2), density::AR1(phi1) ).simulate(x);
    ans += SEPARABLE( density::ARk(phi2), density::AR1(phi1) )(x);
  }
  else if (distr == "GMRF") {
    PARAMETER(delta);
    matrix<Type> Q0(5, 5);
    Q0 <<
      1,-1, 0, 0, 0,
     -1, 2,-1, 0, 0,
      0,-1, 2,-1, 0,
      0, 0,-1, 2,-1,
      0, 0, 0,-1, 1;
    Q0.diagonal().array() += delta;
    Eigen::SparseMatrix<Type> Q = asSparseMatrix(Q0);
    vector<Type> x(5);
    for(int i = 0; i<n; i++) {
      density::GMRF(Q).simulate(x);
      ans += density::GMRF(Q)(x);
    }
  }
  else if (distr == "SEPARABLE_NESTED") {
    PARAMETER(phi1);
    PARAMETER(phi2);
    PARAMETER(delta);
    matrix<Type> Q0(5, 5);
    Q0 <<
      1,-1, 0, 0, 0,
     -1, 2,-1, 0, 0,
      0,-1, 2,-1, 0,
      0, 0,-1, 2,-1,
      0, 0, 0,-1, 1;
    Q0.diagonal().array() += delta;
    Eigen::SparseMatrix<Type> Q = asSparseMatrix(Q0);
    array<Type> x(5, 6, 7);
    for(int i = 0; i<n; i++) {
      SEPARABLE(density::AR1(phi2),
                SEPARABLE(density::AR1(phi1),
                          density::GMRF(Q) ) ).simulate(x);
      ans += SEPARABLE(density::AR1(phi2),
                       SEPARABLE(density::AR1(phi1),
                                 density::GMRF(Q) ) )(x);
    }
  }
  else error( ("Invalid distribution '" + distr + "'").c_str() );
  return ans;
}
Exemple #21
0
int main(int argc, char *argv[]) {
	ub4 tots=0;
	ub4 ts, r, bts, div;
	ub4 q1 = 24;
	ub4 q2 = 28;
	double totSigma=0.0;
	double totRange=0.0;
	double sigma,range,mSigma,mRange;
	// timer
	time_t a,z;
	// rounds
	qi = pow(2,q1);
	// check the command line
	if (argc<=1) { usage(); exit(0); }
	if (argc>=2) q1 = atoi(argv[1]);
	if (argc>=3) q2 = atoi(argv[2]);
	if (argc>=4) rng= atoi(argv[3]) % 9;
	if (argc>=5) strcpy(s,argv[4]);
	
	#ifdef TEST
	#ifdef __TINYC__
		puts("Tiny C");
	#endif
	#ifdef __WATCOMC__
		puts("Open Watcom C");
	#endif
	#ifdef _MSC_VER
		puts("Microsoft Visual C");
	#endif
	#ifdef __GNUC__
		puts("GNU C");
	#endif
	#endif
	#if __STDC_VERSION__ >= 199901L
		puts("C99 supported.");
	#endif

	#ifdef MOD
	printf("MOD: ");
	#endif
	#ifdef LIM
	printf("LIM: ");
	#endif
	#ifdef SAM
	printf("SAM: ");
	#endif

	div = q2-q1+1;
	printf("%d %s trial sets in [2**%d..2**%d]\n",div,RNGs[rng],q1,q2);
		
	puts("Trial      Range        Sigma         Time");
	puts("------------------------------------------");
	
	for (j=q1; j<=q2; j++) {
		for (i=0; i<MODU; i++) totals[i]=0;
		probtot = 0.0;
		qi = pow(2,j);
		rSeed(rng,s,rStateSize(rng)*7);
		time(&a);
		
		for (q=0; q<qi; q++) { 
			#ifdef MOD
			r=rRandom(rng) % MODU;
			#else
			#ifdef LIM
			r=Lim(rng);
			#endif
			r=Sam(rng);
			#endif
			totals[r]++;
		}
		
		time(&z);
		ts=(size_t)(z-a);
		tots+=ts;
	
		for (i=0; i<MODU; i++) {
			// expected probabilities
			expect[i] = (double)1/MODU;
			// actual probabilities
			prob[i]=(double)totals[i]/qi;
			// probtot holds total of probabilities - it should converge to 1.0
			probtot=probtot+prob[i];
			// collect value-names & decide output format
			values[i] = i + 'A';
		}
		sigma = Sigma(0,MODM1);
		range = prob[MaxP(0,MODM1)]-prob[MinP(0,MODM1)];
		totSigma+=sigma; totRange+=range;
		printf("2**%d    %1.7f    %1.7f      %3d s\n",j,range,sigma,ts);
	}
	puts("------------------------------------------");
	mSigma = (double)totSigma/div; mRange = (double)totRange/div;
	    printf("Mean:    %1.7f    %1.7f     %4d s\n",mRange,mSigma,tots);
	#ifdef TEST
	puts(""); for (i=0; i<MODU; i++) printf("%2c) %1.7f\n",values[i],prob[i]);
	#endif
	return 0;
}
 MvRegData *MvReg::simdat(const Vector &x, RNG &rng) const {
   Vector mu = predict(x);
   Vector y = rmvn_mt(rng, mu, Sigma());
   return new MvRegData(y, x);
 }
Exemple #23
0
AlgorithmGaussNoise::AlgorithmGaussNoise(double s):SimpleAlgorithm()
{
    Sigma(s);
}
Exemple #24
0
int main(int argc, char** argv){

    ros::init(argc, argv, "wkmeans_test");
    ros::NodeHandle node;
    ros::Rate rate(100);

    std::size_t K = 10;

    arma::vec pi = arma::randu<arma::vec>(3);
              pi = arma::normalise(pi);
    std::vector<arma::vec> Mu(K);
    std::vector<arma::mat> Sigma(K);


    float a = -2;
    float b =  2;

    for(std::size_t k = 0; k < K;k++){
        Mu[k] = (b - a) * arma::randu<arma::vec>(3) + a;
        Sigma[k].zeros(3,3);
        arma::vec tmp = 0.3 * arma::randu<arma::vec>(3) + 0.2;
        Sigma[k](0,0) =tmp(0);
        Sigma[k](1,1) =tmp(1);
        Sigma[k](2,2) =tmp(2);
    }


      GMM gmm;
      gmm.setParam(pi,Mu,Sigma);
      std::size_t nb_samples = 10000;
      arma::colvec weights;
      arma::mat X(nb_samples,3);
      gmm.sample(X);
      arma::vec L(nb_samples);
      gmm.P(X,L);

      L = L / arma::max(L);

     // L.elem(q1).zeros();

      unsigned char                           rgb[3];
      std::vector<std::array<float,3> >       colors(nb_samples);


      for(std::size_t i = 0 ; i < L.n_elem;i++){
          ColorMap::jetColorMap(rgb,L(i),0,1);
          colors[i][0]    = ((float)rgb[0])/255;
          colors[i][1]    = ((float)rgb[1])/255;
          colors[i][2]    = ((float)rgb[2])/255;
      }


        arma::uvec q1 = arma::find(L > 0.6*arma::max(L));

        std::vector<std::array<float,3> >  colors2(q1.n_elem);
        arma::mat X_W(q1.n_elem,3);
        for(std::size_t i = 0; i < q1.n_elem;i++){
            assert(q1(i) < colors.size());
            assert(q1(i) < X.n_rows);
            colors2[i]  = colors[q1(i)];
            X_W.row(i)  = X.row(q1(i));
        }




      Weighted_Kmeans<double> weighted_kmeans;

      weighted_kmeans.cluster(X_W.st(),L);
      weighted_kmeans.centroids.print("centroids");

      opti_rviz::Vis_points points(node,"centroids");
      points.scale = 0.1;
      points.r = 1;
      points.b = 1;
      arma::fmat c = arma::conv_to<arma::fmat>::from(weighted_kmeans.centroids.st());
      points.initialise("world",c);

      opti_rviz::Vis_point_cloud vis_point(node,"samples");
      vis_point.set_display_type(opti_rviz::Vis_point_cloud::DEFAULT);
      vis_point.initialise("world",X_W);



    opti_rviz::Vis_gmm vis_gmm(node,"gmm");
    vis_gmm.initialise("world",pi,Mu,Sigma);


    while(node.ok()){


        vis_gmm.update(pi,Mu,Sigma);
        vis_gmm.publish();

        vis_point.update(X_W,colors2,weights);
        vis_point.publish();

        points.update(c);
        points.publish();

        ros::spinOnce();
        rate.sleep();
    }



}
main()
{
      
/******************************************************************************/
/*  BUILDING DISK POSITION DISTRIBUTION                                       */
/******************************************************************************/

    std::cout << "Building disk\n";         //  printing disk parameters
    std::cout << "  Mdisk = " << Md << "\n";
    std::cout << "  Ndisk = " << Ndisk << "\n";
    std::cout << "  Radial Scale Length h = " << h << "\n";
    std::cout << "  Vertical Scale Length z0 = " << z0 << "\n";
    std::cout << "  Radial Cutoff = " << diskcut << "\n";
    std::cout << "  Vertical Cutoff = " << thickcut << "\n";
    
    std::vector<Vector> disk(Ndisk, Vector(3)); //  array of disk positions
    
    min = 0.0, max = diskcut;               //  setting max and min radii
    topbound = findtopbound(surfacedist, min, max);   //  finding topbound
    
    for (int i = 0; i < Ndisk; i++)         //  for each particle in disk
    {
        r = rejectionsample(surfacedist, min, max, topbound); //  choose
                                            //  random radius
        disk[i][0] = r;                     //  assigning as such
        disk[i][1] = randomreal(0.0, 2.0*PI); //  randomize azimuthal angle
    }                                       
    
    min = -thickcut;                        //  setting min and max
    max = thickcut;                         //  heights
    topbound = findtopbound(diskthick, min, max);   //  finding topbound
    for (int i = 0; i < Ndisk; i++)         //  for each disk particle
    {
        disk[i][2] = rejectionsample(diskthick, min, max, topbound);    //
                                            //  choosing height randomly
        bodies[i].mass = Md / ((double)Ndisk);  //  assigning masses such that
                                            //  total mass is correct
        bodies[i].pos = cyltocart(disk[i]); //  transforming to cartesian coords
        bodies[i].id = i;                   //  assigning particle id
        bodies[i].DM = false;               //  these are not dark
    }
    

/******************************************************************************/
/*  BUILDING HALO POSITION DISTRIBUTION                                       */
/******************************************************************************/
    
    std::cout << "Building Halo\n";         //  printing parameters
    std::cout << "  Mhalo = " << Mh << "\n";
    std::cout << "  Nhalo = " << Nhalo << "\n";
    std::cout << "  Scale Length rc = " << rc << "\n";
    std::cout << "  Scale Length gamma = " << g << "\n";
    std::cout << "  Cutoff Radius = " << halocut << "\n";

    std::vector<Vector> halo(Nhalo, Vector(3)); //  array of halo positions
    
    min = 0.0, max = halocut;               //  max and min for distribution
    topbound = findtopbound(hernquisthalo, min, max);   //  finding topbound
    for (int i = 0; i < Nhalo; i++)         //  for each bulge particle
    {
        r = rejectionsample(hernquisthalo, min, max, topbound);  //  select r from
                                            //  distribution
        bodies[Ndisk + i].pos = randomsphere(r);    //  randomize position
                                            //  on sphere
        bodies[Ndisk + i].mass = Mh / ((double)Nhalo);  //  normalizing mass
        bodies[Ndisk + i].id = Ndisk + i;   //  setting appropriate ID
        bodies[Ndisk + i].DM = true;        //  these are dark
        halo[i] = carttosphere(bodies[Ndisk + i].pos);  //  saving copy in
                                            //  spherical coords for later
    }
    

/******************************************************************************/
/*  BUILDING BULGE POSITION DISTRIBUTION                                      */
/******************************************************************************/

    std::cout << "Building Bulge\n";
    std::cout << "  Mbulge = " << Mb << "\n";
    std::cout << "  Nbulge = " << Nbulge << "\n";
    std::cout << "  Scale Length a = " << a << "\n";
    std::cout << "  Cutoff Radius = " << bulgecut << "\n";
    
    std::vector<Vector> bulge(Nbulge, Vector(3));   //  array of bulge positions
    
    min = 0.0; max = bulgecut;              //  distribution max and min
    topbound = findtopbound(bulgedist, min, max);   //  finding topbound
    for (int i = 0; i < Nbulge; i++)        //  for each particle
    {
        r = rejectionsample(bulgedist, min, max, topbound);  //  select r from
                                            //  distribution
        bodies[Ndisk + Nhalo + i].pos = randomsphere(r);    //  randomize sphere
                                            //  position
        bodies[Ndisk + Nhalo + i].mass = Mb / (double)Nbulge;   //  setting mass
        bodies[Ndisk + Nhalo + i].id = Ndisk + Nhalo + i;   //  setting IDs
        bulge[i] = carttosphere(bodies[Ndisk + Nhalo + i].pos); //  saving copy
                                            //  in spherical coordinates
    }

    
/******************************************************************************/
/*  Approximating Cumulative Mass Distribution M(r)                           */
/******************************************************************************/
    
    dr = halocut / ((double) massbins);     //  setting separation between mass
                                            //  bins
    
    std::cout << "Approximating Cumulative Mass Distribution M(r)\n";
    std::cout << "  Number of bins = " << massbins << "\n";
    std::cout << "  dr = " << dr << "\n";
    
    std::vector <Vector> Massatr(massbins, Vector(2));  //  Array to hold
                                            //  radius and value of cumulative
                                            //  mass distribution
    
    for (int i = 0; i < massbins; i++)      //  for each mass bin
    {
        Massatr[i][1] = ((double)(i+1))*dr; //  setting radius
        Massatr[i][0] = 0.0;                //  clearing total mass
        
        for (int j = 0; j < Ndisk; j++)     //  for each disk mass
        {
            r = sqrt(disk[j][0]*disk[j][0] + disk[j][2]*disk[j][2]);    // radius
                                            //  in spherical coordinates
            if((r < (double)(i+1)*dr))      //  if radius less than bin radius
            {
                Massatr[i][0] += Md / (double)Ndisk;    //  add mass
            }
        }
        
        for (int j = 0; j < Nhalo; j++)     //  for each halo mass
        {
            r = halo[j][0];                 //  radius
            if((r < (double)(i+1)*dr))      // if radius less than bin radius
            {
                Massatr[i][0] += Mh / (double)Nhalo;    //  add mass
            }
        }
        
        for (int j = 0; j < Nbulge; j++)    // for each bulge mass
        {
            r = bulge[j][0];                //  radius
            if((r < (double)(i+1)*dr))      //  if radius less than bin radius
            {
                Massatr[i][0] += Mb / (double)Nbulge;   //  add mass
            }
        }
    }
    
    
/******************************************************************************/
/*  Setting Halo Velocities                                                   */
/******************************************************************************/
    
    std::cout << "Setting Halo Velocities\n";
    
    double v;                               //  variable to hold speed
    double vesc;                            //  variable to hold escape speed
    
    std::vector<Vector> halovels(Nhalo, Vector(3)); //  Vector to hold halo
                                            //  velocities
    
    for (int i = 0; i < Nhalo; i++)         //  for each halo mass
    {
        r = halo[i][0];                     //  radius
        
        startbin = floor(r/dr);             //  starting index is floor of r/dr
        
        vesc = sqrt(2.0*Massatr[startbin][0]/r);    //  escape velocity
        
        vr2 = 0.0;                          //  clearing radial dispersion
        for (int j = startbin; j < massbins; j++)   //  for each mass bin
        {
            vr2 += hernquisthalo(Massatr[j][1])*dr*Massatr[j][0];   //  add 
        }                                   //  contribution
        vr2 /= (hernquisthalo(r)/(r*r));    //  dividing by halo density at r
        
        
        min = 0.0;                          //  distribution min
        max = 0.95*vesc;                    //  distribution max is 0.95 of
                                            //  escape velocity
        topbound = vr2 / 2.71828;           //  topbound is vr^2 / e
        
        v = rejectionsample(halospeeddist, min, max, topbound); //  selecting
                                            //  absolute speed
        halovels[i] = randomsphere(v);      //  randomizing cartesian velocities
                                            //  on a sphere of radius v
        bodies[Ndisk + i].vel = halovels[i];//  assigning velocities as such
        
    }
    
    
/******************************************************************************/
/*  Setting Bulge Velocities                                                  */
/******************************************************************************/

    
    std::cout << "Setting Bulge Velocities\n";
    
    std::vector<Vector> bulgevels(Nbulge, Vector(3));   // Vector to hold bulge
                                             // velocities
    
    for (int i = 0; i < Nbulge; i++)        //  for each particle
    {
        r = bulge[i][0];                    //  radius
        
        startbin = floor(r / dr);           //  starting index
        
        vesc = sqrt(2.0*Massatr[startbin][0]/r);    //  escape velocity
        
        vr2 = 0.0;                          //  clearing radial dispersion
        
        for (int j = startbin; j < massbins; j++)   //  for each mass bin
        {
            vr2 += bulgedist(Massatr[j][1])*dr*Massatr[j][0];   // add
                                            //  contribution
        }
        vr2 /= bulgedist(r)/(r*r);          //  dividing by halo density at r
        
        
        min = 0.0;                          //  distribution min
        max = 0.95*vesc;                    //  max is 0.95 of escape velocity
        topbound = vr2 / 2.71828;           //  topbound is vr^2 /e
        
        v = rejectionsample(bulgedist, min, max, topbound); //  selecting absolute
                                            //  absolute speed
        bulgevels[i] = randomsphere(v);     //  randomizing constrained cartesian
                                            //  velocities
        bodies[Ndisk + Nhalo + i].vel = bulgevels[i];   //  assining data as such
    }

    
/******************************************************************************/
/*  Setting Disk Velocities                                                   */
/******************************************************************************/

    std::cout << "Setting Disk Velocities\n";
    std::cout << "  Q = " << Q << "\n";
    std::cout << "  Reference radius = " << rref << "\n";
    std::vector<Vector> diskvels(Ndisk, Vector(3)); //  Vector to hold disk
                                            //  velocities
    
    double vz2;                             //  vertical dispersion
    double vc;                              //  circular speed
    double ar;                              //  radial acceleration
    double k;                               //  epicyclic frequency
    double sigmaz2;                         //  azimuthal velocity dispersion
    double sigmaavg;                        //  average dispersion
    double Omega;                           //  angular frequency
    double A;                               //  radial dispersion constant
    int count;                              //  count variable for averaging
    Vector acc(3);                          //  vector to store acceleration
    double as = 0.25*h;
    
    
    maketree(bodies, Ntot, root);           //  making tree
    
    // NORMALIZING RADIAL DISPERSION
    std::cout << "  Normalizing Radial Distribution\n";
    dr = diskcut / 1000.0;                  //  width of annulus in which
                                            //  to average dispersion
    sigmaavg = 0.0;                         //  zeroing average
    for (int i = 0; i < Ndisk; i++)         //  for each disk particle
    {
        r = disk[i][0];                     //  radius
        if (fabs(r - rref) < dr)            //  if radius in annulus
        {                                   //  calculate epicylclic frequency
            k = epicyclicfrequency(bodies, Ntot, i, root, eps, theta, 0.05*dr);
            sigmaavg += 3.36*Sigma(r)/k;    //  calculate dispersion and add to
                                            //  average
            count += 1;                     //  up count
        }  
    }
    
    sigmaavg /= (double)count;              //  divide total by count
    sigmaavg *= Q;                          //  adjust by Q
    
    A = sigmaavg*sigmaavg / Sigma(rref);    //  setting norm constant
    
    
    //  ASSIGNING VELOCITIES
    std::cout << "  Setting particle velocities\n";
    for (int i = 0; i < Ndisk; i++)         //  for every particle
    {
        r = disk[i][0];                     //  radius
        vz2 = PI*z0*Sigma(sqrt(r*r + 2.0*as*as));    //  vertical dispersion
        diskvels[i][2] = gaussianrandom(sqrt(vz2)); //  randomizing vertical
                                            //  with this dispersion
        
        vr2 = A*Sigma(sqrt(r*r + 2.0*as*as));   //  assigning radial dispersion
        diskvels[i][0] = gaussianrandom(sqrt(vr2)); //  randomizing radial
                                            //  dispersion
        
        acc = treeforce(&bodies[i], root, eps, theta);  //  acceleration
        ar = (acc[0]*bodies[i].pos[0] + acc[1]*bodies[i].pos[1])/r; //
                                            //  radial acceleration
        Omega = sqrt(fabs(ar)/r);           //  angular frequency
        k = epicyclicfrequency(bodies, Ntot, i, root, eps, theta, dr);  //
                                            //  epicyclic frequency
        vc = Omega*r;                       //  circular speed
        v = sqrt(fabs(vc*vc + vr2*(1.0 - (k*k)/(4.0*Omega*Omega) - 2.0*r/h)));  //
                                            //  azimuthal streaming velocity
        sigmaz2 = vr2*k*k/(4.0*Omega*Omega);//  azimuthal dispersion
        v += gaussianrandom(sqrt(sigmaz2)); //  adding random azimuthal component
        diskvels[i][1] = v;                 //  assigning azimuthal velocity 
        
                                            //  transforming to cartesian coords
        bodies[i].vel[0] = diskvels[i][0]*cos(disk[i][1])
                            - diskvels[i][1]*sin(disk[i][1]);
        bodies[i].vel[1] = diskvels[i][0]*sin(disk[i][1])
                            + diskvels[i][1]*cos(disk[i][1]);
        bodies[i].vel[2] = diskvels[i][2];
    }
    
    
/******************************************************************************/
/*  Reporting Average Disk Speed                                              */
/******************************************************************************/
    
    v = 0.0;
    
    for (int i = 0; i < Ndisk; i++)
    {
        v += bodies[i].vel.norm();
    }
    
    v /= (double)Ndisk;
    
    std::cout << "Average Disk Particle Speed: " << v << "\n";
    std::cout << "Disk Size: " << diskcut << "\n";
    std::cout << "Disk Crossing Time: " << diskcut / v << "\n";
    
    
    writeinitfile(Ntot, Nhalo, bodies, "data/initfile.txt");
    
    
 
}
int main()
{
	// Set all ranges
	Range<double> X(Xfrom,Xto);
	Range<double> T(Yfrom,Yto);
	
	// Declare all TwoVarDFunctions
	TwoVarDFunction<double,double,double> Sigma(*sigma);
	TwoVarDFunction<double,double,double> Mu(*mu);
	TwoVarDFunction<double,double,double> Forcing(*forcing);
	TwoVarDFunction<double,double,double> B(*b);
	
	// Declare all AtomicDFunctions
	AtomicDFunction<double,double> Ic(*IC); // Change from Call<->Put
//	AtomicDFunction<double,double> Bcr(*BCR_Topper_p11);
	AtomicDFunction<double,double> Bcr(*BCR);// Change from Call<->Put
	AtomicDFunction<double,double> Bcl(*BCL);// Change from Call<->Put
	
	// Declare the pde
	ParabolicPDE<double,double,double> pde(X,T,Sigma,Mu,B,Forcing,Ic,Bcl,Bcr);

	// Declare the finite difference scheme
//	ParabolicFDM<double,double,double> FDM(pde,XINTERVALS,YINTERVALS,THETA); // V1
	int choice = 3;
	cout << "1) Explicit Euler 2) Implicit Euler 3) Crank Nicolson ";
	cin >> choice;

	//OptionType type = AmericanCallType;
	OptionType type = EuropeanCallType;

	ParabolicFDM<double,double,double> FDM(pde,XINTERVALS,YINTERVALS,choice,
											type);

	// compute option prices
	FDM.start();
	
	// Retrieve and store option prices
	Vector <double,long> result = FDM.line(); // Does include ENDS!!


///////////////////////////////////////////////////////////

	Vector<double, long> xArr = FDM.xarr();
	Vector<double, long> tArr = FDM.tarr();

	double h = xArr[2] - xArr[1];
	double k = tArr[2] - tArr[1];

	cout << "h " << h << endl;

	// Create and fill Delta vector
	Vector <double,long> DeltaMesh(xArr.Size()-2, xArr.MinIndex());
	for (long kk = DeltaMesh.MinIndex(); kk <= DeltaMesh.MaxIndex(); kk++)
	{
		DeltaMesh[kk] = xArr[kk+1];
	}

	Vector <double,long> Delta(result.Size()-2,result.MinIndex());
	for (long i = Delta.MinIndex(); i <= Delta.MaxIndex(); i++)
	{
		Delta[i] = (result[i+1] - result[i])/(h);
	}
	print(result);
	print(Delta);

	// Create and fill Gamma vector
	Vector <double,long> GammaMesh(DeltaMesh.Size()-2, DeltaMesh.MinIndex());
	for (long p = GammaMesh.MinIndex(); p <= GammaMesh.MaxIndex(); p++)
	{
		GammaMesh[p] = DeltaMesh[p+1];
	}

	Vector <double,long> Gamma(Delta.Size()-2, Delta.MinIndex());
	for (long n = Gamma.MinIndex(); n <= Gamma.MaxIndex(); n++)
	{
		Gamma[n] = (Delta[n+1] - Delta[n])/(h);
	}

	/*// Create and fill Theta vector
	Vector <double,long> ThetaMesh(tArr.Size()-1, tArr.MinIndex());
	for (long m = ThetaMesh.MinIndex(); m <= ThetaMesh.MaxIndex(); m++)
	{
		ThetaMesh[m] = tArr[m+1];
	}*/

	long NP1 = FDM.result().MaxRowIndex();
	long NP = FDM.result().MaxRowIndex() -1;

	Vector <double,long> Theta(result.Size(), result.MinIndex());
	for (long ii = Theta.MinIndex(); ii <= Theta.MaxIndex(); ii++)
	{
		Theta[ii] = -(FDM.result()(NP1, ii) -FDM.result()(NP, ii) )/k;
	}

	try
	{
		printOneExcel(FDM.xarr(), result, string("Price"));
		printOneExcel(DeltaMesh, Delta, string("Delta"));
		printOneExcel(GammaMesh, Gamma, string("Gamma"));
		printOneExcel(FDM.xarr(), Theta, string("Theta"));

	}
	catch(DatasimException& e)
	{
		e.print();

		ExcelDriver& excel = ExcelDriver::Instance();
		excel.MakeVisible(true);	

		long y = 1;
		excel.printStringInExcel(e.Message(), y, y, string("Err"));

		list<string> dump;
		dump.push_back(e.MessageDump()[0]);
		dump.push_back(e.MessageDump()[1]);
		dump.push_back(e.MessageDump()[2]);

		excel.printStringInExcel(dump, 1, 1, string("Err"));

		return 0;
	}

	return 0;
}
Exemple #27
0
int main(int argc, const char** argv){
  bool ReDoCuts=false;

  TCut TwelveCut = "gamma_CL>0.1&&BDT_response>0.36&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  TCut ElevenCut = "gamma_CL>0.1&&BDT_response>0.30&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  
  //______________________________MAKE CUT FILE FOR 2012___________________________________
  if(ReDoCuts){
    DataFile MCA(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MCB(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    TreeReader* MC12Reader=  new TreeReader("DecayTree");
    MC12Reader->AddFile(MCA);
    MC12Reader->AddFile(MCB);
    MC12Reader->Initialize();
    
    TFile* MC12Cut = new TFile("CutFile12.root","RECREATE");
    TTree* MC12CutTree=MC12Reader->CopyTree(TwelveCut,-1,"DecayTree");
    TRandom3 *MCRand = new TRandom3(224);
    TH1I * MCnCands12= new TH1I("MCnCands12","MCnCands12",10,0,10);
    TTree*MC12SingleTree=HandyFunctions::GetSingleTree(MCRand,MC12CutTree,MCnCands12,NULL);
    MCnCands12->Write();
    MC12SingleTree->Write();
    MC12Cut->Close();
    
    //________________________________MAKE CUT FILE FOR 2011__________________________________
    
    DataFile MC11A(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MC11B(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleB");
    
    TreeReader* MC11Reader= new TreeReader("DecayTree");
    MC11Reader->AddFile(MC11A);
    MC11Reader->AddFile(MC11B);
    MC11Reader->Initialize();
    
    TFile* MC11Cut = new TFile("CutFile11.root","RECREATE");
    TTree* MC11CutTree=MC11Reader->CopyTree(ElevenCut,-1,"DecayTree");

    TH1I * MCnCands11= new TH1I("MCnCands11","MCnCands11",10,0,10);
    TTree* MC11SingleTree=HandyFunctions::GetSingleTree(MCRand,MC11CutTree,MCnCands11,NULL);
    MCnCands11->Write();
    MC11SingleTree->Write();
    MC11Cut->Close();
  //_________________________________ MAKE FLAT TREES  ____________________________________
  
    TFile* MC12Input = new TFile("CutFile12.root");
    TTree* MC12InputTree=(TTree*)MC12Input->Get("DecayTree");
    Float_t MCEta_Mass12[20]; MC12InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass12);
    Int_t isSingle12; MC12InputTree->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MC12FlatOut = new TFile("MCMinimalFile12.root","RECREATE");
    TTree* MC12FlatTree = MC12InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF12; MC12FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=MC12InputTree->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      MC12InputTree->GetEntry(i);
      if(isSingle12==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF12=MCEta_Mass12[0];
      MC12FlatTree->Fill();
    }
    
    MC12FlatTree->Write();
    MC12FlatOut->Close();
    
    TFile* MC11Input = new TFile("CutFile11.root");
    TTree* MC11InputTree=(TTree*)MC11Input->Get("DecayTree");
    Float_t MCEta_Mass11[20]; MC11InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass11);
    Int_t isSingle11; MC11InputTree->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MC11FlatOut = new TFile("MCMinimalFile11.root","RECREATE");
    TTree* MC11FlatTree = MC11InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF11; MC11FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=MC11InputTree->GetEntries();
    
    for(int i=0;i<Entries11;++i){
      MC11InputTree->GetEntry(i);
      if(isSingle11==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF11=MCEta_Mass11[0];
      MC11FlatTree->Fill();
    }
    
    MC11FlatTree->Write();
    MC11FlatOut->Close();
  }
  
  //_____________________________________________LOAD ROODATASETS___________________________________

  TFile* MCFlatInput12= new TFile("MCMinimalFile12.root");
  TTree* MCFlatInputTree12=(TTree*)MCFlatInput12->Get("DecayTree");

  TFile* MCFlatInput11= new TFile("MCMinimalFile11.root");
  TTree* MCFlatInputTree11=(TTree*)MCFlatInput11->Get("DecayTree");

  RooRealVar MCBMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar MCEtaMass("eta_prime_MM","eta_prime_MM",700.0,1200.0);
  RooRealVar BDT_response("BDT_response","BDT_response",-1.0,1.0);
  RooRealVar gamma_CL("gamma_CL","gamma_CL",0.1,1.0);
  RooArgSet Args(MCBMass,MCEtaMass,BDT_response,gamma_CL);

  RooDataSet* MCData12 = new RooDataSet("MCData12","MCData12",Args,Import(*MCFlatInputTree12));
  
  std::cout <<" Data File 12 Loaded"<<std::endl;
  
  RooDataSet* MCData11 = new RooDataSet("MCData11","MCData11",Args,Import(*MCFlatInputTree11));

  std::cout<<" Data File 11 loaded"<<std::endl;

  RooDataSet* MCDataAll= new RooDataSet("MCDataAll","MCDataAll",Args);

  MCDataAll->append(*MCData12);
  MCDataAll->append(*MCData11);
  
  RooPlot* massFrame = MCBMass.frame(Title("Data Import Check"),Bins(50));
  MCDataAll->plotOn(massFrame);
  
  RooPlot *BDTFrame = BDT_response.frame(Title("BDT Cut Check"),Bins(50));
  MCDataAll->plotOn(BDTFrame);
  TCanvas C;
  C.Divide(2,1);
  C.cd(1);
  massFrame->Draw();
  C.cd(2);
  BDTFrame->Draw();
  C.SaveAs("ImportChecks.eps");

  //________________________________MAKE MCROODATACATEGORIES__________________________________

  RooDataSet* MCBData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCBMass));
  MCBData->Print("v");
  
  RooDataSet* MCEtaData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCEtaMass));
  MCEtaData->Print("v");

  RooCategory MCMassType("MCMassType","MCMassType") ;
  MCMassType.defineType("B") ;
  MCMassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet MCcombData("MCcombData","MC combined data",Args,Index(MCMassType),Import("B",*MCBData),Import("Eta",*MCEtaData));

  
  //=============================================== MC FIT MODEL===================================
  
  RooRealVar Mean("Mean","Mean",5279.29,5276.0,5284.00);
  RooRealVar Sigma("Sigma","Sigma",20.54,17.0,24.8);
  RooRealVar LAlpha("LAlpha","LAlpha",-1.064,-2.5,0.0);
  RooRealVar RAlpha("RAlpha","RAlpha",1.88,0.0,5.0);
  RooRealVar LN("LN","LN",13.0,0.0,40.0);
  RooRealVar RN("RN","RN",2.56,0.0,6.0);

  RooCBShape CBLeft("CBLeft","CBLeft",MCBMass,Mean,Sigma,LAlpha,LN);
  
  RooCBShape CBRight("CBRight","CBRight",MCBMass,Mean,Sigma,RAlpha,RN);

  RooRealVar FitFraction("FitFraction","FitFraction",0.5,0.0,1.0);
  RooAddPdf DCB("DCB","DCB",RooArgList(CBRight,CBLeft),FitFraction);

  RooRealVar SignalYield("SignalYield","SignalYield",4338.0,500.0,10000.0);
  //  RooExtendPdf ExtDCB("ExtDCB","ExtDCB",DCB,SignalYield);
  
  //==============================ETA DCB ++++++++++++++++++++++++++++++
  
  RooRealVar MCEtamean("MCEtamean","MCEtamean",958.0,955.0,960.0);
  RooRealVar MCEtasigma("MCEtasigma","MCEtasigma",9.16,8.0,14.0);
  RooRealVar EtaLAlpha("EtaLAlpha","EtaLAlpha",-1.45,-5.0,1.0);
  RooRealVar EtaRAlpha("EtaRAlpha","EtaRAlpha",1.76,0.0,4.0);
  RooRealVar EtaLN("EtaLN","EtaLN",0.1,0.0,20.0);
  RooRealVar EtaRN("EtaRN","EtaRN",0.1,0.0,20.0);

  RooCBShape EtaCBLeft("EtaCBLeft","EtaCBLeft",MCEtaMass,MCEtamean,MCEtasigma,EtaLAlpha,EtaLN);
  
  RooCBShape EtaCBRight("EtaCBRight","EtaCBRight",MCEtaMass,MCEtamean,MCEtasigma,EtaRAlpha,EtaRN);

  RooRealVar EtaFitFraction("EtaFitFraction","EtaFitFraction",0.22,0.1,1.0);
  RooAddPdf EtaDCB("EteaDCB","EtaDCB",RooArgList(EtaCBRight,EtaCBLeft),EtaFitFraction);

  RooProdPdf MCSignalPdf("MCSignalPdf","MCSignalPdf",RooArgSet(EtaDCB,DCB));
  
  RooExtendPdf ExtendedMCSignalPdf("ExtendedMCSignalPdf","ExtendedMCSignalPdf",MCSignalPdf,SignalYield);

  RooSimultaneous MCsimPdf("MCsimPdf","MC simultaneous pdf",MCMassType) ;
  //  MCsimPdf.addPdf(ExtDCB,"B");
  //  MCsimPdf.addPdf(ExtendedMCEtaDCB,"Eta"); 

  //============================== DO the MC FIT =======================================
  //MCsimPdf.fitTo(MCcombData,Extended(kTRUE),Minos(kTRUE));
  //ExtendedMCEtaDCB.fitTo(*MCEtaData,Extended(kTRUE),Minos(kTRUE));
  //ExtDCB.fitTo(*MCBData,Extended(
  ExtendedMCSignalPdf.fitTo(*MCDataAll,Extended(kTRUE),Minos(kTRUE));
  
  RooPlot* MCframe1 = MCBMass.frame(Range(5100.0,5500.0),Bins(50),Title("B mass projection"));
  MCDataAll->plotOn(MCframe1);
  ExtendedMCSignalPdf.plotOn(MCframe1);
  ExtendedMCSignalPdf.paramOn(MCframe1);
  
  RooPlot* MCframe2 = MCEtaMass.frame(Range(880.0,1020.0),Bins(50),Title("Eta mass projection")) ;
  MCDataAll->plotOn(MCframe2);
  ExtendedMCSignalPdf.plotOn(MCframe2);
  ExtendedMCSignalPdf.paramOn(MCframe2);
  
  TCanvas* MCc = new TCanvas("rf501_simultaneouspdf","rf403_simultaneouspdf",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; MCframe1->GetYaxis()->SetTitleOffset(1.4) ; MCframe1->Draw() ;
  MCc->SaveAs("MCSimulCanvas.pdf");

  TCanvas* MCcEta = new TCanvas(" Eta Canvas","Eta Canvas",1200,1000);
  gPad->SetLeftMargin(0.15) ; MCframe2->GetYaxis()->SetTitleOffset(1.4) ; MCframe2->Draw() ;
  MCcEta->SaveAs("MCEtaCanvas.pdf");

  TFile* MCFits= new TFile("MCFitResult.root","RECREATE");
  //  TCanvas* DecMCB=HandyFunctions::DecoratePlot(MCframe1);
  //  TCanvas* DecMCEta=HandyFunctions::DecoratePlot(MCframe2);
  //DecMCEta->Write();
  //  DecMCB->Write();
  MCc->Write();
  MCcEta->Write();

  std::cout<<"MC Eta Chi2 = "<<MCframe2->chiSquare()<<std::endl;
  std::cout<<"MC B Chi2 = "<<MCframe1->chiSquare()<<std::endl;

  //___________________________________ CUT DOWN COLLISION DATA ______________________________
  if(ReDoCuts){
    DataFile TwelveA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleA");

    DataFile TwelveB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    DataFile ElevenA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleA");

    DataFile ElevenB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleB");		

    TRandom3* DataRand= new TRandom3(224);
    TH1I* DataNCand12= new TH1I("DataNCand12","DataNCand12",10,0,10);
    TH1I* DataNCand11= new TH1I("DataNCand11","DataNCand11",10,0,10);
    
    TreeReader* UncutDataReader12= new TreeReader("DecayTree");
    UncutDataReader12->AddFile(TwelveA);
    UncutDataReader12->AddFile(TwelveB);
    UncutDataReader12->Initialize();
    
    TFile* CutDataFile12 = new TFile("CutDataFile12.root","RECREATE");
    TTree* CutDataTree12 = UncutDataReader12->CopyTree(TwelveCut,-1,"DecayTree");
    TTree* SingleCutDataTree12=HandyFunctions::GetSingleTree(DataRand,CutDataTree12,DataNCand12,NULL);
    SingleCutDataTree12->Write();
    CutDataFile12->Close();
    
    TreeReader* UncutDataReader11= new TreeReader("DecayTree");
    UncutDataReader11->AddFile(ElevenB);
    UncutDataReader11->AddFile(ElevenA);
    UncutDataReader11->Initialize();
    
    TFile* CutDataFile11 = new TFile("CutDataFile11.root","RECREATE");
    TTree* CutDataTree11 = UncutDataReader11->CopyTree(ElevenCut,-1,"DecayTree");
    TTree* SingleCutDataTree11=HandyFunctions::GetSingleTree(DataRand,CutDataTree11,DataNCand11,NULL);
    SingleCutDataTree11->Write();
    CutDataFile11->Close();
  

    TFile* DataInput12 = new TFile("CutDataFile12.root");
    TTree* DataInputTree12=(TTree*)DataInput12->Get("DecayTree");
    DataInputTree12->SetBranchStatus("*",0);
    DataInputTree12->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree12->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree12->SetBranchStatus("eta_prime_MM",1);
    DataInputTree12->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass12[20]; DataInputTree12->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass12);
    Int_t isSingle12; DataInputTree12->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MinimalDataFile12 = new TFile("MinimalDataFile12.root","RECREATE");
    TTree* MinimalDataTree12= DataInputTree12->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF12; MinimalDataTree12->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=DataInputTree12->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      DataInputTree12->GetEntry(i);
      if(isSingle12==0)continue;
      Bu_DTFNoFix_eta_prime_MF12=Eta_Mass12[0];
      MinimalDataTree12->Fill();
    }
    
    MinimalDataTree12->Write();
    MinimalDataFile12->Close();
    
    TFile* DataInput11 = new TFile("CutDataFile11.root");
    TTree* DataInputTree11=(TTree*)DataInput11->Get("DecayTree");
    DataInputTree11->SetBranchStatus("*",0);
    DataInputTree11->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree11->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree11->SetBranchStatus("eta_prime_MM",1);
    DataInputTree11->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass11[20]; DataInputTree11->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass11);
    Int_t isSingle11; DataInputTree11->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MinimalDataFile11 = new TFile("MinimalDataFile11.root","RECREATE");
    TTree* MinimalDataTree11= DataInputTree11->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF11; MinimalDataTree11->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=DataInputTree11->GetEntries();
    
    for(int i=0;i<Entries11;++i){
    DataInputTree11->GetEntry(i);
    if(isSingle11==0)continue;
    Bu_DTFNoFix_eta_prime_MF11=Eta_Mass11[0];
    MinimalDataTree11->Fill();
    }
    MinimalDataTree11->Write();
    MinimalDataFile11->Close();
  }

  //___________________________________ LOAD DATA TO ROODATASET____________________________________
  
  RooRealVar BMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar EtaMass("eta_prime_MM","eta_prime_MM",870.0,1050.0);
  RooArgSet MassArgs(BMass,EtaMass);

  TFile* Data12File = new TFile("MinimalDataFile12.root");
  TTree* DataTree12=(TTree*)Data12File->Get("DecayTree");

  RooDataSet* Data12 = new RooDataSet("Data12","Data12",MassArgs,Import(*DataTree12));

  TFile* Data11File = new TFile("MinimalDataFile11.root");
  TTree* DataTree11=(TTree*)Data11File->Get("DecayTree");

  RooDataSet* Data11 = new RooDataSet("Data11","Data11",MassArgs,Import(*DataTree11));
  
  RooDataSet* AllData = new RooDataSet("AllData","AllData",MassArgs);
  AllData->append(*Data12);
  AllData->append(*Data11);
  TCanvas ImportC;
  RooPlot* ImportCheck = BMass.frame(Title("ImportCheck"),Bins(50));
  AllData->plotOn(ImportCheck);
  ImportCheck->Draw();
  ImportC.SaveAs("Alldataimport.pdf");

  std::cout<<" Data Loaded, Total Entries = "<<AllData->numEntries()<<std::endl;

  AllData->Print("v");

  RooDataSet* BData=(RooDataSet*)AllData->reduce(RooArgSet(BMass));
  BData->Print("v");

  RooDataSet* EtaData=(RooDataSet*)AllData->reduce(RooArgSet(EtaMass));
  EtaData->Print("v");

  //___________________________________Fit to Eta_Prime in BMass Sidebands______________________

  RooDataSet* BSidebands=(RooDataSet*)AllData->reduce(Cut("(Bu_DTF_MF>5000.0&&Bu_DTF_MF<5179.0)||(Bu_DTF_MF>5379.0&&Bu_DTF_MF<5800.0)"));

  TCanvas BSidebandCanvas;
  RooPlot* BSidebandPlot = EtaMass.frame(Title("B sidebands"),Bins(30));
  BSidebands->plotOn(BSidebandPlot);
  BSidebandPlot->Draw();
  BSidebandCanvas.SaveAs("BSidebandDataCheck.pdf");

  
  RooRealVar BsbMean(" Mean","BsbMean",958.0,900.0,1020.0);
  RooRealVar BsbSigma(" Sigma","BsbSigma",19.8,10.0,40.8);
  RooRealVar BsbLAlpha(" Alpha","BsbLAlpha",-1.63,-10.0,0.0);
  //  RooRealVar BsbRAlpha("BsbRAlpha","BsbRAlpha",1.47,0.0,10.0);
  RooRealVar BsbLN(" N","BsbLN",0.1,0.0,20.0);
  //  RooRealVar BsbRN("BsbRN","BsbRN",0.1,0.0,20.0);

  RooCBShape BsbCBLeft("BsbCBLeft","BsbCBLeft",EtaMass,BsbMean,BsbSigma,BsbLAlpha,BsbLN);
  
  //  RooCBShape BsbCBRight("BsbCBRight","BsbCBRight",EtaMass,BsbMean,BsbSigma,BsbRAlpha,BsbRN);

  //  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.5,0.0,1.0);
  //  RooAddPdf BsbDCB("BsbDCB","BsbDCB",RooArgList(BsbCBRight,BsbCBLeft),BsbFitFraction);
  RooRealVar Bsbslope("Bsbslope","Bsbslope",0.5,0.0,1.0);
  RooRealVar BsbP2("BsbP2","BsbP2",-0.5,-1.0,0.0);
  RooChebychev BsbLinear("BsbLinear","BsbLinear",EtaMass,RooArgSet(Bsbslope,BsbP2));

  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.2,0.0,1.0);

  RooAddPdf BsbBackground("BsbBackground","BsbBackground",RooArgList(BsbLinear,BsbCBLeft),BsbFitFraction);
  
  RooRealVar BsbYield(" Yield","BsbYield",500.0,0.0,1000.0);
  RooExtendPdf BsbExtDCB("BsbExtDCB","BsbExtDCB",BsbCBLeft,BsbYield);

  BsbExtDCB.fitTo(*BSidebands,Extended(kTRUE),Minos(kTRUE));
  TCanvas BSBFitCanvas;
  RooPlot* BSBFitPlot = EtaMass.frame(Title("Eta fit in B Sidebands"),Bins(30));
  BSidebands->plotOn(BSBFitPlot);
  BsbExtDCB.plotOn(BSBFitPlot);
  BsbExtDCB.paramOn(BSBFitPlot);
  BSBFitPlot->Draw();
  BSBFitCanvas.SaveAs("BSidebandFit.pdf");
  TFile * SidebandFitFile= new TFile("SidebandFit.root","RECREATE");
  BSBFitCanvas.Write();
  SidebandFitFile->Close();
  
  //___________________________________DO THE 2D FIT TO DATA___________________________________


  const double PDGBMass= 5279.26;
  BMass.setRange("SignalWindow",PDGBMass-(3*Sigma.getVal()),PDGBMass+(3*Sigma.getVal()));
  RooRealVar DSignalYield("DSignalYield","DSignalYield",4000.0,0.0,10000.0);

  //================================= B MASS SIGNAL PDF==============================
  RooRealVar DMean("Mean","DMean",5279.29,5270.0,5290.00);
  RooRealVar DSigma("Sigma","DSigma",19.8,10.0,40.8);
  RooRealVar DLAlpha("DLAlpha","DLAlpha",LAlpha.getVal());
  RooRealVar DRAlpha("DRAlpha","DRAlpha",RAlpha.getVal());
  RooRealVar DLN("DLN","DLN",LN.getVal());
  RooRealVar DRN("DRN","DRN",RN.getVal());

  RooCBShape DCBLeft("DCBLeft","DCBLeft",BMass,DMean,DSigma,DLAlpha,DLN);
  
  RooCBShape DCBRight("DCBRight","DCBRight",BMass,DMean,DSigma,DRAlpha,DRN);

  RooRealVar DFitFraction("FitFraction","DFitFraction",0.5,0.0,1.0);
  RooAddPdf DDCB("DDCB","DDCB",RooArgList(DCBRight,DCBLeft),DFitFraction);
  
  //==============================B MASS BKG PDF==============================
  RooRealVar slope("slope","slope",-0.5,-1.0,0.0);
  RooChebychev bkg("bkg","Background",BMass,RooArgSet(slope));
  
  //==============================Eta mass signal pdf================================
  RooRealVar DEtamean("Etamean","DEtamean",958.0,945.0,980.0) ;
  RooRealVar DEtasigma("Etasigma","DEtasigma",15.0,5.0,65.0) ;
  RooRealVar DEtaLAlpha("DEtaLAlpha","DEtaLAlpha",EtaLAlpha.getVal());
  RooRealVar DEtaRAlpha("DEtaRAlpha","DEtaRAlpha",EtaRAlpha.getVal());
  RooRealVar DEtaLN("DEtaLN","DEtaLN",EtaLN.getVal());
  RooRealVar DEtaRN("DEtaRN","DEtaRN",EtaRN.getVal());
  
  RooCBShape EtaDCBLeft("EtaDCBLeft","EtaDCBLeft",EtaMass,DEtamean,DEtasigma,DEtaLAlpha,DEtaLN);
  
  RooCBShape EtaDCBRight("EtaDCBRight","EtaDCBRight",EtaMass,DEtamean,DEtasigma,DEtaRAlpha,DEtaRN);
  
  RooRealVar DEtaFitFraction("EtaFitFraction","DEtaFitFraction",0.5,0.0,1.0);
  RooAddPdf EtaDDCB("EtaDDCB","EtaDDCB",RooArgList(EtaDCBRight,EtaDCBLeft),DEtaFitFraction);

  RooProdPdf DSignalPdf("DSignalPdf","DSignalPdf",RooArgList(EtaDDCB,DDCB));
  
  RooExtendPdf DExtSignalPdf("DExtSignalPdf","DExtSignalPdf",DSignalPdf,DSignalYield);

  //=============================== Eta mass bkg pdf==================================
  
  RooRealVar EtaBkgMean("EtaBkgMean","EtaBkgMean",958.0,900.0,1020.0);
  RooRealVar EtaBkgSigma("EtaBkgSigma","EtaBkgSigma",19.8,10.0,40.8);
  RooRealVar EtaBkgLAlpha("EtaBkgLAlpha","EtaBkgLAlpha",BsbLAlpha.getVal());
  //  RooRealVar EtaBkgRAlpha("EtaBkgRAlpha","EtaBkgRAlpha",BsbRAlpha.getVal());
  RooRealVar EtaBkgLN("EtaBkgLN","EtaBkgLN",BsbLN.getVal());
  //  RooRealVar EtaBkgRN("EtaBkgRN","EtaBkgRN",BsbRN.getVal());

  RooCBShape EtaBkgCBLeft("EtaBkgCBLeft","EtaBkgCBLeft",EtaMass,DEtamean,EtaBkgSigma,EtaBkgLAlpha,EtaBkgLN);
  
  //  RooCBShape EtaBkgCBRight("EtaBkgCBRight","EtaBkgCBRight",EtaMass,DEtamean,EtaBkgSigma,EtaBkgRAlpha,EtaBkgRN);
  
  //  RooRealVar EtaBkgFitFraction("EtaBkgFitFraction","EtaBkgFitFraction",0.5,0.0,1.0);
  //  RooAddPdf EtaBkgDCB("EtaBkgDCB","EtaBkgDCB",RooArgList(EtaBkgCBRight,EtaBkgCBLeft),EtaBkgFitFraction);
  
  RooProdPdf DataBackgroundPDF("DataBackgroundPDF","DataBackgroundPDF",RooArgList(EtaBkgCBLeft,bkg));
  
  RooRealVar DataBackgroundYield("BackgroundYield","DataBackgroundYield",500.0,0.0,10000.0);
  
  RooExtendPdf ExtDataBackgroundPDF("ExtDataBackgroundPDF","ExtDataBackgroundPDF",DataBackgroundPDF,DataBackgroundYield);

  RooAddPdf TotalPDF("TotalPDF","TotalPDF",RooArgList(ExtDataBackgroundPDF,DExtSignalPdf));
  std::cout<<"Dependents = "<<std::endl;
  RooArgSet* Dependents=TotalPDF.getDependents(AllData);
  Dependents->Print("v");
  std::cout<<"parameters= "<<std::endl;
  RooArgSet* parameters=TotalPDF.getParameters(AllData);
  parameters->Print("v");
  RooCategory MassType("MassType","MassType") ;
  MassType.defineType("B") ;
  MassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet combData("combData","combined data",MassArgs,Index(MassType),Import("B",*BData),Import("Eta",*EtaData));

  RooSimultaneous simPdf("simPdf","simultaneous pdf",MassType) ;

  // Associate model with the physics state and model_ctl with the control state
  //  simPdf.addPdf(WholeFit,"B");
  //  simPdf.addPdf(WholeEtaFit,"Eta"); 

  //  simPdf.fitTo(combData,Extended(kTRUE)/*,Minos(kTRUE)*/);
  
  TotalPDF.fitTo(*AllData,Extended(kTRUE),Minos(kTRUE));

  RooPlot* frame1 = BMass.frame(Bins(50),Title("B mass projection"));
  AllData->plotOn(frame1);
  TotalPDF.plotOn(frame1,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame1);
  TotalPDF.paramOn(frame1);
  
  // The same plot for the control sample slice
  RooPlot* frame2 = EtaMass.frame(Bins(50),Title("Eta mass projection")) ;
  AllData->plotOn(frame2);
  TotalPDF.plotOn(frame2,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame2);
  TotalPDF.paramOn(frame2);
  TCanvas* DecoratedCanvas =HandyFunctions::DecoratePlot(frame2);

  
  TCanvas* DataBC= new TCanvas("BCanvas","BCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->Draw() ;
  TCanvas* EtaBC= new TCanvas("EtaCanvas","EtaCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->Draw() ;
  DataBC->SaveAs("DataBC.pdf");
  EtaBC->SaveAs("EtaBC.pdf");
  
  TFile * DataSimulFit = new TFile("DataSimulFit.root","RECREATE");
  DataBC->Write();
  EtaBC->Write();
  DecoratedCanvas->Write();

  
		 
		  

  
}
Exemple #28
0
RcppExport SEXP nniv(SEXP arg1, SEXP arg2, SEXP arg3) {
  // 3 arguments
  // arg1 for parameters
  // arg2 for data
  // arg3 for Gibbs

  // data
  List list2(arg2); 

  const MatrixXd X=as< Map<MatrixXd> >(list2["X"]),
    Z=as< Map<MatrixXd> >(list2["Z"]);

  const VectorXd t=as< Map<VectorXd> >(list2["t"]),
    y=as< Map<VectorXd> >(list2["y"]);

  const int N=X.rows(), p=X.cols(), q=Z.cols(), r=p+q, s=p+r;

  // parameters
  List list1(arg1), 
    beta_info=list1["beta"], 
    Tprec_info=list1["Tprec"], 
    mu_info=list1["mu"], 
    theta_info=list1["theta"];

  // prior parameters
  List beta_prior=beta_info["prior"],
    Tprec_prior=Tprec_info["prior"],
    mu_prior=mu_info["prior"],
    theta_prior=theta_info["prior"];

  const double Tprec_prior_nu=as<double>(Tprec_prior["nu"]);
  const Matrix2d Tprec_prior_Psi=as< Map<MatrixXd> >(Tprec_prior["Psi"]);

  const double beta_prior_mean=as<double>(beta_prior["mean"]);
  const double beta_prior_prec=as<double>(beta_prior["prec"]);

  const Vector2d mu_prior_mean=as< Map<VectorXd> >(mu_prior["mean"]);
  const Matrix2d mu_prior_prec=as< Map<MatrixXd> >(mu_prior["prec"]);

  const VectorXd theta_prior_mean=as< Map<VectorXd> >(theta_prior["mean"]);
  const MatrixXd theta_prior_prec=as< Map<MatrixXd> >(theta_prior["prec"]);

  // initialize parameters
  double beta=as<double>(beta_info["init"]); 

  Matrix2d Tprec=as< Map<MatrixXd> >(Tprec_info["init"]);
  Vector2d mu   =as< Map<VectorXd> >(mu_info["init"]);
  VectorXd theta=as< Map<VectorXd> >(theta_info["init"]);

  // Gibbs
  List list3(arg3); //, save=list3["save"];

  const int burnin=as<int>(list3["burnin"]), M=as<int>(list3["M"]), 
    thin=as<int>(list3["thin"]), m=7+s;

  MatrixXd GS(M, m);

  // prior parameter intermediate values
  double beta_prior_prod=beta_prior_prec * beta_prior_mean;

  VectorXd theta_prior_prod=theta_prior_prec * theta_prior_mean;

  Vector2d mu_prior_prod=mu_prior_prec*mu_prior_mean;

  // parameter intermediate values
  Matrix2d Sigma, B_inverse;

  Sigma=Tprec.inverse();
  B_inverse.setIdentity();

  VectorXd gamma=theta.segment(0, p), 
    delta=theta.segment(p, q), 
    eta  =theta.segment(r, p);

  /*
    MatrixXd Theta(2, r);

    Theta.row(0)=theta.segment(0, r);
    Theta.bottomLeftCorner(1, q)=RowVectorXd::Zero(q);
    Theta.bottomRightCorner(1, p)=eta.transpose();
  */

  Vector2d eps, eps_sum;

  MatrixXd D(N, 2), theta_cond_var_root(s, s), W(2, s);

  W.setZero();

  MatrixXd theta_cond_prec(s, s);

  VectorXd theta_cond_prod(s), w(r);

  Matrix2d mu_cond_prec, mu_cond_var_root, E;

  Vector2d u, R, mu_cond_prod, mu_u;

  double beta_scale, beta_prec, beta_prod, beta_cond_var, beta_cond_mean;

  int h=0, i, l; 


  // Gibbs loop
  //for(int l=-burnin; l<=(M-1)*thin; ++l) {

  l=-burnin;

  do{
    // sample beta
    D.col(0).setConstant(-mu[0]);
    D.col(1).setConstant(-mu[1]);

    D.col(0) += (t - X*gamma - Z*delta);
    D.col(1) += (y - X*eta);

    beta_scale=1./(Sigma(0, 0)*t.dot(t));

    beta_prec=1./(beta_scale*Sigma.determinant());

    beta_prod=beta_prec*beta_scale
      *((Sigma(0, 0)*D.col(1)-Sigma(0, 1)*D.col(0)).array()*t.array()).sum();

    beta_cond_var=1./(beta_prec+beta_prior_prec);

    beta_cond_mean=beta_cond_var*(beta_prod+beta_prior_prod);

    beta=rnorm1d(beta_cond_mean, sqrt(beta_cond_var));

    B_inverse(1, 0)=-beta;

    // sample theta
    theta_cond_prec=theta_prior_prec;
    theta_cond_prod=theta_prior_prod;

    for(i=0; i<N; ++i) {
      /*
	W.topLeftCorner(1, p)=X.row(i);
	W.block(0, p, 1, q)=Z.row(i);
	W.bottomRightCorner(1, p)=X.row(i);
      */

      W.block(0, 0, 1, p)=X.row(i);
      W.block(0, p, 1, q)=Z.row(i);
      W.block(1, r, 1, p)=X.row(i);

      theta_cond_prec += (W.transpose() * Tprec * W);

      u[0]=t[i];
      u[1]=y[i];

      R=B_inverse*u-mu;

      theta_cond_prod += (W.transpose() * Tprec * R);
    }

    theta_cond_var_root=inv_root_chol(theta_cond_prec);
    // theta_cond_var_root=inv_root_svd(theta_cond_prec); // for validation only

    theta=theta_cond_var_root*(rnormXd(s)+theta_cond_var_root.transpose()*theta_cond_prod);

    gamma=theta.segment(0, p); 
    delta=theta.segment(p, q); 
    eta  =theta.segment(r, p);

    /*
      Theta.topRows(1)=theta.segment(0, r).transpose();
      Theta.bottomRightCorner(1, p)=eta.transpose();
    */

    // sample mu
    eps_sum.setZero();
    //W.setZero();

    E.setZero();

    for(i=0; i<N; ++i) {
      /*
	W.topLeftCorner(1, p)=X.row(i);
	W.block(0, p, 1, q)=Z.row(i);
	W.bottomRightCorner(1, p)=X.row(i);
      */

      W.block(0, 0, 1, p)=X.row(i);
      W.block(0, p, 1, q)=Z.row(i);
      W.block(1, r, 1, p)=X.row(i);

      /*
	w.segment(0, q)=Z.row(i);
	w.segment(q, p)=X.row(i);
      */

      u[0]=t[i];
      u[1]=y[i];

      //eps += B_inverse*u - Theta*w;
      eps = B_inverse*u - W*theta;
      eps_sum += eps;
      eps -= mu;
      E += eps*eps.transpose();
    }

    mu_cond_prod=Tprec*eps_sum+mu_prior_prod;

    mu_cond_prec=(N*Tprec+mu_prior_prec);

    mu_cond_var_root=inv_root_chol(mu_cond_prec);
    // mu_cond_var_root=inv_root_svd(mu_cond_prec); // for validation only

    mu=mu_cond_var_root*(rnormXd(2)+mu_cond_var_root.transpose()*mu_cond_prod);

    // sample Tprec
    Tprec = rwishart((E+Tprec_prior_Psi).inverse(), N+Tprec_prior_nu);
    Sigma = Tprec.inverse();

    if(l>=0 && l%thin == 0) {
      h = (l/thin);

      GS.block(h, 0, 1, s)=theta.transpose();

      GS(h, s)=beta;
      GS(h, s+1)=mu[0];
      GS(h, s+2)=mu[1];
      GS(h, s+3)=Tprec(0, 0);
      GS(h, s+4)=Tprec(0, 1);
      GS(h, s+5)=Tprec(0, 1);
      GS(h, s+6)=Tprec(1, 1);
    }

    l++;

  } while (l<=(M-1)*thin && beta==beta); 

  if(beta != beta) GS.conservativeResize(h+1, m);

  return wrap(GS);
}
Exemple #29
0
 MvRegData * MVTR::simdat(const Vec &x)const{
   Vec Y = rmvt(predict(x), Sigma(), nu());
   return new MvRegData(Y,x);
 }
Exemple #30
0
 Ptr<MvtIndepProposal> TIM::create_proposal(int dim, double nu){
   Vector mu(dim);
   SpdMatrix Sigma(dim);
   Sigma.set_diag(1.0);
   return new MvtIndepProposal(mu, Sigma, nu, rng());
 }