Esempio n. 1
0
void Project::computeCrownIntersections()
{
    for(int i=0; i<get_sizeTreeCV()-1; i++)
    {
        if(get_TreeCloud(i).isCrownExist()==true && get_TreeCloud(i).get_TreeCrown().isConvexhull3DExist()==true)
        {
            pcl::PolygonMesh mesh1(get_TreeCloud(i).get_TreeCrown().get3DConvexhull().getMesh());
            QString name1 = get_TreeCloud(i).get_name();
            for(int j=i+1; j<get_sizeTreeCV(); j++)
            {
                if(get_TreeCloud(j).isCrownExist()==true && get_TreeCloud(j).get_TreeCrown().isConvexhull3DExist()==true)
                {
                    pcl::PointXYZI c1 = get_TreeCloud(i).get_TreeCrown().getCrownPosition();
                    pcl::PointXYZI c2 = get_TreeCloud(j).get_TreeCrown().getCrownPosition();
                    float l1 = get_TreeCloud(i).get_TreeCrown().getCrownLenghtXY();
                    float l2 = get_TreeCloud(j).get_TreeCrown().getCrownLenghtXY();

                    if(isIntersectionPossible(c1,l1,c2,l2) == true )
                    {
                        pcl::PolygonMesh mesh2(get_TreeCloud(j).get_TreeCrown().get3DConvexhull().getMesh());
                        QString name2 = get_TreeCloud(j).get_name();
                        PolyhedronIntersections3D p(mesh1,mesh2,name1,name2);
                        if(p.getSurface() > 0 && p.getVolume()>0)
                        {
                            m_intersections3D.push_back(p);
                        }
                    }
                }
            }
        }
    }
}
Esempio n. 2
0
void KNDdeTorusCollocation::importTangent(KNVector& out, KNVector& Re, KNVector& Im, double alpha)
{
  // alpha /= 2.0;
  for (size_t i2 = 0; i2 < nint2; i2++)
  {
    for (size_t i1 = 0; i1 < nint1; i1++)
    {
      for (size_t j2 = 0; j2 < ndeg2; j2++)
      {
        for (size_t j1 = 0; j1 < ndeg1; j1++)
        {
          const size_t idx1 = idxmap(j1, j2, i1, i2);
          const double t1 = (mesh1(j1) + i1) / ((double)nint1);
          const double t2 = (mesh2(j2) + i2) / ((double)nint2);
          for (size_t p = 0; p < NDIM; p++)
          {
            out(p + NDIM*idx1) = cos(-alpha * t1 + 2 * M_PI * t2) * Re(p + NDIM * (j1 + i1 * ndeg1)) + sin(-alpha * t1 + 2 * M_PI * t2) * Im(p + NDIM * (j1 + i1 * ndeg1));
          }
        }
      }
    }
  }
  double norm = sqrt(integrate(out, out));
  out /= norm;
}
Esempio n. 3
0
TEST(Mesh,CompareRealSpace) {
  alps::gf::real_space_index_mesh::container_type points1(boost::extents[20][3]);
  alps::gf::real_space_index_mesh::container_type points2(boost::extents[20][3]);
  alps::gf::real_space_index_mesh::container_type points3(boost::extents[20][3]);
  alps::gf::real_space_index_mesh::container_type points4(boost::extents[3][20]);
  for (int i=0; i<points1.num_elements(); ++i) {
    *(points1.origin()+i)=i;
    *(points2.origin()+i)=i;
    *(points3.origin()+i)=i+1;
    *(points4.origin()+i)=i;
  }

  alps::gf::real_space_index_mesh mesh1(points1);
  alps::gf::real_space_index_mesh mesh2(points2);
  alps::gf::real_space_index_mesh mesh3(points3);
  alps::gf::real_space_index_mesh mesh4(points4);

  EXPECT_TRUE(mesh1==mesh2);
  EXPECT_TRUE(mesh1!=mesh3);
  EXPECT_TRUE(mesh1!=mesh4);

  EXPECT_FALSE(mesh1==mesh3);
  EXPECT_FALSE(mesh1!=mesh2);
  EXPECT_FALSE(mesh1==mesh4);
}
Esempio n. 4
0
int main(int argc, char** argv)
{
	Display display(800, 600, "Test");
	Shader shader("./shaders/basicshader");
	Shader shader2("./shaders/basicshader");
	Vertex vertices[] = { Vertex(glm::vec3(-0.5, -0.5, 0), glm::vec2(0.0, 0.0)),
						Vertex(glm::vec3(0, 0.5, 0) , glm::vec2(0.5, 1.0)),
						Vertex(glm::vec3(0.5, -0.5, 0), glm::vec2(1.0, 0.0)) };
	unsigned int indices[] = { 0, 1, 2 };

	Texture texture("images/test.png");
	Transform transform;
	Transform origin;
	origin.SetPos(glm::vec3(0, 5, 0));

	float counter = 0.0f;
	Camera camera(glm::vec3(0, 0, -30), 70.0f, (float)WIDTH/HEIGHT , 0.01f, 1000.0f);



	//Mesh mesh(vertices, sizeof(vertices)/sizeof(vertices[0]), indices, sizeof(indices)/sizeof(indices[0]));
	Mesh mesh2("./images/mountainsuv.obj");
	//Mesh mesh3("./images/monkey3.obj");

	//Console stuff:
	std::cout << "   Controls:" << '\n' <<'\n'<< "   W A S D = sus stanga jos dreapta"
			  << '\n' << "  z = zoom in"
			  << '\n' << "  x = zoom out"
			  << '\n' << "  UP ARROW  = rotatie verticala sus"
			  << '\n' << "  DOWN ARROW  = rotatie verticala jos"
			  << '\n' << "  LEFT ARROW  = rotatie orizontala stanga"
			  << '\n' << "  RIGHT ARROW  = rotatie verticala dreapta";

	
	while (!display.IsClosed())
	{
		display.Clear(0.0f, 0.5f, 0.3f, 0.0f);

		shader.Bind();
		texture.Bind();

		
		mesh2.Draw();



		//mesh.Draw()
		shader.Update(transform, origin, camera);
		display.Update(transform);
		counter += 0.001f;

	}

	return 0;
}
Esempio n. 5
0
TEST(Mesh,CompareIndex) {
  alps::gf::index_mesh mesh1(20);
  alps::gf::index_mesh mesh2(20);
  alps::gf::index_mesh mesh3(19);

  EXPECT_TRUE(mesh1==mesh2);
  EXPECT_TRUE(mesh1!=mesh3);

  EXPECT_FALSE(mesh1==mesh3);
  EXPECT_FALSE(mesh1!=mesh2);
}
Esempio n. 6
0
TEST(Mesh,CompareITime) {
  alps::gf::itime_mesh mesh1(5.0, 20);
  alps::gf::itime_mesh mesh2(5.0, 20);
  alps::gf::itime_mesh mesh3(4.0, 20);

  EXPECT_TRUE(mesh1==mesh2);
  EXPECT_TRUE(mesh1!=mesh3);

  EXPECT_FALSE(mesh1==mesh3);
  EXPECT_FALSE(mesh1!=mesh2);
}
Esempio n. 7
0
TEST(Mesh,CompareMatsubara) {
  alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_NEGATIVE> mesh1(5.0, 20);
  alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_NEGATIVE> mesh2(5.0, 20);
  alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_NEGATIVE> mesh3(4.0, 20);

  EXPECT_TRUE(mesh1==mesh2);
  EXPECT_TRUE(mesh1!=mesh3);

  EXPECT_FALSE(mesh1==mesh3);
  EXPECT_FALSE(mesh1!=mesh2);

}
Esempio n. 8
0
void
detectHoles(MeshLib::Mesh const& mesh,
	std::vector<std::size_t> erase_elems,
	std::size_t const expected_n_holes)
{
	std::vector<MeshLib::Node*> nodes = MeshLib::copyNodeVector(mesh.getNodes());
	std::vector<MeshLib::Element*> elems = MeshLib::copyElementVector(mesh.getElements(),nodes);
	for (auto pos : erase_elems)
	{
		delete elems[pos];
		elems.erase(elems.begin()+pos);
	}
	MeshLib::Mesh mesh2("mesh2", nodes, elems);
	ASSERT_EQ(expected_n_holes, MeshLib::MeshValidation::detectHoles(mesh2));
};
Esempio n. 9
0
void KNDdeTorusCollocation::Save(const char* dat, const char* idx, const KNVector& in)
{
  // writing to file for plotting
  std::ofstream ff(dat);
  for (size_t i2 = 0; i2 < nint2; i2++)
  {
    for (size_t j2 = 0; j2 < ndeg2; j2++)
    {
      for (size_t i1 = 0; i1 < nint1; i1++)
      {
        for (size_t j1 = 0; j1 < ndeg1; j1++)
        {
          const size_t idx1 = idxmap(j1, j2, i1, i2);
          for (size_t p = 0; p < NDIM; p++)
          {
            ff << in(p + NDIM*idx1) << "\t";
          }
        }
      }
      ff << "\n";
    }
  }

  std::ofstream gg(idx);
  for (size_t i1 = 0; i1 < nint1; i1++)
  {
    for (size_t j1 = 0; j1 < ndeg1; j1++)
    {
      const double t1 = (mesh1(j1) + i1) / ((double)nint1);
      gg << t1 << "\t";
    }
  }
  gg << "\n";
  for (size_t i2 = 0; i2 < nint2; i2++)
  {
    for (size_t j2 = 0; j2 < ndeg2; j2++)
    {
      const double t2 = (mesh2(j2) + i2) / ((double)nint2);
      gg << t2 << "\t";
    }
  }
  gg << "\n";
}
Esempio n. 10
0
Mesh createMesh2D(const Mesh & mesh, const RVector & y, 
                  int front, int back, bool adjustBack){
    Mesh mesh2(2);
    
    bool first = true;
    for (Index iy = 0; iy < y.size(); iy ++){
        for (Index in = 0; in < mesh.nodeCount(); in ++){
            int marker = 0;
            if (first) marker = mesh.node(in).marker();
            
            mesh2.createNode(mesh.node(in).pos() + RVector3(0.0, y[iy]), marker);
        }
        first = false;
    }
    std::vector < Node * > nodes;
    for (Index iy = 1; iy < y.size(); iy ++){
        first = true;
        for (Index in = 0; in < mesh.boundaryCount(); in ++){
            uint nn = mesh.boundary(in).nodeCount();
            nodes.resize(nn * 2) ;
            
            nodes[0] = & mesh2.node((iy - 1) * mesh.nodeCount() + mesh.boundary(in).node(0).id());
            nodes[1] = & mesh2.node((iy - 1) * mesh.nodeCount() + mesh.boundary(in).node(1).id());
            nodes[2] = & mesh2.node((iy * mesh.nodeCount() + mesh.boundary(in).node(1).id()));
            nodes[3] = & mesh2.node((iy * mesh.nodeCount() + mesh.boundary(in).node(0).id()));
            
            mesh2.createCell(nodes, mesh.boundary(in).marker());
            
            if (iy == 1){
                // create top layer boundaries // in revers direction so the outer normal shows downward into the mesh
            }
            if (iy == y.size()-1){
                // create bottom layer boundaries
            }
        }
        first = false;
    }
    
    
    return mesh;
}
Esempio n. 11
0
void Animation::envisionIntro()
{
	Vertex square[] = { Vertex(glm::vec3(0, 0, 0), glm::vec2(0, 0)),
		Vertex(glm::vec3(1, 0, 0), glm::vec2(1, 0)),
		Vertex(glm::vec3(0, 1, 0), glm::vec2(0, 1)),

		Vertex(glm::vec3(1, 1, 0), glm::vec2(1, 1)),
		Vertex(glm::vec3(0, 1, 0), glm::vec2(0, 1)),
		Vertex(glm::vec3(1, 0, 0), glm::vec2(1, 0)) };

	unsigned int indices[] = { 0, 1, 2, 3 };
	unsigned int s = 4;
	unsigned int i = 4;

	Mesh mesh2(square, s, indices, i);
	Texture texture2("./res/textures/envision.jpg");

	texture2.Bind(1);
	mesh2.draw();

}
int main(int argc, char **argv)
{
  TCLAP::ValueArg<int> rotation1("","rotation1", "The rotation of mesh 1", false, 0, "int");
  TCLAP::ValueArg<int> rotation2("","rotation2", "The rotation of mesh 2", false, 0, "int");
  TCLAP::SwitchArg dual1("","dual1", "The rotation of mesh 1", false);
  TCLAP::SwitchArg dual2("","dual2", "The rotation of mesh 2", false);

  TCLAP::UnlabeledValueArg<std::string> solution1_filename("solution1", "File name of first solution", true, "", "string");
  TCLAP::UnlabeledValueArg<std::string> solution2_filename("solution2", "File name of first solution", true, "", "string");


  try
  {
    TCLAP::CmdLine cmd("Compare solutions", ' ', "1.0");

    cmd.add( rotation1 );
    cmd.add( rotation2 );
    cmd.add( dual1 );
    cmd.add( dual2 );
    cmd.add( solution1_filename );
    cmd.add( solution2_filename );

    cmd.parse( argc, argv );
  }
  catch (TCLAP::ArgException &e)  // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return false;
  }


  viennagrid_numeric rotation_angle1 = 2*M_PI / 5 * rotation1.getValue();
  viennagrid_numeric rotation_angle2 = 2*M_PI / 5 * rotation2.getValue();


  viennagrid_mesh cmesh1;
  viennagrid_quantity_field solution1;
  viennagrid_mesh_io reader1;

  viennagrid_mesh_io_create(&reader1);
  viennagrid_error err1 = viennagrid_mesh_io_read_pvd(reader1, solution1_filename.getValue().c_str());
  viennagrid_mesh_io_mesh_get(reader1, &cmesh1);
  viennagrid_mesh_io_quantity_field_get_by_index(reader1, 0, &solution1);


  viennagrid_mesh cmesh2;
  viennagrid_quantity_field solution2;
  viennagrid_mesh_io reader2;

  viennagrid_mesh_io_create(&reader2);
  viennagrid_error err2 = viennagrid_mesh_io_read_pvd(reader2, solution2_filename.getValue().c_str());
  viennagrid_mesh_io_mesh_get(reader2, &cmesh2);
  viennagrid_mesh_io_quantity_field_get_by_index(reader2, 0, &solution2);

  viennagrid::mesh mesh1(cmesh1);
  viennagrid::mesh mesh2(cmesh2);


