Exemplo n.º 1
0
unique_ptr<const BaseContainer> RawWriter::doRead(InputFileInfo in, const Context& context) const
{
	ifstream	indata(in.filepath);
	unique_ptr<StreamBufferContainer> ret(new StreamBufferContainer(&indata, false, in.size));
	StreamCopy(indata, ret->buffer.WritableData(in.size));
    return std::move(ret);
}
Exemplo n.º 2
0
int main(int argc, char *argv[]){
  
    int c;
    CommandLineParser clp(argv[1],',');   //instantiating the class CommandLineParser
    string line;

    if (argc ==1)  {
        cout << "One argument must be passed." << endl ;
        return -1;
    }
    //use CommandLineParser to get the script name
    char *fileA = clp.extract("script");

cout << "script file is: " << fileA << endl;

    //use ScriptParser to get the commands from script file
    ScriptParser SParser =  ScriptParser();
    ifstream indata(fileA);
    
     while(getline( indata, line ) ) {
        cout<<line << endl;
         SParser.ParseLine(line);
          cout<< SParser.cmd.listID<< " " <<SParser.cmd.value1<< "-"<< SParser.cmd.value2<<" Op.Code:";
          switch (SParser.operationCode())
          {
          case 1:
             
              cout << SParser.operationCode()<<endl;
               // Call your function to insert here
              break;
          case 2:
              
              cout << SParser.operationCode()<<endl;
               // Call your function to delete here
              break;
          case 3:
             
             cout << SParser.operationCode()<<endl;
               // Call your function to insert here
              break;
          case 4:
             cout << SParser.operationCode()<<endl;
             // Call your function to fwr write here
              break;
          case 5:
              cout << SParser.operationCode()<<endl;
             // Call your function to rev write here
              break;
           case 0:
              cout << SParser.operationCode()<<" ERROR "<<endl;
              break;
          }
 
    }
  
  cout << "end of parsing" <<endl;

  return  0;
}
board_turn agent_neural_statistical::doTurn ( board b, int player ) {

	/*

		This will be called when the agents needs to make a move.

		You are provided with
			-the board b: This is the current board state.
			-the int player: This is the player number of this agent on the board b.

		All your tiles on the board will have the contents of the int player.

		for all your tiles t, t.getContents ( ) = player.

		You cannot add on more arguments for this function.

	*/

	cout << "Player #" << player << "s turn, neural statistical agent.\n";

	b.print ( );

	auto originalBoard = b;
	int nRotations = b.rotateForPerspective ( player );

	board_turn t;

	vector < board_turn > possibleTurns = b.findAllPossibleTurns ( player );

	board_turn bestTurn = possibleTurns [ 0 ];
	double bestScore = 0;

	for ( size_t i = 0; i < possibleTurns.size ( ); ++ i ) {

		board b2 = b;
		b2.makeTurn ( possibleTurns [ i ] );

		vector < double > indata ( 121, 0 );
		for ( size_t i = 0; i < indata.size ( ); ++ i ) indata [ i ] = lib::intToIndata ( b.intToTile ( i ) -> getContents ( ), player );

		double score = nn.run ( indata ) [ 0 ];

		if ( bestScore < score ) {

			bestTurn = possibleTurns [ i ];
			bestScore = score;

		}

	}

	bestTurn.rotate ( 6 - nRotations );

	return bestTurn;

}
Exemplo n.º 4
0
void InterfaceConfig::_readConfigFile(const QString& fileName){
	QFile* p_file = new QFile(fileName);
	if(!p_file->open(QIODevice::ReadOnly | QIODevice::Text)){
		D::Print("Cannot open file: " + fileName);
		return;
	}
	QTextStream indata(p_file);
	while(!indata.atEnd()){
		QString line =indata.readLine();
		ButtonItemParameter* p_bip = this->_parseParameter(line);
		this->_nameList.append(p_bip->Name());
		this->_itemList->append(p_bip);
	}
	p_file->close();
	delete p_file;
}
Exemplo n.º 5
0
int runSimulation(int numdets, PreCalDet** dets, int numhiatus, double* hdata,
                  int sections, double a, double b, double minyr, double maxyr,
                  double th0, double thp0, double c0, double cm,
                  char* outfile, int numsamples) {

    FuncInput indata(numdets, dets, numhiatus, hdata, sections, a, b,
                     minyr, maxyr, th0, thp0, c0, cm);
    
    int it = ACCEP_EV * indata.Dim() * EVERY_MULT * (numsamples + BURN_IN_MULT);
    int every = -1 * EVERY_MULT * indata.Dim(); // this is how many iterations are saved to file.
    
    //Run the twalk
    indata.RunTwalk(outfile, it, every, (char*)"w+", 0);
    indata.PrintNumWarnings();
    
    return indata.Dim() * EVERY_MULT * BURN_IN_MULT;
}
void read_corpus(std::vector< std::vector<std::string> > &corpus, std::string filename)
{
  std::string temp;
  std::ifstream indata((char *) filename.c_str());
  if (!indata) {
    std::cerr << "Corpus file could not be opened" << std::endl;
    exit(1);
  }
  while(getline(indata, temp)) {
    std::vector<std::string> line;
    line.push_back("DOT");
    boost::tokenizer<> tok(temp);
    for(boost::tokenizer<>::iterator it = tok.begin();
	it != tok.end(); ++it) {
      line.push_back(*it);
    }
    line.push_back("DOT");
    corpus.push_back(line);
  }
  indata.close();
}
Exemplo n.º 7
0
int main(int argc, char *argv[])
{
    ofstream log; // to record log file
    log.open("log.txt", std::fstream::app);
    int i = 0;
    int n;
    CommandLineParser clp(argv[1],',');   //instantiating the class CommandLineParser
    string line; // store each line in script file
    string listID = "";
    WordList L1; // list class

    if (argc == 1) 
    {
        log << "Error: no argument is passed." << endl;
        log.close();
        return -1;
    }

    //use CommandLineParser to get the script name
    char *script = clp.extract("script");
    if (script == NULL)
    {
        log << "Error: no script file specified." << endl;
        log.close();
        return -1;
    }

    //use ScriptParser to get the commands from script file
    ScriptParser SParser =  ScriptParser();
    ifstream indata(script);
    if (!indata.is_open()) // check if script file is correctly opened.
    {
        log << "Error: Script file \'" << script << "\' cannot be opened or does not exist." << endl;
        log.close();
        return -1;
    }
    
    log << "Begin parsing:\n" << endl;
    while(getline(indata, line))
    {
        log << line << '\n';
        SParser.ParseLine(line);

// we need to use "map" container to map different 'listID' to corresponding 'list', here, we suppose only one list will be used (the first created one), the other 'listID' which are different from the first one will be invalid.

/*        if (SParser.operationCode() == 3 && i == 0) // this is the first time create listID
        { 
            listID = SParser.cmd.listID;
        }
        else if (listID == "") // this is the time when list is not created yet
        {
            log << "Error: invalid operation, because list \'" << SParser.cmd.listID << "\' is not created yet, program is terminated.\n\n" << "End of parsing.\n" << endl;
            return -1;
        }
        else if (listID != SParser.cmd.listID) // if we want to create or visit more list other than the first, omit this operation
        {
            log << "Error: only one list \'" << listID << "\' is permitted, \'" << SParser.cmd.listID << "\' is not or cannot be created, program is terminated.\n\n" << "End of parsing.\n" <<endl;
            return -1;
        } */

        // do all the list operations, such as read, insert, delete, write.
        switch (SParser.operationCode())
        {
        case 1:
            n = L1.insert(SParser.cmd.value2, SParser.cmd.value1);
            if (n == -1) { 
                log << "Warning: in insertion, " << '\'' << SParser.cmd.value1 << '\'' << " cannot be found, so insertion fails.\n";
            }
            else {
                log << '\'' << SParser.cmd.value2 << '\'' << " has been inserted after the first appeared word " << '\'' << SParser.cmd.value1 << "\'.\n";
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 2:
            n = L1.erase(SParser.cmd.value1);
	    if (n == 0) log << "Waring: ";
            log << n << " word(s) " << '\'' << SParser.cmd.value1 << '\'' << " have been deleted.\n";
            log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 3:
            ++i;
            n = L1.read(SParser.cmd.value1);
            if (n == 0) {
                log << "Input file \'" << SParser.cmd.value1 << "\' is successfully read into list.\n";
            }
            else {
                log << "Error: fail to open input file \'" << SParser.cmd.value1 << "\', program is terminated.\n" << endl;
		log << "End of parsing.\n" << endl;
		return -1;
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 4:
            n = L1.output_forward(SParser.cmd.value1);
            if (n == 0) {
                log << "List is successfully written to file " << '\'' << SParser.cmd.value1 << '\'' << " in forward order.\n";
            }
            else {
                log << "Error: fail to create output file " << SParser.cmd.value1 << ".\n";
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 5:
            n = L1.output_backward(SParser.cmd.value1);
            if (n == 0) {
                log << "List is successfully written to file " << '\'' << SParser.cmd.value1 << '\'' << " in reverse order.\n";
            }
            else {
                log << "Error: fail to create output file " << SParser.cmd.value1 << ".\n";
            }
                log << "Number of bytes used by list is: " << L1.listSize() << ".\n" << endl;
            break;
        case 0:
            cout << SParser.cmd.listID << endl;
            cout << "Error: above line is not a valid script form.\n" << endl;
            log << "Error: above line is not a valid script form.\n" << endl;
            break;
        } 
    }
  
  log << "End of parsing.\n" <<endl;
  log.close();
  return 0;
}
Exemplo n.º 8
0
int main(int argc, char* argv[]) {

/*mainは整数を格納する配列の宣言、ソートモジュールのエントリポイント格納、*/
/*整列法の選択処理、整列法選択に対するエラー処理、各関数の呼び出しを行う。*/

  int index = 0;					/*indataで入力された整数の個数を保持*/
  int num;						/*整列法の選択に使う*/
  void (*sel[SORT_METHODS]) (int ,int ,long*, int*);	/*ソート関数のエントリポイントを格納するvoid型配列*/
  char line[10];					/*整列法を対話処理で決定する場合、コンソールで入力された文字列を格納する*/
  char sort_name[SORT_METHODS][20];		/*結果出力後に処理した整列法を表示するため、整列法の名称を格納しておく*/
  long ar[MAX_INDEX];				/*入力した整数群を格納する配列*/
  int ar_len[MAX_INDEX];			/*arに格納する整数の文字数を記録する配列*/

/*整列法の名称を配列sort_nameに格納*/
  strcpy(sort_name[0],"bubble sort");
  strcpy(sort_name[1],"quick sort");

/*sel[0]にbubble_sort、sel[1]にquick_sortのエントリポイントを格納*/
  sel[0] = bubble_sort;
  sel[1] = quick_sort;

/*先にファイルからの読み込みを済ませておく*/
  indata(ar, ar_len, &index);

/*整列法を決定する処理*/
/*引数があった場合*/
  if(argc > 1) {
    num = atoi(*++argv);			/*引数をargvからとって来てatoiしてnumに格納*/
    if(num >= 0 && num <= SORT_METHODS-1)	/*引数が0か1なら、ソート実行*/
      (*sel[num])(0, index, ar, ar_len);
    else {					/*引数が0か1以外なら、プログラムを終了*/
      printf("0から%dまでの値を入力してください。",SORT_METHODS-1);
      exit(0);
    }
  }
/*引数がなかった場合の対話処理*/
  else {
    printf("10000個程度の整数を整列します。整列法を選択してください。\n");
    while(1) {
      printf("0:bubble sort\n");
      printf("1:quick sort\n");
      num = atoi(fgets(line, sizeof(line), stdin));	/*fgetsで入力した結果をatoiしてnumに格納*/
      if(num >= 0 && num <= SORT_METHODS-1) {		/*入力が0か1なら、ソートを実行してループ脱出*/
        (*sel[num])(0, index, ar, ar_len);
        break;
      }
/*入力が0か1以外なら、エラーメッセージを出して、再入力させる*/
      else {
        printf("0から%dまでの値を入力してください。\n",SORT_METHODS-1);
        continue;
      }
    }
  }

/*整列終了後、outdataを呼んで結果を端末に出力*/
  outdata(ar, ar_len, index);
/*選択した整列法を出力して、終了。*/
  printf("%sで整列されました。\n",sort_name[num]);

  return 0;
}
Exemplo n.º 9
0
int vec2elemental(const std::vector<double> &vec, El::DistMatrix<El::Complex<double>,El::VC,El::STAR> &Y){

	int data_dof=2;
	int SCAL_EXP = 1;

	int nlocal,gsize; //local elements, start p_id, global size
	double *pt_array; // will hold local array
	int r,q,rq; //Grid sizes
	int nbigs; //Number of large sends (i.e. send 1 extra data point)
	int pstart; // p_id of nstart
	int rank = El::mpi::WorldRank(); //p_id
	int send_size; // base send size
	bool print = rank == -1; 


	// Get Grid and associated params
	const El::Grid* g = &(Y.Grid());
	r = g->Height();
	q = g->Width();
	MPI_Comm comm = (g->Comm()).comm;

	// Get sizes, array in petsc 
	nlocal = vec.size()/data_dof;
	int nstart = 0;
	MPI_Exscan(&nlocal,&nstart,1,MPI_INT,MPI_SUM,comm);
	//VecGetOwnershipRange(pt_vec,&nstart,NULL);

	//Find processor that nstart belongs to, number of larger sends
	rq = r * q;
	pstart = nstart % rq; //int div
	nbigs = nlocal % rq;
	send_size = nlocal/rq;
	
	if(print){
		std::cout << "r: " << r << " q: " << q <<std::endl;
		std::cout << "nstart: " << nstart << std::endl;
		std::cout << "ps: " << pstart << std::endl;
		std::cout << "nbigs: " << nbigs << std::endl;
		std::cout << "send_size: " << send_size << std::endl;
	}

	// Make send_lengths
	std::vector<int> send_lengths(rq);
	std::fill(send_lengths.begin(),send_lengths.end(),send_size);
	if(nbigs >0){
		for(int j=0;j<nbigs;j++){
			send_lengths[(pstart + j) % rq] += 1;
		}
	}

	// Make send_disps
	std::vector<int> send_disps = exscan(send_lengths);

	std::vector<El::Complex<double>> indata(nlocal);
	// copy the data from an ffm tree to into a local vec of complex data for sending #pragma omp parallel for
	El::Complex<double> val;
	for(int i=0;i<nlocal;i++){
		El::SetRealPart(val,vec[2*i+0]);
		El::SetImagPart(val,vec[2*i+1]);
		indata[i] = val;
	}


	// Make send_dataA, i.e. reorder the data
	std::vector<El::Complex<double>> send_data(nlocal);
	for(int proc=0;proc<rq;proc++){
		int offset = send_disps[proc];
		int base_idx = (proc - pstart + rq) % rq; 
		for(int j=0; j<send_lengths[proc]; j++){
			int idx = base_idx + (j * rq);
			send_data[offset + j] = indata[idx];
		}
	}

	// Do all2all to get recv_lengths
	std::vector<int> recv_lengths(rq);
	MPI_Alltoall(&send_lengths[0], 1, MPI_INT, &recv_lengths[0], 1, MPI_INT,comm);

	// Scan to get recv_disps
	std::vector<int> recv_disps = exscan(recv_lengths);

	// Do all2allv to get data on correct processor
	El::Complex<double> * recv_data = Y.Buffer();
	//MPI_Alltoallv(&send_data[0],&send_lengths[0],&send_disps[0],MPI_DOUBLE, \
	//		&recv_data[0],&recv_lengths[0],&recv_disps[0],MPI_DOUBLE,comm);
	El::mpi::AllToAll(&send_data[0], &send_lengths[0], &send_disps[0], recv_data,&recv_lengths[0],&recv_disps[0],comm);

	if(print){
		std::cout << "Send data: " <<std::endl << send_data <<std::endl;
		std::cout << "Send lengths: " <<std::endl << send_lengths <<std::endl;
		std::cout << "Send disps: " <<std::endl << send_disps <<std::endl;
		std::cout << "Recv data: " <<std::endl << recv_data <<std::endl;
		std::cout << "Recv lengths: " <<std::endl << recv_lengths <<std::endl;
		std::cout << "Recv disps: " <<std::endl << recv_disps <<std::endl;
	}

	return 0;
}
Exemplo n.º 10
0
int tree2elemental(InvMedTree<FMM_Mat_t> *tree, El::DistMatrix<T,El::VC,El::STAR> &Y){

	int data_dof=2;
	int SCAL_EXP = 1;

	int nlocal,gsize; //local elements, start p_id, global size
	double *pt_array; // will hold local array
	int r,q,rq; //Grid sizes
	int nbigs; //Number of large sends (i.e. send 1 extra data point)
	int pstart; // p_id of nstart
	int rank = El::mpi::WorldRank(); //p_id
	int send_size; // base send size
	bool print = rank == -1; 


	// Get Grid and associated params
	const El::Grid* g = &(Y.Grid());
	r = g->Height();
	q = g->Width();
	MPI_Comm comm = (g->Comm()).comm;

	std::vector<FMMNode_t*> nlist = tree->GetNGLNodes();

	int cheb_deg = InvMedTree<FMM_Mat_t>::cheb_deg;
	int omp_p=omp_get_max_threads();
	size_t n_coeff3=(cheb_deg+1)*(cheb_deg+2)*(cheb_deg+3)/6;

	// Get sizes, array in petsc 
	//VecGetSize(pt_vec,&gsize);
	gsize = tree->M/data_dof;
	nlocal = tree->m/data_dof;
	//VecGetLocalSize(pt_vec,&nlocal);
	//VecGetArray(pt_vec,&pt_array);
	int nstart = 0;
	MPI_Exscan(&nlocal,&nstart,1,MPI_INT,MPI_SUM,comm);
	//VecGetOwnershipRange(pt_vec,&nstart,NULL);

	//Find processor that nstart belongs to, number of larger sends
	rq = r * q;
	pstart = nstart % rq; //int div
	nbigs = nlocal % rq;
	send_size = nlocal/rq;
	
	if(print){
		std::cout << "r: " << r << " q: " << q <<std::endl;
		std::cout << "nstart: " << nstart << std::endl;
		std::cout << "ps: " << pstart << std::endl;
		std::cout << "nbigs: " << nbigs << std::endl;
		std::cout << "send_size: " << send_size << std::endl;
	}

	// Make send_lengths
	std::vector<int> send_lengths(rq);
	std::fill(send_lengths.begin(),send_lengths.end(),send_size);
	if(nbigs >0){
		for(int j=0;j<nbigs;j++){
			send_lengths[(pstart + j) % rq] += 1;
		}
	}

	// Make send_disps
	std::vector<int> send_disps = exscan(send_lengths);

	std::vector<El::Complex<double>> indata(nlocal);
	// copy the data from an ffm tree to into a local vec of complex data for sending #pragma omp parallel for
	for(size_t tid=0;tid<omp_p;tid++){
		size_t i_start=(nlist.size()* tid   )/omp_p;
		size_t i_end  =(nlist.size()*(tid+1))/omp_p;
		for(size_t i=i_start;i<i_end;i++){
			pvfmm::Vector<double>& coeff_vec=nlist[i]->ChebData();
			double s=std::pow(0.5,COORD_DIM*nlist[i]->Depth()*0.5*SCAL_EXP);

			size_t offset=i*n_coeff3;
			for(size_t j=0;j<n_coeff3;j++){
				double real = coeff_vec[j]*s; // local indices as in the pvfmm trees
				double imag = coeff_vec[j+n_coeff3]*s;
				El::Complex<double> coeff;
				El::SetRealPart(coeff,real);
				El::SetImagPart(coeff,imag);

				indata[offset+j] = coeff;
			}
		}
	}


	// Make send_data
	std::vector<El::Complex<double>> send_data(nlocal);
	for(int proc=0;proc<rq;proc++){
		int offset = send_disps[proc];
		int base_idx = (proc - pstart + rq) % rq; 
		for(int j=0; j<send_lengths[proc]; j++){
			int idx = base_idx + (j * rq);
			send_data[offset + j] = indata[idx];
		}
	}

	// Do all2all to get recv_lengths
	std::vector<int> recv_lengths(rq);
	MPI_Alltoall(&send_lengths[0], 1, MPI_INT, &recv_lengths[0], 1, MPI_INT,comm);

	// Scan to get recv_disps
	std::vector<int> recv_disps = exscan(recv_lengths);

	// Do all2allv to get data on correct processor
	El::Complex<double> * recv_data = Y.Buffer();
	//MPI_Alltoallv(&send_data[0],&send_lengths[0],&send_disps[0],MPI_DOUBLE, \
	//		&recv_data[0],&recv_lengths[0],&recv_disps[0],MPI_DOUBLE,comm);
	El::mpi::AllToAll(&send_data[0], &send_lengths[0], &send_disps[0], recv_data,&recv_lengths[0],&recv_disps[0],comm);

	if(print){
		std::cout << "Send data: " <<std::endl << send_data <<std::endl;
		std::cout << "Send lengths: " <<std::endl << send_lengths <<std::endl;
		std::cout << "Send disps: " <<std::endl << send_disps <<std::endl;
		std::cout << "Recv data: " <<std::endl << recv_data <<std::endl;
		std::cout << "Recv lengths: " <<std::endl << recv_lengths <<std::endl;
		std::cout << "Recv disps: " <<std::endl << recv_disps <<std::endl;
	}

	return 0;
}
Exemplo n.º 11
0
bool Instance::Load(string filename) {
    string dummyStr;

    ifstream indata(filename.c_str(), fstream::in);

	if (indata) {

		Instance::mName = filename;

		// NUMBER OF BASIS: basis
		int basis = 0;
		indata >> dummyStr >> dummyStr >> dummyStr >> basis;

		// NUMBER OF SITES: sites
		int sites = 0;
		indata >> dummyStr >> dummyStr >> dummyStr >> sites;

		// BUDGET: mBudget
		indata >> dummyStr >> dummyStr;

		// Alloca lo spazio per le strutture
		Instance::mVehicles->reserve(2);

		Instance::mClientsX->reserve(basis + sites);
		Instance::mClientsY->reserve(basis + sites);

		int id;
		Coord x, y;
		Profit profit;
		Cost cost;
		Distance d;
		for (int v=0; v<2; ++v) {
			indata >> id >> d;
			Instance::mVehicles->push_back(d);
		}
		for (int b=0; b<basis; ++b) {
			indata >> id >> x >> y;
			Instance::mClientsX->push_back(x);
			Instance::mClientsY->push_back(y);
		}
		for (int s=0; s<sites; ++s) {
			indata >> id >> x >> y; // >> profit >> cost;
			Instance::mClientsX->push_back(x);
			Instance::mClientsY->push_back(y);
		}

		// Costruisce la matrice delle distanze
		int locations = basis + sites;
		Instance::mDistances->reserve(locations);
		for (int i=0; i<locations; ++i) {
			Instance::mDistances->push_back(new DistanceVector(locations, 0));
		}

		// Calcola le distanze tra i clienti
		for (int i=0; i<locations; ++i) {
			for (int j=0; j<locations; ++j) {
				Distance xi, xj, yi, yj;
				xi = (Distance)Instance::mClientsX->at(i);
				yi = (Distance)Instance::mClientsY->at(i);
				xj = (Distance)Instance::mClientsX->at(j);
				yj = (Distance)Instance::mClientsY->at(j);
				Distance xx = ( (xi - xj) * (xi - xj) );
				Distance yy = ( (yi - yj) * (yi - yj) );
				Distance d = sqrt(xx + yy);
				Instance::mDistances->at(i)->at(j) = d;
			}
		}

		indata.close();

		return true;
	}
	return false;
}