Beispiel #1
0
// [[Rcpp::export]]
arma::vec gradcpp(SEXP eta,
                   SEXP beta,
                   SEXP doc_ct,
                   SEXP mu,
                   SEXP siginv){
   
   Rcpp::NumericVector etav(eta); 
   arma::vec etas(etav.begin(), etav.size(), false);
   Rcpp::NumericMatrix betam(beta);
   arma::mat betas(betam.begin(), betam.nrow(), betam.ncol());
   Rcpp::NumericVector doc_ctv(doc_ct);
   arma::vec doc_cts(doc_ctv.begin(), doc_ctv.size(), false);
   Rcpp::NumericVector muv(mu);
   arma::vec mus(muv.begin(), muv.size(), false);
   Rcpp::NumericMatrix siginvm(siginv);
   arma::mat siginvs(siginvm.begin(), siginvm.nrow(), siginvm.ncol(), false);
   
    arma::colvec expeta(etas.size()+1); 
    expeta.fill(1);
    int neta = etas.size(); 
    for(int j=0; j <neta;  j++){
       expeta(j) = exp(etas(j));
    }
    betas.each_col() %= expeta;
    arma::vec part1 = betas*(doc_cts/arma::trans(sum(betas,0))) - (sum(doc_cts)/sum(expeta))*expeta;
    arma::vec part2 = siginvs*(etas - mus);
    part1.shed_row(neta);
    return part2-part1;
}
Beispiel #2
0
// [[Rcpp::export]]
double lhoodcpp(SEXP eta,
                   SEXP beta,
                   SEXP doc_ct,
                   SEXP mu,
                   SEXP siginv){
   
   Rcpp::NumericVector etav(eta); 
   arma::vec etas(etav.begin(), etav.size(), false);
   Rcpp::NumericMatrix betam(beta);
   arma::mat betas(betam.begin(), betam.nrow(), betam.ncol(), false);
   Rcpp::NumericVector doc_ctv(doc_ct);
   arma::vec doc_cts(doc_ctv.begin(), doc_ctv.size(), false);
   Rcpp::NumericVector muv(mu);
   arma::vec mus(muv.begin(), muv.size(), false);
   Rcpp::NumericMatrix siginvm(siginv);
   arma::mat siginvs(siginvm.begin(), siginvm.nrow(), siginvm.ncol(), false);
   
   arma::rowvec expeta(etas.size()+1); 
   expeta.fill(1);
   int neta = etav.size(); 
   for(int j=0; j <neta;  j++){
     expeta(j) = exp(etas(j));
   }
   double ndoc = sum(doc_cts);
   double part1 = arma::as_scalar(log(expeta*betas)*doc_cts - ndoc*log(sum(expeta)));
   arma::vec diff = etas - mus;
   double part2 = .5*arma::as_scalar(diff.t()*siginvs*diff);
   double out = part2 - part1;
   return out;
}
Beispiel #3
0
void MaintainerMain::on_music_converter_batch_clicked()
{
    AudioCvt_Sox_gui mus(NULL);
    mus.setWindowFlags( Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint );
    mus.setWindowModality(Qt::NonModal);
    this->hide();
    mus.exec();
    this->show();
}
Beispiel #4
0
/**
 * Constructs a global optimization problem (box-bounded, continuous) representing an interplanetary trajectory modelled
 * as a Multiple Gravity Assist trajectory that allows one only Deep Space Manouvre between each leg.
 *  
 * @param[in] seq std::vector of kep_toolbox::planet_ptr containing the encounter sequence for the trajectoty (including the initial planet)
 * @param[in] t0_l kep_toolbox::epoch representing the lower bound for the launch epoch
 * @param[in] t0_u kep_toolbox::epoch representing the upper bound for the launch epoch
 * @param[in] tof time-of-flight vector containing lower and upper bounds (in days) for the various legs time of flights
 * @param[in] Tmax maximum time of flight
 * @param[in] Dmin minimum distance from Jupiter (for radiation protection)
 *
 * @throws value_error if the planets in seq do not all have the same central body gravitational constant
 * @throws value_error if tof has a size different from seq.size()
 */
