Esempio n. 1
0
//----------------------------------------------------------------------
void write_file(){

	ofstream ofs("grid");

	for(int i=GRID_SIZE_X-1;i>-1;i--){
		for(int j=GRID_SIZE_Y-1;j>-1;j--){
			ofs <<  grid[i][j] << "	";
		}
		ofs << endl;
	}
	
	ofstream ofs2("particle_number");

	for(int i=GRID_SIZE_X-1;i>-1;i--){
		for(int j=GRID_SIZE_Y-1;j>-1;j--){
			ofs2 <<  particle_number[i][j] << "	";
		}
		ofs2 << endl;
	}
	
	ofstream ofs3("smoothing_particle");

	for(int i=0;i<PARTICLES;i++){
		ofs3 <<  x_smoothing[i] << "	"  << y_smoothing[i] << endl;
	}


}
Esempio n. 2
0
/**
 * @brief writefile::restoreFile
 * @param fileToRestore
 */
void writefile::restoreFile(string fileToRestore){
    string backUp= "backup";
    backUp.append(fileToRestore);

    string pathFileToRestore = createNewBackUp(backUp);
    string pathRestoredFile = createNewFile(fileToRestore);

    ofstream newfile (pathRestoredFile.c_str() , ios::trunc);
    newfile.close();


    std::ifstream ifs(pathFileToRestore.c_str(), std::ios::binary);
    std::ofstream ofs(pathRestoredFile.c_str(), std::ios::binary);

    ofs << ifs.rdbuf();

    ifs.close();
    ofs.close();

    pathFileToRestore.append("Columns");
    pathRestoredFile.append("Columns");

    ofstream newfile2 (pathRestoredFile.c_str() , ios::trunc);
    newfile2.close();

    std::ifstream ifs2(pathFileToRestore.c_str(), std::ios::binary);
    std::ofstream ofs2(pathRestoredFile.c_str(), std::ios::binary);

    ofs2 << ifs2.rdbuf();

    ifs2.close();
    ofs2.close();
}
Esempio n. 3
0
void writefile::backUpFile(string fileTobackUp){
    string backUp= "backup";
    backUp.append(fileTobackUp); //backupTest8

    string pathFileToBackUp = createNewFile(fileTobackUp); //../FSQL/Test8
    string pathbackUpFile = createNewBackUp(backUp);// ../FSQL/backupTest8

    ofstream newfile (pathbackUpFile.c_str() , ios::trunc);
    newfile.close();

    std::ifstream ifs(pathFileToBackUp.c_str(), std::ios::binary);
    std::ofstream ofs(pathbackUpFile.c_str(), std::ios::binary);

    ofs << ifs.rdbuf();

    ifs.close();
    ofs.close();

    pathFileToBackUp.append("Columns");
    pathbackUpFile.append("Columns");

    ofstream newfile2 (pathbackUpFile.c_str() , ios::trunc);
    newfile2.close();

    std::ifstream ifs2(pathFileToBackUp.c_str(), std::ios::binary);
    std::ofstream ofs2(pathbackUpFile.c_str(), std::ios::binary);

    ofs2 << ifs2.rdbuf();

    ifs2.close();
    ofs2.close();
}
Esempio n. 4
0
File: main.cpp Progetto: CCJY/coliru
int main(int argc, char** argv)
{
    classTwo<double> ch2(0.5);
    std::ofstream ofs2("test2.xml");
    boost::archive::xml_oarchive oa2(ofs2);
    oa2 << BOOST_SERIALIZATION_NVP(ch2);
    ofs2.close();
}
Esempio n. 5
0
void BlockEdgeDetectorT::process(vector<cv::Point2f> contour)
{
	vector<double> angles;

	const int _SPAN = 1;
	for (int j = _SPAN; j < contour.size() - _SPAN; j++)
	{
		if (contour[j - _SPAN].y == contour[j + _SPAN].y)
			angles.push_back(0);
		else if (contour[j - _SPAN].x == contour[j + _SPAN].x)
			angles.push_back(90);
		else
		{
			double k = (-1) * (double)(contour[j + _SPAN].y - contour[j - _SPAN].y) / (double)(contour[j + _SPAN].x - contour[j - _SPAN].x);
			double  angle = atan(k) / CV_PI * 180;
			angles.push_back(angle);
		}
	}



	ofstream ofs("up.txt", ios::out);
	ofs << "L2R,";
	for (int i = 0; i < angles.size(); i++)
	{
		ofs << angles[i] << ",";
	}



	vector<int> updown;
	for (int j = 1; j < contour.size(); j++)
	{
		if (contour[j].y == contour[j - 1].y)
			updown.push_back(0);
		else
			updown.push_back(contour[j].y - contour[j - 1].y);
	}
	for (int i = 0; i < updown.size(); i++)
	{
		if (i < 5)
			updown[i] = 0;
		else
		{

		}
	}


	ofstream ofs2("up_updown.txt", ios::out);
	for (int i = 0; i < updown.size(); i++)
	{
		ofs2 << updown[i] << ",";
	}
}
Esempio n. 6
0
int main(int argc, char **argv) {

    Vocab3 vocab;
    Splitter s(vocab,3,true);
    s.load_vocab(argv[1]);
    s.go();
    NgramCounter unigrams(1);
    ifstream ifs1(argv[1]);
    LineTokenizer lt1(ifs1);
    while(lt1.next()){
        Tokenizer tok(lt1.token(),' ');
        while(tok.next()){
            int wid = vocab.Add(tok.token());
            unigrams.increase_count(&wid,1);
        }
    }

    ifstream ifs(argv[1]);
    LineTokenizer lt(ifs);
    NgramCounter ng(2);
    while(lt.next()){
        Tokenizer tok(lt.token(),' ');
        while(tok.next()){
            int wid = vocab.Add(tok.token());
            int clid = s.get_class(wid);
            if (clid < 0 || unigrams.get_count(&wid) > 100 ){
                clid = wid;
            }
            else {
                string cl = "-" + s.class_set.Get(clid).str();
                clid = vocab.Add(LString(cl));
            }

            int key[2] = {clid,wid};
            ng.increase_count(key,1);
            cout << vocab.Get(clid) << " "; 
        }
        cout << endl;
    }
    BtreeIterator it = ng.iterator();
    ofstream ofs("my.classes");
    while(it.next()){
         ofs << vocab.Get(it.key()[1]) << "\t" << vocab.Get(it.key()[0]) << "\t" << (int)it.double_value()[0] << endl;
    }
    ofstream ofs2("my.classmap");
    it = s.class_map.iterator();
    while (it.next()){

         ofs2 << vocab.Get(it.key()[0]) << "\t" << s.class_set.Get(it.key()[1]) << endl;
    }
}
Esempio n. 7
0
void LoginQmail::login()
{
	SocketForHttp SKFH;
	HttpResponse HR;
	HttpHeadForGet HHFG("w.mail.qq.com");//设置http相关的信息
	SKFH.GetRequest(&HR,&HHFG);//获得w.mail.qq.com的html,为了取得ts的值

	setQTSVALUE(HR.body);//取得html文件里的ts的值,并存入QTSVALUE
	QPASSWORD = password;
	//////////////////////////////////////////////////////////////v8
	v8::Isolate *isolate = v8::Isolate::GetCurrent();//取得isolate(就是每个v8程序必须要做的)(设置这个函数的意义是为了多线程)
	v8::HandleScope handle_scope(isolate);//(设置名域)
	//设置访问回调函数
	v8::Handle<v8::ObjectTemplate> globalTemplate = v8::ObjectTemplate::New();
	globalTemplate->SetAccessor(v8::String::New("QPASSWORD"),QPASSWORDGetter);
	globalTemplate->SetAccessor(v8::String::New("QTSVALUE"),QTSVALUEGetter);
	std::ifstream ifs("JS/QJS.SNTJS");//读取js文件
	std::string JSscript;
	std::string res;
	readFile(&ifs,JSscript);//我的读取整个文件的函数
	JsManage::RunScriptRstr(JSscript.c_str(),globalTemplate,res);//运行js,并取得值(存在res里)
	///////////////////////////////////////////////////////////////
	HttpResponse HR2;
	PostName_Key pNK[11];
	setPostName_Key(pNK,username,res,"@qq.com");//设置post的内容
	HttpHeadForPost HHFP("cgi-bin/login?sid=",pNK,11,0,0,"w.mail.qq.com");//post头第一个参数是url域名(不包括主机),第二个是post内容,第三个是post内容的个数,第4,第5是cookie第六是主机名
	SKFH.PostRequest(&HR2,&HHFP);//post
	std::ofstream ofs("qmailrequest.html");
	ofs<<HR2.body;
	//获取里面的js的自动跳转的页面
	std::string rUrl;
	setRUrl(HR2.body,rUrl);//取得url

	Sleep(500);//暂停500毫秒
	pCONK = new Cookie_OnlyNK[HR2.cookies.size()];
	Cookie_OnlyNK::CookieDataToCookie_OnlyNK(HR2.cookies.cookieData.data(),pCONK,HR2.cookies.size());//把cookieData转换成Cookie_OnlyNK型
	HttpHeadForGet HHFG2("w.mail.qq.com",pCONK,HR2.cookies.size(),rUrl);//设置头
	HttpResponse HR3;
	SKFH.GetRequest(&HR3,&HHFG2);//取得信息
	std::ofstream ofs2("loginok.html");
	ofs2<<HR3.body;
}
Esempio n. 8
0
int UHD_SAFE_MAIN(int argc, char *argv[]){



    if (uhd::set_thread_priority_safe(1,true)) {
       std::cout << "set priority went well " << std::endl;
    };


    //variables to be set by po
    std::string args;
    double seconds_in_future;
    size_t total_num_samps;
    double tx_rate, freq, LOoffset;
    float gain;
    bool demoMode, use_8bits;
    bool use_external_10MHz; 
    std::string filename;
    uhd::tx_streamer::sptr tx_stream;
    uhd::device_addr_t dev_addr;
    uhd::usrp::multi_usrp::sptr dev;
    uhd::stream_args_t stream_args;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
      ("help", "help message")
      ("args", po::value<std::string>(&args)->default_value(""), "simple uhd device address args")
      ("secs", po::value<double>(&seconds_in_future)->default_value(3), "number of seconds in the future to transmit")
      ("nsamps", po::value<size_t>(&total_num_samps)->default_value(37028), "total number of samples to transmit")//9428
      ("txrate", po::value<double>(&tx_rate)->default_value(100e6/4), "rate of outgoing samples")
      ("freq", po::value<double>(&freq)->default_value(70e6), "rf center frequency in Hz")
      ("LOoffset", po::value<double>(&LOoffset)->default_value(0), "Offset between main LO and center frequency")
      ("demoMode",po::value<bool>(&demoMode)->default_value(true), "demo mode")
      ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), 
       "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
      ("filename",po::value<std::string>(&filename)->default_value("codedData.dat"), "input filename")
      ("gain",po::value<float>(&gain)->default_value(0), "gain of transmitter(0-13) ")
      ("8bits",po::value<bool>(&use_8bits)->default_value(false), "Use eight bits/sample to increase bandwidth")
    ;

    
    
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    
    //print the help message
    if (vm.count("help")){
      std::cout << boost::format("tx %s") % desc << std::endl;
      return ~0;
    }
    
 ///////////////////////////////////////////////////////////////// START PROCESSING /////////////////////////////////////////////////////////////////////
    
    std::complex<int16_t> *buffer0;
    buffer0 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer1;
    buffer1 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer2;
    buffer2 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer3;
    buffer3 = new std::complex<int16_t>[total_num_samps];
    std::complex<int16_t> *buffer4;
    buffer4 = new std::complex<int16_t>[total_num_samps];

    
    int16_t *aux0;
    aux0 = new int16_t[2*total_num_samps];
    int16_t *aux1;
    aux1 = new int16_t[2*total_num_samps];
    int16_t *aux2;
    aux2 = new int16_t[2*total_num_samps];
    int16_t *aux3;
    aux3 = new int16_t[2*total_num_samps];
    int16_t *aux4;
    aux4 = new int16_t[2*total_num_samps];
    
    //generate the picture as grayscale
    int r=system("octave image_transmition.m &");
    if(r){
      std::cout<<" loading picture - check!\n";
    }
    
    int nPicRaw = 16384;//size of the image in grayscale 128*128
    double nBinPac = 27200;//size of binary data in one packet
 

    //loading picture as grayscale
    int16_t pictureRaw[nPicRaw];
    std::ifstream ifs( "data_toSend.dat", std::ifstream::in );
    ifs.read((char * )pictureRaw,nPicRaw*sizeof(int16_t));
    ifs.close();  
    
    //converting grayscale to binary and XOR with pseudonoise
    itpp::bvec picBinInter = prepairPic(pictureRaw,nPicRaw);//transforms grayscale in binary data

    //cutting the large binary data into 5 packets
    bvec dataBinTmp0;
    dataBinTmp0.ins(dataBinTmp0.length(),picBinInter.get(0,(nBinPac-1)));
    bvec dataBinTmp1;
    dataBinTmp1.ins(dataBinTmp1.length(),picBinInter.get(nBinPac,(2*nBinPac-1)));
    bvec dataBinTmp2;
    dataBinTmp2.ins(dataBinTmp2.length(),picBinInter.get(2*nBinPac,(3*nBinPac-1)));
    bvec dataBinTmp3;
    dataBinTmp3.ins(dataBinTmp3.length(),picBinInter.get(3*nBinPac,(4*nBinPac-1)));
    bvec dataBinTmp4;
    dataBinTmp4.ins(dataBinTmp4.length(),picBinInter.get(4*nBinPac,picBinInter.length()));
    dataBinTmp4.ins(dataBinTmp4.length(),randb(nBinPac-dataBinTmp4.length())); //filling the last packet with random data

    //saving the binary picture
    it_file my_file("binPicture.it");
    my_file << Name("picBinInter") << picBinInter;
    my_file.flush();
    my_file.close();
    
    
    //processing each packet
    tx_funct(aux0,dataBinTmp0,dataBinTmp0.length());
    tx_funct(aux1,dataBinTmp1,dataBinTmp1.length());
    tx_funct(aux2,dataBinTmp2,dataBinTmp2.length());
    tx_funct(aux3,dataBinTmp3,dataBinTmp3.length());
    tx_funct(aux4,dataBinTmp4,dataBinTmp4.length());
    
    //filling the output buffer
    for(int i=0,count1=0;i<(int)(2*total_num_samps);i=i+2){
      buffer0[count1]=std::complex<short>(aux0[i],aux0[i+1]);
      buffer1[count1]=std::complex<short>(aux1[i],aux1[i+1]);
      buffer2[count1]=std::complex<short>(aux2[i],aux2[i+1]);
      buffer3[count1]=std::complex<short>(aux3[i],aux3[i+1]);
      buffer4[count1]=std::complex<short>(aux4[i],aux4[i+1]);
      count1++;
    }
 
    
   
    // Save data to file to check what was sent
    std::ofstream ofs( "sent0.dat" , std::ifstream::out );
    ofs.write((char * ) buffer0, 2*total_num_samps*sizeof(int16_t));
    ofs.flush();
    ofs.close();
    // Save data to file to check what was sent
    std::ofstream ofs1( "sent1.dat" , std::ifstream::out );
    ofs1.write((char * ) buffer1, 2*total_num_samps*sizeof(int16_t));
    ofs1.flush();
    ofs1.close();
    // Save data to file to check what was sent
    std::ofstream ofs2( "sent2.dat" , std::ifstream::out );
    ofs2.write((char * ) buffer2, 2*total_num_samps*sizeof(int16_t));
    ofs2.flush();
    ofs2.close();
    // Save data to file to check what was sent
    std::ofstream ofs3( "sent3.dat" , std::ifstream::out );
    ofs3.write((char * ) buffer3, 2*total_num_samps*sizeof(int16_t));
    ofs3.flush();
    ofs3.close();
    // Save data to file to check what was sent
    std::ofstream ofs4( "sent4.dat" , std::ifstream::out );
    ofs4.write((char * ) buffer4, 2*total_num_samps*sizeof(int16_t));
    ofs4.flush();
    ofs4.close();

    //Conjugate!!!
    for(int i=0; i<(int)(total_num_samps);i++){
      buffer0[i]=std::conj(buffer0[i]);
      buffer1[i]=std::conj(buffer1[i]);
      buffer2[i]=std::conj(buffer2[i]);
      buffer3[i]=std::conj(buffer3[i]);
      buffer4[i]=std::conj(buffer4[i]);
    } 
    
    

    std::cout << " ----------- " << std::endl;
    std::cout<<" Conjugated! \n";
    std::cout << " ----------- " << std::endl;
    
    ///////////////////////////////////////////////////////////////// END  PROCESSING /////////////////////////////////////////////////////////////////////
    
    //create a usrp device and streamer
    dev_addr["addr0"]="192.168.10.2";
    dev = uhd::usrp::multi_usrp::make(dev_addr);    


    // Internal variables 
    uhd::clock_config_t my_clock_config; 

    if (!demoMode) {
      dev->set_time_source("external");
    };

    if (use_external_10MHz) { 
      dev->set_clock_source("external");
    }
    else {
      dev->set_clock_source("internal");
    };


    uhd::usrp::dboard_iface::sptr db_iface;
    db_iface=dev->get_tx_dboard_iface(0);

    board_60GHz_TX  my_60GHz_TX(db_iface);  //60GHz 
    my_60GHz_TX.set_gain(gain); // 60GHz 

    uhd::tune_result_t tr;
    uhd::tune_request_t trq(freq,LOoffset); //std::min(tx_rate,10e6));
    tr=dev->set_tx_freq(trq,0);
    

    //dev->set_tx_gain(gain);
    std::cout << tr.to_pp_string() << "\n";
 

    stream_args.cpu_format="sc16";
    if (use_8bits)
      stream_args.otw_format="sc8";
    else
      stream_args.otw_format="sc16";

    tx_stream=dev->get_tx_stream(stream_args);


    //set properties on the device
    std::cout << boost::format("Setting TX Rate: %f Msps...") % (tx_rate/1e6) << std::endl;
    dev->set_tx_rate(tx_rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (dev->get_tx_rate()/1e6) << std::endl;
    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;


    

    uhd::tx_metadata_t md;


    if(demoMode){

    dev->set_time_now(uhd::time_spec_t(0.0));
    md.start_of_burst = true;
    md.end_of_burst = false;
    md.has_time_spec = false;
    md.time_spec = uhd::time_spec_t(seconds_in_future);

   
    tx_stream->send(buffer0,total_num_samps,md,60);
    
    tx_stream->send(buffer1,total_num_samps,md,3);
    
    tx_stream->send(buffer2,total_num_samps,md,3);

    tx_stream->send(buffer3,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    md.start_of_burst = false;

    std::cout << " " << std::endl;
    std::cout<< "picture transmitted once!" << std::endl;
    std::cout << " " << std::endl;
    
    int f=system("octave toMatlab.m");
    if(f){
      std::cout << " Programm Paused - Press Any Key To leave! " << std::endl;
    }


    }
    else
    {
    
    dev->set_time_now(uhd::time_spec_t(0.0));
    md.start_of_burst = true;
    md.end_of_burst = false;
    md.has_time_spec = false;
    md.time_spec = uhd::time_spec_t(seconds_in_future);

      
    tx_stream->send(buffer0,total_num_samps,md,60);
    
    tx_stream->send(buffer1,total_num_samps,md,3);
    
    tx_stream->send(buffer2,total_num_samps,md,3);

    tx_stream->send(buffer3,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    tx_stream->send(buffer4,total_num_samps,md,3);

    md.start_of_burst = false;

    std::cout << " " << std::endl;
    std::cout<< "picture transmitted once!" << std::endl;
    std::cout << " " << std::endl;

    };

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;


    return 0;
}
Esempio n. 9
0
void emotiv::init(){

	EE_DataChannel_t targetChannelList[] = {
		ED_COUNTER,
		ED_AF3, ED_F7, ED_F3, ED_FC5, ED_T7, 
		ED_P7, ED_O1, ED_O2, ED_P8, ED_T8, 
		ED_FC6, ED_F4, ED_F8, ED_AF4, ED_GYROX, ED_GYROY, ED_TIMESTAMP, 
		ED_FUNC_ID, ED_FUNC_VALUE, ED_MARKER, ED_SYNC_SIGNAL
	};

const char header[] = "COUNTER,AF3,F7,F3, FC5, T7, P7, O1, O2,P8" 
                      ", T8, FC6, F4,F8, AF4,GYROX, GYROY, TIMESTAMP, "   
                      "FUNC_ID, FUNC_VALUE, MARKER, SYNC_SIGNAL,";
const char affectivSuitesName[] = "Engagement,Frustration,Meditation,Excitement,";

	EmoEngineEventHandle eEvent			= EE_EmoEngineEventCreate();
	EmoStateHandle eState				= EE_EmoStateCreate();
	unsigned int userID					= 0;
	const unsigned short composerPort	= 1726;
	float secs							= 1;
	unsigned int datarate				= 0;
	bool readytocollect					= false;
	int option							= 0;
	int state							= 0;


	
	if (EE_EngineConnect() != EDK_OK) {
		throw std::exception("Emotiv Engine start up failed.");
	}
				
		
		std::cout << "Start receiving EEG Data and affectiv data! Press any key to stop logging...\n" << std::endl;
    	std::ofstream ofs("../bin/EEG_Data.csv",std::ios::trunc);
		ofs << header << std::endl;
		std::ofstream ofs2("../bin/Affectiv_Data.csv",std::ios::trunc);
		ofs2 << affectivSuitesName << std::endl;
		
		DataHandle hData = EE_DataCreate();
		EE_DataSetBufferSizeInSec(secs);

		std::cout << "Buffer size in secs:" << secs << std::endl;

		while (!_kbhit()) {

			state = EE_EngineGetNextEvent(eEvent);
			EE_Event_t eventType;

			if (state == EDK_OK) {

				eventType = EE_EmoEngineEventGetType(eEvent);
				EE_EmoEngineEventGetUserId(eEvent, &userID);
				EE_EmoEngineEventGetEmoState(eEvent, eState);

				// Log the EmoState if it has been updated
				if (eventType == EE_UserAdded) {
					std::cout << "User added";
					EE_DataAcquisitionEnable(userID,true);
					readytocollect = true;
				}
			

			if (readytocollect && (eventType == EE_EmoStateUpdated)) {
												
						EE_DataUpdateHandle(0, hData);

						unsigned int nSamplesTaken=0;
						EE_DataGetNumberOfSample(hData,&nSamplesTaken);
		
						std::cout << "Updated " << nSamplesTaken << std::endl;
						
						if (nSamplesTaken != 0  ) {

							double* data = new double[nSamplesTaken];
							for (int sampleIdx=0 ; sampleIdx<(int)nSamplesTaken ; ++ sampleIdx) {
								for (int i = 0 ; i<sizeof(targetChannelList)/sizeof(EE_DataChannel_t) ; i++) {

									EE_DataGet(hData, targetChannelList[i], data, nSamplesTaken);
									ofs << data[sampleIdx] << ",";
								}	
								ofs << std::endl;
							}
							delete[] data;							
						}
						
						float affEngegement = ES_AffectivGetEngagementBoredomScore(eState);
						float affFrus = ES_AffectivGetFrustrationScore(eState);
						float affMed = ES_AffectivGetMeditationScore(eState);
						float affExcitement = ES_AffectivGetExcitementShortTermScore(eState);
						printf("Engagement: %f, Frustration: %f, ...\n",affEngegement,affFrus);
						ofs2 <<affEngegement<<","<<	affFrus<<","<<affMed<<","<<affExcitement<<","<<std::endl;

			}
			}
			Sleep(100);
		}

		ofs.close();
		ofs2.close();
		EE_DataFree(hData);

}
Esempio n. 10
0
void NEATRunner::runLoop()
{
    //setting up signal handlers
    (void)signal(SIGINT,signalhandler);
    (void)signal(SIGTERM,signalhandler);
    (void)signal(SIGKILL,signalhandler);
    //
    time_t startt,tmpt;long totaltime=0;
    int countruns=0;
    
    vector<double> beststate;
    generations++;
    Evaluator * bak = NULL;
    if(nodes==0&&localFE==false){
        localFE=true;
    }else if(!localFE)
        cerr << "running cluster code.." << endl;
    writeRunfile(false,basefile,infoline,pid);
    pop->fe = icb->fe;
    stringstream sgfc; sgfc << sgf.str() << "-" << countruns << ".xml";
    if(speciationGraph)
        sg = new SpecGraph((int)pop->getMembers()->size(),generations,sgfc.str());
    stringstream sCurrentGenomeFilesuffixless; sCurrentGenomeFilesuffixless << sCurrentGenomeFile.str();
    stringstream sCurrentGenomeFilec; sCurrentGenomeFilec << sCurrentGenomeFile.str() << "-" << countruns;
    stringstream sCurrentGenGenomeFilec; sCurrentGenGenomeFilec << sCurrentGenomeFilec.str();
    stringstream sCurrentXMLGenomeFilec; sCurrentXMLGenomeFilec << sCurrentXMLGenomeFile.str() << "-" << countruns << ".xml";
    stringstream sCurrentGraphFilec; sCurrentGraphFilec << sCurrentGraphFile.str() << "-" << countruns;
    if(currentgraphf==NULL){
        currentgraphf = new ofstream(sCurrentGraphFile.str().c_str());
    }
    ofstream ofs(sCurrentGenomeFilec.str().c_str());
    ofstream ofs2(sCurrentGenomeFilesuffixless.str().c_str());
    ofstream ofscurg(newestgenome.c_str());
    bool slaveStop = false;
    int * bestspecid = new int;
    bool teststop = false;
    int gc=0; double ftest = 0;
    FitnessEvaluator * fe =  ev->getFitnessEvaluator();
    while(!stop){
        if(coevo != NULL && pop->getGeneration() == (coevo->getStartGeneration()+1)){
            cout << "doing coevo!?" << endl;
            bak = ev;
            ev = coevo;
        }
        teststop = false;
        startt = time(0);
        if(localFE){
            ev->evaluate(pop->getMembers(),pop->getMembers()->size());
        }else{
            if(generations>0&&(pop->getGeneration()+2)==generations&&runs==(countruns+1))
                slaveStop = true;
            
            comm->outputPopulation(pop,nodes,coevo,mc,slaveStop); //stream the population out to nodes for evaluation	
            ev->evaluate(pop->getMembers(),mc);//sweet..
            comm->readFitness(pop,mc); //read the corresponding returned fitness values
        }
        
        //checking and updating for the overall best phenotype.
        //do population/species sorting and stat updating
        pop->updateSpeciesStats();
        pop->sortmembers();
        pop->sortspecies();
        
        avgf = pop->calcAvgFitness();
        
        //keeping a copy of generation champ:
        gbest = pop->getCopyOfCurrentBest();
        setChamp(best,gbest,bestspecid); 
        if(ftest < pop->getMembers()->at(0)->getFitness()){
            ftest = pop->getMembers()->at(0)->getFitness();
        }
        else if(ftest != 0 && ftest > pop->getMembers()->at(0)->getFitness()){
            cout << "old genome:\n " << best->getGenome();
            cout << "new genome:\n " << pop->getMembers()->at(0)->getGenome();
            cout << "fitness went DOWN ftest: " << ftest << " pop->getMembers()->at(0)->getFitness(): " << pop->getMembers()->at(0)->getFitness() << endl;
            Phenotype * p = pop->getMembers()->at(0);
            vector<double> input = p->getNet()->getInput();
            Phenotypes * testp = new Phenotypes();
            testp->push_back(p);
            testp->push_back(gbest);

            for(unsigned int i=0;i<10;i++){
                ev->evaluate(testp
                             , 1);
            }
        }
        best->getGenome()->setSeed(rands);
        sCurrentGenGenomeFilec.str("");
        sCurrentGenGenomeFilec << sCurrentGenomeFilec.str();
        sCurrentGenGenomeFilec << "-" << pop->getGeneration();
        ofs.open(sCurrentGenomeFilec.str().c_str());
        ofs << best->getGenome();
        ofs.close();
        ofs2.open(sCurrentGenomeFilesuffixless.str().c_str());
        ofs2 << best->getGenome();
        ofs2.close();
        ofscurg.open(newestgenome.c_str());
        ofscurg << best->getGenome();
        ofscurg.close();
        
        ofstream ofs3(sCurrentGenGenomeFilec.str().c_str());
        ofs3 << best->getGenome();
        ofs3.close();
        //    if(pop->getGeneration()%2==0){
        //      cerr << icb->fe->show(best);
        //    }
        
        
        icb->best = best;
        
        writenetwork(best,sCurrentXMLGenomeFilec.str());
        if(speciationGraph)
            sg->update(pop);
        //writing stats to file
        
        *currentgraphf << getStatString(pop,avgf);
        currentgraphf->flush();
        //updating smoothed graph data..
        updateSmoothData(smoothdata,pop,avgf,countruns+1);
        if(coevo!=NULL)
            coevo->update(pop); // update the coevolution data..
        
        tmpt = (time(0)-startt);
        totaltime += tmpt;
        
        cerr << (pop->getGeneration()+1) << ":"
        << " curmaxid: "<<pop->getMembers()->at(0)->getID()
        << "(" << pop->getMembers()->at(0)->getSpecies()->getID() << ")"
        << " curmax: " << pop->getMembers()->at(0)->getFitness()
        << " bestid: "<< best->getID() 
        << "(" << *bestspecid << ")"
        << " bestfitness: "<< best->getFitness()
        << " maxfitness: " << pop->getHighestFitness() 
        << " avgfitness: " << pop->calcAvgFitness()
        << " curmin: " << pop->getMembers()->at(pop->getMembers()->size()-1)->getFitness()
        << " species: " << pop->getSpecies()->size()
        << " (" << pop->spectarget << ") " 
        << " size: " << pop->getMembers()->size() 
        << " time: " << tmpt 
        << " time/size: " << (double)tmpt/(double)pop->getMembers()->size() << endl;
        
        //run the code that adjusts fitness according to species age and size..
        //select the lucky ones for reprocicration..
        
        sel->select(pop,sel->getySpeciesForElitism());
        //do the mating    
        teststop = fe->stop(best);
        rep->reproduce(pop);
        if(((generations>0&&(pop->getGeneration()+1) ==generations) || teststop)
           && runs==(countruns+1)){ // stopconditions
            if(teststop && comm!=NULL)
                comm->outputPopulation(pop,nodes,coevo,mc,true);
            gc += pop->getGeneration();
            setChamp(sbest,best,bestspecid);
            stop = true;
            if(speciationGraph){
                sg->writetofile();
                delete sg;
            }
        }else{
            if(generations>0&& ((pop->getGeneration()+1)==generations || teststop )){
                gc += pop->getGeneration();
                //generation run is over lets go on to the next run..
                countruns++;
                //keep superchamp across runs..
                Phenotype * tmp = best;
                best = NULL;
                setChamp(sbest,tmp,bestspecid);
                //reset population...
                if(pop->spawn)
                    pop->resetSpawn();
                else
                    pop->resetGenesis();
                if(bak!=NULL){
                    ev = bak;
                    bak = NULL;
                }
                
                if(speciationGraph){
                    sg->writetofile();
                    delete sg;
                    sgfc.str(""); sgfc << sgf.str() << "-" << countruns << ".xml";
                    sg = new SpecGraph((int)pop->getMembers()->size(),generations,sgfc.str());
                }
                sCurrentGenomeFilec.str(""); sCurrentGenomeFilec << sCurrentGenomeFile.str() << "-" << countruns;
                sCurrentXMLGenomeFilec.str(""); sCurrentXMLGenomeFilec << sCurrentXMLGenomeFile.str() << "-" << countruns << ".xml";
                sCurrentGraphFilec.str(""); sCurrentGraphFilec << sCurrentGraphFile.str() << "-" << countruns;
                ftest = 0;
                delete currentgraphf; currentgraphf = new ofstream(sCurrentGraphFilec.str().c_str());
                
            }
        }
    }
    ofstream ofsuper(sFinalGenomeFile.c_str());
    ofsuper << sbest->getGenome();
    ofsuper.close();
    cout << "final best fitness" << sbest->getFitness() << endl;
    if(countruns>1){
        cout << "avg gc: " << (double)gc/(double)(countruns+1) << endl;
    }
    delete sbest;
    ofstream finalgraphf(finalgraphfile.c_str());
    for(int i=0;i<generations-1;i++)
        finalgraphf << smoothdata[i][0]/(double)runs << " " 
        << smoothdata[i][1]/(double)runs << " " 
        << smoothdata[i][2]/(double)runs << endl;
    for(int i=0;i<generations-1;i++)
        delete[] smoothdata[i];
    delete[] smoothdata;
    
    //close graph files..
    finalgraphf.close();
    currentgraphf->close();
    delete currentgraphf;
    delete bestspecid;
    writeRunfile(true,basefile,infoline,pid);  
    
}
int main()
{
	//txtPostureData読み込み
	std::ifstream ifs("GetPositionALL.txt");
	std::string str;
	int CountData = 0;
	//postureDataを入れるvector確保
	//std::vector<std::vector<double>>txtPosture(3, std::vector<double>(25));
	std::vector<std::vector<std::vector<double>>> Posture(3, std::vector<std::vector<double>>(25, std::vector<double>(3000, 0)));//1595

	std::vector< std::vector<double> > position( 25, std::vector<double>( 3 ) );
	std::vector< std::vector<double> > PositionBase( 25, std::vector<double>( 3 ) );
	std::vector< std::vector<double> > RotatePosition( 25, std::vector<double>( 3 ) );
	std::vector< std::vector<double> > XRotatePosition( 25, std::vector<double>( 3 ) );
	std::vector< std::vector<double> > YRotatePosition( 25, std::vector<double>( 3 ) );
	std::vector< std::vector<double> > ZRotatePosition( 25, std::vector<double>( 3 ) );

	std::ofstream ofs( "GetPositionALL.txt", std::ios::out | std::ios::app );
	
	std::ofstream ofs2( "GetPositionArm.txt", std::ios::out | std::ios::app );

	while (getline(ifs, str))
	{
		std::string tmp;
		std::istringstream stream(str);
		int CountXYZ = 0, CountPosture = 0;
		while (getline(stream, tmp, '\t'))
		{
			//文字列から数字(double)に変換
			std::istringstream is;
			is.str(tmp);    
			double x;             
			is >> x;                
			//postureにtxtPostureDataを代入
			Posture[CountXYZ][CountPosture][CountData] = x;
			//std::cout <<"("<<CountXYZ<<":"<<CountPosture<<":"<<CountData<<")->"<< x << std::endl;
			
			//countを取ってpostureに代入
			CountXYZ++;
			if (CountXYZ == 3)
			{
				CountPosture++;
				CountXYZ = 0;
			}
			if (CountPosture == 25)
			{
				CountData++;
				CountPosture = 0;
			}
		}
	}

	for ( int i = 0; i <= CountData; i++ )
	{
		//テキストベースでpositionを保存
		for ( int count = 0; count <= 24; count++ )
		{
			for ( int PosCount = 0; PosCount <= 2; PosCount++ )
			{
				Posture[PosCount][count][i] = position[count][PosCount];
			}
		}
		for ( int count = 0; count <= 24; count++ )
		{
			for ( int PosCount = 0; PosCount <= 2; PosCount++ )
			{
				PositionBase[count][PosCount] = position[count][PosCount] - position[0][PosCount];
			}
		}


		//座標変換ユーザの角度
		double crossX = ( PositionBase[8][1] * PositionBase[4][2] ) - ( PositionBase[8][2] * PositionBase[4][1] );
		double crossY = ( PositionBase[8][2] * PositionBase[4][0] ) - ( PositionBase[8][0] * PositionBase[4][2] );
		double crossZ = ( PositionBase[8][0] * PositionBase[4][1] ) - ( PositionBase[8][1] * PositionBase[4][0] );//外積
		double nLength = sqrtf( ( crossX*crossX ) + ( crossY*crossY ) + ( crossZ*crossZ ) );//normalize

		double nx = crossX / nLength;//1より大きかったらだめifブンツクレ
		double ny = crossY / nLength;
		double nz = crossZ / nLength;//面法線ベクトル
		double nxx = crossX / sqrtf( ( crossX*crossX ) + ( crossY*crossY ) );
		double nzz = crossZ / sqrtf( ( crossX*crossX ) + ( crossZ*crossZ ) );
		/*
		if ( nx >= 1 )nx = 1;
		if ( ny >= 1 )ny = 1;
		if ( nz >= 1 )nz = 1;
		*/
		double cosX = nx;//nx / nLength;
		double cosY = ny;//ny / nLength;
		double cosZ = nz;//nz / nLength;//面の傾き(cos)?
		double cosXX = nxx;//x / √x^2+y^2
		double cosZZ = nzz;
		double cosZZZ = ( PositionBase[4][1] ) / sqrtf( ( PositionBase[4][1] * PositionBase[4][1] ) + ( PositionBase[4][2] * PositionBase[4][2] ) );

		double sinX = crossZ / nLength;//sqrtf( 1 - ( cosX*cosX ) );//マイナスになってる?正じゃないといけない
		double sinY = sqrtf( ( crossX*crossX ) + ( crossY*crossY ) ) / nLength;//sqrtf( 1 - ( cosY*cosY ) );
		double sinZ = crossY / nLength;//sqrtf( 1 - ( cosZ*cosZ ) );//面の傾き(sin)?
		double sinXX = sqrtf( 1 - ( cosXX*cosXX ) );
		double sinZZ = crossX / sqrtf( ( crossX*crossX ) + ( crossZ*crossZ ) );
		double sinZZZ = ( PositionBase[4][2] ) / sqrtf( ( PositionBase[4][1] * PositionBase[4][1] ) + ( PositionBase[4][2] * PositionBase[4][2] ) );
		
		//各軸回転行列
		std::vector< std::vector<double> > vectorRx( 3, std::vector<double>( 3 ) );
		std::vector< std::vector<double> > vectorRy( 3, std::vector<double>( 3 ) );
		std::vector< std::vector<double> > vectorRz( 3, std::vector<double>( 3 ) );
		std::vector< std::vector<double> > vectorR( 3, std::vector<double>( 3 ) );

		vectorRx[0][0] = 1;
		vectorRx[0][1] = 0;
		vectorRx[0][2] = 0;
		vectorRx[1][0] = 0;
		vectorRx[1][1] = sinY;//cosX(90"-")
		vectorRx[1][2] = -cosY;//-sinX
		vectorRx[2][0] = 0;
		vectorRx[2][1] = cosY;//sinX
		vectorRx[2][2] = sinY;//cosX//X軸周り回転行列

		vectorRy[0][0] = cosZZ;//cosZ;//cosY
		vectorRy[0][1] = 0;
		vectorRy[0][2] = -sinZZ;//sinZ;//sinY
		vectorRy[1][0] = 0;
		vectorRy[1][1] = 1;
		vectorRy[1][2] = 0;
		vectorRy[2][0] = sinZZ;//-sinZ;//sinY
		vectorRy[2][1] = 0;
		vectorRy[2][2] = cosZZ;//cosY//Y軸周り回転行列

		vectorRz[0][0] = cosX;//cosZ
		vectorRz[0][1] = -sinX;//-sinZ
		vectorRz[0][2] = 0;
		vectorRz[1][0] = sinX;//sinZ
		vectorRz[1][1] = cosX;//cosZ
		vectorRz[1][2] = 0;
		vectorRz[2][0] = 0;
		vectorRz[2][1] = 0;
		vectorRz[2][2] = 1;//Z軸周り回転行列


		//行列計算->Y軸周りの計算
		for ( int count = 0; count <= 24; count++ )
		{
			for ( int PosCount = 0; PosCount <= 2; PosCount++ )
			{
				//cout << position[count][PosCount] << endl;
				//ofs << position[count][PosCount] << "\t";
				if ( PosCount == 0 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						YRotatePosition[count][PosCount] += PositionBase[count][i] * vectorRy[0][i];
					}
				}
				else if ( PosCount == 1 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						YRotatePosition[count][PosCount] += PositionBase[count][i] * vectorRy[1][i];
					}
				}
				else if ( PosCount == 2 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						YRotatePosition[count][PosCount] += PositionBase[count][i] * vectorRy[2][i];
					}
				}
				//RotatePosition[count][PosCount] = PositionBase[count][PosCount];
			}
		}

		//行列計算->X軸周りの計算
		for ( int count = 0; count <= 24; count++ )
		{
			for ( int PosCount = 0; PosCount <= 2; PosCount++ )
			{
				if ( PosCount == 0 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						XRotatePosition[count][PosCount] += YRotatePosition[count][i] * vectorRx[0][i];
					}
				}
				else if ( PosCount == 1 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						XRotatePosition[count][PosCount] += YRotatePosition[count][i] * vectorRx[1][i];
					}
				}
				else if ( PosCount == 2 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						XRotatePosition[count][PosCount] += YRotatePosition[count][i] * vectorRx[2][i];
					}
				}
			}
		}


		std::vector<double> shoulder( 3 );
		shoulder[0] = /*PositionBase[4][0] - PositionBase[8][0];*/XRotatePosition[4][0] - XRotatePosition[8][0];
		shoulder[1] = /*PositionBase[4][1] - PositionBase[8][1]; */XRotatePosition[4][1] - XRotatePosition[8][1];
		shoulder[2] = /*PositionBase[4][2] - PositionBase[8][2];*/XRotatePosition[4][2] - XRotatePosition[8][2];

		double cosXshoulder = shoulder[0] / sqrtf( ( shoulder[0] * shoulder[0] ) + ( shoulder[1] * shoulder[1] ) + ( shoulder[2] * shoulder[2] ) );
		double sinXshoulder = shoulder[1] / sqrtf( ( shoulder[0] * shoulder[0] ) + ( shoulder[1] * shoulder[1] ) + ( shoulder[2] * shoulder[2] ) );
		vectorRz[0][0] = cosXshoulder;//cosZ
		vectorRz[0][1] = sinXshoulder;//-sinZ
		vectorRz[0][2] = 0;
		vectorRz[1][0] = -sinXshoulder;//sinZ
		vectorRz[1][1] = cosXshoulder;//cosZ
		vectorRz[1][2] = 0;
		vectorRz[2][0] = 0;
		vectorRz[2][1] = 0;
		vectorRz[2][2] = 1;//Z軸周り回転行列

		//行列計算->Z軸周りの計算
		for ( int count = 0; count <= 24; count++ )
		{
			for ( int PosCount = 0; PosCount <= 2; PosCount++ )
			{
				if ( PosCount == 0 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						ZRotatePosition[count][PosCount] += XRotatePosition[count][i] * vectorRz[0][i];
					}
				}
				else if ( PosCount == 1 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						ZRotatePosition[count][PosCount] += XRotatePosition[count][i] * vectorRz[1][i];
					}
				}
				else if ( PosCount == 2 )
				{
					for ( int i = 0; i <= 2; i++ )
					{
						ZRotatePosition[count][PosCount] += XRotatePosition[count][i] * vectorRz[2][i];
					}
				}
			}
		}
		//今回はz軸回転->y軸回転->z軸回転順に回転行列を計算した原点は骨格の腰中央点
		RotatePosition = ZRotatePosition;
		//どの回転結果を表示するか->以下RotatePositionを表示


		//座標変換後のpostureをテキストファイルに保存
		std::ofstream ofs1( "RotatePostureALL.txt", std::ios::out | std::ios::app );
		for ( int count = 0; count <= 24; count++ )
		{
			for ( int PosCount = 0; PosCount <= 2; PosCount++ )
			{
				//cout << position[count][PosCount] << endl;
				ofs1 << RotatePosition[count][PosCount] * 80000 << "\t";

			}
			if ( count == 24 )
			{
				ofs1 << "\n";
			}
		}
		std::ofstream ofs3( "RotatePostureArm.txt", std::ios::out | std::ios::app );
		for ( int count = 0; count <= 24; count++ )
		{
			if ( count == 8 || count == 9 || count == 11 )
			{
				ofs3 << RotatePosition[count][0] * 80000 << "\t" << -RotatePosition[count][1] * 80000 << "\t" << RotatePosition[count][2] * 80000 << "\t";
			}
			else
			{
				ofs3 << RotatePosition[count][0] * 80000 << "\t" << -RotatePosition[count][1] * 80000 << "\t" << RotatePosition[count][2] * 80000 << "\t";
			}
			if ( count == 24 )
			{
				ofs3 << "\n";
			}
		}

	}


    return 0;
}
int main(int argc, char *argv[])
{
    unsigned long file_size, all_state_num, iter_num;
    vector<board> all_state;

    uint64_t count[4] = {-1,0,0,0};
    uint64_t count4created[4] = {-1,0,0,0};
    iter_num = 1;

    printf("program started.\n");

    // 全ての局面 all-state_sorted.dat の読込
    file_size     = get_file_size("all-state_sorted.dat");
    all_state_num = file_size / sizeof(board);
    all_state.resize(all_state_num);
    ifstream ifs("all-state_sorted.dat");
    ifs.read((char*)&all_state[0], all_state.size() * sizeof(board));

    printf("read all-state_sorted\n");

    // 勝敗判定の結果,INDEXは all_state 内の局面の位置
    vector<unsigned char> judge(all_state_num,0);

    // 勝敗判定が着くまでの手数
    vector<unsigned char> judge_count(all_state_num,0);

    // 繰り返し操作の上限
    unsigned long MAX_ITER_NUM = 0;
    unsigned long MAX_ITER_STATE_NUM = all_state_num;
    if (argc == 3) {
        MAX_ITER_NUM = atoi(argv[1]);
        MAX_ITER_STATE_NUM = atoi(argv[2]);
    }

    // 初期化
    for (size_t i=0; i<MAX_ITER_STATE_NUM; i++) {
        board b = all_state[i];
        if (is_win_state(b)) {
            judge[i] = WIN;
            count[WIN]++;
        } else if (is_lose_state(b)) {
            judge[i] = LOSE;
            count[LOSE]++;
        } else {
            judge[i] = UNKNOWN;
            count[UNKNOWN]++;
        }
        judge_count[i] = 0;
    }


    printf("begin create win lose baord\n");

    // 繰り返し勝敗データを更新していく
    for(;;) {
        vector<unsigned char> judge_new(judge);

        unsigned int win_add_num = 0;
        unsigned int lose_add_num = 0;
        if (MAX_ITER_NUM != 0 && iter_num > MAX_ITER_NUM) {
            break;
        }

        for (size_t i=0; i<MAX_ITER_STATE_NUM; i++) {
            board b = all_state[i];
            if (judge[i] == UNKNOWN) {
                unsigned char winorlose = get_winorlose(b, all_state, judge);

                if (winorlose == WIN) {
                    judge_new[i] = WIN;
                    judge_count[i] = iter_num;
                    count[WIN]++;
                    count[UNKNOWN]--;
                    win_add_num++;
                } else if(winorlose == LOSE) {
                    judge_new[i] = LOSE;
                    judge_count[i] = iter_num;
                    count[LOSE]++;
                    count[UNKNOWN]--;
                    lose_add_num++;
                }

            }
        }

        count4created[LOSE] += lose_add_num;
        count4created[WIN]  += win_add_num;

        printf("---------------------\n");
        printf("iter_num: %ld\n", iter_num);
        printf("win_add_num: %d\n", win_add_num);
        printf("lose_add_num: %d\n", lose_add_num);
        printf("count4created[win] = %ld\n", count4created[WIN]);
        printf("count4created[lose] = %ld\n", count4created[LOSE]);

        judge.swap(judge_new);

        if (win_add_num == 0 && lose_add_num == 0) {
            break;
        }

        iter_num++;
    }

    // 結果を出力
    printf("---------------------\n");
    printf("size = %ld\n", all_state.size());
    printf("win_num = %ld\n", count[WIN]);
    printf("lose_num = %ld\n", count[LOSE]);
    printf("count4created[win] = %ld\n", count4created[WIN]);
    printf("count4created[lose] = %ld\n", count4created[LOSE]);
    printf("unknown_num = %ld\n", count[UNKNOWN]);
    printf("iter_num = %ld\n", iter_num);

    ofstream ofs1("judge.dat");
    ofs1.write((char *)&judge[0], judge.size()*sizeof(unsigned char));

    ofstream ofs2("judge_count.dat");
    ofs2.write((char *)&judge_count[0], judge_count.size()*sizeof(unsigned char));

    return 0;
}
Esempio n. 13
0
void IDPNagato::sinc()
{
  //char fname_energy[64]; sprintf(fname_energy, ftemp_energy, 0);
  //ofstream ofs_energy(fname_energy);
  //ofstream ofs_r1_st(fname_r1_sinc_st), ofs_r1_ev(fname_r1_sinc_ev);
  //ofstream ofs_r2_st(fname_r2_sinc_st), ofs_r2_ev(fname_r2_sinc_ev);
  //ofstream ofs_endeffector(fname_sinc_endeffector);
  ofstream ofs_energy(fname_lst[eENERGY][eSinc][eName]);
  ofstream ofs_r1_st(fname_lst[eGRAPH_ST_R1][eSinc][eName]);
  ofstream ofs_r1_ev(fname_lst[eGRAPH_EV_R1][eSinc][eName]);
  ofstream ofs_r2_st(fname_lst[eGRAPH_ST_R2][eSinc][eName]);
  ofstream ofs_r2_ev(fname_lst[eGRAPH_EV_R2][eSinc][eName]);
  ofstream ofs_endeffector(fname_lst[eGRAPH_ENDEFFECTOR][eSinc][eName]);
  
  //  FILE* fp_energy = fopen(fname_energy,"w");
  //printf("line=%d %s\n", __LINE__, fname_r1_sinc_st);
  //printf("line=%d %s\n", __LINE__, fname_r2_sinc_st);
  //printf("line=%d %s\n", __LINE__, fname_r1_sinc_ev);
  printf("line=%d %s\n", __LINE__
	 , fname_lst[eGRAPH_ST_R1][eSinc][eName]);
  printf("line=%d %s\n", __LINE__
	 , fname_lst[eGRAPH_EV_R1][eSinc][eName]);
  printf("line=%d %s\n", __LINE__
	 , fname_lst[eGRAPH_ST_R2][eSinc][eName]);
  printf("line=%d %s\n", __LINE__
	 , fname_lst[eGRAPH_EV_R2][eSinc][eName]);
  sleep(2);
  
  double t = 0;
  for(nt = 0; nt <= static_cast<int>(Ts/dt); ++nt )
    {
      graph_standard(ofs_r1_st, t,
		     r1.th, r1.thv, r1.tha,
		     e1.ev, e1.ia, e1.tau,
		     e1.energy, e1.ev*e1.ia);
      graph_volt_constituent(ofs_r1_ev, t, e1.ev,
			     b1*r1.thv, b2*r1.tha, b3*e1.tau);
        
      graph_standard(ofs_r2_st, t,
		     r2.th, r2.thv, r2.tha,
		     e2.ev, e2.ia, e2.tau,
		     e2.energy, e2.ev*e2.ia);
      graph_volt_constituent(ofs_r2_ev, t, e2.ev,
			     b1*r2.thv, b2*r2.tha, b3*e2.tau);
      
      graph_endeffector(ofs_endeffector,  t, v1, r3);
      
      t = t + dt;
      v1.th  = sc.sin_th1(t);
      v1.thv = sc.sin_th1v(t);
      v1.tha = sc.sin_th1a(t);

      enemin2 = En();
      // if (nt < nt11){ enemin2 = En1(); }
      // if (nt >= nt11 && nt < nt22){ enemin2 = En2(); }
      // if (nt >= nt22){ enemin2 = En3(); }
      
      ofs_energy << t <<" "<< enemin2 << endl;
      //      fprintf(fp_energy, "%8.4lf %8.4lf\n", t, enemin2 );

      if (nt % 10 == 0)
	{
	  //char fname[4][64];
	  //sprintf(fname[1], ftemp_sinc_e[1], nt);
	  //sprintf(fname[2], ftemp_sinc_e[2], nt);	
	  //sprintf(fname[3], ftemp_sinc_e[3], nt);
	  sprintf(fname_lst[eZU_E1][eSinc][eName],
		  fname_lst[eZU_E1][eSinc][eTemp], nt);
	  sprintf(fname_lst[eZU_E2][eSinc][eName],
		  fname_lst[eZU_E2][eSinc][eTemp], nt);
	  sprintf(fname_lst[eZU_E3][eSinc][eName],
		  fname_lst[eZU_E3][eSinc][eTemp], nt);
	  
	  ofstream ofs1(fname_lst[eZU_E1][eSinc][eName]);
	  ofstream ofs2(fname_lst[eZU_E2][eSinc][eName]);
	  ofstream ofs3(fname_lst[eZU_E3][eSinc][eName]);
	  //zu( ofs1 ); all in
	  //zu( ofs1, ofs2 );
	  zu( ofs1, ofs2, ofs3 );// !not implement
	}
      // output volt ampere field
      // plot("");
    }
  //assert(false);
}
Esempio n. 14
0
void IDPDIRECT::sinc()
{
  //char fname_energy[64]; sprintf(fname_energy, ftemp_energy, 0);
  ofstream ofs_energy(fname_lst[eENERGY][eSinc][eName]     );
  ofstream ofs_r1_st (fname_lst[eGRAPH_ST_R1][eSinc][eName]);
  ofstream ofs_r1_ev (fname_lst[eGRAPH_EV_R1][eSinc][eName]);
  ofstream ofs_r2_st (fname_lst[eGRAPH_ST_R2][eSinc][eName]);
  ofstream ofs_r2_ev (fname_lst[eGRAPH_ST_R2][eSinc][eName]);
  ofstream ofs_r3_st (fname_lst[eGRAPH_ST_R3][eSinc][eName]);
  ofstream ofs_r3_ev (fname_lst[eGRAPH_ST_R3][eSinc][eName]);
  
  //  FILE* fp_energy = fopen(fname_energy,"w");
  printf("line=%d %s\n", __LINE__, fname_lst[eGRAPH_ST_R1][eSinc][eName]);
  printf("line=%d %s\n", __LINE__, fname_lst[eGRAPH_EV_R1][eSinc][eName]);
  printf("line=%d %s\n", __LINE__, fname_lst[eGRAPH_ST_R2][eSinc][eName]);
  printf("line=%d %s\n", __LINE__, fname_lst[eGRAPH_EV_R2][eSinc][eName]);
  printf("line=%d %s\n", __LINE__, fname_lst[eGRAPH_ST_R3][eSinc][eName]);
  printf("line=%d %s\n", __LINE__, fname_lst[eGRAPH_EV_R3][eSinc][eName]);
  
  double t = 0;
  for( int i = 0; i <= static_cast<int>(Ts/dt); ++i )
    {
      graph_standard(ofs_r1_st, t,
		     r1.th, r1.thv, r1.tha,
		     e1.ev, e1.ia, e1.tau,
		     e1.energy, e1.ev*e1.ia);
      graph_volt_constituent(ofs_r1_ev, t, e1.ev,
			     b1*r1.thv, b2*r1.tha, b3*e1.tau);
      // --------------------------------------------------
      graph_standard(ofs_r2_st, t,
		     r2.th, r2.thv, r2.tha,
		     e2.ev, e2.ia, e2.tau,
		     e2.energy, e2.ev*e2.ia);
      graph_volt_constituent(ofs_r2_ev, t, e2.ev,
			     b1*r2.thv, b2*r2.tha, b3*e2.tau);
      // --------------------------------------------------
      graph_standard(ofs_r3_st, t,
		     r3.z0, r3.Thv(), r3.Tha(),
		     e3.ev, e3.ia, e3.tau,
		     e3.energy, e3.ev*e3.ia);
      graph_volt_constituent(ofs_r3_ev, t, e3.ev,
			     b1*r3.Thv(), b2*r3.Tha(), b3*e3.tau);
      // --------------------------------------------------
      t = t + dt;
      v1.th  = sc.sin_th1(t);
      v1.thv = sc.sin_th1v(t);
      v1.tha = sc.sin_th1a(t);
      enemin2 = En();

      ofs_energy << t <<" "<< enemin2 << endl;
      //      fprintf(fp_energy, "%8.4lf %8.4lf\n", t, enemin2 );

      if (i % 10 == 0)
	{
	  sprintf(fname_lst[eZU_E1][eSinc][eName],
		  fname_lst[eZU_E1][eSinc][eTemp], i);
	  sprintf(fname_lst[eZU_E2][eSinc][eName],
		  fname_lst[eZU_E2][eSinc][eTemp], i);
	  sprintf(fname_lst[eZU_E3][eSinc][eName],
		  fname_lst[eZU_E3][eSinc][eTemp], i);
	  
	  ofstream ofs1(fname_lst[eZU_E1][eSinc][eName]);
	  ofstream ofs2(fname_lst[eZU_E2][eSinc][eName]);
	  ofstream ofs2(fname_lst[eZU_E3][eSinc][eName]);
	  // ofstream ofs3(fname_lst[eZU_E2][eSinc][eName]);
	  //zu( ofs1 ); all in
	  //zu( ofs1, ofs2 );
	  zu( ofs1, ofs2, ofs3 );// !not implement
	}
      // output volt ampere field
      // plot("");
    }
}
Esempio n. 15
0
int main (int argc, char **argv)
{
  std::string file  = "";
  std::string index = "";
  std::string ofile = "";
  extern char *optarg;

  int opt;
  while ((opt = getopt(argc, argv, "i:o:O:")) != -1) {
    switch(opt) {
    case 'i':
      file = std::string (optarg);
      break;
    case 'o':
      index = std::string (optarg);
      break;
    case 'O':
      ofile = std::string (optarg);
       break;
     default:
      std::cout << "Usage: " << argv[0] << OPT << std::endl;
      return -1;
    }
  }

  if (file.empty () || index.empty ()) {
    std::cout << "Usage: " << argv[0] << OPT << std::endl;
    return -1;
  }

  std::istream *is;
  if (file == "-")  is = &std::cin;
  else              is = new std::ifstream (file.c_str());

  if (! *is) {
    std::cerr << "Cannot Open: " << file << std::endl;
    return -1;
  }

  std::vector <Darts::DoubleArray::key_type *> ary;
  std::vector <std::pair<const char *, double> > ary2;
  std::vector <double> alpha;
  std::map<std::string, double> rules;

  char buf[8192];
  char *column[2];
  double bias = 0.0;
  double alpha_sum = 0.0;
  double l1_norm = 0.0;
  double l2_norm = 0.0;

	while (is->getline (buf, 8192)) {
	  	if (buf[strlen(buf) - 1] == '\r') {
	  		buf[strlen(buf) - 1] = '\0';
	  	}

	  	//cout << "\nline:" << no_cr_line;
      	//cout.flush();
    	if (2 != tokenize (buf, "\t ", column, 2)) {
	 		std::cerr << "FATAL: Format Error: " << buf << std::endl;
	 		return -1;
      	}
    	// Ignore rules containing only 1 character.
    	//if (strlen(column[1]) <= 1) continue;

		double a = atof (column[0]);
    	bias -= a;
    	alpha_sum += std::abs (a);
    	rules[column[1]] += 2 * a;
  	}

  bias /= alpha_sum;
  //bias = 0;
 l1_norm = alpha_sum;

  for (std::map<std::string, double>::iterator it = rules.begin(); it != rules.end(); ++it) {
    double a = it->second / alpha_sum;
    l2_norm += 	pow(it->second, 2);

    ary2.push_back (std::make_pair <const char*, double>(it->first.c_str(), a));
    ary.push_back  ((Darts::DoubleArray::key_type *)it->first.c_str());
    alpha.push_back (a);
  }

  l2_norm = pow(l2_norm, 0.5);

  std::cout << "Total: " << alpha.size() << " rule(s)" << std::endl;
  std::cout << "l1_norm: " << l1_norm << ", l2_norm: " << l2_norm << std::endl;

  if (ary.empty()) {
    std::cerr << "FATAL: no feature is added" << std::endl;
    return -1;
  }

  if (file != "-") delete is;

  Darts::DoubleArray da;

  if (da.build (ary.size(), &ary[0], 0, 0, 0) != 0) {
    std::cerr << "Error: cannot build double array  " << file << std::endl;
    return -1;
  }

  std::ofstream ofs (index.c_str(), std::ios::binary|std::ios::out);

  if (!ofs) {
    std::cerr << "Error: cannot open " << index << std::endl;
    return -1;
  }

  unsigned int s = da.size() * da.unit_size();
  ofs.write ((char *)&s, sizeof (unsigned));
  ofs.write ((char *)da.array (), s);
  ofs.write ((char *)&bias, sizeof (double));
  ofs.write ((char *)&alpha[0], sizeof (double) * alpha.size());
  ofs.close ();

  if (! ary2.empty() && ! ofile.empty()) {
    std::ofstream ofs2 (ofile.c_str());
    if (! ofs2) {
       std::cerr << "Cannot Open: " << ofile << std::endl;
       return -1;
    }
    ofs2.precision (24);
    ofs2 << bias << std::endl;
    std::sort (ary2.begin(), ary2.end(), pair_2nd_cmp <const char*, double>());
    for (unsigned int i = 0; i < ary2.size (); ++i) ofs2 << ary2[i].second << " " << ary2[i].first << std::endl;
  }

  return 0;
}
//--------------------------------------------------------------
void testApp::setup(){
	
	EmoEngineEventHandle eEvent			= EE_EmoEngineEventCreate();
	EmoStateHandle eState				= EE_EmoStateCreate();
	unsigned int userID					= 0;
	const unsigned short composerPort	= 1726;
	float secs							= 1;
	unsigned int datarate				= 0;
	bool readytocollect					= false;
	int option							= 0;
	int state							= 0;


	std::string input;

	try {

		//if (argc != 2) {
			//throw std::exception("Please supply the log file name.\nUsage: EEGLogger [log_file_name].");
		//}

		std::cout << "===================================================================" << std::endl;
		std::cout << "Example to show how to log EEG Data and Affectiv Data from EmoEngine/EmoComposer."	   << std::endl;
		std::cout << "===================================================================" << std::endl;
		std::cout << "Press '1' to start and connect to the EmoEngine                    " << std::endl;
		std::cout << "Press '2' to connect to the EmoComposer                            " << std::endl;
		std::cout << ">> ";

		std::getline(std::cin, input, '\n');
		option = atoi(input.c_str());

		switch (option) {
			case 1:
			{
				if (EE_EngineConnect() != EDK_OK) {
					throw std::exception("Emotiv Engine start up failed.");
				}
				break;
			}
			case 2:
			{
				std::cout << "Target IP of EmoComposer? [127.0.0.1] ";
				std::getline(std::cin, input, '\n');

				if (input.empty()) {
					input = std::string("127.0.0.1");
				}

				if (EE_EngineRemoteConnect(input.c_str(), composerPort) != EDK_OK) {
					std::string errMsg = "Cannot connect to EmoComposer on [" + input + "]";
					throw std::exception(errMsg.c_str());
				}
				break;
			}
			default:
				throw std::exception("Invalid option...");
				break;
		}
		
		
		std::cout << "Start receiving EEG Data and affectiv data! Press any key to stop logging...\n" << std::endl;
    	std::ofstream ofs("../bin/EEG_Data.csv",std::ios::trunc);
		ofs << header << std::endl;
		std::ofstream ofs2("../bin/Affectiv_Data.csv",std::ios::trunc);
		ofs2 << affectivSuitesName << std::endl;
		
		DataHandle hData = EE_DataCreate();
		EE_DataSetBufferSizeInSec(secs);

		std::cout << "Buffer size in secs:" << secs << std::endl;

		while (!_kbhit()) {

			state = EE_EngineGetNextEvent(eEvent);
			EE_Event_t eventType;

			if (state == EDK_OK) {

				eventType = EE_EmoEngineEventGetType(eEvent);
				EE_EmoEngineEventGetUserId(eEvent, &userID);
				EE_EmoEngineEventGetEmoState(eEvent, eState);

				// Log the EmoState if it has been updated
				if (eventType == EE_UserAdded) {
					std::cout << "User added";
					EE_DataAcquisitionEnable(userID,true);
					readytocollect = true;
				}
			

			if (readytocollect && (eventType == EE_EmoStateUpdated)) {
												
						EE_DataUpdateHandle(0, hData);

						unsigned int nSamplesTaken=0;
						EE_DataGetNumberOfSample(hData,&nSamplesTaken);
		
						std::cout << "Updated " << nSamplesTaken << std::endl;
						

						if (nSamplesTaken != 0  ) {

							double* data = new double[nSamplesTaken];
							for (int sampleIdx=0 ; sampleIdx<(int)nSamplesTaken ; ++ sampleIdx) {
								for (int i = 0 ; i<sizeof(targetChannelList)/sizeof(EE_DataChannel_t) ; i++) {

									EE_DataGet(hData, targetChannelList[i], data, nSamplesTaken);
									ofs << data[sampleIdx] << ",";
								}	
								ofs << std::endl;
							}
							delete[] data;							
						}
						
						float affEngegement = ES_AffectivGetEngagementBoredomScore(eState);
						float affFrus = ES_AffectivGetFrustrationScore(eState);
						float affMed = ES_AffectivGetMeditationScore(eState);
						float affExcitement = ES_AffectivGetExcitementShortTermScore(eState);
						printf("Engagement: %f, Frustration: %f, ...\n",affEngegement,affFrus);
						ofs2 <<affEngegement<<","<<	affFrus<<","<<affMed<<","<<affExcitement<<","<<std::endl;

			}
			}
			Sleep(100);
		}

		ofs.close();
		ofs2.close();
		EE_DataFree(hData);

	}
	catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		std::cout << "Press any key to exit..." << std::endl;
		getchar();
	}
	
}
Esempio n. 17
0
array_8d<double> Nevpt2_npdm::compute_EEEE_matrix(array_2d<double>& onepdm, array_4d<double>& twopdm, array_6d<double>& threepdm, array_8d<double>& fourpdm)
{
if( mpigetrank() == 0 ) {

  std::cout << "Building spatial <0|EEEE|0>\n";

  int dim = threepdm.dim1(); 
  assert( onepdm.dim1() == twopdm.dim1() );
  array_8d<double> eeee_matrix(dim,dim,dim,dim,dim,dim,dim,dim);
  eeee_matrix.Clear();

  // Output text file
  double factor = 1.0;
  char file[5000];
  sprintf (file, "%s%s%d.%d%s", dmrginp.save_prefix().c_str(),"/EEEE_matrix.", 0, 0,".txt");
  ofstream ofs(file);
  ofs << dim << endl;

  for(int i=0; i<dim; ++i) {
    for(int j=0; j<dim; ++j) {

      for(int k=0; k<dim; ++k) {
        int d_jk = ( j == k );
        for(int l=0; l<dim; ++l) {
          for(int m=0; m<dim; ++m) {
            int d_lm = ( l == m );
            int d_jm = ( j == m );
            for(int n=0; n<dim; ++n) {
              for(int p=0; p<dim; ++p) {
                int d_np = ( n == p );
                int d_lp = ( l == p );
                int d_jp = ( j == p );
                for(int q=0; q<dim; ++q) {

                  double val = 0.0;
                  // 1PDM terms
                  val += d_jk * d_lm * d_np * onepdm(i,q);
                  // 2PDM terms 
                  val += d_jk * d_lm * 2.0*twopdm(i,p,q,n); // Note factor of two difference between Block 2PDMs and other codes
                  val += d_jk * d_np * 2.0*twopdm(i,m,q,l);
                  val += d_jk * d_lp * 2.0*twopdm(i,m,n,q);
                  val += d_jm * d_np * 2.0*twopdm(i,k,l,q);
                  val += d_jm * d_lp * 2.0*twopdm(i,k,q,n);
                  val += d_lm * d_np * 2.0*twopdm(i,k,q,j);
                  val += d_lm * d_jp * 2.0*twopdm(i,k,n,q);
                  // 3PDM terms
                  val += d_jk * threepdm(i,m,p,q,n,l);
                  val += d_jm * threepdm(i,k,p,q,l,n);
                  val += d_lm * threepdm(i,k,p,q,n,j);
                  val += d_np * threepdm(i,k,m,q,l,j);
                  val += d_lp * threepdm(i,k,m,n,q,j);
                  val += d_jp * threepdm(i,k,m,n,l,q);
                  // 4PDM terms
                  val += fourpdm(i,k,m,p,j,l,n,q);

                  if ( abs(val) > 1e-14 ) {
                    ofs << boost::format("%d %d %d %d %d %d %d %d %20.14e\n") % i % j % k % l % m % n % p % q % val;
                    eeee_matrix(i,j,k,l,m,n,p,q) = val;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  ofs.close();

  // Save binary matrix
  sprintf (file, "%s%s%d.%d%s", dmrginp.save_prefix().c_str(),"/EEEE_matrix.", 0, 0,".bin");
  std::ofstream ofs2(file, std::ios::binary);
  boost::archive::binary_oarchive save(ofs2);
  save << eeee_matrix;
  ofs2.close();

  return eeee_matrix;

}
}
Esempio n. 18
0
int main() {
  ColoredGraph<GraphVertex,TriColor> gr;
  set<GraphVertex,less<GraphVertex> > groupsall, filesall,functionsall;
  set<GraphVertex,less<GraphVertex> > groupssome, filessome,functionssome,S;
  set<GraphVertex,less<GraphVertex> > groupsnot, filesnot,functionsnot;
  ifstream ifs1("groups.txt");
  ifstream ifs2("files.txt");
  ifstream ifs3("files.txt");
  ifstream ifs4("choices.txt");
  cerr << "reading groups";
  readDoubleColumnGraph(ifs1,groupsall,gr,true);
  cerr << ", files";
  readDoubleColumnGraph(ifs2,filesall,gr,true);
  cerr << ", functions\n";
  readDoubleColumnGraph(ifs3,functionsall,gr,false);
  readSingleColumn(ifs4,gr);
#if 1
  ifstream ifs5("depends.txt");
  list<list<string> > dbllist;
  readMultiColumns(ifs5,dbllist);
#endif
  bool todo  = true;
  while(todo) {
    todo = false;
    gr.ColorChildComponents(TriColor::s_one,TriColor::s_two);
    list<GraphVertex> L(gr.getColored(TriColor::s_two));
    copy(L.begin(),L.end(),inserter(S,S.begin()));
#if 1
    todo = addElements(gr,TriColor::s_one,S,dbllist);
    cerr << "addelements give " << todo << '\n';
#endif
  };
  cerr << "Here is the set after the loop:\n";
  printset(cerr,S,",");
  set_intersection(S.begin(),S.end(),groupsall.begin(),groupsall.end(),
                   inserter(groupssome,groupssome.begin()));
  set_intersection(S.begin(),S.end(),filesall.begin(),filesall.end(),
                   inserter(filessome,filessome.begin()));
  set_intersection(functionsall.begin(),functionsall.end(),S.begin(),S.end(),
                   inserter(functionssome,functionssome.begin()));
  set_difference(groupsall.begin(),groupsall.end(),S.begin(),S.end(),
                   inserter(groupsnot,groupsnot.begin()));
  set_difference(filesall.begin(),filesall.end(),S.begin(),S.end(),
                   inserter(filesnot,filesnot.begin()));
  set_difference(functionsall.begin(),functionsall.end(),S.begin(),S.end(),
                   inserter(functionsnot,functionsnot.begin()));
  cerr << "all groups:\n";
  printset(cerr,groupsall,", ");
  cerr << "\nall files:\n";
  printset(cerr,filesall,", ");
  cerr << "\nall functions:\n";
  printset(cerr,functionsall,", ");
  cerr << "\n\n\n";
  cerr << "groups (not):\n";
  printset(cerr,groupsnot,", ");
  cerr << "\nfiles (not):\n";
  printset(cerr,filesnot,", ");
  cerr << "\nfunctions(not):\n";
  printset(cerr,functionsnot,", ");
  cerr << "\n\n\n";
  cerr << "groups:\n";
  printset(cerr,groupssome,", ");
  cerr << "\nfiles:\n";
  printset(cerr,filessome,", ");
  cerr << "\nfunctions:\n";
  printset(cerr,functionssome,", ");

  cerr << "Staring creation of the file Makefile.mark\n";
  ofstream ofs("Makefile.mark");
  ofs << "p9clist = ";
  printset(ofs,filessome,".o \\\n",".o \n");
  ofs.close();
  cerr << "Ended creation of the file Makefile.mark\n";

  cerr << "Staring creation of the file Makefile.cp\n";
  ofstream ofs2("Makefile.cp");
  ofs2 << "cp ";
  printset(ofs2,filessome,".[hc]pp copyplace/ \n cp ",".[hc]pp copyplace/ \n");
  ofs2.close();
  cerr << "Ended creation of the file Makefile.cp\n";
};
Esempio n. 19
0
int cond::TestGTPerf::execute(){

  std::string gtag = getOptionValue<std::string>("globaltag");
  bool debug = hasDebug();
  std::string connect = getOptionValue<std::string>("connect");
  bool verbose = hasOptionValue("verbose");

  int nThrF = getOptionValue<int>("n_fetch");
  int nThrD = getOptionValue<int>("n_deser");
  std::cout << "\n++> going to use " << nThrF << " threads for loading, " << nThrD << " threads for deserialization. \n" << std::endl;

  std::string serType = "unknown";
  if ( connect.find("CMS_CONDITIONS") != -1 ) {
    serType = "ROOT-5";
  } else if (connect.find("CMS_TEST_CONDITIONS") != -1 ) {
    serType = "boost";
  }

  Time_t startRun= 150005;
  if(hasOptionValue("start_run")) startRun = getOptionValue<Time_t>("start_run");
  Time_t startTs= 5800013687234232320;
  if(hasOptionValue("start_ts")) startTs = getOptionValue<Time_t>("start_ts");
  Time_t startLumi= 908900979179966;
  if(hasOptionValue("start_lumi")) startLumi = getOptionValue<Time_t>("start_lumi");

  std::string authPath("");
  if( hasOptionValue("authPath")) authPath = getOptionValue<std::string>("authPath");

  initializePluginManager();

  Timer timex(serType);

  ConnectionPoolWrapper connPool( 1, authPath, hasDebug() );
  Session session = connPool.createSession( connect );
  session.transaction().start();
  
  std::cout <<"Loading Global Tag "<<gtag<<std::endl;
  GTProxy gt = session.readGlobalTag( gtag );

  session.transaction().commit();

  std::cout <<"Loading "<<gt.size()<<" tags..."<<std::endl;
  std::vector<UntypedPayloadProxy *> proxies;
  std::map<std::string,size_t> requests;
  size_t nt = 0;
  for( auto t: gt ){
    nt++;
    UntypedPayloadProxy * p = new UntypedPayloadProxy;
    p->init( session );
    try{
      p->load( t.tagName() );
      if (nThrF == 1) { // detailed info only needed in single-threaded mode to get the types/names
	p->setRecordInfo( t.recordName(), t.recordLabel() );
      }
      proxies.push_back( p );
      requests.insert( std::make_pair( t.tagName(), 0 ) );
    } catch ( const cond::Exception& e ){
      std::cout <<"ERROR: "<<e.what()<<std::endl;
    }
  }
  std::cout << proxies.size() << " tags successfully loaded." << std::endl;
  timex.interval("loading iovs");
  
  Time_t run = startRun;
  Time_t lumi = startLumi;
  Time_t ts = startTs;

  if (nThrF > 1) session.transaction().commit();

  tbb::task_scheduler_init init( nThrF );
  std::vector<std::shared_ptr<FetchWorker> > tasks;

  std::string payloadTypeName;
  for( auto p: proxies ){
      payloadTypeName = p->payloadType();
      // ignore problematic ones for now
      if ( (payloadTypeName == "SiPixelGainCalibrationOffline")  // 2 * 133 MB !!!
	   ) { 
	std::cout << "WARNING: Ignoring problematic payload of type " << payloadTypeName << std::endl;
	continue;
      }

      if (nThrF > 1) {
        auto fw = std::make_shared<FetchWorker>(connPool, connect, p, (std::map<std::string,size_t> *) &requests,
							    run, lumi, ts);
	tasks.push_back(fw);
      } else {
	bool loaded = false;
	time::TimeType ttype = p->timeType();
	auto r = requests.find( p->tag() );
	try{
	  if( ttype==runnumber ){
	    p->get( run, hasDebug() );	
	    r->second++;
	  } else if( ttype==lumiid ){
	    p->get( lumi, hasDebug() );
	    r->second++;
	  } else if( ttype==timestamp){
	    p->get( ts, hasDebug() );
	    r->second++;
	  } else {
	    std::cout <<"WARNING: iov request on tag "<<p->tag()<<" (timeType="<<time::timeTypeName(p->timeType())<<") has been skipped."<<std::endl;
	  }
	  timex.fetchInt(p->getBufferSize()); // keep track of time vs. size
	} catch ( const cond::Exception& e ){
	  std::cout <<"ERROR:"<<e.what()<<std::endl;
	}
      } // end else (single thread)
  }

  tbb::parallel_for_each(tasks.begin(),tasks.end(),invoker<std::shared_ptr<FetchWorker> >() );

  std::cout << "global counter : " << fooGlobal << std::endl;

  if (nThrF == 1) session.transaction().commit();
  // session.transaction().commit();

  timex.interval("loading payloads");

  size_t totBufSize = 0;
  for( auto p: proxies ){
      totBufSize += p->getBufferSize();
  }
  std::cout << "++> total buffer size used : " << totBufSize << std::endl;

  std::vector<std::shared_ptr<void> > payloads;
  payloads.resize(400); //-todo: check we don't have more payloads than that !!

  std::shared_ptr<void> payloadPtr;

  tbb::task_scheduler_init initD( nThrD );
  std::vector<std::shared_ptr<DeserialWorker> > tasksD;

  timex.interval("setup deserialization");

  int nEmpty = 0;
  int nBig = 0;
  int index = 0;
  for( auto p: proxies ){

///     if ( p->getBufferSize() == 0 ) { // nothing to do for these ... 
///       std::cout << "empty buffer found for " << p->payloadType() << std::endl;
///       nEmpty++;
///       continue;
///     }

    payloadTypeName = p->payloadType();

    // ignore problematic ones for now
    if ( (payloadTypeName == "SiPixelGainCalibrationForHLT")
	 or (payloadTypeName == "SiPixelGainCalibrationOffline")  // 2 * 133 MB !!!
	 or (payloadTypeName == "DTKeyedConfig") 
	 or (payloadTypeName == "std::vector<unsigned long long>") 
	 or (payloadTypeName == "  AlignmentSurfaceDeformations")
	 // only in root for now:
	 or (payloadTypeName == "PhysicsTools::Calibration::MVAComputerContainer")
	 or (payloadTypeName == "PhysicsTools::Calibration::MVAComputerContainer")
	 or (payloadTypeName == "PhysicsTools::Calibration::MVAComputerContainer")
	 or (payloadTypeName == "PhysicsTools::Calibration::MVAComputerContainer")
	 ) { 
      std::cout << "INFO: Ignoring payload of type " << payloadTypeName << std::endl;
      continue;
    }
    
    if (nThrD > 1) {
      auto dw = std::make_shared<DeserialWorker>(p, payloads[index]);
      tasksD.push_back(dw); 
    } else { // single tread only
       try {
	 std::pair<std::string, std::shared_ptr<void> > result = fetchOne( payloadTypeName, p->getBuffer(), p->getStreamerInfo(), payloadPtr);
           payloads.push_back(result.second);
       } catch ( const cond::Exception& e ){
           std::cout << "\nERROR (cond): " << e.what() << std::endl;
           std::cout << "for payload type name: " << payloadTypeName << std::endl;
       } catch ( const std::exception& e ){
           std::cout << "\nERROR (boost/std): " << e.what() << std::endl;
           std::cout << "for payload type name: " << payloadTypeName << std::endl;
       }
       timex.deserInt(p->getBufferSize()); // keep track of time vs. size
    } // single-thread
    index++; // increment index into payloads
  }
  std::cout << std::endl;

  tbb::parallel_for_each(tasksD.begin(),tasksD.end(),invoker<std::shared_ptr<DeserialWorker> >() );
 
  timex.interval("deserializing payloads");

  std::cout << "global counter : " << fooGlobal << std::endl;
  std::cout << "found   " << nEmpty << " empty payloads while deserialising " << std::endl;

  std::cout <<std::endl;
  std::cout <<"*** End of job."<<std::endl;
  std::cout <<"*** GT: "<<gtag<<" Tags:"<<gt.size()<<" Loaded:"<<proxies.size()<<std::endl;
  std::cout<<std::endl;
  for( auto p: proxies ){
    auto r = requests.find( p->tag() );
    if( verbose ){
      std::cout <<"*** Tag: "<<p->tag()<<" Requests processed:"<<r->second<<" Queries:"<< p->numberOfQueries() <<std::endl;
      const std::vector<std::string>& hist = p->history();
      for( auto e: p->history() ) std::cout <<"    "<<e<<std::endl;
    }
  }

  // only for igprof checking of live mem:
  // ::exit(0);

  timex.interval("postprocessing ... ");
  timex.showIntervals();
  
  if ( nThrF == 1) {
    std::ofstream ofs("fetchInfo.txt");
    timex.showFetchInfo(ofs);
    std::ofstream ofs2("sizeInfo.txt");
    for ( auto p: proxies ) {
      ofs2 << p->payloadType() << "[" << p->recName() << ":" << p->recLabel() << "]" << " : " << p->getBufferSize() << std::endl;
    }
  }
  if ( nThrD == 1) {
    std::ofstream ofs1("deserializeInfo.txt");
    timex.showDeserInfo(ofs1);
  }
  
  return 0;
}