//   viennagrid_numeric matrix[4];

  Transformation transformation = Transformation::make_rotation_2(- (rotation_angle1-rotation_angle2));
//   Transformation rotation =

  if (dual1.getValue() != dual2.getValue())
  {
    viennagrid_numeric angle = rotation_angle2 - 2*2*M_PI/5;
    viennagrid_numeric back_angle = rotation_angle2 - 3*2*M_PI/5;

    Transformation de_mirror =
      composition(
        Transformation::make_rotation_2(2*M_PI/5),
         Transformation::make_reflection_x(2)
      );

//       composition(
//         Transformation::make_rotation_2(-back_angle),
//         composition(
//           Transformation::make_reflection_x(2),
//           Transformation::make_rotation_2(angle)
//         )
//       );

    transformation = composition(
      transformation,
      composition(
        Transformation::make_rotation_2(M_PI),
        Transformation::make_reflection_2(rotation_angle2 - M_PI/5)
      )
    );
  }

//
//   if (dual.isSet())
//   {
//
//   }
//   else
//   {
//     matrix[0] =   std::cos(rotation_angle);
//     matrix[1] = - std::sin(rotation_angle);
//     matrix[2] =   std::sin(rotation_angle);
//     matrix[3] =   std::cos(rotation_angle);
//   }


  viennagrid_mesh_affine_transform(mesh2.internal(), 2, &transformation.matrix.values[0], 0);

  viennagrid_mesh_io_write(reader1, "mesh1.vtu");
  viennagrid_mesh_io_write(reader2, "mesh2.vtu");


  int max_element_per_node = 10;
  int max_depth = 1000;

  NTreeNode * ntree1 = new NTreeNode(viennagrid::make_point(-1.1, -1.1),
                                     viennagrid::make_point( 1.1,  1.1));
  {
    ElementRangeType cells(mesh1, 2);
    for (ElementRangeIterator cit = cells.begin(); cit != cells.end(); ++cit)
      ntree1->add(*cit, max_element_per_node, max_depth);
  }

  NTreeNode * ntree2 = new NTreeNode(viennagrid::make_point(-1.1, -1.1),
                                     viennagrid::make_point( 1.1,  1.1));
  {
    ElementRangeType cells(mesh2, 2);
    for (ElementRangeIterator cit = cells.begin(); cit != cells.end(); ++cit)
      ntree2->add(*cit, max_element_per_node, max_depth);
  }


  std::cout << compare(mesh1, ntree1, viennagrid::quantity_field(solution1),
                       mesh2, ntree2, viennagrid::quantity_field(solution2), 1e-6, 1e-6) << std::endl;;

  viennagrid_mesh_io_release(reader1);
  viennagrid_mesh_io_release(reader2);

  return 0;
}
Esempio n. 13
0
Scene * D3D::BuildScene(IDirect3DDevice9 *d3dDevice)
 {
	 // Setup some materials - we'll use these for 
	 // making the same mesh appear in multiple
	 // colors

	 D3DMATERIAL9 colors[8];
	 D3DUtil_InitMaterial( colors[0], 1.0f, 1.0f, 1.0f, 1.0f );	// white
	 D3DUtil_InitMaterial( colors[1], 0.0f, 1.0f, 1.0f, 1.0f );	// cyan
	 D3DUtil_InitMaterial( colors[2], 1.0f, 0.0f, 0.0f, 1.0f );	// red
	 D3DUtil_InitMaterial( colors[3], 0.0f, 1.0f, 0.0f, 1.0f );	// green
	 D3DUtil_InitMaterial( colors[4], 0.0f, 0.0f, 1.0f, 1.0f );	// blue
	 D3DUtil_InitMaterial( colors[5], 0.4f, 0.4f, 0.4f, 0.4f );	// 40% grey
	 D3DUtil_InitMaterial( colors[6], 0.25f, 0.25f, 0.25f, 0.25f );	// 25% grey
	 D3DUtil_InitMaterial( colors[7], 0.65f, 0.65f, 0.65f, 0.65f );	// 65% grey

	 // The identity matrix is always useful
	 D3DXMATRIX ident;
	 D3DXMatrixIdentity(&ident);

	 // We'll use these rotations for some teapots and grid objects
	 D3DXMATRIX rotateX, rotateY, rotateZ;

	 // Create the root, and the camera.
	 // Remeber how to use smart pointers?? I hope so!

	 boost::shared_ptr<TransformNode> root(new TransformNode(&ident));

	 boost::shared_ptr<CameraNode> camera(new CameraNode(&ident));
	 root->m_children.push_back(camera);



	 // We'll put the camera in the scene at (20,20,20) looking back at the Origin

	 D3DXMATRIX rotOnly, result, inverse;
	 float cameraYaw = - (3.0f * D3DX_PI) / 4.0f;
	 float cameraPitch = D3DX_PI / 4.0f;
	 D3DXQUATERNION q;
	 D3DXQuaternionIdentity(&q);
	 D3DXQuaternionRotationYawPitchRoll(&q, cameraYaw, cameraPitch, 0.0);
	 D3DXMatrixRotationQuaternion(&rotOnly, &q);

	 D3DXMATRIX trans;
	 D3DXMatrixTranslation(&trans, 15.0f, 15.0f, 15.0f);

	 D3DXMatrixMultiply(&result, &rotOnly, &trans);

	 D3DXMatrixInverse(&inverse, NULL, &result);
	 camera->VSetTransform(&result, &inverse);

	 D3DXMatrixRotationZ(&rotateZ, D3DX_PI / 2.0f);
	 D3DXMatrixRotationX(&rotateX, -D3DX_PI / 2.0f);
	 D3DXVECTOR3 target(30, 2, 15);

	 //

	

	 ID3DXMesh *teapot;
	 if( SUCCEEDED( D3DXCreateTeapot( d3dDevice, &teapot, NULL ) ) )
	 {
		 // Teapot #1 - a white one at (x=6,y=2,z=4)
		 D3DXMatrixTranslation(&trans,6,2,4);

		 boost::shared_ptr<SceneNode> mesh1(new MeshNode(teapot, &trans, colors[2]));
		 root->m_children.push_back(mesh1);

		 // Teapot #2 - a cyan one at (x=3,y=2,z=1)
		 //   with a 
		 D3DXMatrixTranslation(&trans, 3,2,1);
		 D3DXMATRIX result;
		 D3DXMatrixMultiply(&result, &rotateZ, &trans);

		 boost::shared_ptr<SceneNode> mesh2(new MeshNode(teapot, &result, colors[1]));
		 root->m_children.push_back(mesh2);

		 // Teapot #3 - another white one at (x=30, y=2, z=15)
		 D3DXMATRIX rotateY90;
		 D3DXMatrixRotationY(&rotateY90, D3DX_PI / 2.0f);
		 D3DXMatrixTranslation(&trans, target.x, target.y, target.z);
		 D3DXMatrixMultiply(&result, &rotateY90, &trans);
		 boost::shared_ptr<SceneNode> mesh3(new MeshNode(teapot, &result, colors[0]));
		 root->m_children.push_back(mesh3);

		 // We can release the teapot now, mesh1 and mesh2 AddRef'd it.
		 SAFE_RELEASE(teapot);
	 }

	 ID3DXMesh *sphere;
	 if ( SUCCEEDED( 
		 D3DXCreateSphere( 
		 d3dDevice, .25, 16, 16, &sphere, NULL) ) )
	 {
		 // We're going to create a spiral of spheres...
		 // starting at (x=3, y=0, z=3), and spiraling
		 // upward about a local Y axis.

		 D3DXMatrixTranslation(&trans, 3,0,3);

		 boost::shared_ptr<SceneNode> sphere1(new MeshNode(sphere, &trans, colors[4]) );
		 root->m_children.push_back(sphere1);

		 // Here's the local rotation and translation.
		 // We'll rotate about Y, and then translate
		 // up (along Y) and forward (along Z).
		 D3DXMatrixRotationY(&rotateY, D3DX_PI / 8.0f);
		 D3DXMATRIX trans2;
		 D3DXMatrixTranslation(&trans2, 0, 0.5, 0.5);
		 D3DXMatrixMultiply(&result, &trans2, &rotateY);

		 for (int i=0; i<25; i++)
		 {
			 // If you didn't think smart pointers were cool - 
			 // watch this! No leaked memory....

			 // Notice this is a heirarchy....
			 boost::shared_ptr<SceneNode> sphere2(new MeshNode(sphere, &result, colors[i%5]) );
			 sphere1->m_children.push_back(sphere2);
			 sphere1 = sphere2;
		 }

		 // We can release the sphere now, all the cylinders AddRef'd it.
		 SAFE_RELEASE(sphere);
	 }
	 

	 //
	 D3DXMatrixTranslation(&trans,-25,20,20);
	 //D3DXMatrixScaling(&trans, -10, -10, -10);
	 ScaleMtrl scale;
	 scale.x = -50.0f;
	 scale.y = -50.0f;
	 scale.z = -50.0f;
	 boost::shared_ptr<SceneNode> xmesh1(new XMeshNode(L"gf3.x", d3dDevice, &trans, &scale));
	 root->m_children.push_back(xmesh1);

	 
	  root->m_children.push_back(xmesh1);

	 /*D3DXMatrixTranslation(&trans,-45,20,20);
	 boost::shared_ptr<SceneNode> xmesh11(new XMeshNode(L"gf3.x", d3dDevice, &trans, &scale));
	 root->m_children.push_back(xmesh11);*/


	  XMeshNode *mm = new XMeshNode(L"gow_m1.x", d3dDevice, &trans, &scale);

	 D3DXMatrixTranslation(&trans,10,10,10);
	 //D3DXMatrixScaling(&trans, -10, -10, -10);
	 //ScaleMtrl scale;
	 scale.x = 100.0f;
	 scale.y = 100.0f;
	 scale.z = 100.0f;
	 boost::shared_ptr<SceneNode> xmesh2( new XMeshNode(L"gow_m1.x", d3dDevice, &trans, &scale));
	 root->m_children.push_back(xmesh2);

	 
	 
	 /*D3DXMatrixTranslation(&trans,20,20,20);
	 boost::shared_ptr<SceneNode> xmesh3(new XMeshNode(mm->m_mesh, mm->Mtrls, mm->Textures, &trans, 0));
	 root->m_children.push_back(xmesh3);*/

	 int col = 10;
	 int row= 10;
	 int zoom = 10;
	 const int COUNT = 13;
	 for(int i = 0; i < COUNT; i++)
	 {
		 for (int j = 0; j< COUNT; j++)
		 {
			 for(int z = 0; z< COUNT; z++)
			 {
				 D3DXMatrixTranslation(&trans, col + i, row + j , zoom + z);
				 boost::shared_ptr<SceneNode> xmeshNew(new XMeshNode(mm->m_mesh, mm->Mtrls, mm->Textures, &trans, 0));
				 root->m_children.push_back(xmeshNew);
			 }
		 }
	 }


	 //D3DXMatrixScaling(&trans, 10, 10, 10);

	 // Here are the grids...they make it easy for us to 
	 // see where the coordinates are in 3D space.
	 boost::shared_ptr<SceneNode> grid1(new Grid(40, 0x00404040, L"Textures\\grid.dds", &ident));
	 root->m_children.push_back(grid1);
	 boost::shared_ptr<SceneNode> grid2(new Grid(40, 0x00004000, L"Textures\\grid.dds", &rotateX));
	 root->m_children.push_back(grid2);
	 boost::shared_ptr<SceneNode> grid3(new Grid(40, 0x00000040, L"Textures\\grid.dds", &rotateZ));
	 root->m_children.push_back(grid3);

	 //  Here's the sky node that never worked!!!!
	 boost::shared_ptr<SkyNode> sky(new SkyNode(_T("Sky2"), camera));
	 root->m_children.push_back(sky);

	 D3DXMatrixTranslation(&trans,15,2,15);
	 D3DXMatrixRotationY(&rotateY, D3DX_PI / 4.0f);
	 D3DXMatrixMultiply(&result, &rotateY, &trans);

	 boost::shared_ptr<SceneNode> arrow1(new ArrowNode(2, &result, colors[0], d3dDevice));
	 root->m_children.push_back(arrow1);

	 D3DXMatrixRotationY(&rotateY, D3DX_PI / 2.0f);
	 D3DXMatrixMultiply(&result, &rotateY, &trans);
	 boost::shared_ptr<SceneNode> arrow2(new ArrowNode(2, &result, colors[5], d3dDevice));
	 root->m_children.push_back(arrow2);

	 D3DXMatrixMultiply(&result, &rotateX, &trans);
	 boost::shared_ptr<SceneNode> arrow3(new ArrowNode(2, &result, colors[0], d3dDevice));
	 root->m_children.push_back(arrow3);


	 // Everything has been attached to the root. Now
	 // we attach the root to the scene.

	 Scene *scene = new Scene(d3dDevice, root);
	 scene->Restore();

	 // A movement controller is going to control the camera, 
	 // but it could be constructed with any of the objects you see in this
	 // function. You can have your very own remote controlled sphere. What fun...
	 boost::shared_ptr<MovementController> m_pMovementController(new MovementController(camera, cameraYaw, cameraPitch));

	 scene->m_pMovementController = m_pMovementController;
	 return scene;
 }
