/**
	Method to open in write mode the file with given name and path
	@param file: file stream to open
	@param filePath: path to the file to open
	@param fileName: name of the path to open
*/
void BasicGenerator::openFile(ofstream &file, const string &filePath, const string &fileName)
{
	string fileFullName=filePath+fileName;
	file.open(fileFullName.c_str(), ios::out);
}
Exemplo n.º 2
0
int main()
{
	srand(time(0));

	HWND console = GetConsoleWindow();
	RECT r;
	GetWindowRect(console, &r);
	MoveWindow(console, r.left, 100, (w_*72) + 100, 250 + (h_*72), TRUE);

	//HWND hwnd = GetConsoleWindow();
	//if (hwnd != NULL) { MoveWindow(hwnd, 340, 550, 680, 150, TRUE); }

	#ifdef _DEBUG
		debug.open("debug.txt");
		if (debug.fail())
			cout << "Failed to open debug stream";
	#endif


	int board[h_][w_];				//the main board
	bool newGame = true;			//whether to start a new game
	int endOfGame;					//6 = yes, 7 = no
	int rowPlayed = 0;				//stores the row in which the last disc was played
	int colPlayed = 0;				//stores the column in which the last disc was played
	int whosTurn;					//keeps track of who's turn it is (1 = player1/human, 2 = player2/computer)
	int turn;						//keeps track of how mant discs have been played
	int MAX_DEPTH;					//max depth of recursion for minimax
	int winner = 0;					//winner at end of game
	int cutCount;					//number of terminal nodes cut
	clock_t t;						//CPU time temp variable
	double timeElapsed;				//CPU time for computer's turn
	double totalTime;
	double averageTime;				//average CPU time per computer turn
	double averageTimeAfter4;		//average CPU time per turn not counting turns 1-4
	int averageCutCount;


	while (newGame)
	{
		boardInit(board);
		system("cls");
		whosTurn = preGame();
		//whosTurn = cDisc;
		printScreen(board);
		MAX_DEPTH = TYPICAL_DEPTH;
		averageTime = 0;
		averageTimeAfter4 = 0;
		totalTime = 0;
		averageCutCount = 0;

		turn = 0;

		while (turn < w_*h_)
		{
			if (MAX_DEPTH > w_*h_ - turn) MAX_DEPTH = w_*h_ - turn;
			else MAX_DEPTH = TYPICAL_DEPTH;

			if (whosTurn == 1) //player's turn
			{
				playerTurn(board, rowPlayed, colPlayed);
				printScreen(board);
				if (winDetect(board, rowPlayed, colPlayed, pDisc))
				{
					winner = 1;
					break;
				}
			}

			else if (whosTurn == 2) //computer's turn
			{
				cutCount = 0;
				t = clock(); //start timer
				compTurn(board, rowPlayed, colPlayed, turn, MAX_DEPTH, cutCount);
				t = clock() - t;
				timeElapsed = (double)t/CLOCKS_PER_SEC;
				averageTime += timeElapsed;
				if (turn > 3) averageTimeAfter4 += timeElapsed;
				printScreen(board);
				averageCutCount += cutCount;

				if (TIME_STATS)
				{
					cout << "This Turn:\t\t" << timeElapsed << endl;
					cout << "Average Time:\t\t" << averageTime / (turn + 1) << endl;
					cout << "Average After 4:\t" << averageTimeAfter4 / (turn - 3) << endl;
					cout << "Cut Count:\t\t" << averageCutCount / (turn + 1) << endl;
					cout << "Turn: \t\t\t" << turn + 1 << endl;
				}

				Sleep(1500); //user friendly delay
				cout << "COMPUTER PLAYED: ";
				printColor(colPlayed+1, GAME_COLOR);
				cout << "\n\n";

				//cout << "CutCount: " << cutCount << "\n\n";

				#ifdef _AB_DEBUG
					cout << "CutCount: " << cutCount << "\n\n";
				#endif

				if (winDetect(board, rowPlayed, colPlayed, cDisc))
				{
					winner = 2;
					break;
				}
				//Sleep(1000);			
			}

			if (whosTurn == 1) whosTurn = 2;
			else whosTurn = 1;

			turn++;
			if (turn >= w_*h_) break;
		}

		//Displaying an end game message box
		switch (winner)
		{
		case 0:
			endOfGame = MessageBox(NULL, TEXT("Cat's Game!\n\nPlay again?"), TEXT("End of Game"), MB_YESNO);
			break;

		case 1:
			endOfGame = MessageBox(NULL, TEXT("You Win!\n\nPlay again?"), TEXT("End of Game"), MB_YESNO);
			break;

		case 2:
			endOfGame = MessageBox(NULL, TEXT("The Computer Wins!\n\nPlay again?"), TEXT("End of Game"), MB_YESNO);
			break;
		}

		if (endOfGame == 6) newGame = true;
		else if (endOfGame == 7) newGame = false;
		else newGame = false;
	}

	printBoard(board);
	return 0;
}
int main() {
  /* CSS GENERATOR - BEGIN */
  tobeprinted.clear();
  tobeprinted += "/*!\n";
  tobeprinted += "* Viewport v" + VERSION +  " (" + REPO + ")\n";
  tobeprinted += "* Copyright 2015 Simone Primarosa. (" + PROFILE + ")\n";
  tobeprinted += "* Licensed under GNU General Public License version 3.0 (http://www.gnu.org/licenses/gpl-3.0.html)\n";
  tobeprinted += "*/\n";
  tobeprinted += "/*! " + FILENAME + ".css v" + VERSION + " | GNU GPL | " + FOLDER + FILENAME + ".css */\n\n";

  tobeprinted += ".vh-test, .vw-test, .vmin-test, .vmax-test {position:fixed;z-index:-999999;height:1px; width:1px; overflow:hidden;}\n";
  tobeprinted += ".vh-test {height: 100vh;} .vw-test {height: 100vw;} .vmin-test {height: 100vmin;} .vmax-test {height: 100vmax;}\n";
  tobeprinted += ".vu-oveflow {overflow: hidden !important;}\n\n";

  for(vector<string>::iterator vt = viewtype.begin(); vt != viewtype.end(); vt++) {
		for(vector<string>::iterator pr = property.begin(); pr != property.end(); pr++) {
			for(int i = 0; i < list_name.size(); i++) {
        tobeprinted += "[" + *vt + "-" + *pr + " = \"" + list_name[i] + "\"] {" + *pr + ":" + to_str(list_value[i]) + *vt + ";}\n";
      }
    }
    tobeprinted += "\n";
  }
  for(int v = 0; v < viewtype.size(); v++) {
	  for(int k = 128; k <= 2560; k *= 2) {
			if(v < 2) tobeprinted += "@media " + media[v] + to_str(k) + "px) {\n";
			else tobeprinted += "@media " + media[v] + to_str(k) + "px), " + media[v+2] + to_str(k) + "px) {\n";
			for(vector<string>::iterator pr = property.begin(); pr != property.end(); pr++) {
			  for(int i = 0; i < list_name.size(); i++) {
				  tobeprinted += "  .no-viewport [" + viewtype[v] + "-" + *pr + " = \"" + list_name[i] + "\"] {" + *pr + ":" + to_str(list_value[i]*(k*2/100.0)) + "px;}\n";
				}
			}
			tobeprinted += "}\n";
		}
	}
  fout.open(FILENAME+".css");
  fout<<tobeprinted;
  fout.close();
  fout.open(FILENAME+".min.css");
  fout<<doMinify(tobeprinted, false);
  fout.close();
  /* CSS GENERATOR - END */

  /* JS GENERATOR - BEGIN */
  tobeprinted.clear();
  tobeprinted += "/*!\n";
  tobeprinted += "* Viewport v" + VERSION +  " (" + REPO + ")\n";
  tobeprinted += "* Copyright 2015 Simone Primarosa. (" + PROFILE + ")\n";
  tobeprinted += "* Licensed under GNU General Public License version 3.0 (http://www.gnu.org/licenses/gpl-3.0.html)\n";
  tobeprinted += "*/\n";
  tobeprinted += "/*! " + FILENAME + ".js v" + VERSION + " | GNU GPL | " + FOLDER + FILENAME + ".js */\n\n";

  tobeprinted += "(function($) {\n";
  tobeprinted += "\"use strict\";\n";
  tobeprinted += "$(window).ready(function() {\n\n";

  for(vector<string>::iterator vt = viewtype.begin(); vt != viewtype.end(); vt++) {
    tobeprinted += "    var " + *vt + "_" + "need = false;\n";
  }
  tobeprinted += "\n";

  tobeprinted += "    function viewport_init() {\n";
  tobeprinted += "      var deviceAgent = navigator.userAgent.toLowerCase();\n";
  tobeprinted += "      var oldIOS = (/ip(ad|hone|od).*os 3_/.test(deviceAgent) || /ip(ad|hone|od).*os 4_/.test(deviceAgent) || /ip(ad|hone|od).*os 5_/.test(deviceAgent) || /ip(ad|hone|od).*os 6_/.test(deviceAgent) || /ip(ad|hone|od).*os 7_/.test(deviceAgent));\n";
  tobeprinted += "      if(oldIOS) {\n";
	for(vector<string>::iterator vt = viewtype.begin(); vt != viewtype.end(); vt++) {
    tobeprinted += "        " + *vt + "_" + "need = false;\n";
  }
	tobeprinted += "        return;\n";
	tobeprinted += "      }\n";
  tobeprinted += "      var html = $(\"html\");\n";
  tobeprinted += "      html.removeClass(\"no-viewport\");\n";
  tobeprinted += "      html.addClass(\"vu-overflow\");\n";
  for(int i = 0; i < viewtype.size(); i++) {
    tobeprinted += "      var " + viewtype[i] + "_test = " + "$(\"<div class='" + viewtype[i] + "-test'></div>\").appendTo(html);\n";
    tobeprinted += "      var " + viewtype[i] + "_calc = (" + viewtype[i] + "_test).height() - " + functions[i] + ";\n";
    tobeprinted += "      " + viewtype[i] + "_" + "need = (" + viewtype[i] + "_calc >= -1 && " + viewtype[i] + "_calc <= 1) ? false : true;\n";
    tobeprinted += "      " + viewtype[i] + "_test.remove();\n";
    //tobeprinted += "      console.log(" + viewtype[i] + "_calc + ' ' + (" + viewtype[i] + "_test).height() + ' ' + " + function[i] + ");\n";
    tobeprinted += "      if(" + viewtype[i] + "_" + "need == true) {\n";
    for(int j = 0; j < property.size(); j++) {
      tobeprinted += "        window." + viewtype[i] + "_" + noDash(property[j]) + " = " + "$(\"[" + viewtype[i] + "-" + property[j] + "]\");\n";
    }
    tobeprinted += "      }\n";
  }
  tobeprinted += "      html.removeClass(\"vu-overflow\");\n";
  tobeprinted += "    }\n";

  tobeprinted += "    function viewport_exec() {\n";
  tobeprinted += "      var html = $(\"html\");\n";
  tobeprinted += "      html.addClass(\"vu-overflow\");\n";
  for(int i = 0; i < viewtype.size(); i++) {
    tobeprinted += "      if(" + viewtype[i] + "_" + "need == true) {\n";
    tobeprinted += "        var " + viewtype[i] + "_value = " + functions[i] + "/100;\n";
    for(int j = 0; j < property.size(); j++) {
      tobeprinted += "        window." + viewtype[i] + "_" + noDash(property[j]) + ".each(function() {$(this).css(\"" + property[j] + "\", " + "$(this).attr(\"" + viewtype[i] + "-" + property[j] + "\") * " + viewtype[i] + "_value" + ");});\n";
    }
    tobeprinted += "      }\n";
  }
  tobeprinted += "      html.removeClass(\"vu-overflow\");\n";
  tobeprinted += "    }\n";

  tobeprinted += "    viewport_init();\n    viewport_exec();\n    $(window).resize(function() { viewport_exec(); });\n  });\n\n";
  tobeprinted += "})(jQuery);";

  fout.open(FILENAME+".js");
  fout<<tobeprinted;
  fout.close();
  fout.open(FILENAME+".min.js");
  fout<<doMinify(tobeprinted, true);
  fout.close();
  /* JS GENERATOR - END */
  return 0;
}
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
  cerr << "PhraseStatistics v1.1 written by Nicola Bertoldi\n"
       << "modifying PhraseScore v1.4 written by Philipp Koehn\n"
       << "It computes statistics for extracted phrase pairs\n"
       << "if (direct):\n"
       << "src_phrase ||| trg_phrase || freq(src_phrase, trg_phrase) freq(src_phrase) length(src_phrase) length(trg_phrase)\n"
       << "if (inverse)\n"
       << "src_phrase ||| trg_phrase || freq(src_phrase, trg_phrase) freq(trg_phrase) length(src_phrase) length(trg_phrase)\n";

  if (argc != 4 && argc != 5) {
    cerr << "syntax: statistics extract lex phrase-table [inverse]\n";
    exit(1);
  }
  char* &fileNameExtract = argv[1];
  char* &fileNameLex = argv[2];
  char* &fileNamePhraseTable = argv[3];
  inverseFlag = false;
  if (argc > 4) {
    inverseFlag = true;
    cerr << "using inverse mode\n";
  }

  // lexical translation table
  lexTable.load( fileNameLex );

  // sorted phrase extraction file
  Moses::InputFileStream extractFile(fileNameExtract);

  if (extractFile.fail()) {
    cerr << "ERROR: could not open extract file " << fileNameExtract << endl;
    exit(1);
  }
  istream &extractFileP = extractFile;

  // output file: phrase translation table
  phraseTableFile.open(fileNamePhraseTable);
  if (phraseTableFile.fail()) {
    cerr << "ERROR: could not open file phrase table file "
         << fileNamePhraseTable << endl;
    exit(1);
  }

  // loop through all extracted phrase translations
  int lastForeign = -1;
  vector< PhraseAlignment > phrasePairsWithSameF;
  int i=0;

  string line;
  while(getline(extractFileP, line)) {
    if (extractFileP.eof()) break;
    if (++i % 100000 == 0) cerr << "." << flush;

    PhraseAlignment phrasePair;
    bool isPhrasePair = phrasePair.create( line.c_str(), i );
    if (lastForeign >= 0 && lastForeign != phrasePair.foreign) {
      processPhrasePairs( phrasePairsWithSameF );
      for(size_t j=0; j<phrasePairsWithSameF.size(); j++)
        phrasePairsWithSameF[j].clear();
      phrasePairsWithSameF.clear();
      phraseTableE.clear();
      phraseTableF.clear();
      phrasePair.clear(); // process line again, since phrase tables flushed
      phrasePair.create( line.c_str(), i );
      phrasePairBase = 0;
    }
    lastForeign = phrasePair.foreign;
    if (isPhrasePair)
      phrasePairsWithSameF.push_back( phrasePair );
    else
      phrasePairBase++;
  }
  processPhrasePairs( phrasePairsWithSameF );
  phraseTableFile.close();
}
Exemplo n.º 5
0
/*Main{{{*/
Int_t main()
{ 
    gStyle->SetOptFit(1);  
    gStyle->SetOptStat(0);

    Int_t iType = 0;
    cout<<"--- Which file ? (1->simple, 2->mult, 3->mult_fsi, 4->fermi, 5->mult_nofermi)  "; cin >> iType;
    if(iType==1) type_name = "simple"; 
    if(iType==2) type_name = "mult"; 
    if(iType==3) type_name = "mult_fsi"; 
    if(iType==4) type_name = "fermi"; 
    if(iType==5) type_name = "mult_nofermi"; 

    Int_t bin_type = 0;
    cout<<"--- Which Bining? (1->t, 2->tp, 3->log(tp) )"; cin>> bin_type;
    if(bin_type==1) bin_name ="t";
    if(bin_type==2) bin_name ="tp";
    if(bin_type==3) bin_name ="logtp";

    int BINS = 0;
    if(bin_type==1) {BINS= 7;}
    if(bin_type==2) {BINS= 9;}
    if(bin_type==3) {BINS= 10;}

    ifstream inputf; 
    inputf.open(Form("../asym_extr/results_may9/%s_dvmp_par_%s_%s.dat",bin_name.Data(), type_name.Data(), fit_pars.Data()));
    TString com;
    double temp;
    int t_bin, Q2_bin;
    inputf>>com>>com>>com>>com>>com
          >>com>>com>>com>>com>>com
          >>com>>com>>com>>com>>com
          >>com>>com>>com>>com>>com
          >>com>>com>>com>>com>>com>>com>>com;
    for(int i=1; i<=BINS;i++){
        for(int j=0; j<1;j++){

            cout<<Form("--- working on IT = %d, IQ = %d", i,j)<<endl;
            inputf >> t_bin >> Q2_bin
                >> asym_1m1_avg>> asym_1m1_fit>> asym_1m1_err
                >> asym_0p1_avg>> asym_0p1_fit>> asym_0p1_err
                >> asym_2m1_avg>> asym_2m1_fit>> asym_2m1_err
                >> asym_3m1_avg>> asym_3m1_fit>> asym_3m1_err
                >> asym_1p1_avg>> asym_1p1_fit>> asym_1p1_err
                >> temp >> temp >> Asym >> Astat
                >> t_avg >> tp_avg >> xb_avg >> Q2_avg >> W_avg >> dilute_avg;

            if(i!=t_bin || j!=Q2_bin){
               cout<<Form("Something wrong?!  T=%d/%d,  Q=%d/%d", i, t_bin, j, Q2_bin)<<endl;
            
            }

            outf.open(Form("./database/BIN_%s_dvmp_par_%s_%s_%d_%d.dat",bin_name.Data(), type_name.Data(), fit_pars.Data(),i,j));
            outf<<Form("%4s %4s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s",
                    "#t", "#Q2", 
                    "A1M1_AVG", "A_1M1", "dA_1M1", 
                    "A0P1_AVG", "A_0P1", "dA_0P1", 
                    "A2M1_AVG", "A_2M1", "dA_2M1", 
                    "A3M1_AVG", "A_3M1", "dA_3M1", 
                    "A1P1_AVG", "A_1P1", "dA_1P1",
                    "Asym", "Astat",
                    "t", "tp","xb", "Q2", "W", "Dilute"
                    )
                <<endl;

            outf<<Form("%4d %4d %10.3e %10.3e %10.4e %10.3e %10.3e %10.4e %10.3e %10.3e %10.4e %10.3e %10.3e %10.4e %10.3e %10.3e %10.4e %10.4e %10.4e %10.4e %10.4e %10.4e %10.4e %10.4e %10.4e",
                    i, j, 
                    asym_1m1_avg, asym_1m1_fit, asym_1m1_err,
                    asym_0p1_avg, asym_0p1_fit, asym_0p1_err,
                    asym_2m1_avg, asym_2m1_fit, asym_2m1_err,
                    asym_3m1_avg, asym_3m1_fit, asym_3m1_err,
                    asym_1p1_avg, asym_1p1_fit, asym_1p1_err,
                    Asym, Astat,
                    t_avg, tp_avg, xb_avg, Q2_avg, W_avg, dilute_avg 
                    )
                <<endl;

            outf <<Form("%6s %6s %12s %12s %12s %12s %12s %12s %12s %12s %12s %12s %12s %12s",
                    "Phi", "PhiS",
                    "N_U_avg", "N_D_avg", "Asym_avg","dAsym_avg",
                    "N_U_fit", "N_D_fit", "Asym_fit","dAsym_fit",
                    "Asym_cal","dAsym_cal",
                    "GOOD_fit", "GOOD_cal"
                    )<<endl;

            /////////////////////////////
            //Load Data from MC Rootfiles to bin on phi and phiS
            /////////////////////////////
            LoadData(i, j);
            outf.close();
        }
    }
    return 0;
}
Exemplo n.º 6
0
Application::Application(int argc,char **argv)
{
    app = this;

    init();

    // Process the command line options
    // These override anything in the configuration file, default or specified
    int longIndex;
    int c;
    string RINEXHeaderFile("");

    while ((c=getopt_long(argc,argv,"hm:",longOptions,&longIndex)) != -1)
    {
        switch(c)
        {
        case 0: // long options
        {
            switch (longIndex)
            {
            case 0:
                configurationFile=optarg;
                break;

            case 1:
                counterPath=optarg;
                break;

            case 2:
                //CGGTSComment=optarg;
                break;
            case 3:
            {
                string dbgout = optarg;
                if ((string::npos != dbgout.find("stderr"))) {
                    debugStream = & std::cerr;
                }
                else {
                    debugFileName = dbgout;
                    debugLog.open(debugFileName.c_str(),ios_base::app);
                    if (!debugLog.is_open()) {
                        cerr << "Unable to open " << dbgout << endl;
                        exit(EXIT_FAILURE);
                    }
                    debugStream = & debugLog;
                }
                break;
            }
            case 4:
                TICenabled=false;
                break;
            case 5:
                showHelp();
                exit(EXIT_SUCCESS);
                break;

            case 6:
                generateNavigationFile=false;
                break;

            case 7:
                receiverPath=optarg;
                break;

            case 8:
            {
                if (1!=sscanf(optarg,"%i",&verbosity)) {
                    cerr << "Bad value for option --verbosity" << endl;
                    showHelp();
                    exit(EXIT_FAILURE);
                }
            }
            break;
            case 9:
                timingDiagnosticsOn=true;
                break;

            case 10:
                showVersion();
                exit(EXIT_SUCCESS);
                break;
            case 11:
                SVDiagnosticsOn=true;
                break;
            case 12:
                shortDebugMessage=true;
                break;
            }
        }
        break;
        case 'h':
            showHelp();
            exit(EXIT_SUCCESS);
            break;
        case 'm':
        {
            if (1!=sscanf(optarg,"%i",&MJD)) {
                cerr << "Bad value for option --mjd" << endl;
                showHelp();
                exit(EXIT_FAILURE);
            }
        }
        break;
        default:
            break;

        }
    }


    if (!loadConfig()) {
        cerr << "Configuration failed - exiting" << endl;
        exit(EXIT_FAILURE);
    }

    // Note: can't get any debugging output until the command line is parsed !

}
Exemplo n.º 7
0
/* Movement of the paddles that is correlated in space and in time
 * This method currently operates on a time-schedule of 1 new correlation computation to the grid every 0.1 seconds.
 * In principle, this can be easily modified to separate the time-scale of the grid from the time-scale of the correlations
 *  (e.g. by running one correlation every 0.5 seconds but still sending angles to the grid every 0.1 seconds). The current schedule
 *  gives the highest rate of correlation computations we can handle, given the nature of the runcorr_3D algorithm and our current computers.
 * We define the term "constraining" as the occasion when a paddle is given a new angle to move to that it cannot reach without exceeding the
 *  limits of its servo (e.g. an amplitude of 60 degrees when the maximum angular distance it can travel in 0.1 seconds is 42.8 degrees). Such
 *  noncompliant paddles will be "constrained" to move at the greatest allowed servo speed (e.g. 4.28 deg/s instead of 6 deg/s) and thus will
 *  not reach their target destinations. This was a necessary comprimise in order to maximize the grid's correlation computation rate.
 */
