Ejemplo n.º 1
0
// --------------------------------------------------------
// ---------- RecreateDB ----------------------------------
// --------------------------------------------------------
void MIViewBrowser::RecreateDB()
{
	wxArrayString files;
	wxFile outfile("browsedb.txt",wxFile::write);
	int fileCount;
	int i,j,k,m;
	int numStudies, numSeries, numFiles;
	wxArrayInt offs, lens;
	wxFile dicomfile;
	wxString str, msg;
	wxString patName, patDOB, studyDate, studyTime, seriesNum;
	wxString patientAndDOB, studyDateTimeStr, sliceNum;
	wxString studyName, seriesName, fileName;
	
	if (chkScanRecursively->GetValue())
		wxDir::GetAllFiles(txtScanDir->GetValue(),&files,"",wxDIR_DEFAULT);
	else
		wxDir::GetAllFiles(txtScanDir->GetValue(),&files,"",wxDIR_FILES);
	fileCount = (int)files.Count();

	/* setup the progress dialog */
	wxProgressDialog progDlg(wxT("Creating database..."), wxT(" "), fileCount, this, wxPD_SMOOTH | wxPD_ELAPSED_TIME | wxPD_CAN_ABORT);

	for (i=0;i<fileCount;i++) {
		wxFileName fn(files[i]);
		if ( (fn.GetExt() == "dcm") || (fn.GetExt() == "acr") || (fn.GetExt() == "") ) {
			if (!progDlg.Update(i,msg.Format("Reading file %d of %d",i,fileCount)))
				break;

			gdcm::ImageReader reader;
			/* see if the file will open */
			reader.SetFileName(files[i].c_str());
			if (reader.Read()) {
				gdcm::DataSet dataSet;
				const gdcm::File &file = reader.GetFile();
				dataSet = file.GetDataSet();

				gdcm::Attribute<0x0010,0x0010> at; /* patient name */
				if (dataSet.FindDataElement( at.GetTag() )) {
					const gdcm::DataElement &de = dataSet.GetDataElement( at.GetTag() );
					at.SetFromDataElement( de );
					patName = at.GetValue().c_str();
					patName.Replace("^",",");
				} else { patName = "";}

				gdcm::Attribute<0x0010,0x0030> at1; /* patient birthdate */
				if (dataSet.FindDataElement( at1.GetTag() )) {
					const gdcm::DataElement &de1 = dataSet.GetDataElement( at1.GetTag() );
					at1.SetFromDataElement( de1 );
					patDOB = at1.GetValue().c_str();
				} else { patDOB = "";}

				gdcm::Attribute<0x0008,0x0020> at2; /* study date */
				if (dataSet.FindDataElement( at2.GetTag() )) {
					const gdcm::DataElement &de2 = dataSet.GetDataElement( at2.GetTag() );
					at2.SetFromDataElement( de2 );
					studyDate = at2.GetValue().c_str();
				} else { studyDate = "";}

				gdcm::Attribute<0x0008,0x0030> at3; /* study time */
				if (dataSet.FindDataElement( at3.GetTag() )) {
					const gdcm::DataElement &de3 = dataSet.GetDataElement( at3.GetTag() );
					at3.SetFromDataElement( de3 );
					studyTime = at3.GetValue().c_str();
				} else { studyTime = "";}

				gdcm::Attribute<0x0020,0x0011> at4; /* series number */
				if (dataSet.FindDataElement( at4.GetTag() )) {
					const gdcm::DataElement &de4 = dataSet.GetDataElement( at4.GetTag() );
					at4.SetFromDataElement( de4 );
					seriesNum = wxString::Format("%d",at4.GetValue());
				} else { seriesNum = "";}

				gdcm::Attribute<0x0020,0x0011> at5; /* series number */
				if (dataSet.FindDataElement( at5.GetTag() )) {
					const gdcm::DataElement &de5 = dataSet.GetDataElement( at5.GetTag() );
					at5.SetFromDataElement( de5 );
					sliceNum = wxString::Format("%d",at5.GetValue());
				} else { sliceNum = "";}
				patientAndDOB = patName + "&" + patDOB;
				studyDateTimeStr = studyDate + "&" + studyTime;
				browsedb[patientAndDOB][studyDateTimeStr][seriesNum][files[i]].slicenum = atoi(sliceNum.c_str());
			}
		}
	}

	/* write out the database file */
	for (i=0;i<browsedb.GetNumPatients();i++) {
		patName = browsedb[i].patientName;
		numStudies = browsedb[i].GetNumStudies();
		str = patName + "\n";
		outfile.Write(str);
		for (j=0;j<numStudies;j++) {
			studyName = browsedb[i][j].studyName;
			numSeries = browsedb[i][j].GetNumSeries();
			str = "\t" + studyName + "\n";
			outfile.Write(str);
			for (k=0;k<numSeries;k++) {
				seriesName = browsedb[i][j][k].seriesName;
				numFiles = browsedb[i][j][k].GetNumFiles();
				str = "\t\t" + seriesName + "\n";
				outfile.Write(str);
				for (m=0;m<numFiles;m++) {
					fileName = browsedb[i][j][k][m].fileName;
					str = "\t\t\t" + fileName + "\n";
					outfile.Write(str);
				}
			}
		}
	}
}
Ejemplo n.º 2
0
int main()
{
	srand((unsigned)time(NULL));
	string graph_address="graph_all.txt";

	VGraph gv(graph_address);//Voting用的图
	PGraph gp(graph_address);//LP用的图
	VGraph gv_flow(graph_address); //Flow Voting用的图
	vector<Voter*> flowL;//记录所有的流实例
	vector<Voter*> voterL;//记录所有的投票者
	vector<Voter*> candiL;//记录所有的候选者
	int voting_choice=1;

	//收集每一轮投票的结果
	vector<double> app_happiness, voting_happiness, network_happiness;
	vector<double> app_delay, voting_delay, network_delay;
	vector<double> app_te, voting_te, network_te;
	vector<double> app_load, voting_load, network_load;

	//记录当前时间
	time_t tt = time(NULL);//这句返回的只是一个时间cuo
 	tm* t= localtime(&tt);

	string s="result";
	stringstream ss1;
	ss1<<t->tm_year+1900;
	s.append(ss1.str());

	stringstream ss2;
	ss2<<t->tm_mon+1;
	s.append(ss2.str());
 	
 	stringstream ss3;
	ss3<<t->tm_mday;
	s.append(ss3.str());
	
	stringstream ss4;
	ss4<<t->tm_hour;
	s.append(ss4.str());
	
	stringstream ss5;
	ss5<<t->tm_min;
	s.append(ss5.str());
	s.append(".txt");

	cout<<"current output file : "<<s<<endl;

	ofstream outfile(s);//最后一个case的结果
	ofstream req_outfile("req_outfile.txt");
	outfile<<graph_address<<"网络拓扑 caseN: "<<caseN<<endl;
	outfile<<"flow Range: "<<Begin_num<<"--"<<Maxflow+Begin_num-1<<endl<<endl;
	outfile<<"current output file : "<<s<<endl;

	vector<Req*> reqL;
	double table[M2C+1][N2C+1] = {0};
	int ranking[N2C+1]={0};//记录一种排序的投票人数
	double happiness_sum=0;
	
	for(int j=1;j<=Voternum;j++)
		ranking[j]=1;//每种投票结果有1个voter,如果为2就说明该方案有得到两个voter的票

	Voter* net_lb = new Network_LB(Maxreq,1);// Maxreq是投票者id, 1 表示网络投票者
	ranking[Voternum]=5;//给网络投票者更多的票数

	//Maxreq+1是投票者id,2表示中立投票者
	Voter* neutral_low = new Neutral(Maxreq+1, 2);  // te = 胜者TE基础上+5%
	Voter* neutral_middle = new Neutral(Maxreq+2, 2);  // te = 胜者TE基础上+10%
	Voter* neutral_high = new Neutral(Maxreq+3, 2); // te = 胜者TE基础上+20%

	//初次 修改neutral的te值
	neutral_low->te = 0.3;
	neutral_middle->te = 0.4;
	neutral_high->te = 0.5;

	//******** Flow Voting Variables *******
	vector<Voter*> flowL_flow;//记录Flow Voting所有的流实例
	vector<Voter*> voterL_flow;//记录Flow Voting所有的投票者
	vector<Voter*> candiL_flow;//记录Flow Voting所有的候选者
	double table_flow[M2C+1][N2C+1] = {0};
	int ranking_flow[N2C+1]={0};//记录一种排序的投票人数
	double happiness_sum_flow=0;
	for(int j=1;j<=Maxreq;j++)
		ranking_flow[j]=1;//每种投票结果有1个voter,如果为2就说明该方案有得到两个voter的票



	for(int i=0;i<caseN;i++)
	{
		cout<<endl<<"*************************"<<" case "<<i<<"*************************"<<endl;
		outfile<<endl<<"*************************"<<" case "<<i<<"*************************"<<endl;
		//初始化
		for(int j=0;j<Voternum;j++)
			for(int k=0;k<Voternum+3;k++)
			{
				table[j][k]=0;
				table_flow[j][k]=0;//table_flow的有效数据范围是table的子集
			}
		req_outfile<<"case "<<i<<endl;

		
		//以下程序时防止每个case都会创建的Req导致的内存泄露
		vector<Req*>::iterator it,iend;
		iend=reqL.end();
		for(it=reqL.begin();it!=iend;it++)	
			delete(*it);
		
		//删除上一个case的流需求
		reqL.clear();
		gv.reqL.clear();
		gv_flow.reqL.clear();

		if(i==0){
			for(int j=0;j<Maxreq;j++)
			{
				int a=0,b=0,c=0;
				while(1){
					c = Begin_num + rand()%Maxflow;
					//if(c!=0) break;
					a = rand()%N;
					b = rand()%N;
					if(a!=b && c!=0) break;
				}
				//a=0;b=1;c=10;
				Req* r = new Req(j,a,b,c);
				reqL.push_back(r);
				gv.reqL.push_back(r);
				gv_flow.reqL.push_back(r);
				Voter* flow_now = new Flow(j,0,a,b,c);
				Voter* flow_now_flow =  new Flow(j,0,a,b,c);//Flow Voting use
				flowL.push_back(flow_now);
				voterL.push_back(flow_now);
				candiL.push_back(flow_now);
				flowL_flow.push_back(flow_now_flow);
				voterL_flow.push_back(flow_now_flow);
				candiL_flow.push_back(flow_now_flow);
				req_outfile<<j<<" "<<a<<" "<<b<<" "<<c<<endl;
			}
			voterL.push_back(net_lb);
			
			candiL.push_back(net_lb);
			candiL.push_back(neutral_low);
			candiL.push_back(neutral_middle);
			candiL.push_back(neutral_high);
		}
		else{
			for(int j=0;j<Maxreq;j++)
			{
				int a=0,b=0,c=0;
				while(1){
					c = Begin_num + rand()%Maxflow;
					//if(c!=0) break;
					a = rand()%N;
					b = rand()%N;
					if(a!=b && c!=0) break;
				}
				//a=0;b=1;c=10;
				Req* r = new Req(j,a,b,c);
				reqL.push_back(r);
				gv.reqL.push_back(r);
				gv_flow.reqL.push_back(r);
				flowL[j]->modify(a,b,c);
				//candiL[j]->modify(a,b,c);
				flowL_flow[j]->modify(a,b,c);
				//candiL_flow[j]->modify(a,b,c);
				req_outfile<<j<<" "<<a<<" "<<b<<" "<<c<<endl;
			}
			net_lb->modify(0,0,0);
			neutral_low->modify(0,0,0);
			neutral_middle->modify(0,0,0);
			neutral_high->modify(0,0,0);
		}

		//cout<<"init completed"<<endl;
		
	

		//**************************************  Flow Voting  **************************************
		//**************************************  Flow Voting  **************************************
		//only flows' proposal can be voted for a winner
		
		//算最完美方案,所有的路都第一个走得到的方案
		for(int j=0;j<Maxreq;j++)
			gv_flow.cost_best[j] = gv.dijkstra(reqL[j]->src,reqL[j]->dst,reqL[j]->flow,flowL_flow[0]->adj);

		//for(int j=0;j<Maxreq;j++)
			//cout<<"gv.cost_best "<<j<<" : "<<gv.cost_best[j]<<endl;

		//提方案
		for(int j=0;j<candiL_flow.size();j++)
			candiL_flow[j]->propose(gv_flow);
		//cout<<"提出方案结束"<<endl;

		//评价方案
		for(int j=0;j<voterL_flow.size();j++)
			voterL_flow[j]->evaluate(gv_flow,candiL_flow);
		//cout<<"评价方案结束"<<endl;

		//投票算法, 投票算法的输入是从1开始的,但是judge是从0开始的,所以需要调整一下
		for(int j=0;j<voterL_flow.size();j++)
			for(int k=0;k<candiL_flow.size();k++)
			{
				//该操作在evaluate时候就惩罚----不用if(voterL[j]->judge[k]==0) table[j+1][k+1]=10000;//如果是0,说明流没有摆在网络中
				table_flow[j+1][k+1]=voterL_flow[j]->judge[k];
			}
		cout<<endl<<"voting uses ";
		int choice_flow=voting_choice;//选择一种投票算法
		int winner_flow=0;
		Voting vv_flow(table_flow,ranking_flow,voterL_flow.size(),candiL_flow.size());
		winner_flow=vv_flow.voting(choice_flow);
		winner_flow=winner_flow-1;//将结果还是按照从0开始编号

		if (choice_flow == 1)
			cout << "schulze method : " << winner_flow << endl;
		else if (choice_flow == 2)
			cout << "comulative method: " << winner_flow << endl;
		else if (choice_flow == 3)
			cout << "copeland condorcet method: " << winner_flow << endl;
		else
			cout << "ranked pairs method: " << winner_flow << endl;

		
		// table show
		for(int i=1;i<=voterL_flow.size();i++)
		{
			cout<<"flow ";
			cout.setf(ios::right);
			cout.width(3);
			cout<<i-1<<" judge: ";
			for(int j=1;j<=candiL_flow.size();j++){
				cout.setf(ios::left);
				cout.width(5);
				cout<<table_flow[i][j]<<" ";
			}
			cout<<endl;
		}
		cout<<endl;
		
		// file record of table show
		outfile<<endl;
		for(int i=1;i<=voterL_flow.size();i++)
		{
			outfile<<"flow ";
			outfile.setf(ios::right);
			outfile.width(3);
			outfile<<i-1<<" judge: ";
			for(int j=1;j<=candiL_flow.size();j++){
				outfile.setf(ios::left);
				outfile.width(5);
				outfile<<table_flow[i][j]<<" ";
			}
			outfile<<endl;
		}
		outfile<<endl;


		//计算满意度
		double happiness_flow=0;//一轮所有流的满意度和,越高越好,0<=满意度<=1
		for(int j=1;j<=Maxreq;j++)
			happiness_flow += gv_flow.cost_best[j-1]/table_flow[j][winner_flow+1];//最好抉择评分/当前抉择评分
		happiness_sum_flow += happiness_flow;
		
		//计算方案部署后当前总的cost,如果流没有被安排进网络,就增加惩罚cost
		
		//统计网络latency
		double latencyVoting_flow=0;
		latencyVoting_flow=judge_sum_function(gv_flow,candiL_flow,winner_flow);

		cout << "winner = "<<winner_flow<<endl;
		cout << "第" << i << "轮整体满意度: " << happiness_flow/Maxreq << endl;
		cout << "多轮满意度:" << happiness_sum_flow/ ((i+1)*Maxreq) << endl;
		cout << "多轮整体延时和: " << latencyVoting_flow << endl;

		double maxUtil_Voting_flow=0;
		double loadNUM_flow=0;//统计网络负载
		for(int j=0;j<gv_flow.m;j++)
		{
			int src=gv_flow.incL[j]->src;
			int dst=gv_flow.incL[j]->dst;
			loadNUM_flow+=flowL_flow[winner_flow]->adj[src][dst];
			double capacity=gv_flow.incL[j]->capacity;
			if(maxUtil_Voting_flow<(flowL_flow[winner_flow]->adj[src][dst]/capacity))
				maxUtil_Voting_flow=flowL_flow[winner_flow]->adj[src][dst]/capacity;
		}
		cout<<"最大链路利用率: "<<maxUtil_Voting_flow<<endl;

		//文件记录
		outfile<<"Case "<<i<<" Flow Voting Result"<<endl;
		outfile << "winner = "<<winner_flow<<endl;
		outfile << "第" << i << "轮整体满意度: " << happiness_flow/Maxreq << endl;
		outfile << "多轮满意度:" << happiness_sum_flow/ ((i+1)*Maxreq) << endl;
		outfile << "多轮整体延时和: " << latencyVoting_flow << endl;
		outfile <<"最大链路利用率: "<<maxUtil_Voting_flow<<endl;
		outfile <<"网络负载"<<loadNUM_flow<<endl;

		app_happiness.push_back(happiness_sum_flow/ ((i+1)*Maxreq));
		app_delay.push_back(latencyVoting_flow);
		app_te.push_back(maxUtil_Voting_flow);
		app_load.push_back(loadNUM_flow);

		//胜利的方案部署
		for(int j=0;j<candiL_flow.size();j++)
			candiL_flow[j]->end_implement(gv_flow,winner_flow,candiL_flow);

		cout<<endl;

		//**************************************   End of Flow Voting    **************************************
		//**************************************   End of Flow Voting    **************************************


		//@@@@@@@@@@@@@@@@  Voting  @@@@@@@@@@@@@@@@@@@@@@
		//@@@@@@@@@@@@@@@@  Voting  @@@@@@@@@@@@@@@@@@@@@@

		//算最完美方案,所有的路都第一个走得到的方案
		for(int j=0;j<Maxreq;j++)
			gv.cost_best[j] = gv.dijkstra(reqL[j]->src,reqL[j]->dst,reqL[j]->flow,flowL[0]->adj);

		//for(int j=0;j<Maxreq;j++)
			//cout<<"gv.cost_best "<<j<<" : "<<gv.cost_best[j]<<endl;

		//提方案
		for(int j=0;j<candiL.size();j++)
			candiL[j]->propose(gv);
		//cout<<"提出方案结束"<<endl;

		//评价方案
		for(int j=0;j<voterL.size();j++)
			voterL[j]->evaluate(gv,candiL);
		//cout<<"评价方案结束"<<endl;

		//投票算法, 投票算法的输入是从1开始的,但是judge是从0开始的,所以需要调整一下
		for(int j=0;j<voterL.size();j++)
			for(int k=0;k<candiL.size();k++)
			{
				//该操作在evaluate时候就惩罚----不用if(voterL[j]->judge[k]==0) table[j+1][k+1]=10000;//如果是0,说明流没有摆在网络中
				table[j+1][k+1]=voterL[j]->judge[k];
			}
		cout<<endl<<"voting uses ";
		int choice=voting_choice;//选择一种投票算法
		int winner=0;
		Voting vv(table,ranking,voterL.size(),candiL.size());
		winner=vv.voting(choice);
		winner=winner-1;//将结果还是按照从0开始编号

		outfile<<endl<<"beat_record: ";
		for(int i=1;i<=candiL.size();i++)
			outfile<<vv.beat_record[i]<<" ";
		outfile<<endl;

		if (choice == 1)
			cout << "schulze method : " << winner << endl;
		else if (choice == 2)
			cout << "comulative method: " << winner << endl;
		else if (choice == 3)
			cout << "copeland condorcet method: " << winner << endl;
		else
			cout << "ranked pairs method: " << winner << endl;

		
		// table show
		for(int i=1;i<=voterL.size();i++)
		{
			cout<<"flow ";
			cout.setf(ios::right);
			cout.width(3);
			cout<<i-1<<" judge: ";
			for(int j=1;j<=candiL.size();j++){
				cout.setf(ios::left);
				cout.width(5);
				cout<<table[i][j]<<" ";
			}
			cout<<endl;
		}
		cout<<endl;
		
		// file record of table show
		outfile<<endl;
		for(int i=1;i<=voterL.size();i++)
		{
			outfile<<"flow ";
			outfile.setf(ios::right);
			outfile.width(3);
			outfile<<i-1<<" judge: ";
			for(int j=1;j<=candiL.size();j++){
				outfile.setf(ios::left);
				outfile.width(5);
				outfile<<table[i][j]<<" ";
			}
			outfile<<endl;
		}
		outfile<<endl;


		//计算满意度
		double happiness=0;//一轮所有流的满意度和,越高越好,0<=满意度<=1
		for(int j=1;j<=Maxreq;j++)
			happiness += gv.cost_best[j-1]/table[j][winner+1];//最好抉择评分/当前抉择评分
		happiness_sum += happiness;

		//计算方案部署后当前总的cost,如果流没有被安排进网络,就增加惩罚cost
		
		//统计网络latency
		double latencyVoting=0;
		latencyVoting=judge_sum_function(gv,candiL,winner);

		cout << "winner = "<<winner<<endl;
		cout << "第" << i << "轮整体满意度: " << happiness/Maxreq << endl;
		cout << "多轮满意度:" << happiness_sum / ((i+1)*Maxreq) << endl;
		cout << "多轮整体延时和: " << latencyVoting << endl;

		double maxUtil_Voting=0;
		maxUtil_Voting=voterL[Maxreq]->judge[winner];
		cout<<"最大链路利用率: "<<maxUtil_Voting<<endl;

		double loadNUM_voting=0;
		for(int j=0;j<gv.m;j++)
		{
			int src=gv.incL[j]->src;
			int dst=gv.incL[j]->dst;
			loadNUM_voting+=candiL[winner]->adj[src][dst];
		}


		//文件记录
		outfile<<"Case "<<i<<" Voting Result"<<endl;
		outfile << "winner = "<<winner<<endl;
		outfile << "第" << i << "轮整体满意度: " << happiness/Maxreq << endl;
		outfile << "多轮满意度:" << happiness_sum / ((i+1)*Maxreq) << endl;
		outfile << "多轮整体延时和: " << latencyVoting << endl;
		outfile <<"最大链路利用率: "<<maxUtil_Voting<<endl;
		outfile <<"网络负载"<<loadNUM_voting<<endl;

		voting_happiness.push_back(happiness_sum / ((i+1)*Maxreq));
		voting_delay.push_back(latencyVoting);
		voting_te.push_back(maxUtil_Voting);
		voting_load.push_back(loadNUM_voting);

		//胜利的方案部署
		for(int j=0;j<candiL.size();j++)
			candiL[j]->end_implement(gv,winner,candiL);
		
		//修改neutral的te值
		neutral_low->te = maxUtil_Voting + 0.05;
		neutral_middle->te = maxUtil_Voting + 0.1;
		neutral_high->te = maxUtil_Voting + 0.2;

		cout<<endl;

		//@@@@@@@@@@@@@@@@@End of Voting@@@@@@@@@@@@@@@@@@@@@@@@@
		//@@@@@@@@@@@@@@@@@End of Voting@@@@@@@@@@@@@@@@@@@@@@@@@

		//分段规划部分
		cout<<endl<<"			LP result			"<<endl;
		
		//judge_LP记录单轮满意度总和,judge_sum_LP记录多轮满意度总和
		double judge_LP=0;
		static double judge_sum_LP=0;

		//最优部署计算
		for(int j=0;j<Maxreq;j++)
			gp.cost_best[j] =gp.dijkstra(reqL[j]->src,reqL[j]->dst,reqL[j]->flow);

		//线性规划部署
		double result_LP=0;//TE结果
		result_LP=LP(&gp,reqL);
		
		//计算满意度
		if(result_LP==Inf)judge_LP=0;
		else
		{
			judge_LP=0;
			//for(int i=0;i<Maxreq;i++)
				//cout<<gp.cost_best[i]<<" "<<gp.cost_LP[i]<<endl;
			for(int j=0;j<Maxreq;j++)
				judge_LP += gp.cost_best[j]/gp.cost_LP[j];
		}
		judge_sum_LP += judge_LP;
		cout<<"单轮满意度: "<<judge_LP/Maxreq<<endl;
		cout<<"多轮满意度: "<<judge_sum_LP/(Maxreq*(i+1))<<endl;

		double latency_LP=0;
		latency_LP=judge_sum_LP_function(gp);
		cout << "多轮整体延时和: " << latency_LP << endl;
		cout<<"最大链路利用率: "<<result_LP<<endl;
		
		double loadNUM_network=0;
		for(int j=0;j<gp.m;j++)
		{
			int src=gp.incL[j]->src;
			int dst=gp.incL[j]->dst;
			loadNUM_network+=gp.adj[src][dst];
		}

		//文件记录
		outfile<<"Case "<<i<<" LP Result"<<endl;
		outfile<<"单轮满意度: "<<judge_LP/Maxreq<<endl;
		outfile<<"多轮满意度: "<<judge_sum_LP/(Maxreq*(i+1))<<endl;
		outfile << "多轮整体延时和: " << latency_LP << endl;
		outfile<<"最大链路利用率: "<<result_LP<<endl;
		outfile <<"网络负载"<<loadNUM_network<<endl;

		network_happiness.push_back(judge_sum_LP/(Maxreq*(i+1)));
		network_delay.push_back(latency_LP);
		network_te.push_back(result_LP);
		network_load.push_back(loadNUM_network);

		/*
		cout<<"单轮最大剩余链路利用率: "<<result_LP<<endl;
		double maxUtil_LP=0;
		for(int j=0;j<gp.m;j++)
		{
			int src=gp.incL[j]->src;
			int dst=gp.incL[j]->dst;
			float capacity=gp.incL[j]->capacity;
			if(maxUtil_LP<(gp.adj[src][dst]/capacity))
				maxUtil_LP=gp.adj[src][dst]/capacity;
		}
		*/
		
		/*
		if(i==(caseN-1)){
			outfile << "LP result"<<endl;
			outfile<<"单轮满意度: "<<judge_LP/Maxreq<<endl;
			outfile<<"多轮满意度: "<<judge_sum_LP/(Maxreq*(i+1))<<endl;
			outfile<<"多轮整体代价和: "<<result_sum_LP<<endl;
		}
		*/
		

	}//一个case结束

	//happiness results: 三行结果分别是app voting network的满意度
	outfile<<endl;
	outfile<<"happiness results: app voting network"<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<app_happiness[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<voting_happiness[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<network_happiness[i]<<",";
	}

	//delay results 
	outfile<<endl;
	outfile<<"delay results: app voting network"<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<app_delay[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<voting_delay[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<network_delay[i]<<",";
	}

	//te results
	outfile<<endl;
	outfile<<"te results: app voting network"<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<app_te[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<voting_te[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<network_te[i]<<",";
	}
	outfile<<endl;

	//load results
	outfile<<endl;
	outfile<<"load results: app voting network"<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<app_load[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<voting_load[i]<<",";
	}
	outfile<<endl;
	for(int i=0;i<caseN;i++)
	{
		outfile<<network_load[i]<<",";
	}
	outfile<<endl;

	getchar();
	return 0;
}
Ejemplo n.º 3
0
/**
 * \brief Called by Windows automagically every time a key is pressed (regardless
 * of who has focus)
 */
__declspec(dllexport) LRESULT CALLBACK handlekeys(int code, WPARAM wp, LPARAM lp)
{
	if (code == HC_ACTION && (wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN)) {
		static bool capslock = false;
		static bool shift = false;
		char tmp[0xFF] = {0};
		std::string str;
		DWORD msg = 1;
		KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);
		bool printable;

		/*
		 * Get key name as string
		 */
		msg += (st_hook.scanCode << 16);
		msg += (st_hook.flags << 24);
		GetKeyNameText(msg, tmp, 0xFF);
		str = std::string(tmp);

		printable = (str.length() <= 1) ? true : false;

		/*
		 * Non-printable characters only:
		 * Some of these (namely; newline, space and tab) will be
		 * made into printable characters.
		 * Others are encapsulated in brackets ('[' and ']').
		 */
		if (!printable) {
			/*
			 * Keynames that change state are handled here.
			 */
			if (str == "CAPSLOCK")
				capslock = !capslock;
			else if (str == "SHIFT")
				shift = true;

			/*
			 * Keynames that may become printable characters are
			 * handled here.
			 */
			if (str == "ENTER") {
				str = "\n";
				printable = true;
			} else if (str == "SPACE") {
				str = " ";
				printable = true;
			} else if (str == "TAB") {
				str = "\t";
				printable = true;
			} else {
				str = ("[" + str + "]");
			}
		}

		/*
		 * Printable characters only:
		 * If shift is on and capslock is off or shift is off and
		 * capslock is on, make the character uppercase.
		 * If both are off or both are on, the character is lowercase
		 */
		if (printable) {
			if (shift == capslock) { /* Lowercase */
				for (size_t i = 0; i < str.length(); ++i)
					str[i] = tolower(str[i]);
			} else { /* Uppercase */
				for (size_t i = 0; i < str.length(); ++i) {
					if (str[i] >= 'A' && str[i] <= 'Z') {
						str[i] = toupper(str[i]);
					}
				}
			}

			shift = false;
		}

#ifdef DEBUG
		std::cout << str;
#endif
		std::string path = std::string(windir) + "\\" + OUTFILE_NAME;
		std::ofstream outfile(path.c_str(), std::ios_base::app);
		outfile << str;
		outfile.close();
	}

	return CallNextHookEx(kbdhook, code, wp, lp);
}
Ejemplo n.º 4
0
void WFileList::OnMenuFileExport(wxCommandEvent& WXUNUSED(event))
{
    if (GetSelectedItemCount() == 0)
    {
        return;
    }
    else if (GetSelectedItemCount() == 1)
    {
        long sfid = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);

        wxString suggestname = strSTL2WX(wmain->container.GetSubFileProperty(sfid, "Name"));

        wxFileDialog dlg(this,
                         _("Save SubFile"), wxEmptyString, suggestname,
                         _("Any file (*)|*"),
                         wxFD_SAVE | wxFD_OVERWRITE_PROMPT);

        if (dlg.ShowModal() != wxID_OK) return;

        wxFile outfile(dlg.GetPath(), wxFile::write);
        if (!outfile.IsOpened()) return;

        {
            wxFileOutputStream outstream(outfile);
            wmain->ExportSubFile(sfid, outstream);
        }

        wmain->UpdateStatusBar(wxString::Format(_("Wrote %u bytes from subfile \"%s\" to %s"),
                                                (unsigned int)(outfile.Tell()),
                                                suggestname.c_str(),
                                                dlg.GetPath().c_str()));
    }
    else
    {
        wxString dlgtitle = wxString::Format(_("Select directory to export %u files to."), GetSelectedItemCount());
        wxDirDialog dlg(this, dlgtitle, wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);

        if (dlg.ShowModal() != wxID_OK) return;

        int filesok = 0;

        long sfid = -1;
        while (1)
        {
            sfid = GetNextItem(sfid, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
            if (sfid == -1) break;

            wxString name = strSTL2WX(wmain->container.GetSubFileProperty(sfid, "Name"));

            wxFileName filename(dlg.GetPath(), name);

            if (filename.FileExists())
            {
                wxString overstr = wxString::Format(_("The export filename \"%s\" already exists.\nDo you wish to overwrite the existing file?"), filename.GetFullPath().c_str());

                wxMessageDialog overdlg(this, overstr, _("Overwrite existing file?"),
                                        wxYES_NO | wxNO_DEFAULT);

                if (overdlg.ShowModal() == wxID_NO) continue;
            }

            wxFile outfile(filename.GetFullPath(), wxFile::write);
            if (!outfile.IsOpened()) continue;

            {
                wxFileOutputStream outstream(outfile);
                wmain->ExportSubFile(sfid, outstream);
            }

            filesok++;
        }

        wmain->UpdateStatusBar(wxString::Format(wxPLURAL("Exported %u subfile to %s",
                                                         "Exported %u subfiles to %s", filesok),
                                                filesok, dlg.GetPath().c_str()));
    }
}
/**
 * argv[1] = path to training ply file
 * argv[2] = hypothesis id
 * argv[3] = path to omap save directory
 * argv[4] = vpx
 * argv[5] = vpy
 * argv[6] = vpz
 * argv[7] = vp_id
 */
int build_omap_main(int argc, char **argv)
{
    std::cout << "Starting oMap build process..." << std::endl;

    if(argc < 4)
        throw std::runtime_error("A directory to save the oMap_hyp.txt is required...\n");
    if(argc < 3)
        throw std::runtime_error("Hypothesis id is required as second argument...\n");
    if(argc < 2)
        throw std::runtime_error("A ply file is required as a first argument...\n");

    // Get directory paths and hypothesis id
    std::string ply_file_path( argv[1] );
    std::string hyp_id( argv[2] );
    std::string save_dir_path( argv[3] );
    std::string node_id("build_omap");
    std::string vision_module_path(ros::package::getPath("vision_module"));

    // Form the output filename
    std::stringstream omap_file_path;
    if(argc > 4) {
        omap_file_path << save_dir_path << "/oMap_" << hyp_id << "_" << argv[7] << ".txt";
        node_id.append( hyp_id + argv[7] );
    }
    else {
        omap_file_path << save_dir_path << "/oMap_" << hyp_id << ".txt";
        node_id.append( hyp_id );
    }
    std::ofstream outfile ( omap_file_path.str().c_str(), ofstream::app );

    if(!outfile.is_open())
        throw std::runtime_error("Unable to open omap save file...\n");

    // Import the sensor locations
    int num_vp;
    int dim_vp = 3;

    Eigen::MatrixXd vp_positions;

    if(argc > 4) {
        num_vp = 1;
        vp_positions.resize( num_vp, dim_vp );
        double vpx = std::atof(argv[4]);
        double vpy = std::atof(argv[5]);
        double vpz = std::atof(argv[6]);
        vp_positions << vpx, vpy, vpz;
    } else {
        std::string vp_file_path(vision_module_path + "/data/omap_vps.txt");
        io_utils::file2matrix( vp_file_path, vp_positions, dim_vp );
        num_vp = vp_positions.rows();
    }

    // Construct and initialize the virtual kinect
    int coord = 1;		// 0 = obj coord, 1 = optical sensor coord, 2 = standard sensor coord
    bool add_noise = false;
    vkin_offline vko( Eigen::Vector3d(0,0,0), Eigen::Vector4d(0,0,0,1),
                      coord, false, add_noise );
    vko.init_vkin( ply_file_path );
    Eigen::Vector3d target(0,0,0);

    // Construct and start a vocabulary tree
    vtree_user vt("/load", vision_module_path + "/data", vision_module_path + "/../data/cloud_data");
    vt.start();

    // noise
    boost::mt19937 rng(time(0));
    boost::normal_distribution<double> normal_distrib(0.0, 1.0);
    boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > gaussian_rng( rng, normal_distrib );


    double vp_noise_param = 0.01;	// standard deviation in position
    double tp_noise_param = 0.005;	// standard deviation in target
    double occ_dev = 0.005;	// occlussion cutoff threshold in the sensor frame

    int num_rep = 2;
    for(int vp = 0; vp < num_vp; ++vp)
    {
        // get a noiseless scan in the sensor frame
        //pcl::PointCloud<pcl::PointXYZ>::Ptr cld_ptr = vko.sense( vp_positions.row(vp).transpose(), target );

        for(int r = 0; r < num_rep; ++r)
        {
            // get cloud copy
            //pcl::PointCloud<pcl::PointXYZ>::Ptr noise_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>);
            //copyPointCloud( *cld_ptr, *noise_cloud_ptr );
            Eigen::Vector3d noise_vp;
            noise_vp.x() = vp_positions(vp,0) + vp_noise_param*gaussian_rng();
            noise_vp.y() = vp_positions(vp,1) + vp_noise_param*gaussian_rng();
            noise_vp.z() = vp_positions(vp,2) + vp_noise_param*gaussian_rng();

            Eigen::Vector3d noise_tp;
            noise_tp.x() = target.x() + tp_noise_param*gaussian_rng();
            noise_tp.y() = target.y() + tp_noise_param*gaussian_rng();
            noise_tp.z() = target.z() + tp_noise_param*gaussian_rng();

            pcl::PointCloud<pcl::PointXYZ>::Ptr cld_ptr = vko.sense( noise_vp, noise_tp );

            // get occluded pcds
            pcl::PointCloud<pcl::PointXYZ>::Ptr cld_ptr_1 (new pcl::PointCloud<pcl::PointXYZ>);
            pcl::PointCloud<pcl::PointXYZ>::Ptr l_cld_ptr (new pcl::PointCloud<pcl::PointXYZ>);
            pcl::PointCloud<pcl::PointXYZ>::Ptr r_cld_ptr (new pcl::PointCloud<pcl::PointXYZ>);
            pcl::PointCloud<pcl::PointXYZ>::Ptr t_cld_ptr (new pcl::PointCloud<pcl::PointXYZ>);
            pcl::PointCloud<pcl::PointXYZ>::Ptr b_cld_ptr (new pcl::PointCloud<pcl::PointXYZ>);
            pcl::PointCloud<pcl::PointXYZ>::Ptr lr_cld_ptr (new pcl::PointCloud<pcl::PointXYZ>);
            pcl::PointCloud<pcl::PointXYZ>::Ptr tb_cld_ptr (new pcl::PointCloud<pcl::PointXYZ>);

            pcl::copyPointCloud(*cld_ptr, *cld_ptr_1);
            pcl::copyPointCloud(*cld_ptr, *l_cld_ptr);
            pcl::copyPointCloud(*cld_ptr, *r_cld_ptr);
            pcl::copyPointCloud(*cld_ptr, *t_cld_ptr);
            pcl::copyPointCloud(*cld_ptr, *b_cld_ptr);
            pcl::copyPointCloud(*cld_ptr, *lr_cld_ptr);
            pcl::copyPointCloud(*cld_ptr, *tb_cld_ptr);

            // occlude the other two clouds too
            occlude_pcd(cld_ptr, 0, -3*occ_dev, 3*occ_dev);	// left-right
            occlude_pcd(cld_ptr_1, 1, -3*occ_dev, 3*occ_dev); // top-bottom

            occlude_pcd(l_cld_ptr, 0, -occ_dev, std::numeric_limits<double>::infinity());
            occlude_pcd(r_cld_ptr, 0, -std::numeric_limits<double>::infinity(), occ_dev);
            occlude_pcd(t_cld_ptr, 1, -occ_dev, std::numeric_limits<double>::infinity());
            occlude_pcd(b_cld_ptr, 1, -std::numeric_limits<double>::infinity(), occ_dev);
            occlude_pcd(lr_cld_ptr, 0, -2.5*occ_dev, 2.5*occ_dev);
            occlude_pcd(tb_cld_ptr, 1, -2.5*occ_dev, 2.5*occ_dev);

            //add noise
            addNoise( Eigen::Vector3d(0,0,0), cld_ptr, gaussian_rng );
            addNoise( Eigen::Vector3d(0,0,0), cld_ptr_1, gaussian_rng );
            addNoise( Eigen::Vector3d(0,0,0), l_cld_ptr, gaussian_rng );
            addNoise( Eigen::Vector3d(0,0,0), r_cld_ptr, gaussian_rng );
            addNoise( Eigen::Vector3d(0,0,0), t_cld_ptr, gaussian_rng );
            addNoise( Eigen::Vector3d(0,0,0), b_cld_ptr, gaussian_rng );
            addNoise( Eigen::Vector3d(0,0,0), lr_cld_ptr, gaussian_rng );
            addNoise( Eigen::Vector3d(0,0,0), tb_cld_ptr, gaussian_rng );

            /*
            //filter
            pcl::StatisticalOutlierRemoval<pcl::PointXYZ> stat;
            stat.setInputCloud( noise_cloud_ptr );
            stat.setMeanK(100);
            stat.setStddevMulThresh(1.0);
            stat.filter( *noise_cloud_ptr );
            */

            // Record scores
            std::pair<float,std::string> vp_score = vt.top_match( cld_ptr->getMatrixXfMap() );
            std::pair<float,std::string> vp_score_1 = vt.top_match( cld_ptr_1->getMatrixXfMap() );
            std::pair<float,std::string> vp_score_l = vt.top_match( l_cld_ptr->getMatrixXfMap() );
            std::pair<float,std::string> vp_score_r = vt.top_match( r_cld_ptr->getMatrixXfMap() );
            std::pair<float,std::string> vp_score_t = vt.top_match( t_cld_ptr->getMatrixXfMap() );
            std::pair<float,std::string> vp_score_b = vt.top_match( b_cld_ptr->getMatrixXfMap() );
            std::pair<float,std::string> vp_score_lr = vt.top_match( lr_cld_ptr->getMatrixXfMap() );
            std::pair<float,std::string> vp_score_tb = vt.top_match( tb_cld_ptr->getMatrixXfMap() );

            // append vp and vp_score to the file
            if(argc > 4)
            {
                outfile << argv[7] << " " << vp_score.second << " " << vp_score.first << std::endl;
                outfile << argv[7] << " " << vp_score_1.second << " " << vp_score_1.first << std::endl;
                outfile << argv[7] << " " << vp_score_l.second << " " << vp_score_l.first << std::endl;
                outfile << argv[7] << " " << vp_score_r.second << " " << vp_score_r.first << std::endl;
                outfile << argv[7] << " " << vp_score_t.second << " " << vp_score_t.first << std::endl;
                outfile << argv[7] << " " << vp_score_b.second << " " << vp_score_b.first << std::endl;
                outfile << argv[7] << " " << vp_score_lr.second << " " << vp_score_lr.first << std::endl;
                outfile << argv[7] << " " << vp_score_tb.second << " " << vp_score_tb.first << std::endl;
            }
            else
            {
                outfile << vp << " " << vp_score.second << " " << vp_score.first << std::endl;
                outfile << vp << " " << vp_score_1.second << " " << vp_score_1.first << std::endl;
                outfile << vp << " " << vp_score_l.second << " " << vp_score_l.first << std::endl;
                outfile << vp << " " << vp_score_r.second << " " << vp_score_r.first << std::endl;
                outfile << vp << " " << vp_score_t.second << " " << vp_score_t.first << std::endl;
                outfile << vp << " " << vp_score_b.second << " " << vp_score_b.first << std::endl;
                outfile << vp << " " << vp_score_lr.second << " " << vp_score_lr.first << std::endl;
                outfile << vp << " " << vp_score_tb.second << " " << vp_score_tb.first << std::endl;
            }

            /*
            // save clouds for inspection
            if((vp == 0) && (r == 0))
            {
            	pcl::PCDWriter writer;
            	std::string pcd_file_path ("/media/natanaso/Data/Stuff/Research/code_develop_area/cpp_test_pkg/data/l_occ1.pcd");
            	writer.writeASCII( pcd_file_path.c_str(), *l_cld_ptr );

            	pcd_file_path = "/media/natanaso/Data/Stuff/Research/code_develop_area/cpp_test_pkg/data/r_occ1.pcd";
            	writer.writeASCII( pcd_file_path.c_str(), *r_cld_ptr );

            	pcd_file_path = "/media/natanaso/Data/Stuff/Research/code_develop_area/cpp_test_pkg/data/t_occ1.pcd";
            	writer.writeASCII( pcd_file_path.c_str(), *t_cld_ptr );

            	pcd_file_path = "/media/natanaso/Data/Stuff/Research/code_develop_area/cpp_test_pkg/data/b_occ1.pcd";
            	writer.writeASCII( pcd_file_path.c_str(), *b_cld_ptr );

            	pcd_file_path = "/media/natanaso/Data/Stuff/Research/code_develop_area/cpp_test_pkg/data/lr_occ1.pcd";
            	writer.writeASCII( pcd_file_path.c_str(), *lr_cld_ptr );

            	pcd_file_path = "/media/natanaso/Data/Stuff/Research/code_develop_area/cpp_test_pkg/data/tb_occ1.pcd";
            	writer.writeASCII( pcd_file_path.c_str(), *tb_cld_ptr );

            	pcd_file_path = "/media/natanaso/Data/Stuff/Research/code_develop_area/cpp_test_pkg/data/orig1.pcd";
            	writer.writeASCII( pcd_file_path.c_str(), *cld_ptr );
            }
            */
        }
    }

    outfile.close();

    return 0;
}
Ejemplo n.º 6
0
bool
FtpClient::GetFile(const string& remote, const string& local, ftp_mode mode)
{
	bool rc = false;
	string cmd, replyString;
	int code, codeType, rlen, slen, i;
	BFile outfile(local.c_str(), B_READ_WRITE | B_CREATE_FILE);
	char buf[8192], sbuf[16384], *stmp;
	bool writeError = false;

	if (outfile.InitCheck() != B_NO_ERROR)
		return false;

	if (mode == binary_mode)
		cmd = "TYPE I";
	else
		cmd = "TYPE A";

	if (_SendRequest(cmd))
		_GetReply(replyString, code, codeType);

	if (_OpenDataConnection()) {
		cmd = "RETR ";
		cmd += remote;
		
		if (_SendRequest(cmd)) {
			if (_GetReply(replyString, code, codeType)) {
				if (codeType <= 2) {
					if (_AcceptDataConnection()) {
						rlen = 1;
						rc = true;
						while (rlen > 0) {
							memset(buf, 0, sizeof(buf));
							memset(sbuf, 0, sizeof(sbuf));
							rlen = fData->Receive(buf, sizeof(buf));
							
							if (rlen > 0) {

								slen = rlen;
								stmp = buf;
								if (mode == ascii_mode) {
									stmp = sbuf;
									slen = 0;
									for (i = 0; i < rlen; i++) {
										if (buf[i] == '\r')
											i++;
										*stmp = buf[i];
										stmp++;
										slen++;
									}
									stmp = sbuf;
								}

								if (slen > 0) {
									if (outfile.Write(stmp, slen) < 0)
										writeError = true;				
								}
							}
						}
					}
				}
			}
		}
	}

	delete fData;
	fData = 0;
	
	if (rc) {					
		_GetReply(replyString, code, codeType);
		rc = (codeType <= 2 && writeError == false);
	}
	return rc;
}
int main(int argc, char** argv)
{
	char *envstring = NULL;
	int iResult;
	string tempStr(REC_UNIT_INFO), tempStr1(REC_MODE);
	string path;
	string strShapeId;
    string strWordId;
	char infilelist[MAX_PATH];
	string outfile("wordrectst.out");
	vector<LTKTraceGroup> fieldInk;
	int charIndex;
	wstring eolstr(L"\r\n");
	int i;
    

	// first argument is the logical project name 
	// second argument is the ink file to recognize
	// third argument is the output file
	if(argc < 4)
	{
		cout << "\nUsage:";
		cout << "\nwordrectst <logical projectname> <list file to recognize> <outputfile>";
		cout << "\nlist of valid <logicalname>s is available in $LIPI_ROOT/projects/lipiengine.cfg file";
		cout << endl;
        delete utilPtr;
		return -1;
	}

	// Get the LIPI_ROOT environment variable 
	envstring = getenv(LIPIROOT_ENV_STRING);
	if(envstring == NULL)
	{
		cout << "\nError, Environment variable is not set LIPI_ROOT\n";
        delete utilPtr;
		return -1;
	}

	// Load the LipiEngine.DLL
	hLipiEngine = NULL;
	iResult = utilPtr->loadSharedLib(envstring, LIPIENGINE_MODULE_STR, &hLipiEngine);

	if(iResult != SUCCESS)
	{
		cout << "Error loading LipiEngine module" << endl;
        delete utilPtr;
		return -1;
	}

	if(MapFunctions() != 0)
	{
		cout << "Error fetching exported functions of the module" << endl;
        delete utilPtr;
		return -1;
	}

	// create an instance of LipiEngine Module
	ptrObj = createLTKLipiEngine();

	// set the LIPI_ROOT path in Lipiengine module instance
	ptrObj->setLipiRootPath(envstring);

	// Initialize the LipiEngine module
	iResult = ptrObj->initializeLipiEngine();
	if(iResult != SUCCESS)
	{
		cout << iResult << ": Error initializing LipiEngine.\n";
		utilPtr->unloadSharedLib(hLipiEngine);
        delete utilPtr;

		return -1;
	}

//	Assign the logical name of the project to this string, i.e. TAMIL_WORD
	string strLogicalName = string(argv[1]);

	strcpy(infilelist,  argv[2]);
	outfile = argv[3];

	LTKWordRecognizer *pWordReco = NULL;
	ptrObj->createWordRecognizer(strLogicalName,&pWordReco);
	if(pWordReco == NULL)
	{
		cout << "\nError creating Word Recognizer\n";
	
		utilPtr->unloadSharedLib(hLipiEngine);
        delete utilPtr;
		return -1;
	}

//	You can also use project and profile name to create LipiEngine instance as follows...
//	string strProjectName = "tamil_boxed_field";
//	string strProfileName = "default";
//	LTKWordRecognizer *pWordReco = ptrObj->createWordRecognizer(&strProjectName, &strProfileName);

	int iErrorCode = 0;
	LTKRecognitionContext *recoContext = new LTKRecognitionContext();

	if(iErrorCode != 0)
	{
		cout << "\nError creating recognition context.\n";
		ptrObj->deleteWordRecognizer(pWordReco);

        utilPtr->unloadSharedLib(hLipiEngine);
        delete utilPtr;
        
		return -1;
	}

	LTKCaptureDevice deviceContext;
	LTKScreenContext screenContext;
	int numChoices = 2;

	// Setting the device attributes
	deviceContext.setSamplingRate(120);	
	deviceContext.setXDPI(2500);
	deviceContext.setYDPI(2500);
	deviceContext.setUniformSampling(true);

	// Set the engine to recognizer
	recoContext->setWordRecoEngine(pWordReco);
	
	// set the device context
	recoContext->setDeviceContext(deviceContext);
	// set the screen context
	recoContext->setScreenContext(screenContext);

	recoContext->setFlag(tempStr,REC_UNIT_CHAR);
	recoContext->setFlag(tempStr1,REC_MODE_STREAMING);

	// set the number of choices required
	recoContext->setNumResults(numChoices);

	ifstream in(infilelist);
	if(in == NULL)
	{
		cout << "Test list file open error : " << infilelist << endl;
        delete utilPtr;
		return -1;
	}

	ofstream resultfile(outfile.c_str(),ios::out|ios::binary);

	//a Header of 0xFEFF is required to identify this is a
	//16 bit unicode file
	const unsigned short fHeader = 0xfeff;
	resultfile.write((char*)&fHeader,sizeof(unsigned short));

	while(in)
	{
		//Get the file name
		if(!getline(in,path,' ')) 
		{
			break;
		}
		
		//Get the word ID
		getline(in,strWordId);
		//iWordID = atoi(strShapeId.c_str());

		cout << path << endl;

		try
		{
			fieldInk.clear();
		
			//read the word file
			readWordFile(path, fieldInk, deviceContext, screenContext);
			
			for(charIndex = 0; charIndex < fieldInk.size(); ++charIndex)
			{
				recoContext->beginRecoUnit();
				recoContext->addTraceGroups(LTKTraceGroupVector(1,fieldInk.at(charIndex)));
				recoContext->endRecoUnit();

			}
		}
		catch(LTKException e)
		{
			LOG(LTKLogger::LTK_LOGLEVEL_ERR) << e.getExceptionMessage();
			return FAILURE;
		}

		//Calling recognize and retrieving the top result
		{
			LTKWordRecoResult result;
			vector<LTKWordRecoResult> r2;
			recoContext->recognize();
			recoContext->getTopResult(result);
			recoContext->getNextBestResults(numChoices-1, r2);

			vector<unsigned short> resultVec = result.getResultWord();

			if(!resultVec.empty())
			{
				resultfile.write((char *)&(resultVec.at(0)), resultVec.size()*sizeof(unsigned short));
				resultfile.write((char*)eolstr.c_str(),eolstr.length()*sizeof(unsigned short));

				for(i =0; i<r2.size(); ++i)
				{
					resultVec = r2.at(i).getResultWord();
					resultfile.write((char *)&(resultVec.at(0)), resultVec.size()*sizeof(unsigned short));
					resultfile.write((char*)eolstr.c_str(),eolstr.length()*sizeof(unsigned short));
				}
			}

			recoContext->clearRecognitionResult();
		}

	}

	resultfile.close();

	//delete word recognition instance
	if(pWordReco)
	{
		ptrObj->deleteWordRecognizer(pWordReco);
	}

	//delete recognition context object
	if(recoContext)
	{
		//ptrObj->deleteRecognitionContext(recoContext);
		delete recoContext;
	}

	

	//unload the LipiEngine module from memory...
	utilPtr->unloadSharedLib(hLipiEngine);
    delete utilPtr;

	return 0;
}
Ejemplo n.º 8
0
// Try to create a CM from the selected entity
void createCMFromSelection(const cmd::ArgumentList& args) {
	// Check the current selection state
	const SelectionInfo& info = GlobalSelectionSystem().getSelectionInfo();
	
	if (info.totalCount == info.entityCount && info.totalCount == 1) {
		// Retrieve the node, instance and entity
		const scene::INodePtr& entityNode = GlobalSelectionSystem().ultimateSelected();
		
		// Try to retrieve the group node
		scene::GroupNodePtr groupNode = Node_getGroupNode(entityNode);
		
		// Remove the entity origin from the brushes
		if (groupNode != NULL) {
			groupNode->removeOriginFromChildren();
			
			// Deselect the node
			Node_setSelected(entityNode, false);
			
			// Select all the child nodes
			NodeSelector visitor;
			entityNode->traverse(visitor);
			
			BrushPtrVector brushes = algorithm::getSelectedBrushes();
		
			// Create a new collisionmodel on the heap using a shared_ptr
			cmutil::CollisionModelPtr cm(new cmutil::CollisionModel());
		
			// Add all the brushes to the collision model
			for (std::size_t i = 0; i < brushes.size(); i++) {
				cm->addBrush(brushes[i]->getBrush());
			}
			
			ui::ModelSelectorResult modelAndSkin = ui::ModelSelector::chooseModel("", false, false);
			std::string basePath = GlobalGameManager().getModPath();
			
			std::string modelPath = basePath + modelAndSkin.model;
			
			std::string newExtension = "." + GlobalRegistry().get(RKEY_CM_EXT);
			
			// Set the model string to correctly associate the clipmodel
			cm->setModel(modelAndSkin.model);
			
			try {
				// create the new autosave filename by changing the extension
				Path cmPath = boost::filesystem::change_extension(
						Path(modelPath, boost::filesystem::native), 
						newExtension
					);
				
				// Open the stream to the output file
				std::ofstream outfile(cmPath.string().c_str());
				
				if (outfile.is_open()) {
					// Insert the CollisionModel into the stream
					outfile << *cm;
					// Close the file
					outfile.close();
					
					globalOutputStream() << "CollisionModel saved to " << cmPath.string() << std::endl;
				}
				else {
					gtkutil::errorDialog(
						(boost::format("Couldn't save to file: %s") % cmPath.string()).str(),
						 GlobalMainFrame().getTopLevelWindow());
				}
			}
			catch (boost::filesystem::filesystem_error f) {
				globalErrorStream() << "CollisionModel: " << f.what() << std::endl;
			}
			
			// De-select the child brushes
			GlobalSelectionSystem().setSelectedAll(false);
			
			// Re-add the origin to the brushes
			groupNode->addOriginToChildren();
		
			// Re-select the node
			Node_setSelected(entityNode, true);
		}
	}
	else {
		gtkutil::errorDialog(
			_(ERRSTR_WRONG_SELECTION.c_str()), 
			GlobalMainFrame().getTopLevelWindow());
	}
}
Ejemplo n.º 9
0
void LbmControlData::parseControldataAttrList(AttributeList *attr) {
	// controlpart vars
	mSetForceStrength = attr->readFloat("tforcestrength", mSetForceStrength,"LbmControlData", "mSetForceStrength", false);
	//errMsg("tforcestrength set to "," "<<mSetForceStrength);
	mCpUpdateInterval = attr->readInt("controlparticle_updateinterval", mCpUpdateInterval,"LbmControlData","mCpUpdateInterval", false);
	// tracer output file
	mCpOutfile = attr->readString("controlparticle_outfile",mCpOutfile,"LbmControlData","mCpOutfile", false);
	if(getenv("ELBEEM_CPOUTFILE")) {
		string outfile(getenv("ELBEEM_CPOUTFILE"));
		mCpOutfile = outfile;
		debMsgStd("LbmControlData::parseAttrList",DM_NOTIFY,"Using envvar ELBEEM_CPOUTFILE to set mCpOutfile to "<<outfile<<","<<mCpOutfile,7);
	}

	for(int cpii=0; cpii<10; cpii++) {
		string suffix("");
		//if(cpii>0)
		{  suffix = string("0"); suffix[0]+=cpii; }
		LbmControlSet *cset;
		cset = new LbmControlSet();
		cset->initCparts();

		cset->mContrPartFile = attr->readString("controlparticle"+suffix+"_file",cset->mContrPartFile,"LbmControlData","cset->mContrPartFile", false);
		if((cpii==0) && (getenv("ELBEEM_CPINFILE")) ) {
			string infile(getenv("ELBEEM_CPINFILE"));
			cset->mContrPartFile = infile;
			debMsgStd("LbmControlData::parseAttrList",DM_NOTIFY,"Using envvar ELBEEM_CPINFILE to set mContrPartFile to "<<infile<<","<<cset->mContrPartFile,7);
		}

		LbmFloat cpvort=0.;
		cset->mcRadiusAtt =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusatt", 0., "LbmControlData","mcRadiusAtt" );
		cset->mcRadiusVel =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusvel", 0., "LbmControlData","mcRadiusVel" );
		cset->mcRadiusVel =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusvel", 0., "LbmControlData","mcRadiusVel" );
		cset->mCparts->setRadiusAtt(cset->mcRadiusAtt.get(0.));
		cset->mCparts->setRadiusVel(cset->mcRadiusVel.get(0.));

		// WARNING currently only for first set
		//if(cpii==0) {
		cset->mcForceAtt  =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_attraction", 0. , "LbmControlData","cset->mcForceAtt", false);
		cset->mcForceVel  =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_velocity",   0. , "LbmControlData","mcForceVel", false);
		cset->mcForceMaxd =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_maxdist",    0. , "LbmControlData","mcForceMaxd", false);
		cset->mCparts->setInfluenceAttraction(cset->mcForceAtt.get(0.) );
		// warning - stores temprorarily, value converted to dt dep. factor
		cset->mCparts->setInfluenceVelocity(cset->mcForceVel.get(0.) , 0.01 ); // dummy dt
		cset->mCparts->setInfluenceMaxdist(cset->mcForceMaxd.get(0.) );
		cpvort =  attr->readFloat("controlparticle"+suffix+"_vorticity",   cpvort, "LbmControlData","cpvort", false);
		cset->mCparts->setInfluenceTangential(cpvort);
			
		cset->mcRadiusMind =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusmin", cset->mcRadiusMind.get(0.), "LbmControlData","mcRadiusMind", false);
		cset->mcRadiusMaxd =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusmax", cset->mcRadiusMind.get(0.), "LbmControlData","mcRadiusMaxd", false);
		cset->mCparts->setRadiusMinMaxd(cset->mcRadiusMind.get(0.));
		cset->mCparts->setRadiusMaxd(cset->mcRadiusMaxd.get(0.));
		//}

		// now local...
		//LbmVec cpOffset(0.), cpScale(1.);
		LbmFloat cpTimescale = 1.;
		string cpMirroring("");

		//cset->mcCpOffset = attr->readChannelVec3f("controlparticle"+suffix+"_offset", ntlVec3f(0.),"LbmControlData","mcCpOffset", false);
		//cset->mcCpScale =  attr->readChannelVec3f("controlparticle"+suffix+"_scale",  ntlVec3f(1.), "LbmControlData","mcCpScale", false);
		cset->mcCpOffset = attr->readChannelVec3f("controlparticle"+suffix+"_offset", ntlVec3f(0.),"LbmControlData","mcCpOffset", false);
		cset->mcCpScale =  attr->readChannelVec3f("controlparticle"+suffix+"_scale",  ntlVec3f(1.), "LbmControlData","mcCpScale", false);
		cpTimescale =  attr->readFloat("controlparticle"+suffix+"_timescale",  cpTimescale, "LbmControlData","cpTimescale", false);
		cpMirroring =  attr->readString("controlparticle"+suffix+"_mirror",  cpMirroring, "LbmControlData","cpMirroring", false);

		LbmFloat cpsWidth = cset->mCparts->getCPSWith();
		cpsWidth =  attr->readFloat("controlparticle"+suffix+"_cpswidth",  cpsWidth, "LbmControlData","cpsWidth", false);
		LbmFloat cpsDt = cset->mCparts->getCPSTimestep();
		cpsDt =  attr->readFloat("controlparticle"+suffix+"_cpstimestep",  cpsDt, "LbmControlData","cpsDt", false);
		LbmFloat cpsTstart = cset->mCparts->getCPSTimeStart();
		cpsTstart =  attr->readFloat("controlparticle"+suffix+"_cpststart",  cpsTstart, "LbmControlData","cpsTstart", false);
		LbmFloat cpsTend = cset->mCparts->getCPSTimeEnd();
		cpsTend =  attr->readFloat("controlparticle"+suffix+"_cpstend",  cpsTend, "LbmControlData","cpsTend", false);
		LbmFloat cpsMvmfac = cset->mCparts->getCPSMvmWeightFac();
		cpsMvmfac =  attr->readFloat("controlparticle"+suffix+"_cpsmvmfac",  cpsMvmfac, "LbmControlData","cpsMvmfac", false);
		cset->mCparts->setCPSWith(cpsWidth);
		cset->mCparts->setCPSTimestep(cpsDt);
		cset->mCparts->setCPSTimeStart(cpsTstart);
		cset->mCparts->setCPSTimeEnd(cpsTend);
		cset->mCparts->setCPSMvmWeightFac(cpsMvmfac);

		cset->mCparts->setOffset( vec2L(cset->mcCpOffset.get(0.)) );
		cset->mCparts->setScale( vec2L(cset->mcCpScale.get(0.)) );
		cset->mCparts->setInitTimeScale( cpTimescale );
		cset->mCparts->setInitMirror( cpMirroring );

		int mDebugInit = 0;
		mDebugInit = attr->readInt("controlparticle"+suffix+"_debuginit", mDebugInit,"LbmControlData","mDebugInit", false);
		cset->mCparts->setDebugInit(mDebugInit);

		// motion particle settings
		LbmVec mcpOffset(0.), mcpScale(1.);
		LbmFloat mcpTimescale = 1.;
		string mcpMirroring("");

		cset->mCpmotionFile = attr->readString("cpmotion"+suffix+"_file",cset->mCpmotionFile,"LbmControlData","mCpmotionFile", false);
		mcpTimescale =  attr->readFloat("cpmotion"+suffix+"_timescale",  mcpTimescale, "LbmControlData","mcpTimescale", false);
		mcpMirroring =  attr->readString("cpmotion"+suffix+"_mirror",  mcpMirroring, "LbmControlData","mcpMirroring", false);
		mcpOffset = vec2L( attr->readVec3d("cpmotion"+suffix+"_offset", vec2P(mcpOffset),"LbmControlData","cpOffset", false) );
		mcpScale =  vec2L( attr->readVec3d("cpmotion"+suffix+"_scale",  vec2P(mcpScale), "LbmControlData","cpScale", false) );

		cset->mCpmotion->setOffset( vec2L(mcpOffset) );
		cset->mCpmotion->setScale( vec2L(mcpScale) );
		cset->mCpmotion->setInitTimeScale( mcpTimescale );
		cset->mCpmotion->setInitMirror( mcpMirroring );

		if(cset->mContrPartFile.length()>1) {
			errMsg("LbmControlData","Using control particle set "<<cpii<<" file:"<<cset->mContrPartFile<<" cpmfile:"<<cset->mCpmotionFile<<" mirr:'"<<cset->mCpmotion->getInitMirror()<<"' " );
			mCons.push_back( cset );
		} else {
			delete cset;
		}
	}

	// debug, testing - make sure theres at least an empty set
	if(mCons.size()<1) {
		mCons.push_back( new LbmControlSet() );
		mCons[0]->initCparts();
	}

	// take from first set
	for(int cpii=1; cpii<(int)mCons.size(); cpii++) {
		mCons[cpii]->mCparts->setRadiusMinMaxd( mCons[0]->mCparts->getRadiusMinMaxd() );
		mCons[cpii]->mCparts->setRadiusMaxd(    mCons[0]->mCparts->getRadiusMaxd() );
		mCons[cpii]->mCparts->setInfluenceAttraction( mCons[0]->mCparts->getInfluenceAttraction() );
		mCons[cpii]->mCparts->setInfluenceTangential( mCons[0]->mCparts->getInfluenceTangential() );
		mCons[cpii]->mCparts->setInfluenceVelocity( mCons[0]->mCparts->getInfluenceVelocity() , 0.01 ); // dummy dt
		mCons[cpii]->mCparts->setInfluenceMaxdist( mCons[0]->mCparts->getInfluenceMaxdist() );
	}
	
	// invert for usage in relax macro
	mDiffVelCon =  1.-attr->readFloat("cpdiffvelcon",  mDiffVelCon, "LbmControlData","mDiffVelCon", false);

	mDebugCpscale     =  attr->readFloat("cpdebug_cpscale",  mDebugCpscale, "LbmControlData","mDebugCpscale", false);
	mDebugMaxdScale   =  attr->readFloat("cpdebug_maxdscale",  mDebugMaxdScale, "LbmControlData","mDebugMaxdScale", false);
	mDebugAttScale    =  attr->readFloat("cpdebug_attscale",  mDebugAttScale, "LbmControlData","mDebugAttScale", false);
	mDebugVelScale    =  attr->readFloat("cpdebug_velscale",  mDebugVelScale, "LbmControlData","mDebugVelScale", false);
	mDebugCompavScale =  attr->readFloat("cpdebug_compavscale",  mDebugCompavScale, "LbmControlData","mDebugCompavScale", false);
	mDebugAvgVelScale =  attr->readFloat("cpdebug_avgvelsc",  mDebugAvgVelScale, "LbmControlData","mDebugAvgVelScale", false);
}
Ejemplo n.º 10
0
/* MainWindow::createStartPage
 * Builds the HTML start page and loads it into the html viewer
 * (start page tab)
 *******************************************************************/
void MainWindow::createStartPage()
{
	// Get relevant resource entries
	Archive* res_archive = theArchiveManager->programResourceArchive();
	if (!res_archive)
		return;
	ArchiveEntry* entry_html = res_archive->entryAtPath("html/startpage.htm");
	ArchiveEntry* entry_logo = res_archive->entryAtPath("logo.png");
	ArchiveEntry* entry_tips = res_archive->entryAtPath("tips.txt");

	// Can't do anything without html entry
	if (!entry_html)
	{
		html_startpage->SetPage("<html><head><title>SLADE</title></head><body><center><h1>Something is wrong with slade.pk3 :(</h1><center></body></html>");
		return;
	}

	// Get html as string
	string html = wxString::FromAscii((const char*)(entry_html->getData()), entry_html->getSize());

	// Generate tip of the day string
	string tip = "It seems tips.txt is missing from your slade.pk3";
	if (entry_tips)
	{
		Tokenizer tz;
		tz.openMem((const char*)entry_tips->getData(), entry_tips->getSize(), entry_tips->getName());
		srand(wxGetLocalTime());
		int numtips = tz.getInteger();
		if (numtips < 2) // Needs at least two choices or it's kinda pointless.
			tip = "Did you know? Something is wrong with the tips.txt file in your slade.pk3.";
		else
		{
			int tipindex = 0;
			// Don't show same tip twice in a row
			do { tipindex = 1 + (rand() % numtips); }
			while (tipindex == lasttipindex);
			lasttipindex = tipindex;
			for (int a = 0; a < tipindex; a++)
				tip = tz.getToken();
		}
	}

	// Generate recent files string
	string recent;
	for (unsigned a = 0; a < 4; a++)
	{
		if (a >= theArchiveManager->numRecentFiles())
			break;	// No more recent files

		// Add line break if needed
		if (a > 0) recent += "<br/>\n";

		// Add recent file link
		recent += S_FMT("<a href=\"recent://%d\">%s</a>", a, theArchiveManager->recentFile(a));
	}

	// Insert tip and recent files into html
	html.Replace("#recent#", recent);
	html.Replace("#totd#", tip);

	// Write html and images to temp folder
	if (entry_logo) entry_logo->exportFile(appPath("logo.png", DIR_TEMP));
	string html_file = appPath("startpage.htm", DIR_TEMP);
	wxFile outfile(html_file, wxFile::write);
	outfile.Write(html);
	outfile.Close();

	// Load page
	html_startpage->LoadPage(html_file);

	// Clean up
	wxRemoveFile(html_file);
	wxRemoveFile(appPath("logo.png", DIR_TEMP));
}
Ejemplo n.º 11
0
/****************************************************************************
 * WindowPrompt
 *
 * Displays a prompt window to user, with information, an error message, or
 * presenting a user with a choice
 ***************************************************************************/
void
updatePrompt(string rev)
{
//	bool stop = true;

	GuiWindow promptWindow(520,360);
	promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	promptWindow.SetPosition(0, -10);
	GuiTrigger trigA;
	trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);


	GuiImageData dialogBox(Theme.dialog_background);
	GuiImage dialogBoxImg(&dialogBox);

	GuiImageData btnOutline(Theme.button_small);
	GuiImage btn1Img(&btnOutline);
	GuiImage btn2Img(&btnOutline);

	GuiImageData btnOutlineOver(Theme.button_small_focus);
	GuiImage btn1ImgOver(&btnOutlineOver);
	GuiImage btn2ImgOver(&btnOutlineOver);

	GuiText titleTxt(tr("Update"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
	titleTxt.SetPosition(0, 40);
	GuiText downloadTxt(tr("Downloading file..."), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	downloadTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	downloadTxt.SetPosition(0, -20);

	GuiText msgTxt(tr("please wait"), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	msgTxt.SetPosition(0, 20);

	GuiText btn1Txt(tr("Yes"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255});
	GuiButton btn1(btnOutline.GetWidth(), btnOutline.GetHeight());

	btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM);
	btn1.SetPosition(20, -25);
	btn1.SetLabel(&btn1Txt);
	btn1.SetImage(&btn1Img);
	btn1.SetImageOver(&btn1ImgOver);
	btn1.SetTrigger(&trigA);
	btn1.SetState(STATE_SELECTED);
	btn1.SetEffectGrow();

	GuiText btn2Txt(tr("No"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255});
	GuiButton btn2(btnOutline.GetWidth(), btnOutline.GetHeight());

	btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM);
	btn2.SetPosition(-20, -25);
	btn2.SetLabel(&btn2Txt);
	btn2.SetImage(&btn2Img);
	btn2.SetImageOver(&btn2ImgOver);
	btn2.SetTrigger(&trigA);
	btn2.SetEffectGrow();

	promptWindow.Append(&dialogBoxImg);
	promptWindow.Append(&titleTxt);
	promptWindow.Append(&downloadTxt);
	promptWindow.Append(&msgTxt);

	HaltGui();
	mainWindow->SetState(STATE_DISABLED);
	mainWindow->Append(&promptWindow);
	mainWindow->ChangeFocus(&promptWindow);
	ResumeGui();

	char url[100];
#ifdef STBOOTVWII
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st.vwii/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st.vwii/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone/prev.dol").c_str(), std::ios_base::binary);
#elif VWII
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL.vwii/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL.vwii/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter.vWii/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter.vWii/prev.dol").c_str(), std::ios_base::binary);
#elif STDBOOT
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter.Standalone/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter.Standalone/prev.dol").c_str(), std::ios_base::binary);
#else
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter/prev.dol").c_str(), std::ios_base::binary);
#endif

	outfile << infile.rdbuf();

	struct block file = downloadfile(url);
	if (file.data && file.size > 0)
	{
		// write file
#ifdef STBOOTVWII
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#elif VWII
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter.vWii").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter.vWii").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter.vWii/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#elif STDBOOT
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter.Standalone").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter.Standalone").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter.Standalone/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#else
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#endif
		if(file.data)
			free(file.data);

		boot_buffer = true;
		updatehbf = true;
	}
	else
	{
		if(file.data)
			free(file.data);
	}

	HaltGui();
	mainWindow->Remove(&promptWindow);
	mainWindow->SetState(STATE_DEFAULT);
	ResumeGui();
}
Ejemplo n.º 12
0
bool Project::readFromFile(QString filename)
{
    mProjectPath = filename;
    QDir tempDir = getTempDir();

    QuaZip zip(mProjectPath);
    if( zip.open(QuaZip::mdUnzip) )
    {
        QuaZipFile file(&zip);
        char* data = (char*)malloc(4096);
        for(bool f=zip.goToFirstFile(); f; f=zip.goToNextFile())
        {
            if( file.open(QIODevice::ReadOnly) )
            {
                QFile outfile( tempDir.absoluteFilePath(file.getActualFileName()) );
                outfile.open(QIODevice::WriteOnly);
                QDataStream out(&outfile);
                while( !file.atEnd() )
                {
                    qint64 bytesRead = file.read(data, 4096);
                    out.writeRawData(data,(uint)bytesRead);
                }
                file.close();
            }
        }
        free(data);
        zip.close();

        if(QFile::exists(tempDir.absoluteFilePath(mDatabaseFilename)))
        {
            if( mDbAdapter != 0 )
            {
                delete mDbAdapter;
                mDbAdapter = 0;
            }

            mDbAdapter = new DatabaseAdapter(tempDir.absoluteFilePath(mDatabaseFilename));
            readTextPaths();
        }
        else
        {
            QMessageBox::critical(0,tr("Error opening file"),tr("Something seems to be wrong with the archive. The file %1, which is an important one, could not be found.").arg(mDatabaseFilename));
            return false;
        }
        if(!QFile::exists(tempDir.absoluteFilePath("configuration.xml")))
        {
            QMessageBox::critical(0,tr("Error opening file"),tr("Something seems to be wrong with the archive. The file configuration.xml, which is an important one, could not be found."));
            return false;
        }
        else
        {
            parseConfigurationFile();
        }
    }
    else
    {
        QMessageBox::critical(0,tr("Error opening file"),tr("The file %1 could not be opened. It may be the wrong format, or it may have been corrupted.").arg(mProjectPath));
        return false;
    }
    return true;
}
Ejemplo n.º 13
0
/**
 * @brief 复制obj文件数据,只复制v部分和只含点信息的f
 * @param 空
 * @return 非零代表复制成功,0代表复制失败
 */
bool ObjModify::copyData()
{
	if(!firstVerticesLine)
	{
		if(!getInfo())
        {
            return false;
        }
	}
    string filePathName = inputPath + "\\" + filename;
    cout << filePathName << endl;
	ifstream infile;
	open_file(infile, filePathName.c_str());
	string newFilename = outputPath + "\\" + getName() + fileSuffix;
	ofstream outfile(newFilename.c_str(), ofstream::out);//如果没有对应文件,在根目录下创建一个
    for(int i = 0; !infile && i != 10; ++i)
    {
        open_file(infile, filePathName.c_str());
    }
	if(!infile)
	{
		cerr << "Try 10 times, but still can not open input file: " << filePathName << endl;
		return false;
	}
	if(!outfile)
	{
		cerr << "Can not open output file: " << newFilename << endl;
		return false;
	}
    ///写入obj文件头
	setHeader(outfile);

	string line;
	for(int i = 0; i != firstVerticesLine - 1;  ++i)
	{
		getline(infile, line);
		//cout << line << endl;
	}
	int v_count = 1, v_percent = 0;
	int r_count = 1, r_percent = 0;
	while(getline(infile, line))
	{
		if(line[0] == 'v' && line[1] == ' ')
		{
			outfile << line << endl;
			//显示已处理百分比
			if((v_count++ * 10 / vertices) != v_percent)
			{
				cout << "vertices processing " << 10 * v_percent << "%" << endl;
				v_percent = v_count * 10 / vertices;
			}
		}
		else if(line[0] == 'f' && line[1] == ' ')
		{
			string fstr;
			fstr = cov_f(line);
			outfile << fstr << endl;
			//显示已处理百分比
			if((r_count++ * 10 / triangles ) != r_percent)
			{
				cout << "triangles processing " << 10 * r_percent << "%" << endl;
				r_percent = r_count * 10 / triangles;
			}
		}
	}
	outfile.close();
	infile.close();
	return true;
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
	if ( argc != 3 )
    {
        std::cout<<"usage: "<< argv[0] <<" <input file> <output file>\n";
        return 1;
    }
	
	std::ifstream infile(argv[1]);
	std::ofstream outfile(argv[2]);
	
	float poissonRatio, youngModulus;
	infile >> poissonRatio >> youngModulus;

	Eigen::Matrix3f D;
	D <<
		1.0f,        	poissonRatio,	0.0f,
		poissonRatio,	1.0,         	0.0f,
		0.0f,        	0.0f,        	(1.0f - poissonRatio) / 2.0f;

	D *= youngModulus / (1.0f - pow(poissonRatio, 2.0f));

	infile >> nodesCount;
	nodesX.resize(nodesCount);
	nodesY.resize(nodesCount);

	for (int i = 0; i < nodesCount; ++i)
	{
		infile >> nodesX[i] >> nodesY[i];
	}

	int elementCount;
	infile >> elementCount;

	for (int i = 0; i < elementCount; ++i)
	{
		Element element;
		infile >> element.nodesIds[0] >> element.nodesIds[1] >> element.nodesIds[2];
		elements.push_back(element);
	}

	int constraintCount;
	infile >> constraintCount;

	for (int i = 0; i < constraintCount; ++i)
	{
		Constraint constraint;
		int type;
		infile >> constraint.node >> type;
		constraint.type = static_cast<Constraint::Type>(type);
		constraints.push_back(constraint);
	}

	loads.resize(2 * nodesCount);
	loads.setZero();

	int loadsCount;
	infile >> loadsCount;

	for (int i = 0; i < loadsCount; ++i)
	{
		int node;
		float x, y;
		infile >> node >> x >> y;
		loads[2 * node + 0] = x;
		loads[2 * node + 1] = y;
	}
	
	std::vector<Eigen::Triplet<float> > triplets;
	for (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)
	{
		it->CalculateStiffnessMatrix(D, triplets);
	}

	Eigen::SparseMatrix<float> globalK(2 * nodesCount, 2 * nodesCount);
	globalK.setFromTriplets(triplets.begin(), triplets.end());

	ApplyConstraints(globalK, constraints);

	Eigen::SimplicialLDLT<Eigen::SparseMatrix<float> > solver(globalK);

	Eigen::VectorXf displacements = solver.solve(loads);

	outfile << displacements << std::endl;

	for (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)
	{
		Eigen::Matrix<float, 6, 1> delta;
		delta << displacements.segment<2>(2 * it->nodesIds[0]),
		         displacements.segment<2>(2 * it->nodesIds[1]),
		         displacements.segment<2>(2 * it->nodesIds[2]);

		Eigen::Vector3f sigma = D * it->B * delta;
		float sigma_mises = sqrt(sigma[0] * sigma[0] - sigma[0] * sigma[1] + sigma[1] * sigma[1] + 3.0f * sigma[2] * sigma[2]);

		outfile << sigma_mises << std::endl;
	}
	return 0;
}
Ejemplo n.º 15
0
void convert_snp_affymetrix_C(char **dirname_, char **filelist, unsigned *files_amount_, char **map_filename_, char **outfilename_, unsigned *skipaffym, char **alleleID_names, char *alleleID, unsigned *alleleID_amount)
{

char *outfilename = *outfilename_;
char *dirname = *dirname_;
char *map_filename = *map_filename_;


unsigned files_amount=*files_amount_;



std::map<std::string, char> coding;
for(unsigned i=0 ; i<*alleleID_amount ; i++)
	{
	coding[alleleID_names[i]] = alleleID[i];
	}


Rprintf("reading map...\n");
//std::cout<<"reading map...\n";
AffymetrixChipMap Map(map_filename, 2, 0, 2, 4, 5, 3, 9, 10, 6);
//std::cout<<"map is read...\n";
Rprintf("map is read...\n");

if(Map.get_exclude_amount() != 0) 
	{
	Rprintf("%i SNPs excluded from annotation because of absent enough information annotation file\n", Map.get_exclude_amount());			
	}



std::vector<ChipData *> ids_chip;
for(unsigned i=0 ; i<files_amount ; i++)
	{
	std::string file = (std::string(dirname) + "/" + std::string(filelist[i]));
	Rprintf("%i: opening file %s\n", i+1, file.c_str());
	ids_chip.push_back(new affymetrix_chip_data(file, 0, 1, *skipaffym));
	}





unsigned id_amount=ids_chip.size(); 


std::ofstream outfile(outfilename);
if(!outfile.is_open()){error("Can not open file \"\"\n",outfilename);}


Rprintf("Save to file %s\n", outfilename);


outfile << "#GenABEL raw data version 0.1\n";

//save IDs
Rprintf("saving Id names...\n");
for(unsigned id=0 ; id<files_amount ; id++)
	{
	outfile<<replace(std::string(filelist[id]), ' ', '_')<<" ";
	}
outfile<<"\n";

std::string snpname;


unsigned long snp_excludet_from_output_data=0;


//save snpnames
Rprintf("saving SNP names...\n");
unsigned snp_amount=ids_chip[0]->get_snp_amount();
for(unsigned snp=0 ; snp<snp_amount ; snp++)
	{
	snpname = ids_chip[0]->get_snp_name(snp);
	if(Map.is_snp_in_map(snpname)){outfile<<Map.recode_snp(snpname.c_str())<<" ";}
	else{snp_excludet_from_output_data++;}
	}
outfile<<"\n";

//save chromosome 
Rprintf("saving chromosome data...\n");
for(unsigned snp=0 ; snp<snp_amount ; snp++)
	{
	snpname = ids_chip[0]->get_snp_name(snp);
	if(Map.is_snp_in_map(snpname)){outfile<<Map.get_chromosome(snpname.c_str())<<" ";}
	}
outfile<<"\n";


//save position (map) 
Rprintf("saving position data...\n");
for(unsigned snp=0 ; snp<snp_amount ; snp++)
	{
	snpname = ids_chip[0]->get_snp_name(snp);
	if(Map.is_snp_in_map(snpname)){outfile<<Map.get_phisical_position(snpname.c_str())<<" ";}
	}
outfile<<"\n";



//save coding
Rprintf("saving coding data...\n");
outfile.flags(std::ios_base::hex); //for what is it <-?
for(unsigned snp=0 ; snp<snp_amount ; snp++)
	{
	snpname = ids_chip[0]->get_snp_name(snp);
	if(Map.is_snp_in_map(snpname))
		{
		outfile.width(2);
		outfile.fill('0');
		static std::string allele_A, allele_B;
		allele_A = Map.get_allele_A(snpname.c_str());
  	allele_B = Map.get_allele_B(snpname.c_str());
		outfile<<unsigned(coding[allele_A+allele_B])<<" ";
		}
	}
outfile<<"\n";





//save strand
Rprintf("saving strand data...\n");
std::map<char, unsigned> strand_recode;
strand_recode['u']=0;
strand_recode['+']=1;
strand_recode['-']=2;

for(unsigned snp=0 ; snp<snp_amount ; snp++)
	{
	snpname = ids_chip[0]->get_snp_name(snp);
	if(Map.is_snp_in_map(snpname))
		{
		outfile.width(2);
		outfile.fill('0');
		static char strand;
		strand = Map.get_strand(snpname.c_str());
		outfile<<strand_recode[strand]<<" ";
		}
	}
outfile<<"\n";



//save polymorphism data
Rprintf("saving polymorphism data...\n");
unsigned long gtps_byte_amount = (unsigned long)ceil((double)id_amount/4.);
char *gtps_for_one_snp = new char[gtps_byte_amount];



unsigned *rearrangement_array = new unsigned[4];
rearrangement_array[0] = 6;
rearrangement_array[1] = 4;
rearrangement_array[2] = 2;
rearrangement_array[3] = 0;


for(unsigned snp=0 ; snp<snp_amount ; snp++)
	{
	if(!Map.is_snp_in_map(ids_chip[0]->get_snp_name(snp))) {continue;} // skip SNP if it doesn't exsist in our MAP
	for(unsigned i=0 ; i<gtps_byte_amount ; i++) gtps_for_one_snp[i]=0;
	
	static unsigned counter1, counter2;
	counter1=counter2=0;
	
	for(unsigned id=0 ; id<id_amount ; id++)
		{
		gtps_for_one_snp[counter2] = gtps_for_one_snp[counter2] | ids_chip[id]->get_polymorphism(snp)	<< rearrangement_array[counter1];
		counter1++;
		if(counter1==4) {counter1=0; counter2++;}
		}
		

	for(unsigned id=0 ; id<gtps_byte_amount ; id++)
		{
		outfile.width(2);
  	outfile.fill('0');
		outfile<<unsigned(gtps_for_one_snp[id]&0xFF)<<" ";
		}
	outfile<<"\n";
	}

delete gtps_for_one_snp;	
delete rearrangement_array;

Rprintf("%i SNPs excluded bacause of absent in annotation\n", snp_excludet_from_output_data);
Rprintf("Total %i SNPs are written into output file\n", snp_amount-snp_excludet_from_output_data);

Rprintf("Finshed... Data saved into file %s\n", outfilename);
outfile.close();
}
Ejemplo n.º 16
0
int main(int argc, char** argv){
	if(argc != 3){
		std::cerr << "USAGE: ./cache_simulator <input_file_name> <output-file-name>" << std::endl;
		exit(1);
	}

	std::ofstream outfile(argv[2]);

	int cache_line_size = -1, cache_size = -1, associativity = -1;
	std::string policy = "";

	Cache_simulator direct_mapped(DIRECT_MAPPED, argv[1]);
	cache_line_size = 32;
	int cache_size_array[] = {1024, 4096, 16384, 32768};

	for(int i = 0; i < 4; i++){
		outfile << direct_mapped.simulate(cache_size_array[i], cache_line_size, associativity, policy);
		outfile <<  " " << direct_mapped.get_total_referenced() << " ";
	}	
	outfile << std::endl;

	Cache_simulator set_associative(SET_ASSOCIATIVE, argv[1]);
	int associativity_array[] = {2, 4, 8, 16};
	cache_size = 16384;
	for(int i = 0; i < 4; i++){
		outfile << set_associative.simulate(cache_size, cache_line_size, associativity_array[i], policy);
		outfile << " " << set_associative.get_total_referenced() << " ";
	}	
	outfile << std::endl;

	Cache_simulator fully_associative(FULLY_ASSOCIATIVE, argv[1]);
	policy = "LRU";
	outfile << fully_associative.simulate(cache_size, cache_line_size, associativity, policy);
	outfile << " " << fully_associative.get_total_referenced() << std::endl;
	policy = "HOT-COLD";
	outfile << fully_associative.simulate(cache_size, cache_line_size, associativity, policy);
	outfile << " " << fully_associative.get_total_referenced() << std::endl;

	Cache_simulator set_associative_no_alloc_write_miss(SET_ASSOCIATIVE_NO_ALLOC_ON_WRITE_MISS, argv[1]);
	for(int i = 0; i < 4; i++){
		outfile << set_associative_no_alloc_write_miss.simulate(cache_size, cache_line_size, associativity_array[i], policy);
		outfile << " " << set_associative_no_alloc_write_miss.get_total_referenced() << " ";
	}	
	outfile << std::endl;
	
	Cache_simulator set_associative_nextline_prefetching(SET_ASSOCIATIVE_NEXTLINE_PREFETCHING, argv[1]);
	for(int i = 0; i < 4; i++){
		outfile << set_associative_nextline_prefetching.simulate(cache_size, cache_line_size, associativity_array[i], policy);
		outfile << " " << set_associative_nextline_prefetching.get_total_referenced() << " ";
	}	
	outfile << std::endl;

	Cache_simulator prefetch_on_miss(PREFETCH_ON_MISS, argv[1]);
	for(int i = 0; i < 4; i++){
		outfile << prefetch_on_miss.simulate(cache_size, cache_line_size, associativity_array[i], policy);
		outfile << " " << prefetch_on_miss.get_total_referenced() << " ";
	}	
	outfile << std::endl;

//Extra credit
	Cache_simulator test(FIFO, argv[1]);
	std::cout << "Extra credit: FIFO replacement\n" << "Cache hit: " << test.simulate(16*1024, 32, -1, "") << ", total referenced: " << test.get_total_referenced() << std::endl;
	outfile.close();
	return 0;
}
Ejemplo n.º 17
0
  Int_t AnalyzeCells_Fill( const char* runlist = "/home/yuxip/FMS/CellScan/macros/fill15419.list",const char* ls = "small" ){
	
	gStyle->SetPalette(1);
	gSystem->Load("../lib/libMyCellMgr.so");
	gROOT->LoadMacro("/home/yuxip/FMS/CellScan/macros/Legal.C");
	gROOT->LoadMacro("/home/yuxip/FMS/CellScan/macros/ConvertTH2Bin.C");
	mGeom = new Geom("./","geom.txt");
	cout<<"runlist: "<<runlist<<endl;
	
	Int_t fillnum = 0;
	Int_t runtoshow = 1;
	Long_t runnum = 0;
	Int_t rcnt = 0;
	sscanf(runlist,"/home/yuxip/FMS/CellScan/macros/fill%d.list",&fillnum);
	fstream infill(runlist,ios::in);
	if(!infill){
		cout<<"ERROR! "<<runlist<<" does not exist!!"<<endl;
		return -1;
	}
	while(infill>>runnum){
		rcnt++;
		if(rcnt==runtoshow)break;
	}
	cout<<"runtoshow: "<<runnum<<endl;
		
	
	Char_t outfilename[30];
	if(!strcmp(ls,"large")){
		sprintf(outfilename,"LargeCells_fill%d_run%ld_n2.ps",fillnum,runnum);
	}
	else if(!strcmp(ls,"small")){
		sprintf(outfilename,"SmallCells_fill%d_run%ld_n4.ps",fillnum,runnum);
	}
	else{
		cout<<"invalid 2nd argument!!"<<endl;
		return -1;
	}
	

	TString outfile(outfilename);
	TString headout = outfile + "[";
	TString endout = outfile + "]";
	
	TCanvas* c1 = new TCanvas("c1","c1",700,1100);
	c1->Divide(2,3);
	c1->Print(headout);
	
	Int_t ncell = 1000;		//for test only
	Int_t cellcnt  = 0;
	Char_t cellname[30];
	Char_t cellfile[30];
	TDirectory* h1where = gDirectory;
	TH1F* hmass 	= new TH1F("hmass","hmass",50,0,1);
	TH2F* hxy1	= new TH2F("hxy1","hxy1",34,-98.6,98.6,34,-98.6,98.6);
	TH2F* hxy2	= new TH2F("hxy2","hxy2",34,-98.6,98.6,34,-98.6,98.6);
	TH2F* smallxy1	= new TH2F("smallxy1","smallxy1",52,-98.6,98.6,52,-98.6,98.6);
	TH2F* smallxy2	= new TH2F("smallxy2","smallxy2",52,-98.6,98.6,52,-98.6,98.6);
	Float_t wbox 	= 12.0*3.8;

	Int_t nentries;
	Int_t 	maxy 	= 0;
	Int_t 	maxx 	= 0;
	UChar_t Status = 0x00;
	Char_t  text[30];
	MyCell* mcell 	= new MyCell();
	TTree* Trpi;
	Float_t	x2, y2;
	Int_t cnt = 1;
	Int_t n1  = 0;
        Int_t n2  = 0;

        if(!strcmp(ls,"large")){
                n1 = 2;
                n2 = 2;		//analysis each nstb separately
        }
        else if(!strcmp(ls,"small")){
                n1 = 4;
                n2 = 4;
        }
        else{
                cout<<"invalid 2nd argument"<<endl;
                return -1;
        }
	Int_t largeN1 = 0;
	Int_t smallN1 = 0;
	Int_t largeN2 = 0;
	Int_t smallN2 = 0;
	TFile* 	fcell = 0;
	MyCellEvt* mcevt = new MyCellEvt();
	
	for(Int_t nstb = n1; nstb <= n2; nstb++){
		for(Int_t row0 = 0; row0 < 34; row0++){
			for(Int_t col0 = 0; col0 < 17; col0++){

				cout<<"row0: "<<row0<<" col0: "<<col0<<" nstb: "<<nstb<<endl;
				if(!Legal(2,nstb,row0,col0)){
					continue;
				}
				cellcnt++;
				sprintf(cellname,"Cellr%d_c%d_n%d",row0,col0,nstb);
				cout<<"processing "<<cellname<<endl;
				sprintf(cellfile,"../cells/Cellr%d_c%d_n%d.root",row0,col0,nstb);
				
				fcell = new TFile(cellfile,"read");
				mcell = (MyCell*)fcell->Get(cellname);
				mcell->SetGeom(mGeom);
				mcell->Print();
				if(!mcell){
					cout<<"ERROR getting "<<cellname<<endl;
					return 0;
				}
				c1->cd(cnt);
				c1->GetPad(cnt)->SetLogy();
				c1->GetPad(cnt)->SetLogx();
				mcell->GetAdcSpectrum(runnum)->Draw();
				cnt++;
				c1->cd(cnt);
				c1->GetPad(cnt)->SetLogy();
				c1->GetPad(cnt)->SetLogx();
				mcell->GetLEDSpectrum(runnum)->Draw();
				mcell->GetLEDSpectrum(runnum)->SetLineColor(kBlue);
				Status = mcell->GetStatusBit(runnum);
				sprintf(text,"0x%x",Status);
				TLatex l(0.5,0.5,text);
				l.SetNDC();
				l.SetTextColor(2);
				l.Draw();
				cnt++;
				c1->cd(cnt);
//				c1->GetPad(cnt)->SetLogy();
				c1->GetPad(cnt)->SetFillColor(37);
				maxy = mcell->GetLEDvsEvt(runnum)->FindLastBinAbove(0,2);
				maxx = mcell->GetLEDvsEvt(runnum)->FindLastBinAbove(0,1);
				cout<<"maxx: "<<maxx<<endl;
				if(maxy < 2000){
					mcell->GetLEDvsEvt(runnum)->GetYaxis()->SetRange(0,2*maxy);
				}
				if(maxx < 2000){
					mcell->GetLEDvsEvt(runnum)->GetXaxis()->SetRange(0,(maxx+100));
				}
				
				mcell->GetLEDvsEvt(runnum)->Draw("COLZ");
				
				Trpi = mcell->GetPionSample("all",runlist);
				nentries = Trpi->GetEntries();
			//	Trpi->Print();
				cout<<"Trpi nentries: "<<nentries<<endl;
				

				if(nentries!=0){
/*
*/					
//					h1where->cd();
//					cnt++;
//					c1->cd(cnt);
//					Trpi->Project("hmass","M","");
//					hmass->Draw();
//					cnt++;
//					c1->cd(cnt);
					Float_t x1;
                                        Float_t x2;
                                        Float_t y1;
                                        Float_t y2;
					Float_t m;
					Trpi->ResetBranchAddresses();	//the orginal MergedTr was hooked up with transient member MyCellEvt of MyCell
                                        Trpi->SetBranchAddress("mycevt",&mcevt);
//                                        Trpi->SetBranchAddress("Y2",&y2);
//					Trpi->SetBranchAddress("M",&m);
                                        Trpi->SetBranchStatus("*",0);
                                        Trpi->SetBranchStatus("X2",1);
                                        Trpi->SetBranchStatus("Y2",1);
                                        Trpi->SetBranchStatus("M",1);
//					Trpi->GetEntry(0);
//					Trpi->Show(0);
//					cout<<"X2: "<<(mcevt->X2)<<", Y2: "<<(mcevt->Y2)<<", M: "<<(mcevt->M)<<endl;

					Int_t binx;
					Int_t biny;
					TString partner;
					Int_t pnstb = 0;
					Int_t prow0 = 0;
					Int_t pcol0 = 0;
					Long_t prun = 0;
					for(Int_t i = 0; i < nentries; i++){
						
						if(nstb<3){		//large cells
							if(!ConvertTH2Bin(nstb,row0,col0,binx,biny,hxy1)){
								cout<<"ERROR in ConvertTH2Bin()!"<<endl;
								return -1;
							}
							hxy1->SetBinContent(binx,biny,(hxy1->GetBinContent(binx,biny)+1));
						}

						if(nstb>2){		//small cells
							if(!ConvertTH2Bin(nstb,row0,col0,binx,biny,smallxy1)){
                                                                cout<<"ERROR in ConvertTH2Bin()!"<<endl;
                                                                return -1;
                                                        }
							smallxy1->SetBinContent(binx,biny,(smallxy1->GetBinContent(binx,biny)+1));
						}
//						cout<<"binx: "<<binx<<", biny: "<<biny<<endl;
						
						Trpi->GetEntry(i);
//						Trpi->Show(i);
						x2 = mcevt->X2;
						y2 = mcevt->Y2;
						 m = mcevt->M; 
//						cout<<"X2: "<<x2<<", Y2: "<<y2<<", M: "<<m<<endl;
						hmass->Fill(m);
						if(!mGeom->getNSTB(x2,y2))continue;	//bypass abnormal nstb
						partner = mcell->GetPartnerByXY(x2,y2,runnum);
						if(col0==0){
							cout<<"debug: partner: "<<partner<<endl;
						}
						sscanf((const char*)partner,"Cellr%d_c%d_n%d_run%ld",&prow0,&pcol0,&pnstb,&prun);
						if(col0==0){
                                                        cout<<"debug: partner (nstb,row0,col0): ("<<pnstb<<", "<<prow0<<", "<<pcol0<<") "<<endl;
                                                }

						if(!Legal(2,pnstb,prow0,pcol0)){
							cout<<"invalid partner id"<<endl;
							continue;
						}
						if(pnstb<3){             //large cells
							if(!ConvertTH2Bin(pnstb,prow0,pcol0,binx,biny,hxy2)){
                                                                cout<<"ERROR in ConvertTH2Bin()!"<<endl;
                                                                return -1;
                                                        }
							hxy2->SetBinContent(binx,biny,(hxy2->GetBinContent(binx,biny)+1));
						}
						if(pnstb>2){		//small cells
							if(!ConvertTH2Bin(pnstb,prow0,pcol0,binx,biny,smallxy2)){
                                                                cout<<"ERROR in ConvertTH2Bin()!"<<endl;
                                                                return -1;
                                                        }
							smallxy2->SetBinContent(binx,biny,(smallxy2->GetBinContent(binx,biny)+1));
						}
					}
					
					smallN1 = smallxy1->GetBinContent(smallxy1->GetMaximumBin());
					largeN1 = hxy1->GetBinContent(hxy1->GetMaximumBin());
					if(smallN1>=largeN1){
						cout<<"smallN1: "<<smallN1<<endl;
						hxy1->GetZaxis()->SetRangeUser(0,smallN1);
						smallxy1->GetZaxis()->SetRangeUser(0,smallN1);
					}
					else{
						cout<<"largeN1: "<<largeN1<<endl;
						hxy1->GetZaxis()->SetRangeUser(0,largeN1);
                                                smallxy1->GetZaxis()->SetRangeUser(0,largeN1);
					}
	
					cnt++;
                                        c1->cd(cnt);	
					hmass->Draw();

					cnt++;
                                        c1->cd(cnt);
					hxy1->SetStats(0);
					hxy1->Draw("COLZ");
					TBox bx(-wbox,-wbox,wbox,wbox);
					bx.SetFillColor(18);
					bx.Draw("same");
					smallxy1->SetStats(0);
					smallxy1->Draw("zcolsame");
				
					cnt++;
					c1->cd(cnt);
					
					largeN2 = hxy2->GetBinContent(hxy2->GetMaximumBin());
					smallN2 = smallxy2->GetBinContent(smallxy2->GetMaximumBin());
					if(smallN2>=largeN2){
						cout<<"smallN2: "<<smallN2<<endl;
                                                hxy2->GetZaxis()->SetRangeUser(0,smallN2);
                                                smallxy2->GetZaxis()->SetRangeUser(0,smallN2);
                                        }
                                        else{
						cout<<"largeN2: "<<largeN2<<endl;
                                                hxy2->GetZaxis()->SetRangeUser(0,largeN2);
                                                smallxy2->GetZaxis()->SetRangeUser(0,largeN2);
                                        }
					hxy2->SetStats(0);
					hxy2->Draw("COLZ");
					bx.Draw("same");
					smallxy2->SetStats(0);
					smallxy2->Draw("zcolsame");
				}
				largeN1 = largeN2 = 0;
				smallN1 = smallN2 = 0;
				Trpi = 0;
				c1->Print(outfile);
				mcell = 0;
				hmass->Reset();
                                hxy1->Reset();
                                hxy2->Reset();
                                smallxy1->Reset();
                                smallxy2->Reset();
				fcell->Close();
				fcell = 0;
				c1->Clear();
				c1->Divide(2,3);
				cnt = 1;
				if(cellcnt == ncell)break;
				
			}
			if(cellcnt == ncell)break;
		}
		if(cellcnt == ncell)break;
	}
	c1->Print(endout);
  	return 1;
  }
Ejemplo n.º 18
0
int main(int argc, char* argv[])

{

    if (argc != 5) {

        std::cout << "Usage: " << argv[0] << " entryPoint target outfile infile" << std::endl;

        std::cout << " Target can be something like ps_4_0, vs_4_0" << std::endl;

        return 1;

    }



    //

    // Read the entire shader source file

    //



    std::cout << "Reading File..." << std::endl;



    // Open the file

    std::ifstream infile(argv[4], std::ios::in | std::ios::binary);

    if (!infile) {

        std::cout << "Unable to open input file " << argv[4] << std::endl;

        return 1;

    }



    // Read the actual data

    std::string shader_source; 

    infile.seekg(0, std::ios::end);

    unsigned int length = infile.tellg();

    shader_source.resize(length);

    infile.seekg(0, std::ios::beg);

    infile.read(&shader_source[0], shader_source.size());

    infile.close();



    //

    // Compile the source code

    //



    std::cout << "Compiling..." << std::endl;



    ID3DBlob *code;

    ID3DBlob *errors;



    HRESULT hr = D3DCompile(

      &shader_source[0],                    //in       LPCVOID pSrcData,

      shader_source.size(),                 //in       SIZE_T SrcDataSize,

      argv[4],                              //in_opt   LPCSTR pSourceName,

      NULL,                                 //in_opt   const D3D_SHADER_MACRO *pDefines,

      D3D_COMPILE_STANDARD_FILE_INCLUDE,    //in_opt   ID3DInclude *pInclude,

      argv[1],                              //in       LPCSTR pEntrypoint,

      argv[2],                              //in       LPCSTR pTarget,

      D3DCOMPILE_OPTIMIZATION_LEVEL3 | 

      D3DCOMPILE_WARNINGS_ARE_ERRORS,       //in       UINT Flags1,

      0,                                    //in       UINT Flags2,

      &code,                                //out      ID3DBlob **ppCode,

      &errors                               //out_opt  ID3DBlob **ppErrorMsgs

    );



    // Check for compilation errors

    if (FAILED(hr)) {

        if (errors) {

            std::cout << "D3DCompile failed!" << std::endl;

            std::cout << (char*) errors->GetBufferPointer() << std::endl;

        } else {

            std::cout << "D3DCompile failed!" << std::endl;

        }

       

        return 1;

    }



    //

    // Open the output file

    //



    std::ofstream outfile(argv[3]);

    if (!outfile) {

        std::cout << "Unable to open output file " << argv[3] << std::endl;

        return 1;

    }



    const char *INDENT = "    ";



    outfile << "shader {" << std::endl;



    //

    // Shader Reflection information

    //



    std::cout << "Analyzing..." << std::endl;



    ID3D11ShaderReflection *reflection = NULL;

    hr = D3DReflect(code->GetBufferPointer(), code->GetBufferSize(), IID_ID3D11ShaderReflection, (void**) &reflection);

    if (SUCCEEDED(hr)) {

        D3D11_SHADER_DESC desc;

        reflection->GetDesc(&desc);



        std::cout << std::endl;

        std::cout << "Required Resources" << std::endl;

        std::cout << "------------------" << std::endl;



        outfile << INDENT << "resources {" << std::endl;



        for (int i = 0; i < desc.BoundResources; ++i) {

            D3D11_SHADER_INPUT_BIND_DESC rDesc;

        

            reflection->GetResourceBindingDesc(i,&rDesc);



            std::cout << i << " " << rDesc.Name << " " << rDesc.BindPoint << std::endl;



            outfile << INDENT << INDENT << "resource = \"" << rDesc.Name << "\" " << rDesc.BindPoint << std::endl;

        }



        outfile << INDENT << "}" << std::endl;

    } else {

        std::string target(argv[2]);



        if (    target.find("_3_") != std::string::npos ||

                target.find("_2_") != std::string::npos ||

                target.find("_1_") != std::string::npos) {



            // Build our own resource table





        }





    }



    // Output compiled shader bytecode

    std::string shader_compiled = toHexString (code->GetBufferPointer(), code->GetBufferSize());
    outfile << INDENT << "shader = \"" << shader_compiled << "\"" << std::endl;



    // Finish off the file

    outfile << "}" << std::endl;



	return 0;

}
void makeCube(std::pair<unsigned short *,int> myData)
{
	calls++;
	time_t rawtime;
	struct tm * timeinfo;
	time (&rawtime);
	timeinfo = localtime(&rawtime);
	char fileDay [100];
	strftime(fileDay,100,"%Y%m%d",timeinfo);
	char fileTime [100];
	strftime(fileTime,100,"%H:%M:%S",timeinfo);
	char directoryTime [100];
	strftime(directoryTime,100,"%H%M%S",timeinfo);
	std::string saveName;
	std::string cubeSaveName;
	std::string stringCalls;
	saveName = filename;
	stringCalls = std::to_string(calls);
	saveName.append(stringCalls);
	saveName.append("-");
	saveName.append(fileDay);
	std::cout << "\nmakeCube successfully called\n" << std::endl;
	std::cout << "Recording Complete\nWriting Datacube to Disk" << std::endl;			//write an ENVI compatible header file
	if (calls <= 1)
	{
		directoryName = ".\\";
		directoryName.append(fileDay);
		directoryName.append(directoryTime);
		//directoryName.append("/");
	}
	CreateDirectoryA(directoryName.c_str(),NULL);
	header_filename = directoryName;
	header_filename.append("\\");
	header_filename.append(saveName);
	header_filename.append(".hdr");
	std::ofstream outfile(header_filename.c_str());
	outfile << "ENVI\n";
	outfile << "File created at " << fileTime << " On " << fileDay << "\n";
	outfile << "interleave = bil\n";
	outfile << "data type = 12\n";
	outfile << "bit depth = 12\n";
	outfile << "samples = " << imager.get_sample_count() << "\n";
	outfile << "bands = " << imager.get_band_count() << "\n";
	outfile << "lines = " << LINE_COUNT << "\n";
	outfile << "framerate = " << imager.get_framerate() << "\n";
	outfile << "shutter = " << imager.get_integration_time() << "\n";
	outfile << "gain = " << imager.get_gain() << "\n";
	outfile << "wavelength = {";
	outfile << std::setprecision(5);
	for(int i = imager.get_window_start_band(); i < imager.get_window_end_band(); i++)
	{
		outfile << imager.get_wavelength_at_band(i);
		if (i < imager.get_window_end_band() - 1)
			outfile << ", ";
	}
	outfile << "}\n";
	outfile.close();

	//write data file
	std::ofstream cubefile;	
	cubeSaveName = directoryName + "\\" + saveName + ".bil";		
	cubefile.open(cubeSaveName.c_str(), std::ios::out | std::ios::binary);
	//cubefile.write((const char*) buffer, cubesize * sizeof(unsigned short));
	cubefile.write((const char*) myData.first, framesize * myData.second * sizeof(unsigned short));
	cubefile.close();
	std::cout << "Done." << std::endl;

	// free allocated resources
	delete [] myData.first;		
}
Ejemplo n.º 20
0
/**
 * Export the model and Task to SEDML.
 * The SEDML document is written to the file given by SEDMLFilename and reference SBML model is written to SBMLFilename .
 * If the export fails, false is returned.
 */
bool CSEDMLExporter::exportModelAndTasks(CCopasiDataModel& dataModel,
    const std::string& filename,
    const std::string& sbmlDocument,
    unsigned int sedmlLevel,
    unsigned int sedmlVersion,
    bool overwrite)
{
  bool success = true;
  /* create a string that represents the SBMLDocument */

  // std::string sedmlModelSource = "model1.xml"; //always name of the SBML model to reference in SEDML document
  // create a unique name for all exported models, rather than to overwrite existing ones!
  std::string sedmlModelSource = createUniqueModelFileName(CDirEntry::dirName(filename), "model", ".xml");

  std::string sbmlFileName;
  sbmlFileName = CDirEntry::dirName(filename) + CDirEntry::Separator + sedmlModelSource;

  std::ifstream sbmlFile(CLocaleString::fromUtf8(sbmlFileName).c_str(), std::ios::in);

  if (sbmlFile && !overwrite)
    {
      // create a CCopasiMessage with the appropriate error
      CCopasiMessage(CCopasiMessage::ERROR, MCDirEntry + 1, sbmlFileName.c_str());
      return false;
    }

  /* write the sbml model document to a file */
  std::ofstream sbmlOutFile(CLocaleString::fromUtf8(sbmlFileName).c_str(), std::ios::out | std::ios::trunc);
  sbmlOutFile << sbmlDocument;
  sbmlOutFile.close();

  std::string str = this->exportModelAndTasksToString(dataModel, sedmlModelSource, sedmlLevel, sedmlVersion);

  //std::cout<<str<<std::endl; //only for debuging

  if (!str.empty())
    {
      /* check if the file already exists.
       If yes, write if overwrite is true,
       else create an appropriate  CCopasiMessage. */
      std::ifstream testInfile(CLocaleString::fromUtf8(filename).c_str(), std::ios::in);

      if (testInfile && !overwrite)
        {
          // create a CCopasiMessage with the appropriate error
          CCopasiMessage(CCopasiMessage::ERROR, MCDirEntry + 1, filename.c_str());
          return false;
        }

      /* write the document to a file */
      std::ofstream outfile(CLocaleString::fromUtf8(filename).c_str(), std::ios::out | std::ios::trunc);
      outfile << str;
      outfile.close();
    }
  else
    {
      /* if no SBMLDocument could be created return false */
      success = false;
    }

  return success;
}
Ejemplo n.º 21
0
int main()
{
	int index = -1;
	//List of data
	FacultyList facultylist;
	StaffList stafflist;
	StudentList studentlist;
	do
	{
		//Print Menu
		cout<<"0. 구성원 파일 로드"<<endl;
		cout<<"1. 전체 구성원 조회"<<endl;
		cout<<"2. 학과(부서) 구성원 조회"<<endl;
		cout<<"3. 이름으로 검색"<<endl;
		cout<<"4. ID로 검색"<<endl;
		cout<<"5. 구성원 추가"<<endl;
		cout<<"6. 구성원 정보 수정"<<endl;
		cout<<"7. 구성원 정보 삭제"<<endl;
		cout<<"8. 구성원 목록 저장"<<endl;
		cout<<"9. 프로그램 종료"<<endl;
		cout<<">>";
		cin>>index;
		
		switch(index)
		{
		case 0:
			{
				string filename, name, id, dept, position, mail;
				char inputstring[BUFFERSIZE], *ptr;
				int party = 0, people = 0;

				//Input
				cout<<"파일 이름 입력 : ";
				cin>>filename;

				//File open
				ifstream infile(filename.c_str(), ios::in);
				if(!infile)
				{
					cout<<"파일이 존재하지 않습니다!"<<endl;
					break;
				}

				//Init Lists
				facultylist.RemoveAll();
				stafflist.RemoveAll();
				studentlist.RemoveAll();

				//Parsing
				while(infile.getline(inputstring, BUFFERSIZE-1))
				{	
					//To remove carrage return caracter in linux
					if(strlen(inputstring)>0 && inputstring[strlen(inputstring)-1]=='\r')
						inputstring[strlen(inputstring)-1]=0;
					if(strcmp(inputstring,"-교원")==0)
					{
						party = FACULTY;
						continue;
					}
					else if(strcmp(inputstring,"-직원")==0)
					{
						party = STAFF;
						continue;
					}
					else if(strcmp(inputstring,"-학생")==0)
					{
						party = STUDENT;
						continue;
					}
					else
					{
						//Parsing Data & Copy
						ptr = strtok(inputstring," ");
						name.assign(ptr);
						ptr = strtok(NULL," ");
						id.assign(ptr);
						ptr = strtok(NULL," ");
						dept.assign(ptr);
						ptr = strtok(NULL," ");
						position.assign(ptr);
						ptr = strtok(NULL," ");
						mail.assign(ptr);
						if(party == FACULTY)
							facultylist.Add(id, name, dept, position, mail);
						else if (party == STAFF)
							stafflist.Add(id, name, dept, position, mail);
						else if(party == STUDENT)
							studentlist.Add(id, name, dept, position, mail);
						people++;
					}

				}
				//print Results
				cout<<people<<"명의 정보를 로드하였습니다!"<<endl;
				infile.close();
			}
			break;
		case 1:
			//query entire member
			facultylist.InquireAll();
			cout<<endl;
			stafflist.InquireAll();
			cout<<endl;
			studentlist.InquireAll();
			break;
		case 2:
			//Search by dept name
			{
				string dept;
				int people = 0;
				cout<<"학과(부서) 입력 : ";
				cin>>dept;
				people = facultylist.InquireByDept(dept);
				people += stafflist.InquireByDept(dept);
				people += studentlist.InquireByDept(dept);
				if(people==0) cout<<"해당 학과(부서)의 사람이 존재하지 않습니다!"<<endl;
			}
			break;
		case 3:
			//Search by name
			{
				string name;
				int people = 0;
				cout<<"이름 입력 : ";
				cin>>name;
				people = facultylist.InquireByName(name);
				people += stafflist.InquireByName(name);
				people += studentlist.InquireByName(name);
				if(people==0)
					cout<<"해당 이름의 사람이 존재하지 않습니다!"<<endl;
			}
			break;
		case 4:
			//Search by id
			{
				string id;
				int people = 0;
				cout<<"ID 입력 : ";
				cin>>id;
				people = facultylist.InquireByID(id);
				people += stafflist.InquireByID(id);
				people += studentlist.InquireByID(id);
				if(people==0)
					cout<<"해당 ID의 사람이 존재하지 않습니다!"<<endl;
			}
			break;
		case 5:
			//Add member data
			{
				int party;
				string  id, name, dept, position, mail;
				cout<<"구성원 소속 선택(1.교수 2.직원 3.학생): ";
				cin>>party;
				cout<<"ID 입력: ";
				cin>>id;
				cout<<"이름 입력: ";
				cin>>name;
				cout<<"학과(부서) 입력: ";
				cin>>dept;
				cout<<"직급 입력: ";
				cin>>position;
				cout<<"메일 입력: ";
				cin>>mail;
				if(party == FACULTY)
				{
					if(!facultylist.Add(id, name, dept, position, mail))
						cout<<"이미 같은 ID가 존재합니다!"<<endl;
				}
				else if(party == STAFF)
				{
					if(!stafflist.Add(id, name, dept, position, mail))
						cout<<"이미 같은 ID가 존재합니다!"<<endl;
				}
				else if(party == STUDENT)
				{
					if(!studentlist.Add(id, name, dept, position, mail))
						cout<<"이미 같은 ID가 존재합니다!"<<endl;
				}
				else
				{
					cout<<"잘못된 소속입니다!"<<endl;
				}
			}
			break;
		case 6:
			//Modify member data
			{
				string  id, name, dept, position, mail;
				cout<<"ID 입력: ";
				cin>>id;
				cout<<"이름 입력: ";
				cin>>name;
				cout<<"학과(부서) 입력: ";
				cin>>dept;
				cout<<"직급 입력: ";
				cin>>position;
				cout<<"메일 입력: ";
				cin>>mail;
				if(facultylist.Modify(id, name, dept, position, mail))
					cout<<"수정 완료!"<<endl;
				else if(stafflist.Modify(id, name, dept, position, mail))
					cout<<"수정 완료!"<<endl;
				else if(studentlist.Modify(id, name, dept, position, mail))
					cout<<"수정 완료!"<<endl;
				else
					cout<<"일치하는 ID를 찾을 수 없습니다"<<endl;
			}
			break;
		case 7:
			//delete member data
			{
				string id;
				cout<<"ID 입력: ";
				cin>>id;
				if(facultylist.Delete(id))
					cout<<"삭제 완료!"<<endl;
				else if(stafflist.Delete(id))
					cout<<"삭제 완료!"<<endl;
				else if(studentlist.Delete(id))
					cout<<"삭제 완료!"<<endl;
				else
					cout<<"일치하는 ID를 찾을 수 없습니다"<<endl;
				
			}
			break;
		case 8:
			//saving to file
			{
				string filename;
				cout<<"파일 이름 입력: ";
				cin>>filename;
				ofstream outfile(filename.c_str());
				if(!outfile)
				{
					cout<<"File Open Error"<<endl;
					break;
				}
				outfile<<"-교원"<<endl;
				facultylist.SaveFile(outfile);
				outfile<<"-직원"<<endl;
				stafflist.SaveFile(outfile);
				outfile<<"-학생"<<endl;
				studentlist.SaveFile(outfile);
				cout<<"저장 완료!"<<endl;
				outfile.close();
			}
			break;
		case 9:
			break;
		default:
			{
				//Wrong input
				cout<<"잘못된 입력입니다!"<<endl;
			}
			break;
		}
		cout<<endl;
	}while(index!=9);
	return 0;
}
Ejemplo n.º 22
0
int main(int argc, char **argv)
{
    if (argc != 2)
    {
        print_usage();
        exit(EXIT_FAILURE);
    }

    std::string froot(argv[1]);
    size_t k(froot.find_first_of("-"));
    bool detector(k != std::string::npos);
    std::string dname;
    if (detector) dname = froot.substr(0, k);
    std::string fname_in(froot + ".txt");
    std::string fname_out(froot + ".dat");
    std::ifstream infile(fname_in.c_str());
    if (!infile.is_open())
    {
        std::cerr << "Error: file " << fname_in << " is not open." << std::endl;
        exit(EXIT_FAILURE);
    }

    std::string fgrid;
    if (detector)
        fgrid = dname + "-hv_grid.txt";
    else // e.g., a Database table file
        fgrid = "hv_grid.txt";
    std::ifstream hv_grid(fgrid.c_str());
    if (!hv_grid.is_open())
    {
        std::cerr << "Error: file " << fgrid << " is not open." << std::endl;
        exit(EXIT_FAILURE);
    }

    std::ofstream outfile(fname_out.c_str());
    if (!outfile.is_open())
    {
        std::cerr << "Error: file " << fname_out << " is not open." << std::endl;
        exit(EXIT_FAILURE);
    }

    utils::find_word(infile, "data");
    std::string s, units;
    while (true)
    {
        infile >> s;
        if (s == "in") break;
    }
    infile >> units;
    outfile << "# hv in eV\n# data in " << units << std::endl;

    utils::find_line(hv_grid, "Number of grid points:");
    size_t nhv;
    hv_grid >> nhv;

    utils::find_line(hv_grid, "Grid points:");
    size_t ihv, j;
    double x, y;
    for (ihv = 0; ihv < nhv; ++ihv)
    {
        hv_grid >> j >> x;
        infile >> y;
        outfile << utils::double_to_string(x) << " "
                << utils::double_to_string(y) << std::endl;
    }
    hv_grid.close();
    hv_grid.clear();
    infile.close();
    infile.clear();
    outfile.close();
    outfile.clear();

    return EXIT_SUCCESS;
}
Ejemplo n.º 23
0
void write_levels(char const* filename, std::vector<grid_t> levels,
                  bool reversed = false) {
    std::ofstream outfile(filename);
    if(!outfile.is_open()) {
        std::fprintf(stderr, "unable to open file: \"%s\"\n", filename);
        throw EXIT_FAILURE;
    }

    outfile << ".include \"src/globals.inc\"\n";
    outfile << "num_levels = " << levels.size() << '\n';
    outfile << ".segment \"RODATA\"\n\n";
    outfile << "level_index:";
    for(int i = 0; i != levels.size(); ++i) {
        if(i % 4 == 0)
            outfile << "\n.dbyt ";
        else
            outfile << ',';
        outfile << level_label(i);
    }
    outfile << "\n\n";

    coord_t prev_door;
    for(int i = 0; i != levels.size(); ++i) {
        std::string error_prefix = "level " + std::to_string(i+1);


        outfile << level_label(i) << ":\n";

        coord_t ralph = get_1_object(levels[i], ralph_char, error_prefix);
        if(ralph == coord_t{0})
            throw std::runtime_error(error_prefix + ": missing ralph");
        outfile << "; Ralph start position:\n";
        outfile << ".byt " << compress_xy(ralph) << '\n';

        coord_t exit = get_1_object(levels[i], '"', error_prefix);
        if(exit == coord_t{0})
            throw std::runtime_error(error_prefix + ": missing exit");

        if(i > 0 && ((reversed && exit != prev_door)
                     || (!reversed && ralph != prev_door))) {
            throw std::runtime_error(
                error_prefix + ": entry/exit mismatch");
        }
        if(reversed)
            prev_door = ralph;
        else
            prev_door = exit;


        coord_t gem = get_1_object(levels[i], '\'', error_prefix);
        outfile << "; Gem position:\n";
        outfile << ".byt " << compress_xy(gem) << '\n';

        std::vector<enemy_t> enemies = extract_enemies(levels[i],
                                                       error_prefix);
        if(enemies.size() > 16)
            throw std::runtime_error(error_prefix + ": too many enemies");
        outfile << "; Num enemies:\n";
        outfile << ".byt " << enemies.size() << '\n';
        if(enemies.size() > 0) {
            outfile << "; Enemy attributes array:\n.byt ";
            for(int i = 0; i != enemies.size(); ++i) {
                if(i != 0)
                    outfile << ',';
                outfile << enemies[i].attr;
            }
            outfile << '\n';
            outfile << "; Enemy positions:\n.byt ";
            for(int i = 0; i != enemies.size(); ++i) {
                if(i != 0)
                    outfile << ',';
                outfile << compress_xy(enemies[i].pos);
            }
            outfile << '\n';
        }

        // Read tiles and compress them
        std::vector<unsigned char> compressed_tiles
            = compress_tiles(get_uncompressed_tiles(levels[i], error_prefix,
                                                    i, levels.size()));
        // Write tiles
        outfile << "; Tiles:\n";
        for(int i = 0; i != compressed_tiles.size(); ++i) {
            if(i % 16 == 0)
                outfile << "\n.byt ";
            else
                outfile << ',';
            outfile << (int)compressed_tiles[i];
        }
        outfile << '\n';
    }
}
Ejemplo n.º 24
0
    void testWriteRead1()
    {
      const char *filename = "TestSTR.testWriteRead1.txt";

      STR stdfRecIn;
      std::ofstream outfile(filename, std::ofstream::binary);
      stdfRecIn.write(outfile);
      outfile.close();

      STR stdfRecOut;
      std::ifstream infile(filename, std::ifstream::binary);
      stdfRecOut.read(infile);
      outfile.close();

      TS_ASSERT_EQUALS(stdfRecIn.storage(), stdfRecOut.storage())
      std::vector<std::basic_string<char> > str;
      stdfRecOut.to_string(str);
      TS_ASSERT_EQUALS(str[0], "88");
      TS_ASSERT_EQUALS(str[1], "15");
      TS_ASSERT_EQUALS(str[2], "30");
      TS_ASSERT_EQUALS(str[3], "00000000"); //CONT_FLG
      TS_ASSERT_EQUALS(str[4], "0");        //TEST_NUM
      TS_ASSERT_EQUALS(str[5], "0");        //HEAD_NUM
      TS_ASSERT_EQUALS(str[6], "0");        //SITE_NUM
      TS_ASSERT_EQUALS(str[7], "0");        //PSR_REF
      TS_ASSERT_EQUALS(str[8], "00000000"); //TEST_FLG
      TS_ASSERT_EQUALS(str[9], "");         //LOG_TYP
      TS_ASSERT_EQUALS(str[10], "");        //TEST_TXT
      TS_ASSERT_EQUALS(str[11], "");        //ALARM_ID
      TS_ASSERT_EQUALS(str[12], "");        //PROG_TXT
      TS_ASSERT_EQUALS(str[13], "");        //RSLT_TXT
      TS_ASSERT_EQUALS(str[14], "0");       //Z_VAL
      TS_ASSERT_EQUALS(str[15], "00000101");//FMU_FLG
      TS_ASSERT_EQUALS(str[16], "");        //MASK_MAP
      TS_ASSERT_EQUALS(str[17], "");        //FAL_MAP
      TS_ASSERT_EQUALS(str[18], "0");       //CYC_CNT
      TS_ASSERT_EQUALS(str[19], "0");       //TOTF_CNT
      TS_ASSERT_EQUALS(str[20], "0");       //TOTL_CNT
      TS_ASSERT_EQUALS(str[21], "0");       //CYC_BASE
      TS_ASSERT_EQUALS(str[22], "0");       //BIT_BASE
      TS_ASSERT_EQUALS(str[23], "0");       //COND_CNT
      TS_ASSERT_EQUALS(str[24], "0");       //LIM_CNT
      TS_ASSERT_EQUALS(str[25], "0");       //CYC_SIZE
      TS_ASSERT_EQUALS(str[26], "0");       //PMR_SIZE
      TS_ASSERT_EQUALS(str[27], "0");       //CHN_SIZE
      TS_ASSERT_EQUALS(str[28], "0");       //PAT_SIZE
      TS_ASSERT_EQUALS(str[29], "0");       //BIT_SIZE
      TS_ASSERT_EQUALS(str[30], "0");       //U1_SIZE
      TS_ASSERT_EQUALS(str[31], "0");       //U2_SIZE
      TS_ASSERT_EQUALS(str[32], "0");       //U3_SIZE
      TS_ASSERT_EQUALS(str[33], "0");       //UTX_SIZE
      TS_ASSERT_EQUALS(str[34], "0");       //CAP_BGN
      TS_ASSERT_EQUALS(str[35], "");        //LIM_INDX
      TS_ASSERT_EQUALS(str[36], "");        //LIM_SPEC
      TS_ASSERT_EQUALS(str[37], "");        //COND_LST
      TS_ASSERT_EQUALS(str[38], "0");       //CYCO_CNT
      TS_ASSERT_EQUALS(str[39], "");        //CYC_OFST
      TS_ASSERT_EQUALS(str[40], "0");       //PMR_CNT
      TS_ASSERT_EQUALS(str[41], "");        //PMR_INDX
      TS_ASSERT_EQUALS(str[42], "0");       //CHN_CNT
      TS_ASSERT_EQUALS(str[43], "");        //CHN_NUM
      TS_ASSERT_EQUALS(str[44], "0");       //EXP_CNT
      TS_ASSERT_EQUALS(str[45], "");        //EXP_DATA
      TS_ASSERT_EQUALS(str[46], "0");       //CAP_CNT
      TS_ASSERT_EQUALS(str[47], "");        //CAP_DATA
      TS_ASSERT_EQUALS(str[48], "0");       //NEW_CNT
      TS_ASSERT_EQUALS(str[49], "");        //NEW_DATA
      TS_ASSERT_EQUALS(str[50], "0");       //PAT_CNT
      TS_ASSERT_EQUALS(str[51], "");        //PAT_NUM
      TS_ASSERT_EQUALS(str[52], "0");       //BPOS_CNT
      TS_ASSERT_EQUALS(str[53], "");        //BIT_POS
      TS_ASSERT_EQUALS(str[54], "0");       //USR1_CNT
      TS_ASSERT_EQUALS(str[55], "");        //USR1
      TS_ASSERT_EQUALS(str[56], "0");       //USR2_CNT
      TS_ASSERT_EQUALS(str[57], "");        //USR2
      TS_ASSERT_EQUALS(str[58], "0");       //USR3_CNT
      TS_ASSERT_EQUALS(str[59], "");        //USR3
      TS_ASSERT_EQUALS(str[60], "0");       //TXT_CNT
      TS_ASSERT_EQUALS(str[61], "");        //USER_TXT
    }
Ejemplo n.º 25
0
void BinaryWriter::Write(std::string fname,
  std::map<std::string, std::string> parameters,
  double *positions,
  std::vector<IntField*> intFields,
  std::vector<DoubleField*> doubleFields,
  int dim,
  long numParticles
  )
{
  std::map<std::string, std::string>::iterator it;
  int progress = 1;
  int j = 0;
  int k = 0;
  double temp;

  if(numParticles == 0)
  {
    std::cout << "Error: Number of particles is 0, exiting" << std::endl;
    std::exit(1);
  }

  ProgressBar pb(intFields.size()+doubleFields.size()+parameters.size()+1,"Writing output");

  std::ofstream outfile((char*)fname.c_str(), std::ios::binary);
  if(outfile.is_open()) 
  {
    std::cout << "Writing to output file..." << std::flush;

    outfile <<  "# vtk DataFile Version 1.0" << std::endl;
    outfile <<  "vtk output" << std::endl;
    outfile <<  "BINARY" << std::endl;
    outfile <<  "DATASET POLYDATA" << std::endl;
    outfile <<  "POINTS " << numParticles << " double" << std::endl;
   for ( int i = 0; i<numParticles; i++ ) // All positions, duplicate this loop to write extra arrays
   {
    j = 3*i;

    // SwapEnd(positions[j]);
    // outfile.write((char*)&positions[j], sizeof(double));
    // SwapEnd(positions[j+1]);
    // outfile.write((char*)&positions[j+1], sizeof(double));
    // SwapEnd(positions[j+2]);
    // outfile.write((char*)&positions[j+2], sizeof(double));

    temp = std::stod(std::to_string(positions[j]));
    SwapEnd(temp);
    outfile.write((char*)&temp, sizeof(double));
    temp = std::stod(std::to_string(positions[j+1]));
    SwapEnd(temp);
    outfile.write((char*)&temp, sizeof(double));
    temp = std::stod(std::to_string(positions[j+2]));
    SwapEnd(temp);
    outfile.write((char*)&temp, sizeof(double));

   }	

    outfile <<  std::endl; // NEW LINE

    outfile <<  "POINT_DATA " << numParticles << std::endl;

    outfile <<  "FIELD FieldData " << doubleFields.size()+intFields.size() << std::endl;

    for (long intf=0; intf < intFields.size(); intf++)
    {
      IntField *thisField = intFields[intf];

      outfile <<  thisField->name << " " << thisField->dim << " " << numParticles << " integer" << std::endl;

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

        k= thisField->dim * i;

        for( int l=0; l<thisField->dim; l++)
        {

          SwapEnd(thisField->data[k+l]);
          outfile.write((char*)&thisField->data[k+l], sizeof(int));


        }
      }

      outfile <<  std::endl;
    }

    for (long intf=0; intf < doubleFields.size(); intf++)
    {
      DoubleField *thisField = doubleFields[intf];

      outfile <<  thisField->name << " " << thisField->dim << " " << numParticles << " double" << std::endl;

      for ( int i = 0; i<numParticles; i++ )
      {
        k= thisField->dim * i;
        for( int l=0; l<thisField->dim; l++)
        {

          SwapEnd(thisField->data[k+l]);
          outfile.write((char*)&thisField->data[k+l], sizeof(double));
        }
      }

      outfile <<  std::endl;
    }

    outfile.close();
  }


  std::string fname_par = fname.substr(0, fname.find(".", 0));
  fname_par = fname_par + ".par";

  std::ofstream outfile2((char*)fname_par.c_str(), std::ios::out);
  if(outfile2.is_open()) 
  {
    outfile2 <<  "numParticles=" << numParticles << std::endl; // Number of particles

    for ( it = parameters.begin(); it != parameters.end(); it++ ) // All the parameters defined int he python script
    {
      outfile2 <<  it->first << "=" << space2comma2(it->second) << std::endl;
    }

    outfile2.close();
  }

  pb.Finish();
}
Ejemplo n.º 26
0
    void testWriteRead3()
    {
      const char *filename = "TestSTR.testWriteRead3.txt";

      STR stdfRecIn;
      stdfRecIn.setContflg("10100101"); //CONT_FLG
      stdfRecIn.setTestnum(123456);     //TEST_NUM
      stdfRecIn.setHeadnum(255);        //HEAD_NUM
      stdfRecIn.setSitenum(0);          //SITE_NUM
      stdfRecIn.setPsrref( 65535);      //PSR_REF
      stdfRecIn.setTestflg("00011000"); //TEST_FLG
      stdfRecIn.setLogtyp( "LOG_TYP");  //LOG_TYP
      stdfRecIn.setTesttxt("TEST_TXT"); //TEST_TXT
      stdfRecIn.setAlarmid("ALARM_ID"); //ALARM_ID
      stdfRecIn.setProgtxt("PROG_TXT"); //PROG_TXT
      stdfRecIn.setRslttxt("RSLT_TXT"); //RSLT_TXT
      stdfRecIn.setZval(   255);        //Z_VAL
      stdfRecIn.setFmuflg( "00000000"); //FMU_FLG: If the bit is set means the field is considered missing or not.
      stdfRecIn.setMaskmap("111");      //MASK_MAP
      stdfRecIn.setFalmap( "1111");     //FAL_MAP
      stdfRecIn.setCyccnt( 123456);     //CYC_CNT 
      stdfRecIn.settotfcnt(123456);     //TOTF_CNT
      stdfRecIn.settotlcnt(123456);     //TOTL_CNT
      stdfRecIn.setCycbase(5);          //CYC_BASE
      stdfRecIn.setBitbase(3);          //BIT_BASE
      stdfRecIn.setCondcnt(5);          //COND_CNT
      stdfRecIn.setLimcnt(3);           //LIM_CNT 
      stdfRecIn.setCycsize(2);          //CYC_SIZE
      stdfRecIn.setPmrsize(2);          //PMR_SIZE
      stdfRecIn.setChnsize(2);          //CHN_SIZE
      stdfRecIn.setPatsize(2);          //PAT_SIZE
      stdfRecIn.setBitsize(2);          //BIT_SIZE
      stdfRecIn.setU1size (2);          //U1_SIZE
      stdfRecIn.setU2size (2);          //U2_SIZE
      stdfRecIn.setU3size (2);          //U3_SIZE
      stdfRecIn.setUtxsize(3);          //UTX_SIZE
      stdfRecIn.setCapbgn (65535);      //CAP_BGN
      stdfRecIn.setLimindx(0,0);        //LIM_INDX
      stdfRecIn.setLimindx(1,1);        //LIM_INDX
      stdfRecIn.setLimindx(2,2);        //LIM_INDX
      stdfRecIn.setLimspec(0,0);        //LIM_SPEC
      stdfRecIn.setLimspec(1,1);        //LIM_SPEC
      stdfRecIn.setLimspec(2,2);        //LIM_SPEC
      stdfRecIn.setCondlst(0,"a");      //COND_LST
      stdfRecIn.setCondlst(1,"b");      //COND_LST
      stdfRecIn.setCondlst(2,"c");      //COND_LST
      stdfRecIn.setCondlst(3,"d");      //COND_LST
      stdfRecIn.setCondlst(4,"e");      //COND_LST
      stdfRecIn.setCycocnt(2);          //CYCO_CNT
      stdfRecIn.setCycofst(0,0);        //CYC_OFST
      stdfRecIn.setCycofst(1,1);        //CYC_OFST
      stdfRecIn.setPmrcnt (2);          //PMR_CNT
      stdfRecIn.setPmrindx(0,0);        //PMR_INDX
      stdfRecIn.setPmrindx(1,1);        //PMR_INDX
      stdfRecIn.setChncnt (2);          //CHN_CNT
      stdfRecIn.setChnnum (0,0);        //CHN_NUM
      stdfRecIn.setChnnum (1,1);        //CHN_NUM
      stdfRecIn.setExpcnt (2);          //EXP_CNT
      stdfRecIn.setExpdata(0,0);        //EXP_DATA
      stdfRecIn.setExpdata(1,1);        //EXP_DATA
      stdfRecIn.setCapcnt (2);          //CAP_CNT
      stdfRecIn.setCapdata(0,0);        //CAP_DATA
      stdfRecIn.setCapdata(1,1);        //CAP_DATA
      stdfRecIn.setNewcnt (2);          //NEW_CNT
      stdfRecIn.setNewdata(0,0);        //NEW_DATA
      stdfRecIn.setNewdata(1,1);        //NEW_DATA
      stdfRecIn.setPatcnt (2);          //PAT_CNT
      stdfRecIn.setPatnum (0,0);        //PAT_NUM
      stdfRecIn.setPatnum (1,1);        //PAT_NUM
      stdfRecIn.setBposcnt(2);          //BPOS_CNT
      stdfRecIn.setBitpos (0,0);        //BIT_POS
      stdfRecIn.setBitpos (1,1);        //BIT_POS
      stdfRecIn.setUsr1cnt(2);          //USR1_CNT
      stdfRecIn.setUsr1   (0,0);        //USR1
      stdfRecIn.setUsr1   (1,1);        //USR1
      stdfRecIn.setUsr2cnt(2);          //USR2_CNT
      stdfRecIn.setUsr2   (0,0);        //USR2
      stdfRecIn.setUsr2   (1,1);        //USR2
      stdfRecIn.setUsr3cnt(2);          //USR3_CNT
      stdfRecIn.setUsr3   (0,0);        //USR3
      stdfRecIn.setUsr3   (1,1);        //USR3
      stdfRecIn.setTxtcnt (3);          //TXT_CNT
      stdfRecIn.setUsertxt(0,"cn11111");//USER_TXT
      stdfRecIn.setUsertxt(1,"cn22222");//USER_TXT
      stdfRecIn.setUsertxt(2,"cn33333");//USER_TXT
      std::ofstream outfile(filename, std::ofstream::binary);
      stdfRecIn.write(outfile);
      outfile.close();
      TS_ASSERT_EQUALS(stdfRecIn.storage(), 198u)

      STR stdfRecOut;
      std::ifstream infile(filename, std::ifstream::binary);
      stdfRecOut.read(infile);
      outfile.close();

      TS_ASSERT_EQUALS(stdfRecIn.storage(), stdfRecOut.storage())
      std::vector<std::basic_string<char> > str;
      stdfRecOut.to_string(str);
      TS_ASSERT_EQUALS(str[0], "198");              
      TS_ASSERT_EQUALS(str[1], "15");
      TS_ASSERT_EQUALS(str[2], "30");
      TS_ASSERT_EQUALS(str[3], "10100101");    //CONT_FLG
      TS_ASSERT_EQUALS(str[4], "123456");      //TEST_NUM
      TS_ASSERT_EQUALS(str[5], "255");         //HEAD_NUM
      TS_ASSERT_EQUALS(str[6], "0");           //SITE_NUM
      TS_ASSERT_EQUALS(str[7], "65535");       //PSR_REF
      TS_ASSERT_EQUALS(str[8], "00011000");    //TEST_FLG
      TS_ASSERT_EQUALS(str[9], "LOG_TYP");     //LOG_TYP
      TS_ASSERT_EQUALS(str[10], "TEST_TXT");   //TEST_TXT
      TS_ASSERT_EQUALS(str[11], "ALARM_ID");   //ALARM_ID
      TS_ASSERT_EQUALS(str[12], "PROG_TXT");   //PROG_TXT
      TS_ASSERT_EQUALS(str[13], "RSLT_TXT");   //RSLT_TXT
      TS_ASSERT_EQUALS(str[14], "255");        //Z_VAL
      TS_ASSERT_EQUALS(str[15], "00000000");   //FMU_FLG
      //TS_ASSERT_EQUALS(str[16], "111");        //MASK_MAP
      //TS_ASSERT_EQUALS(str[17], "1111");       //FAL_MAP
      TS_ASSERT_EQUALS(str[16], "123456");     //CYC_CNT
      TS_ASSERT_EQUALS(str[17], "123456");     //TOTF_CNT
      TS_ASSERT_EQUALS(str[18], "123456");     //TOTL_CNT
      TS_ASSERT_EQUALS(str[19], "5");          //CYC_BASE
      TS_ASSERT_EQUALS(str[20], "3");          //BIT_BASE
      TS_ASSERT_EQUALS(str[21], "5");          //COND_CNT
      TS_ASSERT_EQUALS(str[22], "3");          //LIM_CNT
      TS_ASSERT_EQUALS(str[23], "2");          //CYC_SIZE
      TS_ASSERT_EQUALS(str[24], "2");          //PMR_SIZE
      TS_ASSERT_EQUALS(str[25], "2");          //CHN_SIZE
      TS_ASSERT_EQUALS(str[26], "2");          //PAT_SIZE
      TS_ASSERT_EQUALS(str[27], "2");          //BIT_SIZE
      TS_ASSERT_EQUALS(str[28], "2");          //U1_SIZE
      TS_ASSERT_EQUALS(str[29], "2");          //U2_SIZE
      TS_ASSERT_EQUALS(str[30], "2");          //U3_SIZE
      TS_ASSERT_EQUALS(str[31], "3");          //UTX_SIZE
      TS_ASSERT_EQUALS(str[32], "65535");      //CAP_BGN
      TS_ASSERT_EQUALS(str[33], "0,1,2");      //LIM_INDX
      TS_ASSERT_EQUALS(str[34], "0,1,2");      //LIM_SPEC
      TS_ASSERT_EQUALS(str[35], "a,b,c,d,e");  //COND_LST
      TS_ASSERT_EQUALS(str[36], "2");          //CYCO_CNT
      TS_ASSERT_EQUALS(str[37], "0,1");        //CYC_OFST
      TS_ASSERT_EQUALS(str[38], "2");          //PMR_CNT
      TS_ASSERT_EQUALS(str[39], "0,1");        //PMR_INDX
      TS_ASSERT_EQUALS(str[40], "2");          //CHN_CNT
      TS_ASSERT_EQUALS(str[41], "0,1");        //CHN_NUM
      TS_ASSERT_EQUALS(str[42], "2");          //EXP_CNT
      TS_ASSERT_EQUALS(str[43], "0,1");        //EXP_DATA
      TS_ASSERT_EQUALS(str[44], "2");          //CAP_CNT
      TS_ASSERT_EQUALS(str[45], "0,1");        //CAP_DATA
      TS_ASSERT_EQUALS(str[46], "2");          //NEW_CNT
      TS_ASSERT_EQUALS(str[47], "0,1");        //NEW_DATA
      TS_ASSERT_EQUALS(str[48], "2");          //PAT_CNT
      TS_ASSERT_EQUALS(str[49], "0,1");        //PAT_NUM
      TS_ASSERT_EQUALS(str[50], "2");          //BPOS_CNT
      TS_ASSERT_EQUALS(str[51], "0,1");        //BIT_POS
      TS_ASSERT_EQUALS(str[52], "2");          //USR1_CNT
      TS_ASSERT_EQUALS(str[53], "0,1");        //USR1
      TS_ASSERT_EQUALS(str[54], "2");          //USR2_CNT
      TS_ASSERT_EQUALS(str[55], "0,1");        //USR2
      TS_ASSERT_EQUALS(str[56], "2");          //USR3_CNT
      TS_ASSERT_EQUALS(str[57], "0,1");        //USR3
      TS_ASSERT_EQUALS(str[58], "3");          //TXT_CNT
      TS_ASSERT_EQUALS(str[59], "cn1,cn2,cn3");//USER_TXT

    }