Esempio n. 14
0
int main(int argc, char** argv){

	//initialize libMesh
	LibMeshInit init(argc, argv);
	
	//parameters
	GetPot infile("fem_system_params.in");
  const Real global_tolerance          = infile("global_tolerance", 0.);
  const unsigned int nelem_target      = infile("n_elements", 400);
  const bool transient                 = infile("transient", true);
  const Real deltat                    = infile("deltat", 0.005);
  unsigned int n_timesteps             = infile("n_timesteps", 1);
  //const unsigned int coarsegridsize    = infile("coarsegridsize", 1);
  const unsigned int coarserefinements = infile("coarserefinements", 0);
  const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10);
  //const unsigned int dim               = 2;
  
#ifdef LIBMESH_HAVE_EXODUS_API
  const unsigned int write_interval    = infile("write_interval", 5);
#endif

  // Create a mesh, with dimension to be overridden later, distributed
  // across the default MPI communicator.
  Mesh mesh(init.comm());
  Mesh mesh2(init.comm());
  GetPot infileForMesh("convdiff_mprime.in");
  std::string find_mesh_here = infileForMesh("divided_mesh","meep.exo");
	mesh.read(find_mesh_here);
	mesh2.read(find_mesh_here);
	//mesh.read("psiHF_mesh_1Dfused.xda");

  // And an object to refine it
  /*MeshRefinement mesh_refinement(mesh);
  mesh_refinement.coarsen_by_parents() = true;
  mesh_refinement.absolute_global_tolerance() = global_tolerance;
  mesh_refinement.nelem_target() = nelem_target;
  mesh_refinement.refine_fraction() = 0.3;
  mesh_refinement.coarsen_fraction() = 0.3;
  mesh_refinement.coarsen_threshold() = 0.1;

  mesh_refinement.uniformly_refine(coarserefinements);*/
  
  // Print information about the mesh to the screen.
  mesh.print_info();

  // Create an equation systems object.
  EquationSystems equation_systems (mesh);
  EquationSystems equation_systems_mix(mesh2);
  
  //name system
  ConvDiff_PrimarySys & system_primary = 
  	equation_systems.add_system<ConvDiff_PrimarySys>("ConvDiff_PrimarySys");
	ConvDiff_AuxSys & system_aux = 
  	equation_systems.add_system<ConvDiff_AuxSys>("ConvDiff_AuxSys");
  ConvDiff_MprimeSys & system_mix = 
		equation_systems_mix.add_system<ConvDiff_MprimeSys>("ConvDiff_MprimeSys");

  //steady-state problem	
 	system_primary.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_primary));
  system_aux.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_aux));
  system_mix.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_mix));
  libmesh_assert_equal_to (n_timesteps, 1);

  /*equation_systems.read("psiLF.xda", READ,
			EquationSystems::READ_HEADER |
			EquationSystems::READ_DATA |
			EquationSystems::READ_ADDITIONAL_DATA);
  equation_systems.print_info();*/
  
  // Initialize the system
  equation_systems.init ();

  // Set the time stepping options
  system_primary.deltat = deltat; system_aux.deltat = deltat;//this is ignored for SteadySolver...right?

  // And the nonlinear solver options
  NewtonSolver *solver_primary = new NewtonSolver(system_primary); 
  system_primary.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver_primary); 
  solver_primary->quiet = infile("solver_quiet", true);
  solver_primary->verbose = !solver_primary->quiet;
  solver_primary->max_nonlinear_iterations =
    infile("max_nonlinear_iterations", 15);
  solver_primary->relative_step_tolerance =
    infile("relative_step_tolerance", 1.e-3);
  solver_primary->relative_residual_tolerance =
    infile("relative_residual_tolerance", 0.0);
  solver_primary->absolute_residual_tolerance =
    infile("absolute_residual_tolerance", 0.0);
  NewtonSolver *solver_aux = new NewtonSolver(system_aux); 
  system_aux.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver_aux); 
  solver_aux->quiet = infile("solver_quiet", true);
  solver_aux->verbose = !solver_aux->quiet;
  solver_aux->max_nonlinear_iterations =
    infile("max_nonlinear_iterations", 15);
  solver_aux->relative_step_tolerance =
    infile("relative_step_tolerance", 1.e-3);
  solver_aux->relative_residual_tolerance =
    infile("relative_residual_tolerance", 0.0);
  solver_aux->absolute_residual_tolerance =
    infile("absolute_residual_tolerance", 0.0);

  // And the linear solver options
  solver_primary->max_linear_iterations =
    infile("max_linear_iterations", 50000);
  solver_primary->initial_linear_tolerance =
    infile("initial_linear_tolerance", 1.e-3);
 	solver_aux->max_linear_iterations =
    infile("max_linear_iterations", 50000);
  solver_aux->initial_linear_tolerance =
    infile("initial_linear_tolerance", 1.e-3);

  // Print information about the system to the screen.
  equation_systems.print_info();


  // Now we begin the timestep loop to compute the time-accurate
  // solution of the equations...not that this is transient, but eh, why not...
	for (unsigned int t_step=0; t_step != n_timesteps; ++t_step){
    // A pretty update message
    std::cout << "\n\nSolving time step " << t_step << ", time = "
              << system_primary.time << std::endl;

    // Adaptively solve the timestep
    unsigned int a_step = 0;
    /*for (; a_step != max_adaptivesteps; ++a_step)
      {
        system.solve();
        system.postprocess();
        ErrorVector error;
        AutoPtr<ErrorEstimator> error_estimator;

        // To solve to a tolerance in this problem we
        // need a better estimator than Kelly
        if (global_tolerance != 0.)
          {
            // We can't adapt to both a tolerance and a mesh
            // size at once
            libmesh_assert_equal_to (nelem_target, 0);

            UniformRefinementEstimator *u =
              new UniformRefinementEstimator;

            // The lid-driven cavity problem isn't in H1, so
            // lets estimate L2 error
            u->error_norm = L2;

            error_estimator.reset(u);
          }
        else
          {
            // If we aren't adapting to a tolerance we need a
            // target mesh size
            libmesh_assert_greater (nelem_target, 0);

            // Kelly is a lousy estimator to use for a problem
            // not in H1 - if we were doing more than a few
            // timesteps we'd need to turn off or limit the
            // maximum level of our adaptivity eventually
            error_estimator.reset(new KellyErrorEstimator);
          }

        // Calculate error
        std::vector<Real> weights(9,1.0);  // based on u, v, p, c, their adjoints, and source parameter

        // Keep the same default norm type.
        std::vector<FEMNormType>
          norms(1, error_estimator->error_norm.type(0));
        error_estimator->error_norm = SystemNorm(norms, weights);

        error_estimator->estimate_error(system, error);

        // Print out status at each adaptive step.
        Real global_error = error.l2_norm();
        std::cout << "Adaptive step " << a_step << ": " << std::endl;
        if (global_tolerance != 0.)
          std::cout << "Global_error = " << global_error
                    << std::endl;
        if (global_tolerance != 0.)
          std::cout << "Worst element error = " << error.maximum()
                    << ", mean = " << error.mean() << std::endl;

        if (global_tolerance != 0.)
          {
            // If we've reached our desired tolerance, we
            // don't need any more adaptive steps
            if (global_error < global_tolerance)
              break;
            mesh_refinement.flag_elements_by_error_tolerance(error);
          }
        else
          {
            // If flag_elements_by_nelem_target returns true, this
            // should be our last adaptive step.
            if (mesh_refinement.flag_elements_by_nelem_target(error))
              {
                mesh_refinement.refine_and_coarsen_elements();
                equation_systems.reinit();
                a_step = max_adaptivesteps;
                break;
              }
          }

        // Carry out the adaptive mesh refinement/coarsening
        mesh_refinement.refine_and_coarsen_elements();
        equation_systems.reinit();

        std::cout << "Refined mesh to "
                  << mesh.n_active_elem()
                  << " active elements and "
                  << equation_systems.n_active_dofs()
                  << " active dofs." << std::endl;
      }*/
    // Do one last solve if necessary
    if (a_step == max_adaptivesteps)
      {
        system_primary.solve();
				std::cout << "\n\n Residual L2 norm (primary): " << system_primary.calculate_norm(*system_primary.rhs, L2) << "\n";
				system_aux.solve();
				std::cout << "\n\n Residual L2 norm (auxiliary): " << system_aux.calculate_norm(*system_aux.rhs, L2) << "\n";
				
				equation_systems_mix.init();
  			DirectSolutionTransfer sol_transfer(init.comm()); 
  			sol_transfer.transfer(system_primary.variable(system_primary.variable_number("c")),
  				system_mix.variable(system_mix.variable_number("c")));
				sol_transfer.transfer(system_primary.variable(system_primary.variable_number("zc")),
  				system_mix.variable(system_mix.variable_number("zc")));
				sol_transfer.transfer(system_primary.variable(system_primary.variable_number("fc")),
  				system_mix.variable(system_mix.variable_number("fc")));
				sol_transfer.transfer(system_aux.variable(system_aux.variable_number("aux_c")),
  				system_mix.variable(system_mix.variable_number("aux_c")));
				sol_transfer.transfer(system_aux.variable(system_aux.variable_number("aux_zc")),
  				system_mix.variable(system_mix.variable_number("aux_zc")));
				sol_transfer.transfer(system_aux.variable(system_aux.variable_number("aux_fc")),
  				system_mix.variable(system_mix.variable_number("aux_fc")));
  			std::cout << "c: " << system_mix.calculate_norm(*system_mix.solution, 0, L2) << " " 
  												<< system_primary.calculate_norm(*system_primary.solution, 0, L2) << std::endl;
				std::cout << "zc: " << system_mix.calculate_norm(*system_mix.solution, 1, L2) << " " 
  												<< system_primary.calculate_norm(*system_primary.solution, 1, L2) << std::endl;
				std::cout << "fc: " << system_mix.calculate_norm(*system_mix.solution, 2, L2) << " " 
  												<< system_primary.calculate_norm(*system_primary.solution, 2, L2) << std::endl;
				std::cout << "aux_c: " << system_mix.calculate_norm(*system_mix.solution, 3, L2) << " " 
  												<< system_aux.calculate_norm(*system_aux.solution, 0, L2) << std::endl;
				std::cout << "aux_zc: " << system_mix.calculate_norm(*system_mix.solution, 4, L2) << " " 
  												<< system_aux.calculate_norm(*system_aux.solution, 1, L2) << std::endl;
				std::cout << "aux_fc: " << system_mix.calculate_norm(*system_mix.solution, 5, L2) << " " 
  												<< system_aux.calculate_norm(*system_aux.solution, 2, L2) << std::endl;
  			std::cout << "Overall: " << system_mix.calculate_norm(*system_mix.solution, L2) << std::endl;  
        system_mix.postprocess();
        
        //DEBUG
        std::cout << " M_HF(psiLF): " << std::setprecision(17) << system_mix.get_MHF_psiLF() << "\n";
  			std::cout << " I(psiLF): " << std::setprecision(17) << system_mix.get_MLF_psiLF() << "\n";
      }

    // Advance to the next timestep in a transient problem
    system_primary.time_solver->advance_timestep();

#ifdef LIBMESH_HAVE_EXODUS_API
    // Write out this timestep if we're requested to
    if ((t_step+1)%write_interval == 0)
      {
        //std::ostringstream file_name;

        // We write the file in the ExodusII format.
        //file_name << "out_"
        //          << std::setw(3)
        //          << std::setfill('0')
        //          << std::right
        //          << t_step+1
        //          << ".e";

        //ExodusII_IO(mesh).write_timestep(file_name.str(),
        ExodusII_IO(mesh).write_timestep("psiLF.exo",
                                         equation_systems_mix,
                                         1, /* This number indicates how many time steps
                                               are being written to the file */
                                         system_primary.time);
     		mesh.write("psiLF_mesh.xda");
     		equation_systems_mix.write("psiLF.xda", WRITE, EquationSystems::WRITE_DATA | 
               EquationSystems::WRITE_ADDITIONAL_DATA);
      }
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
  }
  
  // All done.
  return 0;
  
} //end main
Esempio n. 15
0
void NGLScene::initializeGL()
{
  // we must call this first before any other GL commands to load and link the
  // gl commands from the lib, if this is not done program will crash
  ngl::NGLInit::instance();

  glClearColor(0.4f, 0.4f, 0.4f, 1.0f);			   // Grey Background
  // enable depth testing for drawing
  glEnable(GL_DEPTH_TEST);
  // enable multisampling for smoother drawing
  glEnable(GL_MULTISAMPLE);
  // Now we will create a basic Camera from the graphics library
  // This is a static camera so it only needs to be set once
  // First create Values for the camera position
  ngl::Vec3 from(0,10,40);
  ngl::Vec3 to(0,10,0);
  ngl::Vec3 up(0,1,0);


  // first we create a mesh from an obj passing in the obj file and texture
  std::unique_ptr<ngl::Obj>mesh1( new ngl::Obj("models/BrucePose1.obj"));
  m_meshes.push_back(std::move(mesh1));

  std::unique_ptr<ngl::Obj> mesh2( new ngl::Obj("models/BrucePose2.obj"));
  m_meshes.push_back(std::move(mesh2));

  std::unique_ptr<ngl::Obj>mesh3( new ngl::Obj("models/BrucePose3.obj"));
  m_meshes.push_back(std::move(mesh3));
  createMorphMesh();

  m_view=ngl::lookAt(from,to,up);
  // set the shape using FOV 45 Aspect Ratio based on Width and Height
  // The final two are near and far clipping planes of 0.5 and 10
  m_project=ngl::perspective(45,(float)720.0/576.0,0.05,350);
  // now to load the shader and set the values
  // grab an instance of shader manager
  ngl::ShaderLib *shader=ngl::ShaderLib::instance();
  // we are creating a shader called PerFragADS
  shader->createShaderProgram("PerFragADS");
  // now we are going to create empty shaders for Frag and Vert
  shader->attachShader("PerFragADSVertex",ngl::ShaderType::VERTEX);
  shader->attachShader("PerFragADSFragment",ngl::ShaderType::FRAGMENT);
  // attach the source
  shader->loadShaderSource("PerFragADSVertex","shaders/PerFragASDVert.glsl");
  shader->loadShaderSource("PerFragADSFragment","shaders/PerFragASDFrag.glsl");
  // compile the shaders
  shader->compileShader("PerFragADSVertex");
  shader->compileShader("PerFragADSFragment");
  // add them to the program
  shader->attachShaderToProgram("PerFragADS","PerFragADSVertex");
  shader->attachShaderToProgram("PerFragADS","PerFragADSFragment");

  // now we have associated this data we can link the shader
  shader->linkProgramObject("PerFragADS");
  // and make it active ready to load values
  (*shader)["PerFragADS"]->use();
  // now we need to set the material and light values
  /*
   *struct MaterialInfo
   {
        // Ambient reflectivity
        vec3 Ka;
        // Diffuse reflectivity
        vec3 Kd;
        // Specular reflectivity
        vec3 Ks;
        // Specular shininess factor
        float shininess;
  };*/
  shader->setUniform("material.Ka",0.1f,0.1f,0.1f);
  // red diffuse
  shader->setUniform("material.Kd",0.8f,0.8f,0.8f);
  // white spec
  shader->setUniform("material.Ks",1.0f,1.0f,1.0f);
  shader->setUniform("material.shininess",1000.0f);
  // now for  the lights values (all set to white)
  /*struct LightInfo
  {
  // Light position in eye coords.
  vec4 position;
  // Ambient light intensity
  vec3 La;
  // Diffuse light intensity
  vec3 Ld;
  // Specular light intensity
  vec3 Ls;
  };*/
  shader->setUniform("light.position",ngl::Vec3(2,20,2));
  shader->setUniform("light.La",0.1f,0.1f,0.1f);
  shader->setUniform("light.Ld",1.0f,1.0f,1.0f);
  shader->setUniform("light.Ls",0.9f,0.9f,0.9f);

  glEnable(GL_DEPTH_TEST); // for removal of hidden surfaces

  // as re-size is not explicitly called we need to do this.
  glViewport(0,0,width(),height());
  m_text.reset( new ngl::Text(QFont("Arial",16)));
  m_text->setScreenSize(width(),height());
}
Esempio n. 16
0
// The main program
int main(int argc, char** argv)
{
  //for record-keeping
  std::cout << "Running: " << argv[0];
  for (int i=1; i<argc; i++)
    std::cout << " " << argv[i];
  std::cout << std::endl << std::endl;

  clock_t begin = std::clock();
  
  // Initialize libMesh
  LibMeshInit init(argc, argv);
  
  // Parameters
  GetPot solverInfile("fem_system_params.in");
  const bool transient                  = solverInfile("transient", false);
  unsigned int n_timesteps              = solverInfile("n_timesteps", 1);
  const int nx                          = solverInfile("nx",100);
  const int ny                          = solverInfile("ny",100);
  const int nz                          = solverInfile("nz",100);
  GetPot infile("contamTrans.in");
  //std::string find_mesh_here            = infile("initial_mesh","mesh.exo");
  bool doContinuation                   = infile("do_continuation",false);
  bool splitSuperAdj                    = infile("split_super_adjoint",true); //solve as single adjoint or two forwards
  int maxIter                           = infile("max_model_refinements",0);  //maximum number of model refinements
  double refStep                        = infile("refinement_step",0.1); //additional proportion of domain refined per step
    //this refers to additional basis functions...number of elements will be more...
  double qoiErrorTol                    = infile("relative_error_tolerance",0.01); //stopping criterion
  //bool doDivvyMatlab                    = infile("do_divvy_in_Matlab",false); //output files to determine next refinement in Matlab
  bool avoid_sides                      = infile("avoid_sides",false); //DEBUG, whether to avoid sides while refining

  if(refStep*maxIter > 1)
    maxIter = round(ceil(1./refStep));

  Mesh mesh(init.comm());
  Mesh mesh2(init.comm()); 
  
  //create mesh
  unsigned int dim;
  if(nz == 0){ //to check if oscillations happen in 2D as well...
    dim = 2;
    MeshTools::Generation::build_square(mesh, nx, ny, 0., 2300., 0., 1650., QUAD9);
    MeshTools::Generation::build_square(mesh2, nx, ny, 0., 2300., 0., 1650., QUAD9);
  }else{
    dim = 3;
    MeshTools::Generation::build_cube(mesh, nx, ny, nz, 0., 2300., 0., 1650., 0., 100., HEX27);
    MeshTools::Generation::build_cube(mesh2, nx, ny, nz, 0., 2300., 0., 1650., 0., 100., HEX27);
  }
  
  mesh.print_info(); //DEBUG
  
  // Create an equation systems object.
  EquationSystems equation_systems (mesh);
  EquationSystems equation_systems_mix(mesh2);
  
  //name system
  ConvDiff_PrimarySys & system_primary = 
    equation_systems.add_system<ConvDiff_PrimarySys>("ConvDiff_PrimarySys"); //for primary variables
  ConvDiff_AuxSys & system_aux = 
    equation_systems.add_system<ConvDiff_AuxSys>("ConvDiff_AuxSys"); //for auxiliary variables
  ConvDiff_MprimeSys & system_mix = 
    equation_systems_mix.add_system<ConvDiff_MprimeSys>("Diff_ConvDiff_MprimeSys"); //for superadj
  ConvDiff_PrimarySadjSys & system_sadj_primary = 
    equation_systems.add_system<ConvDiff_PrimarySadjSys>("ConvDiff_PrimarySadjSys"); //for split superadj
  ConvDiff_AuxSadjSys & system_sadj_aux = 
    equation_systems.add_system<ConvDiff_AuxSadjSys>("ConvDiff_AuxSadjSys"); //for split superadj
    
  //steady-state problem  
  system_primary.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_primary));
  system_aux.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_aux));
  system_mix.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_mix));
  system_sadj_primary.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_sadj_primary));
  system_sadj_aux.time_solver =
    AutoPtr<TimeSolver>(new SteadySolver(system_sadj_aux));
  libmesh_assert_equal_to (n_timesteps, 1);
  
  // Initialize the system
  equation_systems.init ();
  equation_systems_mix.init();
  
  //initial guess for primary state
  read_initial_parameters();
  system_primary.project_solution(initial_value, initial_grad,
                          equation_systems.parameters);
  finish_initialization();

  //nonlinear solver options
  NewtonSolver *solver_sadj_primary = new NewtonSolver(system_sadj_primary); 
  system_sadj_primary.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver_sadj_primary); 
  solver_sadj_primary->quiet = solverInfile("solver_quiet", true);
  solver_sadj_primary->verbose = !solver_sadj_primary->quiet;
  solver_sadj_primary->max_nonlinear_iterations =
    solverInfile("max_nonlinear_iterations", 15);
  solver_sadj_primary->relative_step_tolerance =
    solverInfile("relative_step_tolerance", 1.e-3);
  solver_sadj_primary->relative_residual_tolerance =
    solverInfile("relative_residual_tolerance", 0.0);
  solver_sadj_primary->absolute_residual_tolerance =
    solverInfile("absolute_residual_tolerance", 0.0);
  NewtonSolver *solver_sadj_aux = new NewtonSolver(system_sadj_aux); 
  system_sadj_aux.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver_sadj_aux); 
  solver_sadj_aux->quiet = solverInfile("solver_quiet", true);
  solver_sadj_aux->verbose = !solver_sadj_aux->quiet;
  solver_sadj_aux->max_nonlinear_iterations =
    solverInfile("max_nonlinear_iterations", 15);
  solver_sadj_aux->relative_step_tolerance =
    solverInfile("relative_step_tolerance", 1.e-3);
  solver_sadj_aux->relative_residual_tolerance =
    solverInfile("relative_residual_tolerance", 0.0);
  solver_sadj_aux->absolute_residual_tolerance =
    solverInfile("absolute_residual_tolerance", 0.0);
  NewtonSolver *solver_primary = new NewtonSolver(system_primary); 
  system_primary.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver_primary); 
  solver_primary->quiet = solverInfile("solver_quiet", true);
  solver_primary->verbose = !solver_primary->quiet;
  solver_primary->max_nonlinear_iterations =
    solverInfile("max_nonlinear_iterations", 15);
  solver_primary->relative_step_tolerance =
    solverInfile("relative_step_tolerance", 1.e-3);
  solver_primary->relative_residual_tolerance =
    solverInfile("relative_residual_tolerance", 0.0);
  solver_primary->absolute_residual_tolerance =
    solverInfile("absolute_residual_tolerance", 0.0);
  NewtonSolver *solver_aux = new NewtonSolver(system_aux); 
  system_aux.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver_aux); 
  solver_aux->quiet = solverInfile("solver_quiet", true);
  solver_aux->verbose = !solver_aux->quiet;
  solver_aux->max_nonlinear_iterations =
    solverInfile("max_nonlinear_iterations", 15);
  solver_aux->relative_step_tolerance =
    solverInfile("relative_step_tolerance", 1.e-3);
  solver_aux->relative_residual_tolerance =
    solverInfile("relative_residual_tolerance", 0.0);
  solver_aux->absolute_residual_tolerance =
    solverInfile("absolute_residual_tolerance", 0.0);
  solver_primary->require_residual_reduction = solverInfile("require_residual_reduction",true);
  solver_sadj_primary->require_residual_reduction = solverInfile("require_residual_reduction",true);
  solver_aux->require_residual_reduction = solverInfile("require_residual_reduction",true);
  solver_sadj_aux->require_residual_reduction = solverInfile("require_residual_reduction",true);  
  
  //linear solver options
  solver_primary->max_linear_iterations       = solverInfile("max_linear_iterations",10000);
  solver_primary->initial_linear_tolerance    = solverInfile("initial_linear_tolerance",1.e-13);
  solver_primary->minimum_linear_tolerance    = solverInfile("minimum_linear_tolerance",1.e-13);
  solver_primary->linear_tolerance_multiplier = solverInfile("linear_tolerance_multiplier",1.e-3);
  solver_aux->max_linear_iterations           = solverInfile("max_linear_iterations",10000);
  solver_aux->initial_linear_tolerance        = solverInfile("initial_linear_tolerance",1.e-13);
  solver_aux->minimum_linear_tolerance        = solverInfile("minimum_linear_tolerance",1.e-13);
  solver_aux->linear_tolerance_multiplier     = solverInfile("linear_tolerance_multiplier",1.e-3);
  solver_sadj_primary->max_linear_iterations       = solverInfile("max_linear_iterations",10000);
  solver_sadj_primary->initial_linear_tolerance    = solverInfile("initial_linear_tolerance",1.e-13);
  solver_sadj_primary->minimum_linear_tolerance    = solverInfile("minimum_linear_tolerance",1.e-13);
  solver_sadj_primary->linear_tolerance_multiplier = solverInfile("linear_tolerance_multiplier",1.e-3);
  solver_sadj_aux->max_linear_iterations           = solverInfile("max_linear_iterations",10000);
  solver_sadj_aux->initial_linear_tolerance        = solverInfile("initial_linear_tolerance",1.e-13);
  solver_sadj_aux->minimum_linear_tolerance        = solverInfile("minimum_linear_tolerance",1.e-13);
  solver_sadj_aux->linear_tolerance_multiplier     = solverInfile("linear_tolerance_multiplier",1.e-3);
  
  /*if(doDivvyMatlab){
    //DOF maps and such to help visualize
    std::ofstream output_global_dof("global_dof_map.dat");
    for(unsigned int i = 0 ; i < system_mix.get_mesh().n_elem(); i++){
      std::vector< dof_id_type > di;
      system_mix.get_dof_map().dof_indices(system_mix.get_mesh().elem(i), di);
      if(output_global_dof.is_open()){
        output_global_dof << i << " ";
        for(unsigned int j = 0; j < di.size(); j++)
          output_global_dof << di[j] << " ";
        output_global_dof << "\n";
      }
    }
    output_global_dof.close();
    std::ofstream output_elem_cent("elem_centroids.dat");
    for(unsigned int i = 0 ; i < system_mix.get_mesh().n_elem(); i++){
      Point elem_cent = system_mix.get_mesh().elem(i)->centroid();
      if(output_elem_cent.is_open()){
        output_elem_cent << elem_cent(0) << " " << elem_cent(1) << "\n";
      }
    }
    output_elem_cent.close();
  }*/
  
  //inverse dof map (elements in support of each node, assuming every 6 dofs belong to same node)
  std::vector<std::set<dof_id_type> > node_to_elem; 
  node_to_elem.resize(round(system_mix.n_dofs()/6.));
  for(unsigned int i = 0 ; i < system_mix.get_mesh().n_elem(); i++){
    std::vector< dof_id_type > di;
    system_mix.get_dof_map().dof_indices(system_mix.get_mesh().elem(i), di);
    for(unsigned int j = 0; j < di.size(); j++)
      node_to_elem[round(floor(di[j]/6.))].insert(i);
  }

  int refIter = 0;
  double relError = 2.*qoiErrorTol;
  while(refIter <= maxIter && relError > qoiErrorTol){
    if(!doContinuation){ //clear out previous solutions
      system_primary.solution->zero();
      system_aux.solution->zero();
      system_sadj_primary.solution->zero();
      system_sadj_aux.solution->zero();
    }
    system_mix.solution->zero();
    
    clock_t begin_inv = std::clock();
    system_primary.solve();
    system_primary.clearQoI();
    clock_t end_inv = std::clock();
    clock_t begin_err_est = std::clock();
    std::cout << "\n End primary solve, begin auxiliary solve..." << std::endl;
    system_aux.solve();
    std::cout << "\n End auxiliary solve..." << std::endl;
    clock_t end_aux = std::clock();
    
    system_primary.postprocess();
    system_aux.postprocess();
    
    system_sadj_primary.set_c_vals(system_primary.get_c_vals());
    system_sadj_aux.set_auxc_vals(system_aux.get_auxc_vals());

    equation_systems_mix.reinit();
    //combine primary and auxiliary variables into psi
    DirectSolutionTransfer sol_transfer(init.comm()); 
    sol_transfer.transfer(system_aux.variable(system_aux.variable_number("aux_c")),
      system_mix.variable(system_mix.variable_number("aux_c")));
    sol_transfer.transfer(system_aux.variable(system_aux.variable_number("aux_zc")),
      system_mix.variable(system_mix.variable_number("aux_zc")));
    sol_transfer.transfer(system_aux.variable(system_aux.variable_number("aux_fc")),
      system_mix.variable(system_mix.variable_number("aux_fc")));
    AutoPtr<NumericVector<Number> > just_aux = system_mix.solution->clone();
    sol_transfer.transfer(system_primary.variable(system_primary.variable_number("c")),
      system_mix.variable(system_mix.variable_number("c")));
    sol_transfer.transfer(system_primary.variable(system_primary.variable_number("zc")),
      system_mix.variable(system_mix.variable_number("zc")));
    sol_transfer.transfer(system_primary.variable(system_primary.variable_number("fc")),
      system_mix.variable(system_mix.variable_number("fc")));

    if(!splitSuperAdj){ //solve super-adjoint as single adjoint
      system_mix.assemble_qoi_sides = true; //QoI doesn't involve sides
      
      std::cout << "\n~*~*~*~*~*~*~*~*~ adjoint solve start ~*~*~*~*~*~*~*~*~\n" << std::endl;
      std::pair<unsigned int, Real> adjsolve = system_mix.adjoint_solve();
      std::cout << "number of iterations to solve adjoint: " << adjsolve.first << std::endl;
      std::cout << "final residual of adjoint solve: " << adjsolve.second << std::endl;
      std::cout << "\n~*~*~*~*~*~*~*~*~ adjoint solve end ~*~*~*~*~*~*~*~*~" << std::endl;
  
      NumericVector<Number> &dual_sol = system_mix.get_adjoint_solution(0); //DEBUG
      
      system_mix.assemble(); //calculate residual to correspond to solution
      
      //std::cout << "\n sadj norm: " << system_mix.calculate_norm(dual_sol, L2) << std::endl; //DEBUG
      //std::cout << system_mix.calculate_norm(dual_sol, 0, L2) << std::endl; //DEBUG
      //std::cout << system_mix.calculate_norm(dual_sol, 1, L2) << std::endl; //DEBUG
      //std::cout << system_mix.calculate_norm(dual_sol, 2, L2) << std::endl; //DEBUG
      //std::cout << system_mix.calculate_norm(dual_sol, 3, L2) << std::endl; //DEBUG
      //std::cout << system_mix.calculate_norm(dual_sol, 4, L2) << std::endl; //DEBUG
      //std::cout << system_mix.calculate_norm(dual_sol, 5, L2) << std::endl; //DEBUG
    }else{ //solve super-adjoint as
      system_mix.assemble(); //calculate residual to correspond to solution
      std::cout << "\n Begin primary super-adjoint solve...\n" << std::endl;
      system_sadj_primary.solve();
      std::cout << "\n End primary super-adjoint solve, begin auxiliary super-adjoint solve...\n" << std::endl;
      system_sadj_aux.solve();
      std::cout << "\n End auxiliary super-adjoint solve...\n" << std::endl;
      const std::string & adjoint_solution0_name = "adjoint_solution0";
      system_mix.add_vector(adjoint_solution0_name, false, GHOSTED);
      system_mix.set_vector_as_adjoint(adjoint_solution0_name,0);
      NumericVector<Number> &eep = system_mix.add_adjoint_rhs(0);
      system_mix.set_adjoint_already_solved(true);
      NumericVector<Number> &dual_sol = system_mix.get_adjoint_solution(0);
      NumericVector<Number> &primal_sol = *system_mix.solution;
      dual_sol.swap(primal_sol);
      sol_transfer.transfer(system_sadj_aux.variable(system_sadj_aux.variable_number("sadj_aux_c")),
        system_mix.variable(system_mix.variable_number("aux_c")));
      sol_transfer.transfer(system_sadj_aux.variable(system_sadj_aux.variable_number("sadj_aux_zc")),
        system_mix.variable(system_mix.variable_number("aux_zc")));
      sol_transfer.transfer(system_sadj_aux.variable(system_sadj_aux.variable_number("sadj_aux_fc")),
        system_mix.variable(system_mix.variable_number("aux_fc")));
      sol_transfer.transfer(system_sadj_primary.variable(system_sadj_primary.variable_number("sadj_c")),
        system_mix.variable(system_mix.variable_number("c")));
      sol_transfer.transfer(system_sadj_primary.variable(system_sadj_primary.variable_number("sadj_zc")),
        system_mix.variable(system_mix.variable_number("zc")));
      sol_transfer.transfer(system_sadj_primary.variable(system_sadj_primary.variable_number("sadj_fc")),
        system_mix.variable(system_mix.variable_number("fc")));
      //std::cout << "\n sadj norm: " << system_mix.calculate_norm(primal_sol, L2) << std::endl; //DEBUG
      dual_sol.swap(primal_sol);
      //std::cout << "\n sadj norm: " << system_mix.calculate_norm(primal_sol, L2) << std::endl; //DEBUG
      //std::cout << system_sadj_primary.calculate_norm(*system_sadj_primary.solution, 0, L2) << std::endl; //DEBUG
      //std::cout << system_sadj_primary.calculate_norm(*system_sadj_primary.solution, 1, L2) << std::endl; //DEBUG
      //std::cout << system_sadj_primary.calculate_norm(*system_sadj_primary.solution, 2, L2) << std::endl; //DEBUG
      //std::cout << system_sadj_aux.calculate_norm(*system_sadj_aux.solution, 0, L2) << std::endl; //DEBUG
      //std::cout << system_sadj_aux.calculate_norm(*system_sadj_aux.solution, 1, L2) << std::endl; //DEBUG
      //std::cout << system_sadj_aux.calculate_norm(*system_sadj_aux.solution, 2, L2) << std::endl; //DEBUG
    }
    NumericVector<Number> &dual_solution = system_mix.get_adjoint_solution(0);
/*  
    NumericVector<Number> &primal_solution = *system_mix.solution; //DEBUG
    primal_solution.swap(dual_solution); //DEBUG
    ExodusII_IO(mesh).write_timestep("super_adjoint.exo",
                                   equation_systems,
                                   1, /  his number indicates how many time steps are being written to the file
                                   system_mix.time); //DEBUG
    primal_solution.swap(dual_solution); //DEBUG
*/
    //adjoint-weighted residual
    AutoPtr<NumericVector<Number> > adjresid = system_mix.solution->zero_clone();
    adjresid->pointwise_mult(*system_mix.rhs,dual_solution); 
    adjresid->scale(-0.5);
    std::cout << "\n -0.5*M'_HF(psiLF)(superadj): " << adjresid->sum() << std::endl; //DEBUG
    
    //LprimeHF(psiLF)
    AutoPtr<NumericVector<Number> > LprimeHF_psiLF = system_mix.solution->zero_clone();
    LprimeHF_psiLF->pointwise_mult(*system_mix.rhs,*just_aux);
    std::cout << " L'_HF(psiLF): " << LprimeHF_psiLF->sum() << std::endl; //DEBUG
    
    //QoI and error estimate
    std::cout << "QoI: " << std::setprecision(17) << system_primary.getQoI() << std::endl;
    std::cout << "QoI Error estimate: " << std::setprecision(17) 
        << adjresid->sum()+LprimeHF_psiLF->sum() << std::endl; 
        
    relError = fabs((adjresid->sum()+LprimeHF_psiLF->sum())/system_primary.getQoI());
    
    //print out information
    std::cout << "Estimated absolute relative qoi error: " << relError << std::endl << std::endl;
    std::cout << "Estimated HF QoI: " << std::setprecision(17) << system_primary.getQoI()+adjresid->sum()+LprimeHF_psiLF->sum() << std::endl;
    clock_t end = clock();
    std::cout << "Time so far: " << double(end-begin)/CLOCKS_PER_SEC << " seconds..." << std::endl;
    std::cout << "Time for inverse problem: " << double(end_inv-begin_inv)/CLOCKS_PER_SEC << " seconds..." << std::endl;
    std::cout << "Time for extra error estimate bits: " << double(end-begin_err_est)/CLOCKS_PER_SEC << " seconds..." << std::endl;
    std::cout << "    Time to get auxiliary problems: " << double(end_aux-begin_err_est)/CLOCKS_PER_SEC << " seconds..." << std::endl;
    std::cout << "    Time to get superadjoint: " << double(end-end_aux)/CLOCKS_PER_SEC << " seconds...\n" << std::endl;
    
    //proportion of domain refined at this iteration
    MeshBase::element_iterator       elem_it  = mesh.elements_begin();
    const MeshBase::element_iterator elem_end = mesh.elements_end();
    double numMarked = 0.;
    for (; elem_it != elem_end; ++elem_it){
      Elem* elem = *elem_it;
      numMarked += elem->subdomain_id();
    }
    std::cout << "Refinement fraction: " << numMarked/system_mix.get_mesh().n_elem() << std::endl << std::endl;

    
    //output at each iteration
    std::stringstream ss;
    ss << refIter;
    std::string str = ss.str();
    std::string write_error_basis_blame = 
      (infile("error_est_output_file_basis_blame", "error_est_breakdown_basis_blame")) + str + ".dat";
    std::ofstream output2(write_error_basis_blame);
    for(unsigned int i = 0 ; i < adjresid->size(); i++){
      if(output2.is_open())
        output2 << (*adjresid)(i) + (*LprimeHF_psiLF)(i) << "\n";
    }
    output2.close();
    
    if(refIter < maxIter && relError > qoiErrorTol){ //if further refinement needed
    
      //collapse error contributions into nodes
      std::vector<std::pair<Number,dof_id_type> > node_errs(round(system_mix.n_dofs()/6.));
      for(unsigned int node_num = 0; node_num < node_errs.size(); node_num++){
        node_errs[node_num] = std::pair<Number,dof_id_type>
                             (fabs((*adjresid)(6*node_num) + (*LprimeHF_psiLF)(6*node_num)
                            + (*adjresid)(6*node_num+1) + (*LprimeHF_psiLF)(6*node_num+1)
                            + (*adjresid)(6*node_num+2) + (*LprimeHF_psiLF)(6*node_num+2)
                            + (*adjresid)(6*node_num+3) + (*LprimeHF_psiLF)(6*node_num+3)
                            + (*adjresid)(6*node_num+4) + (*LprimeHF_psiLF)(6*node_num+4)
                            + (*adjresid)(6*node_num+5) + (*LprimeHF_psiLF)(6*node_num+5)), node_num);
      }
  
      //find nodes contributing the most
      //double refPcnt = std::min((refIter+1)*refStep,1.);
      double refPcnt = std::min(refStep,1.); //additional refinement (compared to previous iteration)
      int cutoffLoc = round(node_errs.size()*refPcnt);
      std::sort(node_errs.begin(), node_errs.end()); 
      std::reverse(node_errs.begin(), node_errs.end()); 
      
      //find elements in support of worst offenders
      std::vector<dof_id_type> markMe;
      markMe.reserve(cutoffLoc*8);
      for(int i = 0; i < cutoffLoc; i++){
        markMe.insert(markMe.end(), node_to_elem[node_errs[i].second].begin(), node_to_elem[node_errs[i].second].end());
      }
  
      //mark those elements for refinement.
      for(int i = 0; i < markMe.size(); i++){
        if(!avoid_sides || (avoid_sides && !mesh.elem(markMe[i])->on_boundary()))
          mesh.elem(markMe[i])->subdomain_id() = 1; //assuming HF regions marked with 1
      }
  
      //to test whether assignment matches matlab's
      /*std::string stash_assign = "divvy_c_poke.txt";
      std::ofstream output_dbg(stash_assign.c_str());
      MeshBase::element_iterator       elem_it  = mesh.elements_begin();
      const MeshBase::element_iterator elem_end = mesh.elements_end();
      for (; elem_it != elem_end; ++elem_it){
        Elem* elem = *elem_it;
            
        if(output_dbg.is_open()){
          output_dbg << elem->id() << " " << elem->subdomain_id() << "\n";
        }
      }
      output_dbg.close();*/
      
#ifdef LIBMESH_HAVE_EXODUS_API
    std::stringstream ss2;
    ss2 << refIter + 1;
    std::string str = ss2.str();
    std::string write_divvy = "divvy" + str + ".exo";
    ExodusII_IO (mesh).write_equation_systems(write_divvy,equation_systems); //DEBUG
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
    }
    refIter += 1;
  }
  
  std::string stash_assign = "divvy_final.txt";
  std::ofstream output_dbg(stash_assign.c_str());
  MeshBase::element_iterator       elem_it  = mesh.elements_begin();
  const MeshBase::element_iterator elem_end = mesh.elements_end();
  double numMarked = 0.;
  for (; elem_it != elem_end; ++elem_it){
    Elem* elem = *elem_it;
    numMarked += elem->subdomain_id();
    if(output_dbg.is_open()){
      output_dbg << elem->id() << " " << elem->subdomain_id() << "\n";
    }
  }
  output_dbg.close();
  
  std::cout << "\nRefinement concluded..." << std::endl;
  std::cout << "Final refinement fraction: " << numMarked/system_mix.get_mesh().n_elem() << std::endl;
  std::cout << "Final estimated relative error: " << relError << std::endl;
  
  return 0; //done

} //end main