<commit_before>#include <string.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <sys/stat.h>
#include <time.h>

#include "SuMo.h"
#include "Timer.h"

/* specific to file */
const int NUM_ARGS = 4;
const char* filename = "logData";
const char* description = "log data from DAQ";
using namespace std;
/********************/

/* subtract pedestal values on-line */
static bool PED_SUBTRCT = false;

static int LIMIT_READOUT_RATE = 10000;
static int NUM_SEQ_TIMEOUTS = 100;
const  float  MAX_INT_TIMER    = 600.;  // 10 minutes
/* note: usb timeout defined in include/stdUSB.h */

bool overwriteExistingFile = false;

bool fileExists(const std::string& filename);

int main(int argc, char* argv[]){
  if(argc == 2 && std::string(argv[1]) == "-h"){
    cout << endl;
    cout << filename << " :: " << description << endl;
    cout << filename << " :: takes " << NUM_ARGS-1 << " arguments" << endl;
    return 1;
  }
  else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){
    cout << "error: too many number of arguments" << endl;
    return -1;
  }
  else{
    int num_checks = 5;
    int num_events = 100;
    int acq_rate   = 10000;
    SuMo command;
    char log_data_filename[100];

    strcpy(log_data_filename, argv[1]);
    num_events = atoi(argv[2]);
    int trig_mode = atoi(argv[3]);

    if(command.check_active_boards(num_checks))
      return 1;

    command.log_data(log_data_filename, num_events, trig_mode, acq_rate);

    return 0;
  }
}

int SuMo::log_data(const char* log_filename, unsigned int NUM_READS, int trig_mode, int acq_rate){
  bool convert_to_voltage;
  int sample, check_event, asic_baseline[psecSampleCells], count = 0, psec_cnt = 0, numTimeouts = 0, last_k;
  float  _now_, t = 0.;
  char logDataFilename[300];
  Timer timer = Timer();
  time_t now;

  /* handle filename */
  // 'scalar' mode
  ofstream rate_fs;
  if(trig_mode == 2){
    char logRateFilename[300];
    sprintf(logRateFilename, "%s.acdc.rate", log_filename);
    rate_fs.open(logRateFilename, ios::trunc);
  }

  // full waveform, standard mode
  sprintf(logDataFilename, "%s.acdc.dat", log_filename);
  string temp;
  while(fileExists(logDataFilename)){
    cout << "file already exists, try new filename: (or enter to overwrite / ctrl-C to quit): ";
    getline(cin, temp);
    if(temp.empty()) break;
    sprintf(logDataFilename, "%s.acdc.dat", temp.c_str());
  }

  ofstream ofs;
  ofs.open(logDataFilename, ios::trunc);

  /* read all front end cards */
  bool all[numFrontBoards];
  for(int i=0;i<numFrontBoards; i++) all[i] = true;

  /* setup some things */
  if(trig_mode==1) {
                    set_usb_read_mode(24);
    if(mode==USB2x) set_usb_read_mode_slaveDevice(24);
  }
  else {
    if(mode==USB2x) set_usb_read_mode_slaveDevice(16);
    set_usb_read_mode(16), dump_data();
  }

  load_ped();
  /* save pedestal data to file header for reference, easy access */
  /* zero pad to match data format */
  for(int i=0; i < psecSampleCells; i++){

    ofs << i << " " << 0 << " ";
    for(int board=0; board<numFrontBoards; board++){
      if(DC_ACTIVE[board]){
	for(int channel=0; channel < AC_CHANNELS; channel++) ofs << PED_DATA[board][channel][i]<< " ";
	ofs << 0 << " ";
      }
    }
    ofs << endl;
  }

  /* cpu time zero */
  //t0 = time(NULL);
  timer.start();

  for(int k=0;k<NUM_READS; k++){
    /* unix timestamp */
    time(&now);
    /* rough cpu timing in seconds since readout start time*/
    t = timer.stop();
    if(t > MAX_INT_TIMER) {
      cout << endl << "readout timed out at " << t << "on event " << k << endl;
      break;
    }
    /*set read mode to NULL */
    set_usb_read_mode(16);
    if(mode==USB2x) set_usb_read_mode_slaveDevice(16);
    /*reset last event on firmware */
    manage_cc_fifo(1);
    if(mode==USB2x) manage_cc_fifo_slaveDevice(1);

    /*send trigger over software if not looking externally */
    if(trig_mode==1){
                         reset_self_trigger(15, 0), set_usb_read_mode(7);
      if(mode == USB2x)  reset_self_trigger(15, 1), set_usb_read_mode_slaveDevice(7);
      usleep(acq_rate+LIMIT_READOUT_RATE);
                         set_usb_read_mode(0);
      if(mode == USB2x)  set_usb_read_mode_slaveDevice(0);
    }
    else{
      // 'rate-only' mode, only pull data every second
      if(trig_mode == 2){
	usleep(3e6);
      }

      software_trigger((unsigned int)15);
      if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);
      usleep(LIMIT_READOUT_RATE); /* somewhat arbitrary hard-coded rate limitation */

    }

    /* show event number at terminal */
    if((k+1) % 2 == 0 || k==0){
      cout << "Readout:  " << k+1 << " of " << NUM_READS << " :: @time "<< t << " sec         \r";
      cout.flush();
    }
    /**************************************/
    /*Do bulk read on all front-end cards */
    int numBoards = read_AC(1, all, false);
    /**************************************/
    /* handle timeouts or lack of data */
    int numBoardsTimedout = 0;
    for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];
    // timeout on all boards
    if( numBoards == 0 ){
      ofs << k << " " << 0xFF << " " << endl;

      k = k-1;  //repeat event
      continue;

    }
    /*
    int numBoardsTimedout = 0;
    for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];
    if(numBoards == 0 || numBoardsTimedout > 0){
      // check for number of timeouts in a row
      numTimeouts++;
      // handle if too many timeouts:
      if(numTimeouts > NUM_SEQ_TIMEOUTS){
	cout << endl << "error: too many timeouts in a row" << endl;
	return -1;
      }
      k = k-1;
      continue;
    }
    else numTimeouts = 0;
    */

    /* form data for filesave */
    for(int targetAC = 0; targetAC < numFrontBoards; targetAC++){
      if(BOARDS_READOUT[targetAC] && numBoards > 0){
	psec_cnt = 0;
	/*assign meta data */
	get_AC_info(false, targetAC);
	form_meta_data(targetAC, k, t, now);

	check_event = 0;

	for(int i = 0; i < AC_CHANNELS; i++){
	  if(i>0 && i % 6 == 0) psec_cnt ++;

	  for(int j = 0; j < psecSampleCells; j++){
	    sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];
	    if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j];

	    adcDat[targetAC]->Data[i][j] = sample;
	  }
	}
	/* wraparound_correction, if desired: */
	int baseline[psecSampleCells];
	unwrap_baseline(baseline, 2);
	for (int j = 0; j < psecSampleCells; j++) asic_baseline[j] = baseline[j];
      }
      //if timeout on only some, but not all boards
      else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] ){
	for(int i = 0; i < AC_CHANNELS; i++){
	  if(i>0 && i % 6 == 0) psec_cnt ++;

	  for(int j = 0; j < psecSampleCells; j++){
	    sample = 0xFF;
	    adcDat[targetAC]->Data[i][j] = sample;
	  }
	}
      }
    }

    for(int i=0; i < psecSampleCells; i++){

      ofs << i << " " << asic_baseline[i] << " ";
      for(int board=0; board<numFrontBoards; board++)
	if(BOARDS_READOUT[board])
	  for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << " ";
        else if(BOARDS_TIMEOUT[board])
  	  for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << " ";

      ofs <<endl;
    }

    if(trig_mode == 2){
      for(int board=0; board<numFrontBoards; board++){
	if(BOARDS_READOUT[board]){

	  rate_fs << k << "\t" << board << "\t" << t << "\t";

	  for(int channel=0; channel < AC_CHANNELS; channel++)  rate_fs <<  adcDat[board]->self_trig_scalar[channel] << "\t";

	  rate_fs << endl;
	}
      }
    }
    last_k = k;
  }

  cout << "Readout:  " << last_k+1<< " of " << NUM_READS << " :: @time " <<t<< " sec...........\r", usleep(100000),cout.flush();
  cout << "Readout:  " << last_k+1 << " of " << NUM_READS << " :: @time " <<t<< " sec...........finished logging\r",cout.flush();

  manage_cc_fifo(1);
  /* add whitespace to end of file */
  ofs <<endl<<endl;
  ofs.close();

  if(trig_mode == 2) rate_fs.close();

  set_usb_read_mode(16);  //turn off trigger, if on
  dump_data();

  cout << endl;
  cout << "Data saved in file: " << logDataFilename << endl << "*****" << endl;
  return 0;
}

bool fileExists(const string& filename)
{
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
    {
        return true;
    }
    return false;
}

void SuMo::form_meta_data(int Address, int count, double cpuTime, time_t now)
{
  int i = Address;
  adcDat[i]->Data[AC_CHANNELS][0] = count;
  adcDat[i]->Data[AC_CHANNELS][1] = Address;
  adcDat[i]->Data[AC_CHANNELS][2] = adcDat[i]->CC_EVENT_COUNT;
  adcDat[i]->Data[AC_CHANNELS][3] = adcDat[i]->CC_BIN_COUNT;
  adcDat[i]->Data[AC_CHANNELS][4] = adcDat[i]->timestamp_hi;
  adcDat[i]->Data[AC_CHANNELS][5] = adcDat[i]->timestamp_mid;
  adcDat[i]->Data[AC_CHANNELS][6] = adcDat[i]->timestamp_lo;

  adcDat[i]->Data[AC_CHANNELS][7] = adcDat[i]->CC_TIMESTAMP_HI;
  adcDat[i]->Data[AC_CHANNELS][8] = adcDat[i]->CC_TIMESTAMP_MID;
  adcDat[i]->Data[AC_CHANNELS][9] = adcDat[i]->CC_TIMESTAMP_LO;

  adcDat[i]->Data[AC_CHANNELS][10] = adcDat[i]->bin_count_rise;
  adcDat[i]->Data[AC_CHANNELS][11] = adcDat[i]->bin_count_fall;
  adcDat[i]->Data[AC_CHANNELS][12] = adcDat[i]->self_trig_settings;
  adcDat[i]->Data[AC_CHANNELS][13] = adcDat[i]->event_count;
  adcDat[i]->Data[AC_CHANNELS][14] = adcDat[i]->reg_self_trig[0];
  adcDat[i]->Data[AC_CHANNELS][15] = adcDat[i]->reg_self_trig[1];
  adcDat[i]->Data[AC_CHANNELS][16] = adcDat[i]->reg_self_trig[2];
  adcDat[i]->Data[AC_CHANNELS][17] = adcDat[i]->reg_self_trig[3];
  adcDat[i]->Data[AC_CHANNELS][18] = adcDat[i]->self_trig_mask;
  adcDat[i]->Data[AC_CHANNELS][19] = adcDat[i]->last_ac_instruct;
  adcDat[i]->Data[AC_CHANNELS][20] = adcDat[i]->last_last_ac_instruct;
  adcDat[i]->Data[AC_CHANNELS][21] = adcDat[i]->trig_en;
  adcDat[i]->Data[AC_CHANNELS][22] = adcDat[i]->trig_wait_for_sys;
  adcDat[i]->Data[AC_CHANNELS][23] = adcDat[i]->trig_rate_only;
  adcDat[i]->Data[AC_CHANNELS][24] = adcDat[i]->trig_sign;

  /*fill slots 25-39 */
  for(int j=0; j<numChipsOnBoard; j++){
    adcDat[i]->Data[AC_CHANNELS][j+25] = adcDat[i]->ro_cnt[j];
    adcDat[i]->Data[AC_CHANNELS][j+25+numChipsOnBoard] = adcDat[i]->vbias[j];
    adcDat[i]->Data[AC_CHANNELS][j+25+2*numChipsOnBoard] = adcDat[i]->trigger_threshold[j];
  }
  /*fill slots 40-69 */
  for(int j=0; j<AC_CHANNELS; j++){
    adcDat[i]->Data[AC_CHANNELS][j+40] = adcDat[i]->self_trig_scalar[j];
  }
  adcDat[i]->Data[AC_CHANNELS][70] = cpuTime;
  adcDat[i]->Data[AC_CHANNELS][71] = now;
  adcDat[i]->Data[AC_CHANNELS][72] = WRAP_CONSTANT;

}

