void calcEscaleSystematics(TString lumiTag="DY_j22_19712pb", 
int saveTexTable=0){

  int nUnfoldingBins = DYTools::getTotalNumberOfBins();
  TVectorD observedYields(nUnfoldingBins);
  TVectorD observedYieldsErr(nUnfoldingBins);
  TVectorD dummyArr(nUnfoldingBins);
  TVectorD unfoldedYields(nUnfoldingBins);

  // 
  // Indicators (and also counters) whether the data was present
  //
  int countEScaleSyst=0;
  int countResidualShape=0;
  int countEtaSyst=0;
  int countFittingShape=0;
  std::vector<TString> usedFiles;

  ElectronEnergyScale escale("Date20120802_default");

  //
  // Calculate error associated with statistical 
  // uncertainty on the energy scale factors
  //
  TVectorD unfoldedYieldsMean(nUnfoldingBins);
  TVectorD unfoldedYieldsRMS(nUnfoldingBins);
  TVectorD unfoldedYieldsSquaredMean(nUnfoldingBins);

  unfoldedYieldsMean = 0;
  unfoldedYieldsRMS = 0;
  unfoldedYieldsSquaredMean = 0;

  TString matrixFileName = TString("../root_files/constants/") + lumiTag + 
    TString("/detResponse_unfolding_constants") + DYTools::analysisTag + TString("_PU.root");
  const int nFiles1 = 20;  // expected number of files
  if (1)
  for(int ifile=0; ifile<nFiles1; ifile++){
    int seed = 1001+ifile;
    escale.randomizeEnergyScaleCorrections(seed);
    TString fname = TString("../root_files/yields/") + lumiTag + 
      TString("_escale_randomized/yields_bg-subtracted") + DYTools::analysisTag + 
      TString("__") + escale.calibrationSetShortName();
    fname += ".root";
    TFile file(fname);
    if (!file.IsOpen()) {
      std::cout << "failed to open a file <" << fname << ">\n";
    }
    else {
      file.Close();

      // register
      usedFiles.push_back(fname);
      // work with data
      int res=	(readData(fname, observedYields,observedYieldsErr,dummyArr) == 1)
	&& (applyUnfoldingLocal(observedYields,unfoldedYields,matrixFileName) == 1);
      if (res==1) {
	countEScaleSyst++;
	//std::cout << "unfoldedYields for seed=" << seed << ": "; unfoldedYields.Print();
	// Accumulate mean and RMS
	for(int idx = 0; idx < nUnfoldingBins; idx++){
	  unfoldedYieldsMean[idx] += unfoldedYields[idx];
	  unfoldedYieldsSquaredMean[idx] += unfoldedYields[idx]*unfoldedYields[idx];
	}
      }
    }
  }

  // Final calculation of the mean and RMS for Smearing
  TVectorD escaleRandomizedSystRelative(nUnfoldingBins);
  if (countEScaleSyst) {
    for(int idx = 0; idx < nUnfoldingBins; idx++){
      unfoldedYieldsMean[idx] = unfoldedYieldsMean[idx]/double(countEScaleSyst);
      unfoldedYieldsSquaredMean[idx] = unfoldedYieldsSquaredMean[idx]/double(countEScaleSyst);
      unfoldedYieldsRMS[idx] = sqrt(unfoldedYieldsSquaredMean[idx] - 
				  unfoldedYieldsMean[idx]*unfoldedYieldsMean[idx]);
      escaleRandomizedSystRelative[idx] = unfoldedYieldsRMS[idx]/unfoldedYieldsMean[idx];
    }
    //std::cout << "unfoldedYieldsMean=" << ": "; unfoldedYieldsMean.Print();
    //std::cout << "escaleRandomizedSystRelative: "; escaleRandomizedSystRelative.Print();
  }
  else {
    std::cout << "escaleRandomizomized files were not found\n";
  }

  //
  // Calculate error related to the difference between
  // data and MC mass distribution shape after all corrections
  // had been applied to data and MC. "Residual differences"
  //
  TVectorD unfoldedYieldsVariation(nUnfoldingBins);
  TVectorD escaleResidualDiffSystRelative(nUnfoldingBins);
  TString fname = TString("../root_files/yields/") + lumiTag + 
    TString("/yields_bg-subtracted") + DYTools::analysisTag + TString(".root");
  int res=1;
  {
  TFile file(fname);
  if (file.IsOpen()) {
    file.Close();
    if (readData(fname,observedYields,observedYieldsErr,dummyArr) != 1) {
      std::cout << "failed to get data from file <" << fname << ">\n";
      throw 2;
    }
  //
    matrixFileName = TString("../root_files/constants/") + lumiTag + 
      TString("/detResponse_unfolding_constants") + DYTools::analysisTag + TString("_PU.root");
    res=applyUnfoldingLocal(observedYields, unfoldedYields, matrixFileName);
    if (res==1) usedFiles.push_back(matrixFileName);

  //
    if (res==1) {
      matrixFileName = TString("../root_files/constants/") + lumiTag + 
	TString("_escale_residual/unfolding_constants") + DYTools::analysisTag +
	TString("_escaleResidual.root");
      res=applyUnfoldingLocal(observedYields, unfoldedYieldsVariation, matrixFileName);
      if (res==1) {
	countResidualShape++;
	usedFiles.push_back(matrixFileName);
      }
    }
  }
  if (res==1) {
    for(int idx=0; idx<nUnfoldingBins; idx++){
      escaleResidualDiffSystRelative[idx] = 
	fabs(unfoldedYields[idx] - unfoldedYieldsVariation[idx])
	/(unfoldedYields[idx] + unfoldedYieldsVariation[idx]);
    }
  }
  }

  //
  // Calculate error related to extra smearing function shape
  //
  std::vector<TString> shapeNames;
  shapeNames.push_back("_6binNegs_BreitWigner_20120802");
  shapeNames.push_back("_6binNegs_Voigtian_20120802");
  std::vector<TVectorD*> unfoldedYieldsShape;
  if (1)
  for (unsigned int i=0; i<shapeNames.size(); ++i) {
    TVectorD observedYieldsShape(nUnfoldingBins);
    TVectorD observedYieldsShapeErr(nUnfoldingBins);
    TString shapeFName=TString("../root_files/yields/") + lumiTag + 
      TString("_escale_shape/yields_bg-subtracted") + DYTools::analysisTag +
      TString("_") + shapeNames[i] + TString(".root");
    TFile fShape(shapeFName);
    if (fShape.IsOpen()) {
      fShape.Close();
      usedFiles.push_back(shapeFName);
      if ( readData(shapeFName,observedYieldsShape,observedYieldsShapeErr,dummyArr) !=1) {
	std::cout << "failed to load data from <" << shapeFName << ">\n";
	throw 2;
      }
      TString matrixFileNameShape = TString("../root_files/constants/") + lumiTag + 
	TString("_escale_shape/unfolding_constants") + DYTools::analysisTag +
	TString("_") + shapeNames[i] + TString(".root");
      TVectorD *shapeYields=new TVectorD(nUnfoldingBins);
      {
	TFile ftmp(TString("tmp_") + shapeNames[i] + TString(".root"),"recreate");
	observedYieldsShape.Write("YieldsSignal");
	TVectorD tmp(nUnfoldingBins);
	tmp=0;
	tmp.Write("YieldsSignalErr");
	tmp.Write("YieldsSignalSystErr");
	ftmp.Close();
      }
      res=applyUnfoldingLocal(observedYieldsShape, *shapeYields, matrixFileNameShape);
      if (res) {
	countFittingShape++;
	usedFiles.push_back(matrixFileNameShape);
	unfoldedYieldsShape.push_back(shapeYields);
      }
      else delete shapeYields;
    }
  }
  
  //
  TVectorD escaleFitShapeSystRelative(nUnfoldingBins);
  for(int idx=0; idx<nUnfoldingBins; idx++){
    double min = unfoldedYields[idx];
    double max = unfoldedYields[idx];
    for (unsigned int iShape=0; iShape<unfoldedYieldsShape.size(); ++iShape) {
      min = TMath::Min( min, (*unfoldedYieldsShape[iShape])[idx] );
      max = TMath::Max( max, (*unfoldedYieldsShape[iShape])[idx] );
    }
    escaleFitShapeSystRelative[idx] = fabs(max-min)/(max+min);
  }

  //
  // Calculate error related to eta binning
  //
  std::vector<TString> etaBinNames;
  etaBinNames.push_back("_2binNegs_Gauss_20120802");
  etaBinNames.push_back("_3EB3EENegs_Gauss_20120802");
  etaBinNames.push_back("_4binNegs_Gauss_20120802");
  etaBinNames.push_back("_4EB3EENegs_Gauss_20120802");
  etaBinNames.push_back("_5binNegs_Gauss_20120802");
  etaBinNames.push_back("_6binNegs_Gauss_20120802"); // default
  etaBinNames.push_back("_6bins_Gauss_20120802");
  std::vector<TVectorD*> unfoldedYieldsEta;
  unfoldedYieldsEta.reserve(etaBinNames.size());
  if (1)
  for (unsigned int i=0; i<etaBinNames.size(); ++i) {
    TString fEtaFileName=TString("../root_files/yields/") + lumiTag + 
      TString("_escale_eta/yields_bg-subtracted") + DYTools::analysisTag +
      TString("_") + etaBinNames[i] + TString(".root");
    TFile fEta(fEtaFileName);
    if (fEta.IsOpen()) {
      fEta.Close();
      usedFiles.push_back(fEtaFileName);
      TVectorD observedYieldsEta(nUnfoldingBins);
      TVectorD observedYieldsEtaErr(nUnfoldingBins);
      if (readData(fEtaFileName,observedYieldsEta,observedYieldsEtaErr,dummyArr)!=1) {
	std::cout << "failed to get info from <" << fEtaFileName << ">\n";
	throw 2;
      }
      matrixFileName = TString("../root_files/constants/") + lumiTag + 
	TString("_escale_eta/unfolding_constants") + DYTools::analysisTag +
	TString("_") + etaBinNames[i] + TString(".root");
      TVectorD *unfYields = new TVectorD(nUnfoldingBins);
      res=applyUnfoldingLocal(observedYieldsEta, *unfYields, matrixFileName);
      if (res==1) {
	countEtaSyst++;
	usedFiles.push_back(matrixFileName);
	unfoldedYieldsEta.push_back(unfYields);
      }
      else {
	delete unfYields;
      }
    }
  }

  //
  TVectorD escaleEtaBinSystRelative(nUnfoldingBins);
  for(int idx=0; idx<nUnfoldingBins; idx++){
    double min = unfoldedYields[idx];
    double max = unfoldedYields[idx];
    for (unsigned int iShape=0; iShape<unfoldedYieldsEta.size(); ++iShape) {
      min = TMath::Min( min, (*unfoldedYieldsEta[iShape])[idx] );
      max = TMath::Max( max, (*unfoldedYieldsEta[iShape])[idx] );
    }
    escaleEtaBinSystRelative[idx] = fabs(max-min)/(max+min);
  }

  // 
  // Put all errors together
  //
  TVectorD escaleSystPercent(nUnfoldingBins);
  for(int idx = 0; idx < nUnfoldingBins; idx++){
    escaleSystPercent[idx] = 100.0 *
      sqrt(
	   escaleRandomizedSystRelative[idx]*escaleRandomizedSystRelative[idx]
	   + escaleResidualDiffSystRelative[idx]*escaleResidualDiffSystRelative[idx]
	   + escaleFitShapeSystRelative[idx]*escaleFitShapeSystRelative[idx]
	   + escaleEtaBinSystRelative[idx]*escaleEtaBinSystRelative[idx]
	   );
  }

  // Don't write TObject part of the objects
  TDescriptiveInfo_t::Class()->IgnoreTObjectStreamer();
  TDescriptiveInfo_t *info= new TDescriptiveInfo_t();
  std::vector<std::string> *lines = (info) ? (& info->_info) : NULL;

  const int bufsize=300;
  char buf[bufsize];
  std::string sbuf;


  snprintf(buf,bufsize," Summary of successful loads:\n");
  printf(buf);
  if (lines) lines->push_back(buf);
  snprintf(buf,bufsize,"  escale systematics   file count=  %2d\n", countEScaleSyst);
  printf(buf);
  if (lines) lines->push_back(buf);
  snprintf(buf,bufsize,"  residual shape syst. file count=  %2d\n", countResidualShape);
  printf(buf);
  if (lines) lines->push_back(buf);
  snprintf(buf,bufsize,"  eta systematics      file count=  %2d\n", countEtaSyst);
  printf(buf);
  if (lines) lines->push_back(buf);
  snprintf(buf,bufsize,"  fitting shape        file count=  %2d\n", countFittingShape);
  printf(buf);
  if (lines) { lines->push_back(buf); lines->push_back("\n"); }
  std::cout << "\n";

  int listFilesOnScreen=1;
  snprintf(buf,bufsize," Loaded files:\n");
  if (listFilesOnScreen) printf(buf);
  if (lines) lines->push_back(buf);
  for (unsigned int i=0; i<usedFiles.size(); ++i) {
    snprintf(buf,bufsize," %s\n",usedFiles[i].Data());
    if (listFilesOnScreen) printf(buf);
    if (lines) lines->push_back(buf);
  }
  std::cout << std::endl;


  if (saveTexTable) {
    std::vector<TString> headers;
    std::vector<int> padding;
    std::vector<TVectorD*> data;
    std::vector<double> factors;
    headers.push_back("mass range");
    headers.push_back("rapidity range");
    headers.push_back("\\multicolumn{1}{c|}{statistical, \\%}"); data.push_back(&escaleRandomizedSystRelative); factors.push_back(100.); padding.push_back(6);
    headers.push_back("\\multicolumn{1}{c|}{shape, \\%}"); data.push_back(&escaleFitShapeSystRelative); factors.push_back(100.); padding.push_back(4);
    headers.push_back("\\multicolumn{1}{c|}{residual, \\%}"); data.push_back(&escaleResidualDiffSystRelative); factors.push_back(100.); padding.push_back(5);
    headers.push_back("\\multicolumn{1}{c|}{$\\eta$ binning, \\%}"); data.push_back(&escaleEtaBinSystRelative); factors.push_back(100.); padding.push_back(6);
    headers.push_back("\\multicolumn{1}{c|}{total, \\%}"); data.push_back(&escaleSystPercent); factors.push_back(1.); padding.push_back(3);
    
    TString texFName=TString("../root_files/systematics/") + lumiTag + 
      TString("/escale_systematics") + DYTools::analysisTag + TString("_tmp.tex");
    printTexTable(texFName,headers,padding,data,factors);
  }

  TString finalFName=TString("../root_files/systematics/") + lumiTag + 
    TString("/escale_systematics") + DYTools::analysisTag + TString("_tmp.root");
  TFile fout(finalFName,"recreate");
  unfolding::writeBinningArrays(fout);
  escaleRandomizedSystRelative.Write("escaleRandomizedSystRelativeFI");
  escaleFitShapeSystRelative.Write("escaleFitShapeSystRelativeFI");
  escaleResidualDiffSystRelative.Write("escaleResidualDiffSystRelativeFI");
  escaleEtaBinSystRelative.Write("escaleEtaBinSystRelativeFI");
  escaleSystPercent.Write("escaleSystPercentFI");

  if (info) {
    TTree *infoTree = new TTree("Description","description");
    infoTree->Branch("description","TDescriptiveInfo_t",&info);
    infoTree->Fill();
    infoTree->Write();
  }
  fout.Close();

  return;
}
void VoiceActingManager::OnGenerateScript()
{
	int i;
	char pathname[256];

	// stuff data to variables
	UpdateData(TRUE);

	// prompt to save script
	CFileDialog dlg(FALSE, "txt", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Text files (*.txt)|*.txt||");
	if (dlg.DoModal() != IDOK)
		return;

	string_copy(pathname, dlg.GetPathName(), 256);
	fp = cfopen(pathname, "wt", CFILE_NORMAL);
	if (!fp)
	{
		MessageBox("Can't open file to save.", "Error!");
		return;
	}

	fout("%s\n", Mission_filename);
	fout("%s\n\n", The_mission.name);

	if (m_export_everything || m_export_command_briefings)
	{
		fout("\n\nCommand Briefings\n-----------------\n\n");

		for (i = 0; i < Cmd_briefs[0].num_stages; i++)
		{
			CString entry = m_script_entry_format;
			entry.Replace("\r\n", "\n");

			cmd_brief_stage *stage = &Cmd_briefs[0].stage[i];
			entry.Replace("$filename", stage->wave_filename);
			entry.Replace("$message", stage->text);
			entry.Replace("$persona", "<no persona specified>");
			entry.Replace("$sender", "<no sender specified>");

			fout("%s\n\n\n", (char *) (LPCTSTR) entry);
		}
	}

	if (m_export_everything || m_export_briefings)
	{
		fout("\n\nBriefings\n---------\n\n");

		for (i = 0; i < Briefings[0].num_stages; i++)
		{
			CString entry = m_script_entry_format;
			entry.Replace("\r\n", "\n");

			brief_stage *stage = &Briefings[0].stages[i];
			entry.Replace("$filename", stage->voice);
			entry.Replace("$message", stage->new_text);
			entry.Replace("$persona", "<no persona specified>");
			entry.Replace("$sender", "<no sender specified>");

			fout("%s\n\n\n", (char *) (LPCTSTR) entry);
		}
	}

	if (m_export_everything || m_export_debriefings)
	{
		fout("\n\nDebriefings\n-----------\n\n");

		for (i = 0; i < Debriefings[0].num_stages; i++)
		{
			CString entry = m_script_entry_format;
			entry.Replace("\r\n", "\n");

			debrief_stage *stage = &Debriefings[0].stages[i];
			entry.Replace("$filename", stage->voice);
			entry.Replace("$message", stage->new_text);
			entry.Replace("$persona", "<no persona specified>");
			entry.Replace("$sender", "<no sender specified>");
	
			fout("%s\n\n\n", (char *) (LPCTSTR) entry);
		}
	}

	if (m_export_everything || m_export_messages)
	{
		fout("\n\nMessages\n--------\n\n");

		for (i = 0; i < Num_messages - Num_builtin_messages; i++)
		{
			CString entry = m_script_entry_format;
			entry.Replace("\r\n", "\n");

			MMessage *message = &Messages[i + Num_builtin_messages];
			entry.Replace("$filename", message->wave_info.name);
			entry.Replace("$message", message->message);
			if (message->persona_index >= 0)
				entry.Replace("$persona", Personas[message->persona_index].name);
			else
				entry.Replace("$persona", "<none>");
			entry.Replace("$sender", get_message_sender(message->name));
	
			fout("%s\n\n\n", (char *) (LPCTSTR) entry);
		}
	}

	cfclose(fp);

	// notify
	MessageBox("Script generation complete.", "Woohoo!");
}
Example #3
0
bool MomentumEstimator::putSpecial(xmlNodePtr cur, ParticleSet& elns, bool rootNode)
{
    OhmmsAttributeSet pAttrib;
    string hdf5_flag="yes";
    pAttrib.add(hdf5_flag,"hdf5");
    pAttrib.add(M,"samples");
    pAttrib.put(cur);
    hdf5_out = (hdf5_flag=="yes");



    xmlNodePtr kids=cur->children;
    while (kids!=NULL)
    {
        string cname((const char*)(kids->name));
        if (cname=="kpoints")
        {
            string ctype("manual");
            OhmmsAttributeSet pAttrib;
            pAttrib.add(ctype,"mode");
            pAttrib.add(kgrid,"grid");
            pAttrib.put(kids);

            int numqtwists(6*kgrid+3);
            std::vector<int> qk(0);
            mappedQtonofK.resize(numqtwists,qk);
            compQ.resize(numqtwists);

            RealType qn(4.0*M_PI*M_PI*std::pow(Lattice.Volume,-2.0/3.0));
            mappedQnorms.resize(numqtwists,qn*0.5/RealType(M));
            if (twist[0]==0) mappedQnorms[kgrid]=qn/RealType(M);
            if (twist[1]==0) mappedQnorms[3*kgrid+1]=qn/RealType(M);
            if (twist[2]==0) mappedQnorms[5*kgrid+2]=qn/RealType(M);

//             app_log()<<" Jnorm="<<qn<<endl;
            Q.resize(numqtwists);
            for (int i=-kgrid; i<(kgrid+1); i++)
            {
                PosType kpt;
                kpt[0]=i-twist[0];
                kpt[1]=i-twist[1];
                kpt[2]=i-twist[2];
                kpt=Lattice.k_cart(kpt);
                Q[i+kgrid]=abs(kpt[0]);
                Q[i+kgrid+(2*kgrid+1)]=abs(kpt[1]);
                Q[i+kgrid+(4*kgrid+2)]=abs(kpt[2]);
            }

            app_log()<<" Using all k-space points with (nx^2+ny^2+nz^2)^0.5 < "<< kgrid <<" for Momentum Distribution."<<endl;
            app_log()<<"  My twist is:"<<twist[0]<<"  "<<twist[1]<<"  "<<twist[2]<<endl;

            int indx(0);
            for (int i=-kgrid; i<(kgrid+1); i++)
            {
                for (int j=-kgrid; j<(kgrid+1); j++)
                {
                    for (int k=-kgrid; k<(kgrid+1); k++)
                    {
                        if (std::sqrt(i*i+j*j+k*k)<=kgrid)
                        {
                            PosType kpt;
                            kpt[0]=i-twist[0];
                            kpt[1]=j-twist[1];
                            kpt[2]=k-twist[2];

                            //convert to Cartesian: note that 2Pi is multiplied
                            kpt=Lattice.k_cart(kpt);
                            kPoints.push_back(kpt);

                            mappedQtonofK[i+kgrid].push_back(indx);
                            mappedQtonofK[j+kgrid+(2*kgrid+1)].push_back(indx);
                            mappedQtonofK[k+kgrid+(4*kgrid+2)].push_back(indx);
                            indx++;
                        }
                    }
                }
            }
        }

        kids=kids->next;
    }
    if (rootNode)
    {
        std::stringstream sstr;
        int t0=(int)round(100.0*twist[0]);
        int t1=(int)round(100.0*twist[1]);
        int t2=(int)round(100.0*twist[2]);
        sstr<<"Kpoints."<<t0<<"_"<<t1<<"_"<<t2<<".dat";
        ofstream fout(sstr.str().c_str());
        fout.setf(ios::scientific, ios::floatfield);
        fout << "# mag_k        kx           ky            kz " << endl;
        for (int i=0; i<kPoints.size(); i++)
        {
            float khere(std::sqrt(dot(kPoints[i],kPoints[i])));
            fout<<khere<<"   "<<kPoints[i][0]<<"    "<<kPoints[i][1]<<"    "<<kPoints[i][2]
                <<endl;
        }
        fout.close();
        sstr.str("");
        sstr<<"Qpoints."<<t0<<"_"<<t1<<"_"<<t2<<".dat";
        ofstream qout(sstr.str().c_str());
        qout.setf(ios::scientific, ios::floatfield);
        qout << "# mag_q" << endl;
        for (int i=0; i<Q.size(); i++)
        {
            qout<<Q[i]<<endl;
        }
        qout.close();
    }

    nofK.resize(kPoints.size());
    norm_nofK=1.0/RealType(M);

    return true;
}
Example #4
0
    bool save_zoltan_hypergraph_structure(const std::string& filename,
                                          const graphlab::local_graph<VertexType, EdgeType>& graph) {
      typedef graphlab::local_graph<VertexType, EdgeType> graph_type;
      typedef typename graph_type::edge_type          edge_type;
      typedef typename graph_type::edge_list_type     edge_list_type;

      std::ofstream fout(filename.c_str());
      if(!fout.good()) return false;

      // ok. I need to uniquely number each edge.
      // how?
      boost::unordered_map<std::pair<vertex_id_type, 
        vertex_id_type>, size_t> edgetoid;
      size_t curid = 0;
      for(vertex_id_type i = 0; i < graph.num_vertices(); ++i) {
        foreach(const typename graph_type::edge_type& edge, graph.in_edges(i)) {
          std::pair<vertex_id_type, vertex_id_type> e = 
            std::make_pair(edge.source(), edge.target());
          if (e.first > e.second) std::swap(e.first, e.second);
          if (edgetoid.find(e) == edgetoid.end()) {
            edgetoid[e] = curid;
            ++curid;
          }
        }
        foreach(const typename graph_type::edge_type& edge, graph.out_edges(i)) {
          std::pair<vertex_id_type, vertex_id_type> e = 
            std::make_pair(edge.source(), edge.target());
          if (e.first > e.second) std::swap(e.first, e.second);
          if (edgetoid.find(e) == edgetoid.end()) {
            edgetoid[e] = curid;
            ++curid;
          }
        }
      }

      size_t numedges = curid;
      // each edge is a vertex, each vertex is an edge
      // a pin is total adjacency of a hyper edge
      fout << numedges << "\n\n";
      for (size_t i = 0;i < numedges; ++i) {
        fout << i+1 << "\n";
      }
      fout << "\n";
      fout << graph.num_vertices() << "\n\n";
      
      fout << numedges * 2 << "\n\n";
      // loop over the "hyperedge" and write out the edges it is adjacent to
      for(vertex_id_type i = 0; i < graph.num_vertices(); ++i) {
        boost::unordered_set<size_t> adjedges;
        foreach(const typename graph_type::edge_type& edge, graph.in_edges(i)) {
          std::pair<vertex_id_type, vertex_id_type> e = 
            std::make_pair(edge.source(), edge.target());
          if (e.first > e.second) std::swap(e.first, e.second);
          adjedges.insert(edgetoid[e]);
        }
        foreach(const typename graph_type::edge_type& edge, graph.out_edges(i)) {
          std::pair<vertex_id_type, vertex_id_type> e = 
            std::make_pair(edge.source(), edge.target());
          if (e.first > e.second) std::swap(e.first, e.second);
          adjedges.insert(edgetoid[e]);
        }
        // write
        std::vector<size_t> adjedgesvec;
        std::copy(adjedges.begin(), adjedges.end(), 
                  std::inserter(adjedgesvec, adjedgesvec.end()));
        fout << i+1 << " " << adjedgesvec.size() << "\t";        
        for (size_t j = 0;j < adjedgesvec.size(); ++j) {
          fout << adjedgesvec[j] + 1;
          if (j < adjedgesvec.size() - 1) fout << "\t";
        }
        fout << "\n";
      }
      fout.close();
      return true;
    }  // end of save_zoltan_hypergraph_structure
Example #5
0
int main(int argc, char * argv[])
{
	XMLNode xMainNode = XMLNode::openFileHelper(argv[1], "score-partwise");
	std::string filename = (std::string) argv[2];
	std::ofstream fout(filename);
	int n_measures = std::stoi(argv[3]);
	// note_count records relative frequency of each pitch bar-by-bar
	// notes related by octaves considered equivalent
	// C natural is 0
	// each half step increments by 1
	// quarter note has weight 1
	double note_count[n_measures][12];
	for(int i=0; i< 12; i++){
		for(int j = 0; j < n_measures;j++)
		{
			note_count[j][i]=0;
		}
	}
	
	//count bars starting from 0
	int num_notes;
	
	int num_parts = xMainNode.nChildNode("part");
	int k =0;
	// if score is written with multiple parts, loop over parts
	while(k < num_parts){
		XMLNode partNode = xMainNode.getChildNode("part", k);

		for(int current_meas = 0; current_meas < n_measures; current_meas++)
		{
			XMLNode mNode = partNode.getChildNode("measure",current_meas);
			XMLNode attNode = mNode.getChildNode("attributes");
			XMLNode dNode;
			if(!attNode.isEmpty())
				dNode = attNode.getChildNode("divisions");
			// divisions counts number of sub-beats in each beat
			double divisions;
			if(!dNode.isEmpty())
			{
				// is there a better way to read from xmlParser
				// than reading strings first and converting to numbers?
				std::string st = (std::string) dNode.getText();
				// note we use double because we want to do division later
				divisions = std::stof(st);
			}
			num_notes = mNode.nChildNode("note");
			
			
			//loop over notes
			for(int i = 0; i < num_notes; i++)
			{
				XMLNode nNode = mNode.getChildNode("note",i);
				XMLNode pitchNode = nNode.getChildNode("pitch");
				// ignores grace notes (for now)
				if(!pitchNode.isEmpty() && nNode.getChildNode("grace").isEmpty())
				{
					// XML records notes by letter
					char ch = *(pitchNode.getChildNode("step").getText());
					// convert letter to number
					int note_val = note_to_int(ch);
					// take accidentals into account
					XMLNode aNode = pitchNode.getChildNode("alter");
					if(!aNode.isEmpty()){
						std::string alt_str = (std::string) aNode.getText();
						note_val += std::stoi(alt_str);
						note_val %= 12;
					}
					XMLNode durNode = nNode.getChildNode("duration");
					std::string dur_str = (std::string) durNode.getText();
					double duration = std::stof(dur_str)/divisions;
					note_count[current_meas][note_val] += duration;
				}
			}
		}
		k++;
	}
	
	for(int j = 0;j < n_measures; j++)
	{
		for(int i = 0; i < 12; i++){
			if(note_count[j][i] < 0.0001)
				note_count[j][i] = 0;
			fout <<note_count[j][i] << " \t";
		}
		fout << std::endl;
	}
	fout.close();

	return 0;
}
/**
 * \brief     Conversion function
 * \param[in] chInputFile Input file name to convert from
 * \param[in] chOutputFile Output file name to convert to
 * \return    Result code
 *
 * This is the actual conversion function with input and output file name.
 */
HRESULT CBlfLogConverter::ConvertFile(string& chInputFile, string& chOutputFile)
{
    HRESULT hResult = S_OK;

    try
    {
        bool isOk = true;

        // Create BLF Library interface
        BLF::IBlfLibrary* pBlfLib = BLF::GetIBlfLibrary();
        isOk = (NULL != pBlfLib);
        if (!isOk)
        {
            m_omstrConversionStatus = _("Unable to get BLF Library interface");
            m_hResult = ERR_UNABLE_TO_GET_LIB_INTERFACE;
            return ERR_UNABLE_TO_GET_LIB_INTERFACE;
        }

        // Load BLF file
        CBlfLibraryKeeper blfKeeper(pBlfLib);
        HRESULT hResult = pBlfLib->Load(chInputFile);

        if (hResult != S_OK)
        {
            m_omstrConversionStatus = _("Error: Invalid BLF file");
            m_hResult = hResult;
            return hResult;
        }

        std::ofstream fout(chOutputFile.c_str());
        // Let the output stream to throw exception on errors
        fout.exceptions(std::ifstream::failbit | std::ifstream::badbit);
        if (!fout.is_open())
        {
            m_omstrConversionStatus = _("Output File path is not found");
            m_hResult = ERR_OUTPUT_FILE_NOTFOUND;
            return ERR_OUTPUT_FILE_NOTFOUND;
        }

        HRESULT hRes = WriteToLog(pBlfLib, fout);
        if (!SUCCEEDED(hRes))
        {
            if(hRes == ERR_PROTOCOL_NOT_SUPPORTED)
            {
                m_omstrConversionStatus = _("Error: No CAN data found for conversion.");
                m_hResult = ERR_PROTOCOL_NOT_SUPPORTED;
                return ERR_PROTOCOL_NOT_SUPPORTED;
            }
            else
            {
                m_omstrConversionStatus = _("Error: Unable to convert file.");
                m_hResult = ERR_OUTPUT_FILE_NOTFOUND;
                return ERR_OUTPUT_FILE_NOTFOUND;
            }
        }
    }
    catch (std::ifstream::failure& e)
    {
        // Process output stream errors (like not enough disk space)
        m_omstrConversionStatus = _("Error while writing output file.");
        m_hResult = E_FAIL;
        return E_FAIL;
    }
    catch (const std::exception& e)
    {
        // Process critical error
        m_omstrConversionStatus = e.what();
        m_hResult = E_FAIL;
        return E_FAIL;
    }

    m_omstrConversionStatus = _("Conversion Completed Successfully");
    m_hResult = hResult;
    return hResult;
}
void user_settings_io::export_settings(const std::string& output_dir)
{
  if(!settings_file_name_.empty())
  {
    namespace fs = boost::filesystem;
    std::string config_dir = output_dir + "/config";
    fs::path out_path(config_dir);
    fs::create_directory(out_path);

    YAML::Emitter out;
    out << YAML::BeginMap;
    out << YAML::Key << usc::fs;
    out << YAML::Value << settings_.get_fs();

    out << YAML::Key << usc::forces_dynamic;
    out << YAML::Value << settings_.get_forces_dynamic();

    out << YAML::Key << usc::excitation_time_step;
    out << YAML::Value << settings_.get_excitation_time_step();

    out << YAML::Key << usc::excitation_time;
    out << YAML::Value << settings_.get_excitation_time();

    out << YAML::Key << usc::rtss::self;
    out << YAML::BeginMap;
    out << YAML::Key << usc::rtss::initial_step;
    out << YAML::Value << settings_.get_relaxation_time_step_spec().initial_step;
    out << YAML::Key << usc::rtss::time_delta;
    out << YAML::Value << settings_.get_relaxation_time_step_spec().time_delta;
    out << YAML::Key << usc::rtss::coefficient;
    out << YAML::Value << settings_.get_relaxation_time_step_spec().coefficient;
    out << YAML::EndMap;

    out << YAML::Key << usc::simulations_count;
    out << YAML::Value << settings_.get_simulations_count();

    out << YAML::Key << usc::visualization_nodes;
    out << YAML::Value << YAML::BeginSeq;
    const auto& vis_nodes = settings_.get_visualization_nodes();
    for(auto it = vis_nodes.begin(); it != vis_nodes.end(); ++it)
    {
      out << *it;
    }
    out << YAML::EndSeq;

    if(!settings_.get_force_application_nodes().empty())
    {
      out << YAML::Key << usc::force_application_nodes;
      out << YAML::Value << YAML::BeginSeq;
      const auto& force_nodes = settings_.get_force_application_nodes();
      for(auto it = force_nodes.begin(); it != force_nodes.end(); ++it)
      {
        out << *it;
      }
      out << YAML::EndSeq;
    }

    if(settings_.get_cutoff_distance())
    {
      out << YAML::Key << usc::l0;
      out << YAML::Value << *settings_.get_cutoff_distance();
    }
    if(!settings_.get_network_file_path())
    {
      if(settings_.get_node_positions())
      {
        out << YAML::Key << usc::nodes;
        const node_positions_type& node_positions = *settings_.get_node_positions();
        out << YAML::Value << YAML::BeginSeq;
        for(auto it = node_positions.begin(); it != node_positions.end(); ++it)
        {
          out << YAML::BeginSeq;
          out << (*it)[0];
          out << (*it)[1];
          out << (*it)[2];
          out << YAML::EndSeq;
        }
        out << YAML::EndSeq;
      }
      if(settings_.get_links())
      {
        out << YAML::Key << usc::links;
        out << YAML::Value << YAML::BeginSeq;
        const std::vector<std::pair<std::size_t, std::size_t>>& links = *settings_.get_links();
        for(auto it = links.begin(); it != links.end(); ++it)
        {
          out << YAML::BeginSeq << it->first << it->second << YAML::EndSeq;
        }
        out << YAML::EndSeq;
      }
    }
    else
    {
      out << YAML::Key << usc::network_file_path;
      /**
       * @note Output only network file name as it will anyway be copied to the same directory as user config.
       */
      std::string file_name = *settings_.get_network_file_path();
      if(std::string::npos != file_name.find_first_of('/'))
      {
        file_name = file_name.substr(file_name.find_last_of('/')+1);
      }
      out << YAML::Value << file_name;
    }
    out << YAML::EndMap;

    std::ofstream fout(config_dir + "/config.yaml");
    if(!fout.is_open())
    {
      LOG(logger::error, "Cannot create output config file.");
      return;
    }
    fout << out.c_str() << std::endl;
    fout.close();

    if(settings_.get_network_file_path())
    {
      utils::copy_file(*settings_.get_network_file_path(), config_dir);
    }
  }
}
int main(int argc, char **argv)
{
	// run for selected COCO functions
	for(uint function = 1; function < 25; function++) {

		// read XML config
		std::ifstream fin(argv[1]);
		if (!fin) {
			throw std::string("Error opening file! ");
		}

		std::string xmlFile, temp;
		while (!fin.eof()) {
			getline(fin, temp);
			xmlFile += "\n" + temp;
		}
		fin.close();

		// set log and stats parameters
		std::string funcName = uint2str(function);
		std::string logName = "log", statsName = "stats";
		if(function < 10) {
			logName += "0";
			statsName += "0";
		}
		logName += uint2str(function) + ".txt";
		statsName += uint2str(function) + ".txt";

		// update in XML
		XMLResults results;
		XMLNode xConfig = XMLNode::parseString(xmlFile.c_str(), "ECF", &results);
		XMLNode registry = xConfig.getChildNode("Registry");

		XMLNode func = registry.getChildNodeWithAttribute("Entry", "key", "coco.function");
		func.updateText(funcName.c_str());
		XMLNode log = registry.getChildNodeWithAttribute("Entry", "key", "log.filename");
		log.updateText(logName.c_str());
		XMLNode stats = registry.getChildNodeWithAttribute("Entry", "key", "batch.statsfile");
		stats.updateText(statsName.c_str());

		// write back
		std::ofstream fout(argv[1]);
		fout << xConfig.createXMLString(true);
		fout.close();


		// finally, run ECF on single function
		StateP state (new State);

		//set newAlg
		MyAlgP alg = (MyAlgP) new MyAlg;
		state->addAlgorithm(alg);
		// set the evaluation operator
		state->setEvalOp(new FunctionMinEvalOp);

		state->initialize(argc, argv);
		state->run();
	}

	return 0;
}
// print the yields
void CreateCrossSectionTable 
(
    const std::string& label, 
    const std::string& hist_name = "h_reco_full_yield",
    const std::string& output_file = "", 
    bool print_latex = false
)
{
    const double lumi = 0.082; // fb^-1

    // map of samples and yields
    const dy::YieldVector yields = dy::GetYieldVector(label, hist_name);
    const dy::Yield y_data       = yields[dy::Sample::data];
    const dy::Yield y_bk_pred    = dy::GetBackgroundPred(label, hist_name);
    const dy::Yield y_dy_pred    = yields[dy::Sample::dyll];
    const dy::Yield y_mc_pred    = y_dy_pred + y_bk_pred;
    const dy::Yield y_den_acc    = dy::GetYieldFromLabel(dy::Sample::dyll, label, "h_acc_gen_den");
    const dy::Yield y_num_acc    = dy::GetYieldFromLabel(dy::Sample::dyll, label, "h_acc_rec_num");
    const dy::Yield y_acc        = dy::GetYieldFromLabel(dy::Sample::dyll, label, "h_acc_rec");
    const dy::Yield y_nsig       = y_data - y_bk_pred; 

    // xsec = (Nobs - Nbkg)/(lumi * acc)
    dy::Yield xsec = y_nsig/(lumi * y_acc); 
    xsec = xsec * (1e-6); // fb --> nb


    std::string result;
    if (print_latex)
    {
        string latex("\\begin{table}[ht!]\n"                    ); 
        latex.append("\\begin{center}\n"                        ); 
        latex.append("\\begin{tabular}{l|ccc} \\hline\\hline\n" ); 
        latex.append("source & $ee$ & $\\mu\\mu$ \\\\\n"        ); 
        latex.append("\\hline\n"                                ); 
        latex.append(Form("%s \\\\\n", GetLatex("$N_{obs}$" ,    y_data).c_str()));
        latex.append(Form("%s \\\\\n", GetLatex("$N_{mc}$"  , y_mc_pred).c_str()));
        latex.append(Form("%s \\\\\n", GetLatex("$N_{dyll}$", y_dy_pred).c_str()));
        latex.append(Form("%s \\\\\n", GetLatex("$N_{bkgd}$", y_bk_pred).c_str()));
        latex.append(Form("%s \\\\\n", GetLatex("$N_{sig}$" ,    y_nsig).c_str()));
        latex.append(Form("%s \\\\\n", GetLatex("Acc"       ,     y_acc).c_str()));
        latex.append("\\hline\\hline\n");
        latex.append(Form("%s \\\\\n", GetLatex("Sigma (nb)", xsec).c_str()));
        latex.append("\\hline\\hline\n"                              ); 
        latex.append("\\end{tabular}\n"                              ); 
        latex.append("\\caption{Drell-Yan Exercise Cross-Section}\n" ); 
        latex.append("\\end{center}\n"                               ); 
        latex.append("\\end{table}"                                  ); 
        result = latex;
    }
    else
    {
        // make the table
        CTable t_yields;
        t_yields.useTitle();
        t_yields.setTitle("Cross-Sectoin for Drell-Yan Exercise");
        t_yields.setTable()
        (                                  "ee",                    "mm") 
        ("N_obs"       ,    y_data.ee.pm("4.0"),     y_data.mm.pm("4.0")) 
        ("N_mc"        , y_mc_pred.ee.pm("4.1"),  y_mc_pred.mm.pm("4.1")) 
        ("N_dyll"      , y_dy_pred.ee.pm("4.1"),  y_dy_pred.mm.pm("4.1")) 
        ("N_bkgd"      , y_bk_pred.ee.pm("4.1"),  y_bk_pred.mm.pm("4.1")) 
        ("N_sig"       ,    y_nsig.ee.pm("4.1"),     y_nsig.mm.pm("4.1")) 
        ("Num Acc"     , y_num_acc.ee.pm("4.3"),  y_num_acc.mm.pm("4.3")) 
        ("Den Acc"     , y_den_acc.ee.pm("4.3"),  y_den_acc.mm.pm("4.3")) 
        ("Acc"         ,     y_acc.ee.pm("4.3"),      y_acc.mm.pm("4.3")) 
        ("Sigma (nb)"  ,      xsec.ee.pm("4.3"),       xsec.mm.pm("4.3")) 
        ;

        // print it
        std::ostringstream os;
        os << t_yields;
        result = os.str();
    }

    // output
    if (output_file.empty())
    {
        std::cout << result << std::endl;
    }
    else
    {
        std::ofstream fout(output_file);
        fout << result << std::endl;
    }
}
Example #10
0
  bool MSD::ProcessLine()
  {
    cerr << "MSD reordering Step1: generating msd.reordering.model.1" << endl;
    ifstream finsrc(m_src);
    ifstream fintgt(m_tgt);
    ifstream finaln(m_aln);
    string srcline, tgtline, alnline;
    //check validity of input files
    if (!finsrc){
      cerr << "Please check source file: " << m_src << endl;
      return false;
    }
    if (!fintgt){
      cerr << "Please check target file: " << m_tgt << endl;
      return false;
    }
    if (!finaln){
      cerr << "Please check alignment file: " << m_aln << endl;
      return false;
    }
    ofstream fout(m_tmpModel);
    if (!fout){
      cerr << "Couldn't create output file msd.reordering.model.1"
        << endl;
    }
    //start whole process
    int lineNo = 1;
    while (getline(finsrc, srcline)
      && getline(fintgt, tgtline)
      && getline(finaln, alnline)){
      if (lineNo % 10000 == 0){
        cerr << "Processed " << lineNo << " lines." << endl;
      }
      SentnInfo srcsen, tgtsen;
      srcsen.m_words = BasicMethod::Split(srcline);
      tgtsen.m_words = BasicMethod::Split(tgtline);
      srcsen.m_align.assign(srcsen.m_words.size(), vector<size_t>());
      tgtsen.m_align.assign(tgtsen.m_words.size(), vector<size_t>());
      srcsen.m_alnmax.assign(srcsen.m_words.size(), -1);
      tgtsen.m_alnmax.assign(tgtsen.m_words.size(), -1);
      srcsen.m_alnmin.assign(srcsen.m_words.size(), -1);
      tgtsen.m_alnmin.assign(tgtsen.m_words.size(), -1);
      tgtsen.m_ppstart.assign(tgtsen.m_words.size(), vector<MSDPhrasePair*>());
      tgtsen.m_ppend.assign(tgtsen.m_words.size(), vector<MSDPhrasePair*>());

      for (auto& align : BasicMethod::Split(alnline))
      {
        unsigned int srcWordId, tgtWordId;
        //check aligment format
        if (!sscanf_s(align.c_str(), "%d-%d", &srcWordId, &tgtWordId)){
          cerr << "WARNING: " << align << " is a bad aligment point in sentence " << endl
            << "T: " << tgtline << endl << "S: " << srcline << endl;
        }
        //check out of bound case
        if ((size_t)srcWordId >= srcsen.m_words.size() || (size_t)tgtWordId >= tgtsen.m_words.size()){
          cerr << "WARNING: " << align << " out of bounds." << endl
            << "T: " << tgtline << endl << "S: " << srcline << endl;
        }

        srcsen.m_align[srcWordId].push_back(tgtWordId);
        tgtsen.m_align[tgtWordId].push_back(srcWordId);

        if (srcsen.m_alnmax[srcWordId] == -1){
          srcsen.m_alnmax[srcWordId] = tgtWordId;
        }
        else{
          if (tgtWordId > srcsen.m_alnmax[srcWordId]){
            srcsen.m_alnmax[srcWordId] = tgtWordId;
          }
        }
        if (tgtsen.m_alnmax[tgtWordId] == -1){
          tgtsen.m_alnmax[tgtWordId] = srcWordId;
        }
        else{
          if (srcWordId > tgtsen.m_alnmax[tgtWordId]){
            tgtsen.m_alnmax[tgtWordId] = srcWordId;
          }
        }
        if (srcsen.m_alnmin[srcWordId] == -1){
          srcsen.m_alnmin[srcWordId] = tgtWordId;
        }
        else{
          if (tgtWordId < srcsen.m_alnmin[srcWordId]){
            srcsen.m_alnmin[srcWordId] = tgtWordId;
          }
        }
        if (tgtsen.m_alnmin[tgtWordId] == -1){
          tgtsen.m_alnmin[tgtWordId] = srcWordId;
        }
        else{
          if (srcWordId < tgtsen.m_alnmin[tgtWordId]){
            tgtsen.m_alnmin[tgtWordId] = srcWordId;
          }
        }

        srcsen.m_align[srcWordId].push_back(tgtWordId);
        tgtsen.m_align[tgtWordId].push_back(srcWordId);      
      }
      ExtractPhrasePairs(srcsen, tgtsen);
      CalculateMSD(srcsen, tgtsen);
      OutputMSDtemp(tgtsen, fout);
      lineNo++;
    }
    fout.close();
    finsrc.close();
    fintgt.close();
    finaln.close();
  }
Example #11
0
void bfcread_tagsBranch( 
  const char *MainFile="/afs/rhic.bnl.gov/star/data/samples/gstar.tags.root",
  Int_t printEvent=1,
  const char *fname="qa_tags.out",
  Int_t fullPrint=0) 
{
  // start timer
  TStopwatch timer;
  timer.Start();

  cout << endl << endl;
  cout << " bfcread_tagsBranch.C: input file  = " << MainFile << endl;
  cout << " bfcread_tagsBranch.C: print event # " << printEvent << endl;
  cout << " bfcread_tagsBranch.C: output file = " << fname << endl;
  cout << " bfcread_tagsBranch.C: full printout = " << fullPrint << endl;
  cout << endl;

  ofstream fout(fname);

  fout << endl << endl;
  fout << " bfcread_tagsBranch.C: input file  = " << MainFile << endl;
  fout << " bfcread_tagsBranch.C: print evt#  = " << printEvent << endl;
  fout << " bfcread_tagsBranch.C: output file = " << fname << endl;
  fout << " bfcread_tagsBranch.C: full printout = " << fullPrint << endl;
  fout << endl;

  TFile *file = TFile::Open(MainFile);
  TTree *tree = (TTree*)file->Get("Tag");

  cout <<" read file: " << file->GetName() << endl << endl;

  Int_t nEntries = tree->GetEntries();
  cout << " Total # events  = " << nEntries << endl;

  TObjArray *leaves = tree->GetListOfLeaves();
  Int_t nLeaves = leaves->GetEntriesFast();

  cout << "  Total # leaves  = " << nLeaves << endl;

  TString *tName = new TString(" ");
  TNamed *tableName=0;
  TObjArray *tagTable = new TObjArray;
  Int_t tableCount = 0;
  Int_t *tableIndex = new Int_t[nLeaves];
  Int_t tagCount = 0;

  TBranch *branch=0;
  TLeaf *leaf=0;
  Int_t ndim =0;

//count number of tag tables encoded in the TTree branch names
  for (Int_t l=0;l<nLeaves;l++) {
    leaf = (TLeaf*)leaves->UncheckedAt(l);
    tagCount+=leaf->GetNdata();
    branch = leaf->GetBranch();
      cout << "leaf #  " << l << "  br name = " <<  
                                     branch->GetName() << endl;
    //new tag table name
    if ( strstr(branch->GetName(), tName->Data()) == 0 ) {
      tName = new TString(branch->GetName());
      tName->Resize(tName->Index("."));
      //the tableName is encoded in the branch Name before the "."
      tableName = new TNamed(tName->Data(),"Tag");
      tagTable->AddLast(tableName);
      tableCount++;
    }
    tableIndex[l]=tableCount-1;
  }

  cout << endl << "  Total num tables(branches),tags = " 
              << tableCount << "   " << tagCount << endl << endl;

  Int_t *countTagsTable = new Int_t[tableCount];
  Int_t *countLeavesTable = new Int_t[tableCount];
  Float_t *sumTagsLeaf = new Float_t[nLeaves];
  Int_t *countTagsLeaf = new Int_t[nLeaves];

// Now loop over leaves (to get values of tags)

   Int_t setBranch = -1;
   Int_t nowBranch = -1;

   for (Int_t l=0;l<nLeaves;l++) {

      leaf = (TLeaf*)leaves->UncheckedAt(l);
      branch = leaf->GetBranch();
      ndim = leaf->GetNdata();

      nowBranch = tableIndex[l];

      //cout << " nowbranch, setBranch = " << 
      //  nowBranch << ", "<< setBranch << endl;

      Float_t RtableIndex=tableIndex[l];

      if (nowBranch !=  setBranch){ 
          setBranch=nowBranch;
          cout << " QAInfo: branch ";
            cout.width(2);
            cout << tableIndex[l] << " = ";
            cout.width(10);
            cout << ((TNamed*)tagTable->UncheckedAt(tableIndex[l]))->GetName();
            cout << endl;
          fout << " QAInfo: branch ";
            fout.width(2);
            fout << RtableIndex << " = ";
            fout.width(10);
            fout << ((TNamed*)tagTable->UncheckedAt(tableIndex[l]))->GetName();
            fout << endl;
      }

      countTagsTable[tableIndex[l]]+=leaf->GetNdata();
      countLeavesTable[tableIndex[l]]++;
      countTagsLeaf[l]+=ndim;

      Float_t Rl=l;
      Float_t Rndim=ndim;
      cout << " QAInfo:     leaf ";
        cout.width(3);
        cout << l << " has ";
        cout.width(1);
        cout << ndim << " tags:";
        cout << endl;
      fout << " QAInfo:     leaf ";
        fout.width(3);
        fout << Rl << " has ";
        fout.width(1);
        fout << Rndim << " tags:";
        fout << endl;

//  loop over all events in each leaf

      for (Int_t nev=0; nev<nEntries; nev++) {
	branch->GetEntry(nev);

//  loop over all tags in each leaf for each event

	for (Int_t itag=0;itag<ndim;itag++) {

          Int_t ik = nev+1;
	  if (ik==printEvent) {

	     cout << " QAInfo:         " << leaf->GetName();
	     if (ndim>1) cout << '['<<itag<<']';
             cout << " = " << leaf->GetValue(itag) << endl; 	

	     fout << " QAInfo:         " << leaf->GetName();
	     if (ndim>1) fout << '['<<itag<<']';
             fout << " = " << leaf->GetValue(itag) << endl; 	  
	  }

          sumTagsLeaf[l]+=leaf->GetValue(itag);

	} 	
      }
    }
    cout << endl  << endl;
    fout << endl  << endl;


    if (fullPrint == 1){
// loop over leaves again for printout at end
     for (Int_t m=0; m<nLeaves; m++){

       leaf = (TLeaf*)leaves->UncheckedAt(m);
       branch = leaf->GetBranch();
       ndim = leaf->GetNdata();

      cout << " QAInfo: branch ";
        cout.width(2);
        cout << tableIndex[m] << " = ";
        cout.width(10);
        cout << ((TNamed*)tagTable->UncheckedAt(tableIndex[m]))->GetName();
        cout << ", leaf ";
        cout.width(3);
        cout << m << " = ";
        cout.width(24);
        cout << leaf->GetName();
        cout << ", #tags = ";     
        cout.width(1);
        cout << ndim;
        cout << endl;

	Float_t RtableIndex=tableIndex[m];
        Float_t Rm=m;
        Float_t Rndim=ndim;
      fout << " QAInfo: branch ";
        fout.width(2);
        fout << RtableIndex << " = ";
        fout.width(10);
        fout << ((TNamed*)tagTable->UncheckedAt(tableIndex[m]))->GetName();
        fout << ", leaf ";
        fout.width(3);
        fout << Rm << " = ";
        fout.width(24);
        fout << leaf->GetName();
        fout << ", #tags = ";     
        fout.width(1);
        fout << Rndim;
        fout << endl;

     }
    }
     cout << endl  << endl;
     fout << endl  << endl;



// loop over leaves again for printout at end of averages
     cout << " QAInfo: each leaf's avg over all tags,evts: " << endl;
     fout << " QAInfo: each leaf's avg over all tags,evts: " << endl;

     for (Int_t m=0; m<nLeaves; m++){

      leaf = (TLeaf*)leaves->UncheckedAt(m);

      sumTagsLeaf[m]/=countTagsLeaf[m]*nEntries;

      cout << " QAInfo: avg leaf #";
        cout.width(2);
        cout << m << ", ";
        cout.width(23);
        cout << leaf->GetName() << " = ";
        cout.width(12);
        cout << sumTagsLeaf[m];
        cout << endl;

	Float_t Rm=m;
      fout << " QAInfo: avg leaf #";
        fout.width(2);
        fout << Rm << ", ";
        fout.width(23);
        fout << leaf->GetName() << " = ";
        fout.width(12);
        fout << sumTagsLeaf[m];
        fout << endl;

     }
     cout << endl  << endl;
     fout << endl  << endl;



// loop over all tables
     for (Int_t m=0; m<tableCount; m++){

        cout << " QAInfo: branch(table) ";
	  cout.width(10);
	  cout << ((TNamed*)tagTable->UncheckedAt(m))->GetName() << " has ";
	  cout.width(4);
	  cout << countLeavesTable[m] << " leaves,";
	  cout.width(4);
	  cout << countTagsTable[m] << " tags" << endl;

	  Float_t RcountLeavesTable=countLeavesTable[m];
          Float_t RcountTagsTable=countTagsTable[m];
        fout << " QAInfo: branch(table) ";
	  fout.width(10);
	  fout << ((TNamed*)tagTable->UncheckedAt(m))->GetName() << " has ";
	  fout.width(4);
	  fout << RcountLeavesTable << " leaves,";
	  fout.width(4);
	  fout << RcountTagsTable << " tags" << endl;

     }
     cout << endl  << endl;
     fout << endl  << endl;


     Float_t RnEntries=nEntries;
     Float_t RtableCount=tableCount; 
     Float_t RnLeaves=nLeaves; 
     Float_t RtagCount=tagCount; 

     cout << " QAInfo:  tot num events = " << nEntries << endl;
     fout << " QAInfo:  tot num events = " << RnEntries << endl;

     cout << " QAInfo:   tot num branches = " << tableCount << endl;
     fout << " QAInfo:   tot num branches = " << RtableCount << endl;

     cout << " QAInfo:   tot num leaves = " << nLeaves << endl;
     fout << " QAInfo:   tot num leaves = " << RnLeaves << endl;

     cout << " QAInfo:   tot num tags = " << tagCount << endl;
     fout << " QAInfo:   tot num tags = " << RtagCount << endl;


  // stop timer and print results
  timer.Stop();
  cout<< endl << endl <<"RealTime="<<timer.RealTime()<<
       " seconds, CpuTime="<<timer.CpuTime()<<" seconds"<<endl;

  //cleanup
  file->Close();
  fout.close();
}
Example #12
0
  bool MSD::Aggregate() const
  {
    ifstream fin(m_tmpModel);
    if (!fin){
      cerr << "Cannot find file msd.reordering.model.1.sorted" << endl;
      return false;
    }

    ofstream fout(m_tmpModel + ".aggregated");
    if (!fout){
      cerr << "Cannot create aggregation file: " <<
        m_tmpModel + ".arggregated" << endl;
      return false;
    }

    cerr << "MSD reordering Step2: Aggregating MSD scores..." << endl;
    string line, lastsrc = "", lasttgt = "";
    size_t score[6] = {0};
    vector<string> msdscore;
    while (getline(fin, line)){
      vector<string> tmp = BasicMethod::Split(line, " ||| ");
      if (tmp.size() != 3){
        cerr << "msd reordering table bad data: "
          << line << endl;
        continue;
      }
      if (lastsrc == "" && lasttgt == ""){
        lastsrc = tmp[0]; lasttgt = tmp[1];
        memset(score, 0, sizeof(score));
        msdscore = BasicMethod::Split(tmp[2]);
        for (int i = 0; i < 6; ++i){
          score[i] = atoi(msdscore[i].c_str());
        }
      }
      else{
        if (tmp[0] == lastsrc && tmp[1] == lasttgt){
          msdscore = BasicMethod::Split(tmp[2]);
          for (int i = 0; i < 6; ++i){
            score[i] += atoi(msdscore[i].c_str());
          }
        }
        else{
          //we now output the aggregation of previous pharse pair
          fout << lastsrc << " ||| " << lasttgt << " ||| ";
          for (int i = 0; i < 6; ++i){
            if (i != 5){
              fout << score[i] << " ";
            }
            else{
              fout << score[i] << endl;
            }
          }
          lastsrc = tmp[0]; lasttgt = tmp[1];
          memset(score, 0, sizeof(score));
          msdscore = BasicMethod::Split(tmp[2]);
          for (int i = 0; i < 6; ++i){
            score[i] = atoi(msdscore[i].c_str());
          }
        }
      }
    }
    //output remaining items
    fout << lastsrc << " ||| " << lasttgt << " ||| ";
    for (int i = 0; i < 6; ++i){
      if (i != 5){
        fout << score[i] << " ";
      }
      else{
        fout << score[i] << endl;
      }
    }
    fout.close();
    fin.close();
  }
// Runs program with input from test files in testFiles vector.
void TestSuite::runTests()
{
    int numCorrect = 0, numWrong = 0;
    int i;
    string name;
    string logName;
    string stored_dir;
    double rate;
    bool crit = false;
    string crit_string = "crit.tst";
    bool crit_passed = true;
    char buff[40];
    int chpid = 45;
	
    //Get directory of current program
    i = testProgram.rfind('.');
    testProgram = testProgram.substr(0, i);

    // Create log file.
    logName = testProgram + "-";
    logName += exeTime;
    logName += ".log";
    ofstream fout(logName.c_str());
    if (!fout)
    {
        return;
    }

    // Iterate over test files.
    vector<string>::iterator it;
    for ( it = testFiles.begin(); it != testFiles.end() ; it++ )
    {

        //Determine if this is a critical test
        if(it->find(crit_string) != string::npos)
        {
            crit = true;
        }

        // Get test file name without path.
        size_t pos = it->rfind("/");
        if(pos != std::string::npos)
        {
            name = it->substr(pos+1,it->length());
        }

        // Output test file name to log file.
        fout << name;


        // Run program with given test file.
        run_code(*it,name);

		//else, do a failed program log file i supposd

        // Determine corresponding answer file.
        string ans = *it;
        ans.replace(ans.end()-4, ans.end(),answerExtension);

        // Output results.
        if (correct_answer(ans))
        {
            numCorrect++;
            fout << ": PASS" << endl;
        }
        else
        {
            //If this was a crit test, they auto fail
            if(crit)
            {
                crit_passed = false;
            }
            numWrong++;
            fout << ": FAIL" << endl;
        }

    }



    //If all possible crit tests were passed
    if(crit_passed)
    {
        // Output pass and fail stats.
        rate = ( numCorrect / (double)(numCorrect + numWrong) ) * 100;
        fout << rate <<  "% CORRECT," << numCorrect << " PASSED," << numWrong << " FAILED";
        sprintf(buff, "  %f%% Correct\n", rate);
        i = testProgram.rfind('/');
        studentResults.push_back(testProgram.substr(i+1) + string(buff));
    }
    else
    {
        //If one or more were not passed
        fout << "Failed: Did not pass one or more acceptance tests (Labeled as crit)" << endl;
        i = testProgram.rfind('/');
        studentResults.push_back(testProgram.substr(i) + "  FAILED\n");
    }


    fout << "\n" <<  get_gcov(testProgram) << endl;
    fout.close();
    if(profiling)
        get_gprof(testProgram);
}
Example #14
0
bool EncoderLame::encode(QString input,QString output)
{
    qDebug() << "[EncoderLame] Encoding" << QDir::cleanPath(input);
    if(!m_symbolsResolved) {
        qDebug() << "[EncoderLame] Symbols not successfully resolved, cannot run!";
        return false;
    }

    QFile fin(input);
    QFile fout(output);
    // initialize encoder
    lame_global_flags *gfp;
    unsigned char header[12];
    unsigned char chunkheader[8];
    unsigned int datalength = 0;
    unsigned int channels = 0;
    unsigned int samplerate = 0;
    unsigned int samplesize = 0;
    int num_samples = 0;
    int ret;
    unsigned char* mp3buf;
    int mp3buflen;
    short int* wavbuf;
    int wavbuflen;


    gfp = m_lame_init();
    m_lame_set_out_samplerate(gfp, 12000);      // resample to 12kHz
    // scale input volume
    m_lame_set_scale(gfp, m_encoderVolume);
    m_lame_set_mode(gfp, MONO);                 // mono output mode
    m_lame_set_VBR(gfp, vbr_default);           // enable default VBR mode
    // VBR quality
    m_lame_set_VBR_quality(gfp, m_encoderQuality);
    m_lame_set_VBR_max_bitrate_kbps(gfp, 64);   // maximum bitrate 64kbps
    m_lame_set_bWriteVbrTag(gfp, 0);            // disable LAME tag.

    if(!fin.open(QIODevice::ReadOnly)) {
        qDebug() << "[EncoderLame] Could not open input file" << input;
            return false;
    }

    // read RIFF header
    fin.read((char*)header, 12);
    if(memcmp("RIFF", header, 4) != 0) {
        qDebug() << "[EncoderLame] RIFF header not found!"
                 << header[0] << header[1] << header[2] << header[3];
        fin.close();
        return false;
    }
    if(memcmp("WAVE", &header[8], 4) != 0) {
        qDebug() << "[EncoderLame] WAVE FOURCC not found!"
                 << header[8] << header[9] << header[10] << header[11];
        fin.close();
        return false;
    }

    // search for fmt chunk
    do {
        // read fmt
        fin.read((char*)chunkheader, 8);
        int chunkdatalen = chunkheader[4] | chunkheader[5]<<8
                           | chunkheader[6]<<16 | chunkheader[7]<<24;
        if(memcmp("fmt ", chunkheader, 4) == 0) {
            // fmt found, read rest of chunk.
            // NOTE: This code ignores the format tag value.
            // Ideally this should be checked as well. However, rbspeex doesn't
            // check the format tag either when reading wave files, so if
            // problems arise we should notice pretty soon. Furthermore, the
            // input format used should be known. In case some TTS uses a
            // different wave encoding some time this needs to get adjusted.
            if(chunkdatalen < 16) {
                qDebug() << "[EncoderLame] fmt chunk too small!";
            }
            else {
                unsigned char *buf = new unsigned char[chunkdatalen];
                fin.read((char*)buf, chunkdatalen);
                channels = buf[2] | buf[3]<<8;
                samplerate = buf[4] | buf[5]<<8 | buf[6]<<16 | buf[7]<<24;
                samplesize = buf[14] | buf[15]<<8;
                delete[] buf;
            }
        }
        // read data
        else if(memcmp("data", chunkheader, 4) == 0) {
            datalength = chunkdatalen;
            break;
        }
        else {
            // unknown chunk, just skip its data.
            qDebug() << "[EncoderLame] unknown chunk, skipping."
                     << chunkheader[0] << chunkheader[1]
                     << chunkheader[2] << chunkheader[3];
            fin.seek(fin.pos() + chunkdatalen);
        }
    } while(!fin.atEnd());

    // check format
    if(channels == 0 || samplerate == 0 || samplesize == 0 || datalength == 0) {
        qDebug() << "[EncoderLame] invalid format. Channels:" << channels
                 << "Samplerate:" << samplerate << "Samplesize:" << samplesize
                 << "Data chunk length:" << datalength;
        fin.close();
        return false;
    }
    num_samples = (datalength / channels / (samplesize/8));

    // set input format values
    m_lame_set_in_samplerate(gfp, samplerate);
    m_lame_set_num_channels(gfp, channels);

    // initialize encoder.
    ret = m_lame_init_params(gfp);
    if(ret != 0) {
        qDebug() << "[EncoderLame] lame_init_params() failed with" << ret;
        fin.close();
        return false;
    }

    // we're dealing with rather small files here (100kB-ish), so don't care
    // about the possible output size and simply allocate the same number of
    // bytes the input file has. This wastes space but should be ok.
    // Put an upper limit of 8MiB.
    if(datalength > 8*1024*1024) {
        qDebug() << "[EncoderLame] Input file too large:" << datalength;
        fin.close();
        return false;
    }
    mp3buflen = datalength;
    wavbuflen = datalength;
    mp3buf = new unsigned char[mp3buflen];
    wavbuf = new short int[wavbuflen];
#if defined(Q_OS_MACX)
    // handle byte order -- the host might not be LE.
    if(samplesize == 8) {
        // no need to convert.
        fin.read((char*)wavbuf, wavbuflen);
    }
    else if(samplesize == 16) {
        // read LE 16bit words. Since the input format is either mono or
        // interleaved there's no need to care for that.
        unsigned int pos = 0;
        char word[2];
        while(pos < datalength) {
            fin.read(word, 2);
            wavbuf[pos++] = (word[0]&0xff) | ((word[1]<<8)&0xff00);
        }
    }
    else {
        qDebug() << "[EncoderLame] Unknown samplesize:" << samplesize;
        fin.close();
        delete[] mp3buf;
        delete[] wavbuf;
        return false;
    }
#else
    // all systems but OS X are considered LE.
    fin.read((char*)wavbuf, wavbuflen);
#endif
    fin.close();
    // encode data.
    fout.open(QIODevice::ReadWrite);
    ret = m_lame_encode_buffer(gfp, wavbuf, wavbuf, num_samples, mp3buf, mp3buflen);
    if(ret < 0) {
        qDebug() << "[EncoderLame] Error during encoding:" << ret;
    }
    if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) {
        qDebug() << "[EncoderLame] Writing mp3 data failed!" << ret;
        fout.close();
        delete[] mp3buf;
        delete[] wavbuf;
        return false;
    }
    // flush remaining data
    ret = m_lame_encode_flush(gfp, mp3buf, mp3buflen);
    if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) {
        qDebug() << "[EncoderLame] Writing final mp3 data failed!";
        fout.close();
        delete[] mp3buf;
        delete[] wavbuf;
        return false;
    }
    // shut down encoder and clean up.
    m_lame_close(gfp);
    fout.close();
    delete[] mp3buf;
    delete[] wavbuf;

    return true;
}
void HMMObserver::start() {
	vector<vector<TimeSeries *> *> chunk_bins;
	vector<double> current_means;
	vector<double> current_ns;
	vector<double> current_variance;
	vector<TimeSeries *> chunks;

	TimeSeries * inputTS = NULL;
	if (use_csv) {
		inputTS = CSVLoader::loadTSfromCSV(csvin_fname);
	} else {
		log_e("No input source defined. Stop.");
		return;
	}

#define NUM_STEPS 5
	TimeSeries * inputRaw = inputTS->copy();

	TRANS_DETECTOR.setParams(0.05,60);
	double NEW_BIN_THRESH = 1.2;

	log_prog(1,NUM_STEPS,"Detect Transitions","");
	EventSeries<TransitionEvent> * es = TRANS_DETECTOR.detect(inputTS);

	log_i("%d Transitions found\n",es->events.size());
	if ( es->events.size() <= 1 ) {
		log_i("Not enough transitions to do anything useful");
		log_prog(NUM_STEPS,NUM_STEPS,"Early abort","No data");
		error = 1;
		return;
	}

	// STEP Ia : SEPARATE INTO CHUNKS
	log_prog(2,NUM_STEPS,"Separate Time Chunks","");
	chunks.push_back(inputTS->selectTime(inputTS->t[0],es->events[0].t));
	for ( size_t c = 0; c < es->events.size() - 1; c++) {
		chunks.push_back(inputTS->selectTime(es->events[c].t,es->events[c+1].t));
	}
	chunks.push_back(inputTS->selectTime(es->events[es->events.size()-1].t,inputTS->t[inputTS->t.size()-1]));

	if (csvout_fname.size() > 0) {
		TimeSeries * tsout = new TimeSeries();
		tsout->metadata.push_back(" Data separated into chunks via the transition detector");
		for (size_t c = 0; c < chunks.size(); c++) {
			tsout->insertPointAtEnd(chunks[c]->t[0],chunks[c]->mean());
		}
		CSVLoader::writeTStoCSV(csvout_fname,tsout,outprec);
		delete tsout;
	}


	if (statesin_fname.size() > 0 ) {
		// STEP Ib : ORDER CHUNKS BY SIZE
		log_prog(3,NUM_STEPS,"Order by Size","");
		sort(chunks.begin(), chunks.end(), cmp_by_timeseries_length);

		// STEP Ic : CATAGORIZE CHUNKS BY MEANS

		// start with biggest chunk in first bin
		chunk_bins.push_back(new vector<TimeSeries *>);
		chunk_bins[0]->push_back(chunks[0]);
		current_means.push_back(chunks[0]->mean());

		for ( int c = 1; c < chunks.size(); c++ ) {
			log_prog(4,NUM_STEPS,"Categorize by Means","%.2f%%",(100.0*c/chunks.size()));
			double chmean = chunks[c]->mean();

			// find the "closest" bin
			int minmean = 0;
			for ( int d = 1; d < chunk_bins.size(); d++ ) {
				if ( fabs(chmean - current_means[d]) < fabs(chmean - current_means[minmean]) ) {
					minmean = d;
				}
			}
			// if closest bin is too far off, create a new bin
			if ( current_means[minmean] / chmean > NEW_BIN_THRESH || chmean / current_means[minmean] > NEW_BIN_THRESH ) {
				chunk_bins.push_back(new vector<TimeSeries *>);
				chunk_bins.back()->push_back(chunks[c]);
				current_means.push_back(chmean);
			} else { // add to bin and update mean
				current_means[minmean] = (current_means[minmean] * chunk_bins[minmean]->size() + chmean) / (chunk_bins[minmean]->size() + 1);
				chunk_bins[minmean]->push_back(chunks[c]);
			}
		}

		for ( int c = 0; c < chunk_bins.size(); c++ ) {
			int varn = 0;
			double varsum = 0;
			double meansum = 0;
			for (int d = 0; d < chunk_bins[c]->size(); d++ ) {
				varn += chunk_bins[c]->at(d)->t.size();
			}
			current_ns.push_back(varn);
			// recalculate means
			for ( int d = 0; d < chunk_bins[c]->size(); d++ ) {
				meansum += chunk_bins[c]->at(d)->sum();
			}
			meansum = current_means[c] = meansum/varn;

			for (int d = 0; d < chunk_bins[c]->size(); d++ ) {
				varn += chunk_bins[c]->at(d)->t.size();
				for ( int e = 0; e < chunk_bins[c]->at(d)->t.size(); e++) {
					double tsq = chunk_bins[c]->at(d)->v[e] - meansum;
					varsum += tsq * tsq;
				}
			}
			current_variance.push_back(varsum / varn);
		}

		for ( int c = 0; c < chunk_bins.size(); c++ ) {
			log_i("Cluster %2d : Mean %10.2f  Variance %10.2f",c,current_means[c],current_variance[c]);
			for ( int d = 0; d < chunk_bins[c]->size(); d++) {
				log_i("\tChunk %3d: t:%10.2f mean:%10.2f",d,chunk_bins[c]->at(d)->t.front() - inputTS->t.front(),chunk_bins[c]->at(d)->mean());
			}
		}

		log_prog(5,NUM_STEPS,"Writing Output","");
		ofstream fout(statesin_fname.c_str());
		fout.precision(outprec);
		if ( !fout.is_open() ) {
			log_e("Cannot open file %s for writing: %s",statesin_fname.c_str(),strerror(errno));
			exit(2);
		}

		fout << "# Describes states and their statistical measurements"<<endl;
		fout<< "# State, sample size, Mean, Variance"<<endl;
		for ( int c = 0; c < chunk_bins.size(); c++ ){
			fout << c << "," << current_ns[c] << "," << current_means[c] << "," << current_variance[c] << endl;
		}
		fout.close();
	}



	cleanup:
	// cleanup
	while(!chunk_bins.empty()) delete chunk_bins.back(), chunk_bins.pop_back();
	while(!chunks.empty()) delete chunks.back(), chunks.pop_back();
	delete es;
	delete inputTS;
	delete inputRaw;

	log_i("Done.");
}
int main(int argc, char* argv[])
{

    directory_structure_t ds;

    vector<object_trj_t> good_trlet_list;
    {
	std::string name = ds.workspace+"good_trlet_list.xml";
	std::ifstream fin(name.c_str());
	boost::archive::xml_iarchive ia(fin);
	ia >> BOOST_SERIALIZATION_NVP(good_trlet_list);
    }

    if(good_trlet_list.size()==0) 
    {
	std::cout<<"reading good_trlet_list.xml fails."<<std::endl;
	return 1;
    }
    int Ncam = good_trlet_list(0).trj.size();

    vector<object_trj_t> final_trj_list;
    vector<vector<int> > final_trj_index;
    matrix<int> final_state_list;

    {
	std::string name = ds.workspace+"final_trj_list_alone.xml";
	std::ifstream fin(name.c_str());
	boost::archive::xml_iarchive ia(fin);
	ia >> BOOST_SERIALIZATION_NVP(final_trj_list);
    }

    {
	std::string name = ds.workspace+"final_state_list_alone.txt";
	std::ifstream fin(name.c_str());
	fin>>final_state_list;
	fin.close();
    }

    {
	std::string name = ds.workspace+"final_trj_index_alone.txt";
	std::ifstream fin(name.c_str());
	fin >> final_trj_index;
	fin.close();
    }

    int len_thr = 4;
    vector<object_trj_t> merged_trj_list;
    vector<vector<int> > merged_trj_index;
    matrix<int> merged_state_list;

    post_process_trj(good_trlet_list, final_trj_list, final_trj_index,
		     final_state_list, Ncam, len_thr,
		     merged_trj_list, merged_trj_index,
		     merged_state_list);

    {
	std::string name = ds.workspace+"merged_trj_list_alone.xml";
	std::ofstream fout(name.c_str());
	boost::archive::xml_oarchive oa(fout);
	oa << BOOST_SERIALIZATION_NVP(merged_trj_list);
    }

    {
	std::string name = ds.workspace+"merged_trj_index_alone.txt";
	std::ofstream fout(name.c_str());
	fout<<merged_trj_index;
	fout.close();
    }

    {
	std::string name = ds.workspace+"merged_state_list_alone.txt";
	std::ofstream fout(name.c_str());
	fout << merged_state_list;
	fout.close();
    }

    return 0;

}
Example #17
0
int _tmain(int argc, _TCHAR* argv[])
{	
	/* add valid user */
	valid_user.Add(_T("mr_timon"));
	valid_user.Add(_T("mr_pumbaa"));
	valid_user.Add(_T("star_patrick"));
	valid_user.Add(_T("乐乐是我的哦"));
	valid_user.Add(_T("457800643xc"));
	valid_user.Add(_T("lingzhiji服饰旗舰店"));
	valid_user.Add(_T("呢好美"));
	//valid_user.Add(_T("star"));
	//valid_user.Add(_T("lele"));

	if(checkUser(argv[2])){
		std::cout << std::endl << std::endl << "       you are not a valid user!          " << std::endl << std::endl << std::endl;
		return 0;
	}

	CString URL;
	CString url_date;
	CString url_spm = _T("spm=1.7274553.1997520841.1");
	CString url_keyWord ;
	CString url_option = _T("commend=all&ssid=s5-e&search_type=item&sourceId=tb.index");
	CString url_head = _T("http://s.taobao.com/search?");
	CString url_page;

	CString filePath = _T("dist");
	//CString string_keyWord = _T("儿童防紫外线帽子");
	//CString string_id = _T("mr_timon");
	CString string_keyWord = argv[1];
	CString string_id = argv[2];


	url_date = _T("initiative_id=tbindexz_") + generateUrlDate();
	url_keyWord = _T("q=") + generateUrlKeyWord(string_keyWord);

	for(int i = 1; i <= 100; i++){
		url_page = generateUrlPage(i);
		if((i - 1)%10 == 0){
			std::cout << "     searching";
			for(int j = 0; j < i/10; j++){
				std::cout << ".";
			}
			std::cout << std::endl;
		}
		if(i != 1){
			URL = url_head + url_keyWord + _T("&") + url_spm + _T("&") + url_option+ _T("&") + url_date + _T("&") + url_page;
		}else{
			URL = url_head + url_keyWord + _T("&") + url_spm + _T("&") + url_option+ _T("&") + url_date;
		}

		/*   这里有资源链接的话,可以把对应的资源下载下来   */
		//URL = _T("http://www.jojomamanbebe.co.uk/products/images/large/B2755C.jpg");
		
		HRESULT result =  URLDownloadToFile(0, URL, filePath, 0, NULL);
		if(result == S_OK){
			//std::cout << "down\n";
			if(!searchLocation(filePath,string_id)){
				std::cout << "            page = " << i << std::endl << std::endl << std::endl;
				break;
			}else{
				if(i == 100)
					std::cout << std::endl << std::endl << "*************  sorry,we don't have found it  *************" << std::endl << std::endl << std::endl ;
			}
		}else{
			std::cout << "URLDownloadToFile failed\n";
			return 1;
		}
	}

	//std::cout << "real_url = " << URL << std::endl;

	std::ofstream fout("currentURL.txt");
	fout << URL;
	fout.flush();
	fout.close();
	
	//getchar();
	return 0;
}
Example #18
0
template<typename real> void
pcl::BivariatePolynomialT<real>::writeBinary (const char* filename) const
{
  std::ofstream fout (filename);
  writeBinary (fout);
}
Example #19
0
int main() {
	std::string filename="MyFile.txt"; //' '
	std::ofstream /* ifstream */ fout(filename.c_str()); // (filename)
	fout << /* >> */ "Hello World" << std::endl;
	fout.close(); //finish
}
//----------------------------------------------------------------
void GetImageH264(AV2000F& dll, PARAMS& params)
{
	// using client
	unsigned long size = 1024*1024, capacity = 1024*1024;
	char* data = new char[size]; // image
	int ret;
	
	if(ret = dll.pCreateClient(1))
	{
		std::cout << "\nerror on create client, code: " << ret << '\n';
		return;
	}
	dll.pSetClientIp(1, params["-ip"].c_str());
	
	dll.pSetClientBuffer(1, data, size);
	

	if(dll.pUpdateVersion(1) )
	
	{
		
		
		//if(!dll.pGetDefaultImage(1, &data, &size, &capacity)) return;
		PARAMS::iterator iter = params.find("-out"); // out file with image
		if(iter == params.end()) params["-out"] = "test.mpg";


		std::ofstream fout(params["-out"].c_str(), std::ios_base::binary);
		std::cout << "Camera model: " << dll.pModel(1) << " / " <<  dll.pVersion(1) << '\n';
		if(!fout)
			std::cout << "can't open file\n";
		else
		{

			IMAGE_RESOLUTION res = imFULL;
			if((iter = params.find("-res")) != params.end())
				if(iter->second == "half") res = imHALF;
			long quality = 15; // 
			int left = 0, top = 0, width = 1600, height = 1184;
			int codec = H264_CODEC;
			int streamId = 1;
			int kbps = 0;// bit rate control off
			int IntraFramePeriod = 0;// if bit rate control off, then this value is ignored


			for (int frame=0; frame < 25; ++frame)
			{


			        int IFrame = 0; //request P frame if possible. if not available
                                                //SDK will change it to 1, so it must be set every time 
				ret = dll.pGetWindowImageQEx(1, &data, &size , &capacity, imFULL, 0, quality, left, top, width, height, codec, streamId, &IFrame, kbps, IntraFramePeriod);


				std::cout << " return " << size << "bytes" << '\n';
				for(unsigned long i = 0; i < size; i++)
					fout << data[i];
			}

			std::cout << "image saved to file: \"" << params["-out"] << "\"\n";

		}
	}
	else
	{

		const ClientError* pcler = dll.pGetLastClientError(1);

		std::cout << "error: code: " << pcler->code << ", description: " << pcler->description << '\n';
	}
	dll.pDestroyClient(1);

}
Example #21
0
void ShearCatalog::writeAscii(std::string file, std::string delim) const
{
    Assert(int(_id.size()) == size());
    Assert(int(_pos.size()) == size());
    Assert(int(_sky.size()) == size());
    Assert(int(_noise.size()) == size());
    Assert(int(_flags.size()) == size());
    Assert(int(_skypos.size()) == size());
    Assert(int(_shear.size()) == size());
    Assert(int(_nu.size()) == size());
    Assert(int(_cov.size()) == size());
    Assert(int(_meas_galorder.size()) == size());
    Assert(int(_shape.size()) == size());

    std::ofstream fout(file.c_str());
    if (!fout) {
        throw WriteException("Error opening shear file"+file);
    }

    bool output_psf = _params.read("shear_output_psf",false);

    Form sci8; sci8.sci().trail(0).prec(8);
    Form fix3; fix3.fix().trail(0).prec(3);
    Form fix8; fix8.fix().trail(0).prec(8);
    Form fix6; fix6.fix().trail(0).prec(6);

    const int ngals = size();
    for(int i=0;i<ngals;++i) {
        fout
            << _id[i] << delim
            << fix3(_pos[i].getX()) << delim
            << fix3(_pos[i].getY()) << delim
            << fix3(_sky[i]) << delim
            << sci8(_noise[i]) << delim
            << _flags[i] << delim
            << fix8(_skypos[i].getX()/3600.) << delim 
            << fix8(_skypos[i].getY()/3600.) << delim
            << sci8(real(_shear[i])) << delim
            << sci8(imag(_shear[i])) << delim
            << fix3(_nu[i]) << delim
            << sci8(_cov[i](0,0)) << delim
            << sci8(_cov[i](0,1)) << delim
            << sci8(_cov[i](1,1)) << delim
            //<< _shape[i].getOrder() << delim
            << _meas_galorder[i] << delim
            << fix6(_shape[i].getSigma());
        const int ncoeff = _shape[i].size();
        for(int j=0;j<ncoeff;++j)
            fout << delim << sci8(_shape[i](j));
        if (output_psf) {
            Assert(_fitpsf);
            BVec interp_psf(_fitpsf->getPsfOrder(),_fitpsf->getSigma());
            interp_psf = (*_fitpsf)(_pos[i]);
            fout
                << delim << interp_psf.getOrder()
                << delim << fix6(interp_psf.getSigma());
            const int npsf_coeff = interp_psf.size();
            for(int j=0;j<npsf_coeff;++j)
                fout << delim << sci8(interp_psf(j));
        }
        fout << std::endl;
    }
}
Example #22
0
void TalkCard::handleVCard(const JID & jid, const VCard * vcard)
{
        if (!vcard) {
                DLOG("empty %s's vcard!\n", jid.full().c_str());
                return ;
        }

        Bodies& bodies = Bodies::Get_Bodies();
        const JID& myjid = bodies.get_jid();

        char *random =
                g_strdup_printf("%x", g_random_int());
        const char *dirname = GUnit::getIconPath();
        char *filename =
                g_build_filename(dirname, random, NULL);
        int f_size;
        int n_size;

        struct stat f_stat;
        DLOG("geting %s vcard\n", jid.username().c_str());

        //获取自己的vcard照片

        if (myjid.bare() == jid.bare()) {
                //bodies.set_vcard(vcard);

                const std::string m_file = bodies.getAccountTag("icon");

                if ((!m_file.empty())
                                && (!access(m_file.c_str(), F_OK))) {


                        if (stat(m_file.c_str(), &f_stat))
                                return ;

                        f_size = f_stat.st_size;
                } else
                        f_size = 0;

                if (!vcard->photo().type.empty()) {
                        n_size = vcard->photo().binval.size();

                        if (f_size != n_size) {
                                DLOG("orig picture size = %d,new size= %d\n", f_size, n_size);
                                std::ofstream fout(filename);
                                fout.write((const char *) vcard->
                                           photo().binval.c_str(),
                                           vcard->photo().binval.
                                           size());
                                fout.close();

                                bodies.setAccountTag("icon", filename);
                                bodies.get_main_window().set_logo(filename);
                        }
                }

        }

        Buddy *buddy =
                bodies.get_buddy_list().find_buddy(jid.
                                                   bare
                                                   ());
        assert(buddy);
        //buddy->set_vcard(vcard);

        const std::string & buddyname = buddy->get_jid();
        const std::string & f_file =
                bodies.get_main_window().get_buddy_view().getBlistTag("buddy", buddyname, "icon");

        if ((!f_file.empty())
                        && (!access(f_file.c_str(), F_OK))) {

                if (stat(f_file.c_str(), &f_stat))
                        return ;

                f_size = f_stat.st_size;
        } else
                f_size = 0;

        if (!vcard->photo().binval.empty()) {
                n_size = vcard->photo().binval.size();

                if (f_size != n_size) {
                        DLOG("orig picture size = %d,new size= %d\n", f_size, n_size);
                        std::ofstream fout(filename);
                        fout.write((const char *) vcard->
                                   photo().binval.c_str(),
                                   n_size);
                        fout.close();
                        bodies.get_main_window().get_buddy_view().setBlistTag("buddy",
                                        buddyname,
                                        "icon",
                                        filename);
                }
        }


        buddy->refreshinfo();
}
Example #23
0
/**
 * The main entry of dw-lr-train, whose goal
 * is to takes as input in the same format as
 * libsvm, and train a classifier.
 **/