Ejemplo n.º 27
0
void plotSpectrum() {
  CreateHistograms();
  char* append = "";

  // ****** get the weight value for each pthat bin ******* //
  for(int i=0; i<nGenPtBins; i++) {
    // for(int i=5; i<6; i++) {
    if(i!=0) append = "+";
    DrawTreeForAllHistos( i, append );
  }


  ///////////////////////////////////////

  nJetsCalo->SetBinContent( 1, Zmass->Integral() ); 
  nJetsCalo->SetBinError( 1, sqrt(Zmass->Integral()) );
  nJetsPF->SetBinContent( 1, Zmass->Integral());
  nJetsPF->SetBinError( 1, sqrt(Zmass->Integral()) );
  nJetsGen->SetBinContent( 1, Zmass->Integral());
  nJetsGen->SetBinError( 1, sqrt(Zmass->Integral()) );

  nJetsCalo->SetBinContent( 2, CaloJetPt->Integral() ); 
  nJetsCalo->SetBinError( 2, sqrt(CaloJetPt->Integral()) );
  nJetsPF->SetBinContent( 2, PFJetPt->Integral());
  nJetsPF->SetBinError( 2, sqrt(PFJetPt->Integral()) );
  nJetsGen->SetBinContent( 2, GenJetPt->Integral());
  nJetsGen->SetBinError( 2, sqrt(GenJetPt->Integral()) );

  nJetsCalo->SetBinContent( 3, CaloJetPt2->Integral()); 
  nJetsCalo->SetBinError( 3, sqrt(CaloJetPt2->Integral()) );
  nJetsPF->SetBinContent( 3, PFJetPt2->Integral());
  nJetsPF->SetBinError( 3, sqrt(PFJetPt2->Integral()) );
  nJetsGen->SetBinContent( 3, GenJetPt2->Integral());
  nJetsGen->SetBinError( 3, sqrt(GenJetPt2->Integral()) );

  nJetsCalo->SetBinContent( 4, CaloJetPt3->Integral()); 
  nJetsCalo->SetBinError( 4, sqrt(CaloJetPt3->Integral()) );
  nJetsPF->SetBinContent( 4, PFJetPt3->Integral());
  nJetsPF->SetBinError( 4, sqrt(PFJetPt3->Integral()) );
  nJetsGen->SetBinContent( 4, GenJetPt3->Integral());
  nJetsGen->SetBinError( 4, sqrt(GenJetPt3->Integral()) );


  /////////////////////////////////////
  ZPt_Gen->Sumw2();
  ZPt_Reco->Sumw2();
  GenJetPt->Sumw2();
  CaloJetPt->Sumw2();
  PFJetPt->Sumw2();

  emPt_Gen->Sumw2();
  emPt_Reco->Sumw2();
  epPt_Gen->Sumw2();
  epPt_Reco->Sumw2();
  Zmass->Sumw2();
  ZEta_Gen->Sumw2();
  ZEta_Reco->Sumw2();
  GenJetEta->Sumw2();
  CaloJetEta->Sumw2();
  PFJetEta->Sumw2();

  GenJetPt2->Sumw2();
  CaloJetPt2->Sumw2();
  PFJetPt2->Sumw2();

  GenJetPt3->Sumw2();
  CaloJetPt3->Sumw2();
  PFJetPt3->Sumw2();


  // set proper style for plots
  gROOT->ProcessLine(".L mystyle.C");
  setTDRStyle();
  tdrStyle->SetErrorX(0.5);
  tdrStyle->SetPadLeftMargin(0.18);
  tdrStyle->SetPadRightMargin(0.10);
  tdrStyle->SetPadBottomMargin(0.16);
  tdrStyle->SetLegendBorderSize(0);
  tdrStyle->SetTitleYOffset(1.5);

  makeplotTwo(*ZPt_Reco, *ZPt_Gen, "ZPt_spectrum", 1);
  // makeplotTwo( *emPt_Reco, *emPt_Gen, "emPt_spectrum", 0);
  // makeplotTwo( *epPt_Reco, *epPt_Gen, "epPt_spectrum", 0);
  // makeplotTwo(*ZEta_Reco, *ZEta_Gen, "Z_eta_spectrum", 2);

  makeplotThree(*CaloJetPt, *GenJetPt, *PFJetPt, "Jet_spectrum", 1);
  makeplotThree(*CaloJetPt2, *GenJetPt2, *PFJetPt2, "Jet_spectrum2", 1);
  makeplotThree(*CaloJetPt3, *GenJetPt3, *PFJetPt3, "Jet_spectrum3", 1);

  makeplotThree(*CaloJetEta, *GenJetEta, *PFJetEta, "Jet_eta_spectrum", 2);
  //makeplot( *Zmass, "Zmass", "e", 0);



  //make ratio histograms
  CaloJetPtRatio2over1 = makeRatioHist( *CaloJetPt, *CaloJetPt2, "CaloJetPtRatio2over1",150);
  CaloJetPtRatio3over2 = makeRatioHist( *CaloJetPt2, *CaloJetPt3, "CaloJetPtRatio2over1",100);
  PFJetPtRatio2over1 = makeRatioHist( *PFJetPt, *PFJetPt2, "PFJetPtRatio2over1",150);
  PFJetPtRatio3over2 = makeRatioHist( *PFJetPt2, *PFJetPt3, "PFJetPtRatio3over2",100);
  GenJetPtRatio2over1 = makeRatioHist( *GenJetPt, *GenJetPt2, "GenJetPtRatio2over1",150);
  GenJetPtRatio3over2 = makeRatioHist( *GenJetPt2, *GenJetPt3, "GenJetPtRatio3over2",100);
  CaloJetPtRatio2over1->GetYaxis()->SetTitle("n^{Jet}_{#geq 2} / n^{Jet}_{#geq 1}");
  CaloJetPtRatio3over2->GetYaxis()->SetTitle("n^{Jet}_{#geq 3} / n^{Jet}_{#geq 2}");

  makeplotThree(*CaloJetPtRatio2over1, *GenJetPtRatio2over1, *PFJetPtRatio2over1, "JetPtRatio2over1", 0);
  makeplotThree(*CaloJetPtRatio3over2, *GenJetPtRatio3over2, *PFJetPtRatio3over2, "JetPtRatio3over2", 0);
  makeplotThree( *nJetsCalo, *nJetsGen, *nJetsPF, "JetMultiplicity", 1);

  //////////////////////////////////////
  //tdrStyle->SetPadLeftMargin(0.22);
  TFile outfile( (std::string("histograms_")+cmEnergy+".root").c_str(), "RECREATE"  );
  outfile.cd();
  ZPt_Gen->Write();
  ZPt_Reco->Write();
  GenJetPt->Write();
  CaloJetPt->Write();
  PFJetPt->Write();
  emPt_Gen->Write();
  emPt_Reco->Write();
  epPt_Gen->Write();
  epPt_Reco->Write();
  Zmass->Write();

  ZEta_Gen->Write();
  ZEta_Reco->Write();
  GenJetEta->Write();
  CaloJetEta->Write();
  PFJetEta->Write();

  GenJetPt2->Write();
  CaloJetPt2->Write();
  PFJetPt2->Write();

  GenJetPt3->Write();
  CaloJetPt3->Write();
  PFJetPt3->Write();

  nJetsCalo->Write();
  nJetsPF->Write();
  nJetsGen->Write();

  CaloJetPtRatio2over1->Write();
  CaloJetPtRatio3over2->Write();
  PFJetPtRatio2over1->Write();
  PFJetPtRatio3over2->Write();
  GenJetPtRatio2over1->Write();
  GenJetPtRatio3over2->Write();

  outfile.Close();
}
Ejemplo n.º 28
0
/***********************************************************************
 * recv_to_file function
 **********************************************************************/