<commit_msg>modify logData to handle low rates and timeouts<commit_after>#include <string.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <sys/stat.h>
#include <time.h>

#include "SuMo.h"
#include "Timer.h"

/* specific to file */
const int NUM_ARGS = 4;
const char* filename = "logData";
const char* description = "log data from DAQ";
using namespace std;
/********************/

/* subtract pedestal values on-line */
static bool PED_SUBTRCT = false;

static int LIMIT_READOUT_RATE = 10000;
static int NUM_SEQ_TIMEOUTS = 100;
const  float  MAX_INT_TIMER    = 100.;
/* note: usb timeout defined in include/stdUSB.h */

bool overwriteExistingFile = false;

bool fileExists(const std::string& filename);

int main(int argc, char* argv[]){
  if(argc == 2 && std::string(argv[1]) == "-h"){
    cout << endl;
    cout << filename << " :: " << description << endl;
    cout << filename << " :: takes " << NUM_ARGS-1 << " arguments" << endl;
    return 1;
  }
  else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){
    cout << "error: too many number of arguments" << endl;
    return -1;
  }
  else{
    int num_checks = 5;
    int num_events = 100;
    int acq_rate   = 10000;
    SuMo command;
    char log_data_filename[100];

    strcpy(log_data_filename, argv[1]);
    num_events = atoi(argv[2]);
    int trig_mode = atoi(argv[3]);

    if(command.check_active_boards(num_checks))
      return 1;

    command.log_data(log_data_filename, num_events, trig_mode, acq_rate);

    return 0;
  }
}

int SuMo::log_data(const char* log_filename, unsigned int NUM_READS, int trig_mode, int acq_rate){
  bool convert_to_voltage;
  int sample, check_event, asic_baseline[psecSampleCells], count = 0, psec_cnt = 0, numTimeouts = 0, last_k;
  float  _now_, t = 0.;
  char logDataFilename[300];
  Timer timer = Timer();
  time_t now;

  /* handle filename */
  // 'scalar' mode
  ofstream rate_fs;
  if(trig_mode == 2){
    char logRateFilename[300];
    sprintf(logRateFilename, "%s.acdc.rate", log_filename);
    rate_fs.open(logRateFilename, ios::trunc);
  }

  // full waveform, standard mode
  sprintf(logDataFilename, "%s.acdc.dat", log_filename);
  string temp;
  while(fileExists(logDataFilename)){
    cout << "file already exists, try new filename: (or enter to overwrite / ctrl-C to quit): ";
    getline(cin, temp);
    if(temp.empty()) break;
    sprintf(logDataFilename, "%s.acdc.dat", temp.c_str());
  }

  ofstream ofs;
  ofs.open(logDataFilename, ios::trunc);

  /* read all front end cards */
  bool all[numFrontBoards];
  for(int i=0;i<numFrontBoards; i++) all[i] = true;

  /* setup some things */
  if(trig_mode==1) {
                    set_usb_read_mode(24);
    if(mode==USB2x) set_usb_read_mode_slaveDevice(24);
  }
  else {
    if(mode==USB2x) set_usb_read_mode_slaveDevice(16);
    set_usb_read_mode(16), dump_data();
  }

  load_ped();
  /* save pedestal data to file header for reference, easy access */
  /* zero pad to match data format */
  for(int i=0; i < psecSampleCells; i++){

    ofs << i << " " << 0 << " ";
    for(int board=0; board<numFrontBoards; board++){
      if(DC_ACTIVE[board]){
	for(int channel=0; channel < AC_CHANNELS; channel++) ofs << PED_DATA[board][channel][i]<< " ";
	ofs << 0 << " ";
      }
    }
    ofs << endl;
  }

  /* cpu time zero */
  //t0 = time(NULL);
  timer.start();

  for(int k=0;k<NUM_READS; k++){
    /* unix timestamp */
    time(&now);
    /* rough cpu timing in seconds since readout start time*/
    t = timer.stop();
    if(t > MAX_INT_TIMER) {
      cout << endl << "readout timed out at " << t << "on event " << k << endl;
      break;
    }
    /*set read mode to NULL */
    set_usb_read_mode(16);
    if(mode==USB2x) set_usb_read_mode_slaveDevice(16);
    /*reset last event on firmware */
    manage_cc_fifo(1);
    if(mode==USB2x) manage_cc_fifo_slaveDevice(1);

    /*send trigger over software if not looking externally */
    if(trig_mode==1){
      if(mode == USB2x) reset_self_trigger(15, 1);
      reset_self_trigger(15, 0);

      if(mode == USB2x)  set_usb_read_mode_slaveDevice(7);
      set_usb_read_mode(7);

      usleep(acq_rate+LIMIT_READOUT_RATE);  //acq rate limit

      if(mode == USB2x)  set_usb_read_mode_slaveDevice(0);
      set_usb_read_mode(0);
    }
    else{
      // 'rate-only' mode, only pull data every second
      if(trig_mode == 2){
	usleep(3e6);
      }

      software_trigger((unsigned int)15);
      if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);
      usleep(LIMIT_READOUT_RATE); /* somewhat arbitrary hard-coded rate limitation */

    }

    /* show event number at terminal */
    if((k+1) % 2 == 0 || k==0){
      cout << "Readout:  " << k+1 << " of " << NUM_READS << " :: @time "<< t << " sec         \r";
      cout.flush();
    }
    /**************************************/
    /*Do bulk read on all front-end cards */
    int numBoards = read_AC(1, all, false);
    /**************************************/

    /* handle timeouts or lack of data */
    int numBoardsTimedout = 0;
    for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];
    // timeout on all boards
    if( numBoards == 0 ){
      //ofs << k << " " << 0xFF << " " << endl;
      k = k-1;  //repeat event
      continue;

    }
    /*
    int numBoardsTimedout = 0;
    for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];
    if(numBoards == 0 || numBoardsTimedout > 0){
      // check for number of timeouts in a row
      numTimeouts++;
      // handle if too many timeouts:
      if(numTimeouts > NUM_SEQ_TIMEOUTS){
	cout << endl << "error: too many timeouts in a row" << endl;
	return -1;
      }
      k = k-1;
      continue;
    }
    else numTimeouts = 0;
    */

    /* form data for filesave */
    for(int targetAC = 0; targetAC < numFrontBoards; targetAC++){
      if(BOARDS_READOUT[targetAC] && numBoards > 0){
	psec_cnt = 0;
	/*assign meta data */
	get_AC_info(false, targetAC);
	form_meta_data(targetAC, k, t, now);

	check_event = 0;

	for(int i = 0; i < AC_CHANNELS; i++){
	  if(i>0 && i % 6 == 0) psec_cnt ++;

	  for(int j = 0; j < psecSampleCells; j++){
	    sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];
	    if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j];

	    adcDat[targetAC]->Data[i][j] = sample;
	  }
	}
	/* wraparound_correction, if desired: */
	int baseline[psecSampleCells];
	unwrap_baseline(baseline, 2);
	for (int j = 0; j < psecSampleCells; j++) asic_baseline[j] = baseline[j];
      }
      //if timeout on only some, but not all boards
      else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] ){
	for(int i = 0; i < AC_CHANNELS; i++){
	  if(i>0 && i % 6 == 0) psec_cnt ++;

	  for(int j = 0; j < psecSampleCells; j++){
	    sample = 0xFF;
	    adcDat[targetAC]->Data[i][j] = sample;
	  }
	}
      }
    }

    for(int i=0; i < psecSampleCells; i++){

      ofs << i << " " << asic_baseline[i] << " ";
      for(int board=0; board<numFrontBoards; board++)
	if(BOARDS_READOUT[board])
	  for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << " ";
        else if(BOARDS_TIMEOUT[board])
  	  for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << " ";

      ofs <<endl;
    }

    if(trig_mode == 2){
      for(int board=0; board<numFrontBoards; board++){
	if(BOARDS_READOUT[board]){

	  rate_fs << k << "\t" << board << "\t" << t << "\t";

	  for(int channel=0; channel < AC_CHANNELS; channel++)  rate_fs <<  adcDat[board]->self_trig_scalar[channel] << "\t";

	  rate_fs << endl;
	}
      }
    }
    last_k = k;
  }

  cout << "Readout:  " << last_k+1<< " of " << NUM_READS << " :: @time " <<t<< " sec...........\r", usleep(100000),cout.flush();
  cout << "Readout:  " << last_k+1 << " of " << NUM_READS << " :: @time " <<t<< " sec...........finished logging\r",cout.flush();

  manage_cc_fifo(1);
  /* add whitespace to end of file */
  ofs <<endl<<endl;
  ofs.close();

  if(trig_mode == 2) rate_fs.close();

  set_usb_read_mode(16);  //turn off trigger, if on
  dump_data();

  cout << endl;
  cout << "Data saved in file: " << logDataFilename << endl << "*****" << endl;
  return 0;
}

bool fileExists(const string& filename)
{
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
    {
        return true;
    }
    return false;
}

void SuMo::form_meta_data(int Address, int count, double cpuTime, time_t now)
{
  int i = Address;
  adcDat[i]->Data[AC_CHANNELS][0] = count;
  adcDat[i]->Data[AC_CHANNELS][1] = Address;
  adcDat[i]->Data[AC_CHANNELS][2] = adcDat[i]->CC_EVENT_COUNT;
  adcDat[i]->Data[AC_CHANNELS][3] = adcDat[i]->CC_BIN_COUNT;
  adcDat[i]->Data[AC_CHANNELS][4] = adcDat[i]->timestamp_hi;
  adcDat[i]->Data[AC_CHANNELS][5] = adcDat[i]->timestamp_mid;
  adcDat[i]->Data[AC_CHANNELS][6] = adcDat[i]->timestamp_lo;

  adcDat[i]->Data[AC_CHANNELS][7] = adcDat[i]->CC_TIMESTAMP_HI;
  adcDat[i]->Data[AC_CHANNELS][8] = adcDat[i]->CC_TIMESTAMP_MID;
  adcDat[i]->Data[AC_CHANNELS][9] = adcDat[i]->CC_TIMESTAMP_LO;

  adcDat[i]->Data[AC_CHANNELS][10] = adcDat[i]->bin_count_rise;
  adcDat[i]->Data[AC_CHANNELS][11] = adcDat[i]->bin_count_fall;
  adcDat[i]->Data[AC_CHANNELS][12] = adcDat[i]->self_trig_settings;
  adcDat[i]->Data[AC_CHANNELS][13] = adcDat[i]->event_count;
  adcDat[i]->Data[AC_CHANNELS][14] = adcDat[i]->reg_self_trig[0];
  adcDat[i]->Data[AC_CHANNELS][15] = adcDat[i]->reg_self_trig[1];
  adcDat[i]->Data[AC_CHANNELS][16] = adcDat[i]->reg_self_trig[2];
  adcDat[i]->Data[AC_CHANNELS][17] = adcDat[i]->reg_self_trig[3];
  adcDat[i]->Data[AC_CHANNELS][18] = adcDat[i]->self_trig_mask;
  adcDat[i]->Data[AC_CHANNELS][19] = adcDat[i]->last_ac_instruct;
  adcDat[i]->Data[AC_CHANNELS][20] = adcDat[i]->last_last_ac_instruct;
  adcDat[i]->Data[AC_CHANNELS][21] = adcDat[i]->trig_en;
  adcDat[i]->Data[AC_CHANNELS][22] = adcDat[i]->trig_wait_for_sys;
  adcDat[i]->Data[AC_CHANNELS][23] = adcDat[i]->trig_rate_only;
  adcDat[i]->Data[AC_CHANNELS][24] = adcDat[i]->trig_sign;

  /*fill slots 25-39 */
  for(int j=0; j<numChipsOnBoard; j++){
    adcDat[i]->Data[AC_CHANNELS][j+25] = adcDat[i]->ro_cnt[j];
    adcDat[i]->Data[AC_CHANNELS][j+25+numChipsOnBoard] = adcDat[i]->vbias[j];
    adcDat[i]->Data[AC_CHANNELS][j+25+2*numChipsOnBoard] = adcDat[i]->trigger_threshold[j];
  }
  /*fill slots 40-69 */
  for(int j=0; j<AC_CHANNELS; j++){
    adcDat[i]->Data[AC_CHANNELS][j+40] = adcDat[i]->self_trig_scalar[j];
  }
  adcDat[i]->Data[AC_CHANNELS][70] = cpuTime;
  adcDat[i]->Data[AC_CHANNELS][71] = now;
  adcDat[i]->Data[AC_CHANNELS][72] = WRAP_CONSTANT;

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: usrpref.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:13:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _USRPREF_HXX
#define _USRPREF_HXX

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _FLDUPDE_HXX
#include <fldupde.hxx>
#endif
#include "viewopt.hxx"

#ifndef _VCL_FLDUNIT_HXX
#include <vcl/fldunit.hxx>
#endif

/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwMasterUsrPref;
class SwContentViewConfig : public utl::ConfigItem
{
    SwMasterUsrPref&        rParent;
    BOOL                    bWeb;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwContentViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);
        ~SwContentViewConfig();

    // utl::ConfigItem
    virtual void    Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames );
    virtual void    Commit();

    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwLayoutViewConfig : public utl::ConfigItem
{
    SwMasterUsrPref&    rParent;
    BOOL                bWeb;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwLayoutViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);
        ~SwLayoutViewConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------19.01.01 13:06--------------------------------

 ---------------------------------------------------------------------------*/