int correlatedMovement_correlatedInTime(int constantArea, float spatial_sigma, float temporal_sigma, float spatial_alpha, float temporal_alpha, float spatial_height, float temporal_height, int typeOfSpatialCorr, int typeOfTemporalCorr, float target_rms, int numberOfSlices){

    /* To install mySignalHandler (which prints statistics when you type CTRL-C)
    you must make sure that CTRL-C signals are not blocked.
    If you are having problems with the signal handler (i.e. CTRL-C signals are blocked)
    you can just comment out the following block and the block after this one where the signal handler is actually installed.*/
    void (*pfRet)(int);
    sigset_t sSet;
    int iRet;
    iRet = sigemptyset(&sSet);
    if (iRet == -1) {perror("ERROR installing signal handler in correlatedMovement_correlatedInTime"); exit(EXIT_FAILURE); }
    iRet = sigaddset(&sSet, SIGINT);
    if (iRet == -1) {perror("ERROR installing signal handler in correlatedMovement_correlatedInTime"); exit(EXIT_FAILURE); }
    iRet = sigprocmask(SIG_UNBLOCK, &sSet, NULL);
    if (iRet == -1) {perror("ERROR installing signal handler in correlatedMovement_correlatedInTime"); exit(EXIT_FAILURE); }
    
    // Install mySignalHandler as the handler for CTRL-C signals.
    pfRet = signal(SIGINT, mySignalHandler);
    if (pfRet == SIG_ERR) {perror("error installing signal handler in correlatedMovement_correlatedInTime"); exit(EXIT_FAILURE); }

    // special method selection (for slow or unconventional kernels that need to be inlined)
    bool ltfast_on = false;
    bool unsharp_on = false;
    if (typeOfSpatialCorr == 8 && typeOfTemporalCorr == 8) {
        cout << "\n***********************************\n";
        cout << "*      Running ltfast method      *";
        cout << "\n***********************************" << endl;
        ltfast_on = true;
    }
    if (typeOfSpatialCorr == 10 && typeOfTemporalCorr == 10) {
        cout << "\n************************************\n";
        cout << "*      Running double unsharp      *";
        cout << "\n************************************" << endl;
        unsharp_on = true;
    }
    // NOTE: if you're interested, you could re-implement true top hats by inlining them here as well
    
    // UI to avoid accidentally overwriting angle files
    ifstream ifile("angleservo_cM_cIT.txt");
    int overwriteFile;
    if (ifile) {
        cout << "WARNING: An angle file for this program already exists. 1: continue and overwrite file, 0: kill program" << endl;
        cin >> overwriteFile;
        if (!overwriteFile)
            exit(0);
    }
    
    anglefile.open("angleservo_cM_cIT.txt", ios::out | ios::trunc); // file to plot angles in function of time
    
    // create (bake?) Loaf object using constructor
    loaf freshLoaf = loaf(numberOfSlices);
    
    float oldslice[13][11] = {{0}}; // stores the last configuration of paddles that was sent to the grid
    float step_size[13][11] = {{0}}; // stores the step size needed to get to the next configuration
    float newslice[13][11] = {{0}}; // stores the step size needed to get to the next configuration
    
    float rms;
    float correction = 1;
    int i = 1; // grid number counter
    int SPACING = 1; // number of interpolations needed to keep servo speed under its max value, in worst case
    
    float amplitude; // for steps/speeds calculations and safety checks, below
    float diff; // difference between two doubles (used with epsilon in place of == operator, which doesn't perform well on doubles)
    float EPSILON = 0.1; // error tolerance for double comparisons (just be within a tenth of a degree)
    int halfLoaf = numberOfSlices / (int) 2; // determine where to set middle slice of loaf (assumes numberOfSlices is odd)
    
    // Normalization calculations (complicated because different correlation functions have different methods for normalization)
    norm = 0; // master norm parameter that's accessible/used from runcorr_3D
    float bound;
    if (typeOfSpatialCorr <= 4 || typeOfSpatialCorr == 10 || typeOfSpatialCorr == 0) bound = range_of_corr;
    else bound = spatial_sigma;
    /* Declare function pointers for the spatial correlation functions
     First, we declare a pointer *pfSpatial/TemporalCorr to a function with 2 arguments j and k (or 1 argument t), plus parameters necessary for function operation (currently sigma and height, though more may need to be added if different kernels or a customizable unsharp are to be implemented).
     Then we call the function pickSpatialCorr (from pickCorrelations.cpp). This function returns a pointer to the function of choice (determined by 'mode'),
     which can then be used by simply calling pfSpatial/TemporalCorr(j, k). */
    
    /* NOTE: We attempted to import sigma, alpha, and height using the pickSpatialCorr/pickTemporalCorr functions, saving them as private global variables in pickCorrelations.cpp.
     This allowed us to simply call pfSpatialCorr(j, k) and pfTemporalCorr(t), removing excess arguments from the runcorr and computermscorr functions, and changing the implementation so that (except in the periodic case) the function pointers would only be created once and then would be passed to the necessary methods as arguments.
     We found this method to be much cleaner, but unfortunately we introduced a bug somewhere along the line. Rather than spend days trying to track it down, we reverted to our previous version and continued taking data. It might be worth re-implementing this feature, if you have time and want to make the code more streamlined. For reference, our previous attempt should still be in a series of commits on GitHub. ~ Nathan Wei and Kevin Griffin
     */
    
    float (*pfSpatialCorr)(int j, int k, float spatial_sigma, float spatial_alpha, float spatial_height);
    float (*pfTemporalCorr)(int t, float temporal_sigma, float temporal_alpha, float temporal_height);
    pfSpatialCorr = pickSpatialCorr(typeOfSpatialCorr);
    pfTemporalCorr = pickTemporalCorr(typeOfTemporalCorr);
    
    // Correlation function work for finding normalization
    // Note: this is different from the previous implementation, which had mysteriously different logic for each function
    for (int j = -bound; j <= bound; j++) { // range of neighbors used to compute normalization/convolution
        for (int k = -bound; k <= bound; k++) { // j and k refer to the shift
            for (int t = -halfLoaf; t <= halfLoaf; t++) {
                norm += (pfSpatialCorr(j, k, spatial_sigma, spatial_alpha, spatial_height) * pfTemporalCorr(t, temporal_sigma, temporal_alpha, temporal_height));
            }
        }
    }
    
    // makes a random correlated sequence of angles, with the same parameters but without correction
    // computes its mean and rms value of angles. This is done so that the rms correction factor can be
    // determined before the angles have been produced
    rms = compute_rmscorr_3D(spatial_sigma, temporal_sigma, typeOfSpatialCorr, typeOfTemporalCorr, spatial_alpha, temporal_alpha, spatial_height, temporal_height, 1, 1, halfLoaf);
    correction = target_rms / rms; // correction factor
    cout << "Done! Correction factor is " << correction << endl << "Setting up timing..." << endl;
    cout << "Done! Starting grid motions" << endl;
    
    //timing:
    // timing uses the standard timeval structure. a timeval struct holds seconds and remaining microseconds. This time is the number of seconds and remaining microseconds since 01.01.1970. Note: once microseconds reaches 10000000, seconds increments and microseconds is set to zero
    timeval startTime; // declare a structure for holding the time that the last slice of angles was sent to the grid
    timeval currentTime; // declare a structure for holding the current time
    long usecElapsed; // a varaible for holding the difference between currentTime and startTime
    gettimeofday(&startTime,0); // initialize startTime with the current time
    
    // ------------ (unclear whether this is actually necessary)
    gettimeofday(&currentTime,0);
    usecElapsed = (currentTime.tv_sec - startTime.tv_sec)*1000000 + ((signed long)currentTime.tv_usec - (signed long)startTime.tv_usec);
    while (usecElapsed <= updatetimeinmus){
        gettimeofday(&currentTime,0);
        usecElapsed = (currentTime.tv_sec - startTime.tv_sec)*1000000 + ((signed long)currentTime.tv_usec - (signed long)startTime.tv_usec);
    }
    while (usecElapsed > updatetimeinmus){
        gettimeofday(&currentTime,0);
        usecElapsed = (signed long)currentTime.tv_usec - (signed long)startTime.tv_usec;
    }
    // ------------
    
    bool firstTime = true; // prevent timing error message from showing up during first iteration
    // main loop: give angle orders (runs until ctrl-C is issued by user, which is caught by signal handler in menuII)
    while(0==0){
        
        //freshLoaf.Loaf_printFullArray(); // debugging
        cout << "\nGrid #" << i << " "; // print grid number
        i += 1;
        // get new slice of angles (using either inlined algorithm or standard function pointer algorithm)
        if (ltfast_on)
            ltfast(newslice, &freshLoaf, halfLoaf, spatial_sigma, temporal_sigma, spatial_alpha, temporal_alpha,
                   spatial_height, temporal_height, correction);
        else if (unsharp_on)
            unsharp(newslice, &freshLoaf, halfLoaf, spatial_sigma, temporal_sigma, spatial_alpha, temporal_alpha,
                    spatial_height, temporal_height, correction);
        else
            runcorr_3D(newslice, &freshLoaf, halfLoaf, spatial_sigma, temporal_sigma, spatial_alpha, temporal_alpha,
                       spatial_height, temporal_height, typeOfSpatialCorr, typeOfTemporalCorr, 0, 0, correction);
        
        // store necessary servo speeds after carrying out safety checks
        for (int row = 0; row < 11; row++) {
            for (int col = 0; col < 13; col++){
                numberOfAnglesSet++; // total number of paddles moved, since the beginning of time (global variable)
                // angle safety processing: do not exceed angle of 90 degrees
                if (newslice[col][row]>90){
                    newslice[col][row]=90;
                    over90orminus90count++; // keep track of number of angles that need to be kept from exceeding +/- 90 degrees
                    //cout << "+"; // print visual representation within histogram if you want
                }
                else if (newslice[col][row]<-90){
                    newslice[col][row]=-90;
                    over90orminus90count++;
                    //cout << "-";
                }
                
                amplitude = newslice[col][row] - oldslice[col][row]; // calculate the amplitude between the old and the new angles
                if (fabs(amplitude)/(max_speed) > SPACING) { // constrain paddles that have to move too far for the servos to handle
                    cout << "*"; // constraining histogram - 1 * = 1 paddle constrained by max speed
                    outOfBoundsCount++; // keep track of number of constrained paddles
                    if (amplitude > 0) step_size[col][row] = max_speed;
                    else if (amplitude < 0) step_size[col][row] = -max_speed;
                }
                // move at constant speed (equal-sized steps over SPACING interpolations) to the target angle
                // this implemenation assumes that servos don't have a minimum speed or angle
                else step_size[col][row] = amplitude/(SPACING);
            }
        }
        
        /* Create SPACING timeslices to separate old and new configurations, and feed each one to the grid in succession.
         * This decouples the grid updating timescale from the correlation computation timescale, and also means we call the
         *   computationally-expensive runcorr_3D method once every SPACING grid configurations.
         * SPACING is currently set to 1, in order to get the highest frequency of correlations possible. With faster computers or a more efficient
         *   runcorr_3D algorithm, increasing SPACING to improve the resolution of the grid motions (while still running 10 correlations per second)
         *   might be possible. */
        for (int t = 0; t < SPACING; t++) {
            //cout << " " << (t+1); // print interpolation number
            
            // compute new intermediate grid position, with steps necessary to attain it
            // adding the calculated servo speed every 0.1 seconds SPACING times guarantees the angle will reach its target by the end of the iteration
            for (int row = 0; row < 11; row++) {
                for(int col = 0; col < 13; col++){
                    if (step_size[col][row] != 0) { // don't bother checking servos that have already arrived
                        diff = fabs(newslice[col][row] - oldslice[col][row]); // determination of approximate equality for doubles
                        if (diff > EPSILON) oldslice[col][row] += step_size[col][row]; // not equal -> add another step
                        else step_size[col][row] = 0; // paddle has arrived; tell servo not to move any more
                    }
                }
            }
            
            //set position of each servo (within 0.1 seconds)
            gettimeofday(&currentTime,0); // set currentTime to hold the current time
            usecElapsed = (currentTime.tv_sec - startTime.tv_sec)*1000000 + ((signed long)currentTime.tv_usec - (signed long)startTime.tv_usec);// useconds elapsed since startTime
            
            if (usecElapsed > updatetimeinmus && !firstTime){ // no need to wait because runcorr took more than .1 sec
                cout << "Time Elapsed is greater than .1 sec.  Time Elapsed = " << usecElapsed;
            }
            else if (usecElapsed < 0){
                assert(0); // assert because something bizarre happened (maybe the timer overflowed somehow) - safety for a case that shouldn't ever occur
            }
            else {
                cout << " " << usecElapsed << "\u03BCs"; // print computation time in microseconds (at end of histogram)
                while (usecElapsed < updatetimeinmus){ // we need to wait
                    gettimeofday(&currentTime,0);
                    usecElapsed = (currentTime.tv_sec - startTime.tv_sec)*1000000 + ((signed long)currentTime.tv_usec - (signed long)startTime.tv_usec);
                }
            }
            // record new start time to compare against for next iteration
            gettimeofday(&startTime,0);
            
            if (firstTime) firstTime = false; // set to false for remainder of run
            
            //----------------
            setanglestoallservosIII(oldslice, step_size, constantArea, target_rms); // for motion - send generated 2D arrays to grid communication method
        }
    }
    anglefile.close(); // never reaches this point
    return 0; // never reaches this point
}
Exemplo n.º 8
0
/*******************************************************************************
 * For each run, the input filename and restart information (if needed) must   *
 * be given on the command line.  For non-restarted case, command line is:     *
 *                                                                             *
 *    executable <input file name>                                             *
 *                                                                             *
 * For restarted run, command line is:                                         *
 *                                                                             *
 *    executable <input file name> <restart directory> <restart number>        *
 *                                                                             *
 *******************************************************************************/
int main(int argc, char* argv[])
{
    // Initialize libMesh, PETSc, MPI, and SAMRAI.
    LibMeshInit init(argc, argv);
    SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD);
    SAMRAI_MPI::setCallAbortInSerialInsteadOfExit();
    SAMRAIManager::startup();

    { // cleanup dynamically allocated objects prior to shutdown

        // Parse command line options, set some standard options from the input
        // file, initialize the restart database (if this is a restarted run),
        // and enable file logging.
        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "IB.log");
        Pointer<Database> input_db = app_initializer->getInputDatabase();

        // Get various standard options set in the input file.
        const bool dump_viz_data = app_initializer->dumpVizData();
        const int viz_dump_interval = app_initializer->getVizDumpInterval();
        const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter();
        const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty();

        const string beam_exodus_filename = app_initializer->getExodusIIFilename("beam");

        const bool dump_restart_data = app_initializer->dumpRestartData();
        const int restart_dump_interval = app_initializer->getRestartDumpInterval();
        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();

        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();
        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();
        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();
        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())
        {
            Utilities::recursiveMkdir(postproc_data_dump_dirname);
        }

        const bool dump_timer_data = app_initializer->dumpTimerData();
        const int timer_dump_interval = app_initializer->getTimerDumpInterval();

               // >> obtain restart directory and restart number, added by walter
        const string restart_directory =app_initializer->getThisRestartDirectory();
        const int restart_number = app_initializer->getThisRestartNumber();

        // Create a simple FE mesh.
        const double dx = input_db->getDouble("DX");
        const double ds = input_db->getDouble("MFAC") * dx;

     
	const double beam_h = input_db->getDouble("Beam_H");
	const double beam_l = input_db->getDouble("Beam_L");
	Is_curved = input_db->getBoolWithDefault("USING_INTRINSIC_CURVATURE", false);
	delta_h = ds * 0.05;
	curved_a2 = input_db->getDoubleWithDefault("CURVATURE_Coefficient_SecondOrder", 0.0);
 // second-order coefficient
	curved_a1 = input_db->getDoubleWithDefault("CURVATURE_Coefficient_FirstOrder", 0.0); // first-order coefficient
	Beam_Length = beam_l;
  if (Is_curved)
  { pout<<"+++++++++++++[Arc length mapping for stress]: delta_h=" <<delta_h << "; solid_mesh-size ds = " << ds << endl;
    pout<< "+++++++++++++[Arc length mapping for stress]: ( curved_a2, curved_a1) = " << "( "   << curved_a2 <<", " << curved_a1 << " ); beam_length = " << Beam_Length << endl;
  }
  else
  pout<<"++++++++++++++[Arch length mapping is not used]: no curvature" << endl;

        Mesh beam_mesh(NDIM);