template<typename samp_type> void recv_to_file(
    uhd::usrp::multi_usrp::sptr usrp,
    const std::string &cpu_format,
    const std::string &wire_format,
    const std::string &file,
    size_t samps_per_buff,
    int num_requested_samples,
    float settling_time,
    std::vector<size_t> rx_channel_nums
) {
    int num_total_samps = 0;
    //create a receive streamer
    uhd::stream_args_t stream_args(cpu_format,wire_format);
    stream_args.channels = rx_channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile(file.c_str(), std::ofstream::binary);
    bool overflow_message = true;
    float timeout = settling_time + 0.1; //expected settling time + padding for first recv

    //setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)?
                                 uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
                                 uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
                                );
    stream_cmd.num_samps = num_requested_samples;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(settling_time);
    rx_stream->issue_stream_cmd(stream_cmd);

    while(not stop_signal_called and (num_requested_samples != num_total_samps or num_requested_samples == 0)) {
        size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, timeout);
        timeout = 0.1; //small timeout for subsequent recv

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) {
            if (overflow_message) {
                overflow_message = false;
                std::cerr << boost::format(
                              "Got an overflow indication. Please consider the following:\n"
                              "  Your write medium must sustain a rate of %fMB/s.\n"
                              "  Dropped samples will not be written to the file.\n"
                              "  Please modify this example for your purposes.\n"
                              "  This message will not appear again.\n"
                          ) % (usrp->get_rx_rate()*sizeof(samp_type)/1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) {
            throw std::runtime_error(str(boost::format(
                                             "Receiver error %s"
                                         ) % md.strerror()));
        }

        num_total_samps += num_rx_samps;

        outfile.write((const char*)&buff.front(), num_rx_samps*sizeof(samp_type));
    }

    outfile.close();
}
Ejemplo n.º 29
0
int	main(int argc, char *argv[]) {
	int	c;
	int	longindex;
	std::string	outfilename;
	bool	force = false;
	float	alpha = 0.001;
	while (EOF != (c = getopt_long(argc, argv, "a:dfho:", longopts,
                &longindex)))
                switch (c) {
		case 'a':
			alpha = std::stof(optarg);
			break;
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		case 'f':
			force = true;
			break;
		case 'h':
			usage(argv[0]);
			return EXIT_SUCCESS;
		case 'o':
			outfilename = std::string(optarg);
			break;
		default:
			throw std::runtime_error("unknown option");
		}

	// get the file name
	if (argc <= optind) {
		throw std::runtime_error("input file name missing");
	}
	std::string	infilename(argv[optind++]);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "processing image %s",
		infilename.c_str());

	// read the input file
	FITSin	infile(infilename);
	ImagePtr	image = infile.read();
	ImagePtr	outimage;

	// prepare a background extractor
	BackgroundExtractor	extractor(alpha);

	// if this is a mono image, we just use luminance for background
	// extraction
	switch (image->planes()) {
	case 1:	{
		// make image accessible as an image with float pixels
		ConstPixelValueAdapter<float>	from(image);

		// get the background
		Background<float>	bg = extractor(image->center(), true,
					BackgroundExtractor::QUADRATIC, from);

		// subtract the background
		BackgroundFunctionAdapter	bfa(from, bg.G());

		// write the result to the output
		outimage = ImagePtr(new Image<float>(bfa));
		}
		break;
	case 3:	{
		// make image accessible as an RGB<float> image
		ConstPixelValueAdapter<RGB<float> >	from(image);

		// get the background
		Background<float>	bg = extractor(image->center(), true,
					BackgroundExtractor::QUADRATIC, from);

		// subtract the background
		BackgroundSubtractionAdapter	bsa(from, bg);

		// write the result to the output
		outimage = ImagePtr(new Image<RGB<float> >(bsa));
		}
		break;
	default:
		std::string	msg = stringprintf("don't know how to handle "
			"background for images with %d planes",
			image->planes());
		debug(LOG_ERR, DEBUG_LOG, 0, "%s", msg.c_str());
		throw std::runtime_error(msg);
	}

	// we give up here, because we don't want to write the changed file
	if (0 == outfilename.size()) {
		return EXIT_SUCCESS;
	}


	FITSout	outfile(outfilename);
	outfile.setPrecious(!force);
	outfile.write(outimage);

	// that's it
	return EXIT_SUCCESS;
}
Ejemplo n.º 30
0
int main(int argc, char **argv) {
  printf("ERKALE - Basis set tools from Hel.\n");
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc<3) {
    printf("Usage: %s input.gbs command\n\n",argv[0]);
    help();
    return 0;
  }

  // Get filename
  std::string filein(argv[1]);
  // Load input
  BasisSetLibrary bas;
  bas.load_gaussian94(filein);

  // Get command
  std::string cmd(argv[2]);
  // and determine what to do.
  if(stricmp(cmd,"cholesky")==0) {
    // Print completeness profile.

    if(argc!=7) {
      printf("\nUsage: %s input.gbs cholesky thr maxam ovlthr output.gbs\n",argv[0]);
      return 1;
    }

    double thr(atof(argv[3]));
    int maxam(atoi(argv[4]));
    double ovlthr(atof(argv[5]));
    std::string outfile(argv[6]);

    if(maxam>=LIBINT_MAX_AM) {
      printf("Setting maxam = %i because limitations in used version of LIBINT.\n",LIBINT_MAX_AM-1);
      maxam=LIBINT_MAX_AM-1;
    }
			       
    init_libint_base();
    BasisSetLibrary ret=bas.cholesky_set(thr,maxam,ovlthr);
    ret.save_gaussian94(outfile);
    
  } else if(stricmp(cmd,"completeness")==0) {
    // Print completeness profile.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs completeness element output.dat (coulomb)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);
    bool coulomb=false;
    if(argc==6)
      coulomb=atoi(argv[5]);

    // Get wanted element from basis
    ElementBasisSet elbas=bas.get_element(el);

    // Compute completeness profile
    compprof_t prof=compute_completeness(elbas,-10.0,10.0,2001,coulomb);

    // Print profile in output file
    FILE *out=fopen(fileout.c_str(),"w");
    for(size_t i=0;i<prof.lga.size();i++) {
      // Value of scanning exponent
      fprintf(out,"%13e",prof.lga[i]);
      // Print completeness of shells
      for(size_t j=0;j<prof.shells.size();j++)
	fprintf(out,"\t%13e",prof.shells[j].Y[i]);
      fprintf(out,"\n");
    }
    fclose(out);

  } else if(stricmp(cmd,"composition")==0) {
    // Determine composition of basis set.

    if(argc!=3 && argc!=4) {
      printf("\nUsage: %s input.gbs composition (El)\n",argv[0]);
      return 1;
    }

    // Elemental basis sets
    std::vector<ElementBasisSet> elbases;

    if(argc==4)
      elbases.push_back(bas.get_element(argv[3]));
    else
      elbases=bas.get_elements();

    printf("\n");
    printf("el at#  [npr|nbf] [primitive|contracted(?)]\n");
    printf("-------------------------------------------\n");

    // Loop over elements
    for(size_t iel=0;iel<elbases.size();iel++) {
      // Get the basis set
      ElementBasisSet elbas=elbases[iel];

      // Decontracted basis
      ElementBasisSet eldec(elbas);
      eldec.decontract();

      // Get the shells
      std::vector<FunctionShell> sh=elbas.get_shells();
      std::vector<FunctionShell> decsh=eldec.get_shells();

      // Count the shells
      arma::imat Nsh(max_am,2);
      Nsh.zeros();
      for(size_t ish=0;ish<decsh.size();ish++)
	Nsh(decsh[ish].get_am(),0)++;
      for(size_t ish=0;ish<sh.size();ish++)
	Nsh(sh[ish].get_am(),1)++;

      // Determine if basis set is contracted and the amount of
      // functions
      bool contr=false;
      size_t nbf=0;
      size_t nprim=0;
      for(int am=0;am<max_am;am++) {
	// Number of primitives
	nprim+=Nsh(am,0)*(2*am+1);
	// Number of contracted functions
	nbf+=Nsh(am,1)*(2*am+1);
      }
      if(nbf!=nprim)
	contr=true;

      // Print composition
      printf("%-2s %3i ",elbas.get_symbol().c_str(),(int) elbas.get_number());
      if(contr) {
	// Print amount of functions
	char cmp[20];
	sprintf(cmp,"[%i|%i]",(int) nprim,(int) nbf);
	printf("%10s [",cmp);

	// Print primitives
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)>0)
	    printf("%i%c",Nsh(am,0),tolower(shell_types[am]));
	// Print contractions
	printf("|");
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)!=Nsh(am,1))
	    printf("%i%c",Nsh(am,1),tolower(shell_types[am]));
	printf("]\n");
      } else {
	printf("%10i  ",(int) nbf);
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)>0)
	    printf("%i%c",Nsh(am,0),tolower(shell_types[am]));
	printf("\n");
      }
    }
  } else if(stricmp(cmd,"daug")==0 || stricmp(cmd,"taug")==0) {
    // Augment basis set

    if(argc!=4) {
      printf("\nUsage: %s input.gbs %s output.gbs\n",argv[0],tolower(cmd).c_str());
      return 1;
    }

    int naug;
    if(stricmp(cmd,"daug")==0)
      naug=1;
    else
      naug=2;

    std::string fileout(argv[3]);
    bas.augment(naug);
    bas.save_gaussian94(fileout);
  } else if(stricmp(cmd,"decontract")==0) {
  // Decontract basis set.

    if(argc!=4) {
      printf("\nUsage: %s input.gbs decontract output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout(argv[3]);
    bas.decontract();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"densityfit")==0) {
  // Generate density fitted set

    if(argc!=6) {
      printf("\nUsage: %s input.gbs densityfit lval fsam output.gbs\n",argv[0]);
      return 1;
    }

    int lval(atoi(argv[3]));
    double fsam(atof(argv[4]));
    std::string fileout(argv[5]);
    BasisSetLibrary dfit(bas.density_fitting(lval,fsam));
    dfit.save_gaussian94(fileout);

  } else if(stricmp(cmd,"dump")==0) {
    // Dump wanted element.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs dump element output.gbs (number)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);

    int no=0;
    if(argc==6)
      no=atoi(argv[5]);

    // Save output
    BasisSetLibrary elbas;
    elbas.add_element(bas.get_element(el,no));
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"dumpdec")==0) {
    // Dump wanted element in decontracted form.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs dumpdec element output.gbs (number)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);

    int no=0;
    if(argc==6)
      no=atoi(argv[5]);

    // Save output
    BasisSetLibrary elbas;
    bas.decontract();
    elbas.add_element(bas.get_element(el,no));
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"genbas")==0) {
    // Generate basis set for xyz file

    if(argc!=5) {
      printf("\nUsage: %s input.gbs genbas system.xyz output.gbs\n",argv[0]);
      return 1;
    }

    // Load atoms from xyz file
    std::vector<atom_t> atoms=load_xyz(argv[3]);
    // Output file
    std::string fileout(argv[4]);
    // Save output
    BasisSetLibrary elbas;

    // Collect elements
    std::vector<ElementBasisSet> els=bas.get_elements();
    // Loop over atoms in system
    for(size_t iat=0;iat<atoms.size();iat++) {
      bool found=false;

      // First, check if there is a special basis for the atom.
      for(size_t iel=0;iel<els.size();iel++)
	if(stricmp(atoms[iat].el,els[iel].get_symbol())==0 && atoms[iat].num == els[iel].get_number()) {
	  // Yes, add it.
	  elbas.add_element(els[iel]);
	  found=true;
	  break;
	}

      // Otherwise, check if a general basis is already in the basis
      if(!found) {
	std::vector<ElementBasisSet> added=elbas.get_elements();
	for(size_t j=0;j<added.size();j++)
	  if(added[j].get_number()==0 && stricmp(atoms[iat].el,added[j].get_symbol())==0)
	    found=true;
      }

      // If general basis not found, add it.
      if(!found) {
	for(size_t iel=0;iel<els.size();iel++)
	  if(stricmp(atoms[iat].el,els[iel].get_symbol())==0 && els[iel].get_number()==0) {
	    // Yes, add it.
	    elbas.add_element(els[iel]);
	    found=true;
	    break;
	  }
      }

      if(!found) {
	std::ostringstream oss;
	oss << "Basis set for element " << atoms[iat].el << " does not exist in " << filein << "!\n";
	throw std::runtime_error(oss.str());
      }
    }
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"merge")==0) {
    // Merge functions with too big overlap

    if(argc!=5) {
      printf("\nUsage: %s input.gbs merge cutoff output.gbs\n",argv[0]);
      return 1;
    }

    // Cutoff value
    double cutoff=atof(argv[3]);
    bas.merge(cutoff);
    bas.save_gaussian94(argv[4]);

  } else if(stricmp(cmd,"norm")==0) {
    // Normalize basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs norm output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.normalize();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"orth")==0) {
    // Orthogonalize basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs orth output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.orthonormalize();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"overlap")==0) {
    // Primitive overlap

    if(argc!=4) {
      printf("\nUsage: %s input.gbs overlap element\n",argv[0]);
      return 1;
    }

    // Get element basis set
    ElementBasisSet elbas=bas.get_element(argv[3]);
    elbas.decontract();

    // Loop over angular momentum
    for(int am=0;am<=elbas.get_max_am();am++) {
      // Get primitives
      arma::vec exps;
      arma::mat contr;
      elbas.get_primitives(exps,contr,am);

      // Compute overlap matrix
      arma::mat S=overlap(exps,exps,am);

      // Print out overlap
      printf("*** %c shell ***\n",shell_types[am]);
      exps.t().print("Exponents");
      printf("\n");

      S.print("Overlap");
      printf("\n");
    }

  } else if(stricmp(cmd,"Porth")==0) {
    // P-orthogonalize basis

    if(argc!=6) {
      printf("\nUsage: %s input.gbs Porth cutoff Cortho output.gbs\n",argv[0]);
      return 1;
    }

    double cutoff=atof(argv[3]);
    double Cortho=atof(argv[4]);
    std::string fileout=argv[5];
    bas.P_orthogonalize(cutoff,Cortho);
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"prodset")==0) {
    // Generate product set
    
    if(argc!=6) {
      printf("\nUsage: %s input.gbs prodset lval fsam output.gbs\n",argv[0]);
      return 1;
    }

    int lval(atoi(argv[3]));
    double fsam(atof(argv[4]));
    std::string fileout(argv[5]);
    BasisSetLibrary dfit(bas.product_set(lval,fsam));
    dfit.save_gaussian94(fileout);
    
  } else if(stricmp(cmd,"save")==0) {
    // Save basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs save output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"savecfour")==0) {
    // Save basis in CFOUR format

    if(argc!=5) {
      printf("\nUsage: %s input.gbs savecfour name basis.cfour\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    std::string name=argv[4];
    bas.save_cfour(name,fileout);

  } else if(stricmp(cmd,"savedalton")==0) {
    // Save basis in Dalton format

    if(argc!=4) {
      printf("\nUsage: %s input.gbs savedalton output.dal\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_dalton(fileout);

  } else if(stricmp(cmd,"savemolpro")==0) {
    // Save basis in Molpro format

    if(argc!=4) {
      printf("\nUsage: %s input.gbs savemolpro output.mol\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_molpro(fileout);

  } else if(stricmp(cmd,"sort")==0) {
    // Sort basis set

    if(argc!=4) {
      printf("\nUsage: %s input.gbs sort output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.sort();
    bas.save_gaussian94(fileout);
  } else {
    printf("\nInvalid command.\n");

    help();
  }

  return 0;
}