class SwGridConfig : public utl::ConfigItem
{
    SwMasterUsrPref&    rParent;
    BOOL                bWeb;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwGridConfig(BOOL bWeb, SwMasterUsrPref& rParent);
        ~SwGridConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------19.01.01 13:06--------------------------------

 ---------------------------------------------------------------------------*/
class SwCursorConfig : public utl::ConfigItem
{
    SwMasterUsrPref&    rParent;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwCursorConfig(SwMasterUsrPref& rParent);
        ~SwCursorConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwWebColorConfig : public utl::ConfigItem
{
    SwMasterUsrPref&        rParent;
    com::sun::star::uno::Sequence<rtl::OUString> aPropNames;

    public:
        SwWebColorConfig(SwMasterUsrPref& rParent);
        ~SwWebColorConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwMasterUsrPref : public SwViewOption
{
    friend class SwContentViewConfig;
    friend class SwLayoutViewConfig;
    friend class SwGridConfig;
    friend class SwCursorConfig;
    friend class SwWebColorConfig;

    SwContentViewConfig aContentConfig;
    SwLayoutViewConfig  aLayoutConfig;
    SwGridConfig        aGridConfig;
    SwCursorConfig      aCursorConfig;
    SwWebColorConfig*   pWebColorConfig;

    SwFldUpdateFlags eFldUpdateFlags;    //udpate of fields and charts
    sal_Int32   nLinkUpdateMode;
    FieldUnit   eUserMetric;
    FieldUnit   eHScrollMetric;
    sal_Bool    bIsHScrollMetricSet;
    FieldUnit   eVScrollMetric;
    sal_Bool    bIsVScrollMetricSet;

    sal_Int32   nDefTab;            //default tab stop distance

public:
    SwMasterUsrPref(BOOL bWeb);
    ~SwMasterUsrPref();

    void SetUsrPref(const SwViewOption &rCopy);

    void Commit()
        {
            aContentConfig.Commit();
            aLayoutConfig.Commit();
            aGridConfig.Commit();
            aCursorConfig.Commit();
            if(pWebColorConfig)
                pWebColorConfig->Commit();
        }
    void SetModified()
        {
            aContentConfig.SetModified();
            aLayoutConfig.SetModified();
            aGridConfig.SetModified();
            aCursorConfig.SetModified();
            if(pWebColorConfig)
                pWebColorConfig->SetModified();
        }

    void SetUpdateLinkMode(sal_Int32 nSet, sal_Bool bNoModify = sal_False)
        {
            nLinkUpdateMode = nSet;
            if(!bNoModify)
                aContentConfig.SetModified();
        }
    sal_Int32 GetUpdateLinkMode() const {return nLinkUpdateMode; }

    void SetUpdateFields(BOOL bSet, sal_Bool bNoModify = sal_False)
        {
            if(bSet && eFldUpdateFlags == AUTOUPD_OFF)
            {
                eFldUpdateFlags = AUTOUPD_FIELD_ONLY;
                if(!bNoModify)
                    aContentConfig.SetModified();
             }
            else if(!bSet)
            {
                eFldUpdateFlags = AUTOUPD_OFF;
                if(!bNoModify)
                    aContentConfig.SetModified();
            }
        };
    sal_Bool IsUpdateFields()const {return eFldUpdateFlags != AUTOUPD_OFF; }

    SwFldUpdateFlags   GetFldUpdateFlags()const {return eFldUpdateFlags;}
    void        SetFldUpdateFlags(SwFldUpdateFlags eSet, sal_Bool bNoModify = sal_False)
        {
            eFldUpdateFlags = eSet;
            if(!bNoModify)
                aContentConfig.SetModified();
        }

    void SetUpdateCharts(BOOL bSet, sal_Bool bNoModify = sal_False)
        {
            if(bSet)
            {
                eFldUpdateFlags = AUTOUPD_FIELD_AND_CHARTS;
                if(!bNoModify)
                    aContentConfig.SetModified();
             }
             else if(eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS)
             {
                eFldUpdateFlags = AUTOUPD_FIELD_ONLY;
                if(!bNoModify)
                    aContentConfig.SetModified();
             }
        };
    sal_Bool IsUpdateCharts()const {return eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS; }

    FieldUnit   GetMetric() const { return eUserMetric;}
    void        SetMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)
                {
                    eUserMetric = eSet;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

    sal_Bool    IsHScrollMetric()const {return bIsHScrollMetricSet;}
    FieldUnit   GetHScrollMetric() const { return bIsHScrollMetricSet ? eHScrollMetric : eUserMetric;}
    void        SetHScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)
                {
                    eHScrollMetric = eSet; bIsHScrollMetricSet = sal_True;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

    sal_Bool    IsVScrollMetric()const {return bIsVScrollMetricSet;}
    FieldUnit   GetVScrollMetric() const { return bIsVScrollMetricSet ? eVScrollMetric : eUserMetric;}
    void        SetVScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)
                {
                    eVScrollMetric = eSet; bIsVScrollMetricSet = sal_True;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

    sal_Int32   GetDefTab() const { return nDefTab;}
    void        SetDefTab( sal_Int32  nSet, sal_Bool bNoModify = sal_False )
                {
                    nDefTab = nSet;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

};

#endif

<commit_msg>INTEGRATION: CWS os103 (1.11.116); FILE MERGED 2007/10/01 07:04:54 os 1.11.116.2: RESYNC: (1.11-1.12); FILE MERGED 2007/09/05 12:22:31 os 1.11.116.1: #81258# SwMasterUsrPref members reordered<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: usrpref.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2007-11-06 16:26:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _USRPREF_HXX
#define _USRPREF_HXX

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _FLDUPDE_HXX
#include <fldupde.hxx>
#endif
#include "viewopt.hxx"

#ifndef _VCL_FLDUNIT_HXX
#include <vcl/fldunit.hxx>
#endif

/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwMasterUsrPref;
class SwContentViewConfig : public utl::ConfigItem
{
    SwMasterUsrPref&        rParent;
    BOOL                    bWeb;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwContentViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);
        ~SwContentViewConfig();

    // utl::ConfigItem
    virtual void    Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames );
    virtual void    Commit();

    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwLayoutViewConfig : public utl::ConfigItem
{
    SwMasterUsrPref&    rParent;
    BOOL                bWeb;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwLayoutViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);
        ~SwLayoutViewConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------19.01.01 13:06--------------------------------

 ---------------------------------------------------------------------------*/
class SwGridConfig : public utl::ConfigItem
{
    SwMasterUsrPref&    rParent;
    BOOL                bWeb;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwGridConfig(BOOL bWeb, SwMasterUsrPref& rParent);
        ~SwGridConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------19.01.01 13:06--------------------------------

 ---------------------------------------------------------------------------*/
class SwCursorConfig : public utl::ConfigItem
{
    SwMasterUsrPref&    rParent;

    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
    public:
        SwCursorConfig(SwMasterUsrPref& rParent);
        ~SwCursorConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwWebColorConfig : public utl::ConfigItem
{
    SwMasterUsrPref&        rParent;
    com::sun::star::uno::Sequence<rtl::OUString> aPropNames;

    public:
        SwWebColorConfig(SwMasterUsrPref& rParent);
        ~SwWebColorConfig();

    virtual void            Commit();
    void                    Load();
    void                    SetModified(){ConfigItem::SetModified();}
};
/* -----------------------------28.09.00 09:45--------------------------------

 ---------------------------------------------------------------------------*/
class SwMasterUsrPref : public SwViewOption
{
    friend class SwContentViewConfig;
    friend class SwLayoutViewConfig;
    friend class SwGridConfig;
    friend class SwCursorConfig;
    friend class SwWebColorConfig;

    SwFldUpdateFlags eFldUpdateFlags;    //udpate of fields and charts
    sal_Int32   nLinkUpdateMode;
    FieldUnit   eUserMetric;
    FieldUnit   eHScrollMetric;
    sal_Bool    bIsHScrollMetricSet;
    FieldUnit   eVScrollMetric;
    sal_Bool    bIsVScrollMetricSet;

    sal_Int32   nDefTab;            //default tab stop distance

    SwContentViewConfig aContentConfig;
    SwLayoutViewConfig  aLayoutConfig;
    SwGridConfig        aGridConfig;
    SwCursorConfig      aCursorConfig;
    SwWebColorConfig*   pWebColorConfig;

public:
    SwMasterUsrPref(BOOL bWeb);
    ~SwMasterUsrPref();

    void SetUsrPref(const SwViewOption &rCopy);

    void Commit()
        {
            aContentConfig.Commit();
            aLayoutConfig.Commit();
            aGridConfig.Commit();
            aCursorConfig.Commit();
            if(pWebColorConfig)
                pWebColorConfig->Commit();
        }
    void SetModified()
        {
            aContentConfig.SetModified();
            aLayoutConfig.SetModified();
            aGridConfig.SetModified();
            aCursorConfig.SetModified();
            if(pWebColorConfig)
                pWebColorConfig->SetModified();
        }

    void SetUpdateLinkMode(sal_Int32 nSet, sal_Bool bNoModify = sal_False)
        {
            nLinkUpdateMode = nSet;
            if(!bNoModify)
                aContentConfig.SetModified();
        }
    sal_Int32 GetUpdateLinkMode() const {return nLinkUpdateMode; }

    void SetUpdateFields(BOOL bSet, sal_Bool bNoModify = sal_False)
        {
            if(bSet && eFldUpdateFlags == AUTOUPD_OFF)
            {
                eFldUpdateFlags = AUTOUPD_FIELD_ONLY;
                if(!bNoModify)
                    aContentConfig.SetModified();
             }
            else if(!bSet)
            {
                eFldUpdateFlags = AUTOUPD_OFF;
                if(!bNoModify)
                    aContentConfig.SetModified();
            }
        };
    sal_Bool IsUpdateFields()const {return eFldUpdateFlags != AUTOUPD_OFF; }

    SwFldUpdateFlags   GetFldUpdateFlags()const {return eFldUpdateFlags;}
    void        SetFldUpdateFlags(SwFldUpdateFlags eSet, sal_Bool bNoModify = sal_False)
        {
            eFldUpdateFlags = eSet;
            if(!bNoModify)
                aContentConfig.SetModified();
        }

    void SetUpdateCharts(BOOL bSet, sal_Bool bNoModify = sal_False)
        {
            if(bSet)
            {
                eFldUpdateFlags = AUTOUPD_FIELD_AND_CHARTS;
                if(!bNoModify)
                    aContentConfig.SetModified();
             }
             else if(eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS)
             {
                eFldUpdateFlags = AUTOUPD_FIELD_ONLY;
                if(!bNoModify)
                    aContentConfig.SetModified();
             }
        };
    sal_Bool IsUpdateCharts()const {return eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS; }

    FieldUnit   GetMetric() const { return eUserMetric;}
    void        SetMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)
                {
                    eUserMetric = eSet;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

    sal_Bool    IsHScrollMetric()const {return bIsHScrollMetricSet;}
    FieldUnit   GetHScrollMetric() const { return bIsHScrollMetricSet ? eHScrollMetric : eUserMetric;}
    void        SetHScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)
                {
                    eHScrollMetric = eSet; bIsHScrollMetricSet = sal_True;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

    sal_Bool    IsVScrollMetric()const {return bIsVScrollMetricSet;}
    FieldUnit   GetVScrollMetric() const { return bIsVScrollMetricSet ? eVScrollMetric : eUserMetric;}
    void        SetVScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)
                {
                    eVScrollMetric = eSet; bIsVScrollMetricSet = sal_True;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

    sal_Int32   GetDefTab() const { return nDefTab;}
    void        SetDefTab( sal_Int32  nSet, sal_Bool bNoModify = sal_False )
                {
                    nDefTab = nSet;
                    if(!bNoModify)
                        aLayoutConfig.SetModified();
                }

};

#endif

<|endoftext|>


<commit_before>#include "core.h"

const uint8_t PROGMEM lcdBootProgram[] = {
  0xAE,  // Display Off
  0XD5,  // Set Display Clock Divisor v
  0xF0,  //   0x80 is default
  0xA8,  // Set Multiplex Ratio v
  0x3F,
  0xD3,  // Set Display Offset v
  0x00,
  0x40,  // Set Start Line (0)
  0x8D,  // Charge Pump Setting v
  0x14,  //   Enable
  // running this next pair twice?
  0x20,  // Set Memory Mode v
  0x00,  //   Horizontal Addressing
  0xA1,  // Set Segment Re-map (A0) | (b0001)
  0xC8,  // Set COM Output Scan Direction
  0xDA,  // Set COM Pins v
  0x12,
  0x81,  // Set Contrast v
  0xCF,
  0xD9,  // Set Precharge
  0xF1,
  0xDB,  // Set VCom Detect
  0x40,
  0xA4,  // Entire Display ON
  0xA6,  // Set normal/inverse display
  0xAF,  // Display On

  0x20,     // set display mode
  0x00,     // horizontal addressing mode

  0x21,     // set col address
  0x00,
  COLUMN_ADDRESS_END,

  0x22, // set page address
  0x00,
  PAGE_ADDRESS_END
};

ArduboyCore::ArduboyCore() {}

// meant to be overridden by subclasses
void ArduboyCore::setup()
{
  boot();
}

void ArduboyCore::boot()
{
  #if F_CPU == 8000000L
  slowCPU();
  #endif

  SPI.begin();
  bootPins();
  bootLCD();

  #ifdef SAFE_MODE
  if (getInput() == (LEFT_BUTTON | UP_BUTTON))
    safeMode();
  #endif

  saveMuchPower();
}

#if F_CPU == 8000000L
// if we're compiling for 8Mhz we need to slow the CPU down because the
// hardware clock on the Arduboy is 16MHz
void ArduboyCore::slowCPU()
{
  uint8_t oldSREG = SREG;
  cli();                // suspend interrupts
  CLKPR = _BV(CLKPCE);  // allow reprogramming clock
  CLKPR = 1;            // set clock divisor to 2 (0b0001)
  SREG = oldSREG;       // restore interrupts
}
#endif

void ArduboyCore::bootPins()
{
  // OLED SPI
  pinMode(DC, OUTPUT);
  pinMode(CS, OUTPUT);
  pinMode(RST, OUTPUT);
  digitalWrite(RST, HIGH);
  delay(1);           // VDD (3.3V) goes high at start, lets just chill for a ms
  digitalWrite(RST, LOW);   // bring reset low
  delay(10);          // wait 10ms
  digitalWrite(RST, HIGH);  // bring out of reset

  // Buttons
  pinMode(PIN_LEFT_BUTTON, INPUT_PULLUP);
  pinMode(PIN_RIGHT_BUTTON, INPUT_PULLUP);
  pinMode(PIN_UP_BUTTON, INPUT_PULLUP);
  pinMode(PIN_DOWN_BUTTON, INPUT_PULLUP);
  pinMode(PIN_A_BUTTON, INPUT_PULLUP);
  pinMode(PIN_B_BUTTON, INPUT_PULLUP);

}

void ArduboyCore::bootLCD()
{
  // setup the ports we need to talk to the OLED
  csport = portOutputRegister(digitalPinToPort(CS));
  cspinmask = digitalPinToBitMask(CS);
  dcport = portOutputRegister(digitalPinToPort(DC));
  dcpinmask = digitalPinToBitMask(DC);

  LCDCommandMode();
  for (int8_t i=0; i < sizeof(lcdBootProgram); i++) {
    SPI.transfer(pgm_read_byte(lcdBootProgram + i));
  }
  LCDDataMode();
}

void ArduboyCore::LCDDataMode()
{
  *dcport |= dcpinmask;
  *csport &= ~cspinmask;
}

void ArduboyCore::LCDCommandMode()
{
  *csport |= cspinmask; // why are we doing this twice?
  *csport |= cspinmask;
  *dcport &= ~dcpinmask;
  *csport &= ~cspinmask;
}

// Safe Mode is engaged by holding down both the LEFT button and UP button
// when plugging the device into USB.  It puts your device into a tight
// loop and allows it to be reprogrammed even if you have uploaded a very
// broken sketch that interferes with the normal USB triggered auto-reboot
// functionality of the device.
void ArduboyCore::safeMode()
{
  blank(); // too avoid random gibberish
  while (true) {
    asm volatile("nop \n");
  }
}

/* Power Management */

void ArduboyCore::idle()
{
  set_sleep_mode(SLEEP_MODE_IDLE);
  sleep_mode();
}

void ArduboyCore::saveMuchPower()
{
  power_adc_disable();
  power_usart0_disable();
  power_twi_disable();
  // timer 0 is for millis()
  // timers 1 and 3 are for music and sounds
  power_timer2_disable();
  power_usart1_disable();
  // we need USB, for now (to allow triggered reboots to reprogram)
  // power_usb_disable()
}

uint8_t ArduboyCore::width() { return WIDTH; }

uint8_t ArduboyCore::height() { return HEIGHT; }

/* Drawing */

void ArduboyCore::paint8Pixels(uint8_t pixels)
{
  SPI.transfer(pixels);
}

void ArduboyCore::paintScreen(const unsigned char *image)
{
  for (int i = 0; i < (HEIGHT*WIDTH)/8; i++)
  {
    SPI.transfer(pgm_read_byte(image + i));
  }
}

void ArduboyCore::paintScreen(unsigned char image[])
{
  for (int i = 0; i < (HEIGHT*WIDTH)/8; i++)
  {
    SPI.transfer(image[i]);
  }
}

void ArduboyCore::blank()
{
  for (int i = 0; i < (HEIGHT*WIDTH)/8; i++)
    SPI.transfer(0x00);
}

/* Buttons */

uint8_t ArduboyCore::getInput()
{
  // using ports here is ~100 bytes smaller than digitalRead()
  #ifdef DEVKIT
  // down, left, up
  uint8_t buttons = ((~PINB) & B01110000);
  // right button
  buttons = buttons | (((~PINC) & B01000000) >> 4);
  // A and B
  buttons = buttons | (((~PINF) & B11000000) >> 6);
  #endif

  // b0dlu0rab - see button defines in Arduboy.h
  return buttons;
}
<commit_msg>hand optimized paintScreen from memory buffer<commit_after>#include "core.h"

const uint8_t PROGMEM lcdBootProgram[] = {
  0xAE,  // Display Off
  0XD5,  // Set Display Clock Divisor v
  0xF0,  //   0x80 is default
  0xA8,  // Set Multiplex Ratio v
  0x3F,
  0xD3,  // Set Display Offset v
  0x00,
  0x40,  // Set Start Line (0)
  0x8D,  // Charge Pump Setting v
  0x14,  //   Enable
  // running this next pair twice?
  0x20,  // Set Memory Mode v
  0x00,  //   Horizontal Addressing
  0xA1,  // Set Segment Re-map (A0) | (b0001)
  0xC8,  // Set COM Output Scan Direction
  0xDA,  // Set COM Pins v
  0x12,
  0x81,  // Set Contrast v
  0xCF,
  0xD9,  // Set Precharge
  0xF1,
  0xDB,  // Set VCom Detect
  0x40,
  0xA4,  // Entire Display ON
  0xA6,  // Set normal/inverse display
  0xAF,  // Display On

  0x20,     // set display mode
  0x00,     // horizontal addressing mode

  0x21,     // set col address
  0x00,
  COLUMN_ADDRESS_END,

  0x22, // set page address
  0x00,
  PAGE_ADDRESS_END
};

ArduboyCore::ArduboyCore() {}

// meant to be overridden by subclasses
void ArduboyCore::setup()
{
  boot();
}

void ArduboyCore::boot()
{
  #if F_CPU == 8000000L
  slowCPU();
  #endif

  SPI.begin();
  bootPins();
  bootLCD();

  #ifdef SAFE_MODE
  if (getInput() == (LEFT_BUTTON | UP_BUTTON))
    safeMode();
  #endif

  saveMuchPower();
}

#if F_CPU == 8000000L
// if we're compiling for 8Mhz we need to slow the CPU down because the
// hardware clock on the Arduboy is 16MHz
void ArduboyCore::slowCPU()
{
  uint8_t oldSREG = SREG;
  cli();                // suspend interrupts
  CLKPR = _BV(CLKPCE);  // allow reprogramming clock
  CLKPR = 1;            // set clock divisor to 2 (0b0001)
  SREG = oldSREG;       // restore interrupts
}
#endif

void ArduboyCore::bootPins()
{
  // OLED SPI
  pinMode(DC, OUTPUT);
  pinMode(CS, OUTPUT);
  pinMode(RST, OUTPUT);
  digitalWrite(RST, HIGH);
  delay(1);           // VDD (3.3V) goes high at start, lets just chill for a ms
  digitalWrite(RST, LOW);   // bring reset low
  delay(10);          // wait 10ms
  digitalWrite(RST, HIGH);  // bring out of reset

  // Buttons
  pinMode(PIN_LEFT_BUTTON, INPUT_PULLUP);
  pinMode(PIN_RIGHT_BUTTON, INPUT_PULLUP);
  pinMode(PIN_UP_BUTTON, INPUT_PULLUP);
  pinMode(PIN_DOWN_BUTTON, INPUT_PULLUP);
  pinMode(PIN_A_BUTTON, INPUT_PULLUP);
  pinMode(PIN_B_BUTTON, INPUT_PULLUP);

}

void ArduboyCore::bootLCD()
{
  // setup the ports we need to talk to the OLED
  csport = portOutputRegister(digitalPinToPort(CS));
  cspinmask = digitalPinToBitMask(CS);
  dcport = portOutputRegister(digitalPinToPort(DC));
  dcpinmask = digitalPinToBitMask(DC);

  LCDCommandMode();
  for (int8_t i=0; i < sizeof(lcdBootProgram); i++) {
    SPI.transfer(pgm_read_byte(lcdBootProgram + i));
  }
  LCDDataMode();
}

void ArduboyCore::LCDDataMode()
{
  *dcport |= dcpinmask;
  *csport &= ~cspinmask;
}

void ArduboyCore::LCDCommandMode()
{
  *csport |= cspinmask; // why are we doing this twice?
  *csport |= cspinmask;
  *dcport &= ~dcpinmask;
  *csport &= ~cspinmask;
}

// Safe Mode is engaged by holding down both the LEFT button and UP button
// when plugging the device into USB.  It puts your device into a tight
// loop and allows it to be reprogrammed even if you have uploaded a very
// broken sketch that interferes with the normal USB triggered auto-reboot
// functionality of the device.
void ArduboyCore::safeMode()
{
  blank(); // too avoid random gibberish
  while (true) {
    asm volatile("nop \n");
  }
}

/* Power Management */

void ArduboyCore::idle()
{
  set_sleep_mode(SLEEP_MODE_IDLE);
  sleep_mode();
}

void ArduboyCore::saveMuchPower()
{
  power_adc_disable();
  power_usart0_disable();
  power_twi_disable();
  // timer 0 is for millis()
  // timers 1 and 3 are for music and sounds
  power_timer2_disable();
  power_usart1_disable();
  // we need USB, for now (to allow triggered reboots to reprogram)
  // power_usb_disable()
}

uint8_t ArduboyCore::width() { return WIDTH; }

uint8_t ArduboyCore::height() { return HEIGHT; }

/* Drawing */

void ArduboyCore::paint8Pixels(uint8_t pixels)
{
  SPI.transfer(pixels);
}

void ArduboyCore::paintScreen(const unsigned char *image)
{
  for (int i = 0; i < (HEIGHT*WIDTH)/8; i++)
  {
    SPI.transfer(pgm_read_byte(image + i));
  }
}

// paint from a memory buffer, this should be FAST as it's likely what
// will be used by any buffer based subclass
void ArduboyCore::paintScreen(unsigned char image[])
{
  for (int i = 0; i < (HEIGHT*WIDTH)/8; i++)
  {
    // SPI.transfer(image[i]);

    // we need to burn 18 cycles between sets of SPDR
    // 4 clock cycles
    SPDR = image[i];
    // 7 clock cycles
    asm volatile(
      "mul __zero_reg__, __zero_reg__ \n" // 2 cycles
      "mul __zero_reg__, __zero_reg__ \n" // 2 cycles
      "mul __zero_reg__, __zero_reg__ \n" // 2 cycles
      );
  }
}

void ArduboyCore::blank()
{
  for (int i = 0; i < (HEIGHT*WIDTH)/8; i++)
    SPI.transfer(0x00);
}

/* Buttons */

uint8_t ArduboyCore::getInput()
{
  // using ports here is ~100 bytes smaller than digitalRead()
  #ifdef DEVKIT
  // down, left, up
  uint8_t buttons = ((~PINB) & B01110000);
  // right button
  buttons = buttons | (((~PINC) & B01000000) >> 4);
  // A and B
  buttons = buttons | (((~PINF) & B11000000) >> 6);
  #endif

  // b0dlu0rab - see button defines in Arduboy.h
  return buttons;
}
<|endoftext|>


<commit_before>///
/// @file
/// @copyright Copyright (C) 2017-2018, Jonathan Bryan Schmalhofer
///
/// @brief AirSimToRos Implementation
///

#include "js_airsim_to_ros_library/airsim_to_ros_class.h"

namespace js_airsim_to_ros_library
{

AirSimToRosClass::AirSimToRosClass(std::string const& addr)
    : zmq_context_(1)
    , zmq_subscriber_(zmq_context_, ZMQ_SUB)
{
    zmq_subscriber_.setsockopt(ZMQ_IDENTITY, "AirSimToRosSubscriber", 5);
    zmq_subscriber_.setsockopt(ZMQ_SUBSCRIBE, "", 0);
    zmq_subscriber_.setsockopt(ZMQ_RCVTIMEO, 5000);
    zmq_subscriber_.connect(addr);

    // Header
    header_seq_                 = 0;
    header_stamp_sec_           = 0;
    header_stamp_nsec_          = 0;
    header_frame_id_            = "";
    // Left
    left_height_                = 0;
    left_width_                 = 0;
    left_encoding_              = "";
    left_is_bigendian_          = 0;
    left_step_                  = 0;
    left_data_                  = NULL;
    left_data_size_             = 0;
    // Right
    right_height_               = 0;
    right_width_                = 0;
    right_encoding_             = "";
    right_is_bigendian_         = 0;
    right_step_                 = 0;
    right_data_                 = NULL;
    right_data_size_            = 0;

    // Pose.position
    pose_position_x_            = 0;
    pose_position_y_            = 0;
    pose_position_z_            = 0;
    // Pose.orientation
    pose_orientation_roll_      = 0;
    pose_orientation_pitch_     = 0;
    pose_orientation_yaw_       = 0;
}

void AirSimToRosClass::Connect(std::string const& addr)
{
	zmq_subscriber_.connect(addr);
}

AirSimToRosClass::~AirSimToRosClass()
{
    free(left_data_);
    free(right_data_);
}

int8_t AirSimToRosClass::ReceivedMessage()
{
    zmq::message_t zmq_received_message;
    zmq_subscriber_.recv(&zmq_received_message);

    flatbuffers::FlatBufferBuilder fbb;
    airsim_to_ros::StereoImagePoseBuilder builder(fbb);

    // Verify the message contents are trustworthy.
    flatbuffers::Verifier verifier((const unsigned char *)zmq_received_message.data(),
                                                          zmq_received_message.size());
    int8_t return_value = 0;

    if (zmq_received_message.size() > 0)
    {
      // Make sure the message has valid data.
      if (airsim_to_ros::VerifyStereoImagePoseBuffer(verifier))
      {
          auto flatbuffer_rcvd = airsim_to_ros::GetStereoImagePose(zmq_received_message.data());

          // Header
          header_seq_                 = flatbuffer_rcvd->header()->seq();
          header_stamp_sec_           = flatbuffer_rcvd->header()->stamp()->sec();
          header_stamp_nsec_          = flatbuffer_rcvd->header()->stamp()->nsec();
          header_frame_id_            = flatbuffer_rcvd->header()->frame_id()->c_str();
          // Left
          left_height_               = flatbuffer_rcvd->left()->height();
          left_width_                = flatbuffer_rcvd->left()->width();
          left_encoding_             = flatbuffer_rcvd->left()->encoding()->c_str();
          left_is_bigendian_         = flatbuffer_rcvd->left()->is_bigendian();
          left_step_                 = flatbuffer_rcvd->left()->step();
          left_data_                 = (std::uint8_t*)realloc(left_data_, left_step_ * left_height_);//zmq_received_message.size());
          left_data_size_            = left_step_ * left_height_;
          memcpy(left_data_, flatbuffer_rcvd->left()->data(), left_data_size_);
          // Right
          right_height_               = flatbuffer_rcvd->right()->height();
          right_width_                = flatbuffer_rcvd->right()->width();
          right_encoding_             = flatbuffer_rcvd->right()->encoding()->c_str();
          right_is_bigendian_         = flatbuffer_rcvd->right()->is_bigendian();
          right_step_                 = flatbuffer_rcvd->right()->step();
          right_data_                 = (std::uint8_t*)realloc(right_data_, right_step_ * right_height_);//zmq_received_message.size());
          right_data_size_            = right_step_ * right_height_;
          memcpy(right_data_, flatbuffer_rcvd->right()->data(), right_data_size_);

          // position
          pose_position_x_            = flatbuffer_rcvd->pose()->position()->x();
          pose_position_y_            = flatbuffer_rcvd->pose()->position()->y();
          pose_position_z_            = flatbuffer_rcvd->pose()->position()->z();
          // orientation
          pose_orientation_roll_      = flatbuffer_rcvd->pose()->orientation()->roll();
          pose_orientation_pitch_     = flatbuffer_rcvd->pose()->orientation()->pitch();
          pose_orientation_yaw_       = flatbuffer_rcvd->pose()->orientation()->yaw();
          return_value                = 1;
      }
      else
      {
          return_value                = -1;
      }
    }

    return return_value;
}

uint32_t AirSimToRosClass::GetHeaderSeq()
{
    return header_seq_;
}

uint32_t AirSimToRosClass::GetHeaderStampSec()
{
    return header_stamp_sec_;
}

uint32_t AirSimToRosClass::GetHeaderStampNsec()
{
    return header_stamp_nsec_;
}

std::string AirSimToRosClass::GetHeaderFrameid()
{
    return header_frame_id_;
}

uint32_t AirSimToRosClass::GetLeftHeight()
{
    return left_height_;
}

uint32_t AirSimToRosClass::GetLeftWidth()
{
    return left_width_;
}

std::string AirSimToRosClass::GetLeftEncoding()
{
    return left_encoding_;
}

uint8_t AirSimToRosClass::GetLeftIsBigendian()
{
    return left_is_bigendian_;
}

uint32_t AirSimToRosClass::GetLeftStep()
{
    return left_step_;
}

std::uint8_t* AirSimToRosClass::GetLeftData()
{
    return left_data_;
}

size_t AirSimToRosClass::GetLeftDataSize()
{
    return left_data_size_;
}

uint32_t AirSimToRosClass::GetRightHeight()
{
    return right_height_;
}

uint32_t AirSimToRosClass::GetRightWidth()
{
    return right_width_;
}

std::string AirSimToRosClass::GetRightEncoding()
{
    return right_encoding_;
}

uint8_t AirSimToRosClass::GetRightIsBigendian()
{
    return right_is_bigendian_;
}

uint32_t AirSimToRosClass::GetRightStep()
{
    return right_step_;
}

std::uint8_t* AirSimToRosClass::GetRightData()
{
    return right_data_;
}

size_t AirSimToRosClass::GetRightDataSize()
{
    return right_data_size_;
}

double AirSimToRosClass::GetPosePositionX()
{
    return pose_position_x_;
}

double AirSimToRosClass::GetPosePositionY()
{
    return pose_position_y_;
}

double AirSimToRosClass::GetPosePositionZ()
{
    return pose_position_z_;
}

double AirSimToRosClass::GetPoseOrientationRoll()
{
    return pose_orientation_roll_;
}

double AirSimToRosClass::GetPoseOrientationPitch()
{
    return pose_orientation_pitch_;
}

double AirSimToRosClass::GetPoseOrientationYaw()
{
    return pose_orientation_yaw_;
}
}  // namespace js_airsim_to_ros_library

<commit_msg>removed those behated tabs<commit_after>///
/// @file
/// @copyright Copyright (C) 2017-2018, Jonathan Bryan Schmalhofer
///
/// @brief AirSimToRos Implementation
///

#include "js_airsim_to_ros_library/airsim_to_ros_class.h"

namespace js_airsim_to_ros_library
{

AirSimToRosClass::AirSimToRosClass(std::string const& addr)
    : zmq_context_(1)
    , zmq_subscriber_(zmq_context_, ZMQ_SUB)
{
    zmq_subscriber_.setsockopt(ZMQ_IDENTITY, "AirSimToRosSubscriber", 5);
    zmq_subscriber_.setsockopt(ZMQ_SUBSCRIBE, "", 0);
    zmq_subscriber_.setsockopt(ZMQ_RCVTIMEO, 5000);
    zmq_subscriber_.connect(addr);

    // Header
    header_seq_                 = 0;
    header_stamp_sec_           = 0;
    header_stamp_nsec_          = 0;
    header_frame_id_            = "";
    // Left
    left_height_                = 0;
    left_width_                 = 0;
    left_encoding_              = "";
    left_is_bigendian_          = 0;
    left_step_                  = 0;
    left_data_                  = NULL;
    left_data_size_             = 0;
    // Right
    right_height_               = 0;
    right_width_                = 0;
    right_encoding_             = "";
    right_is_bigendian_         = 0;
    right_step_                 = 0;
    right_data_                 = NULL;
    right_data_size_            = 0;

    // Pose.position
    pose_position_x_            = 0;
    pose_position_y_            = 0;
    pose_position_z_            = 0;
    // Pose.orientation
    pose_orientation_roll_      = 0;
    pose_orientation_pitch_     = 0;
    pose_orientation_yaw_       = 0;
}

void AirSimToRosClass::Connect(std::string const& addr)
{
    zmq_subscriber_.connect(addr);
}

AirSimToRosClass::~AirSimToRosClass()
{
    free(left_data_);
    free(right_data_);
}

int8_t AirSimToRosClass::ReceivedMessage()
{
    zmq::message_t zmq_received_message;
    zmq_subscriber_.recv(&zmq_received_message);

    flatbuffers::FlatBufferBuilder fbb;
    airsim_to_ros::StereoImagePoseBuilder builder(fbb);

    // Verify the message contents are trustworthy.
    flatbuffers::Verifier verifier((const unsigned char *)zmq_received_message.data(),
                                                          zmq_received_message.size());
    int8_t return_value = 0;

    if (zmq_received_message.size() > 0)
    {
      // Make sure the message has valid data.
      if (airsim_to_ros::VerifyStereoImagePoseBuffer(verifier))
      {
          auto flatbuffer_rcvd = airsim_to_ros::GetStereoImagePose(zmq_received_message.data());

          // Header
          header_seq_                 = flatbuffer_rcvd->header()->seq();
          header_stamp_sec_           = flatbuffer_rcvd->header()->stamp()->sec();
          header_stamp_nsec_          = flatbuffer_rcvd->header()->stamp()->nsec();
          header_frame_id_            = flatbuffer_rcvd->header()->frame_id()->c_str();
          // Left
          left_height_               = flatbuffer_rcvd->left()->height();
          left_width_                = flatbuffer_rcvd->left()->width();
          left_encoding_             = flatbuffer_rcvd->left()->encoding()->c_str();
          left_is_bigendian_         = flatbuffer_rcvd->left()->is_bigendian();
          left_step_                 = flatbuffer_rcvd->left()->step();
          left_data_                 = (std::uint8_t*)realloc(left_data_, left_step_ * left_height_);//zmq_received_message.size());
          left_data_size_            = left_step_ * left_height_;
          memcpy(left_data_, flatbuffer_rcvd->left()->data(), left_data_size_);
          // Right
          right_height_               = flatbuffer_rcvd->right()->height();
          right_width_                = flatbuffer_rcvd->right()->width();
          right_encoding_             = flatbuffer_rcvd->right()->encoding()->c_str();
          right_is_bigendian_         = flatbuffer_rcvd->right()->is_bigendian();
          right_step_                 = flatbuffer_rcvd->right()->step();
          right_data_                 = (std::uint8_t*)realloc(right_data_, right_step_ * right_height_);//zmq_received_message.size());
          right_data_size_            = right_step_ * right_height_;
          memcpy(right_data_, flatbuffer_rcvd->right()->data(), right_data_size_);

          // position
          pose_position_x_            = flatbuffer_rcvd->pose()->position()->x();
          pose_position_y_            = flatbuffer_rcvd->pose()->position()->y();
          pose_position_z_            = flatbuffer_rcvd->pose()->position()->z();
          // orientation
          pose_orientation_roll_      = flatbuffer_rcvd->pose()->orientation()->roll();
          pose_orientation_pitch_     = flatbuffer_rcvd->pose()->orientation()->pitch();
          pose_orientation_yaw_       = flatbuffer_rcvd->pose()->orientation()->yaw();
          return_value                = 1;
      }
      else
      {
          return_value                = -1;
      }
    }

    return return_value;
}

uint32_t AirSimToRosClass::GetHeaderSeq()
{
    return header_seq_;
}

uint32_t AirSimToRosClass::GetHeaderStampSec()
{
    return header_stamp_sec_;
}

uint32_t AirSimToRosClass::GetHeaderStampNsec()
{
    return header_stamp_nsec_;
}

std::string AirSimToRosClass::GetHeaderFrameid()
{
    return header_frame_id_;
}

uint32_t AirSimToRosClass::GetLeftHeight()
{
    return left_height_;
}

uint32_t AirSimToRosClass::GetLeftWidth()
{
    return left_width_;
}

std::string AirSimToRosClass::GetLeftEncoding()
{
    return left_encoding_;
}

uint8_t AirSimToRosClass::GetLeftIsBigendian()
{
    return left_is_bigendian_;
}

uint32_t AirSimToRosClass::GetLeftStep()
{
    return left_step_;
}

std::uint8_t* AirSimToRosClass::GetLeftData()
{
    return left_data_;
}

size_t AirSimToRosClass::GetLeftDataSize()
{
    return left_data_size_;
}

uint32_t AirSimToRosClass::GetRightHeight()
{
    return right_height_;
}

uint32_t AirSimToRosClass::GetRightWidth()
{
    return right_width_;
}

std::string AirSimToRosClass::GetRightEncoding()
{
    return right_encoding_;
}

uint8_t AirSimToRosClass::GetRightIsBigendian()
{
    return right_is_bigendian_;
}

uint32_t AirSimToRosClass::GetRightStep()
{
    return right_step_;
}

std::uint8_t* AirSimToRosClass::GetRightData()
{
    return right_data_;
}

size_t AirSimToRosClass::GetRightDataSize()
{
    return right_data_size_;
}

double AirSimToRosClass::GetPosePositionX()
{
    return pose_position_x_;
}

double AirSimToRosClass::GetPosePositionY()
{
    return pose_position_y_;
}

double AirSimToRosClass::GetPosePositionZ()
{
    return pose_position_z_;
}

double AirSimToRosClass::GetPoseOrientationRoll()
{
    return pose_orientation_roll_;
}

double AirSimToRosClass::GetPoseOrientationPitch()
{
    return pose_orientation_pitch_;
}

double AirSimToRosClass::GetPoseOrientationYaw()
{
    return pose_orientation_yaw_;
}
}  // namespace js_airsim_to_ros_library

<|endoftext|>


<commit_before>
#include "gtest/gtest.h"
#include <alcommon-ng/serialization/serialization.h>
#include <boost/timer.hpp>
#include <string>

using namespace AL::Serialization;
int numMessages = 1000;

TEST(SerializationTest, TextSerializationSimpleTypes)
{
  //    float three = 3.0f;
  std::string text = "three";
  std::string str;

  // text
  str = serialize(3, TEXT);
  int str_int = deserialize<int>(str, TEXT);
  EXPECT_EQ(3, str_int);

  str = serialize(3.0f, TEXT);
  float str_float = deserialize<float>(str, TEXT);
  EXPECT_EQ(3.0f, str_float);

  str = serialize(text, TEXT);
  std::string str_str = deserialize<std::string>(str, TEXT);
  EXPECT_EQ(text, str_str);
}

TEST(SerializationTest, XmlSerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // xml
  str = serialize(3, XML);
  int xml_int = deserialize<int>(str, XML);
  EXPECT_EQ(3, xml_int);

  str = serialize(3.0f, XML);
  float xml_float = deserialize<float>(str, XML);
  EXPECT_EQ(3.0f, xml_float);

  str = serialize(text, XML);
  std::string xml_str = deserialize<std::string>(str, XML);
  EXPECT_EQ(text, xml_str);
}

TEST(SerializationTest, BinarySerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // bin
  str = serialize(3, BINARY);
  int bin_int = deserialize<int>(str, BINARY);
  EXPECT_EQ(3, bin_int);

  str = serialize(3.0f, BINARY);
  float bin_float = deserialize<float>(str, BINARY);
  EXPECT_EQ(3.0f, bin_float);

  str = serialize(text, BINARY);
  std::string bin_str = deserialize<std::string>(str, BINARY);
  EXPECT_EQ(text, bin_str);

}

TEST(SerializationTest, DefaultSerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // auto binary
  str = serialize(3);
  int aut_int = deserialize<int>(str);
  EXPECT_EQ(3, aut_int);

  str = serialize(3.0f);
  float aut_float = deserialize<float>(str);
  EXPECT_EQ(3.0f, aut_float);

  str = serialize(text);
  std::string aut_str = deserialize<std::string>(str);
  EXPECT_EQ(text, aut_str);

}

TEST(SerializationTest, BinaryToPtrSerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // to ptr
  str = serialize(3);
  boost::shared_ptr<int> ptr_int = deserializeToPtr<int>(str);
  EXPECT_EQ(3, *ptr_int.get());

  str = serialize(3.0f);
  boost::shared_ptr<float> ptr_float = deserializeToPtr<float>(str);
  EXPECT_EQ(3.0f, *ptr_float.get());

  str = serialize(text);
  boost::shared_ptr<std::string> ptr_str = deserializeToPtr<std::string>(str);
  EXPECT_EQ(text, *ptr_str.get());

  // from ptr
}

void testSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {

  std::cout << "Bytes, msg/s, MB/s" << std::endl;
  // loop message sizes 2^i bytes
  for (unsigned int i=1; i < 15; i++) {

    char character = 'A';
    unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string request = std::string(numBytes, character);

    boost::timer t;
    double elapsed;
    t.restart();

    for (int loop = 0; loop < numMessages; loop++) {
      // Serialize
      std::string reply = AL::Serialization::serialize(request, type);
    }

    elapsed = t.elapsed();
    float msgPs = 1.0f / ((float)elapsed / (1.0f * numMessages) );
    float mgbPs = (msgPs * numBytes) / (1024 * 1024.0f);
    std::cout << numBytes << ", " << msgPs << ", " << mgbPs << std::endl;
  }
}

void testDeSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {

  std::cout << "Bytes, msg/s, MB/s" << std::endl;
  // loop message sizes 2^i bytes
  for (unsigned int i=1; i < 15; i++) {

    char character = 'A';
    unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string request = std::string(numBytes, character);

    boost::timer t;
    double elapsed;
    std::string buffer = AL::Serialization::serialize(request, type);

    t.restart();

    for (int loop = 0; loop < numMessages; loop++) {
      // Serialize
      std::string reply = AL::Serialization::deserialize<std::string>(buffer, type);
    }

    elapsed = t.elapsed();
    float msgPs = 1.0f / ((float)elapsed / (1.0f * numMessages) );
    float mgbPs = (msgPs * numBytes) / (1024 * 1024.0f);
    std::cout << numBytes << ", " << msgPs << ", " << mgbPs << std::endl;
  }
}

TEST(SerializationPerformance, binary) {
  //int numMessages = 10000;
  std::cout << " BINARY Serialization " << numMessages << std::endl;
  testSerialization_StringBufferSizes(BINARY, numMessages);
  std::cout << " BINARY DeSerialization " << numMessages << std::endl;
  testDeSerialization_StringBufferSizes(BINARY, numMessages);
}

TEST(SerializationPerformance, text) {
  //int numMessages = 10000;

  std::cout << " TEXT Serialization " << numMessages << std::endl;
  testSerialization_StringBufferSizes(TEXT, numMessages);
  std::cout << " TEXT DeSerialization " << numMessages << std::endl;
  testDeSerialization_StringBufferSizes(TEXT, numMessages);
}

TEST(SerializationPerformance, xml) {
  //int numMessages = 10000;

  std::cout << " XML Serialization " << numMessages << std::endl;
  testSerialization_StringBufferSizes(XML, numMessages);
  std::cout << " XML DeSerialization " << numMessages << std::endl;
  testDeSerialization_StringBufferSizes(XML, numMessages);

}<commit_msg>Added vector float tests<commit_after>
#include "gtest/gtest.h"
#include <alcommon-ng/serialization/serialization.h>
#include <boost/timer.hpp>
#include <string>

using namespace AL::Serialization;
int numMessages = 1000;

TEST(SerializationTest, TextSerializationSimpleTypes)
{
  //    float three = 3.0f;
  std::string text = "three";
  std::string str;

  // text
  str = serialize(3, TEXT);
  int str_int = deserialize<int>(str, TEXT);
  EXPECT_EQ(3, str_int);

  str = serialize(3.0f, TEXT);
  float str_float = deserialize<float>(str, TEXT);
  EXPECT_EQ(3.0f, str_float);

  str = serialize(text, TEXT);
  std::string str_str = deserialize<std::string>(str, TEXT);
  EXPECT_EQ(text, str_str);

  std::vector<float> floats;
  floats.assign(26,1.1028284f);
  str = serialize(floats, TEXT);
  std::vector<float>  rep = deserialize<std::vector<float> >(str, TEXT);
  for (unsigned int i = 0; i < floats.size(); ++i) {
    EXPECT_EQ(floats[i], rep[i]);
  }
}

TEST(SerializationTest, XmlSerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // xml
  str = serialize(3, XML);
  int xml_int = deserialize<int>(str, XML);
  EXPECT_EQ(3, xml_int);

  str = serialize(3.0f, XML);
  float xml_float = deserialize<float>(str, XML);
  EXPECT_EQ(3.0f, xml_float);

  str = serialize(text, XML);
  std::string xml_str = deserialize<std::string>(str, XML);
  EXPECT_EQ(text, xml_str);

  std::vector<float> floats;
  floats.assign(26,1.1028284f);
  str = serialize(floats, XML);
  std::vector<float>  rep = deserialize<std::vector<float> >(str, XML);
  for (unsigned int i = 0; i < floats.size(); ++i) {
    EXPECT_EQ(floats[i], rep[i]);
  }
}

TEST(SerializationTest, BinarySerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // bin
  str = serialize(3, BINARY);
  int bin_int = deserialize<int>(str, BINARY);
  EXPECT_EQ(3, bin_int);

  str = serialize(3.0f, BINARY);
  float bin_float = deserialize<float>(str, BINARY);
  EXPECT_EQ(3.0f, bin_float);

  str = serialize(text, BINARY);
  std::string bin_str = deserialize<std::string>(str, BINARY);
  EXPECT_EQ(text, bin_str);

  std::vector<float> floats;
  floats.assign(26,1.1028284f);
  str = serialize(floats, BINARY);
  std::vector<float>  rep = deserialize<std::vector<float> >(str, BINARY);
  for (unsigned int i = 0; i < floats.size(); ++i) {
    EXPECT_EQ(floats[i], rep[i]);
  }

}

TEST(SerializationTest, DefaultSerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // auto binary
  str = serialize(3);
  int aut_int = deserialize<int>(str);
  EXPECT_EQ(3, aut_int);

  str = serialize(3.0f);
  float aut_float = deserialize<float>(str);
  EXPECT_EQ(3.0f, aut_float);

  str = serialize(text);
  std::string aut_str = deserialize<std::string>(str);
  EXPECT_EQ(text, aut_str);

}

TEST(SerializationTest, BinaryToPtrSerializationSimpleTypes)
{
  std::string text = "three";
  std::string str;

  // to ptr
  str = serialize(3);
  boost::shared_ptr<int> ptr_int = deserializeToPtr<int>(str);
  EXPECT_EQ(3, *ptr_int.get());

  str = serialize(3.0f);
  boost::shared_ptr<float> ptr_float = deserializeToPtr<float>(str);
  EXPECT_EQ(3.0f, *ptr_float.get());

  str = serialize(text);
  boost::shared_ptr<std::string> ptr_str = deserializeToPtr<std::string>(str);
  EXPECT_EQ(text, *ptr_str.get());

  // from ptr
}

void testSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {

  std::cout << "Bytes, msg/s, MB/s" << std::endl;
  // loop message sizes 2^i bytes
  for (unsigned int i=1; i < 21; i++) {

    char character = 'A';
    unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string request = std::string(numBytes, character);

    boost::timer t;
    double elapsed;
    t.restart();

    for (int loop = 0; loop < numMessages; loop++) {
      // Serialize
      std::string reply = AL::Serialization::serialize(request, type);
    }

    elapsed = t.elapsed();
    float msgPs = 1.0f / ((float)elapsed / (1.0f * numMessages) );
    float mgbPs = (msgPs * numBytes) / (1024 * 1024.0f);
    std::cout << numBytes << ", " << msgPs << ", " << mgbPs << std::endl;
  }
}

void testDeSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {

  std::cout << "Bytes, msg/s, MB/s" << std::endl;
  // loop message sizes 2^i bytes
  for (unsigned int i=1; i < 21; i++) {

    char character = 'A';
    unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string request = std::string(numBytes, character);

    boost::timer t;
    double elapsed;
    std::string buffer = AL::Serialization::serialize(request, type);

    t.restart();

    for (int loop = 0; loop < numMessages; loop++) {
      // Serialize
      std::string reply = AL::Serialization::deserialize<std::string>(buffer, type);
    }

    elapsed = t.elapsed();
    float msgPs = 1.0f / ((float)elapsed / (1.0f * numMessages) );
    float mgbPs = (msgPs * numBytes) / (1024 * 1024.0f);
    std::cout << numBytes << ", " << msgPs << ", " << mgbPs << std::endl;
  }
}

TEST(SerializationPerformance, DISABLED_binary) {
  //int numMessages = 10000;
  std::cout << " BINARY Serialization " << numMessages << std::endl;
  testSerialization_StringBufferSizes(BINARY, numMessages);
  std::cout << " BINARY DeSerialization " << numMessages << std::endl;
  testDeSerialization_StringBufferSizes(BINARY, numMessages);
}

TEST(SerializationPerformance, DISABLED_text) {
  //int numMessages = 10000;

  std::cout << " TEXT Serialization " << numMessages << std::endl;
  testSerialization_StringBufferSizes(TEXT, numMessages);
  std::cout << " TEXT DeSerialization " << numMessages << std::endl;
  testDeSerialization_StringBufferSizes(TEXT, numMessages);
}

TEST(SerializationPerformance, DISABLED_xml) {
  //int numMessages = 10000;

  std::cout << " XML Serialization " << numMessages << std::endl;
  testSerialization_StringBufferSizes(XML, numMessages);
  std::cout << " XML DeSerialization " << numMessages << std::endl;
  testDeSerialization_StringBufferSizes(XML, numMessages);

}
void testSerialization_vectorfloat(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {
  std::string str;
  std::vector<float> floats;
  floats.assign(26,1.1028284f);

  int numBytes = sizeof(float) * 26;

  //std::cout << "Vector<float> binary: " << numMessages << std::endl;
  //std::cout << "Bytes, msg/s, MB/s" << std::endl;
  boost::timer t;

  for( int i=0; i< numMessages; i++) {

    str = serialize(floats, type);
    std::vector<float>  rep = deserialize<std::vector<float> >(str, type);
  }

  double elapsed = t.elapsed();
  float msgPs = 1.0f / ((float)elapsed / (1.0f * numMessages) );
  float mgbPs = (msgPs * numBytes) / (1024 * 1024.0f);
  //std::cout << numBytes << ", " << msgPs << ", " << mgbPs << std::endl;
}

TEST(SerializationPerformance, vectorfloatBinary) {
  int numMessages = 1000;
  testSerialization_vectorfloat(BINARY,numMessages);
}

TEST(SerializationPerformance, vectorfloatText) {
  int numMessages = 1000;
  testSerialization_vectorfloat(TEXT,numMessages);
}

TEST(SerializationPerformance, vectorfloatXML) {
  int numMessages = 1000;
  testSerialization_vectorfloat(XML,numMessages);
}
<|endoftext|>


<commit_before>/**
 * \file
 * Copyright 2015 Benjamin Worpitz
 *
 * This file is part of alpaka.
 *
 * alpaka is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * alpaka is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with alpaka.
 * If not, see <http://www.gnu.org/licenses/>.
 */

// \Hack: Boost.MPL defines BOOST_MPL_CFG_GPU_ENABLED to __host__ __device__ if nvcc is used.
// BOOST_AUTO_TEST_CASE_TEMPLATE and its internals are not GPU enabled but is using boost::mpl::for_each internally.
// For each template parameter this leads to:
// /home/travis/build/boost/boost/mpl/for_each.hpp(78): warning: calling a __host__ function from a __host__ __device__ function is not allowed
// because boost::mpl::for_each has the BOOST_MPL_CFG_GPU_ENABLED attribute but the test internals are pure host methods.
// Because we do not use MPL within GPU code here, we can disable the MPL GPU support.
#define BOOST_MPL_CFG_GPU_ENABLED

#include <alpaka/alpaka.hpp>
#include <alpaka/test/acc/Acc.hpp>                  // alpaka::test::acc::TestAccs
#include <alpaka/test/stream/Stream.hpp>            // alpaka::test::stream::DefaultStream
#include <alpaka/test/KernelExecutionFixture.hpp>   // alpaka::test::KernelExecutionFixture

#include <boost/test/unit_test.hpp>

//#############################################################################
//!
//#############################################################################
class BlockSharedMemDyn
{
public:
    //-----------------------------------------------------------------------------
    //!
    //-----------------------------------------------------------------------------
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TAcc>
    ALPAKA_FN_ACC auto operator()(
        TAcc const & acc) const
    -> void
    {
        // Assure that the pointer is non null.
        auto && a = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);
        BOOST_REQUIRE_NE(static_cast<std::uint32_t *>(nullptr), a);

        // Each call should return the same pointer ...
        auto && b = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);
        BOOST_REQUIRE_EQUAL(a, b);

        // ... even for different types.
        auto && c = alpaka::block::shared::dyn::getMem<float>(acc);
        BOOST_REQUIRE_EQUAL(a, reinterpret_cast<std::uint32_t *>(c));
    }
};

namespace alpaka
{
    namespace kernel
    {
        namespace traits
        {
            //#############################################################################
            //! The trait for getting the size of the block shared dynamic memory for a kernel.
            //#############################################################################
            template<
                typename TAcc>
            struct BlockSharedMemDynSizeBytes<
                BlockSharedMemDyn,
                TAcc>
            {
                //-----------------------------------------------------------------------------
                //! \return The size of the shared memory allocated for a block.
                //-----------------------------------------------------------------------------
                template<
                    typename TVec>
                ALPAKA_FN_HOST static auto getBlockSharedMemDynSizeBytes(
                    BlockSharedMemDyn const & blockSharedMemDyn,
                    TVec const & blockThreadExtent,
                    TVec const & threadElemExtent)
                -> size::Size<TAcc>
                {
                    boost::ignore_unused(blockSharedMemDyn);
                    return sizeof(std::uint32_t) * blockThreadExtent.prod() * threadElemExtent.prod();
                }
            };
        }
    }
}

BOOST_AUTO_TEST_SUITE(blockSharedMemDyn)

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE_TEMPLATE(
    sameNonNullAdress,
    TAcc,
    alpaka::test::acc::TestAccs)
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Size = alpaka::size::Size<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::Vec<Dim, Size>::ones());

    BlockSharedMemDyn kernel;

    BOOST_REQUIRE_EQUAL(
        true,
        fixture(
            kernel));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>unify test kernel names<commit_after>/**
 * \file
 * Copyright 2015 Benjamin Worpitz
 *
 * This file is part of alpaka.
 *
 * alpaka is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * alpaka is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with alpaka.
 * If not, see <http://www.gnu.org/licenses/>.
 */

// \Hack: Boost.MPL defines BOOST_MPL_CFG_GPU_ENABLED to __host__ __device__ if nvcc is used.
// BOOST_AUTO_TEST_CASE_TEMPLATE and its internals are not GPU enabled but is using boost::mpl::for_each internally.
// For each template parameter this leads to:
// /home/travis/build/boost/boost/mpl/for_each.hpp(78): warning: calling a __host__ function from a __host__ __device__ function is not allowed
// because boost::mpl::for_each has the BOOST_MPL_CFG_GPU_ENABLED attribute but the test internals are pure host methods.
// Because we do not use MPL within GPU code here, we can disable the MPL GPU support.
#define BOOST_MPL_CFG_GPU_ENABLED

#include <alpaka/alpaka.hpp>
#include <alpaka/test/acc/Acc.hpp>                  // alpaka::test::acc::TestAccs
#include <alpaka/test/stream/Stream.hpp>            // alpaka::test::stream::DefaultStream
#include <alpaka/test/KernelExecutionFixture.hpp>   // alpaka::test::KernelExecutionFixture

#include <boost/test/unit_test.hpp>

//#############################################################################
//!
//#############################################################################
class BlockSharedMemDynTestKernel
{
public:
    //-----------------------------------------------------------------------------
    //!
    //-----------------------------------------------------------------------------
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TAcc>
    ALPAKA_FN_ACC auto operator()(
        TAcc const & acc) const
    -> void
    {
        // Assure that the pointer is non null.
        auto && a = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);
        BOOST_REQUIRE_NE(static_cast<std::uint32_t *>(nullptr), a);

        // Each call should return the same pointer ...
        auto && b = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);
        BOOST_REQUIRE_EQUAL(a, b);

        // ... even for different types.
        auto && c = alpaka::block::shared::dyn::getMem<float>(acc);
        BOOST_REQUIRE_EQUAL(a, reinterpret_cast<std::uint32_t *>(c));
    }
};

namespace alpaka
{
    namespace kernel
    {
        namespace traits
        {
            //#############################################################################
            //! The trait for getting the size of the block shared dynamic memory for a kernel.
            //#############################################################################
            template<
                typename TAcc>
            struct BlockSharedMemDynSizeBytes<
                BlockSharedMemDynTestKernel,
                TAcc>
            {
                //-----------------------------------------------------------------------------
                //! \return The size of the shared memory allocated for a block.
                //-----------------------------------------------------------------------------
                template<
                    typename TVec>
                ALPAKA_FN_HOST static auto getBlockSharedMemDynSizeBytes(
                    BlockSharedMemDynTestKernel const & blockSharedMemDyn,
                    TVec const & blockThreadExtent,
                    TVec const & threadElemExtent)
                -> size::Size<TAcc>
                {
                    boost::ignore_unused(blockSharedMemDyn);
                    return sizeof(std::uint32_t) * blockThreadExtent.prod() * threadElemExtent.prod();
                }
            };
        }
    }
}

BOOST_AUTO_TEST_SUITE(blockSharedMemDyn)

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE_TEMPLATE(
    sameNonNullAdress,
    TAcc,
    alpaka::test::acc::TestAccs)
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Size = alpaka::size::Size<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::Vec<Dim, Size>::ones());

    BlockSharedMemDynTestKernel kernel;

    BOOST_REQUIRE_EQUAL(
        true,
        fixture(
            kernel));
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include <stan/math/prim/scal.hpp>
#include <test/unit/math/prim/scal/prob/util.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <gtest/gtest.h>