// >> add 3D mesh (cylinder with radius) -- 02/03/2016 by walter

	if (NDIM==2)
{
		pout << "++++++++++++++[Geometry]:  we use 2D mesh ++++++++++++++++++++++ \n";
        string beam_elem_type = input_db->getString("BEAM_ELEM_TYPE");
		const double R = beam_h/2.0;
		//const double ds =input_db->getDouble("AXIAL_MESH_SIZE");
		
	    const int num_axial_elements = ceil(beam_l / ds); // elements
        MeshTools::Generation::build_square(beam_mesh,
                                            ceil(beam_l / ds),
                                            ceil(beam_h / ds),
                                            0.0,
                                            beam_l, //0.6,
                                            -0.5 * beam_h,
                                            0.5 * beam_h,
                                            Utility::string_to_enum<ElemType>(beam_elem_type));
	 const double R_tip = input_db->getDoubleWithDefault("TIP_RADIUS", R);
		if (R_tip == R)
			pout << "++++++++++++++[3D MESH]:  No taper, as R_tip = R ="<< R_tip <<" ++++++++++++++++++++++ \n";
		else if (R_tip < R)
			pout << "++++++++++++++[3D MESH]:  With Taper, as R_tip ="<< R_tip <<" R =" << R <<" ++++++++++++++++++++++ \n";
		else 
			pout << "++++++++++++++[3D MESH]:  Error: Wrong Taper: R_tip > R, as R_tip ="<< R_tip <<" R =" << R <<" ++++++++++++++++++++++ \n";
	
		double tip_scale = (R_tip / R);
	
	// deal with intrinsic curvature
		const bool is_with_curvature= input_db->getBoolWithDefault("USING_INTRINSIC_CURVATURE", false);
		const double coef_a2 = input_db->getDoubleWithDefault("CURVATURE_Coefficient_SecondOrder", 0.0);
		const double coef_a1 = input_db->getDoubleWithDefault("CURVATURE_Coefficient_FirstOrder", 0.0);
		int num_segments = input_db->getIntegerWithDefault("CURVATURE_Mapping_Number_of_segments",1); // number of segments when we compute the mapping
		if (is_with_curvature)
		{
		pout << "++++++++++++++[2D MESH]:  Intrinsic Curvature is used, (x1,0) ->(x2, f(x2)) ++++++++++++++++++++++ \n";
		pout << "++++++++++++++[2D MESH]:  f(x) = a2 x^2 + a1 x, where, a2 = " << coef_a2 << ", a1 = "<< coef_a1 << "++++++++++++++++++++++ \n";
		pout << "++++++++++++++[2D MESH]:  We do the mapping with number of segments as" << num_segments << "++++++++++++++++++++++ \n";
		}
		else
		{
		pout << "++++++++++++++[2D MESH]:  Intrinsic Curvature is not used ++++++++++++++++++++++ \n";
		num_segments = 1;
		pout << "++++++++++++++[2D MESH]:  We set number of segments as " << num_segments << "++++++++++++++++++++++ \n";
		}
		
	
		vector<double> vec_x2_at_nodes(num_axial_elements +1);
		const double exact_dz = beam_l / num_axial_elements;
		
		vec_x2_at_nodes[0] = 0.0; // (x1,0) ->(x2, f(x2)), when x1=0, we know x2 = 0

		tip_center=libMesh::Point(beam_l, 0.0, 0);
		double last_x1= 0.0;
		if(is_with_curvature)
		{  
			const double dseg = beam_l / num_segments;
			
			for (unsigned int kseg = 0; kseg < num_segments; kseg++)
				{   double cur_x2= dseg * (kseg +1); // x2 =  ds * (k+1)
					double g_x2 = sqrt(1.0 + (coef_a1 + 2.0 * coef_a2 * cur_x2) * (coef_a1 + 2.0 * coef_a2 * cur_x2)); //  g(x2) = \sqrt[1+ (a1 + 2 a2 x2)^2 ]
					double new_x1 = last_x1 + g_x2 * dseg; //x1[kseg+1] = x1[kseg] + g_x2 * dseg;
					unsigned int new_ind = ceil(new_x1 / exact_dz);
					unsigned int last_ind = ceil(last_x1 / exact_dz);
					if ( (last_ind < new_ind) && (last_ind < num_axial_elements +1) ) // this interval contains one node: vec_x2_at_nodes[last_ind]
					{   double last_x2 = kseg * dseg; 
						double new_x2 = (kseg+1) * dseg;
						double cur_x1 = last_ind * exact_dz;
						vec_x2_at_nodes[last_ind] = (cur_x1 - last_x1) / (new_x1 - last_x1) * new_x2 + (new_x1 - cur_x1) / (new_x1 - last_x1) * last_x2;
						
					}
					// next step
					last_x1 = new_x1;
					 
				}
		// we check the vec_x2(x1);
			
		pout << "++++++++++++++[2D MESH]:  finish the x2-x1 mapping with segments as " << num_segments << "++++++++++++++++++++++ \n";	
		// get the new tip_center
				double cur_x2 = vec_x2_at_nodes[num_axial_elements];				
				double dfdx= coef_a1 + 2.0* coef_a2 * cur_x2;
				double fx= coef_a1 * cur_x2 + coef_a2 * cur_x2 * cur_x2;
				double g_x2 = sqrt(1.0 + dfdx * dfdx); // g(x2)

				tip_center(0) = cur_x2;
				tip_center(1) = fx;
				tip_center(2) = 0;	
		pout << "++++++++++++++[2D MESH]:  Now the coordinates of tip-center are: " << tip_center<< "++++++++++++++++++++++ \n";	
		
		}
		// change the node_coordinates
		Mesh::node_iterator       it_nd      = beam_mesh.nodes_begin(); //mesh.active_local_elements_begin();//mesh.elements_begin();
    	        const Mesh::node_iterator it_last_nd = beam_mesh.nodes_end(); //mesh.active_local_elements_end();//mesh.elements_end();
    	for ( ; it_nd != it_last_nd ; ++it_nd) {
        	Node* node = *it_nd;
		// step 1) new_x = old_z; new_y = old_x; new_z = old_y
			double new_x = (*node)(0);
			double new_y = (*node)(1);
			

		// step 2) add varing radius for taper
			double current_scale = (new_x / beam_l) * tip_scale + ( 1.0 - new_x / beam_l) * 1.0;
			new_y = new_y* current_scale;
				
		// step 3) add intrinsic curvature (see the note)
			if (is_with_curvature)
			{
				 // pout << "++++++++++++++[3D MESH]:  Begin the curvature mapping ++++++++++++++++++++++ \n";		
				
				// (x1,y1,z1) --mapped to-->(x2,y2,z1)
				// first, we need to compute x2
				unsigned int cur_ind = ceil ( new_x / exact_dz + 0.2 )  - 1; // to get the index;
				double cur_x2 = vec_x2_at_nodes[cur_ind];				
				double dfdx= coef_a1 + 2.0* coef_a2 * cur_x2;
				double fx= coef_a1 * cur_x2 + coef_a2 * cur_x2 * cur_x2;
				double g_x2 = sqrt(1.0 + dfdx * dfdx); // g(x2)

				(*node)(0) = cur_x2 - dfdx * new_y / g_x2;
				(*node)(1) = fx + new_y /g_x2 ;
								
				/*				
				pout <<" cur_ind is = " << cur_x2 <<"; new_x2 = " << cur_x2 - dfdx * new_y / g_x2 << endl;
				pout <<"previous node cords: (" << new_x <<", " << new_y <<", " << new_z << endl;
				pout <<"current node cords: (" << (*node)(0) << ", " << (*node)(1)<<", " << (*node)(2)<< endl;
				*/
								
			}
			else
			{
				(*node)(0) = new_x;
				(*node)(1) = new_y;
				
			}
		
		
	   } // for 
        
}
	else // NDIM ==3
{
		pout << "++++++++++++++[Geometry]:  we use 3D mesh ++++++++++++++++++++++ \n";
        Mesh block_mesh(2); // circle mesh
		string block_elem_type = input_db->getString("CSA_ELEM_TYPE"); // currently, tri3 or tri6
		const double dr = input_db->getDouble("CSA_MESH_SIZE");
		const double R = input_db->getDouble("ROOT_RADIUS");
		const double dz =input_db->getDouble("AXIAL_MESH_SIZE");
		const int num_circum_nodes = ceil(2.0 * M_PI * R / dr);
	    const int num_axial_elements = ceil(beam_l / dz); // elements
		pout << "++++++++++++++[Geometry]:  First is 2D CSA mesh ++++++++++++++++++++++ \n";
		pout << "+++++++++++++++++++++++++++ [2D CSA]: (R, dz) = (" << R << ", " <<dz << ")++++++++++++++++++++++ \n";
		
        for (int k = 0; k < num_circum_nodes; ++k)
            {
                const double theta = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_circum_nodes);
                block_mesh.add_point(libMesh::Point( R * cos(theta), R * sin(theta)));
            }
            TriangleInterface triangle(block_mesh);
            triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL;
            triangle.elem_type() = Utility::string_to_enum<ElemType>(block_elem_type);
            triangle.desired_area() = sqrt(3.0) / 4.0 * dr * dr;
            triangle.insert_extra_points() = true;
            triangle.smooth_after_generating() = true;
            triangle.triangulate();
            block_mesh.prepare_for_use();
		pout << "++++++++++++++[Geometry]:  finish generatign 2D mesh ++++++++++++++++++++++ \n";
		const RealVectorValue extrusion_vector (0.0, 0.0, beam_l);
		pout << "++++++++++++++[Geometry]:  begin to deal with 3D mesh ++++++++++++++++++++++ \n";
		const double R_tip = input_db->getDoubleWithDefault("TIP_RADIUS", R);
		if (R_tip == R)
			pout << "++++++++++++++[3D MESH]:  No taper, as R_tip = R ="<< R_tip <<" ++++++++++++++++++++++ \n";
		else if (R_tip < R)
			pout << "++++++++++++++[3D MESH]:  With Taper, as R_tip ="<< R_tip <<" R =" << R <<" ++++++++++++++++++++++ \n";
		else 
			pout << "++++++++++++++[3D MESH]:  Error: Wrong Taper: R_tip > R, as R_tip ="<< R_tip <<" R =" << R <<" ++++++++++++++++++++++ \n";
	
		double tip_scale = (R_tip / R);
		
		// deal with intrinsic curvature
		const bool is_with_curvature= input_db->getBoolWithDefault("USING_INTRINSIC_CURVATURE", false);
		const double coef_a2 = input_db->getDoubleWithDefault("CURVATURE_Coefficient_SecondOrder", 0.0);
		const double coef_a1 = input_db->getDoubleWithDefault("CURVATURE_Coefficient_FirstOrder", 0.0);
		int num_segments = input_db->getIntegerWithDefault("CURVATURE_Mapping_Number_of_segments",1); // number of segments when we compute the mapping
		if (is_with_curvature)
		{
		pout << "++++++++++++++[3D MESH]:  Intrinsic Curvature is used, (x1,0) ->(x2, f(x2)) ++++++++++++++++++++++ \n";
		pout << "++++++++++++++[3D MESH]:  f(x) = a2 x^2 + a1 x, where, a2 = " << coef_a2 << ", a1 = "<< coef_a1 << "++++++++++++++++++++++ \n";
		pout << "++++++++++++++[3D MESH]:  We do the mapping with number of segments as" << num_segments << "++++++++++++++++++++++ \n";
		}
		else
		{
		pout << "++++++++++++++[3D MESH]:  Intrinsic Curvature is not used ++++++++++++++++++++++ \n";
		num_segments = 1;
		pout << "++++++++++++++[3D MESH]:  We set number of segments as " << num_segments << "++++++++++++++++++++++ \n";
		}
		
	
		vector<double> vec_x2_at_nodes(num_axial_elements +1);
		const double exact_dz = beam_l / num_axial_elements;
		
		vec_x2_at_nodes[0] = 0.0; // (x1,0) ->(x2, f(x2)), when x1=0, we know x2 = 0

		tip_center=libMesh::Point(beam_l, 0.0, 0);
		double last_x1= 0.0;
		if(is_with_curvature)
		{  
			const double dseg = beam_l / num_segments;
			
			for (unsigned int kseg = 0; kseg < num_segments; kseg++)
				{   double cur_x2= dseg * (kseg +1); // x2 =  ds * (k+1)
					double g_x2 = sqrt(1.0 + (coef_a1 + 2.0 * coef_a2 * cur_x2) * (coef_a1 + 2.0 * coef_a2 * cur_x2)); //  g(x2) = \sqrt[1+ (a1 + 2 a2 x2)^2 ]
					double new_x1 = last_x1 + g_x2 * dseg; //x1[kseg+1] = x1[kseg] + g_x2 * dseg;
					unsigned int new_ind = ceil(new_x1 / exact_dz);
					unsigned int last_ind = ceil(last_x1 / exact_dz);
					if ( (last_ind < new_ind) && (last_ind < num_axial_elements +1) ) // this interval contains one node: vec_x2_at_nodes[last_ind]
					{   double last_x2 = kseg * dseg; 
						double new_x2 = (kseg+1) * dseg;
						double cur_x1 = last_ind * exact_dz;
						vec_x2_at_nodes[last_ind] = (cur_x1 - last_x1) / (new_x1 - last_x1) * new_x2 + (new_x1 - cur_x1) / (new_x1 - last_x1) * last_x2;
						
					}
					// next step
					last_x1 = new_x1;
					 
				}
		// we check the vec_x2(x1);
			
		pout << "++++++++++++++[3D MESH]:  finish the x2-x1 mapping with segments as " << num_segments << "++++++++++++++++++++++ \n";	
		// get the new tip_center
				double cur_x2 = vec_x2_at_nodes[num_axial_elements];				
				double dfdx= coef_a1 + 2.0* coef_a2 * cur_x2;
				double fx= coef_a1 * cur_x2 + coef_a2 * cur_x2 * cur_x2;
				double g_x2 = sqrt(1.0 + dfdx * dfdx); // g(x2)

				tip_center(0) = cur_x2;
				tip_center(1) = fx;
				tip_center(2) = 0;	
		pout << "++++++++++++++[3D MESH]:  Now the coordinates of tip-center are: " << tip_center<< "++++++++++++++++++++++ \n";	
		
		}

        MeshTools::Generation::build_extrusion(beam_mesh,
                                                block_mesh,num_axial_elements, extrusion_vector);
		// change the node_coordinates
		Mesh::node_iterator       it_nd      = beam_mesh.nodes_begin(); //mesh.active_local_elements_begin();//mesh.elements_begin();
    	const Mesh::node_iterator it_last_nd = beam_mesh.nodes_end(); //mesh.active_local_elements_end();//mesh.elements_end();
    	for ( ; it_nd != it_last_nd ; ++it_nd) {
        	Node* node = *it_nd;
		// step 1) new_x = old_z; new_y = old_x; new_z = old_y
			double new_x = (*node)(2);
			double new_y = (*node)(0);
			double new_z = (*node)(1);

		// step 2) add varing radius for taper
			double current_scale = (new_x / beam_l) * tip_scale + ( 1.0 - new_x / beam_l) * 1.0;
			new_y = new_y* current_scale;
			new_z = new_z* current_scale;	
		// step 3) add intrinsic curvature (see the note)
			if (is_with_curvature)
			{
				 // pout << "++++++++++++++[3D MESH]:  Begin the curvature mapping ++++++++++++++++++++++ \n";		
				
				// (x1,y1,z1) --mapped to-->(x2,y2,z1)
				// first, we need to compute x2
				unsigned int cur_ind = ceil ( new_x / exact_dz + 0.2 )  - 1; // to get the index;
				double cur_x2 = vec_x2_at_nodes[cur_ind];				
				double dfdx= coef_a1 + 2.0* coef_a2 * cur_x2;
				double fx= coef_a1 * cur_x2 + coef_a2 * cur_x2 * cur_x2;
				double g_x2 = sqrt(1.0 + dfdx * dfdx); // g(x2)

				(*node)(0) = cur_x2 - dfdx * new_y / g_x2;
				(*node)(1) = fx + new_y /g_x2 ;
				(*node)(2) = new_z;				
				/*				
				pout <<" cur_ind is = " << cur_x2 <<"; new_x2 = " << cur_x2 - dfdx * new_y / g_x2 << endl;
				pout <<"previous node cords: (" << new_x <<", " << new_y <<", " << new_z << endl;
				pout <<"current node cords: (" << (*node)(0) << ", " << (*node)(1)<<", " << (*node)(2)<< endl;
				*/
								
			}
			else
			{
				(*node)(0) = new_x;
				(*node)(1) = new_y;
				(*node)(2) = new_z;
			}
		
		
	   } // for 


}

