Ejemplo n.º 1
0
void
TempoTrackV2::calculateBeatPeriod(const vector<double> &df,
                                  vector<double> &beat_period,
                                  vector<double> &tempi)
{
    // to follow matlab.. split into 512 sample frames with a 128 hop size
    // calculate the acf,
    // then the rcf.. and then stick the rcfs as columns of a matrix
    // then call viterbi decoding with weight vector and transition matrix
    // and get best path

    unsigned int wv_len = 128;
    double rayparam = 43.;

    // make rayleigh weighting curve
    d_vec_t wv(wv_len);
    for (unsigned int i=0; i<wv.size(); i++)
    {
        wv[i] = (static_cast<double> (i) / pow(rayparam,2.)) * exp((-1.*pow(-static_cast<double> (i),2.)) / (2.*pow(rayparam,2.)));
    }

    // beat tracking frame size (roughly 6 seconds) and hop (1.5 seconds)
    unsigned int winlen = 512;
    unsigned int step = 128;

    // matrix to store output of comb filter bank, increment column of matrix at each frame
    d_mat_t rcfmat;
    int col_counter = -1;

    // main loop for beat period calculation
    for (unsigned int i=0; i+winlen<df.size(); i+=step)
    {
        // get dfframe
        d_vec_t dfframe(winlen);
        for (unsigned int k=0; k<winlen; k++)
        {
            dfframe[k] = df[i+k];
        }
        // get rcf vector for current frame
        d_vec_t rcf(wv_len);
        get_rcf(dfframe,wv,rcf);

        rcfmat.push_back( d_vec_t() ); // adds a new column
        col_counter++;
        for (unsigned int j=0; j<rcf.size(); j++)
        {
            rcfmat[col_counter].push_back( rcf[j] );
        }
    }

    // now call viterbi decoding function
    viterbi_decode(rcfmat,wv,beat_period,tempi);
}
Ejemplo n.º 2
0
// Open Media file and return elapsed time in millseconds
int Waveform::OpenfileMedia(AudioManager* media, wxString& error)
{
	_media = media;
    views.clear();
	if (_media != NULL)
	{
		float samplesPerLine = GetSamplesPerLineFromZoomLevel(mZoomLevel);
		WaveView wv(mZoomLevel, samplesPerLine, media);
		views.push_back(wv);
		mCurrentWaveView = 0;
		return media->LengthMS();
	}
	else
	{
		return 0;
	}
}
Ejemplo n.º 3
0
void Waveform::SetZoomLevel(int level)
{
    mZoomLevel = level;

    if(!mIsInitialized){return;}

    mCurrentWaveView = NO_WAVE_VIEW_SELECTED;
    for(int i=0;i<views.size();i++)
    {
        if(views[i].GetZoomLevel() == mZoomLevel)
        {
            mCurrentWaveView = i;
        }
    }
    if (mCurrentWaveView == NO_WAVE_VIEW_SELECTED)
    {
        float samplesPerLine = GetSamplesPerLineFromZoomLevel(mZoomLevel);
        WaveView wv(mZoomLevel,samplesPerLine,m_left_data,mMediaTrackSize);
        views.push_back(wv);
        mCurrentWaveView = views.size()-1;
    }
}
Ejemplo n.º 4
0
// Open Media file and return elapsed time in millseconds
int Waveform::OpenfileMediaFile(const wxString &filename, wxString& error)
{
    mpg123_handle *mh = NULL;
    int err;
    size_t buffer_size;
    int channels, encoding;
    long rate;

    err = mpg123_init();
    if(err != MPG123_OK || (mh = mpg123_new(NULL, &err)) == NULL)
    {
        error = wxString::Format("Basic setup goes wrong: %s", mpg123_plain_strerror(err));
        if (mh != NULL) {
            cleanup(mh);
        }
        return -1;
    }

    /* open the file and get the decoding format */
    if( mpg123_open(mh, filename.c_str()) != MPG123_OK ||
        mpg123_getformat(mh, &rate, &channels, &encoding) != MPG123_OK )
    {
        error = wxString::Format("Trouble with mpg123: %s", mpg123_strerror(mh));
        cleanup(mh);
        return -1;
    }

    if( encoding != MPG123_ENC_SIGNED_16 )
    {
        error = "Encoding unsupported.  Must be signed 16 bit.";
        cleanup(mh);
        return -2;
    }

    /* set the output format and open the output device */
    m_bits = mpg123_encsize(encoding);
    m_rate = rate;
    m_channels = channels;
    /* Get Track Size */
    mMediaTrackSize = GetTrackSize(mh,m_bits,m_channels);
    buffer_size = mpg123_outblock(mh);
    int size = (mMediaTrackSize+buffer_size)*m_bits*m_channels;
    char * trackData = (char*)malloc(size);
    LoadTrackData(mh,trackData, size);
    // Split data into left and right and normalize -1 to 1
    m_left_data = (float*)malloc(sizeof(float)*mMediaTrackSize);
    if( m_channels == 2 )
    {
        m_right_data = (float*)malloc(sizeof(float)*mMediaTrackSize);
        SplitTrackDataAndNormalize((signed short*)trackData,mMediaTrackSize,m_left_data,m_right_data);
    }
    else if( m_channels == 1 )
    {
        NormalizeMonoTrackData((signed short*)trackData,mMediaTrackSize,m_left_data);
    }
    else
    {
        error = "More than 2 audio channels is not supported yet.";
    }
    views.clear();
    float samplesPerLine = GetSamplesPerLineFromZoomLevel(mZoomLevel);
    WaveView wv(mZoomLevel,samplesPerLine,m_left_data,mMediaTrackSize);
    views.push_back(wv);
    mCurrentWaveView = 0;

    mpg123_close(mh);
    mpg123_delete(mh);
    mpg123_exit();
    free(trackData);
    float seconds = (float)mMediaTrackSize * ((float)1/(float)rate);
    mAudioIsLoaded = true;
    return (int)(seconds * (float)1000);
}
Ejemplo n.º 5
0
arma::field<arma::field<arma::mat> > model_select(arma::vec& data,
                                                  const std::set<std::vector<std::string > >& models,
                                                  const std::vector< std::string >& full_model,
                                                  std::string model_type,
                                                  bool bs_optimism,
                                                  double alpha,
                                                  std::string compute_v, 
                                                  unsigned int K, unsigned int H, unsigned int G, 
                                                  bool robust, double eff, unsigned int seed){
  
  // Number of data points
  unsigned int N = data.n_rows;
  
  // Number of models
  unsigned int num_models = models.size(); 
  
  // Store output from models
  arma::field<arma::field<arma::mat> > model_results(num_models);
  
  // Make an iterator to iterator through it
  std::set<std::vector<std::string > > ::const_iterator iter;
  iter = models.begin(); 
  
  // Get the first model
  std::vector<std::string> desc = full_model;
  
  // Find where the results should be input. (No protection needed, we know it is in the matrix)
  unsigned int full_model_index = std::distance(models.begin(), models.find(full_model));
  
  // Build the fields off of the first model's description
  arma::vec theta = model_theta(desc);
  arma::field<arma::vec> objdesc = model_objdesc(desc); 
  
  // Build matrix to store results
  arma::mat results(num_models, 4);
  
  Rcpp::Rcout << "Processing model 1 out of " << num_models << std::endl;
  
  set_seed(seed);
  
  // Obtain the largest models information
  arma::field<arma::mat> master = gmwm_master_cpp(data, 
                                                  theta,
                                                  desc,
                                                  objdesc, 
                                                  model_type, 
                                                  true, //starting
                                                  alpha, 
                                                  "fast", // compute V
                                                  K, H,
                                                  G, 
                                                  robust, eff);
  
  // Theta update
  theta = master(0);
  
  // Define WV Empirical
  arma::vec wv_empir = master(2);
  
  // Create WV Matrix
  
  arma::mat wv(wv_empir.n_elem,3);
  wv.col(0) = wv_empir;
  wv.col(1) = master(3);
  wv.col(2) = master(4);
  
  // Get the original "FAST" matrix
  arma::mat orgV = master(6); // Original V
  
  // Take the inverse
  arma::mat omega = inv(orgV); // Original V => Omega
  
  // Get expect_diff for guesses with DR
  double expect_diff = arma::as_scalar(master(7));
  
  // Obtain the theoretical WV
  arma::vec theo = master(8);
  
  // Obtain the obj_value of the function
  double obj_value = arma::as_scalar(master(10));
  
  // Calculate the values of the Scales 
  arma::vec scales = scales_cpp(floor(log2(N)));
  
  double dr_slope = arma::as_scalar(master(12));
  
  // ------------------------------------
  
  // Store output from default GMWM object
  arma::field<arma::mat> mod_output(13);
  mod_output(0) = theta;
  mod_output(1) = master(1);
  mod_output(2) = wv_empir;
  mod_output(3) = master(3);
  mod_output(4) = master(4);
  mod_output(5) = master(5);
  mod_output(6) = orgV;
  mod_output(7) = expect_diff;
  mod_output(8) = theo;
  mod_output(9) = master(9);
  mod_output(10) = obj_value;
  mod_output(11) = omega;
  mod_output(12) = dr_slope;
  
  
  // ------------------------------------
  
  // Here we set up specifics that are used not in a specific mode.
  
  // Asymptotic ----
  
  // Get bootstrapped V
  arma::mat V;
  
  // Bootstrap ----
  // Hold optimism result
  arma::mat cov_nu_nu_theta;
  
  // Hold the bootstrapped obj values
  arma::vec bs_obj_values;
  
  if(bs_optimism){
    results.row(full_model_index) = bs_optim_calc(theta,  desc,  objdesc, model_type, scales, omega, N,
                obj_value, alpha, compute_v, K, H, G, robust, eff);
  }else{
    
    Rcpp::Rcout << "Bootstrapping the covariance matrix... Please stand by." << std::endl;
    V = cov_bootstrapper(theta, desc, objdesc, N, robust, eff, H, false); // Bootstrapped V (largest model)
    
    // Calculate the model score according to model selection criteria paper
    results.row(full_model_index) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value);
    
  }
  
  // Custom GMWM Update Obj
  
  arma::field<arma::mat> model_update_info(6);
  model_update_info(0) = master(0); // theta
  model_update_info(1) = master(1); // guessed_theta
  model_update_info(2) = master(5); // V
  model_update_info(3) = master(8); // theo
  model_update_info(4) = master(9); // decomp_theo
  model_update_info(5) = master(10); // objective value
  
  model_results(full_model_index) = model_update_info;
  
  // Initialize counter to keep track of values
  unsigned int count = 0;
  
  unsigned int countModels = 1;
  
  while(iter != models.end()){
    
    if(full_model_index != count){
      countModels++;
      
      // Set guessing seed
      set_seed(seed);
      
      Rcpp::Rcout << "Processing model " << countModels << " out of " << num_models << std::endl;
      // Get the first model
      desc = *iter;
      
      // Build the fields off of the first model's description
      theta = model_theta(desc);
      objdesc = model_objdesc(desc); 
      
      // Run the update version of the GMWM
      arma::field<arma::mat> update = gmwm_update_cpp(theta, desc, objdesc, model_type, 
                                                      N, expect_diff, dr_slope,
                                                      orgV, scales, wv,
                                                      true, //starting
                                                      "fast", 
                                                      K,H,G, 
                                                      robust,eff);
      
      
      // Theta update
      theta = update(0);
      
      // Update theo
      theo = update(3);
      
      // Update objective function
      obj_value = arma::as_scalar(update(5));
      
      if(bs_optimism){
        results.row(count) = bs_optim_calc(theta,  desc,  objdesc, model_type, scales, omega, N,
                    obj_value, alpha, compute_v, K, H, G, robust, eff);
      }else{
        // Calculate the model score according to model selection criteria paper
        results.row(count) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value);
      }
      
      model_results(count) = update;
      
    }
    // end if
    
    // Increment iterator
    iter++;
    
    // Increase count
    count++;
  }
  
  
  
  // Only run if in asymptotic mode
  if(!bs_optimism){
    
    // std::set<std::vector<std::string > > ::const_iterator iter2;
    // 
    // iter = models.begin(); 
    // 
    // /*
    // * Iterate through all models
    // * If i != j, then 
    // * IF (Complex_i > Complex_j && Obj_i > Obj_j){
    // *  IF(Crit_i < Crit_J)
    // * }
    // */
    // while(iter != models.end()){
    //   iter2 = models.begin(); 
    //   while(iter2 != models.end()){
    //     if(iter != iter2){
    //       double m1_index = std::distance(models.begin(),iter);
    //       double m2_index = std::distance(models.begin(),iter2);
    //       
    //       if(count_params(*iter) > count_params(*iter2) && results(m1_index,0) >  results(m2_index,0)){
    //         if(results(m1_index,2) < results(m2_index,2)){
    //           results(m1_index,1) = results(m2_index,1) + fabs(R::rnorm(0, sqrt(results(m2_index,0)/10) ));
    //         }
    //       }
    //     }
    //     iter2++;
    //   }
    //   iter++; 
    // }
    
  }
  
  results.col(2) = results.col(0) + results.col(1);
  
  // Sort matrix
  arma::uvec sort_ind = sort_index(results.col(2));
  
  // Pick the "best" model
  unsigned int best_model_id = sort_ind(0);
  
  // Get the sort column index
  arma::vec ex_sort = arma::conv_to<arma::vec>::from(sort_ind);
  
  // Sort the result matrix by Criterion
  arma::mat sorted = sort_mat(results, 2);
  
  // ---------
  
  // Set up output feed
  arma::field< arma::field<arma::mat> > out(2);
  
  // Build the results matrix
  arma::field<arma::mat> ms(2);
  ms(0) = sorted;
  ms(1) = ex_sort + 1; // Sorted vector (so R can know desc IDs) ALSO change index
  
  // Create m 
  
  // If the output object is not the full model, let's inject the new results.
  if(best_model_id != full_model_index){
    
    arma::field<arma::mat> m;
    m = model_results(best_model_id);
    mod_output(0) = m(0);
    mod_output(1) = m(1);
    mod_output(5) = m(2);
    mod_output(8) = m(3);
    mod_output(9) = m(4);
    mod_output(10) = m(5);
  }
  
  
  // Output to me!
  out(0) = ms;
  out(1) = mod_output;
  
  
  return out;
}