mga_incipit_cstrs::mga_incipit_cstrs(
			 const std::vector<kep_toolbox::planets::planet_ptr> seq,
			 const kep_toolbox::epoch t0_l,
			 const kep_toolbox::epoch t0_u,
			 const std::vector<std::vector<double> > tof,
			 double Tmax,
			 double Dmin) : base(4*seq.size(),0,1,2,2,1E-3), m_tof(tof), m_tmax(Tmax), m_dmin(Dmin)
{
	// We check that all planets have equal central body
	std::vector<double> mus(seq.size());
	for (std::vector<kep_toolbox::planets::planet_ptr>::size_type i = 0; i< seq.size(); ++i) {
		mus[i] = seq[i]->get_mu_central_body();
	}
	if ((unsigned int)std::count(mus.begin(), mus.end(), mus[0]) != mus.size()) {
		pagmo_throw(value_error,"The planets do not all have the same mu_central_body");  
	}
	// We check the consistency of the time of flights
	if (tof.size() != seq.size()) {
		pagmo_throw(value_error,"The time-of-flight vector (tof) has the wrong length");  
	}
	for (size_t i = 0; i < tof.size(); ++i) {
		if (tof[i].size()!=2) pagmo_throw(value_error,"Each element of the time-of-flight vector (tof)  needs to have dimension 2 (lower and upper bound)"); 
	}
	
	// Filling in the planetary sequence data member. This requires to construct the polymorphic planets via their clone method 
	for (std::vector<kep_toolbox::planets::planet_ptr>::size_type i = 0; i < seq.size(); ++i) {
		m_seq.push_back(seq[i]->clone());
	}
	
	// Now setting the problem bounds
	size_type dim(4*m_tof.size());
	decision_vector lb(dim), ub(dim);
	
	// First leg
	lb[0] = t0_l.mjd2000(); ub[0] = t0_u.mjd2000();
	lb[1] = 0; lb[2] = 0; ub[1] = 1; ub[2] = 1;
	lb[3] = m_tof[0][0]; ub[3] = m_tof[0][1];
	
	// Successive legs
	for (std::vector<kep_toolbox::planets::planet_ptr>::size_type i = 1; i < m_tof.size(); ++i) {
		lb[4*i] = - 2 * boost::math::constants::pi<double>();    ub[4*i] = 2 * boost::math::constants::pi<double>();
		lb[4*i+1] = 1.1;  ub[4*i+1] = 30;
		lb[4*i+2] = 1e-5; ub[4*i+2] = 1-1e-5;
		lb[4*i+3] = m_tof[i][0]; ub[4*i+3] = m_tof[i][1];
	}
	
	// Adjusting the minimum and maximum allowed fly-by rp to the one defined in the kep_toolbox::planet class
	for (std::vector<kep_toolbox::planets::planet_ptr>::size_type i = 0; i < m_tof.size()-1; ++i) {
		lb[4*i+5] = m_seq[i]->get_safe_radius() / m_seq[i]->get_radius();
		ub[4*i+5] = (m_seq[i]->get_radius() + 2000000) / m_seq[i]->get_radius(); //from gtoc6 problem description
	}
	set_bounds(lb,ub);
}
Beispiel #5
0
int game(void* data)
{
    //StringData loading...
    StringData myText("Common");

    //Create a SDL screen.
    const int SCREEN_WIDTH = 640;
    const int SCREEN_HEIGHT = 480;
    const Uint32 SCREEN_FLAGS = 0; //SDL_FULLSCREEN | SDL_DOUBLEBUF | SDL_HWSURFACE
    const std::string WINDOW_NAME = "The Keys To Your Heart";
    ScreenSurface screen(SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_NAME, 0, SCREEN_FLAGS);

    //bg loading
    PictureSurface bg("./images/h3_bg.png", screen);

    //music loading
    MusicSound mus("./sounds/bgMusic.mid");
    mus.play();

    //UVi Logo
    UVi_begin(screen);

    //main loop
    bool gameOver = false;
    while ( gameOver == false ) {
        //Title loop
        gameOver = title_loop_quit(screen);

        //pages show and get result
        std::vector<char> result;
        if ( gameOver != true ) {
            gameOver = get_result_quit(result, bg, screen);
        }

        //show result;
        if ( gameOver != true ) {
            gameOver = show_result_quit(result, screen);
        }
    }

    //end show
    end_show(screen);

    //end music
    mus.stop();

    return 0;
}
Beispiel #6
0
// [[Rcpp::export]]
SEXP hpbcpp(SEXP eta,
            SEXP beta,
            SEXP doc_ct,
            SEXP mu,
            SEXP siginv,
            SEXP sigmaentropy){
 
   Rcpp::NumericVector etav(eta); 
   arma::vec etas(etav.begin(), etav.size(), false);
   Rcpp::NumericMatrix betam(beta);
   arma::mat betas(betam.begin(), betam.nrow(), betam.ncol());
   Rcpp::NumericVector doc_ctv(doc_ct);
   arma::vec doc_cts(doc_ctv.begin(), doc_ctv.size(), false);
   Rcpp::NumericVector muv(mu);
   arma::vec mus(muv.begin(), muv.size(), false);
   Rcpp::NumericMatrix siginvm(siginv);
   arma::mat siginvs(siginvm.begin(), siginvm.nrow(), siginvm.ncol(), false);
   Rcpp::NumericVector sigmaentropym(sigmaentropy);
   arma::vec entropy(sigmaentropym);

   //Performance Nots from 3/6/2015
   //  I tried a few different variants and benchmarked this one as roughly twice as
   //  fast as the R code for a K=100 problem.  Key to performance was not creating
   //  too many objects and being selective in how things were flagged as triangular.
   //  Some additional notes in the code below.
   //
   //  Some things this doesn't have or I haven't tried
   //  - I didn't tweak the arguments much.  sigmaentropy is a double, and I'm still
   //    passing beta in the same way.  I tried doing a ", false" for beta but it didn't
   //    change much so I left it the same as in gradient.  
   //  - I tried treating the factors for doc_cts and colSums(EB) as a diagonal matrix- much slower.
   
   //  Haven't Tried/Done
   //  - each_row() might be much slower (not sure but arma is column order).  Maybe transpose in place?
   //  - depending on costs there are some really minor calculations that could be precomputed: 
   //     - sum(doc_ct)
   //     - sqrt(doc_ct)
   
   //  More on passing by reference here:
   //  - Hypothetically we could alter beta (because hessian is last thing we do) however down
   //    the road we may want to explore treating nonPD hessians by optimization at which point
   //    we would need it again.
   
   arma::colvec expeta(etas.size()+1); 
   expeta.fill(1);
   int neta = etas.size(); 
   for(int j=0; j <neta;  j++){
     expeta(j) = exp(etas(j));
   }
   arma::vec theta = expeta/sum(expeta);

   //create a new version of the matrix so we can mess with it
   arma::mat EB(betam.begin(), betam.nrow(), betam.ncol());
   //multiply each column by expeta
   EB.each_col() %= expeta; //this should be fastest as its column-major ordering
  
   //divide out by the column sums
   EB.each_row() %= arma::trans(sqrt(doc_cts))/sum(EB,0);
    
   //Combine the pieces of the Hessian which are matrices
   arma::mat hess = EB*EB.t() - sum(doc_cts)*(theta*theta.t());
  
   //we don't need EB any more so we turn it into phi
   EB.each_row() %= arma::trans(sqrt(doc_cts));
   
   //Now alter just the diagonal of the Hessian
   hess.diag() -= sum(EB,1) - sum(doc_cts)*theta;
   //Drop the last row and column
   hess.shed_row(neta);
   hess.shed_col(neta);
   //Now we can add in siginv
   hess = hess + siginvs;
   //At this point the Hessian is complete.
   
   //This next bit of code is from http://arma.sourceforge.net/docs.html#logging
   //It basically keeps arma from printing errors from chol to the console.
   std::ostream nullstream(0);
   arma::set_stream_err2(nullstream);
   
   ////
   //Invert via cholesky decomposition
   ////
   //Start by initializing an object
   arma::mat nu = arma::mat(hess.n_rows, hess.n_rows);
   //This version of chol generates a boolean which tells us if it failed.
   bool worked = arma::chol(nu,hess);
   if(!worked) {
     //It failed!  Oh Nos.
     // So the matrix wasn't positive definite.  In practice this means that it hasn't
     // converged probably along some minor aspect of the dimension.
     
     //Here we make it positive definite through diagonal dominance
     arma::vec dvec = hess.diag();
     //find the magnitude of the diagonal 
     arma::vec magnitudes = sum(abs(hess), 1) - abs(dvec);
     //iterate over each row and set the minimum value of the diagonal to be the magnitude of the other terms
     int Km1 = dvec.size();
     for(int j=0; j < Km1;  j++){
       if(arma::as_scalar(dvec(j)) < arma::as_scalar(magnitudes(j))) dvec(j) = magnitudes(j); //enforce diagonal dominance 
     }
     //overwrite the diagonal of the hessian with our new object
     hess.diag() = dvec;
     //that was sufficient to ensure positive definiteness so we now do cholesky
     nu = arma::chol(hess);
   }
   //compute 1/2 the determinant from the cholesky decomposition
   double detTerm = -sum(log(nu.diag()));
   
   //Now finish constructing nu
   nu = arma::inv(arma::trimatu(nu));
   nu = nu * nu.t(); //trimatu doesn't do anything for multiplication so it would just be timesink to signal here.
   
   //Precompute the difference since we use it twice
   arma::vec diff = etas - mus;
   //Now generate the bound and make it a scalar
   double bound = arma::as_scalar(log(arma::trans(theta)*betas)*doc_cts + detTerm - .5*diff.t()*siginvs*diff - entropy); 
   
   // Generate a return list that mimics the R output
   return Rcpp::List::create(
        Rcpp::Named("phis") = EB,
        Rcpp::Named("eta") = Rcpp::List::create(Rcpp::Named("lambda")=etas, Rcpp::Named("nu")=nu),
        Rcpp::Named("bound") = bound
        );
}
Beispiel #7
0
void LvlMusPlay::setMusic(LvlMusPlay::MusicType mt, unsigned long id, QString cmus)
{
    QString root = ".";
    MainWindow  *mw = MainWinConnect::pMainWin;
    if(!mw) return;

    if(id==0)
    {
        setNoMusic();
        return;
    }

    if(mw->activeChildWindow()==1)
    {
        if(mw->activeLvlEditWin() != nullptr)
            root = mw->activeLvlEditWin()->LvlData.meta.path+"/";
    }
    else
    if(mw->activeChildWindow()==3)
    {
        if(mw->activeWldEditWin() != nullptr)
            root = mw->activeWldEditWin()->WldData.meta.path+"/";
    }

    //Force correction of Windows paths into UNIX style
    cmus.replace('\\', '/');

    switch(mt)
    {
        case LevelMusic:
            if(id==mw->configs.music_custom_id)
            {
                LogDebug(QString("get Custom music path"));
                currentMusicPath = root + cmus;
            }
            else
            {
                LogDebug(QString("get standart music path (level)"));
                QString musicFile;
                long j = mw->configs.getMusLvlI(id);
                if(j>=0)
                {
                    if(id==mw->configs.main_music_lvl[j].id)
                    {
                        musicFile = mw->configs.main_music_lvl[j].file;
                    }
                }
                currentMusicPath = mw->configs.dirs.music + musicFile;
            }
            break;
        case WorldMusic:
            if(id==mw->configs.music_w_custom_id)
            {
                LogDebug(QString("get Custom music path"));
                currentMusicPath = root + cmus;
            }
            else
            {
                LogDebug(QString("get standart music path (world)"));
                QString musicFile;
                long j = mw->configs.getMusWldI(id);
                if(j>=0)
                {
                    if(id==mw->configs.main_music_wld[j].id)
                    {
                        musicFile = mw->configs.main_music_wld[j].file;
                    }
                }
                currentMusicPath = mw->configs.dirs.music + musicFile;
            }
            break;
        case SpecialMusic:
            {
                LogDebug(QString("get standart music path (special)"));
                QString musicFile;
                long j = mw->configs.getMusSpcI(id);
                if(j>=0)
                {
                    if(id==mw->configs.main_music_spc[j].id)
                    {
                        musicFile = mw->configs.main_music_spc[j].file;
                    }
                }
                currentMusicPath = mw->configs.dirs.music + musicFile;
            }
            break;
    }

    LogDebug(QString("path is %1").arg(currentMusicPath));

    QString trackNum;
    if(currentMusicPath.contains('|'))
    {
        QStringList x=currentMusicPath.split("|");
        currentMusicPath=x[0];
        trackNum=x[1];
    }
    QFileInfo mus(currentMusicPath);
    if((!mus.exists())||(!mus.isFile()))
    {
        currentMusicPath.clear();
    }
    else
    {
        if(!trackNum.isEmpty())
        {
            currentMusicPath=currentMusicPath+"|"+trackNum;
        }
    }
}
Beispiel #8
0
  void pelt(Dataloader &dload, const CageParams& params) {

    // Copy parameters for convenience
    int start = params.dataloader_params.start;
    int end = params.dataloader_params.end;
    int step = params.dataloader_params.step;
    double beta = params.beta;
    double K = 0;
    bool verbose = params.dataloader_params.verbose;
    string output_file = params.output_file;

    // Allocate vector for storing subproblem results
    vector<double> f((end - start) / step + 1, 0);

    f[0] = -1.0 * beta;

    // Store last prior changepoint positions for subproblems
    vector<int> cps((end - start) / step + 1, 0);
    cps[0] = start;

    vector<int> R(1);
    R[0] = start;

    int i;
    if (verbose) 
      cout << "Progress:\n";

    /*
       Note on indexing:
       i is in genome coordinates
       R stores numbers as genome coordinates
       */

    int maxcosts = 0;
    int maxlength = 0;
    long long int total_length = 0;

    // Spawn the data loading thread
    thread t(&Dataloader::loadfunc, &dload);

    // Loop through the data
    for (i = start; i < end + 1; i+= step) {

      if (beta == 0) {
        R[0] = i;
        continue;
      }

      maxcosts = (int)R.size() > maxcosts ? R.size() : maxcosts;
      int length_now = (i - *min_element(R.begin(), R.end()));
      maxlength = length_now > maxlength ? length_now : maxlength;

      if (verbose) {
        if ((i - start) % 100000 == 0) {
          printf("Position: %i\tMax Costs: %i\tMax Length: %i\tTotal length: %lld\n", i, maxcosts, maxlength, total_length);
          maxcosts = 0;
          maxlength = 0;
          total_length = 0;
        }
      }

      // Deal with the centromere - area of no coverage
      if ((i > start) & (i < end - 1)) {	
        if (dload.get_region(i, min(i + step, end)).empty_region()) {
          f[(i - start) / step] = f[(i - step - start) / step];
          cps[(i - start) / step] = cps[(i - step - start) / step];
          continue;
        }
      }

      vector<float> costs(R.size());
      vector<float> Fs(R.size());

      for (int j = 0; j < (int)R.size(); j++) {
        costs[j] = cost(dload.get_region(R[j], i));

        total_length += i - R[j];
        Fs[j] = f[(R[j]-start) / step];
      }

      vector<float> vals(costs.size());

      for (int j = 0; j < (int)vals.size(); j++)
        vals[j] = costs[j] + Fs[j];

      auto min_ptr = min_element(vals.begin(), vals.end());
      int idx = distance(vals.begin(), min_ptr);
      f[(i - start) / step] = *min_ptr + beta;
      cps[(i - start) / step] = R[idx];

      vector<int> R_new(0);
      for (int j = 0; j < (int)vals.size(); j++) {
        if (vals[j] + K <= f[(i - start) / step]) {
          R_new.push_back(R[j]);
        }
      }

      R_new.push_back(i);
      R = move(R_new);
    }

    i -= step;	

    vector<int> cps_n;

    if (beta != 0) {

      int pos;
      cps_n.push_back(end);
      cps_n.push_back(i);

      pos = cps[(i - start) / step];

      while (pos != start) {
        cps_n.push_back(pos);
        pos = cps[(pos - start) / step];
      }

      cps_n.push_back(start); 
      reverse(cps_n.begin(), cps_n.end());

      // Take the unique elements
      auto it = unique(cps_n.begin(), cps_n.end());
      cps_n.resize(distance(cps_n.begin(), it));

    } else {
      printf("Calling changepoints every %i bases\n", step);
      for (int k = start; k < (int)end; k += step) {
        cps_n.push_back(k);
      }
      cps_n.push_back(end);
    }

    cout << "Num of changepoints: " << cps_n.size() << endl;
    // Get the parameter values
    vector<double> lambdas(cps_n.size()-1);
    vector<double> eps(cps_n.size()-1);
    vector<double> gammas(cps_n.size()-1);
    vector<double> iotas(cps_n.size()-1);
    vector<double> zetas(cps_n.size()-1);
    vector<double> mus(cps_n.size()-1);
    vector<double> sigmas(cps_n.size()-1);
    vector<int> lengths(cps_n.size()-1);

    int row = 0;

    for (auto i = cps_n.begin(); i != cps_n.end() - 1; ++i) {
      int left = *i;
      int right = *(i+1);

      SuffStats tot_stats = dload.get_region(left, right);
      lambdas[row] = (double)tot_stats.N / tot_stats.L;
      eps[row] = (tot_stats.tot_bases == 0) ? 0 : (double)tot_stats.tot_errors / tot_stats.tot_bases;
      gammas[row] = (double)tot_stats.N_SNPs / tot_stats.L;
      iotas[row] = (tot_stats.tot_bases == 0) ? 0 : (double)tot_stats.indels / tot_stats.tot_bases;
      zetas[row] = (tot_stats.N == 0) ? 0 : (double)tot_stats.zero_mapq / tot_stats.N;
      mus[row] = (tot_stats.n_inserts == 0) ? 0 : (double)tot_stats.inserts_sum / tot_stats.n_inserts;
      sigmas[row] = (tot_stats.n_inserts > 0) ? 0 : sqrt((tot_stats.inserts_sumsq - pow((long long)tot_stats.inserts_sum,2)) / (tot_stats.n_inserts - 1));

      lengths[row] = right - left;
      row++;
    }

    if(t.joinable())
    {
      t.join();
    }

    FILE *f_out;
    if (strcmp(output_file.c_str(), "") != 0) { 
      f_out = fopen(output_file.c_str(), "w");
      if (f_out == nullptr) {
        throw runtime_error("Could not open file " + output_file); 
      }
      for (row = 0; row < (int)cps_n.size() - 2; row++) {
        if ((lengths[row] != 0)) { 
          fprintf(f_out, "%i\t%i\t%0.8f\t%0.8f\t%0.8f\t%0.8f\t%0.8f\n", cps_n[row], 
              lengths[row], lambdas[row], eps[row], gammas[row], iotas[row], zetas[row]);
        }
      }
      fclose(f_out); 
    }
  }