TEST(ProbDistributionsVonMises, error_check) {
  boost::random::mt19937 rng;
  EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 2.0, rng));
  EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 0.0, rng));

  EXPECT_THROW(
      stan::math::von_mises_rng(stan::math::negative_infinity(), 2.0, rng),
      std::domain_error);
  EXPECT_THROW(
      stan::math::von_mises_rng(1, stan::math::positive_infinity(), rng),
      std::domain_error);
  EXPECT_THROW(stan::math::von_mises_rng(1, -3, rng), std::domain_error);
  EXPECT_NO_THROW(stan::math::von_mises_rng(2, 1, rng));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest1) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = 80;
  boost::math::chi_squared mydist(K - 1);

  double loc[]
      = {1.589032, 1.835082, 1.977091, 2.078807, 2.158994, 2.225759, 2.283346,
         2.334261, 2.380107, 2.421973, 2.460635, 2.496664, 2.530492, 2.562457,
         2.592827, 2.621819, 2.649609, 2.676346, 2.702153, 2.727137, 2.751389,
         2.774988, 2.798002, 2.820493, 2.842515, 2.864116, 2.885340, 2.906227,
         2.926814, 2.947132, 2.967214, 2.987089, 3.006782, 3.026321, 3.045728,
         3.065028, 3.084243, 3.103394, 3.122504, 3.141593, 3.160681, 3.179791,
         3.198942, 3.218157, 3.237457, 3.256865, 3.276403, 3.296097, 3.315971,
         3.336053, 3.356372, 3.376958, 3.397845, 3.419069, 3.440671, 3.462693,
         3.485184, 3.508198, 3.531796, 3.556048, 3.581032, 3.606840, 3.633576,
         3.661367, 3.690358, 3.720728, 3.752694, 3.786522, 3.822550, 3.861212,
         3.903079, 3.948925, 3.999839, 4.057427, 4.124191, 4.204379, 4.306094,
         4.448103, 4.694153};
  for (int i = 0; i < K - 1; i++)
    loc[i] = loc[i] - stan::math::pi();

  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }

  while (count < N) {
    double a = stan::math::von_mises_rng(0, 3.0, rng);
    int i = 0;
    while (i < K - 1 && a > loc[i])
      ++i;
    ++bin[i];
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++) {
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  }

  EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest2) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = 80;
  boost::math::chi_squared mydist(K - 1);

  double loc[]
      = {1.5890, 1.8351, 1.9771, 2.0788, 2.1590, 2.2258, 2.2833, 2.3343, 2.3801,
         2.4220, 2.4606, 2.4967, 2.5305, 2.5625, 2.5928, 2.6218, 2.6496, 2.6763,
         2.7022, 2.7271, 2.7514, 2.7750, 2.7980, 2.8205, 2.8425, 2.8641, 2.8853,
         2.9062, 2.9268, 2.9471, 2.9672, 2.9871, 3.0068, 3.0263, 3.0457, 3.0650,
         3.0842, 3.1034, 3.1225, 3.1416, 3.1607, 3.1798, 3.1989, 3.2182, 3.2375,
         3.2569, 3.2764, 3.2961, 3.3160, 3.3361, 3.3564, 3.3770, 3.3978, 3.4191,
         3.4407, 3.4627, 3.4852, 3.5082, 3.5318, 3.5560, 3.5810, 3.6068, 3.6336,
         3.6614, 3.6904, 3.7207, 3.7527, 3.7865, 3.8226, 3.8612, 3.9031, 3.9489,
         3.9998, 4.0574, 4.1242, 4.2044, 4.3061, 4.4481, 4.6942};

  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }

  while (count < N) {
    double a = stan::math::von_mises_rng(11 * 3.14, 3.0, rng);
    int i = 0;
    while (i < K - 1 && a > loc[i])
      ++i;
    ++bin[i];
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++) {
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  }

  EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest3) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = 80;
  boost::math::chi_squared mydist(K - 1);

  double loc[] = {
      -0.552560, -0.306511, -0.164502, -0.062786, 0.017401, 0.084166, 0.141753,
      0.192668,  0.238514,  0.280381,  0.319043,  0.355071, 0.388899, 0.420864,
      0.451235,  0.480226,  0.508016,  0.534753,  0.560560, 0.585545, 0.609796,
      0.633395,  0.656409,  0.678900,  0.700922,  0.722523, 0.743748, 0.764635,
      0.785221,  0.805540,  0.825622,  0.845496,  0.865190, 0.884728, 0.904136,
      0.923435,  0.942650,  0.961802,  0.980911,  1.000000, 1.019089, 1.038198,
      1.057350,  1.076565,  1.095864,  1.115272,  1.134810, 1.154504, 1.174378,
      1.194460,  1.214779,  1.235365,  1.256252,  1.277477, 1.299078, 1.321100,
      1.343591,  1.366605,  1.390204,  1.414455,  1.439440, 1.465247, 1.491984,
      1.519774,  1.548765,  1.579136,  1.611101,  1.644929, 1.680957, 1.719619,
      1.761486,  1.807332,  1.858247,  1.915834,  1.982599, 2.062786, 2.164502,
      2.306511,  2.552560};
  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }

  while (count < N) {
    double a = stan::math::von_mises_rng(-17.85, 3.0, rng);
    int i = 0;
    while (i < K - 1 && a > loc[i])
      ++i;
    ++bin[i];
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++) {
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  }

  EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest4) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = stan::math::round(2 * std::pow(N, 0.4));

  std::vector<double> samples;
  for (int i = 0; i < N; ++i) {
    samples.push_back(stan::math::von_mises_rng(stan::math::pi(), 0.0, rng));
  }

  std::vector<double> quantiles;
  for (int i = 1; i <= K; ++i) {
    double frac = static_cast<double>(i) * stan::math::TWO_PI / K;
    quantiles.push_back(0.0 + frac);
  }

  assert_matches_quantiles(samples, quantiles, 1e-6);
}
<commit_msg>Fix cpplint<commit_after>#include <stan/math/prim/scal.hpp>
#include <test/unit/math/prim/scal/prob/util.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(ProbDistributionsVonMises, error_check) {
  boost::random::mt19937 rng;
  EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 2.0, rng));
  EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 0.0, rng));

  EXPECT_THROW(
      stan::math::von_mises_rng(stan::math::negative_infinity(), 2.0, rng),
      std::domain_error);
  EXPECT_THROW(
      stan::math::von_mises_rng(1, stan::math::positive_infinity(), rng),
      std::domain_error);
  EXPECT_THROW(stan::math::von_mises_rng(1, -3, rng), std::domain_error);
  EXPECT_NO_THROW(stan::math::von_mises_rng(2, 1, rng));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest1) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = 80;
  boost::math::chi_squared mydist(K - 1);

  double loc[]
      = {1.589032, 1.835082, 1.977091, 2.078807, 2.158994, 2.225759, 2.283346,
         2.334261, 2.380107, 2.421973, 2.460635, 2.496664, 2.530492, 2.562457,
         2.592827, 2.621819, 2.649609, 2.676346, 2.702153, 2.727137, 2.751389,
         2.774988, 2.798002, 2.820493, 2.842515, 2.864116, 2.885340, 2.906227,
         2.926814, 2.947132, 2.967214, 2.987089, 3.006782, 3.026321, 3.045728,
         3.065028, 3.084243, 3.103394, 3.122504, 3.141593, 3.160681, 3.179791,
         3.198942, 3.218157, 3.237457, 3.256865, 3.276403, 3.296097, 3.315971,
         3.336053, 3.356372, 3.376958, 3.397845, 3.419069, 3.440671, 3.462693,
         3.485184, 3.508198, 3.531796, 3.556048, 3.581032, 3.606840, 3.633576,
         3.661367, 3.690358, 3.720728, 3.752694, 3.786522, 3.822550, 3.861212,
         3.903079, 3.948925, 3.999839, 4.057427, 4.124191, 4.204379, 4.306094,
         4.448103, 4.694153};
  for (int i = 0; i < K - 1; i++)
    loc[i] = loc[i] - stan::math::pi();

  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }

  while (count < N) {
    double a = stan::math::von_mises_rng(0, 3.0, rng);
    int i = 0;
    while (i < K - 1 && a > loc[i])
      ++i;
    ++bin[i];
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++) {
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  }

  EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest2) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = 80;
  boost::math::chi_squared mydist(K - 1);

  double loc[]
      = {1.5890, 1.8351, 1.9771, 2.0788, 2.1590, 2.2258, 2.2833, 2.3343, 2.3801,
         2.4220, 2.4606, 2.4967, 2.5305, 2.5625, 2.5928, 2.6218, 2.6496, 2.6763,
         2.7022, 2.7271, 2.7514, 2.7750, 2.7980, 2.8205, 2.8425, 2.8641, 2.8853,
         2.9062, 2.9268, 2.9471, 2.9672, 2.9871, 3.0068, 3.0263, 3.0457, 3.0650,
         3.0842, 3.1034, 3.1225, 3.1416, 3.1607, 3.1798, 3.1989, 3.2182, 3.2375,
         3.2569, 3.2764, 3.2961, 3.3160, 3.3361, 3.3564, 3.3770, 3.3978, 3.4191,
         3.4407, 3.4627, 3.4852, 3.5082, 3.5318, 3.5560, 3.5810, 3.6068, 3.6336,
         3.6614, 3.6904, 3.7207, 3.7527, 3.7865, 3.8226, 3.8612, 3.9031, 3.9489,
         3.9998, 4.0574, 4.1242, 4.2044, 4.3061, 4.4481, 4.6942};

  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }

  while (count < N) {
    double a = stan::math::von_mises_rng(11 * 3.14, 3.0, rng);
    int i = 0;
    while (i < K - 1 && a > loc[i])
      ++i;
    ++bin[i];
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++) {
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  }

  EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest3) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = 80;
  boost::math::chi_squared mydist(K - 1);

  double loc[] = {
      -0.552560, -0.306511, -0.164502, -0.062786, 0.017401, 0.084166, 0.141753,
      0.192668,  0.238514,  0.280381,  0.319043,  0.355071, 0.388899, 0.420864,
      0.451235,  0.480226,  0.508016,  0.534753,  0.560560, 0.585545, 0.609796,
      0.633395,  0.656409,  0.678900,  0.700922,  0.722523, 0.743748, 0.764635,
      0.785221,  0.805540,  0.825622,  0.845496,  0.865190, 0.884728, 0.904136,
      0.923435,  0.942650,  0.961802,  0.980911,  1.000000, 1.019089, 1.038198,
      1.057350,  1.076565,  1.095864,  1.115272,  1.134810, 1.154504, 1.174378,
      1.194460,  1.214779,  1.235365,  1.256252,  1.277477, 1.299078, 1.321100,
      1.343591,  1.366605,  1.390204,  1.414455,  1.439440, 1.465247, 1.491984,
      1.519774,  1.548765,  1.579136,  1.611101,  1.644929, 1.680957, 1.719619,
      1.761486,  1.807332,  1.858247,  1.915834,  1.982599, 2.062786, 2.164502,
      2.306511,  2.552560};
  int count = 0;
  int bin[K];
  double expect[K];
  for (int i = 0; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }

  while (count < N) {
    double a = stan::math::von_mises_rng(-17.85, 3.0, rng);
    int i = 0;
    while (i < K - 1 && a > loc[i])
      ++i;
    ++bin[i];
    count++;
  }

  double chi = 0;

  for (int j = 0; j < K; j++) {
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
  }

  EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));
}

TEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest4) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = stan::math::round(2 * std::pow(N, 0.4));

  std::vector<double> samples;
  for (int i = 0; i < N; ++i) {
    samples.push_back(stan::math::von_mises_rng(stan::math::pi(), 0.0, rng));
  }

  std::vector<double> quantiles;
  for (int i = 1; i <= K; ++i) {
    double frac = static_cast<double>(i) * stan::math::TWO_PI / K;
    quantiles.push_back(0.0 + frac);
  }

  assert_matches_quantiles(samples, quantiles, 1e-6);
}
<|endoftext|>


<commit_before><commit_msg>error C2666: 'operator ==' : 2 overloads have similar conversions<commit_after><|endoftext|>