int main(int argc, char ** argv){

  /**
   * First, parse command line input to get
   *    (1) step size
   *    (2) number of epoches to run
   *    (3) regularization (l2)
   **/  
  std::string filename;
  int flags, opt;
  int nsecs, tfnd;
  nsecs = 0;
  tfnd = 0;
  flags = 0;
  while ((opt = getopt(argc, argv, "s:e:r:")) != -1) {
    switch (opt) {
    case 's':
      stepsize = atof(optarg);
      break;
    case 'e':
      epoches = atof(optarg);
      break;
    case 'r':
      lambda = atof(optarg);
      break;
    default: 
      fprintf(stderr, "Usage: %s [-s stepsize] [-e epoches] [-r regularization] trainfile\n", argv[0]);
      exit(EXIT_FAILURE);
    }
  }
  if (optind >= argc) {
      fprintf(stderr, "Expected argument after options\n");
      exit(EXIT_FAILURE);
  }
  filename = std::string(argv[optind]);
  printf("stepsize=%f; epoches=%f; lambda=%f\n", stepsize, epoches, lambda);
  printf("trainfile = %s\n", filename.c_str());

  /**
   * Second, create corpus
   **/
  size_t n_elements, n_examples, n_features;
  double * p_examples;
  long * p_cols;
  long * p_rows;
  get_corpus_stats(filename.c_str(), &n_elements, &n_examples);
  n_features = create_dw_corpus(filename.c_str(), n_elements, n_examples, p_examples, p_cols, p_rows);
  printf("#elements=%zu; #examples=%zu; #n_features=%zu\n", n_elements, n_examples, n_features);

  /**
   * Third, create DimmWitted object, and let it run.
   **/
  GLMModelExample_Sparse model(n_features);
  for(int i=0;i<model.n;i++){
    model.p[i] = 0.0;
  }

  SparseDimmWitted<double, GLMModelExample_Sparse, DW_MODELREPL_PERMACHINE, DW_DATAREPL_SHARDING, DW_ACCESS_ROW> 
    dw(p_examples, p_rows, p_cols, n_examples, n_features+1, n_elements, &model);
  
  unsigned int f_handle_grad = dw.register_row(f_lr_grad_sparse);
  unsigned int f_handle_loss = dw.register_row(f_lr_loss_sparse);
  dw.register_model_avg(f_handle_grad, f_lr_modelavg);
  dw.register_model_avg(f_handle_loss, f_lr_modelavg);

  printf("Start training...\n");

  double sum = 0.0;
  for(int i_epoch=0;i_epoch<epoches;i_epoch++){
    double loss = dw.exec(f_handle_loss)/n_examples;
    std::cout << "loss=" << loss << std::endl;
    dw.exec(f_handle_grad);
  }

  /**
   * Forth, dump result.
   **/
   printf("Dumping training result to %s.model...\n", filename.c_str());
  std::ofstream fout((filename + ".model").c_str());
  fout << n_features << std::endl;
  for(int i=0;i<model.n;i++){
    fout << model.p[i] << std::endl;
  }
  fout.close();

  exit(EXIT_SUCCESS);
}
Example #24
0
int sql()
{
  char f_l[4][15]={"employee","payroll","spending","expendit"};
  char fn[15];
  clrscr();
  char comm[30]="w";
  char name[20];int am;unsigned long int ac;
  cout<<"This Server supports miniSQL. Use q to exit";
  NL
  cputs("#");int r=1;
  cin.getline(comm,30);
do{
  strcpy(fn,f_l[cfn]);
  cin.getline(comm,30);
  if(strstr(comm,"insert")==comm)
  {

    if(strstr(comm,"into")!=NULL)
    {
      if(strstr(comm,fn)!=NULL)
      {
	NL
	cout<<"Enter Name: ";
	gets(name);
	cout<<"Enter Amount: ";
	cin>>am;
	do{
	cout<<"Enter Account No: ";
	cin>>ac;}while(ac<111111||ac>999999);
	ofstream fout(strcat(fn,".dbf"),ios::app);
	strcpy(fn,f_l[cfn]);
	fout<<name<<"\t\t$"<<am<<"\t\t"<<ac<<endl;
	p.cash+=am;
	NL
	if(abs(am-avg)<500)
	  r=1;
	else
	  r=0;
      }                         }
  }
  else if(strstr(comm,"select")==comm)
  {
    if(strstr(comm,"from")!=NULL)
    {
       if(strstr(comm,fn)!=NULL)
       {
	 NL
	 if(strstr(comm,"*")!=NULL)
	 {
	 ifstream f(strcat(fn,".dbf"));
	 char *p;
	 while(f)
	 {
	   f.getline(p,50);
	   cout<<p<<endl;
	 }
	 f.close();
	 strcpy(fn,"");
	 }
	 else if(strstr(comm,"avg")!=NULL)
	 {
	    NL
	    cout<<"Average="<<avg;
	 }
       }
    }
  }
Example #25
0
/**
 * \brief Faz o dump dos dados da Halo_Top para o arquivo de nome filename.
 * 
 * @param [in] filename  Nome do arquivo.
 */
void Halo_Top::print_iter_to_file(const char *filename) {
    if (this->rank_neighbor == MPI_PROC_NULL) {
        return;
    }

    fstream fout(filename, fstream::out | fstream::app);

    fout << "Source:" << endl;

    for (int i = 0; i < this->get_num_halos(); i++) {
        for (halo_iterator hi = h_source[i]->first();; hi++) {
            fout << *hi << " ";
            if (hi == h_source[i]->last()) {
                break;
            }
        }
        fout << endl;
    }

    fout << "Dest:" << endl;

    for (int i = 0; i < this->get_num_halos(); i++) {
        for (halo_iterator hi = h_dest[i]->first();; hi++) {
            fout << *hi << " ";
            if (hi == h_dest[i]->last()) {
                break;
            }
        }
        fout << endl;
    }

    this->swap();

    fout << "Source:" << endl;

    for (int i = 0; i < this->get_num_halos(); i++) {
        for (halo_iterator hi = h_source[i]->first();; hi++) {
            fout << *hi << " ";
            if (hi == h_source[i]->last()) {
                break;
            }
        }
        fout << endl;
    }

    fout << "Dest:" << endl;

    for (int i = 0; i < this->get_num_halos(); i++) {
        for (halo_iterator hi = h_dest[i]->first();; hi++) {
            fout << *hi << " ";
            if (hi == h_dest[i]->last()) {
                break;
            }
        }
        fout << endl;
    }

    fout.close();

    return;
}
Example #26
0
void scan_airspaces(const AIRCRAFT_STATE state, 
                    const Airspaces& airspaces,
                    const AirspaceAircraftPerformance& perf,
                    bool do_report,
                    const GeoPoint &target) 
{
  const fixed range(20000.0);

  const std::vector<Airspace> vn = airspaces.scan_nearest(state.Location);
  AirspaceVisitorPrint pvn("results/res-bb-nearest.txt",
                           do_report);
  std::for_each(vn.begin(), vn.end(), CallVisitor<AirspaceVisitor>(pvn));

  {
    AirspaceVisitorPrint pvisitor("results/res-bb-range.txt",
                                  do_report);
    airspaces.visit_within_range(state.Location, range, pvisitor);
  }

  {
    AirspaceVisitorClosest pvisitor("results/res-bb-closest.txt",
                                    state, perf);
    airspaces.visit_within_range(state.Location, range, pvisitor);
  }

  {
    const std::vector<Airspace> vi = airspaces.find_inside(state);
    AirspaceVisitorPrint pvi("results/res-bb-inside.txt",
                             do_report);
    std::for_each(vi.begin(), vi.end(), CallVisitor<AirspaceVisitor>(pvi));
  }
  
  {
    AirspaceIntersectionVisitorPrint ivisitor("results/res-bb-intersects.txt",
                                              "results/res-bb-intersected.txt",
                                              "results/res-bb-intercepts.txt",
                                              do_report,
                                              state, perf);
    GeoVector vec(state.Location, target);
    airspaces.visit_intersecting(state.Location, vec, ivisitor);
  }

  {
    AirspaceNearestSort ans(state.Location);
    const AbstractAirspace* as = ans.find_nearest(airspaces, range);
    if (do_report) {
      std::ofstream fout("results/res-bb-sortednearest.txt");
      if (as) {
        fout << *as << "\n";
      } else {
        fout << "# no nearest found\n";
      }
    }
  }

  {
    AirspaceSoonestSort ans(state, perf);
    const AbstractAirspace* as = ans.find_nearest(airspaces);
    if (do_report) {
      std::ofstream fout("results/res-bb-sortedsoonest.txt");
      if (as) {
        fout << *as << "\n";
      } else {
        fout << "# no soonest found\n";
      }
    }
  }

}
Example #27
0
//
// This is an example ROOT macro to show how to use a KAmper
//
void testSimpleKamper(const char* input, const char * out)
{
  KDataReader f(input);

  TH1D hAmpHA("hAmpHeatA", "hAmpHeatA", 10000,-5000, 5000);
  TH1D hAmpHC("hAmpHeatC", "hAmpHeatC", 10000,-5000, 5000);
  TH1D hAmpIA("hAmpIonA", "hAmpIonA", 10000,-5000, 5000);
  TH1D hAmpIB("hAmpIonB", "hAmpIonB", 10000,-5000, 5000);
  TH1D hAmpIC("hAmpIonC", "hAmpIonC", 10000,-5000, 5000);
  TH1D hAmpID("hAmpIonD", "hAmpIonD", 10000,-5000, 5000);

  KEvent *e = f.GetEvent();
  KPulseAnalysisRecord *prec = new KPulseAnalysisRecord;
  KSimpleKamper1 myKamper;
  int heatMinPeak = 250;
  int heatMaxPeak = 290;
  int ionMinPeak = 6500;
  int ionMaxPeak = 6700;
  
  for(Int_t i = 0; i < f.GetEntries(); i++){
    f.GetEntry(i);
    if (i % 500 == 0) cout << "entry " << i << endl;
    
    for(Int_t j = 0; j < e->GetNumBoloPulses(); j++){
      KRawBoloPulseRecord *p = (KRawBoloPulseRecord *)e->GetBoloPulse(j);
      if( strcmp(p->GetBolometerRecord()->GetDetectorName(), "FID802") != 0)
        continue;
      
      if(p->GetPulseLength() == 0)
        continue;
        
      myKamper.MakeKamp(p,prec);
      string name = p->GetChannelName();
      if(strcmp(p->GetChannelName(),"chaleur FID802AB") == 0){
        if(prec->GetPeakPosition() > heatMinPeak && prec->GetPeakPosition() < heatMaxPeak)
          hAmpHA.Fill(prec->GetAmp());
      }
      else if(strcmp(p->GetChannelName(),"centre FID802AB") == 0){
        if(prec->GetPeakPosition() > ionMinPeak && prec->GetPeakPosition() < ionMaxPeak)
          hAmpIA.Fill(prec->GetAmp());
      }
      else if(strcmp(p->GetChannelName(),"garde FID802AB") == 0){
        if(prec->GetPeakPosition() > ionMinPeak && prec->GetPeakPosition() < ionMaxPeak)
          hAmpIB.Fill(prec->GetAmp());
      }
      else if(strcmp(p->GetChannelName(),"chaleur FID802CD") == 0){
        if(prec->GetPeakPosition() > heatMinPeak && prec->GetPeakPosition() < heatMaxPeak)
          hAmpHC.Fill(prec->GetAmp());
      }
      else if(strcmp(p->GetChannelName(),"centre FID802CD") == 0){
        if(prec->GetPeakPosition() > ionMinPeak && prec->GetPeakPosition() < ionMaxPeak)
          hAmpIA.Fill(prec->GetAmp());
      }
      else if(strcmp(p->GetChannelName(),"garde FID802CD") == 0){
        if(prec->GetPeakPosition() > ionMinPeak && prec->GetPeakPosition() < ionMaxPeak)
          hAmpIB.Fill(prec->GetAmp());
      }
      
      
    }
  }

  
  TFile fout(out,"recreate");
  hAmpHA.Write();
  hAmpHC.Write();
  hAmpIA.Write();
  hAmpIB.Write();
  hAmpIC.Write();
  hAmpID.Write();
    
}
Example #28
0
int MainWindow::CliwocConverter( const QString &s_FilenameIn, const QString &s_FilenameOut,  const QString &s_FilenameConf, const int i_NumOfFiles )
{
    int             k               = 0;
    int             n               = 0;

    QString         InputStr        = "";
    QString         s_EventLabel    = "";

    QStringList     sl_Conf;

    unsigned int	ui_length		= 1;
    unsigned int	ui_filesize		= 1;

// **********************************************************************************************

    n = readFile( s_FilenameConf, sl_Conf );

    if ( n < 9 )
        return( _ERROR_ );

// **********************************************************************************************
// open input file

    QFile fin( s_FilenameIn );

    if ( fin.open( QIODevice::ReadOnly | QIODevice::Text ) == false )
        return( -10 );

    ui_filesize = fin.size();

    QTextStream tin( &fin );

// **********************************************************************************************
// open output file

    QFile fout( s_FilenameOut );

    if ( fout.open( QIODevice::WriteOnly | QIODevice::Text ) == false )
        return( -20 );

    QTextStream tout( &fout );

// **********************************************************************************************

    initProgress( i_NumOfFiles, s_FilenameIn, tr( "Converting..." ), 100 );

// **********************************************************************************************
// read file

// Header
    tout << k++ << "\t" << "Event label" << "\t" << "Date/Time" << "\t" << "Latitude" << "\t" << "Longitude";

    for ( int i=9; i<n; i++ )
    {
        if ( sl_Conf.at( i ).section( "\t", 0, 0 ) == "x" )
            tout << "\t" << sl_Conf.at( i ).section( "\t", 3, 3 ); // Column no 4: Parameter name
    }

    tout << endl;

    while ( ( tin.atEnd() == false ) && ( ui_length != (unsigned int) _APPBREAK_ ) )
    {
        InputStr  = tin.readLine();
        ui_length = incProgress( i_NumOfFiles, ui_filesize, ui_length, InputStr );

// Event label
        s_EventLabel = "@" + InputStr.mid( 34, 9 ).simplified() + "_" + InputStr.mid( 2597, 8 ).simplified() + "_" + InputStr.mid( 297, 30 ).simplified();

        s_EventLabel.replace( "EXTRACT ", "" );
        s_EventLabel.replace( ",", "" );
        s_EventLabel.replace( ".", "" );
        s_EventLabel.replace( "(", "-" );
        s_EventLabel.replace( ")", "" );
        s_EventLabel.replace( " ", "_" );
        s_EventLabel.replace( "_-_", "_" );
        s_EventLabel.replace( "_-", "_" );
        s_EventLabel.replace( "-_", "_" );
        s_EventLabel.replace( "__", "_" );
        s_EventLabel.replace( "'", "" );

        tout << k++ << "\t" << s_EventLabel << "\t";

// Date/Time
        QString s_DateTime = InputStr.mid( 0, 4 ) + tr( "-" ) + InputStr.mid( 4, 2 ) + tr( "-" ) + InputStr.mid( 6, 2 ) + tr( "T" ) + InputStr.mid( 8, 2 ) + tr( ":" ) + InputStr.mid( 10, 2 );
        s_DateTime.replace( " ", "0" );
        tout << s_DateTime << "\t";

// Position
        // Latitude
        if ( InputStr.mid( 12, 5 ) != "     " )
            tout << InputStr.mid( 12, 5 ).toFloat()/100. << "\t";
        else
            tout << "\t";

        // Longitude
        if ( InputStr.mid( 17, 6 ) != "      " )
        {
            float f_Longitude = InputStr.mid( 17, 6 ).toFloat()/100.;

            if ( f_Longitude > 180. )
                f_Longitude -=360;

            tout << f_Longitude;
        }
        else
            tout << "";

        for ( int i=9; i<n; i++ )
        {
            if ( sl_Conf.at( i ).section( "\t", 0, 0 ) == "x" )
            {
                QString s_Factor = sl_Conf.at( i ).section( "\t", 1, 1 );
                QString s_Entry  = InputStr.mid( sl_Conf.at( i ).section( "\t", 4, 4 ).toInt()-1, sl_Conf.at( i ).section( "\t", 6, 6 ).toInt() ).simplified();

                if ( s_Entry.isEmpty() == true )
                {
                    tout << "\t";
                }
                else
                {
                    if ( s_Factor == "T" )
                    {
                        s_Entry.replace( "\"", "''" );
                        tout << "\t~@" << s_Entry;
                    }
                    else
                    {
                        if ( s_Factor.isEmpty() == false )
                            tout << "\t" << s_Entry.toFloat()*s_Factor.toFloat();
                        else
                            tout << "\t" << s_Entry;
                    }
                }
            }
        }

        tout << endl;
    }

    resetProgress( i_NumOfFiles );

    fin.close();
    fout.close();

// **********************************************************************************************

    if ( ui_length == (unsigned int) _APPBREAK_ )
        return( _APPBREAK_ );

    return( _NOERROR_ );
}
Example #29
0
//
// Analyze_ECvsP - fit the EC/P vs P distributions
//
//                  fAna = output from eg2a DMS
//                  target = target name
//
void Analyze(char *fAna="Ana.root", char *target)
{
    Int_t i, j;
    
    const Int_t NPARAM = 3;
    TH1D *h1D[NPHOTONS][NPARAM];
    TH1D *h2D[NPHOTONS];
    
    char HistName1D[50];
    char strname[50];
    char *yname[NPARAM] = {"Amplitude","Mean","Sigma"};
    
    // open text file for the yields
    char OutFile[100];
    sprintf(OutFile,"ECtimeEClPhoton1_%s.dat",target);
    ofstream fout(OutFile);
    
    TCanvas *can[NPHOTONS]; // Canvas to plot histogram
    
    Double_t par[3]={1.0,1.0,1.0};
    TF1 *pol;
    TF1 *sig;
    
    // data files contain the trees
    printf("Analyzing file %s\n",fAna);
    TFile *fm = new TFile(fAna,"READ");
    TDirectory *tmp = fm->GetDirectory("PhotonID");
    
    for(j=0; j<NPHOTONS; j++){
        sprintf(cname,"can%i",j+1);
        sprintf(cname,"Canvas, Sector %i",j+1);
        can[j] = new TCanvas(cname,ctitle,50*j,0,600,600);
        can[j]->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
        can[j]->SetBorderSize(5);
        gStyle->SetOptStat(1111);
        can[j]->SetFillStyle(4000);
        
        sprintf(HistName1D,"ECtimeEClPhoton%i",j+1);
        h2D[j] = (TH1D*)tmp->Get(HistName1D);

        can[j]->cd();
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);

        h2D[j]->GetXaxis()->CenterTitle();
        h2D[j]->GetYaxis()->CenterTitle();
        h2D[j]->GetYaxis()->SetTitleOffset(yoff);

//        h2D[j]->SetAxisRange(0.0,0.3,"X");
//        h2D[j]->Draw("colz");

//        h2D[j]->FitSlicesY(0,0,-1,20,"QNR");//TODO MAYBE
    
        fout<<j+1<<"\t";
        
        
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);

        sprintf(strname,"%s",HistName1D);
        gaus = new TF1("gaus","gaus",-1,1); //ADJUST fit range
        TFitResultPtr r = h2D[j]->Fit("gaus","R");
        fout<<gaus->GetParameter(0)<<"\t"<<gaus->GetParameter(1)<<"\t"<<gaus->GetParameter(2)<<"\t";
        h2D[j]->Draw();
        
       	sprintf(OutCan,"ECtimeEClPhoton%i_%s.gif",j+1,target);
        can[j]->Print(OutCan);
        sprintf(OutCan,"ECtimeEClPhoton%i_%s.eps",j+1,target);
        can[j]->Print(OutCan);
    }
    fout.close(); // close the text file
}
Example #30
0
void
RemapHDF4::saveTrimmed(QString trimFile,
		       int dmin, int dmax,
		       int wmin, int wmax,
		       int hmin, int hmax)
{
  QProgressDialog progress("Saving trimmed volume",
			   "Cancel",
			   0, 100,
			   0);
  progress.setMinimumDuration(0);

  int nX, nY, nZ;
  nX = m_depth;
  nY = m_width;
  nZ = m_height;

  int mX, mY, mZ;
  mX = dmax-dmin+1;
  mY = wmax-wmin+1;
  mZ = hmax-hmin+1;

  int nbytes = m_height*m_width*m_bytesPerVoxel;
  uchar *tmp = new uchar[nbytes];

  uchar vt;
  if (m_voxelType == _UChar) vt = 0; // unsigned byte
  if (m_voxelType == _Char) vt = 1; // signed byte
  if (m_voxelType == _UShort) vt = 2; // unsigned short
  if (m_voxelType == _Short) vt = 3; // signed short
  if (m_voxelType == _Int) vt = 4; // int
  if (m_voxelType == _Float) vt = 8; // float

  QFile fout(trimFile);
  fout.open(QFile::WriteOnly);

  fout.write((char*)&vt, 1);
  fout.write((char*)&mX, 4);
  fout.write((char*)&mY, 4);
  fout.write((char*)&mZ, 4);

  int32 start[2], edges[2];
  start[0] = 0;
  start[1] = 0;
  edges[0] = m_width;
  edges[1] = m_height;

  for(uint i=dmin; i<=dmax; i++)
    {
      int32 sd_id = SDstart(m_imageList[i].toAscii().data(),
			    DFACC_READ);
      int32 sds_id = SDselect(sd_id, m_Index);
      int status = SDreaddata(sds_id,
			      start, NULL, edges,
			      (VOIDP)tmp);
      status = SDendaccess(sds_id);
      status = SDend(sd_id);
      
      for(uint j=wmin; j<=wmax; j++)
	{
	  memcpy(tmp+(j-wmin)*mZ*m_bytesPerVoxel,
		 tmp+(j*nZ + hmin)*m_bytesPerVoxel,
		 mZ*m_bytesPerVoxel);
	}

      fout.write((char*)tmp, mY*mZ*m_bytesPerVoxel);
      
      progress.setValue((int)(100*(float)(i-dmin)/(float)mX));
      qApp->processEvents();
    }

  fout.close();

  delete [] tmp;

  m_headerBytes = 13; // to be used for applyMapping function
}