// << add 3D mesh (cylinder with radius) -- 02/03/2016 by walter
		beam_mesh.prepare_for_use();
		pout << "++++++++++++++[Geometry]: finish generating the beam mesh ++++++++++++++++++++++ \n";
        
        fixed_L = input_db->getDouble("FIXED_L");
        mu_s = input_db->getDouble("MU_S");
        lambda_s = input_db->getDouble("LAMBDA_S");
        kappa_s = input_db->getDouble("KAPPA_S");
		slope =input_db->getDouble("SLOPE_RADIUS");
		r0 = input_db->getDouble("ROOT_RADIUS");
	// >> begin to print out
        pout << "\n";
		pout << "Modulus = " << mu_s <<"; Bulk Modulus =" << lambda_s << "\n";
		pout << "SLOPE of radius change: " << slope << "; Radius at root " << r0 << "\n";
	// << end print out
	// end_modulus_ratio = input_db->getDouble("END_MODULUS_RATIO"); // not used, change on 01/29/2016
	// end_coordinate = input_db->getDouble("END_COORDINATE"); // not used change on 01/29/2016
        // Create major algorithm and data objects that comprise the
        // application.  These objects are configured from the input database
        // and, if this is a restarted run, from the restart database.
        Pointer<INSHierarchyIntegrator> navier_stokes_integrator;
        const string solver_type = app_initializer->getComponentDatabase("Main")->getString("solver_type");
        if (solver_type == "STAGGERED")
        {
            navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(
                "INSStaggeredHierarchyIntegrator",
                app_initializer->getComponentDatabase("INSStaggeredHierarchyIntegrator"));
        }
        else if (solver_type == "COLLOCATED")
        {
            navier_stokes_integrator = new INSCollocatedHierarchyIntegrator(
                "INSCollocatedHierarchyIntegrator",
                app_initializer->getComponentDatabase("INSCollocatedHierarchyIntegrator"));
        }
        else
        {
            TBOX_ERROR("Unsupported solver type: " << solver_type << "\n"
                                                   << "Valid options are: COLLOCATED, STAGGERED");
        }
        Pointer<IBFEMethod> ib_method_ops =
            new IBFEMethod("IBFEMethod",
                           app_initializer->getComponentDatabase("IBFEMethod"),
                           &beam_mesh, 
                           app_initializer->getComponentDatabase("GriddingAlgorithm")->getInteger("max_levels")
			   , restart_directory,  restart_number
			   );
        Pointer<IBHierarchyIntegrator> time_integrator =
            new IBExplicitHierarchyIntegrator("IBHierarchyIntegrator",
                                              app_initializer->getComponentDatabase("IBHierarchyIntegrator"),
                                              ib_method_ops,
                                              navier_stokes_integrator);
        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(
            "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry"));
        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>("PatchHierarchy", grid_geometry);
        Pointer<StandardTagAndInitialize<NDIM> > error_detector =
            new StandardTagAndInitialize<NDIM>("StandardTagAndInitialize",
                                               time_integrator,
                                               app_initializer->getComponentDatabase("StandardTagAndInitialize"));
        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();
        Pointer<LoadBalancer<NDIM> > load_balancer =
            new LoadBalancer<NDIM>("LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer"));
        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =
            new GriddingAlgorithm<NDIM>("GriddingAlgorithm",
                                        app_initializer->getComponentDatabase("GriddingAlgorithm"),
                                        error_detector,
                                        box_generator,
                                        load_balancer);


        // Configure the IBFE solver.
	

        IBFEMethod::LagBodyForceFcnData beam_tether_force_data(beam_tether_force_function);
        IBFEMethod::PK1StressFcnData beam_PK1_stress_data(beam_PK1_stress_function);
        ib_method_ops->registerLagBodyForceFunction(beam_tether_force_data);
        ib_method_ops->registerPK1StressFunction(beam_PK1_stress_data);
 
        EquationSystems* beam_equation_systems = ib_method_ops->getFEDataManager()->getEquationSystems();
	
        FEDataManager* fe_data_manager = ib_method_ops->getFEDataManager(0);
        Pointer<IBFEPostProcessor> ib_post_processor = new IBFECentroidPostProcessor("IBFEPostProcessor", fe_data_manager);

        ib_post_processor->registerTensorVariable(
            "FF", MONOMIAL, CONSTANT, IBFEPostProcessor::FF_fcn);

        std::pair<IBTK::TensorMeshFcnPtr,void*> PK1_dev_stress_fcn_data(beam_PK1_stress_function,static_cast<void*>(NULL));
        ib_post_processor->registerTensorVariable(
            "sigma_dev", MONOMIAL, CONSTANT,
            IBFEPostProcessor::cauchy_stress_from_PK1_stress_fcn,
            std::vector<unsigned int>(), &PK1_dev_stress_fcn_data);
	// >> add pressure interpolation
	Pointer<IBFEPostProcessor> ib_pressure_processor =
            new IBFECentroidPostProcessor("IBFEPressureProcessor", fe_data_manager);
	 std::vector<double> vec_ones (3,1.0);
        HierarchyGhostCellInterpolation::InterpolationTransactionComponent p_ghostfill(
/*data_idx*/ -1, "LINEAR_REFINE", /*use_cf_bdry_interpolation*/ false, "CONSERVATIVE_COARSEN", "LINEAR");
	    
		FEDataManager::InterpSpec p_interp_spec("PIECEWISE_LINEAR", QGAUSS, FIFTH, /*use_adaptive_quadrature*/ false,
/*point_density*/ 2.0, /*use_consistent_mass_matrix*/ true, false, vec_ones);



	ib_pressure_processor->registerInterpolatedScalarEulerianVariable("pressure_f",
                                                                      MONOMIAL, //LAGRANGE,
                                                                      CONSTANT, // FIRST,
                                                                      navier_stokes_integrator->getPressureVariable(),
                                                                      navier_stokes_integrator->getCurrentContext(),
								      p_ghostfill, p_interp_spec);   
	// << add pressure interpolation


        // Create Eulerian initial condition specification objects.
        if (input_db->keyExists("VelocityInitialConditions"))
        {
            Pointer<CartGridFunction> u_init = new muParserCartGridFunction(
                "u_init", app_initializer->getComponentDatabase("VelocityInitialConditions"), grid_geometry);
            navier_stokes_integrator->registerVelocityInitialConditions(u_init);
        }

        if (input_db->keyExists("PressureInitialConditions"))
        {
            Pointer<CartGridFunction> p_init = new muParserCartGridFunction(
                "p_init", app_initializer->getComponentDatabase("PressureInitialConditions"), grid_geometry);
            navier_stokes_integrator->registerPressureInitialConditions(p_init);
        }

        // Create Eulerian boundary condition specification objects (when necessary).
        const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift();
        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM);
        if (periodic_shift.min() > 0)
        {
            for (unsigned int d = 0; d < NDIM; ++d)
            {
                u_bc_coefs[d] = NULL;
            }
        }
        else
        {
            for (unsigned int d = 0; d < NDIM; ++d)
            {
                ostringstream bc_coefs_name_stream;
                bc_coefs_name_stream << "u_bc_coefs_" << d;
                const string bc_coefs_name = bc_coefs_name_stream.str();

                ostringstream bc_coefs_db_name_stream;
                bc_coefs_db_name_stream << "VelocityBcCoefs_" << d;
                const string bc_coefs_db_name = bc_coefs_db_name_stream.str();

                u_bc_coefs[d] = new muParserRobinBcCoefs(
                    bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry);
            }
            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);
        }

        // Create Eulerian body force function specification objects.
        if (input_db->keyExists("ForcingFunction"))
        {
            Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction(
                "f_fcn", app_initializer->getComponentDatabase("ForcingFunction"), grid_geometry);
            time_integrator->registerBodyForceFunction(f_fcn);
        }

        // Set up visualization plot file writers.
        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();
        if (uses_visit)
        {
            time_integrator->registerVisItDataWriter(visit_data_writer);
        }
        // AutoPtr<ExodusII_IO> block_exodus_io(uses_exodus ? new ExodusII_IO(block_mesh) : NULL);
        AutoPtr<ExodusII_IO> beam_exodus_io(uses_exodus ? new ExodusII_IO(beam_mesh) : NULL);

        // Initialize hierarchy configuration and data on all patches.
        ib_method_ops->initializeFEData();
	ib_post_processor->initializeFEData();
	ib_pressure_processor->initializeFEData();
        time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);

        // Deallocate initialization objects.
        app_initializer.setNull();

        // Print the input database contents to the log file.
        plog << "Input database:\n";
        input_db->printClassData(plog);

        // Write out initial visualization data.
        int iteration_num = time_integrator->getIntegratorStep();
        double loop_time = time_integrator->getIntegratorTime();
        if (dump_viz_data)
        {
            pout << "\n\nWriting visualization files...\n\n";
            if (uses_visit)
            {
                time_integrator->setupPlotData();
                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);
            }
            if (uses_exodus)
            {
		ib_post_processor->postProcessData(loop_time); 
		ib_pressure_processor->postProcessData(loop_time);
                beam_exodus_io->write_timestep(
                    beam_exodus_filename, *beam_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);
            
	                   std::ostringstream file_name;
            file_name << beam_exodus_filename +"_"
                      << std::setw(6)
                      << std::setfill('0')
                      << std::right
                      << iteration_num;
	    GMVIO(beam_mesh).write_equation_systems(file_name.str()+".gmv",*beam_equation_systems);
            }
        }

        // Open streams to save lift and drag coefficients.
        if (SAMRAI_MPI::getRank() == 0)
        {
            drag_stream.open("C_D.curve", ios_base::out | ios_base::trunc);
            lift_stream.open("C_L.curve", ios_base::out | ios_base::trunc);
	    moment_stream.open("Moment.curve", ios_base::out | ios_base::trunc);
            A_x_posn_stream.open("A_x.curve", ios_base::out | ios_base::trunc);
            A_y_posn_stream.open("A_y.curve", ios_base::out | ios_base::trunc);
        }

        // Main time step loop.
        double loop_time_end = time_integrator->getEndTime();
        double dt = 0.0;
        while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining())
        {
            iteration_num = time_integrator->getIntegratorStep();
            loop_time = time_integrator->getIntegratorTime();

            pout << "\n";
            pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n";
            pout << "At beginning of timestep # " << iteration_num << "\n";
            pout << "Simulation time is " << loop_time << "\n";

            dt = time_integrator->getMaximumTimeStepSize();
            time_integrator->advanceHierarchy(dt);
            loop_time += dt;
	    
	  //  ib_pressure_processor->postProcessData(loop_time);
            pout << "\n";
            pout << "At end       of timestep # " << iteration_num << "\n";
            pout << "Simulation time is " << loop_time << "\n";
            pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n";
            pout << "\n";

            // At specified intervals, write visualization and restart files,
            // print out timer data, and store hierarchy data for post
            // processing.
	    

	    
            iteration_num += 1;
            const bool last_step = !time_integrator->stepsRemaining();
            if (dump_viz_data && (iteration_num % viz_dump_interval == 0 || last_step))
            {
                pout << "\nWriting visualization files...\n\n";
                if (uses_visit)
                {
                    time_integrator->setupPlotData();
                    visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);
                }
                if (uses_exodus)
                {
			   ib_pressure_processor->postProcessData(loop_time);
             		ib_post_processor->postProcessData(loop_time);     
		     		beam_exodus_io->write_timestep(
                        beam_exodus_filename, *beam_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);
                
                    std::ostringstream file_name;
            		file_name << beam_exodus_filename +"_"
                      << std::setw(6)
                      << std::setfill('0')
                      << std::right
                      << iteration_num;
            		GMVIO(beam_mesh).write_equation_systems(file_name.str()+".gmv",*beam_equation_systems);


				}
            }
            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))
            {
                pout << "\nWriting restart files...\n\n";
                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);
           	    ib_method_ops->writeRestartEquationSystems(restart_dump_dirname, iteration_num);
	    }
            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))
            {
                pout << "\nWriting timer data...\n\n";
                TimerManager::getManager()->print(plog);
            }
            if (dump_postproc_data && (iteration_num % postproc_data_dump_interval == 0 || last_step))
            {
                pout << "\nWriting state data...\n\n";
                postprocess_data(patch_hierarchy,
                                 navier_stokes_integrator,
                                 beam_mesh,
                                 beam_equation_systems,
                                 //,  block_mesh,
                                 //, // block_equation_systems,
                                 iteration_num,
                                 loop_time,
                                 postproc_data_dump_dirname);
            }
        }

        // Close the logging streams.
        if (SAMRAI_MPI::getRank() == 0)
        {
            drag_stream.close();
            lift_stream.close();
	    moment_stream.close();
            A_x_posn_stream.close();
            A_y_posn_stream.close();
        }

        // Cleanup Eulerian boundary condition specification objects (when
        // necessary).
        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];

    } // cleanup dynamically allocated objects prior to shutdown

    SAMRAIManager::shutdown();
    return 0;
} // main
void openStream(int mVideoIndex)
{
	out.open(mVideoData[mVideoIndex].name + ".txt", ios::out);
}
Exemplo n.º 10
0
// Main method
int main(int argc, char* argv[]) {
	if (argc != 7) {
		// Wrong number of parameters
		cerr << "Wrong number of parameters!" << endl << endl;
		printUsage();
		return -1;
	}

	// Right number of parameters; parse them
	string fileName = "";
	int pn = 0;
	int gn = 0;
	int rn = 0;
	int fn = 0;
	int kernelType = -1;

	try {
		// Split arguments
		fileName = argv[1];
		pn = stoi(argv[2]);
		gn = stoi(argv[3]);
		rn = stoi(argv[4]);
		fn = stoi(argv[5]);
		kernelType = stoi(argv[6]);
	}
	catch (std::invalid_argument e) {
		cerr << "Found wrong parameter!" << endl;
		printUsage();
		return -1;
	}
	catch (std::out_of_range e) {
		cerr << "Found out of range parameter!" << endl;
		printUsage();
		return -1;
	}

	if (pn < 1) {
		cerr << "The number of people must be positive!" << endl;
		printUsage();
		return -1;
	}

	if (gn < 1) {
		cerr << "The number of gesture classes must be positive!" << endl;
		printUsage();
		return -1;
	}

	if (rn < 1) {
		cerr << "The number of repetitions for each gesture must be positive!" << endl;
		printUsage();
		return -1;
	}

	if (fn < 1) {
		cerr << "The number of features must be positive!" << endl;
		printUsage();
		return -1;
	}

	SVM::KernelTypes kernel;
	switch (kernelType) {
	case 0: kernel = SVM::KernelTypes::LINEAR; break;
	case 1: kernel = SVM::KernelTypes::POLY; break;
	case 2: kernel = SVM::KernelTypes::RBF; break;
	case 3: kernel = SVM::KernelTypes::SIGMOID; break;
	case 4: kernel = SVM::KernelTypes::CHI2; break;
	case 5: kernel = SVM::KernelTypes::INTER; break;
	default: cerr << "Invalid kernel type!" << endl;
		printUsage();
		return -1;
	}

	// Open log file	
	logFile.open(fileName + "_log.txt");
	if (!logFile.is_open()) {
		cerr << "Unable to create log file!" << endl;		
		return -1;
	}

	cout << "Dataset file name: " << fileName << endl;
	cout << "Number of people: " << pn << endl;
	cout << "Number of gesture classes: " << gn << endl;
	cout << "Number of repetitions per gesture: " << rn << endl;
	cout << "Number of features: " << fn << endl;
	cout << "Kernel type: " << kernelType << endl;
	logFile << "Dataset file name: " << fileName << endl;
	logFile << "Number of people: " << pn << endl;
	logFile << "Number of gesture classes: " << gn << endl;
	logFile << "Number of repetitions per gesture: " << rn << endl;
	logFile << "Number of features: " << fn << endl;
	logFile << "Kernel type: " << kernelType << endl;

	// Read dataset
	Mat_<float> dataset;
	bool res = readDataset(fileName, pn, gn, rn, fn, dataset);
	if (!res) {
		logFile.close();
		return -1;
	}
	else {
		// Call training method
		trainSVMParallel(dataset, pn, gn, rn, fn, kernel, fileName + "_confusionMatrix.dat");
		logFile.close();
	}	
	return 0;
}
Exemplo n.º 11
0
int main()
{
    
    //Open output file
    file.open("Result_ADI_Hetero_II.txt", fstream::app|fstream::out);
    
    if (! file)
    {
        //if fail to open the file
        cerr << "can't open output file Result_ADI_Hetero_II.txt!" << endl;
        exit(EXIT_FAILURE);
    }
    
    file << setprecision(10);
    cout << setprecision(10);
    
    //--------------------------------------------------------------
    // output header to screen and file
    cout << "N\tL\tT\tlambda0\tlambda1\tlambda2\tK\th\tb\tCost";
    file << "N\tL\tT\tlambda0\tlambda1\tlambda2\tK\th\tb\tCost";
    
    for (int vv = 0; vv <= VMAX; vv++)
    {
        cout << "\t" << "s" << vv << "\t" << "S" << vv;
        file << "\t" << "s" << vv << "\t" << "S" << vv;
    }
    cout << endl;
    file << endl;

    
    // initialize parameters
    //K = 100;
    //h = 1.0;
    //b = 9.0;
    //lambda[0] = 4;
    //lambda[1] = 1;
    //lambda[2] = 1;
    
    for (lambda[0] = 0; lambda[0] <= 5; lambda[0]++)
    {
        lambda[1] = 1;
        lambda[2] = 5 - lambda[0];

        // initialize demand distributions
        phi_Init();

        for(K = 50; K <= 200; K *= 2)
        for(h = 1; h <= 5; h += 2)
        for(b = 9; b <= 29; b += 10)
        {
        
            cout << N << "\t" << L << "\t" << T << "\t" << lambda[0] << "\t" << lambda[1] << "\t" << lambda[2] << "\t" << K << "\t" << h << "\t" << b << "\t";
            file << N << "\t" << L << "\t" << T << "\t" << lambda[0] << "\t" << lambda[1] << "\t" << lambda[2] << "\t" << K << "\t" << h << "\t" << b << "\t";
            
            // initialize memory for saving the value function
            for (int i = 0; i <= N; i++)
                for (int j = 0; j <= UMAX; j++)
                    for (int k = 0; k <= VMAX; k++)
                        f[i][j][k] = -7;
            
            
            // cost via the DP
            double C1 = F(1, 0, 0);
            
            cout << C1 << "\t";
            file << C1 << "\t";
            
            
            //search for optimal (s, S) in period 1
            for (int j = -40; j <= 40; j++)
                for (int k = 0; k <= VMAX; k++)
                    F(1, j, k);
            
            for (int vv = 0; vv <= VMAX; vv++)
            {
                for (int uu = UMAX; uu >= 0; uu--)
                {
                    if (Y[uu][vv] > uu - UMID)
                    {
                        S_Opt[vv] = Y[uu][vv];
                        s_Opt[vv] = uu - UMID;
                        
                        cout << s_Opt[vv] << "\t" << S_Opt[vv] << "\t";
                        file << s_Opt[vv] << "\t" << S_Opt[vv] << "\t";
                        
                        break;
                    }
                }
                
            }
            
            cout << endl;
            file << endl;
        }
    }
    
    file.close();
    return 0;
}
Exemplo n.º 12
0
void main()
{
     int i=0,n=0, chkstate;

     Class class1;
     Passed pass;
     Failed fail;

     clrscr();

     cout<<"Enter the number of students in the class:";
     cin>>n;

     fout.open("class.dat", ios::binary);

     for(i=1;i<=n;i++)
     {
	 class1.accept();
	 fout.write((char*)&class1, sizeof(class1));
     }

     fout.close();

     fin.open("class.dat", ios::binary);
     fout_pass.open("pass.dat", ios::binary);
     fout_fail.open("fail.dat", ios::binary);

     while(!fin.eof())
     {
	   fin.read((char*)&class1, sizeof(class1));
	   chkstate=class1.check();
	   if(chkstate==1)
	   {
	      writepass(class1, pass);
	   }

	   else
	   {
	      writefail(class1, fail);
	   }
     }

     fin.close();
     fout_pass.close();
     fout_fail.close();

     fin.open("pass.dat", ios::binary);

     while(!fin.eof())
     {
	   fin.read((char*)&pass, sizeof(pass));
	   pass.display();
     }

     fin.close();

     fin.open("fail.dat", ios::binary);

     while(!fin.eof())
     {
	   fin.read((char*)&fail, sizeof(fail));
	   fail.display();
     }
}
Exemplo n.º 13
0
void StatisticsFileWriter::initPlugin() throw() {
	StatisticsFileWriterOptions &  o = getOptions<StatisticsFileWriterOptions>();
	file.open( o.filename );
	oa = new boost::archive::text_oarchive( file, boost::archive::no_header | boost::archive::no_codecvt );
}
Exemplo n.º 14
0
Arquivo: qtm.cpp Projeto: cnga/qsim
int main(int argc, char** argv) {
  // Open trace file.
  tout.open("EXEC_TRACE");
  std::string qsim_prefix(getenv("QSIM_PREFIX"));
  if (!tout) { cout << "Could not open EXEC_TRACE for writing.\n"; exit(1); }

  // Create a runnable OSDomain.
  OSDomain *cdp = NULL;
  if (argc < 3) {
    cdp = new OSDomain(MAX_CPUS, qsim_prefix + "/../x86_64_images/vmlinuz", "x86");
    //cd.connect_console(cout);
  } else {
    cdp = new OSDomain(MAX_CPUS, argv[1]);
    //cd.connect_console(cout);
    cout << "Loaded state. Reading benchmark.\n";
    Qsim::load_file(*cdp, argv[2]);
    cout << "Loaded benchmark .tar file.\n";
  }
  OSDomain &cd(*cdp);
  cd.set_inst_cb(&cb_obj, &cb_struct::inst_cb);
  cd.set_int_cb(&cb_obj, &cb_struct::int_cb);
  cd.set_app_end_cb(&cb_obj, &cb_struct::end_cb);

  // Init. sync objects 
  pthread_barrier_init(&cpu_barrier1, NULL, cd.get_n());
  pthread_barrier_init(&cpu_barrier2, NULL, cd.get_n());


  // Launch threads
  start_time = utime();
  for (int i = 0; i < cd.get_n(); i++) {
    threads[i]     = new pthread_t    ;
    thread_args[i] = new thread_arg_t ;

    thread_args[i]->cpu    = i;
    thread_args[i]->cd     = &cd;
    thread_args[i]->icount = 0;

    pthread_create(threads[i], NULL, cpu_thread_main, thread_args[i]);
  }

  // Wait for threads to end
  for (int i = 0; i < cd.get_n(); i++) pthread_join(*threads[i], NULL);
  end_time = utime();

  // Print stats.
  for (int i = 0; i < cd.get_n(); i++) {
    cout << "CPU " << i << ": " << thread_args[i]->icount 
         << " instructions.\n";
  }
  cout << end_time - start_time << "us\n";

  // Clean up.
  pthread_barrier_destroy(&cpu_barrier1);
  pthread_barrier_destroy(&cpu_barrier2);
  for (int i = 0; i < cd.get_n(); i++) { 
    delete threads[i]; 
    delete thread_args[i];
  }

  tout.close();

  return 0;
}
Exemplo n.º 15
0
void RunProcess(void)
{
	//pair-end alignment
	if((!query_a_file.empty()) && (!query_b_file.empty()))
	{
		cout<<"Pair-end alignment:\n";
		cout<<"Query: "<<query_a_file<<"  "<<query_b_file<<"  Reference: "<<ref_file<<"  Output: "<<out_align_file<<"  "<<out_align_file_unpair<<endl;
		fin_a.open(query_a_file.c_str());
		if(!fin_a) {
			cerr<<"failed to open file: "<<query_a_file<<endl;
			exit(1);
		}
		fin_b.open(query_b_file.c_str());
		if(!fin_b) {
			cerr<<"failed to open file: "<<query_b_file<<endl;
			exit(1);
		}		
		fout.open(out_align_file.c_str());
		if(!fout) {
			cerr<<"failed to open file: "<<out_align_file<<endl;
			exit(1);
		}
		fout_unpair.open(out_align_file_unpair.c_str());
		if(!fout_unpair) {
			cerr<<"failed to open file: "<<out_align_file_unpair<<endl;
			exit(1);
		}
		n_aligned_pairs=n_aligned_a=n_aligned_b=0;
		read_a.InitialIndex();
		read_b.InitialIndex();
		Do_PairAlign();
		fin_a.close();
		fin_b.close();
		fout.close();
		fout_unpair.close();
		cout<<"Total number of aligned reads: \n"
			<<"pairs:       "<<n_aligned_pairs<<" ("<<setprecision(2)<<100.0*n_aligned_pairs/read_a._index<<"%)\n"
			<<"single a:    "<<n_aligned_a<<" ("<<setprecision(2)<<100.0*n_aligned_a/read_a._index<<"%)\n"
			<<"single b:    "<<n_aligned_b<<" ("<<setprecision(2)<<100.0*n_aligned_b/read_b._index<<"%)\n";
	}	
	//single-read alignment
	else
	{
		if(!query_a_file.empty()) {
			fin_a.open(query_a_file.c_str());
			if(!fin_a) {
				cerr<<"b failed to open file: "<<query_a_file<<endl;
				exit(1);
			}
		}
		else
		{
			cerr<<"missing query file(s)\n";
			exit(1);
		}
		cout<<"Single read alignment:\n";
		cout<<"Query: "<<query_a_file<<"  Reference: "<<ref_file<<"  Output: "<<out_align_file<<endl;
		fout.open(out_align_file.c_str());
		if(!fout) {
			cerr<<"failed to open file: "<<out_align_file<<endl;
			exit(1);
		}
		n_aligned=0;
		read_a.InitialIndex();
		Do_SingleAlign();
		fin_a.close();
		fout.close();
		cout<<"Total number of aligned reads: "<<n_aligned<<" ("<<setprecision(2)
		<<100.0*n_aligned/read_a._index<<"%)\n";
	}

	cout<<"Done.\n";
	cout<<"Finished at "<<Curr_Time();
	cout<<"Total time consumed:  "<<Cal_AllTime()<<" secs\n";
};
Exemplo n.º 16
0
/// wsm_tx - wait for data on eth0 interface socket fd_listen
void wsm_tx(int sock_t, void *eloop_data, void *user_data)
{
  timeUtils::getFullTimeStamp(fullTimeStamp);
	ssize_t bytesReceived = recv(sock_t,recvbuf,sizeof(recvbuf),0);
  /// recvbuf: mmitss header + payload
  
  if (bytesReceived > 0 && (size_t)bytesReceived > sizeof(mmitss_udp_header_t))
  {
    mmitss_udp_header_t* header = (mmitss_udp_header_t*)&recvbuf[0];
    if (header->msgheader != msg_header)
      return;
    if (verbose)
    {
      cout << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
      cout << ", receive on eth0 " << bytesReceived << " bytes, 0x" << hex << uppercase << static_cast<int>(header->msgid) << dec << endl;
    }
    if (logDetails)
    {
      OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
      OS_log << ", receive on eth0 " << bytesReceived << " bytes, 0x" << hex << uppercase << static_cast<int>(header->msgid) << dec << endl;
      l_logRows++;
    }
    
		it = wmeUtils::mmitssMsgid2psidMap.find(header->msgid);
    if (it == wmeUtils::mmitssMsgid2psidMap.end())
    {
      cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
			cerr << ", failed finding msgid 0x" << hex << uppercase << static_cast<int>(header->msgid) << dec << " in mmitssMsgid2psidMap" << endl;
      if (logFile)
      {
        OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
        OS_log << ", failed finding msgid 0x" << hex << uppercase << static_cast<int>(header->msgid) << dec << " in mmitssMsgid2psidMap" << endl;
        l_logRows++;
      }  
    }  
		else
		{
			ite = appHandle.appPSIDmap.find(it->second);
			if (ite != appHandle.appPSIDmap.end() && savariHandle[ite->second].isRegistered)
			{
				savariHandle[ite->second].wmetx.tx_length = static_cast<int>(header->length);
				if (wme_wsm_tx(handler[appHandle.applications[ite->second].e_iface],&(savariHandle[ite->second].wmetx),&recvbuf[sizeof(mmitss_udp_header_t)]) < 0)
				{
          cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
					cerr << ", failed wme_wsm_tx for " << appHandle.applications[ite->second].s_name;
          if (logFile)
          {
            OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
            OS_log << ", failed wme_wsm_tx for " << appHandle.applications[ite->second].s_name;
            l_logRows++;
          }
				}		
				else 
        {
          if(verbose)
          {
            cout << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
            cout << ", send msgid 0x" << hex << uppercase << static_cast<int>(header->msgid) << dec << ", application " << appHandle.applications[ite->second].s_name;
            cout << " to wme psid 0x" << hex << uppercase << it->second << dec << " for broadcast" << endl;
          }
          if (logDetails)
          {
            OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);              
            OS_log << ", send msgid 0x" << hex << uppercase << static_cast<int>(header->msgid) << dec << ", application " << appHandle.applications[ite->second].s_name;
            OS_log << " to wme psid 0x" << hex << uppercase << it->second << dec << " for broadcast" << endl;
            l_logRows++;
          }  
        }
			}
    }
	}
  
  /// check reopen log files
  if (logFile && fullTimeStamp.tms_minute > logfile_tms_minute + logFileInterval)
  {
    OS_log.close();
    if (l_logRows == 0)
      remove(s_logfilename.c_str());
    s_logfilename = appHandle.s_logPath + std::string("/wmetx.") + timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp) + std::string(".log");    
    OS_log.open(s_logfilename.c_str());
    l_logRows = 0;
    
    logfile_tms_minute = fullTimeStamp.tms_minute;
  }
}
int main(int argc, char* argv[]){
	bool test, loop;
	bool** stateset, **temp;

	int n, p, omega, m, count, nchoosem, counter;
	int i, j, k, q;
	int* list;

	char* outfile, *outfile_screenprint;

	double energy, g, d, tolerance, time;
	double** hamiltonian, **hamil, **vectors, **eigenvalues;
	tolerance = 1e-10;

	/************************************
		Check for proper file input
	************************************/
	if(argc<7){
		cout << "Bad usage. Enter also 'level_count degeneracy level_spacing g outfilename screenprint_filename' on same line" << endl;
		exit(1);
	}
	else{
		p = atoi(argv[1]);
		omega = atoi(argv[2]);
		n = p*omega;
		d = atof(argv[3]);
		g = atof(argv[4]);
		outfile = argv[5];
		outfile_screenprint = argv[6];
	}

	/************************************
		Print to screen constants
		and labels for coming chart
	************************************/
	ofile2.open(outfile_screenprint);

	ofile2 << endl;
	ofile2 << "p=" << p << setw(10) << "omega=" << omega<< setw(10) << "d=" << d << setw(10) << "g=" << g << endl;
	ofile2 << endl;
	ofile2 << "part" << setw(6) << "bp" << setw(10) << "states" << setw(10) << "gs en." << setw(10) << "time" << endl;
	
	cout << endl;
	cout << "p=" << p << setw(10) << "omega=" << omega<< setw(10) << "d=" << d << setw(10) << "g=" << g << endl;
	cout << endl;
	cout << "part" << setw(6) << "bp" << setw(10) << "states" << setw(10) << "gs en." << setw(10) << "time" << endl;

	/************************************
		Write labels to file
	************************************/
	ofile.open(outfile);
	ofile << "#m";
	for(i=0;i<p/2+1;i++){
		ofile << setw(8) << i << "bp";
	}
	ofile << endl;

	/************************************
		Begin looping over number of
		particles. Allocate stateset
	************************************/
	for(i=1;i<n+1;i++){
		m=i;
		choose(nchoosem, n, m);
		matrix_alloc(stateset, nchoosem, n);
		construct_stateset(stateset, count, n, m);
		ofile << m;
		ofile2 << endl << m << endl;
		cout << endl << m << endl;

		/************************************
			Begin looping over number of
			broken pairs. Allocate and
			initialize matrices.
		************************************/
		for(q=0;q<m/2+1;q++){

			/************************************
				Start clock.
				Calculate how many states will
				have q broken pairs given
					n, omega, m
				If count==0, break loop
			************************************/
			start = clock();
			count_brokenpairstates(count, n, omega, m, q);
			if(count==0){
				break;
			}

			/************************************
				**list holds the location of 
					appropriate states from 
					stateset
				**temp is created from the **list
					of states
				**hamiltonian is energy matrix
				**hamil copies hamiltonian so it
					may be printed to screen
				**vectors are the state vectors
					of hamiltonian--shows mixing
				**eigenvalues is to be an ordered
					list of energies, sm-->lg
			************************************/
			array_alloc(list,count);
			matrix_alloc(temp, count, n);
			matrix_alloc(hamiltonian, count, count);
			matrix_alloc(hamil, count, count);
			matrix_alloc(vectors, count, count);
			matrix_alloc(eigenvalues, count, 2);
			for(j=0;j<count;j++){
				vectors[j][j] = 1.0;
			}
			for(j=0;j<count;j++){
				eigenvalues[j][0] = 0;
				eigenvalues[j][1] = -1;
			}

			/************************************
				construct list from stateset of 
				those states which have q broken
				pairs
			************************************/
			construct_brokenpairs_list(stateset, list, nchoosem, n, omega, q);
			for(j=0;j<count;j++){
				for(k=0;k<n;k++){
					temp[j][k] = stateset[list[j]][k];
				}
			}
			
			/************************************
				construct and diagonalize the
				energy matrix given our pairing
				hamiltonian
			************************************/
			derive_hamiltonian_matrix_zproj0(hamiltonian, temp, count, n, omega, d, g);
			jacobi_simrot_eigen_solver(hamiltonian, vectors, count, tolerance, counter);
			matrix_diag_sort(hamiltonian, eigenvalues, count);


			/************************************
				Calculate time to find all states
				with q broken pairs, construct
				hamiltonian, and diagonalize,
				all steps necessary to find
				groundstate energy.
			************************************/
			finish = clock();
			time = (finish - start)/((double) CLOCKS_PER_SEC);

			/************************************
				Print to screen information about
				bp, states, gs en., time
			************************************/
			ofile2 << setw(10) << q << setw(10) << count << setw(10) <<  setw(10) << eigenvalues[0][0] << setw(15) << time << endl;			
			cout << setw(10) << q << setw(10) << count << setw(10) <<  setw(10) << eigenvalues[0][0] << setw(15) << time << endl;
			ofile << setw(10) << eigenvalues[0][0];

			/************************************
				Delete all but stateset to allow
				for next broken pair count
			************************************/
			array_delete(list);
			matrix_delete(temp, count);
			matrix_delete(hamiltonian, count);
			matrix_delete(vectors, count);
			matrix_delete(eigenvalues, count);
		}

		/************************************
			Next line in output file
			Delete stateset to allow for next
			next particle count
		************************************/
		ofile << endl;
		matrix_delete(stateset, nchoosem);
	}

	/************************************
		close output file
		create space for tidy screen
	************************************/
	ofile.close();
	ofile2.close();
	cout << endl;
	return 0;

}
Exemplo n.º 18
0
int main (int argc, char** argv)
{
	int option;
	char* f_wmefwdConfig = NULL;
  
	/// getopt
	while ((option = getopt(argc, argv, "c:f:v")) != EOF) 
	{
		switch(option) 
		{
		case 'c':
			f_wmefwdConfig = strdup(optarg);
			break;
    case 'f':
      {
        int flag = atoi(optarg);
        if (flag > 0) 
          logFile = true;
        if (flag > 1)
          logDetails = true;
      }
      break;
		case 'v':
			verbose = true;
			break;
		default:
			do_usage(argv[0]);
			break;
		}
	}
	if (f_wmefwdConfig == NULL)
		do_usage(argv[0]);
	
	/* ----------- preparing -------------------------------------*/  
  timeUtils::getFullTimeStamp(fullTimeStamp);  
	/// instance WMEconfig::configWme to read configuration files
	WMEconfig::configWme s_appConfig(f_wmefwdConfig);
	if (!s_appConfig.isConfigSucceed())
	{
    cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
		cerr << ", failed construct WMEconfig::configWme, filename " << f_wmefwdConfig << endl;
		delete f_wmefwdConfig;
		exit(1);
	}
	delete f_wmefwdConfig;
  
	appHandle = s_appConfig.getAppHandler();
  if (appHandle.applications.empty())
  {
    cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
    cerr << ", appHandle: no applications" << endl;
    exit(1);
  }
  
  /// open log file
  logFileInterval = static_cast<long long>(appHandle.i_logInterval) * 60 * 1000LL; 
  s_logfilename = appHandle.s_logPath + std::string("/wmetx.") + timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp) + std::string(".log");
  if (logFile)
  {
    OS_log.open(s_logfilename.c_str());
    if (!OS_log.is_open())
    {
      cerr << "Failed open logfile " << s_logfilename << endl;
      exit(1);      
    }
    logfile_tms_minute = fullTimeStamp.tms_minute;
    l_logRows = 0;
  }
	if (verbose)
	{
		cout << "appHandle " << appHandle.applications.size() << " applications, map size " << appHandle.appPSIDmap.size() << endl;		
		for (ite = appHandle.appPSIDmap.begin(); ite != appHandle.appPSIDmap.end(); ite++)
		{
      if (appHandle.applications[ite->second].e_direction == WMEconfig::appConfigEnum_t::RX)
        continue;
			cout << "Application " << appHandle.applications[ite->second].s_name;
			cout << " psid: " << "0x" << hex << uppercase << ite->first << dec;
      cout << " network byte order psid: " << "0x" << hex << uppercase << wme_convert_psid_be(ite->first) << dec;
			cout << ", application index: " << ite->second << endl;
		}
	}
  if (logFile)
	{
		OS_log << "appHandle " << appHandle.applications.size() << " applications, map size " << appHandle.appPSIDmap.size() << endl;		
		for (ite = appHandle.appPSIDmap.begin(); ite != appHandle.appPSIDmap.end(); ite++)
		{
      if (appHandle.applications[ite->second].e_direction == WMEconfig::appConfigEnum_t::RX)
        continue;
			OS_log << "Application " << appHandle.applications[ite->second].s_name;
			OS_log << " psid: " << "0x" << hex << uppercase << ite->first << dec;
      OS_log << " network byte order psid: " << "0x" << hex << uppercase << wme_convert_psid_be(ite->first) << dec;
			OS_log << ", application index: " << ite->second << endl;
		}
    l_logRows++;
	}
  
	/// open eth0 listen socket
	fd_listen = socketUtils::server(*(appHandle.mpListenAddr),false);
	if (fd_listen < 0)
	{
    cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
		cerr << ", failed create listen socket" << endl;
    if (logFile)
    {
      OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
      OS_log << ", failed create listen socket" << endl;
      OS_log.close();
    }
		exit (1);
	}
  if (verbose)
  {
    cout << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
    cout << ", fd_listen = " << fd_listen << ", listen on " << appHandle.mpListenAddr->name << ":" << appHandle.mpListenAddr->port << endl;
  }
  if (logFile)
  {
    OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
    OS_log << ", fd_listen = " << fd_listen << ", listen on " << appHandle.mpListenAddr->name << ":" << appHandle.mpListenAddr->port << endl;
    l_logRows++;
  }
	  
	/// fill structure savariWmeHandler_t
	uint8_t broadcast_mac[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
	savariHandle.resize(appHandle.applications.size());
	for (size_t i = 0; i < appHandle.applications.size(); i++)
	{
		savariHandle[i].isRegistered = false;
    /// wmereq
		memset(&(savariHandle[i].wmereq),0,sizeof(struct savariwme_reg_req));
		savariHandle[i].wmereq.channel = appHandle.applications[i].channel;
		memcpy(savariHandle[i].wmereq.destmacaddr, broadcast_mac, SAVARI1609_IEEE80211_ADDR_LEN);
		savariHandle[i].wmereq.psid = wme_convert_psid_be(appHandle.applications[i].psid);
    wmePSIDmap[savariHandle[i].wmereq.psid] = i;
		savariHandle[i].wmereq.priority = appHandle.applications[i].priority;
#ifdef RSU		
		if (appHandle.applications[i].e_channelMode == wmeUtils::channelmode_enum_t::CONTINUOUS)
		{			
      /* type of user application request:
          SAVARI1609_USER_AUTOACCESS_ONMATCH (Switch Between 178 and SCH after receiving Matching WSA from RSE)
          SAVARI1609_USER_AUTOACCESS_UNCOND (Start Switching between 178 and SCH without Waiting for Matching WSA from RSEs)
          SAVARI1609_USER_AUTOACCESS_NOSCHACCESS(CCH Only Mode. No Switching). Only applicable if channel_access is ALTERNATING
      */
			savariHandle[i].wmereq.request_type = SAVARI1609_USER_AUTOACCESS_ONMATCH;
			savariHandle[i].wmereq.extended_access = 0xFFFF;
			savariHandle[i].wmereq.channel_access = SAVARI1609_CHANNEL_ACCESS_CONTINUOUS;   // value 0
		}
		else
		{
			savariHandle[i].wmereq.request_type = SAVARI1609_USER_AUTOACCESS_UNCOND;
			savariHandle[i].wmereq.extended_access = 0;
			savariHandle[i].wmereq.channel_access = SAVARI1609_CHANNEL_ACCESS_ALTERNATING;  // value 1
		}	
#else
//    savariHandle[i].wmereq.channel_access = LIBWME_CHANNEL_ACCESS_CONTINUOUS; // default LIBWME_CHANNEL_ACCESS_CONTINUOUS = 0
		savariHandle[i].wmereq.request_type = LIBWME_USER_AUTOACCESS_ONMATCH;
		savariHandle[i].wmereq.extended_access = 0xFFFF;    // continuous access
#endif		
		savariHandle[i].wmereq.immediate_access = 0;
//    savariHandle[i].wmereq.wsatype = SAVARI1609_WSA_UNSECURED;  /// default SAVARI1609_WSA_UNSECURED = 0
		savariHandle[i].wmereq.psc_length = static_cast<int>(appHandle.applications[i].s_psc.size() + 1);
		memcpy(savariHandle[i].wmereq.psc, appHandle.applications[i].s_psc.c_str(), savariHandle[i].wmereq.psc_length);
    savariHandle[i].wmereq.local_service_index = static_cast<int>(i+1);
    if (appHandle.applications[i].e_iface == wmeUtils::channelmode_enum_t::ATH0_)
      savariHandle[i].wmereq.secondradio = 0;
    else
      savariHandle[i].wmereq.secondradio = 1;
    /// wmetx
		memset(&(savariHandle[i].wmetx),0, sizeof(struct savariwme_tx_req));
		savariHandle[i].wmetx.channel = appHandle.applications[i].channel;
		savariHandle[i].wmetx.psid = savariHandle[i].wmereq.psid;
		savariHandle[i].wmetx.priority = appHandle.applications[i].priority;
		savariHandle[i].wmetx.datarate = 6; //3Mbps
		savariHandle[i].wmetx.txpower = 15; //in dbM
		memcpy(savariHandle[i].wmetx.mac, broadcast_mac, SAVARI1609_IEEE80211_ADDR_LEN);
		savariHandle[i].wmetx.expiry_time = 0;
		savariHandle[i].wmetx.element_id = WAVE_ELEMID_WSMP;
		savariHandle[i].wmetx.tx_length = 0;    // fill tx_length on-the-fly
		savariHandle[i].wmetx.supp_enable = 0;  // do not consider the safetysupp to transmit in the WSMP header
    savariHandle[i].wmetx.safetysupp = 0;
  }
    
  /// connect to WME
  for (int i=0;i<2;i++)
  {
    handler[i] = wme_init("::1", (char*)wmeUtils::iface[i]);
    if (handler[i] < 0)
    {
      cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);          
      cerr << ", failed wme_init for interface " << wmeUtils::iface[i] << endl;
      if (logFile)
      {
        OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);          
        OS_log << ", failed wme_init for interface " << wmeUtils::iface[i] << endl;
        OS_log.close();
      }      
      close(fd_listen);
      exit(1);
    }
    if (verbose)
    {
      cout << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);          
      cout << ", handler = " << handler[i] << ", wme_init succeed for interface " << wmeUtils::iface[i] << endl;
    }
    if (logFile)
    {
      OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);          
      OS_log << ", handler = " << handler[i] << ", wme_init succeed for interface " << wmeUtils::iface[i] << endl;
      l_logRows++;
    }
  }
  
	/// initial event loop
	if (eloop_init(0) < 0)
	{
    cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);          
		cerr << ", failed eloop_init" << endl;
    if (logFile)
    {
      OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);          
      OS_log << ", failed eloop_init" << endl;
      OS_log.close();
    }
		close(fd_listen);
		exit(1);
	}
  
  /// register applications to WME
  int ret;
	for (size_t i = 0; i < appHandle.applications.size(); i++)
	{
    if (appHandle.applications[i].e_direction == WMEconfig::appConfigEnum_t::RX)
      continue;
    if (appHandle.applications[i].e_registerType == WMEconfig::appConfigEnum_t::USER)
      ret = wme_register_user(handler[appHandle.applications[i].e_iface],&savariHandle[i].wmereq);
    else
      ret = wme_register_provider(handler[appHandle.applications[i].e_iface],&savariHandle[i].wmereq);
    
    if (ret < 0)
    {
      cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
      cerr << ", failed wme_register for " << appHandle.applications[i].s_name << endl;
      if (logFile)
      {
        OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
        OS_log << ", failed wme_register for " << appHandle.applications[i].s_name << endl;
      }
      close_all();
    }
    
    savariHandle[i].isRegistered = true;
    if (verbose)
    {
      cout << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
      cout << ", wme_register succeed for " << appHandle.applications[i].s_name << endl;
    }
    if (logFile)
    {
      OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
      OS_log << ", wme_register succeed for " << appHandle.applications[i].s_name << endl;
      l_logRows++;
    }
  }
    
  /// fd_listen eloop_register_read_sock
  ret = eloop_register_read_sock(fd_listen,wsm_tx,0,0);
  if (ret < 0)
  {
    cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
    cerr << ", failed eloop_register_read_sock for listening socket" << endl;
    if (logFile)
    {
      OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
      OS_log << ", failed eloop_register_read_sock for listening socket" << endl;
    }
    close_all();
  }
  if (verbose)
  {
    cout << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
    cout << ", eloop_register_read_sock succeed for listening socket" << endl;
  }
  if (logFile)
  {
    OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);                
    OS_log << ", eloop_register_read_sock succeed for listening socket" << endl;
    l_logRows++;
  } 
  
	/* ----------- intercepts signals -------------------------------------*/
	if (setjmp(exit_env) != 0) 
	{
    timeUtils::getFullTimeStamp(fullTimeStamp);
    cerr << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);          
		cerr << ", received user termination signal, quit!" << endl;
    if (logFile)
    {
      OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
      OS_log << ", received user termination signal, quit!" << endl;
    }
    close_all();
	}
	else
		sig_ign( sig_list, sig_hand );  
  
	if (verbose)
	{
    cout << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
		cout << ", start eloop_run waiting for data ..." << endl;
	}
  if (logFile)
  {
    OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
    OS_log << ", start eloop_run waiting for data ..." << endl;
    l_logRows++;
  }
	eloop_run();
	
	/// should not be here
  if (logFile)
  {
    timeUtils::getFullTimeStamp(fullTimeStamp);
    OS_log << timeUtils::getTimestampStr(fullTimeStamp.localDateTimeStamp);
    OS_log << ", exited from eloop_run!" << endl;
  }  
  close_all();
	return 0;
}
Exemplo n.º 19
0
int _tmain(int argc, _TCHAR* argv[])
{
	CString s_filefolder;
	s_filefolder.Format("..\\output");
	_mkdir(s_filefolder);
	outfile.open("..\\output\\HOGfeature.csv", ios::out);

	CvMat* cvMat_ori = cvCreateMat(height,width,CV_64FC1);
	CvMat* cvMat_Gh = cvCreateMat(height,width,CV_64FC1);
	CvMat* cvMat_Gv = cvCreateMat(height,width,CV_64FC1);
	CvMat* cvMat_M = cvCreateMat(height,width,CV_64FC1);
	CvMat* cvMat_Angle = cvCreateMat(height,width,CV_64FC1);

	double minDepth;
	double maxDepth;
	getAFrame(cvMat_ori, minDepth, maxDepth); //Just get one frame for testing.
	cout<<minDepth<<'\t'<<maxDepth<<endl;

	IplImage* img_show = cvCreateImage(cvSize(width,height),8,1);
	//mat2Image(cvMat_ori,img_show);
	calGh(cvMat_ori, cvMat_Gh);
	calGv(cvMat_ori, cvMat_Gv);
	calMAndAngle(cvMat_Gh, cvMat_Gv, cvMat_M, cvMat_Angle);
	mat2Image(cvMat_M,img_show);
	drawAngle(cvMat_M, cvMat_Angle);


	int blockSize = 64;
	int blockStrid = 32;
	int cellSize = 32;
	int bin = 9;
	
	int cellNum = blockSize/cellSize;
	int BlockNumH = (height-blockSize)/blockStrid + 1;
	int BlockNumW = (width-blockSize)/blockStrid + 1;

	int dimension = BlockNumH*BlockNumW*bin*cellNum*cellNum;
	double* hogFeature = new double[dimension];
	calHOG(cvMat_M, cvMat_Angle, hogFeature, blockSize, blockStrid, cellSize, bin);

	//hogFeature is normalized here. The sum is 1.0;
	double den = 0.0;
	for (int k=0; k<dimension; k++)
	{
		den += abs(hogFeature[k]);
	}
	den = den+ep;
	for (int k=0; k<dimension; k++)
	{
		hogFeature[k] /= den;
		outfile<<hogFeature[k]<<endl;
	}



	delete[] hogFeature;
	cout<<"Done!"<<endl;
	outfile.close();
	getchar();
	return 0;
}
Exemplo n.º 20
0
//------------------------------------------------------------------------------------
// called from EditDDs.cpp
int OutputRawDData(const DDid& ddid, const DDData& dddata, const vector<int>& mark)
   throw(Exception)
{
try {
   bool TripleOut=true;                      // output triple differences as well
   if(CI.OutputRawDDFile.empty()) return 0;

   static ofstream rddofs;

      // allow caller to close the file...
   if(mark.size() == 0) {
      if(rddofs.is_open()) rddofs.close();
      return 0;
   }

   if(!rddofs.is_open()) {           // first call : open the file
      if(CI.Verbose) oflog << "BEGIN OutputRawDData()" << endl;
      rddofs.open(CI.OutputRawDDFile.c_str(),ios::out);
      if(rddofs.is_open()) {
         oflog << "Opened file " << CI.OutputRawDDFile
            << " for raw DD data output." << endl;
         rddofs << "# " << Title << endl;
         rddofs << "RDD sit1 sit2 sat ref week  sec_wk     flag      DDL1_m"
            << "           "
            << "DDL2_m           DDER_m            resL1_m          resL2_m";
         if(CI.Frequency == 3) rddofs << "          WLbias_m";
         rddofs << endl;
         if(TripleOut) rddofs
            << "RTD sit1 sit2 sat ref week  sec_wk     flag      TDL1_m"
            << "           TDL2_m           TDER_m" << endl;
      }
      else {
         // TD error msg
         return -1;
      }
   }

   int i;
   double wlb;
   DayTime tt;
   format f166(16,6);

      // loop over epochs
   for(i=0; i<dddata.count.size(); i++) {

      tt = FirstEpoch + dddata.count[i]*CI.DataInterval;

      if(CI.Frequency == 3)
         wlb =   wl1p * dddata.DDL1[i]      // wide lane range minus phase
               + wl2p * dddata.DDL2[i]      // = WL phase - NL range
               - wl1r * dddata.DDP1[i] 
               - wl2r * dddata.DDP2[i];

      rddofs << "RDD " << ddid << " " << tt.printf("%4F %10.3g")
         << " " << setw(2) << mark[i]
         << " " << f166 << dddata.DDL1[i]
         << " " << f166 << dddata.DDL2[i]
         << " " << f166 << dddata.DDER[i]
         << " " << f166 << dddata.DDL1[i] - dddata.DDER[i]
         << " " << f166 << dddata.DDL2[i] - dddata.DDER[i];
      if(CI.Frequency == 3) rddofs << " " << f166 << wlb;
      rddofs << endl;

      if(TripleOut && i>0) {
         // wlb is a dummy here, = delta time for this triple diff
         wlb = (dddata.count[i]-dddata.count[i-1])*CI.DataInterval;
         rddofs << "RTD " << ddid << " " << tt.printf("%4F %10.3g")
            << " " << setw(2) << 10*mark[i]+mark[i-1]
            << " " << f166 << (dddata.DDL1[i]-dddata.DDL1[i-1])/wlb
            << " " << f166 << (dddata.DDL2[i]-dddata.DDL2[i-1])/wlb
            << " " << f166 << (dddata.DDER[i]-dddata.DDER[i-1])/wlb
            << endl;
      }
   }

   return 0;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}   // end OutputRawDData()
Exemplo n.º 21
0
/*******************************************
 * Model: runSobelST
 * Input: None
 * Output: None
 * Desc: This method pulls in an image from the webcam, feeds it into the
 *   sobelCalc module, and displays the returned Sobel filtered image. This
 *   function processes NUM_ITER frames.
 ********************************************/
void runSobelST()
{
    // Set up variables for computing Sobel
    string top = "Sobel Top";
    Mat src;
    uint64_t cap_time, gray_time, sobel_time, disp_time, sobel_l1cm, sobel_ic;

    counters_t perf_counters;

    pc_init(&perf_counters, getpid());

    // Start algorithm
    CvCapture* web_cam_cap;
//  web_cam_cap = cvCreateCameraCapture(0);
    web_cam_cap = cvCreateFileCapture("baxter.avi");
    cvSetCaptureProperty(web_cam_cap, CV_CAP_PROP_FRAME_WIDTH, IMG_WIDTH);
    cvSetCaptureProperty(web_cam_cap, CV_CAP_PROP_FRAME_HEIGHT, IMG_HEIGHT);

    // Keep track of the frames
    int i = 0;

    while (1) {
        // Allocate memory to hold grayscale and sobel images
        img_gray = Mat(IMG_HEIGHT, IMG_WIDTH, CV_8UC1);
        img_sobel = Mat(IMG_HEIGHT, IMG_WIDTH, CV_8UC1);

        pc_start(&perf_counters);
        src = cvQueryFrame(web_cam_cap);
        pc_stop(&perf_counters);

        cap_time = perf_counters.cycles.count;
        sobel_l1cm = perf_counters.l1_misses.count;
        sobel_ic = perf_counters.ic.count;

        pc_start(&perf_counters);
        grayScale(src, img_gray);
        pc_stop(&perf_counters);

        gray_time = perf_counters.cycles.count;
        sobel_l1cm += perf_counters.l1_misses.count;
        sobel_ic += perf_counters.ic.count;

        pc_start(&perf_counters);
        sobelCalc(img_gray, img_sobel);
        pc_stop(&perf_counters);

        sobel_time = perf_counters.cycles.count;

        pc_start(&perf_counters);
        namedWindow(top, CV_WINDOW_AUTOSIZE);
        imshow(top, img_sobel);
        pc_stop(&perf_counters);

        disp_time = perf_counters.cycles.count;
        sobel_l1cm += perf_counters.l1_misses.count;
        sobel_ic += perf_counters.ic.count;

        cap_total += cap_time;
        gray_total += gray_time;
        sobel_total += sobel_time;
        sobel_l1cm_total += sobel_l1cm;
        sobel_ic_total += sobel_ic;
        disp_total += disp_time;
        total_fps += PROC_FREQ/float(cap_time + gray_time + sobel_time);
        total_ipc += float(sobel_ic/float(gray_time + sobel_time));

        // Press q to exit
        char c = cvWaitKey(10);
        if (c == 'q') {
            break;
        }
        i++;
    }

    total_epf = PROC_EPC*NCORES/(total_fps/i);
    float total_time = float(gray_total + sobel_total + cap_total + disp_total);

    results_file.open("sobel_perf_st.csv", ios::out);
    results_file << "Percent of time per function" << endl;
    results_file << "Capture, " << (cap_total/total_time)*100 << "%" << endl;
    results_file << "Grayscale, " << (gray_total/total_time)*100 << "%" << endl;
    results_file << "Sobel, " << (sobel_total/total_time)*100 << "%" << endl;
    results_file << "Display, " << (disp_total/total_time)*100 << "%" << endl;
    results_file << "\nSummary" << endl;
    results_file << "Frames per second, " << total_fps/i << endl;
    results_file << "Cycles per frame, " << total_time/i << endl;
    results_file << "Energy per frames (mJ), " << total_epf*1000 << endl;
    results_file << "Total frames, " << i << endl;
    results_file << "\nHardware Stats (Cap + Gray + Sobel + Display)" << endl;
    results_file << "Instructions per cycle, " << total_ipc/i << endl;
    results_file << "L1 misses per frame, " << sobel_l1cm_total/i << endl;
    results_file << "L1 misses per instruction, " << sobel_l1cm_total/sobel_ic_total << endl;
    results_file << "Instruction count per frame, " << sobel_ic_total/i << endl;

    cvReleaseCapture(&web_cam_cap);
    results_file.close();
}
Exemplo n.º 22
0
void open_log(char *logfile){
   if(OpenLog) close_log();
   LogH.open(logfile, ios::out);
   if(!LogH.is_open()) error("Cannot open the file", logfile);
   OpenLog = true;
}
Exemplo n.º 23
0
int main()
{ BOOL bResult; char *chPtr0, *chPtr1, *chPtr2; DWORD dw1, dw2, dwIndex;
  HINTERNET hInet, hRequest; int i, iChunks;

  of_OutFile.open ("output.txt");  // Output will be written to the screen and to output.txt.

  if(InternetCheckConnection("https://api-fxpractice.oanda.com/", FLAG_ICC_FORCE_CONNECTION, 0))
  { cout << "\nCall to InternetCheckConnection returned true.\n";
    of_OutFile << "Call to InternetCheckConnection returned true.\n";
  }
  else
  { cout << "\nCall to InternetCheckConnection returned false.\n";
    of_OutFile << "Call to InternetCheckConnection returned false.\n";
    of_OutFile.close();
    return 0;
  }

  h_Inet = InternetOpen("OTest",                    // _In_ LPCTSTR lpszAgent
                        INTERNET_OPEN_TYPE_DIRECT,  // _In_ DWORD dwAccessType
                        NULL,                       // _In_ LPCTSTR lpszProxyName
                        NULL,                       // _In_ LPCTSTR lpszProxyBypass
                        NULL);                      // _In_ DWORD dwFlags

  if(h_Inet == NULL) 
  { cout       << "Call to InternetOpen returned NULL. Aborting.\n"; 
    of_OutFile << "Call to InternetOpen returned NULL. Aborting.\n";
    of_OutFile.close();
    return 0;
  }
  else
  { cout       << "Call to InternetOpen returned valid handle.\n";
    of_OutFile << "Call to InternetOpen returned valid handle.\n";
  }

  hInet = InternetConnect(h_Inet,        // _In_ HINTERNET hInternet
            "api-fxpractice.oanda.com",  // _In_ LPCTSTR lpszServerName
            INTERNET_DEFAULT_HTTPS_PORT, // _In_ INTERNET_PORT nServerPort
            NULL, // _In_ LPCTSTR lpszUsername  Don't send your user name if you don't have to. 
            NULL, // _In_ LPCTSTR lpszPassword  Don't send your password if you don't have to.
            INTERNET_SERVICE_HTTP,       // _In_ DWORD dwService
            NULL,                        // _In_ DWORD dwFlags
            NULL);                       // _In_ DWORD dwContext

  if(hInet == NULL) 
  { cout       << "Call to InternetConnect returned NULL.\n";
    of_OutFile << "Call to InternetConnect returned NULL.\n";
  }
  else
  { cout       << "Call to InternetConnect returned valid handle.\n";
    of_OutFile << "Call to InternetConnect returned valid handle.\n";
  }

// Set up request to get a single quote.
  hRequest = HttpOpenRequest(hInet,               // _In_ HINTERNET hConnect
               "GET",                             // _In_ LPCTSTR lpszVerb
               "/v1/prices?instruments=EUR_USD",  // _In_ LPCTSTR lpszObjectName, target on server
               "HTTP/1.1",                        // _In_ LPCTSTR lpszVersion
               NULL,                              // _In_ LPCTSTR lpszReferer
               str_Array,                         // _In_ LPCTSTR *lplpszAcceptTypes
               INTERNET_FLAG_SECURE,              // _In_ DWORD dwFlags
               NULL);                             // _In_ DWORD dwContext

  if(hRequest == NULL) 
  { cout       << "Call to HttpOpenRequest returned NULL.\n";
    of_OutFile << "Call to HttpOpenRequest returned NULL.\n";
  }
  else
  { cout       << "Call to HttpOpenRequest returned valid handle.\n";
    of_OutFile << "Call to HttpOpenRequest returned valid handle.\n";
  }

  bResult = HttpSendRequest(hRequest,  // _In_ HINTERNET hRequest
              "Authorization: Bearer <your_access_token>", //_In_ LPCTSTR lpszHeaders
                            -1,        // _In_ DWORD dwHeadersLength
                            NULL,      // _In_ LPVOID lpOptional
                            0);        // _In_ DWORD dwOptionalLength
  
  if(bResult)
  { cout       << "Call to HttpSendRequest returned TRUE.\n\n";
    of_OutFile << "Call to HttpSendRequest returned TRUE.\n\n";
  }
  else
  { dw1 = GetLastError();
    cout       << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
    of_OutFile << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
  }

  dw1 = 4096;  // size of ch_Buffer
  dwIndex = 0;

  bResult = HttpQueryInfo(hRequest,                     // _In_ HINTERNET hRequest
                          HTTP_QUERY_RAW_HEADERS_CRLF,  // _In_ DWORD dwInfoLevel
                          ch_Buffer,                    // _Inout_ LPVOID lpvBuffer
                          &dw1,                         // _Inout_ LPDWORD lpdwBufferLength
                          &dwIndex);                    // _Inout_ LPDWORD lpdwIndex

  if (bResult)
  { cout << "Call to HttpQueryInfo returned TRUE.\n";
    cout << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    cout << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
    of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
    of_OutFile << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    of_OutFile << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
  }
  else
  { cout       << "Call to HttpQueryInfo returned FALSE. ";
    of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << "\n";
    of_OutFile << "Error code " << dw2 << "\n";
  }

  dw1 = 4096;  // size of ch_Buffer
  dwIndex = 0;

  bResult = HttpQueryInfo(hRequest,                   // _In_ HINTERNET hRequest
                          HTTP_QUERY_CONTENT_LENGTH,  // _In_ DWORD dwInfoLevel
                          ch_Buffer,                  // _Inout_ LPVOID lpvBuffer
                          &dw1,                       // _Inout_ LPDWORD lpdwBufferLength
                          &dwIndex);                  // _Inout_ LPDWORD lpdwIndex

  ch_Buffer[dw1] = 0;  // Terminate string in ch_Buffer by appending a null character.

  if(bResult)
  { cout << "Call to HttpQueryInfo returned TRUE.\n";
    cout << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
    cout << "String in ch_Buffer: " << ch_Buffer << "\n";
    of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
    of_OutFile << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
    of_OutFile << "String in ch_Buffer: " << ch_Buffer << "\n";
  }
  else
  { cout       << "Call to HttpQueryInfo returned FALSE. ";
    of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << "\n";
    of_OutFile << "Error code " << dw2 << "\n";
  }

  dw1 = atol(ch_Buffer);  // Convert CONTENT_LENGTH string in ch_Buffer to numerical value.

  bResult = InternetReadFile(hRequest,  // _In_  HINTERNET hFile
                             ch_Buffer, // _Out_ LPVOID lpBuffer
                             dw1,       // _In_  DWORD dwNumberOfBytesToRead
                             &dw2);     // _Out_ LPDWORD lpdwNumberOfBytesRead

  ch_Buffer[dw2] = 0;  // Terminate string in ch_Buffer by appending a null character.

  if(bResult)
  { cout << "\nCall to InternetReadFile returned TRUE.\n";
    cout << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
    cout << "CONTENT string written to ch_Buffer (starting on next line):\n";
    cout << ch_Buffer << endl;
    of_OutFile << "\nCall to InternetReadFile returned TRUE.\n";
    of_OutFile << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
    of_OutFile << "CONTENT string written to ch_Buffer (starting on next line):\n";
    of_OutFile << ch_Buffer << endl;
  }
  else
  { cout       << "\nCall to InternetReadFile returned FALSE. ";
    of_OutFile << "\nCall to InternetReadFile returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << endl;
    of_OutFile << "Error code " << dw2 << endl;
  }

// Release request handle before making new request.
  InternetCloseHandle(hRequest);

// Set up request to BUY 100 units of EUR/USD.
  hRequest = HttpOpenRequest(hInet,                         // _In_ HINTERNET hConnect
                             "POST",                        // _In_ LPCTSTR lpszVerb
                             "/v1/accounts/<your_account_number>/orders", // _In_ LPCTSTR lpszObjectName
                             "HTTP/1.1",                    // _In_ LPCTSTR lpszVersion
                             NULL,                          // _In_ LPCTSTR lpszReferer
                             str_Array,                     // _In_ LPCTSTR *lplpszAcceptTypes
                             INTERNET_FLAG_SECURE,          // _In_ DWORD dwFlags
                             NULL);                         // _In_ DWORD dwContext

  if(hRequest == NULL) 
  { cout       << "\nCall to HttpOpenRequest returned NULL.\n";
    of_OutFile << "\nCall to HttpOpenRequest returned NULL.\n";
  }
  else
  { cout       << "\nCall to HttpOpenRequest returned valid handle.\n";
    of_OutFile << "\nCall to HttpOpenRequest returned valid handle.\n";
  }

  HttpAddRequestHeaders(hRequest,
    "Authorization: Bearer <your_access_token>" , // _In_  LPCTSTR lpszHeaders,
                        -1,  //_In_  DWORD dwHeadersLength
                        0);  //_In_  DWORD dwModifiers

// Specify parameters of order in body of request.
  char *chValues = "instrument=EUR_USD&units=100&side=buy&type=market";

  bResult = HttpSendRequest(hRequest,                                           // _In_ HINTERNET hRequest
                            "content-type: application/x-www-form-urlencoded",  // _In_ LPCTSTR lpszHeaders
                            -1,                                                 // _In_ DWORD dwHeadersLength
                            chValues,                                           // _In_ LPVOID lpOptional
                            strlen(chValues));                                  // _In_ DWORD dwOptionalLength
  
  if(bResult)
  { cout       << "Call to HttpSendRequest returned TRUE.\n";
    of_OutFile << "Call to HttpSendRequest returned TRUE.\n";
  }
  else
  { dw1 = GetLastError();
    cout       << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
    of_OutFile << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
  }

  dw1 = 4096;  // size of ch_Buffer
  dwIndex = 0;

  bResult = HttpQueryInfo(hRequest,         // _In_ HINTERNET hRequest
              HTTP_QUERY_RAW_HEADERS_CRLF,  // _In_ DWORD dwInfoLevel
              ch_Buffer,                    // _Inout_ LPVOID lpvBuffer
              &dw1,                         // _Inout_ LPDWORD lpdwBufferLength
              &dwIndex);                    // _Inout_ LPDWORD lpdwIndex

  if (bResult)
  { cout << "Call to HttpQueryInfo returned TRUE.\n";
    cout << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    cout << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
    of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
    of_OutFile << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    of_OutFile << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
  }
  else
  { cout       << "Call to HttpQueryInfo returned FALSE. ";
    of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << "\n";
    of_OutFile << "Error code " << dw2 << "\n";
  }

  dw1 = 4096;  // size of ch_Buffer
  dwIndex = 0;

  bResult = HttpQueryInfo(hRequest,                   // _In_ HINTERNET hRequest
                          HTTP_QUERY_CONTENT_LENGTH,  // _In_ DWORD dwInfoLevel
                          ch_Buffer,                  // _Inout_ LPVOID lpvBuffer
                          &dw1,                       // _Inout_ LPDWORD lpdwBufferLength
                          &dwIndex);                  // _Inout_ LPDWORD lpdwIndex

  ch_Buffer[dw1] = 0;  // Terminate string in ch_Buffer by appending a null character.

  if(bResult)
  { cout << "Call to HttpQueryInfo returned TRUE.\n";
    cout << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
    cout << "String in ch_Buffer: " << ch_Buffer << "\n";
    of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
    of_OutFile << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
    of_OutFile << "String in ch_Buffer: " << ch_Buffer << "\n";
  }
  else
  { cout       << "Call to HttpQueryInfo returned FALSE. ";
    of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << "\n";
    of_OutFile << "Error code " << dw2 << "\n";
  }

  dw1 = atol(ch_Buffer); // Convert CONTENT_LENGTH string in ch_Buffer to numerical value.

  bResult = InternetReadFile(hRequest,  // _In_  HINTERNET hFile
                             ch_Buffer, // _Out_ LPVOID lpBuffer
                             dw1,       // _In_  DWORD dwNumberOfBytesToRead
                             &dw2);     // _Out_ LPDWORD lpdwNumberOfBytesRead

  ch_Buffer[dw2] = 0;  // Terminate string in ch_Buffer by appending a null character.

  if(bResult)
  { cout << "\nCall to InternetReadFile returned TRUE.\n";
    cout << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
    cout << "CONTENT string written to ch_Buffer (starting on next line):\n";
    cout << ch_Buffer << endl;
    of_OutFile << "\nCall to InternetReadFile returned TRUE.\n";
    of_OutFile << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
    of_OutFile << "CONTENT string written to ch_Buffer (starting on next line):\n";
    of_OutFile << ch_Buffer << endl;
  }
  else
  { cout       << "\nCall to InternetReadFile returned FALSE. ";
    of_OutFile << "\nCall to InternetReadFile returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << endl;
    of_OutFile << "Error code " << dw2 << endl;
  }

// Close handle of previous request before initializing hRequest for new request to list trades.
  InternetCloseHandle(hRequest);

// Set "count" parameter to maximum number of trades to list.
  hRequest = HttpOpenRequest(hInet,                                 // _In_ HINTERNET hConnect
                             "GET",                                 // _In_ LPCTSTR lpszVerb
                             "/v1/accounts/<your_account_number>/trades?count=15", // _In_ LPCTSTR lpszObjectName
//                           "/v1/accounts/<your_account_number>",  // Use this line to get account information.
                             "HTTP/1.1",                            // _In_ LPCTSTR lpszVersion
                             NULL,                                  // _In_ LPCTSTR lpszReferer
                             str_Array,                             // _In_ LPCTSTR *lplpszAcceptTypes
                             INTERNET_FLAG_SECURE,                  // _In_ DWORD dwFlags
                             NULL);                                 // _In_ DWORD dwContext

  if(hRequest == NULL) 
  { cout       << "Call to HttpOpenRequest returned NULL.\n";
    of_OutFile << "Call to HttpOpenRequest returned NULL.\n";
  }
  else
  { cout       << "\nCall to HttpOpenRequest returned valid handle.\n";
    of_OutFile << "\nCall to HttpOpenRequest returned valid handle.\n";
  }

  bResult = HttpSendRequest(hRequest,  // _In_ HINTERNET hRequest
              "Authorization: Bearer <your_access_token>", // _In_ LPCTSTR lpszHeaders
                            -1,        // _In_ DWORD dwHeadersLength
                            NULL,      // _In_ LPVOID lpOptional
                            0);        // _In_ DWORD dwOptionalLength
  
  if(bResult)
  { cout       << "Call to HttpSendRequest returned TRUE.\n";
    of_OutFile << "Call to HttpSendRequest returned TRUE.\n";
  }
  else
  { dw1 = GetLastError();
    cout       << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
    of_OutFile << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
  }

  dw1 = 4096;  // size of ch_Buffer
  dwIndex = 0;

  bResult = HttpQueryInfo(hRequest,                     // _In_ HINTERNET hRequest
                          HTTP_QUERY_RAW_HEADERS_CRLF,  // _In_ DWORD dwInfoLevel
                          ch_Buffer,                    // _Inout_ LPVOID lpvBuffer
                          &dw1,                         // _Inout_ LPDWORD lpdwBufferLength
                          &dwIndex);                    // _Inout_ LPDWORD lpdwIndex

  if (bResult)
  { cout << "Call to HttpQueryInfo returned TRUE.\n";
    cout << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    cout << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
    of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
    of_OutFile << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    of_OutFile << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
  }
  else
  { cout       << "Call to HttpQueryInfo returned FALSE. ";
    of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << "\n";
    of_OutFile << "Error code " << dw2 << "\n";
  }

  dw1 = 4096;  // size of ch_Buffer
  dwIndex = 0;

  bResult = HttpQueryInfo(hRequest,                   // _In_ HINTERNET hRequest
                          HTTP_QUERY_CONTENT_LENGTH,  // _In_ DWORD dwInfoLevel
                          ch_Buffer,                  // _Inout_ LPVOID lpvBuffer
                          &dw1,                       // _Inout_ LPDWORD lpdwBufferLength
                          &dwIndex);                  // _Inout_ LPDWORD lpdwIndex

  ch_Buffer[dw1] = 0;  // Terminate string in ch_Buffer by appending a null character.

  if(bResult)
  { cout << "Call to HttpQueryInfo returned TRUE.\n";
    cout << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
    cout << "String in ch_Buffer: " << ch_Buffer << "\n";
    of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
    of_OutFile << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
    of_OutFile << "String in ch_Buffer: " << ch_Buffer << "\n";
  }
  else
  { cout       << "Call to HttpQueryInfo returned FALSE. ";
    of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << "\n";
    of_OutFile << "Error code " << dw2 << "\n";
  }

  dw1 = atol(ch_Buffer); // Convert CONTENT_LENGTH string in ch_Buffer to numerical value.

  bResult = InternetReadFile(hRequest,  // _In_  HINTERNET hFile
                             ch_Buffer, // _Out_ LPVOID lpBuffer
                             dw1,       // _In_  DWORD dwNumberOfBytesToRead
                             &dw2);     // _Out_ LPDWORD lpdwNumberOfBytesRead

  ch_Buffer[dw2] = 0;  // Terminate string in ch_Buffer by appending a null character.

  if(bResult)
  { cout << "\nCall to InternetReadFile returned TRUE.\n";
    cout << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
    cout << "CONTENT string written to ch_Buffer (starting on next line):\n";
    cout << ch_Buffer << endl;
    of_OutFile << "\nCall to InternetReadFile returned TRUE.\n";
    of_OutFile << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
    of_OutFile << "CONTENT string written to ch_Buffer (starting on next line):\n";
    of_OutFile << ch_Buffer << endl;
  }
  else
  { cout       << "\nCall to InternetReadFile returned FALSE. ";
    of_OutFile << "\nCall to InternetReadFile returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << endl;
    of_OutFile << "Error code " << dw2 << endl;
  }

// The oldest trade must be closed first, so get the trade_id of the last trade in JSON string in ch_Buffer, so 
// it can be closed. We will use functions from the C library to do that, but JSON parsing libraries are available.

  strcpy(ch_Line, "/v1/accounts/<your_account_number>/trades/");  // trade_id to be appended to this string.

// See if JSON string in ch_Buffer contains ""id"", and if it does, find last occurrance. 
  chPtr0 = strstr(ch_Buffer, "\"id\"");
  if(chPtr0 != NULL)
  { chPtr0 = chPtr1 = ch_Buffer;
    while(chPtr0 != NULL)
    { chPtr1 = chPtr0;
      chPtr0 = strstr(chPtr1+1, "\"id\"");
    }

    chPtr1 += 7; // Advance pointer to start of trade_id number.
// Find comma at end of number, and write NULL to that address.
    chPtr2 = strchr(chPtr1, 44);  chPtr2[0] = 0;
// Append trade_id number to line buffer.
    strcat(ch_Line, chPtr1);
    cout       << "Last trade_id found: " << chPtr1 << "\n" << endl;
    of_OutFile << "Last trade_id found: " << chPtr1 << "\n" << endl;

// Release request handle before making new request.
    InternetCloseHandle(hRequest);

// Close the trade.
    hRequest = HttpOpenRequest(hInet,                 // _In_ HINTERNET hConnect
                               "DELETE",              // _In_ LPCTSTR lpszVerb
                               ch_Line,               // _In_ LPCTSTR lpszObjectName
                               "HTTP/1.1",            // _In_ LPCTSTR lpszVersion
                               NULL,                  // _In_ LPCTSTR lpszReferer
                               str_Array,             // _In_ LPCTSTR *lplpszAcceptTypes
                               INTERNET_FLAG_SECURE,  // _In_ DWORD dwFlags
                               NULL);                 // _In_ DWORD dwContext

    if(hRequest == NULL) 
    { cout       << "Call to HttpOpenRequest returned NULL.\n";
      of_OutFile << "Call to HttpOpenRequest returned NULL.\n";
    }
    else
    { cout       << "Call to HttpOpenRequest returned valid handle.\n";
      of_OutFile << "Call to HttpOpenRequest returned valid handle.\n";
    }

    bResult = HttpSendRequest(hRequest,  // _In_ HINTERNET hRequest
                "Authorization: Bearer <your_access_token>", // _In_ LPCTSTR lpszHeaders
                              -1,        // _In_ DWORD dwHeadersLength
                              NULL,      // _In_ LPVOID lpOptional
                              0);        // _In_ DWORD dwOptionalLength
  
    if(bResult)
    { cout       << "Call to HttpSendRequest returned TRUE.\n";
      of_OutFile << "Call to HttpSendRequest returned TRUE.\n";
    }
    else
    { dw1 = GetLastError();
      cout       << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
      of_OutFile << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
    }

    dw1 = 4096;  // size of ch_Buffer
    dwIndex = 0;

    bResult = HttpQueryInfo(hRequest,                     // _In_ HINTERNET hRequest
                            HTTP_QUERY_RAW_HEADERS_CRLF,  // _In_ DWORD dwInfoLevel
                            ch_Buffer,                    // _Inout_ LPVOID lpvBuffer
                            &dw1,                         // _Inout_ LPDWORD lpdwBufferLength
                            &dwIndex);                    // _Inout_ LPDWORD lpdwIndex

    if (bResult)
    { cout << "Call to HttpQueryInfo returned TRUE.\n";
      cout << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
      cout << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
      of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
      of_OutFile << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
      of_OutFile << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
    }
    else
    { cout       << "Call to HttpQueryInfo returned FALSE. ";
      of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
      dw2 = GetLastError();
      cout       << "Error code " << dw2 << "\n";
      of_OutFile << "Error code " << dw2 << "\n";
    }

    dw1 = 4096;  // size of ch_Buffer
    dwIndex = 0;

    bResult = HttpQueryInfo(hRequest,                   // _In_ HINTERNET hRequest
                            HTTP_QUERY_CONTENT_LENGTH,  // _In_ DWORD dwInfoLevel
                            ch_Buffer,                  // _Inout_ LPVOID lpvBuffer
                            &dw1,                       // _Inout_ LPDWORD lpdwBufferLength
                            &dwIndex);                  // _Inout_ LPDWORD lpdwIndex

    ch_Buffer[dw1] = 0;  // Terminate string in ch_Buffer by appending a null character.

    if(bResult)
    { cout << "Call to HttpQueryInfo returned TRUE.\n";
      cout << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
      cout << "String in ch_Buffer: " << ch_Buffer << "\n";
      of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
      of_OutFile << "Number of bytes written to ch_Buffer for CONTENT LENGTH: " << dw1 << "\n";
      of_OutFile << "String in ch_Buffer: " << ch_Buffer << "\n";
    }
    else
    { cout       << "Call to HttpQueryInfo returned FALSE. ";
      of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
      dw2 = GetLastError();
      cout       << "Error code " << dw2 << "\n";
      of_OutFile << "Error code " << dw2 << "\n";
    }

    dw1 = atol(ch_Buffer); // Convert CONTENT_LENGTH string in ch_Buffer to numerical value.

    bResult = InternetReadFile(hRequest,  // _In_  HINTERNET hFile
                               ch_Buffer, // _Out_ LPVOID lpBuffer
                               dw1,       // _In_  DWORD dwNumberOfBytesToRead
                               &dw2);     // _Out_ LPDWORD lpdwNumberOfBytesRead

    ch_Buffer[dw2] = 0;  // Terminate string in ch_Buffer by appending a null character.

    if(bResult)
    { cout << "\nCall to InternetReadFile returned TRUE.\n";
      cout << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
      cout << "CONTENT string written to ch_Buffer (starting on next line):\n";
      cout << ch_Buffer << "\n" << endl;
      of_OutFile << "\nCall to InternetReadFile returned TRUE.\n";
      of_OutFile << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
      of_OutFile << "CONTENT string written to ch_Buffer (starting on next line):\n";
      of_OutFile << ch_Buffer << "\n" << endl;
    }
    else
    { cout       << "\nCall to InternetReadFile returned FALSE. ";
      of_OutFile << "\nCall to InternetReadFile returned FALSE. ";
      dw2 = GetLastError();
      cout       << "Error code " << dw2 << endl;
      of_OutFile << "Error code " << dw2 << endl;
    }

  }//END if(chPtr0 != NULL)
  else cout << "The string \"id\" could not be found in ch_Buffer." << endl;

// The next section displays streaming quotes, calling InternetReadFile() in synchronous mode.

// Close handles before initializing to new values to connect to streaming server.
  InternetCloseHandle(hRequest);
  InternetCloseHandle(hInet);

  hInet = InternetConnect(h_Inet,          // _In_ HINTERNET hInternet
            "stream-fxpractice.oanda.com", // _In_ LPCTSTR lpszServerName
            INTERNET_DEFAULT_HTTPS_PORT,   // _In_ INTERNET_PORT nServerPort
            NULL, // _In_ LPCTSTR lpszUsername, Don't send your user name if you don't have to.
            NULL, // _In_ LPCTSTR lpszPassword, Dont' send your password if you don't have to.
            INTERNET_SERVICE_HTTP,         // _In_ DWORD dwService
            NULL,                          // _In_ DWORD dwFlags
            NULL);                         // _In_ DWORD dwContext

  if(hInet == NULL) 
  { cout       << "Call to InternetConnect returned NULL.\n";
    of_OutFile << "Call to InternetConnect returned NULL.\n";
  }
  else
  { cout       << "Call to InternetConnect returned valid handle.\n";
    of_OutFile << "Call to InternetConnect returned valid handle.\n";
  }

// Set up request to get streaming quotes.
  hRequest = HttpOpenRequest(hInet,  // _In_ HINTERNET hConnect
               "GET",                // _In_ LPCTSTR lpszVerb
               "/v1/prices?accountId=<your_account_number>&instruments=EUR_USD", // _In_ LPCTSTR lpszObjectName
               "HTTP/1.1",           // _In_ LPCTSTR lpszVersion
               NULL,                 // _In_ LPCTSTR lpszReferer
               str_Array,            // _In_ LPCTSTR *lplpszAcceptTypes
               INTERNET_FLAG_SECURE | INTERNET_FLAG_KEEP_CONNECTION, // _In_ DWORD dwFlags
               NULL);                // _In_ DWORD dwContext

  if(hRequest == NULL) 
  { cout       << "Call to HttpOpenRequest returned NULL.\n";
    of_OutFile << "Call to HttpOpenRequest returned NULL.\n";
  }
  else
  { cout       << "Call to HttpOpenRequest returned valid handle.\n";
    of_OutFile << "Call to HttpOpenRequest returned valid handle.\n";
  }

  bResult = HttpSendRequest(hRequest,  // _In_ HINTERNET hRequest
              "Authorization: Bearer <your_access_token>",  // _In_ LPCTSTR lpszHeaders
                            -1,        // _In_ DWORD dwHeadersLength
                            NULL,      // _In_ LPVOID lpOptional
                            0);        // _In_ DWORD dwOptionalLength

  if(bResult)
  { cout       << "Call to HttpSendRequest returned TRUE.\n";
    of_OutFile << "Call to HttpSendRequest returned TRUE.\n";
  }
  else
  { dw1 = GetLastError();
    cout       << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
    of_OutFile << "Call to HttpSendRequest returned FALSE. Error code " << dw1 << "\n"; 
  }

  dw1 = 4096;  // size of ch_Buffer
  dwIndex = 0;

  bResult = HttpQueryInfo(hRequest,                     // _In_ HINTERNET hRequest
                          HTTP_QUERY_RAW_HEADERS_CRLF,  // _In_ DWORD dwInfoLevel
                          ch_Buffer,                    // _Inout_ LPVOID lpvBuffer
                          &dw1,                         // _Inout_ LPDWORD lpdwBufferLength
                          &dwIndex);                    // _Inout_ LPDWORD lpdwIndex

  if (bResult)
  { cout << "Call to HttpQueryInfo returned TRUE.\n";
    cout << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    cout << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
    of_OutFile << "Call to HttpQueryInfo returned TRUE.\n";
    of_OutFile << "Number of bytes written to ch_Buffer for HTTP_QUERY_RAW_HEADERS_CRLF: " << dw1 << "\n";
    of_OutFile << "String in ch_Buffer (starting on next line):\n" << ch_Buffer;
  }
  else
  { cout       << "Call to HttpQueryInfo returned FALSE. ";
    of_OutFile << "Call to HttpQueryInfo returned FALSE. ";
    dw2 = GetLastError();
    cout       << "Error code " << dw2 << "\n";
    of_OutFile << "Error code " << dw2 << "\n";
  }

// Set iChunks equal to the number of streaming chunks to receive, including ticks and heartbeats.
  iChunks = 24;

  for(i = 0; i < iChunks; i++)
  { dw1 = 4096;  // size of ch_Buffer
    bResult = InternetReadFile(hRequest,  // _In_  HINTERNET hFile
                               ch_Buffer, // _Out_ LPVOID lpBuffer
                               dw1,       // _In_  DWORD dwNumberOfBytesToRead
                               &dw2);     // _Out_ LPDWORD lpdwNumberOfBytesRead

    ch_Buffer[dw2] = 0;  // Terminate string in ch_Buffer by appending a null character.

    if(bResult)
    { cout       << "Call to InternetReadFile returned TRUE.\n";
      of_OutFile << "Call to InternetReadFile returned TRUE.\n";
      cout       << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
      of_OutFile << "Size of CONTENT string written to ch_Buffer: " << dw2 << "\n";
      cout       << "CONTENT string written to ch_Buffer (starting on next line):\n";
      of_OutFile << "CONTENT string written to ch_Buffer (starting on next line):\n";
      cout       << ch_Buffer << endl;
      of_OutFile << ch_Buffer << endl;
    }
    else
    { dw2 = GetLastError();
      cout       << "\nCall to InternetReadFile returned FALSE. Error code " << dw2 << endl;
      of_OutFile << "\nCall to InternetReadFile returned FALSE. Error code " << dw2 << endl;
      if(dw2 == ERROR_INTERNET_TIMEOUT) break; // error code 12002
    }
  }//END for(i = 0; i < iChunks; i++)

//Close open handles.
  InternetCloseHandle(hRequest);
  InternetCloseHandle(hInet);
  InternetCloseHandle(h_Inet);
//Close output.txt.
  of_OutFile.close();
  return 0;
} //END of main() 
Exemplo n.º 24
0
void WriteDatacard( float threshold ){

	gSystem -> mkdir( "datacards/", kTRUE );

	datacard.open( Form("/afs/cern.ch/user/j/jgarciaf/www/txt-files/datacards/170525/%s_%s_%4.2f_%s_fixed.txt", processID[ttDM].Data(), "mt2ll80", threshold, region.Data() ) );

	datacard << "imax 1 number of channels \n" ;
	datacard << Form( "jmax %d number of backgrounds \n", 9 ); //nprocess );
	datacard << Form( "kmax %d number of nuisance parameters \n", nsystematic-1 );
	datacard << "------------ \n" ;
	datacard << "\n" ;
	datacard << Form("bin %s \n", region.Data());
if( region == "SR" ){ datacard << Form("observation %5.0f \n", yield[data][nominal][NN]);   }
if( region == "CR" ){ datacard << Form("observation %5.0f \n", yield[data][nominal][hard]); }
	datacard << "------------\n" ;
	datacard << "\n" ;
datacard << Form("bin        \t     \t  %s   \t  %s   \t  %s   \t  %s   \t  %s   \t  %s   \t  %s   \t  %s   \t  %s   \t  %s   \n",
	    region.Data(), region.Data(), region.Data(), region.Data(), region.Data(), region.Data(), region.Data(), region.Data(), region.Data(), region.Data()  );//\t   1   \t   1   \n";//\t   1   \t   1  \n" ;
datacard << "process    \t     \t  DM   \t fakes \t  TT   \t  ST   \t  DY   \t  TTV  \t  WW   \t  WZ   \t  VZ   \t  VVV  \n";//\t  Wg   \t  Zg   \n";//\t  HWW  \t  HZ  \n" ;
datacard << "process    \t     \t   0   \t   1   \t   2   \t   3   \t   4   \t   5   \t   6   \t   7   \t   8   \t   9   \n";//\t  10   \t  11   \n";//\t  12   \t  13  \n" ;
if( region == "SR" ){
datacard << Form("rate  \t\t   \t%7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f \n", /*%7.3f %7.3f \n", //%7.3f %7.3f \n",*/ 
                    yield[ttDM][nominal][NN]/9, yield[fakes][nominal][NN], yield[TT][nominal][NN], yield[ST][nominal][NN], yield[DY][nominal][NN], 
		    yield[TTV][nominal][NN], yield[WW][nominal][NN], yield[WZ][nominal][NN], yield[VZ][nominal][NN], yield[VVV][nominal][NN] 
		    /*, yield[Wg][nominal][NN], yield[Zg][nominal][NN], yield[HWW][nominal][NN], yield[HZ][nominal][NN]*/ );
}
if( region == "CR" ){
datacard << Form("rate  \t\t   \t%7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f %7.3f \n", /*%7.3f %7.3f \n", //%7.3f %7.3f \n",*/ 
                    yield[ttDM][nominal][hard]/9, yield[fakes][nominal][hard], yield[TT][nominal][hard], yield[ST][nominal][hard], yield[DY][nominal][hard], 
		    yield[TTV][nominal][hard], yield[WW][nominal][hard], yield[WZ][nominal][hard], yield[VZ][nominal][hard], yield[VVV][nominal][hard]
		    /*, yield[Wg][nominal][hard], yield[Zg][nominal][hard], yield[HWW][nominal][hard], yield[HZ][nominal][hard]*/ );
}
	datacard << "------------ \n" ;

	for( int j = 1; j < nsystematic; j++ ){   // systematic

		if(  j < toppTrw  &&  j%2 == 0  ) continue; 

		for( int k = 0; k < nsysttype; k++ ){

			if( j == toppTrw && k == nrmlz ) continue; 
			if( j == DDtt    && k == shape ) continue; 
			if( j == DDDY    && k == shape ) continue; 
			if( j == DDfakes && k == shape ) continue; 

			if ( j == DDtt && k == nrmlz ) datacard << Form( "%s_%s \t lnU \t", systematicIDdatacard[j].Data(), systtypeID[k].Data() ); 
			else                           datacard << Form( "%s_%s \t lnN \t", systematicIDdatacard[j].Data(), systtypeID[k].Data() ); 

			for( int i = 1; i <= VVV; i++ ){   // process

				if( relunc[i][j][k] < 0 ){

					datacard << Form( "%7s ", "   -   " ); 
			
				}

				else {
 					float figure = relunc[i][j][k]; 

					if( j < toppTrw ){

						figure = 1+(relunc[i][j][k]-relunc[i][j+1][k])/2; // (up-down)/2

						if( figure < 0.80 )  figure = 0.80;   // cheating...
						if( figure > 1.20 )  figure = 1.20;   // cheating... 

					} 

					if( figure < 1.0 ) figure = 2 - figure; 


					datacard << Form( "%7.3f ", figure );					

				}


			}   // process	

			datacard << "\n" ; 

		}   // nrmlz or shape

	}   // systematic


	datacard.close();

}
Exemplo n.º 25
0
ExplicitEuler::ExplicitEuler()
: SceneStepper()
{
  text_file.open ("kinetic_energy.txt");
}
Exemplo n.º 26
0
//主程序
HINT APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, HINT nCmdShow)
{
	DWORD nCostTime = GetTickCount();
	CBTCommand *pComand=CBTCommand::Instance(); 
	if(pComand != NULL)
	{
		pComand->LowBTPower();
	}
	wprintf(L"[wWinMain] Begin\r\n");
	//g_Mutex =::CreateMutex(NULL, TRUE, APP_CLASSNAME_TEST1);
	INSTANCE_START
	HINT nParam = 0;
	_stscanf_s(GetCommandLine(),_T("%d"),&nParam);
	nCmdShow = PARAM_SHOW_CMD(nParam);
	s_Show = nCmdShow;
	BTDEBUGINFO(L"nCmdShow = %d",nCmdShow);
	HINT nDlg = PARAM_BT_DLG_CMD(nParam);
	BTDEBUGINFO(L"nDlg = %d",nDlg);
	s_nDlg = nDlg;
//	HINT nDlgType =	PARAM_BT_DLG_CMD(nParam);	
	// HMI 初始化
	if( !UIDevInit(
		SCREEN_WIDTH, SCREEN_HEIGHT,
		hInstance,
		const_cast<HCHAR*>(STR_PROCESSNAME_BT),
		const_cast<HCHAR*>(STR_PROCESSNAME_BT),
		0,
		g_hBTWnd) )
	{
		return 0;
	}
	::ShowWindow(g_hBTWnd, nCmdShow);
	SetOwnerProc(MyProc);   //注册回调
	// 注册IPC
	//移到后面
	CEIPC_Regist(IPC_ID_BT, g_hBTWnd, RecvIPCEvent);
	//	切换字体
	GetRESingleton()->ReLoadFont(FONT_MSYH_TTF);
	GetRESingleton()->ReLoadFont(FONT_QUARTZ_REGULAR_TTF);
	InitPopupSurface(GetHMIPath(_T("")).c_str());
	KCBTDialogManager* pObj =  KCBTDialogManager::Instance();

	
	btSource::Instance()->GetBtSource(GetHMIPath(_T("")).c_str());
	if(pComand != NULL)
	{
		pComand->SetMyhWnd(g_hBTWnd);
		pComand->OnInit(1,115200);
		nCostTime = GetTickCount() - nCostTime;
		BTDEBUGINFO(L"%s,CostTime1 = %d",__FUNCTIONW__,nCostTime);
		nCostTime = GetTickCount();
	}
	if(pObj != NULL)
	{
	   pObj->CreateAllBTDlg();
		pComand->SendGetBTInfo();
		pObj->ShowDlg(eDIALOGT_BTCONNECTSETTING);
	
		nCostTime = GetTickCount() - nCostTime;
		BTDEBUGINFO(L"%s,CostTime2 = %d",__FUNCTIONW__,nCostTime);
		nCostTime = GetTickCount();
		//pObj->ShowBTHMIDlg();
	}	 
	// 获取配置信息
	if( NULL != KCLastMemory::GetInstance() )
	{
		// 读取SETUP配置文件
		KCLastMemory::GetInstance()->GetSetupMemory(g_SetupSetting);
	}
	else
	{
		KCLastMemory::GetSetupMemoryDefault(g_SetupSetting);
	}
	//::ShowWindow(g_hBTWnd, nCmdShow);
	::UpdateWindow(g_hBTWnd);
	//CEIPC_Regist(IPC_ID_BT, g_hBTWnd, RecvIPCEvent);
	//s_nDlg = 4;
	if(s_nDlg == 4)
	{
		BTDEBUGINFO(L"s_nDlg == 4");
		UINT nrett = SetTimer(g_hBTWnd,15,10000,SetDlg);
		if(nrett == 0)
		{
			BTDEBUGINFO(L"SetTimer error: %d",GetLastError());
		}
	}
	nCostTime = GetTickCount() - nCostTime;
	BTDEBUGINFO(L"%s,CostTime3 = %d",__FUNCTIONW__,nCostTime);
	HCHAR		szPath[MAX_PATH] = {0};
	::GetModuleFileName(NULL, szPath, MAX_PATH);
	appPath += szPath;
	HINT nPos = (HINT)appPath.rfind(_T('\\'));
	if(nPos == -1)
	{
		wprintf(L"[HCSourceBase::GetExePath] exe path error ");
		return false;
	}
	appPath = appPath.substr(0, nPos+1);
#if BTLOGSTATE
	appPath += L"..\\Config\\BTLog.txt";
	g_Logfile1.open(appPath.c_str(),ios::app);
#else
#endif
#if TESTRESTARTPROTEM
	 char buffer[256] = {0};
	 char buffer1[256] = {0};
	 char Num[20] ={0};
	  ifstream examplefile1;
	  int i1,j1;
	  i1= j1 = 0;
	  int nn = 0;
	appPath += L"..\\Config\\BTPro.txt";
	examplefile1.open(appPath.c_str());
	if(!examplefile1)
	{
		printf("File Not Exsit\r\n");
		g_nRestTime = 1;
	}
	else
	{
		while (! examplefile1.eof() ) 
		{
			memset(buffer,0,sizeof(buffer));
			examplefile1.getline(buffer,100);
			if(buffer[0] == 'T')
			{
				memset(buffer1,0,sizeof(buffer1));
				memcpy(buffer1,buffer,100);
			}
			//nn++;
		//cout<<"====="<<nn<<endl;
		}
		while (buffer1[i1] != '^')
		{
			i1++;
				cout<<"i= "<<i1<<endl;
		}
		j1 = i1 + 1;
		while (buffer1[j1] != '^')
		{
			j1++;
			cout<<"j = "<<j1<<endl;
		}
		if(i1 < j1 && i1 > 0 && (j1-i1)  < 10)
		{
			memcpy(Num,buffer1+i1+1,j1-i1-1);
		}
		g_nRestTime = atoi(Num) + 1;
		cout << "666++++"<<g_nRestTime<<endl;
		examplefile1.close();
	}
	g_Profile1.open(appPath.c_str(),ios::app);
	char Temm[200] = {0};
	//sprintf(Temm,"Totol^%d^^^^%d\n",g_nRestTime,GetTickCount());
	//g_Profile1.write(Temm);
	g_Profile1<<"Total^"<<g_nRestTime<<"^^^^"<<GetTickCount()<<endl;
	//g_Profile1<<"Total^"<<g_nRestTime<<"^^^^"<<GetTickCount()<<endl;
	g_Profile1.close();
#endif
	//消息循环
	MSG msg;
	UINT nretTime = SetTimer(g_hBTWnd,10,1000,CheckHDMISignal);
	if(nretTime == 0)
	{
		BTDEBUGINFO(L"SetTimer error: %d",GetLastError());
	}
	DWORD dwClickDownTime = GetTickCount();
	while(GetMessage(&msg, NULL, 0, 0))
	{
		eDIALOGTYPE  eDlgType = KCBTDialogManager::Instance()->GetCurrentDlgType();
		if(GetTickCount() - dwClickDownTime >= 800 && msg.message == WM_LBUTTONDOWN && ((eDlgType == eDIALOGT_BTADDRESSBOOK) || (eDlgType == eDIALOGT_BTCALLRECORDS)))
		{
			dwClickDownTime = GetTickCount();
		}
		else if(msg.message == WM_LBUTTONDOWN && GetTickCount() - dwClickDownTime < 800 && ((eDlgType == eDIALOGT_BTADDRESSBOOK) || (eDlgType == eDIALOGT_BTCALLRECORDS)))
		{
            continue;
		}
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	CEIPC_UnRegist();
	CBTCommand::DeleteInstance();
	KCBTDialogManager::Instance()->DeleteInstance();
	btSource::Instance()->DeleteInstance();
	//UnInitPopupSurface();
	//释放
	UIDevRelease();
	KillTimer(g_hBTWnd,10);
	KillTimer(g_hBTWnd,15);
	HWND hServerWnd = ::FindWindow(STR_PROCESSNAME_MANAGE, STR_PROCESSNAME_MANAGE);
	HWND hBtUpateWnd = ::FindWindow(L"BTAPP.exe", L"BTAPP.exe");
	if(hBtUpateWnd != NULL)
	{
			::PostMessage(hBtUpateWnd, WM_USER + 1000, 0, NULL);
			
	}
	//printf("+++++++++++++VWM_SERVER_SRC_CLOSE+++++IPC_ID_BT++++++\r\n");
	if (hServerWnd)
	{
		::PostMessage(hServerWnd, VWM_SERVER_SRC_CLOSE, IPC_ID_BT, NULL);
	}

	return 0;
}
Exemplo n.º 27
0
int
main(int argc, char* argv[])
{
  std::string fof = "fof.txt";
  std::string dropFileName = "drops.txt";
  std::string topologyFile = "src/ndnSIM/examples/topologies/topo-tree.txt";
  std::string appDelayFile = "app-delays-trace.txt";
  std::string rateTraceFile = "rate-trace.txt";
  std::string percentage = "1.0";
  std::string frequency = "1";
  int simulationTime = 1000;

  CommandLine cmd;
  cmd.AddValue("fof", "forwarder overhead file", fof);
  cmd.AddValue("time", "simulation time argument", simulationTime);
  cmd.AddValue("top", "topology file", topologyFile);
  cmd.AddValue("drop", "bead drop file", dropFileName);
  cmd.AddValue("appd", "app delay file", appDelayFile);
  cmd.AddValue("rate", "rate trace file", rateTraceFile);
  cmd.AddValue("percentage", "bead percentage", percentage);
  cmd.AddValue("freq", "bead frequency", frequency);
  cmd.Parse(argc, argv);

  delayFile.open(fof);
  dropFile.open(dropFileName);

  AnnotatedTopologyReader topologyReader("", 1);
  topologyReader.SetFileName(topologyFile);
  topologyReader.Read();

  ndn::StackHelper ndnHelper;
  ndnHelper.InstallAll();

  // Getting containers for the consumer/producer
  Ptr<Node> consumers[4] = {Names::Find<Node>("leaf-1"), Names::Find<Node>("leaf-2"),
                            Names::Find<Node>("leaf-3"), Names::Find<Node>("leaf-4")};
  Ptr<Node> routers[2] = {Names::Find<Node>("rtr-1"), Names::Find<Node>("rtr-2")};
  // Ptr<Node> producers[2] = {Names::Find<Node>("root-1"), Names::Find<Node>("root-2")};
  Ptr<Node> producer = Names::Find<Node>("root-1");

  // Choosing forwarding strategy
  ndn::StrategyChoiceHelper::InstallAll("/root", "/localhost/nfd/strategy/best-route");

  // Installing global routing interface on all nodes
  ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
  ndnGlobalRoutingHelper.InstallAll();

  // Install NDN on routers
  ndn::StackHelper ndnHelperWithCache;
  ndnHelperWithCache.SetDefaultRoutes(true);
  ndnHelperWithCache.SetOldContentStore("ns3::ndn::cs::Freshness::Lru", "MaxSize", "0");
  ndnHelperWithCache.InstallCallback(routers[0], (size_t)&ForwardingDelay, 0);
  ndnHelperWithCache.InstallBeadDropCallback(routers[0], (size_t)&BeadDropCallback, 0);
  ndnHelperWithCache.SetUseHistory(routers[0], 100);
  ndnHelperWithCache.InstallCallback(routers[1], (size_t)&ForwardingDelay, 1);
  ndnHelperWithCache.InstallBeadDropCallback(routers[1], (size_t)&BeadDropCallback, 1);
  ndnHelperWithCache.SetUseHistory(routers[0], 100);


  ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
  // Consumer will request /prefix/0, /prefix/1, ...
  consumerHelper.SetPrefix("/root");
  consumerHelper.SetAttribute("Frequency", StringValue("10")); // 10 interests a second
  consumerHelper.Install(consumers[0]);
  consumerHelper.Install(consumers[1]);
  consumerHelper.Install(consumers[2]);

  ndn::AppHelper producerHelper("ns3::ndn::Producer");
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
  producerHelper.SetAttribute("Frequency", StringValue(frequency)); // 1 BEAD every second
  producerHelper.SetAttribute("Percentage", StringValue(percentage));

  // Register /root prefix with global routing controller and
  // install producer that will satisfy Interests in /root namespace
  ndnGlobalRoutingHelper.AddOrigins("/root", producer);
  producerHelper.SetPrefix("/root");
  producerHelper.Install(producer).Start(Seconds(0));
  producerHelper.Install(producer).Start(Seconds(0));
  ndnHelperWithCache.InstallCallback(producer, (size_t)&ForwardingDelay, 2);

  // ndnGlobalRoutingHelper.AddOrigins("/root/nonbead", producers[1]);
  // producerHelper.SetPrefix("/root/nonbead");
  // producerHelper.Install(producers[1]).Start(Seconds(9));

  // Calculate and install FIBs
  ndn::GlobalRoutingHelper::CalculateRoutes();

  Simulator::Stop(Seconds(simulationTime));

  ndn::AppDelayTracer::InstallAll(appDelayFile);
  ndn::L3RateTracer::InstallAll(rateTraceFile, Seconds(0.5));

  Simulator::Run();
  Simulator::Destroy();

  delayFile.flush();
  delayFile.close();

  dropFile.flush();
  dropFile.close();

  return 0;
}
Exemplo n.º 28
0
int main(int argc, char *argv[])
{
    

   outfile.open("./tree.txt");

    printf("THR = %f\n", THR);
    for (int ini = 0; ini < 9; ini++)
    {
        char temp = '1'+ini;
        AsciiToInt[temp] = ini;
        IntToAscii[ini] = temp;
    }
    for (int ini = 0; ini < 26; ini++)
    {
        char temp = 'a'+ini;
        AsciiToInt[temp] = 9 + ini;
        IntToAscii[9+ini] = temp;
    }
    for (int ini = 0; ini < 26; ini++)
    {
        char temp = 'A'+ini;
        AsciiToInt[temp] = 35 + ini;
        IntToAscii[35+ini] = temp;
    }
    //cout<<AsciiToInt.find('a')->first<<endl;
    //cout<<AsciiToInt.find('a')->second<<endl;
    double total_random_time = 0;
    double random_time , main_time;
    clock_t start_random_time, end_random_time;
    timeval tv, tv1, tvPartition;
    timeval treeover, DSeqover, Camover;
    register int i, j;
    long long subgraphCounterMain;
    generator gen;
      int next_option;
  const char *const short_options = "hi:d:o:r:s:f:";
  const struct option long_options[] = {
        {"help",   0, NULL, 'h'},
        {"input",  1, NULL, 'i'},
        {"Dnodes input",  1, NULL, 'd'},
        {"output", 1, NULL, 'o'},
        {"random", 1, NULL, 'r'},
        {"size",   1, NULL, 's'},
        {"treeflag",   1, NULL, 'f'},       
        {NULL,     0, NULL,  0 }        
    };
    
    char *program_name;
    char input_filename[256], output_directory[256], Dpath[256];

    int verbose = 0;
    strcpy(output_directory, "result");

    program_name = argv[0];
    do {
        next_option = getopt_long (argc, argv, short_options, long_options, NULL);
    
        switch (next_option) {
            case 'h':
                print_usage (stdout, 0);

            case 'i':
                strcpy(input_filename, optarg);
                break;

            case 'd':
                strcpy(Dpath, optarg);
                break;
                
            case 'o':
                strcpy(output_directory, optarg);
                break;
            
            case 'r':
                 num_random_graphs = atoi(optarg);
                break;

            case 's':
                subgraphSize = atoi(optarg);
                break;

            case 'f':
                treeflag = atoi(optarg);
                break;
            
            case '?':
                print_usage (stdout, 1);
                
            case -1:        /* Done with options. */
                break;
            
            default:        /* Something else: unexpected. */
                print_usage (stderr, -1);
        }
    } while (next_option != -1);

 
    if (input_filename == NULL) {
        fprintf(stderr, "Input Argument Error: Please specify an input filename using \"-i <FILE NAME>\".\n");
        print_usage (stderr, -1);
    }
    
    if (subgraphSize == -1) {
        fprintf(stderr, "Input Argument Error: Please specify a motif size using \"-s <MOTIF SIZE>\".\n");
        print_usage (stderr, -1);
    }
    
    num_random_graphs = 0;
   
    subgraph = new int*[subgraphSize];
    for (int i = 0; i < subgraphSize; i++)
        subgraph[i] = new int[subgraphSize+3];   //add two cells on subgraph save the number of nodes, edges

    num = 0;
    printf("Graphlets Size: %d\n", subgraphSize);
    printf("Input Graph: %s\n", input_filename);

    if (!ReadData(input_filename, Dpath))
        return 0;

    g->setPath(output_directory);

    double realStart_t = realtime();

    clock_t startTime = clock();
    gettimeofday(&tv, 0);
    //for main graph
    isRand = false;
    subgraphCounter = 0;
    Enumerate();
    

    gettimeofday(&tvPartition, 0);

    cout<<"partitionTime"<<(tvPartition.tv_sec - tv.tv_sec + (double)(tvPartition.tv_usec - tv.tv_usec) / CLOCKS_PER_SEC)<<endl;
    exit(1);

    int deleted=0;
    vector<std::string> frequentG;
    
    vector< pair<std::string, long long int> > finalTree;
    hash_map<std::string, vector< const std::string* > > degreeSeq;
    hash_map<std::string, long long int> degreeSeqCount;
    /*******************Tree isomorphic*****************************/

    /*
    int treeSize = treeInt.size();
 
    int flag=0;
    
    int countTree =0;
  
    for (hash_map<std::string, long long int>::iterator it = treeInt.begin(); it != treeInt.end(); it++)
    {
        std::string tree1 = it->first;
        cout<<"Tree1 = "<<tree1<<endl;
        long long int tempCount = it->second;

        flag = 0;
    
        countTree++;
        
        for (int vi = 0; vi < finalTree.size(); vi++)
        {

            std::string tree2 = finalTree[vi].first;


            if(treeIso(tree1,tree2))
            {
                finalTree[vi].second = tempCount + finalTree[vi].second;
                flag = 1;
                break;
            }
        }
        if(flag == 0)
        {
            pair<string, long long int> tempPair = make_pair(tree1, tempCount);
            finalTree.push_back(tempPair);
        }
        
    }
    */


 
    /******************write non-isomorphic trees into file***********/
    int frequentTree = 0;
    ofstream fileTree;

    fileTree.open(("resultTree_"+intToString(subgraphSize)+".txt").c_str());

    for (hash_map<std::string, long long int>::iterator it = treeInt.begin(); it != treeInt.end(); it++)
    {
        if(it->second > (THR*subgraphCounter))
        {
            frequentTree++;
            //fileTree<< it->first<<" "<<it->second<<"\n";
        }
    }
    
    fileTree.close();

    printf("OutTree: %d\n", frequentTree);

    treeInt.clear();
    finalTree.clear();
    gettimeofday(&treeover, 0);

    cout<<"Time of dealing with tree after Partition before graph: "<<(treeover.tv_sec - tvPartition.tv_sec + (double)(treeover.tv_usec - tvPartition.tv_usec) / CLOCKS_PER_SEC)<<endl;
    
    /****************************************************************/
    /*****************graph isomorphic********************************/
    int graphSize = graphInt.size();
    //cout<<"graphSize:"<<graphSize<<endl;
    vector<bool> CountedGraph(graphSize, true);

    int flag = 0;
    int flag2 = 0;
    //degree sequence
    /*1210 2013**/
    for (hash_map<std::string, long long int>::iterator it = graphInt.begin(); it != graphInt.end(); it++)
    {
        const std::string *graph1 = &(it->first);

        //cout<<"Graph1 = " << *graph1 <<endl;

        std::string gds1 = graphDegreeSequence(*graph1,subgraphSize,AsciiToInt);
        long long int tempCount = it->second;
        //vector<const std::string*> tempGraphs;
        //tempGraphs.push_back(graph1);

        if(degreeSeqCount.find(gds1)==degreeSeqCount.end())
        {
            degreeSeqCount[gds1] = tempCount;
            vector<const std::string*> tempGraphsTemp;
            tempGraphsTemp.push_back(graph1);
            degreeSeq[gds1] = tempGraphsTemp;
        }
        else
        {
            degreeSeqCount.find(gds1)->second = degreeSeqCount.find(gds1)->second + tempCount;
            degreeSeq.find(gds1)->second.push_back(graph1);
        }

    }

    gettimeofday(&DSeqover, 0);

    cout<<"Time of dealing with Degree sequence: "<<(DSeqover.tv_sec - treeover.tv_sec  + (double)(DSeqover.tv_usec - treeover.tv_usec ) / CLOCKS_PER_SEC)<<endl;

    hash_map<std::string, long long int> finalGraph;
    int countCam = 0;
    for (hash_map<std::string, vector<const std::string*> >::iterator it = degreeSeq.begin(); it != degreeSeq.end(); it++)
    {
        vector<const std::string*> tempV = it->second;//graph strings' address with the same degreeSeq 

        if (degreeSeqCount.find(it->first)->second <= (seqTHR*subgraphCounter))
        {
            continue;
        }

        for (int iv = 0; iv < tempV.size(); iv++)
        {
            string tempCam = *(tempV[iv]);
            //cout<<"tempCam = "<<tempCam<<endl;
            countCam++;
            string cam =  calculateCam(tempCam,subgraphSize,AsciiToInt);
            //cout<<"cam = "<< cam<<endl;

            hash_map<std::string, long long int>::iterator it2 =  finalGraph.find(cam);
            if (it2 == finalGraph.end())
            {

                finalGraph[cam] = graphInt.find(tempCam)->second;
            }
            else
            {
                (it2->second) =  (it2->second) + graphInt.find(tempCam)->second;
            }
        }
        tempV.clear();
    }


    gettimeofday(&Camover, 0);

    cout<<"Time of dealing with Cam: "<<(Camover.tv_sec - DSeqover.tv_sec   + (double)(Camover.tv_usec - DSeqover.tv_usec) / CLOCKS_PER_SEC)<<endl;

    // cout<<"here 3333"<<endl;
    ofstream fileGraph;
    fileGraph.open(("resultGraph_"+intToString(subgraphSize)+".txt").c_str());
    //cout<<"Number of finalGraph : "<<finalGraph.size()<<endl;
    int frequentGraph = 0;
    for (hash_map<std::string, long long int> ::iterator it = finalGraph.begin(); it != finalGraph.end(); it++)
    {
        if (it->second > THR*subgraphCounter)
        {
            frequentGraph ++;
            //fileGraph<< it->first<<" "<<it->second<<"\n";
        }
    }
    printf("OutGraph: %d\n", frequentGraph);
    fileGraph.close();

    /****************************************************************/
    //g->AllocateCounter();
    //std::cout<<"countCam"<<countCam<<std::endl;
    //std::cout<<"degreeSeq:"<<degreeSeq.size()<<std::endl;
    //std::cout<<"finalGraph:"<<finalGraph.size()<<std::endl;
    //std::cout<<"deleted:"<<deleted<<std::endl;
    //std::cout<<"frequentGCount:"<<frequentG.size()<<std::endl;
    
    //g->Extract();

    clock_t end_main_time = clock();
    main_time = difftime(end_main_time, startTime)/(double)CLOCKS_PER_SEC;
    //printf("Time Used for main graph: %f\n", main_time);

    subgraphCounterMain = subgraphCounter;
    //for random graphs
    srand(time(NULL));
    isRand = true;
    long long boz = 0;
    //printf("Number of Random Graphs: %d\n", num_random_graphs);
    for (i = 1; i <= num_random_graphs; i++)
    {
        
        gen.genRandGraph_Edge(g);
        subgraphCounter = 0;
        Enumerate();
        g->Extract();
    }

    if (0 < num_random_graphs)
        g->calculateZSCORE(num_random_graphs, subgraphCounterMain, output_directory);

    for(i = 0; i < subgraphSize; i++)
    {
        delete [] Index[i];
        delete [] childSet[i];
    }

    for (int i = 0; i < subgraphSize; i++)
        delete [] subgraph[i];

    delete [] subgraph;
    delete [] Index;
    delete [] childSet;
    delete [] Visited;
    delete g;
    gettimeofday(&tv1, 0);
    clock_t endTime = clock();
    double total_time = difftime(endTime, startTime)/(double)CLOCKS_PER_SEC;
    printf("Time Used: %f\n", total_time);
    cout<<(tv1.tv_sec - tv.tv_sec + (double)(tv1.tv_usec - tv.tv_usec) / CLOCKS_PER_SEC)<<endl;

    double realEnd_t = realtime();
    cout<<"Total real Time: "<<realEnd_t - realStart_t <<endl;
    printf("=============================\n");
    //printf("graphInt: %d\n", graphInt.size());

    //printf("finalGraph: %d\n", finalGraph.size());
    printf("Tree Cam Count: %d\n", frequentTree);
    printf("Graph Cam Count: %d\n", finalGraph.size());
    printf("Total Cam Count: %d\n", finalGraph.size() + frequentTree);
    printf("Total Number of Subgraphs: %lld\n", subgraphCounter);


    return 0;
}
Exemplo n.º 29
0
void runEngine() {
	ChessBoard board;
	string Line;
	file.open("DEBUG.TXT");
	string board_status;
	cout.setf (ios::unitbuf); //disable buffering
	board.changeColor(BLACK);
	while (getline(cin,Line)) {
		int test = cutils::parseCommand(Line,file);
		switch (test) {
		case (NEW): 
		{
			board.reset();
			break;
		}
		case (BLACK):
			{
				board.changeColor(BLACK); //do not move now;
				break;
			}
		case (WHITE):
			{
				board.changeColor(WHITE);
				cutils::sendDebug(file,board_status);
				break;
			}
		case (MOVE): 
			{
				if (board.isForceModeOn()) { //is on when playing against computer
					SquarePack pack = cutils::convert(Line);
					board.movePiece(Line, board.board);
					board.history.push_back(Line);
					break;
				}

				SquarePack pack = cutils::convert(Line);
				board.movePiece(Line,board.board);
				board.history.push_back(Line);
				board.genMove();
				break;
			}
		case (CASTLE_SMALL_BLACK):
			{
					board.castle(CASTLE_SMALL_BLACK);
					board.history.push_back(Line);
					board.genMove();
			}
		case (CASTLE_BIG_BLACK):
			{
				board.castle(CASTLE_BIG_BLACK);
				board.history.push_back(Line);
				board.genMove();
				break;
			}
		case (CASTLE_SMALL_WHITE):
			{
				board.castle(CASTLE_SMALL_WHITE);
				board.history.push_back(Line);
				board.genMove();	
				break;
			}
		case (CASTLE_BIG_WHITE):
			{
				board.castle(CASTLE_BIG_WHITE);
				board.history.push_back(Line);
				board.genMove();
				break;
			}
		case (FEATURE_REQUEST):
			{
				cutils::sendOutput("feature myname=\"The Penguin is here.\" debug=1 done=1");
				break;
			}
		case (FORCE):
			{
				board.setForceMode(true);
				break;
			}
		case (GO):
			{
				file << "turn " << board.turn << " beginning " << endl;
				board.genMove();
				board.setForceMode(false);
				file << "turn " << board.turn << " end " << endl;
				board.turn++;
				break;
				
			}
		case (NO_RESPONSE):
			{
				break;
			}
		case (COMPUTER): 
			{
				board.setComputer(true);
				break;
			}
		default: 
			{
				break;
			}
		}
	}
	file.close();
}
Exemplo n.º 30
0
int main(int argc, char **argv)
{
#ifndef _DEBUG
	if (argc != 2)
	{
		printf("invalid arg");
		return 0;
	}
	const char* filename = argv[1];
#else
	const char* filename = "*****@*****.**";
#endif
	
	output.open("output.txt", ios::out | ios::trunc);
	output2.open("output2.txt", ios::out | ios::trunc);
	output3.open("output3.txt", ios::out | ios::trunc);
	if (!output.is_open())
	{
		exit(1);
	}
	FbxManager* fm = FbxManager::Create();
	FbxIOSettings *ios = FbxIOSettings::Create(fm, IOSROOT);
	//ios->SetBoolProp(EXP_FBX_ANIMATION, false);
	ios->SetIntProp(EXP_FBX_COMPRESS_LEVEL, 9);
	
	ios->SetAllObjectFlags(true);
	fm->SetIOSettings(ios);

	FbxImporter* importer = FbxImporter::Create(fm, "");
	if (!importer->Initialize(filename, -1, fm->GetIOSettings()))
	{
		printf("error returned : %s\n", importer->GetStatus().GetErrorString());
		exit(-1);
	}

	FbxScene* scene = FbxScene::Create(fm, "myscene");

	importer->Import(scene);
	importer->Destroy();
	output << "some\n";
	output << "charcnt : " << scene->GetCharacterCount() << endl << "node cnt : " << scene->GetNodeCount() << endl;
	int animstackcnt = scene->GetSrcObjectCount<FbxAnimStack>();
	output << "animstackcnt : " << animstackcnt << endl;

	output << "------------" << endl;
	vector<FbxNode*> removableNodes;

	for (int i = 0; i < scene->GetNodeCount(); i++)
	{
		FbxNode* node = scene->GetNode(i);
		output << "scene's node " << i << " : " << node->GetName() << ", childcnt : " << node->GetChildCount();
		if (node->GetNodeAttribute())
		{
			output <<", att type : " << node->GetNodeAttribute()->GetAttributeType();
			if (node->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::EType::eMesh)
			{
				FbxMesh* mesh = node->GetMesh();

				output << ", mem usage : " << mesh->MemoryUsage() << ", deformer cnt : " << mesh->GetDeformerCount(FbxDeformer::EDeformerType::eSkin) << endl;
				collapseMesh(mesh);
				FbxSkin* skin = (FbxSkin*) (mesh->GetDeformer(0, FbxDeformer::EDeformerType::eSkin));
				if (skin)
				{
					
					for (int cli = 0; cli < skin->GetClusterCount(); cli++)
					{
						FbxCluster* cluster = skin->GetCluster(cli);
						output << "\tcluster no." << cli << " has " << cluster->GetControlPointIndicesCount() << " connected verts" << endl;
						if (cluster->GetControlPointIndicesCount() == 0)
							removableNodes.push_back( cluster->GetLink() );
						
						//cluster->
						//skin->RemoveCluster(cluster);효과없음
					}

					
					
				}
				if (mesh->IsTriangleMesh())
				{
					output << "\tit's triangle mesh" << endl;
					
				}
				//mesh->RemoveDeformer(0);효과없음
			}
			else
				output << endl;
		}
		else
		{
			output << ", att type : none" << endl;
		}
	}

	for (int rni = 0; rni < removableNodes.size(); rni++)
	{
		FbxNode* rnd = removableNodes[rni];
		if (rnd && rnd->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::EType::eSkeleton)
		{
			output3 << rnd->GetName() << " node with no vert attached's curve : " << rnd->GetSrcObjectCount<FbxAnimCurve>() << "," << rnd->GetSrcObjectCount<FbxAnimCurveNode>() << endl;
		}
	}

	output << "-----------animinfo" << endl;
	int cubic = 0, linear = 0, cons = 0;
	for (int si = 0; si < animstackcnt; si++)
	{
		FbxAnimStack* stack = scene->GetSrcObject<FbxAnimStack>(si);
		for (int i = 0; i < stack->GetMemberCount<FbxAnimLayer>(); i++)
		{
			FbxAnimLayer* layer = stack->GetMember<FbxAnimLayer>(i);
			int curvenodecnt = layer->GetMemberCount<FbxAnimCurveNode>();
			int compositcnt = 0;
			for (int j = 0; j < curvenodecnt; j++)
			{
				FbxAnimCurveNode* cnode = layer->GetMember<FbxAnimCurveNode>(j);
				compositcnt += (cnode->IsComposite() ? 1 : 0);
			}
			output << "\tanimstack's layer " << i << " : " << layer->GetName() << ", curve node cnt : " << curvenodecnt << ", composit node cnt : " << compositcnt << endl;
			vector<FbxAnimCurveNode*> nodes2del;
			
			for (int j = 0; j < curvenodecnt; j++)
			{
				FbxAnimCurveNode* cnode = layer->GetMember<FbxAnimCurveNode>(j);
				output << "\t\tcurvenode " << j << " channel cnt : " << cnode->GetChannelsCount() << ", dst obj cnt " << cnode->GetDstObjectCount() << "(";
				for (int dsti = 0; dsti < cnode->GetDstObjectCount(); dsti++)
				{
					output << "," << cnode->GetDstObject(dsti)->GetName();
					if (cnode->GetDstObject(dsti)->GetSrcObjectCount() > 0)
						output << "<" << cnode->GetDstObject(dsti)->GetSrcObjectCount<FbxSkeleton>() << ">";
				}
				output << ")";
				FbxTimeSpan interval;
				if (cnode->GetAnimationInterval(interval))
				{
					output << ", start : " << interval.GetStart().GetTimeString() << ", end : " << interval.GetStop().GetTimeString() << endl;
				}
				else
				{
					nodes2del.push_back(cnode);
					output << ", no interval" << endl;
				}

				for (int chi = 0; chi < cnode->GetChannelsCount(); chi++)
				{
					
					int curvecnt = cnode->GetCurveCount(chi);
					output << "\t\t\tchannel." << chi << " curvecnt : " << curvecnt << endl;
					for (int ci = 0; ci < curvecnt; ci++)
					{
						FbxAnimCurve* curve = cnode->GetCurve(chi, ci);
						int keycnt = curve->KeyGetCount();
						output << "\t\t\t\tcurve no." << ci << " : key count : " << keycnt;
						output2 << "curve  " << ci << endl;
						
						vector<int> keys2Remove;
						for (int cki = 0; cki < keycnt; cki++)
						{
							FbxAnimCurveKey prevkey, currkey, nextkey;

							if (cki == 0 || cki == keycnt - 1)
								continue;
							
							currkey = curve->KeyGet(cki);
							prevkey = curve->KeyGet(cki-1);
							nextkey = curve->KeyGet(cki + 1);
							
							bool keepit = true;

							output2 << ci << "-" << cki;

//							keepit = keepTestHorizon(curve, prevkey, currkey, nextkey);
	//						if (keepit)
	//							keepit = slopkeepTest(curve, prevkey, currkey, nextkey);

							if (!keepit)
							{
								if (!(currkey.GetInterpolation() == FbxAnimCurveDef::EInterpolationType::eInterpolationConstant && nextkey.GetInterpolation() != FbxAnimCurveDef::EInterpolationType::eInterpolationConstant))
									keys2Remove.push_back(cki);
							}
						}
						for (int kri = keys2Remove.size() - 1; kri >= 0; kri--)
						{
							
							//curve->KeyRemove(keys2Remove[kri]);
						}
						output2 << endl;
						//output << ", cubic:linear:const : " << cubic << ":" << linear << ":" << cons << endl;
						if (keys2Remove.size() > 0)
							output << ", " << keys2Remove.size() << " keys removed";

						keycnt = curve->KeyGetCount();
						
					}

				}
			}
			//이부분은 별로 효과없음
			/*
			for (int di = 0; di < nodes2del.size(); di++)
			{
				layer->RemoveMember(nodes2del[di]);
			}
			*/
			
		}
	}
	output << "cubic:linear:const  " << cubic << ":" << linear << ":" << cons << endl;
	FbxExporter* exporter = FbxExporter::Create(fm, "");
	const char* outFBXName = "after.fbx";

	bool exportstatus = exporter->Initialize(outFBXName, -1, fm->GetIOSettings());
	if (exportstatus == false)
	{
		puts("err export fail");
	}
	exporter->Export(scene);
	exporter->Destroy();
	scene->Destroy();
	
	ios->Destroy();
	fm->Destroy();
	output.close();
	output2.close();
	output3.close();
	return 0;
}