示例#1
0
/* mapTri:
 * Map vertex indices from router_t to tripoly_t coordinates.
 */
static void mapTri(Dt_t * map, tri * tp)
{
    for (; tp; tp = tp->nxttri) {
	tp->v.i = vMap(map, tp->v.i);
	tp->v.j = vMap(map, tp->v.j);
    }
}
bool MapSerializer_stl::read_stla(
    const std::string& file_name, AbstractMapBuilder& builder)
{
    std::ifstream input(file_name.c_str()) ;
    if(input.fail()) {
        Logger::err("MapSerializer_stl")
                << "could not open file\'"
                << file_name << "\'" << std::endl ;
        return false ;
    }

    PointCmp cmp(eps_);
    typedef std::map<vec3, int, PointCmp> VertexMap;
    VertexMap vMap(cmp);
    int  index(0);  // the index of the current read vertex

    builder.begin_surface();

    while (!input.eof())
    {
        std::string line;
        getline(input, line);

        if (line.find("outer") != std::string::npos ||
                line.find("OUTER") != std::string::npos)
        {
            builder.begin_facet();

            for (unsigned int i=0; i<3; ++i)
            {
                getline(input, line);
                std::istringstream face_input(line) ;
                std::string dumy;
                double x, y, z;
                face_input >> dumy >> x >> y >> z;
                vec3 v(x, y, z);

                // has point been referenced before?
                VertexMap::iterator vMapIt = vMap.find(v);
                if ( vMapIt == vMap.end()) {
                    // No : add vertex and remember idx/vector mapping
                    builder.add_vertex(v) ;
                    builder.add_vertex_to_facet(index) ;
                    vMap[v] = index ++;
                } else {
                    // Yes : get index from map
                    builder.add_vertex_to_facet(vMapIt->second) ;
                }
            }

            builder.end_facet();
        }
    }
示例#3
0
 /** 
  * The current network state is gathered from the network.
  * 
  * @param factory powerflow factory 
  * @param network network controlled by @c factory
  * 
  * @return 
  */
 PFSolverHelper(PFFactory& factory, boost::shared_ptr<PFNetwork> network)
   : p_factory(factory), p_network(network), Xold(), Xdelta()
 {
   p_factory.setMode(State);
   mapper::BusVectorMap<PFNetwork> vMap(p_network);
   Xold = vMap.mapToVector();
   // Xold->print();
   X.reset(Xold->clone());
   Xdelta.reset(Xold->clone());
   Xdelta->zero();
   p_factory.setMode(Jacobian);
   mapper::FullMatrixMap<PFNetwork> jMap(p_network);
   J = jMap.mapToMatrix();
 }
示例#4
0
 /** 
  * This is called by the nonlinear solver each iteration to build
  * the RHS vector from the current network state.  This is also
  * responsible for updating the network state with the current
  * solution estimate, which assumes that it is called only once per
  * solver iteration.  This may not be true if certain methods are
  * used or if a finite difference Jacobian is computed by the
  * solver.
  * 
  * @param Xcur current state estimate
  * @param PQ computed RHS vector
  */
 void
 operator() (const math::Vector& Xcur, math::Vector& PQ)
 {
   // In both the Netwon-Raphson and PETSc nonlinear solver
   // implementations, this is called before the Jacobian builder, so
   // we may only need to map the solution back on to the network here.
   
   // X.print();
   update(Xcur);
   
   // set to build RHS vector
   p_factory.setMode(RHS);
   mapper::BusVectorMap<PFNetwork> vMap(p_network);
   
   // build the RHS vector
   vMap.mapToVector(PQ);
 }
示例#5
0
  /** 
   * The network state (voltage, phase) is updated with the current
   * estimate from the nonlinear solver.
   * 
   * FIXME: The problem here is that ...::mapToBus expects the
   * @e CHANGE (old - current)? in state variables. IMHO, there should
   * be a way to set the state variables directly.  The solver should
   * be responsible for making the @e entire estimate.
   *
   * @param Xcur current state estimate from the solver
   */
  void
  update(const math::Vector& Xcur)
  {
    
    Xdelta->equate(Xcur);
    Xdelta->scale(-1.0);
    Xdelta->add(*Xold);
    double snorm(Xdelta->norm2());
    if (Xdelta->processor_rank() == 0) {
      std::cout << "PFSolverHelper::update(): solution residual: " << snorm << std::endl;
    }

    // Xdelta->print();
    p_factory.setMode(RHS);
    mapper::BusVectorMap<PFNetwork> vMap(p_network);
    vMap.mapToBus(Xdelta);
    Xold->equate(Xcur);
    
    // Exchange data between ghost buses (I don't think we need to exchange data
    // between branches)
    p_network->updateBuses();
    
  }
示例#6
0
// -------------------------------------------------------------------------------
aiMesh* MakeSubmesh(const aiMesh *pMesh, const std::vector<unsigned int> &subMeshFaces, unsigned int subFlags)
{		
	aiMesh *oMesh = new aiMesh(); 
	std::vector<unsigned int> vMap(pMesh->mNumVertices,UINT_MAX);

	size_t numSubVerts = 0; 
	size_t numSubFaces = subMeshFaces.size();

	for(unsigned int i=0;i<numSubFaces;i++)	{
		const aiFace &f = pMesh->mFaces[subMeshFaces[i]];

		for(unsigned int j=0;j<f.mNumIndices;j++)	{
			if(vMap[f.mIndices[j]]==UINT_MAX)	{
				vMap[f.mIndices[j]] = numSubVerts++;
			}
		}		
	} 

	oMesh->mName = pMesh->mName;
		
	oMesh->mMaterialIndex = pMesh->mMaterialIndex;
	oMesh->mPrimitiveTypes = pMesh->mPrimitiveTypes;
	
	// create all the arrays for this mesh if the old mesh contained them
		
	oMesh->mNumFaces = subMeshFaces.size();
	oMesh->mNumVertices = numSubVerts;
	oMesh->mVertices = new aiVector3D[numSubVerts];
	if( pMesh->HasNormals() ) {
		oMesh->mNormals = new aiVector3D[numSubVerts];
	}

	if( pMesh->HasTangentsAndBitangents() )	{
		oMesh->mTangents = new aiVector3D[numSubVerts];
		oMesh->mBitangents = new aiVector3D[numSubVerts];
	}

	for( size_t a = 0;  pMesh->HasTextureCoords( a) ; ++a )	{
		oMesh->mTextureCoords[a] = new aiVector3D[numSubVerts];
		oMesh->mNumUVComponents[a] = pMesh->mNumUVComponents[a];
	}

	for( size_t a = 0; pMesh->HasVertexColors( a); ++a )	{
		oMesh->mColors[a] = new aiColor4D[numSubVerts];
	}

	// and copy over the data, generating faces with linear indices along the way
	oMesh->mFaces = new aiFace[numSubFaces];
	
	for(unsigned int a = 0; a < numSubFaces; ++a )	{

		const aiFace& srcFace = pMesh->mFaces[subMeshFaces[a]];
		aiFace& dstFace = oMesh->mFaces[a];
		dstFace.mNumIndices = srcFace.mNumIndices;
		dstFace.mIndices = new unsigned int[dstFace.mNumIndices];

		// accumulate linearly all the vertices of the source face
		for( size_t b = 0; b < dstFace.mNumIndices; ++b )	{
			dstFace.mIndices[b] = vMap[srcFace.mIndices[b]];
		}
	}

	for(unsigned int srcIndex = 0; srcIndex < pMesh->mNumVertices; ++srcIndex ) {
		unsigned int nvi = vMap[srcIndex]; 
		if(nvi==UINT_MAX) {
			continue;
		}

		oMesh->mVertices[nvi] = pMesh->mVertices[srcIndex];
		if( pMesh->HasNormals() ) {
			oMesh->mNormals[nvi] = pMesh->mNormals[srcIndex];
		}
		
		if( pMesh->HasTangentsAndBitangents() )	{
			oMesh->mTangents[nvi] = pMesh->mTangents[srcIndex];
			oMesh->mBitangents[nvi] = pMesh->mBitangents[srcIndex];
		}
		for( size_t c = 0, cc = pMesh->GetNumUVChannels(); c < cc; ++c )	{
				oMesh->mTextureCoords[c][nvi] = pMesh->mTextureCoords[c][srcIndex];
		}
		for( size_t c = 0, cc = pMesh->GetNumColorChannels(); c < cc; ++c )	{
			oMesh->mColors[c][nvi] = pMesh->mColors[c][srcIndex];
		}
	}

	if(~subFlags&AI_SUBMESH_FLAGS_SANS_BONES)	{			
		std::vector<unsigned int> subBones(pMesh->mNumBones,0);

		for(unsigned int a=0;a<pMesh->mNumBones;++a)	{
			const aiBone* bone = pMesh->mBones[a];

			for(unsigned int b=0;b<bone->mNumWeights;b++)	{
				unsigned int v = vMap[bone->mWeights[b].mVertexId];

				if(v!=UINT_MAX) {
					subBones[a]++;
				}
			}
		}

		for(unsigned int a=0;a<pMesh->mNumBones;++a)	{
			if(subBones[a]>0) {
				oMesh->mNumBones++;
			}
		}

		if(oMesh->mNumBones) {
			oMesh->mBones = new aiBone*[oMesh->mNumBones]();
			unsigned int nbParanoia = oMesh->mNumBones;

			oMesh->mNumBones = 0; //rewind

			for(unsigned int a=0;a<pMesh->mNumBones;++a)	{
				if(subBones[a]==0) {
					continue; 
				}
				aiBone *newBone = new aiBone;
				oMesh->mBones[oMesh->mNumBones++] = newBone;

				const aiBone* bone = pMesh->mBones[a];

				newBone->mName = bone->mName;
				newBone->mOffsetMatrix = bone->mOffsetMatrix;
				newBone->mWeights = new aiVertexWeight[subBones[a]];

				for(unsigned int b=0;b<bone->mNumWeights;b++)	{
					const unsigned int v = vMap[bone->mWeights[b].mVertexId];

					if(v!=UINT_MAX)	{	
						aiVertexWeight w(v,bone->mWeights[b].mWeight);
						newBone->mWeights[newBone->mNumWeights++] = w;
					}
				}
			}

			ai_assert(nbParanoia==oMesh->mNumBones);
			(void)nbParanoia; // remove compiler warning on release build
		}
	}					 

	return oMesh;
}
示例#7
0
void combineBins(int mass, double scale_factor = 1.0){ //mass = mass of tprime quark

  //define some parameters
  //char fname[100]={"data/mujets_821/tprime_mujets_2D_821ipb.root"}; //input file name
  char fname[100]={"data/ejets_3560/tprime_ejets_2D_3560ipb.root"}; //input file name
  char oname[256]; //output file name
  char sname[100]; //name of signal histogram
  //sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_15jul2011test.root",mass);
  sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_test.root",mass);
  sprintf(sname,"TPrime%i_HtvsMfit",mass);
  char bname[20][100]={ //array of data and background histograms
    "Data_HtvsMfit", //data histogram must be first in this list
    "TTjets_HtvsMfit",
    "Ewk_HtvsMfit",
    "TPrime%i_HtvsMfit_JESup",
    "TPrime%i_HtvsMfit_JESdown",
    "TTjets_HtvsMfit_JESup",
    "TTjets_HtvsMfit_JESdown",
    "Ewk_HtvsMfit_JESup",
    "Ewk_HtvsMfit_JESdown"
  };
  
  int nb=9; //number of histograms in list
  int n_skip=3; // starting with this index, do not consider for background normalization
  float femax=0.20; //max fractional error in each bin of background histogram

  TFile *f = TFile::Open(fname);
  if (f==NULL) {
    printf("Cannot open file '%s'\n",fname);
    return;
  }

  TH2F* hs; f->GetObject(sname,hs); 
  // Gena: scale signal template to proper cross section
  hs->Scale(scale_factor);
  if (hs==NULL) {
    printf("Cannot find histogram '%s' in '%s'\n",sname,fname);
    return;
  }

  //figure out the binning
  int nx = hs->GetNbinsX()+2;
  int ny = hs->GetNbinsY()+2;

  // cross check printout
  std::cout << "2D hist name: " << hs->GetName() << std::endl;
  std::cout << "Integral with overflow: " << hs->Integral(0,nx-1,0,ny-1) << std::endl;
  std::cout << "Integral no overflow: " << hs->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;

  TH2F *hb = (TH2F*)hs->Clone(); 
  hb->SetName("hb");
  hb->Reset();
  TH2F *hX[20];
  for (int i=0;i<nb;i++){
    std::string sBName(bname[i]);
    // GENA: get names for signal JES histos
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){

      sprintf(bname[i],sBName.c_str(),mass);
      std::cout << bname[i] << std::endl;
    }

    f->GetObject(bname[i],hX[i]); 

    // GENA: scale JES signal templates to proper cross section
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){
      hX[i]->Scale(scale_factor);      
    }
    if (hX[i]==NULL) {
      printf("Cannot find histogram '%s' in '%s'\n",bname[i],fname);
      return;
    }
    //hX[i]->Print("base");
    std::cout << "2D hist name: " << hX[i]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << hX[i]->Integral(0,nx-1,0,ny-1) << std::endl;
    std::cout << "Integral no overflow: " << hX[i]->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;
    //sum all background histograms into hb; do not add the data histogram
    if (i>0 && i<n_skip) hb->Add(hX[i]); 
  }

  //figure out the binning
  //int nx = hs->GetNbinsX()+2;
  //int ny = hs->GetNbinsY()+2;
  int nbin=nx*ny;
  std::cout << "number of bins: x="<<nx<<", y="<<ny<<std::endl;
  
  //book some 1d histograms with the same number of bins for diagnostics
  TH1F *h1sb = new TH1F("h1sb","h1sb",nbin,0,nbin);
  TH1F *h1s = new TH1F("h1s","h1s",nbin,0,nbin);
  TH1F *h1b = new TH1F("h1b","h1b",nbin,0,nbin);
  // GENA: vector to create 2D->1D bin map
  std::vector<std::vector<int> > vMap(nbin);

  float xs,xb;
  //xsb holds the s/b values for each bin
  //xx are the histogram contents 
  //(0=signal, 1=total background, 2=data, 3...nb-1=individual backgrounds) GENA: nb+1 ?
  float xsb[30000],xx[30000][20],xe[30000][20];
  int ibin; 
  double _sum = 0.0;
  for (int i=0;i<nx;i++){
    for (int j=0;j<ny;j++){

      ibin=hs->GetBin(i,j);

      // GENA: Will fill each bin with its original index
      vMap[ibin].push_back(ibin);

      xs=hs->GetBinContent(ibin);
      xb=hb->GetBinContent(ibin);
      //compute signal/background
      if (xb>0) {
	xsb[ibin]=xs/xb;
      }else{
	if (xs>0){
	  xsb[ibin]=999;
	}else{
	  xsb[ibin]=0;
	}
      }
      xx[ibin][0]=xs;
      xe[ibin][0]=hs->GetBinError(ibin);
      xx[ibin][1]=xb;
      xe[ibin][1]=hb->GetBinError(ibin);
      for (int k=0;k<nb;k++){
	xx[ibin][k+2]=hX[k]->GetBinContent(ibin);
	xe[ibin][k+2]=hX[k]->GetBinError(ibin);
      }
      if (xb>0) h1sb->SetBinContent(ibin,xs/xb);
      h1s->SetBinContent(ibin,xx[ibin][0]);
      h1s->SetBinError(ibin,xe[ibin][0]);
      h1b->SetBinContent(ibin,xx[ibin][1]);
      h1b->SetBinError(ibin,xe[ibin][1]);
      
      _sum += xx[ibin][0];
    }
  }

  std::cout << "SUM: " << _sum << std::endl;

  //sort all histogram bins in decreasing s/b
  int nswap=1;
  float xtmp;

  // GENA: for bin map
  int ibin_tmp;

  while (nswap>0) {
    nswap=0;
    for (int i=0;i<nbin-1;i++) {
      if (xsb[i]<xsb[i+1]){
	xtmp=xsb[i];
	xsb[i]=xsb[i+1];
	xsb[i+1]=xtmp;

	// GENA: for bin map
	ibin_tmp = vMap[i][0];
	vMap[i][0] = vMap[i+1][0];
	vMap[i+1][0] = ibin_tmp;

	for (int j=0;j<nb+2;j++){
	  xtmp=xx[i][j];
	  xx[i][j]=xx[i+1][j];
	  xx[i+1][j]=xtmp;

	  xtmp=xe[i][j];
	  xe[i][j]=xe[i+1][j];
	  xe[i+1][j]=xtmp;
	}
	nswap=nswap+1;
      }
    }
  }

  //these histograms have the bins ordered in decrerasing s/b for diagnostics
  TH1F *h1sb1 = new TH1F("h1sb1","h1sb1",nbin,0,nbin);
  TH1F *h1fe1 = new TH1F("h1fe1","h1fe1",nbin,0,nbin);
  TH1F *h1s1 = new TH1F("h1s1","h1s1",nbin,0,nbin);
  TH1F *h1b1 = new TH1F("h1b1","h1b1",nbin,0,nbin);
  for (int i=0;i<nbin;i++){
    h1sb1->SetBinContent(i+1,xsb[i]);
    if (xx[i][1]>0) h1fe1->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s1->SetBinContent(i+1,xx[i][0]);
    h1s1->SetBinError(i+1,xe[i][0]);
    h1b1->SetBinContent(i+1,xx[i][1]);
    h1b1->SetBinError(i+1,xe[i][1]);
  }


  //combine bins starting with the highest s/b until the fractional error in
  //the total backround in every bin is smaller than femax
  int ncomb=1;
  //float xtmp;
  float fe=0;
  while (ncomb>0) {
    ncomb=0;
    for (int i=0;i<nbin-1;i++){

      if (xx[i][1]>0){
	fe=xe[i][1]/xx[i][1]; //fractional error in background
      }else{
	fe=1;
      }
      if (fe>femax){

	// GENA: write down bin
	for (std::vector<int>::const_iterator vi=vMap[i+1].begin();
	     vi != vMap[i+1].end(); ++vi){
	  vMap[i].push_back(*vi);
	}
	//move all successive bins up
	vMap.erase(vMap.begin()+i+1);

	for (int k=0;k<nb+2;k++){ //add the next bin
	  xx[i][k]=xx[i][k]+xx[i+1][k];
	  xe[i][k]=sqrt(xe[i][k]*xe[i][k]+xe[i+1][k]*xe[i+1][k]);
	  for (int j=i+1;j<nbin-1;j++){ //move all successive bins up
	    xx[j][k]=xx[j+1][k];
	    xe[j][k]=xe[j+1][k];
	  }
	}
	ncomb++;
	nbin=nbin-1; //decrease the total number of bins

      }
    }
  }


  //GENA: open the map file
  std::ofstream mapFile;
  mapFile.open("bin.map");
  int bin_count = 0;
  for (std::vector<std::vector<int> >::const_iterator i=vMap.begin();
       i != vMap.end(); ++i){

    mapFile << " " << i-vMap.begin()+1 << ":";

    for(std::vector<int>::const_iterator j=i->begin();
	j != i->end(); ++j){
      mapFile << " " << *j;
      ++bin_count;
    }

    mapFile << std::endl;

  }
  //GENA: close the map file
  mapFile.close();

  //these are the output histograms
  TFile *f2 = TFile::Open(oname,"recreate");
  TH1F *h1feb2 = new TH1F("h1fe2","h1fe2",nbin,0,nbin);
  TH1F *h1s2 = new TH1F(sname,sname,nbin,0,nbin);
  TH1F *h1b2 = new TH1F("h1b2","h1b2",nbin,0,nbin);
  TH1F *h1X2[20];
  for (int i=0;i<nb;i++){
    h1X2[i] = new TH1F(bname[i],bname[i],nbin,0,nbin);
  }
  for (int i=0;i<nbin;i++){
    h1feb2->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s2->SetBinContent(i+1,xx[i][0]);
    h1s2->SetBinError(i+1,xe[i][0]);
    h1b2->SetBinContent(i+1,xx[i][1]);
    h1b2->SetBinError(i+1,xe[i][1]);
    for (int j=0;j<nb;j++){
      h1X2[j]->SetBinContent(i+1,xx[i][j+2]);
      h1X2[j]->SetBinError(i+1,xe[i][j+2]);
    }
  }
  
  std::cout << "Merged 1D hist name: " << h1s2->GetName() << std::endl;
  std::cout << "Integral with overflow: " << h1s2->Integral(0,nbin+1) << std::endl;
  std::cout << "Integral no overflow: " << h1s2->Integral(1,nbin) << std::endl << std::endl;
  h1s2->Write();
  for (int j=0;j<nb;j++){
    std::cout << "Merged 1D hist name: " << h1X2[j]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << h1X2[j]->Integral(0,nbin+1) << std::endl;
    std::cout << "Integral no overflow: " << h1X2[j]->Integral(1,nbin) << std::endl << std::endl;
    h1X2[j]->Write();
  }
  
  h1s2->Print("base");

  f2->Close();
  f->Close();

  std::cout << "map size: " << vMap.size() << " combined bins" << std::endl;
  std::cout << "total bins merged: " << bin_count << std::endl;
}
示例#8
0
    bool
    STLReader::
    read_stla(std::istream& _in, TriMeshModelPtr t) const
    {

        if (!t)
        {
            return false;
        }

        unsigned int               i;
        Eigen::Vector3f            v;
        Eigen::Vector3f            n;
        std::vector<unsigned int> vhandles;

        CmpVec comp(eps_);
        std::map<Eigen::Vector3f, unsigned int, CmpVec>            vMap(comp);
        std::map<Eigen::Vector3f, unsigned int, CmpVec>::iterator  vMapIt;

        std::string line;

        bool facet_normal(false);

        while (_in && !_in.eof())
        {

            // Get one line
            std::getline(_in, line);

            if (_in.bad())
            {
                VR_ERROR << "  Warning! Could not read stream properly!\n";
                return false;
            }

            // Trim Both leading and trailing spaces
            trimStdString(line);

            // Normal found?
            if (line.find("facet normal") != std::string::npos)
            {
                std::stringstream strstream(line);

                std::string garbage;

                // facet
                strstream >> garbage;

                // normal
                strstream >> garbage;

                strstream >> n[0];
                strstream >> n[1];
                strstream >> n[2];

                facet_normal = true;
            }

            // Detected a triangle
            if ((line.find("outer") != std::string::npos) || (line.find("OUTER") != std::string::npos))
            {

                vhandles.clear();

                for (i = 0; i < 3; ++i)
                {
                    // Get one vertex
                    std::getline(_in, line);
                    trimStdString(line);

                    std::stringstream strstream(line);

                    std::string garbage;
                    strstream >> garbage;

                    strstream >> v[0];
                    strstream >> v[1];
                    strstream >> v[2];

                    v *= scaling;

                    // has vector been referenced before?
                    if ((vMapIt = vMap.find(v)) == vMap.end())
                    {
                        // No : add vertex and remember idx/vector mapping
                        int handle = int (t->vertices.size());
                        t->addVertex(v);//_bi.add_vertex(v);
                        vhandles.push_back(handle);
                        vMap[v] = handle;
                    }
                    else
                        // Yes : get index from map
                    {
                        vhandles.push_back(vMapIt->second);
                    }
                }

                // Add face only if it is not degenerated
                if ((vhandles[0] != vhandles[1]) &&
                    (vhandles[0] != vhandles[2]) &&
                    (vhandles[1] != vhandles[2]))
                {
                    MathTools::TriangleFace f;
                    f.set(vhandles[0], vhandles[1], vhandles[2]);

                    if (facet_normal)
                    {
                        unsigned int noId = t->normals.size();
                        t->addNormal(n);
                        f.setNormal(noId, noId, noId);
                    }

                    int fh = int(t->faces.size());
                    t->addFace(f);
                    //_bi.add_face(vhandles);
                    facet_normal = false;
                }
            }
示例#9
0
/**
 * Execute the iterative solve portion of the application using a
 * hand-coded Newton-Raphson solver
 * @return false if an error was encountered in the solution
 */
bool gridpack::powerflow::PFAppModule::solve()
{
  bool ret = true;
  gridpack::utility::CoarseTimer *timer =
    gridpack::utility::CoarseTimer::instance();
  int t_total = timer->createCategory("Powerflow: Total Application");
  timer->start(t_total);

  // set YBus components so that you can create Y matrix
  int t_fact = timer->createCategory("Powerflow: Factory Operations");
  timer->start(t_fact);
  p_factory->setYBus();
  timer->stop(t_fact);

  int t_cmap = timer->createCategory("Powerflow: Create Mappers");
  timer->start(t_cmap);
  p_factory->setMode(YBus); 
#if 0
  gridpack::mapper::FullMatrixMap<PFNetwork> mMap(p_network);
#endif
  timer->stop(t_cmap);
  int t_mmap = timer->createCategory("Powerflow: Map to Matrix");
  timer->start(t_mmap);
#if 0
  boost::shared_ptr<gridpack::math::Matrix> Y = mMap.mapToMatrix();
  p_busIO->header("\nY-matrix values\n");
  Y->print();
//  Y->save("Ybus.m");
#endif
  timer->stop(t_mmap);

  timer->start(t_fact);
  p_factory->setMode(S_Cal);
  timer->stop(t_fact);
  timer->start(t_cmap);
  gridpack::mapper::BusVectorMap<PFNetwork> vvMap(p_network);
  timer->stop(t_cmap);
  int t_vmap = timer->createCategory("Powerflow: Map to Vector");

  // make Sbus components to create S vector
  timer->start(t_fact);
  p_factory->setSBus();
  timer->stop(t_fact);
//  p_busIO->header("\nIteration 0\n");

  // Set PQ
  timer->start(t_cmap);
  p_factory->setMode(RHS); 
  gridpack::mapper::BusVectorMap<PFNetwork> vMap(p_network);
  timer->stop(t_cmap);
  timer->start(t_vmap);
#ifdef USE_REAL_VALUES
  boost::shared_ptr<gridpack::math::RealVector> PQ = vMap.mapToRealVector();
#else
  boost::shared_ptr<gridpack::math::Vector> PQ = vMap.mapToVector();
#endif
  timer->stop(t_vmap);
//  PQ->print();
  timer->start(t_cmap);
  p_factory->setMode(Jacobian);
  gridpack::mapper::FullMatrixMap<PFNetwork> jMap(p_network);
  timer->stop(t_cmap);
  timer->start(t_mmap);
#ifdef USE_REAL_VALUES
  boost::shared_ptr<gridpack::math::RealMatrix> J = jMap.mapToRealMatrix();
#else
  boost::shared_ptr<gridpack::math::Matrix> J = jMap.mapToMatrix();
#endif
  timer->stop(t_mmap);
//  p_busIO->header("\nJacobian values\n");
//  J->print();

  // Create X vector by cloning PQ
#ifdef USE_REAL_VALUES
  boost::shared_ptr<gridpack::math::RealVector> X(PQ->clone());
#else
  boost::shared_ptr<gridpack::math::Vector> X(PQ->clone());
#endif

  gridpack::utility::Configuration::CursorPtr cursor;
  cursor = p_config->getCursor("Configuration.Powerflow");
  // Create linear solver
  int t_csolv = timer->createCategory("Powerflow: Create Linear Solver");
  timer->start(t_csolv);
#ifdef USE_REAL_VALUES
  gridpack::math::RealLinearSolver solver(*J);
#else
  gridpack::math::LinearSolver solver(*J);
#endif
  solver.configure(cursor);
  timer->stop(t_csolv);

  gridpack::ComplexType tol = 2.0*p_tolerance;
  int iter = 0;

  // First iteration
  X->zero(); //might not need to do this
  //p_busIO->header("\nCalling solver\n");
  int t_lsolv = timer->createCategory("Powerflow: Solve Linear Equation");
  timer->start(t_lsolv);
//    char dbgfile[32];
//    sprintf(dbgfile,"j0.bin");
//    J->saveBinary(dbgfile);
//    sprintf(dbgfile,"pq0.bin");
//    PQ->saveBinary(dbgfile);
  try {
    solver.solve(*PQ, *X);
  } catch (const gridpack::Exception e) {
    p_busIO->header("Solver failure\n\n");
    timer->stop(t_lsolv);
    return false;
  }
  timer->stop(t_lsolv);
  tol = PQ->normInfinity();

  // Create timer for map to bus
  int t_bmap = timer->createCategory("Powerflow: Map to Bus");
  int t_updt = timer->createCategory("Powerflow: Bus Update");
  char ioBuf[128];

  while (real(tol) > p_tolerance && iter < p_max_iteration) {
    // Push current values in X vector back into network components
    // Need to implement setValues method in PFBus class in order for this to
    // work
    timer->start(t_bmap);
    p_factory->setMode(RHS);
    vMap.mapToBus(X);
    timer->stop(t_bmap);

    // Exchange data between ghost buses (I don't think we need to exchange data
    // between branches)
    timer->start(t_updt);
    p_network->updateBuses();
    timer->stop(t_updt);

    // Create new versions of Jacobian and PQ vector
    timer->start(t_vmap);
#ifdef USE_REAL_VALUES
    vMap.mapToRealVector(PQ);
#else
    vMap.mapToVector(PQ);
#endif
//    p_busIO->header("\nnew PQ vector\n");
//    PQ->print();
    timer->stop(t_vmap);
    timer->start(t_mmap);
    p_factory->setMode(Jacobian);
#ifdef USE_REAL_VALUES
    jMap.mapToRealMatrix(J);
#else
    jMap.mapToMatrix(J);
#endif
    timer->stop(t_mmap);

    // Create linear solver
    timer->start(t_lsolv);
    X->zero(); //might not need to do this
//    sprintf(dbgfile,"j%d.bin",iter+1);
//    J->saveBinary(dbgfile);
//    sprintf(dbgfile,"pq%d.bin",iter+1);
//    PQ->saveBinary(dbgfile);
    try {
      solver.solve(*PQ, *X);
    } catch (const gridpack::Exception e) {
      p_busIO->header("Solver failure\n\n");
      timer->stop(t_lsolv);
      return false;
    }
    timer->stop(t_lsolv);

    tol = PQ->normInfinity();
    sprintf(ioBuf,"\nIteration %d Tol: %12.6e\n",iter+1,real(tol));
    p_busIO->header(ioBuf);
    iter++;
  }

  if (iter >= p_max_iteration) ret = false;

  // Push final result back onto buses
  timer->start(t_bmap);
  p_factory->setMode(RHS);
  vMap.mapToBus(X);
  timer->stop(t_bmap);

  // Make sure that ghost buses have up-to-date values before printing out
  // results
  timer->start(t_updt);
  p_network->updateBuses();
  timer->stop(t_updt);
  timer->stop(t_total);
  return ret;
}