Example #1
0
void VectorTest::test_calculate_mean_standard_deviation(void)
{
   message += "test_calculate_mean_standard_deviation\n";

   Vector<double> v;
   Vector<double> mean_standard_deviation;

   // Test

   v.set(2);
   v[0] = -1.0;
   v[1] =  1.0;

   mean_standard_deviation = v.calculate_mean_standard_deviation();

   assert_true(mean_standard_deviation[0] == 0.0, LOG);
   assert_true(fabs(mean_standard_deviation[1]-1.4142) < 1.0e-3, LOG);
}
/**
 * Get the value at a paricular point in time
 * @param time the time
 * @param point (output) the point
 * @param randomOrder Set this to true if this function will be called with 
 * values for "time" that are not in increasing order
 */
void WaveForm3D::getValue(float const time, Vector & point, bool randomOrder)
{
	VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(0.0f, time, 1.0f);

	if (m_isDirty || randomOrder)
	{
		m_xWaveIterator.reset(m_xWaveForm.getIteratorBegin());
		m_yWaveIterator.reset(m_yWaveForm.getIteratorBegin());
		m_zWaveIterator.reset(m_zWaveForm.getIteratorBegin());
		m_isDirty = false;
	}

	float const x = m_xWaveForm.getValue(m_xWaveIterator, time);
	float const y = m_yWaveForm.getValue(m_yWaveIterator, time);
	float const z = m_zWaveForm.getValue(m_zWaveIterator, time);

	point.set(x, y, z);
}
Example #3
0
void BaseView::update_solution()
{
  Vector* vec = new AVector(ndof);
  memset(vec->get_c_array(), 0, sizeof(scalar) * ndof);
  if (base_index >= 0)
  {
    if (base_index < ndof) vec->set(base_index, 1.0);
    sln->set_coeff_vector(space, pss, vec, 0.0);
  }
  else
  {
    sln->set_coeff_vector(space, pss, vec, 1.0);
  }

  ScalarView::show(sln, eps, item);
  update_title();
  delete vec;
}
Example #4
0
int main(){
  ifstream in("in.txt");
  int x,y;  in>>x>>y;
  Matrix ma;
  ma.set(x,y);
  for(int i=0; i<x; ++i)
  for(int j=0; j<y; ++j)
    in>>ma.elem(i,j);
  in>>x;
  Vector ve;
  ve.set(x);
  for(int i=0; i<x; ++i)
    in>>ve[i];
  Vector vx = multiply(ma,ve);
  vx.display();
  ma.remove();
  ve.remove();
  vx.remove();
}//====================================
void Matrix<elType>::rowSum(Vector<elType>& vecSum) const
{
	if(vecSum.getLength() != height)
		vecSum.create(height);
	vecSum.set(0);
	elType* pSum;
	elType* pMatrix = pData;

	for(int col=0; col < width; col++)
	{
		pSum = vecSum.pData;
		for(int row = 0; row < height;row++)
		{
			*pSum += *pMatrix;
			pSum++;
			pMatrix++;
		}
	}
}
Example #6
0
void VectorTest::test_calculate_maximal_indices(void) {
  message += "test_calculate_maximal_indices\n";

  Vector<double> v;
  Vector<unsigned> maximal_indices;

  // Test

  v.set(4);
  v[0] = -1.0;
  v[1] = 2.0;
  v[2] = -3.0;
  v[3] = 4.0;

  maximal_indices = v.calculate_maximal_indices(2);

  assert_true(maximal_indices[0] == 3, LOG);
  assert_true(maximal_indices[1] == 1, LOG);
}
Example #7
0
void VectorTest::test_calculate_histogram(void) {
  message += "test_calculate_histogram\n";

  Vector<double> v;

  Histogram<double> histogram;

  Vector<double> centers;
  Vector<unsigned> frequencies;

  // Test

  v.set(0.0, 1.0, 9.0);

  histogram = v.calculate_histogram(10);

  assert_true(histogram.get_bins_number() == 10, LOG);

  centers = histogram.centers;
  frequencies = histogram.frequencies;

  assert_true(fabs(centers[0] - 0.45) < 1.0e-12, LOG);
  assert_true(fabs(centers[1] - 1.35) < 1.0e-12, LOG);
  assert_true(fabs(centers[2] - 2.25) < 1.0e-12, LOG);
  assert_true(fabs(centers[3] - 3.15) < 1.0e-12, LOG);
  assert_true(fabs(centers[4] - 4.05) < 1.0e-12, LOG);
  assert_true(fabs(centers[5] - 4.95) < 1.0e-12, LOG);
  assert_true(fabs(centers[6] - 5.85) < 1.0e-12, LOG);
  assert_true(fabs(centers[7] - 6.75) < 1.0e-12, LOG);
  assert_true(fabs(centers[8] - 7.65) < 1.0e-12, LOG);
  assert_true(fabs(centers[9] - 8.55) < 1.0e-12, LOG);

  assert_true(frequencies[0] == 1, LOG);
  assert_true(frequencies[1] == 1, LOG);
  assert_true(frequencies[2] == 1, LOG);
  assert_true(frequencies[3] == 1, LOG);
  assert_true(frequencies[4] == 1, LOG);
  assert_true(frequencies[5] == 1, LOG);
  assert_true(frequencies[6] == 1, LOG);
  assert_true(frequencies[7] == 1, LOG);
  assert_true(frequencies[8] == 1, LOG);
  assert_true(frequencies[9] == 1, LOG);
}
void MatrixTest::test_multiplication_operator(void)
{
   message += "test_multiplication_operator\n";

   Matrix<int> a;
   Matrix<int> b;
   Matrix<int> c;
   
   Vector<int> v;

   // Scalar

   a.set(1, 1, 2);

   c = a*2;

   assert_true(c.get_rows_number() == 1, LOG);
   assert_true(c.get_columns_number() == 1, LOG);
   assert_true(c == 4, LOG);

   // Vector

   a.set(1, 1, 1);
   v.set(1, 1);
  
   b = a*v;

   assert_true(b.get_rows_number() == 1, LOG);
   assert_true(b.get_columns_number() == 1, LOG);
   assert_true(b == 1, LOG);  

   // Matrix

   a.set(1, 1, 2);
   b.set(1, 1, 2);

   c = a*b;

   assert_true(c.get_rows_number() == 1, LOG);
   assert_true(c.get_columns_number() == 1, LOG);
   assert_true(c == 4, LOG);

}
Example #9
0
void VectorTest::test_calculate_statistics(void) {
  message += "test_calculate_statistics\n";

  Vector<double> v;
  Statistics<double> statistics;

  // Test

  v.set(2);
  v[0] = -1.0;
  v[1] = 1.0;

  statistics = v.calculate_statistics();

  assert_true(statistics.minimum == -1.0, LOG);
  assert_true(statistics.maximum == 1.0, LOG);
  assert_true(statistics.mean == 0.0, LOG);
  assert_true(fabs(statistics.standard_deviation - 1.4142135624) < 1.0e-6, LOG);
}
Example #10
0
void
MatrixEigenSparse<T>::zeroRows( std::vector<int> const& rows,
                                Vector<value_type> const& vals,
                                Vector<value_type>& rhs,
                                Context const& on_context )
{
    LOG(INFO) << "zero out " << rows.size() << " rows except diagonal is row major: " << M_mat.IsRowMajor;
    Feel::detail::ignore_unused_variable_warning( rhs );
    Feel::detail::ignore_unused_variable_warning( vals );
    boost::unordered_map<int,std::set<int>> m;
    for (int k=0; k<rows.size(); ++k)
    {
        for (typename matrix_type::InnerIterator it(M_mat,rows[k]); it; ++it)
        {
            m[it.row()].insert(it.col());
            double value = 1.0;
            if ( on_context.test( OnContext::ELIMINATION_KEEP_DIAGONAL ) )
                value = it.value();
            rhs.add( it.row(), -it.value() * vals(rows[k]) );
            it.valueRef() = 0;

            if ( it.row() == it.col() )
            {
                it.valueRef() = value;
                rhs.set( it.row(), value * vals(rows[k]) );
            }
        }
    }
    for(auto rit = m.begin();rit != m.end();++rit )
    {
        for (typename matrix_type::InnerIterator it(M_mat,rit->first); it; ++it)
        {
            double value = 1.0;
            if( rit->second.find( it.row() ) != rit->second.end() )
            {
                // don't change diagonal, it was done in the first pass
                if ( it.row() != it.col() )
                    it.valueRef() = 0;
            }
        }
    }
}
Example #11
0
TEST( MatrixUtils, generateLookAtLH )
{
   Matrix tamyLookAtMtx;

   Vector cameraOriginPos( 10, 20, -30 ); 
   Vector lookAtPos( 15, 20, -30 );
   Vector upAxis; upAxis.set( Quad_0100 );

   MatrixUtils::generateLookAtLH( cameraOriginPos, lookAtPos, upAxis, tamyLookAtMtx );

   Vector expectedLookVec;
   expectedLookVec.setSub( lookAtPos, cameraOriginPos );
   expectedLookVec.normalize();

   Vector transformedLookVec;
   tamyLookAtMtx.transformNorm( Vector( 0, 0, 1 ), transformedLookVec );

   COMPARE_VEC( cameraOriginPos, tamyLookAtMtx.position() );
   COMPARE_VEC( expectedLookVec, transformedLookVec );
}
Example #12
0
int main(int argc, char *argv[])
{	
	//Mat m0;
	//m0.rota(v0);
	//v0.print();
	//m0.print();

	Vector v;
	v.set(3.0,4.0,5.0);
	//Matrix m;
//	m.setupTranslation(v);
	//Vector v1=m.getTranslation();
	//v1.print();
//	m.scale(v);
//	v.print();
	//m.print();

	//	system("pause");
		printf("%d\n",_MM_SHUFFLE(  3,1,0,3 ));
}
Example #13
0
int main(void)
{
	using namespace std;
	using VECTOR::Vector;
	srand(time(0));
	double direction;
	Vector step;
	Vector result(0.0,0.0);
	unsigned long steps = 0;
	double target;
	double dstep;

	cout << "Enter target distance (q to quit): ";
	while(cin >> target)
	{
		cout << "Enter step length: ";
		if(! (cin >> dstep))
			break;
		
		while(result.magval() < target)
		{
			direction = rand() % 360;
			step.set(dstep, direction, 'p');
			result = result + step;
			steps++;
		}
		cout << "After " << steps << " steps, the subject "
			"has the following location: \n";
		cout << result << endl;

		result.polar_mode();
		cout << " or\n" << result << endl;
		cout << "Average outward distance per step = "
			<< result.magval()/steps << endl;
		steps = 0;
		result.set(0.0, 0.0);
		cout << "Enter target distance(q to quit): ";
	}
	cout << "Bye!\n";
	return 0;
}
Example #14
0
void VectorTest::test_calculate_frequency(void)
{
    message += "test_calculate_frequency\n";

    Vector<double> v;

    size_t frequency;

    Histogram<double> histogram;

    // Test

    v.set(0.0, 1.0, 9.0);

    histogram = v.calculate_histogram(10);

    frequency = histogram.calculate_frequency(v[9]);

    assert_true(frequency == 1, LOG);

}
Example #15
0
void codingTable(Node* n, Vector<int> & code, Vector< Vector<int> > & codeTable, int & numOfCodes){

    if(n->left != NULL){
        code.add(0);
        codingTable(n->left, code, codeTable, numOfCodes);
    }
    if(n->right != NULL){
        code.add(1);

        codingTable(n->right, code, codeTable, numOfCodes);
    }

    if(isLeaf(n)){
        codeTable.set((n->value + 128), code);
        ++numOfCodes; // counter of coded symbols

    }
    if(code.size() > 0){
        code.remove(code.size()-1); // remove the last symbol in the code when returning one level above
    }
}
void NumericalDifferentiationTest::test_calculate_central_differences_Jacobian(void)
{
   message += "test_calculate_central_differences_Jacobian\n";

   NumericalDifferentiation nd;

   Vector<double> x;
   Matrix<double> J;

   Matrix<double> J_true;

   // Test

   x.set(2, 0.0);

   J = nd.calculate_central_differences_Jacobian(*this, &NumericalDifferentiationTest::f3, x);

   J_true.set_identity(2);

   assert_true(J == J_true, LOG);
}
Example #17
0
void FeProblem::assemble(_Vector *rhs, _Matrix *jac, _Vector *x)
{
        // Sanity checks.
	if (x->length() != this->ndof) error("Wrong vector length in assemble().");
	if (!have_spaces) error("You have to call set_spaces() before calling assemble().");
        for (int i=0; i<this->wf->neq; i++) {
          if (this->spaces[i] == NULL) error("A space is NULL in assemble().");
        }
 
        // Extract values from the vector 'x'.
	Vector* vv;
        if (x != NULL) {
          vv = new AVector(this->ndof);
	  memset(vv->get_c_array(), 0, this->ndof * sizeof(scalar));
	  for (int i=0; i<this->ndof; i++) vv->set(i, x->get(i));
        }

        // Convert the coefficient vector 'x' into solutions Tuple 'u_ext'.
        Tuple<Solution*> u_ext;
	for (int i = 0; i < this->wf->neq; i++) {
	  if (x != NULL) {
            u_ext.push_back(new Solution(this->spaces[i]->get_mesh()));
	    u_ext[i]->set_fe_solution(this->spaces[i], this->pss[i], vv);
          }
          else u_ext.push_back(NULL);
	}
	if (x != NULL) delete vv;

        // Perform assembling.
        this->assemble(rhs, jac, u_ext);

        // Delete temporary solutions.
	for (int i = 0; i < wf->neq; i++) {
	  if (u_ext[i] != NULL) {
            delete u_ext[i];
	    u_ext[i] = NULL;
          }
	}
}
Example #18
0
/** @brief calculate the normals of all triangles (Tn) and the average
  normals of the vertices (N); average normals are averaged over
  all adjacent triangles that are in the triangle list or member of
  a strip */
void Mesh::computeNormals() {
  uint i;
  Vector a, b, c;
  Tn.resize(T.d0, 3);
  Tn.setZero();
  Vn.resize(V.d0, 3);
  Vn.setZero();
  //triangle normals and contributions
  for(i=0; i<T.d0; i++) {
    a.set(&V(T(i, 0), 0));
    b.set(&V(T(i, 1), 0));
    c.set(&V(T(i, 2), 0));

    b-=a; c-=a; a=b^c; a.normalize();
    Tn(i, 0)=a.x;  Tn(i, 1)=a.y;  Tn(i, 2)=a.z;
    Vn(T(i, 0), 0)+=a.x;  Vn(T(i, 0), 1)+=a.y;  Vn(T(i, 0), 2)+=a.z;
    Vn(T(i, 1), 0)+=a.x;  Vn(T(i, 1), 1)+=a.y;  Vn(T(i, 1), 2)+=a.z;
    Vn(T(i, 2), 0)+=a.x;  Vn(T(i, 2), 1)+=a.y;  Vn(T(i, 2), 2)+=a.z;
  }
  Vector d;
  for(i=0; i<Vn.d0; i++) { d.set(&Vn(i, 0)); Vn[i]()/=d.length(); }
}
Example #19
0
void NeuralNetworkTest::test_set_parameters(void) {
  message += "test_set_parameters\n";

  Vector<unsigned> multilayer_perceptron_architecture;
  NeuralNetwork nn;

  unsigned parameters_number;
  Vector<double> parameters;

  // Test

  nn.set_parameters(parameters);

  parameters = nn.arrange_parameters();
  assert_true(parameters.size() == 0, LOG);

  // Test

  multilayer_perceptron_architecture.set(2, 2);
  nn.set(multilayer_perceptron_architecture);

  nn.construct_independent_parameters();

  nn.get_independent_parameters_pointer()->set_parameters_number(2);

  parameters_number = nn.count_parameters_number();

  parameters.set(0.0, 1.0, parameters_number - 1);
  nn.set_parameters(parameters);
  parameters = nn.arrange_parameters();

  assert_true(parameters.size() == parameters_number, LOG);
  assert_true(parameters[0] == 0.0, LOG);
  assert_true(parameters[parameters_number - 1] == parameters_number - 1.0,
              LOG);
}
Example #20
0
void Camera::createRay( float viewportX, float viewportY, Ray& outRay )
{
   // now I treat the mouse position as if it was located on the near clipping plane
   Vector mouseOnNearPlane;
   mouseOnNearPlane.set( viewportX, viewportY, -m_nearZPlane );

   // these 3d coords are in the viewport space - now I need to transform them into world space
   const Matrix& viewMtx = getViewMtx();
   const Matrix& projMtx = getProjectionMtx();

   Matrix combinedMtx;
   combinedMtx.setMul( viewMtx, projMtx );
   combinedMtx.invert();

   // once I have the backwards transformation, I use it on the 3D mouse coord
   Vector projMouseOnNearPlane;
   combinedMtx.transform( mouseOnNearPlane, projMouseOnNearPlane );

   // now I just need to find the vector between this point and the camera world space position and normalize it, and I should get my direction:
   const Matrix& globalMtx = getGlobalMtx();
   outRay.origin = globalMtx.position();
   outRay.direction.setSub( projMouseOnNearPlane, outRay.origin );
   outRay.direction.normalize();
}
void PerformanceFunctionalTest::test_calculate_directional_performance(void)
{
   message += "test_calculate_directional_performance\n";

   NeuralNetwork nn;

   Vector<double> direction;
   double rate;

   PerformanceFunctional pf(&nn);

   // Test

   nn.set(1, 1);

   pf.destruct_all_terms();
   pf.set_regularization_type(PerformanceFunctional::NEURAL_PARAMETERS_NORM_REGULARIZATION);

   direction.set(2, 1.0e3);

   rate = 1.0e3;

   assert_true(pf.calculate_performance(direction, rate) != pf.calculate_performance(), LOG);
}
Example #22
0
void HouseHold::HouseHolder(Vector v,int n)
{
	delta=v.modular();
	if(delta==0)
	{
		Matrix temp(n);
		T=&temp;
	}
	else
	{
	    v.set(0,v[0]-delta);
	    if(v.modular()==0)//ÒÔºóÒª¸Ä
		{
		Matrix temp(n);
		T=&temp;
	    }
	    else 
	    v.Normalize();
	    v.Span(*T);
	    Matrix temp(n);
		T->NumProd(2);
	    temp.Minus(*T);
	}
}
void NumericalDifferentiationTest::test_calculate_forward_differences_Hessian_form(void)
{
   message += "test_calculate_forward_differences_Hessian_form\n";

   NumericalDifferentiation nd;

   Vector<double> x;
   Vector< Matrix<double> > H;

   // Test

   x.set(2, 0.0);
   H = nd.calculate_forward_differences_Hessian_form(*this, &NumericalDifferentiationTest::f3, x);

   assert_true(H.size() == 2, LOG);

   assert_true(H[0].get_rows_number() == 2, LOG);
   assert_true(H[0].get_columns_number() == 2, LOG);
   assert_true(H[0] == 0.0, LOG);

   assert_true(H[1].get_rows_number() == 2, LOG);
   assert_true(H[1].get_columns_number() == 2, LOG);
   assert_true(H[1] == 0.0, LOG);
}
Example #24
0
void VectorTest::test_dot_vector(void)
{
   message += "test_dot_vector\n";

   Vector<double> a;
   Vector<double> b;

   double c;

   // Test

   a.set(1, 2.0);
   b.set(1, 2.0);

   c = a.dot(b);

   assert_true(c == 4.0, LOG);

   // Test

   a.set(2, 0.0);
   b.set(2, 0.0);

   c = a.dot(b);

   assert_true(c == 0.0, LOG);

   // Test

   a.set(3);
   a.randomize_normal();

   b.set(3);
   b.randomize_normal();

   c = a.dot(b);

   assert_true(c == dot(a, b), LOG);
}
Example #25
0
void VectorTest::test_get_assembly(void)
{
   message += "test_get_assembly\n";

   Vector<int> a;
   Vector<int> b;
   Vector<int> c; 
   Vector<int> d; 
	   
   c = a.assemble(b);

   assert_true(c.size() == 0, LOG);

   a.set(1, 0);
   b.set(0, 0),
   c = a.assemble(b);

   assert_true(c.size() == 1, LOG);

   a.set(0, 0);
   b.set(1, 0),
   c = a.assemble(b);

   assert_true(c.size() == 1, LOG);

   a.set(1, 0);
   b.set(1, 1);
  
   c = a.assemble(b);

   d.resize(2);
   d[0] = 0;
   d[1] = 1;

   assert_true(c == d, LOG);
}
Example #26
0
int main(int argc, char* argv[])
{
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Load the mesh.
  Mesh basemesh, mesh_T, mesh_phi;
  H2DReader mloader;
  mloader.load("domain.mesh", &basemesh);

  // Perform initial mesh refinements.
  for (int i=0; i < INIT_GLOB_REF_NUM; i++)
    basemesh.refine_all_elements();
  basemesh.refine_towards_boundary(1, INIT_BDY_REF_NUM);
  
  // Create a special mesh for each physical field.
  mesh_T.copy(&basemesh);
  mesh_phi.copy(&basemesh);

  // Create H1 spaces with default shapesets.
  H1Space space_T(&mesh_T, bc_types_T, essential_bc_values_T, P_INIT);
  H1Space space_phi(&mesh_phi, bc_types_phi, essential_bc_values_phi, P_INIT);
  Tuple<Space*> spaces(&space_T, &space_phi);
  int ndof = Space::get_num_dofs(spaces); 
 
  // Solutions in the previous time step (converging within the time stepping loop).
  Solution T_prev_time, phi_prev_time;
  Tuple<Solution*> prev_time_solutions(&T_prev_time, &phi_prev_time);
  
  // Solutions on the coarse and refined meshes in current time step (converging within the Newton's loop).
  Solution T_coarse, phi_coarse, T_fine, phi_fine;
  Tuple<Solution*> coarse_mesh_solutions(&T_coarse, &phi_coarse);
  Tuple<Solution*> fine_mesh_solutions(&T_fine, &phi_fine);
  
  // Initialize the weak formulation.
  WeakForm wf(2);
  wf.add_matrix_form(0, 0, jac_TT, jac_TT_ord);
  wf.add_matrix_form(0, 1, jac_Tphi, jac_Tphi_ord);
  wf.add_vector_form(0, res_T, res_T_ord, HERMES_ANY, &T_prev_time);
  wf.add_matrix_form(1, 0, jac_phiT, jac_phiT_ord);
  wf.add_matrix_form(1, 1, jac_phiphi, jac_phiphi_ord);
  wf.add_vector_form(1, res_phi, res_phi_ord, HERMES_ANY, &phi_prev_time);

  // DOF and CPU convergence graphs.
  SimpleGraph graph_dof_est_T, graph_dof_exact_T, graph_cpu_est_T, graph_cpu_exact_T;
  SimpleGraph graph_dof_est_phi, graph_dof_exact_phi, graph_cpu_est_phi, graph_cpu_exact_phi;
  
  // Exact solutions for error evaluation.
  ExactSolution T_exact_solution(&mesh_T, T_exact);
  ExactSolution phi_exact_solution(&mesh_phi, phi_exact);

  // Initialize refinement selector.
  H1ProjBasedSelector selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER);

  // Initialize the nonlinear system.
  DiscreteProblem dp(&wf, spaces);
  Tuple<ProjNormType> proj_norms(HERMES_H1_NORM, HERMES_H1_NORM);
  
  // Set initial conditions.
  T_prev_time.set_exact(&mesh_T, T_exact);
  phi_prev_time.set_exact(&mesh_phi, phi_exact);
  
  // Newton's loop on the initial coarse meshes.
  info("Solving on coarse meshes.");
  scalar* coeff_vec_coarse = new scalar[Space::get_num_dofs(spaces)];
  OGProjection::project_global(spaces, Tuple<MeshFunction*>((MeshFunction*)&T_prev_time, (MeshFunction*)&phi_prev_time), 
                 coeff_vec_coarse, matrix_solver, proj_norms);
  bool verbose = true; // Default is false.
  
  // Initialize the FE problem.
  bool is_linear = false;
  DiscreteProblem dp_coarse(&wf, spaces, is_linear);

  // Set up the solver_coarse, matrix_coarse, and rhs_coarse according to the solver_coarse selection.
  SparseMatrix* matrix_coarse = create_matrix(matrix_solver);
  Vector* rhs_coarse = create_vector(matrix_solver);
  Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse);

  // Perform Newton's iteration.
  int it = 1;
  while (1)
  {
    // Obtain the number of degrees of freedom.
    int ndof = Space::get_num_dofs(spaces);

    // Assemble the Jacobian matrix_coarse and residual vector.
    dp_coarse.assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse, false);

    // Multiply the residual vector with -1 since the matrix_coarse 
    // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
    for (int i = 0; i < ndof; i++) rhs_coarse->set(i, -rhs_coarse->get(i));
    
    // Calculate the l2-norm of residual vector.
    double res_l2_norm = get_l2_norm(rhs_coarse);

    // Info for user.
    info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(spaces), res_l2_norm);

    // If l2 norm of the residual vector is within tolerance, or the maximum number 
    // of iteration has been reached, then quit.
    if (res_l2_norm < NEWTON_TOL_COARSE || it > NEWTON_MAX_ITER) break;

    // Solve the linear system.
    if(!solver_coarse->solve())
      error ("matrix_coarse solver_coarse failed.\n");

    // Add \deltaY^{n+1} to Y^n.
    for (int i = 0; i < ndof; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i];
    
    if (it >= NEWTON_MAX_ITER)
      error ("Newton method did not converge.");

    it++;
  }
  
  // Translate the resulting coefficient vector into the actual solutions. 
  Solution::vector_to_solutions(coeff_vec_coarse, spaces, coarse_mesh_solutions);

  delete [] coeff_vec_coarse;
  delete rhs_coarse;
  delete matrix_coarse;
  delete solver_coarse;
  
  // Time stepping loop:
  int nstep = (int)(T_FINAL/TAU + 0.5);
  for(int ts = 1; ts <= nstep; ts++)
  {
    // Update global time.
    TIME = ts*TAU;

    // Update time-dependent exact solutions.
    T_exact_solution.update(&mesh_T, T_exact);
    phi_exact_solution.update(&mesh_phi, phi_exact);

    // Periodic global derefinement.
    if (ts > 1) {
      if (ts % UNREF_FREQ == 0) {
        info("---- Time step %d - prior to adaptivity:", ts);
        info("Global mesh derefinement.");
        mesh_T.copy(&basemesh);
        mesh_phi.copy(&basemesh);
        space_T.set_uniform_order(P_INIT);
        space_phi.set_uniform_order(P_INIT);
        
        if (SOLVE_ON_COARSE_MESH) {
          // Newton's loop on the globally derefined meshes.
          scalar* coeff_vec_coarse = new scalar[Space::get_num_dofs(spaces)];
          info("Solving on globally derefined meshes, starting from the latest fine mesh solutions.");
          OGProjection::project_global(spaces, Tuple<MeshFunction*>((MeshFunction*)&T_fine, (MeshFunction*)&phi_fine), 
                         coeff_vec_coarse, matrix_solver, proj_norms);
          
          // Initialize the FE problem.
          bool is_linear = false;
          DiscreteProblem dp_coarse(&wf, spaces, is_linear);

          // Set up the solver_coarse, matrix_coarse, and rhs_coarse according to the solver_coarse selection.
          SparseMatrix* matrix_coarse = create_matrix(matrix_solver);
          Vector* rhs_coarse = create_vector(matrix_solver);
          Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse);

          // Perform Newton's iteration.
          int it = 1;
          while (1)
          {
            // Obtain the number of degrees of freedom.
            int ndof = Space::get_num_dofs(spaces);

            // Assemble the Jacobian matrix_coarse and residual vector.
            dp_coarse.assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse, false);

            // Multiply the residual vector with -1 since the matrix_coarse 
            // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
            for (int i = 0; i < ndof; i++) rhs_coarse->set(i, -rhs_coarse->get(i));
            
            // Calculate the l2-norm of residual vector.
            double res_l2_norm = get_l2_norm(rhs_coarse);

            // Info for user.
            info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(spaces), res_l2_norm);

            // If l2 norm of the residual vector is within tolerance, or the maximum number 
            // of iteration has been reached, then quit.
            if (res_l2_norm < NEWTON_TOL_COARSE || it > NEWTON_MAX_ITER) break;

            // Solve the linear system.
            if(!solver_coarse->solve())
              error ("matrix_coarse solver_coarse failed.\n");

            // Add \deltaY^{n+1} to Y^n.
            for (int i = 0; i < ndof; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i];
            
            if (it >= NEWTON_MAX_ITER)
              error ("Newton method did not converge.");

            it++;
          }
          
          // Translate the resulting coefficient vector into the actual solutions. 
          Solution::vector_to_solutions(coeff_vec_coarse, spaces, coarse_mesh_solutions);
          delete [] coeff_vec_coarse;
          delete rhs_coarse;
          delete matrix_coarse;
          delete solver_coarse;
        } 
        else {
          // Projection onto the globally derefined meshes.
          info("Projecting the latest fine mesh solution onto globally derefined meshes.");
          OGProjection::project_global(spaces, fine_mesh_solutions, coarse_mesh_solutions, matrix_solver, proj_norms); 
        }
      } 
    }

    // Adaptivity loop:
    bool done = false;
    int as = 0;
    do {
      as++;
      
      info("---- Time step %d, adaptivity step %d:", ts, as);

      // Construct globally refined reference mesh
      // and setup reference space.
      Tuple<Space *>* ref_spaces = construct_refined_spaces(spaces);

      // Newton's loop on the refined meshes.
      scalar* coeff_vec = new scalar[Space::get_num_dofs(*ref_spaces)];
      if (as == 1) {
        info("Solving on fine meshes, starting from previous coarse mesh solutions.");
        OGProjection::project_global(*ref_spaces, Tuple<MeshFunction*>((MeshFunction*)&T_coarse, (MeshFunction*)&phi_coarse), 
                       coeff_vec, matrix_solver, proj_norms);
      } else {
        info("Solving on fine meshes, starting from previous fine mesh solutions.");
        OGProjection::project_global(*ref_spaces, Tuple<MeshFunction*>((MeshFunction*)&T_fine, (MeshFunction*)&phi_fine), 
                       coeff_vec, matrix_solver, proj_norms);
      }
      
      // Initialize the FE problem.
      bool is_linear = false;
      DiscreteProblem dp(&wf, *ref_spaces, is_linear);

      // Set up the solver, matrix, and rhs according to the solver selection.
      SparseMatrix* matrix = create_matrix(matrix_solver);
      Vector* rhs = create_vector(matrix_solver);
      Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

      // Perform Newton's iteration.
      int it = 1;
      while (1)
      {
        // Obtain the number of degrees of freedom.
        int ndof = Space::get_num_dofs(*ref_spaces);

        // Assemble the Jacobian matrix and residual vector.
        dp.assemble(coeff_vec, matrix, rhs, false);

        // Multiply the residual vector with -1 since the matrix 
        // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
        for (int i = 0; i < ndof; i++) rhs->set(i, -rhs->get(i));
        
        // Calculate the l2-norm of residual vector.
        double res_l2_norm = get_l2_norm(rhs);

        // Info for user.
        info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(*ref_spaces), res_l2_norm);

        // If l2 norm of the residual vector is within tolerance, or the maximum number 
        // of iteration has been reached, then quit.
        if (res_l2_norm < NEWTON_TOL_FINE || it > NEWTON_MAX_ITER) break;

        // Solve the linear system.
        if(!solver->solve())
          error ("Matrix solver failed.\n");

        // Add \deltaY^{n+1} to Y^n.
        for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i];
        
        if (it >= NEWTON_MAX_ITER)
          error ("Newton method did not converge.");

        it++;
      }
      
      // Translate the resulting coefficient vector into the actual solutions. 
      Solution::vector_to_solutions(coeff_vec, *ref_spaces, fine_mesh_solutions);
      delete [] coeff_vec;
      delete rhs;
      delete matrix;
      delete solver;

      // Calculate element errors.
      info("Calculating error estimate and exact error."); 
      Adapt* adaptivity = new Adapt(spaces, proj_norms);

      // Calculate error estimate for each solution component and the total error estimate.
      bool solutions_for_adapt = true;
      Tuple<double> err_est_rel;
      double err_est_rel_total = adaptivity->calc_err_est(coarse_mesh_solutions, fine_mesh_solutions, solutions_for_adapt, 
                                 HERMES_TOTAL_ERROR_REL | HERMES_ELEMENT_ERROR_ABS, &err_est_rel) * 100;

      // Calculate exact error for each solution component and the total exact error.
      solutions_for_adapt = false;
      Tuple<double> err_exact_rel;
      double err_exact_rel_total = adaptivity->calc_err_exact(coarse_mesh_solutions, Tuple<Solution *>(&T_exact_solution, &phi_exact_solution), solutions_for_adapt, 
                                 HERMES_TOTAL_ERROR_REL | HERMES_ELEMENT_ERROR_ABS, &err_exact_rel) * 100;

      info("T: ndof_coarse: %d, ndof_fine: %d, err_est: %g %%, err_exact: %g %%", 
            space_T.get_num_dofs(), (*ref_spaces)[0]->get_num_dofs(), err_est_rel[0]*100, err_exact_rel[0]*100);
      info("phi: ndof_coarse: %d, ndof_fine: %d, err_est: %g %%, err_exact: %g %%", 
            space_phi.get_num_dofs(), (*ref_spaces)[1]->get_num_dofs(), err_est_rel[1]*100, err_exact_rel[1]*100);
      
      // If err_est too large, adapt the mesh.
      if (err_est_rel_total < ERR_STOP) done = true;
      else {
        info("Adapting the coarse meshes.");
        done = adaptivity->adapt(Tuple<RefinementSelectors::Selector*> (&selector, &selector), THRESHOLD, STRATEGY, MESH_REGULARITY);
        if (Space::get_num_dofs(spaces) >= NDOF_STOP) done = true; 
        
        if (!done) {
          if (SOLVE_ON_COARSE_MESH) {        
            // Newton's loop on the new coarse meshes.
            scalar* coeff_vec_coarse = new scalar[Space::get_num_dofs(spaces)];
            info("Solving on coarse meshes, starting from the latest fine mesh solutions.");
            OGProjection::project_global(spaces, Tuple<MeshFunction*>((MeshFunction*)&T_fine, (MeshFunction*)&phi_fine), 
                           coeff_vec_coarse, matrix_solver, proj_norms);
            
            // Initialize the FE problem.
            bool is_linear = false;
            DiscreteProblem dp_coarse(&wf, spaces, is_linear);

            // Set up the solver_coarse, matrix_coarse, and rhs_coarse according to the solver_coarse selection.
            SparseMatrix* matrix_coarse = create_matrix(matrix_solver);
            Vector* rhs_coarse = create_vector(matrix_solver);
            Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse);

            // Perform Newton's iteration.
            int it = 1;
            while (1)
            {
              // Obtain the number of degrees of freedom.
              int ndof = Space::get_num_dofs(spaces);

              // Assemble the Jacobian matrix_coarse and residual vector.
              dp.assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse, false);

              // Multiply the residual vector with -1 since the matrix_coarse 
              // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
              for (int i = 0; i < ndof; i++) rhs_coarse->set(i, -rhs_coarse->get(i));
              
              // Calculate the l2-norm of residual vector.
              double res_l2_norm = get_l2_norm(rhs_coarse);

              // Info for user.
              info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(spaces), res_l2_norm);

              // If l2 norm of the residual vector is within tolerance, or the maximum number 
              // of iteration has been reached, then quit.
              if (res_l2_norm < NEWTON_TOL_COARSE || it > NEWTON_MAX_ITER) break;

              // Solve the linear system.
              if(!solver_coarse->solve())
                error ("matrix_coarse solver_coarse failed.\n");

              // Add \deltaY^{n+1} to Y^n.
              for (int i = 0; i < ndof; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i];
              
              if (it >= NEWTON_MAX_ITER)
                error ("Newton method did not converge.");

              it++;
            }
            
            // Translate the resulting coefficient vector into the actual solutions. 
            Solution::vector_to_solutions(coeff_vec_coarse, spaces, coarse_mesh_solutions);
            delete [] coeff_vec_coarse;
            delete rhs_coarse;
            delete matrix_coarse;
            delete solver_coarse;
          } 
          else {
            // Projection onto the new coarse meshes.
            info("Projecting the latest fine mesh solution onto new coarse meshes.");
            OGProjection::project_global(spaces, fine_mesh_solutions, coarse_mesh_solutions, matrix_solver, proj_norms); 
          }
        }
      }
      delete adaptivity;
      for(int i = 0; i < ref_spaces->size(); i++)
        delete (*ref_spaces)[i]->get_mesh();
      delete ref_spaces;
    }
    while (!done);

    // Make the fine mesh solution at current time level the previous time level solution in the following time step.
    T_prev_time.copy(&T_fine);
    phi_prev_time.copy(&phi_fine);
  }

  info("Coordinate ( 25.0,  25.0) T value = %lf", T_prev_time.get_pt_value(25.0, 25.0));
  info("Coordinate ( 25.0,  75.0) T value = %lf", T_prev_time.get_pt_value(25.0, 75.0));
  info("Coordinate ( 75.0, 25.0) T value = %lf", T_prev_time.get_pt_value(75.0, 25.0));
  info("Coordinate ( 75.0, 75.0) T value = %lf", T_prev_time.get_pt_value(75.0, 75.0));
  info("Coordinate ( 50.0, 50.0) T value = %lf", T_prev_time.get_pt_value(50.0, 50.0));

  info("Coordinate ( 25.0, 25.0) phi value = %lf", phi_prev_time.get_pt_value(25.0, 25.0));
  info("Coordinate ( 25.0, 75.0) phi value = %lf", phi_prev_time.get_pt_value(25.0, 75.0));
  info("Coordinate ( 75.0, 25.0) phi value = %lf", phi_prev_time.get_pt_value(75.0, 25.0));
  info("Coordinate ( 75.0, 75.0) phi value = %lf", phi_prev_time.get_pt_value(75.0, 75.0));
  info("Coordinate ( 50.0, 50.0) phi value = %lf", phi_prev_time.get_pt_value(50.0, 50.0));

#define ERROR_SUCCESS                               0
#define ERROR_FAILURE                               -1
  int ndof_allowed_T = 130;
  int ndof_allowed_phi = 300;
  int ndof_T = Space::get_num_dofs(&space_T);
  int ndof_phi = Space::get_num_dofs(&space_phi);
  printf("ndof_actual_T = %d\n", ndof_T);
  printf("ndof_actual_phi = %d\n", ndof_phi);
  printf("ndof_allowed_T = %d\n", ndof_allowed_T);
  printf("ndof_allowed_phi = %d\n", ndof_allowed_phi);
  if ((ndof_T <= ndof_allowed_T) && (ndof_phi <= ndof_allowed_phi)) {  
    // ndofs_T was 121 and ndof_phi was 267 at the time this test was created
    printf("Success!\n");
    return ERROR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERROR_FAILURE;
  }
}
Example #27
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("domain.mesh", &mesh);

  // Initial mesh refinements.
  mesh.refine_all_elements();
  mesh.refine_towards_boundary(bdy_obstacle, 4, false);
  mesh.refine_towards_boundary(bdy_top, 4, true);     // '4' is the number of levels,
  mesh.refine_towards_boundary(bdy_bottom, 4, true);  // 'true' stands for anisotropic refinements.

  // Spaces for velocity components and pressure.
  H1Space xvel_space(&mesh, xvel_bc_type, essential_bc_values_xvel, P_INIT_VEL);
  H1Space yvel_space(&mesh, yvel_bc_type, NULL, P_INIT_VEL);
#ifdef PRESSURE_IN_L2
  L2Space p_space(&mesh, P_INIT_PRESSURE);
#else
  H1Space p_space(&mesh, NULL, NULL, P_INIT_PRESSURE);
#endif

  // Calculate and report the number of degrees of freedom.
  int ndof = Space::get_num_dofs(Tuple<Space *>(&xvel_space, &yvel_space, &p_space));
  info("ndof = %d.", ndof);

  // Define projection norms.
  ProjNormType vel_proj_norm = HERMES_H1_NORM;
#ifdef PRESSURE_IN_L2
  ProjNormType p_proj_norm = HERMES_L2_NORM;
#else
  ProjNormType p_proj_norm = HERMES_H1_NORM;
#endif

  // Solutions for the Newton's iteration and time stepping.
  info("Setting initial conditions.");
  Solution xvel_prev_time, yvel_prev_time, p_prev_time; 
  xvel_prev_time.set_zero(&mesh);
  yvel_prev_time.set_zero(&mesh);
  p_prev_time.set_zero(&mesh);

  // Initialize weak formulation.
  WeakForm wf(3);
  if (NEWTON) {
    wf.add_matrix_form(0, 0, callback(bilinear_form_sym_0_0_1_1), HERMES_SYM);
    wf.add_matrix_form(0, 0, callback(newton_bilinear_form_unsym_0_0), HERMES_UNSYM, HERMES_ANY);
    wf.add_matrix_form(0, 1, callback(newton_bilinear_form_unsym_0_1), HERMES_UNSYM, HERMES_ANY);
    wf.add_matrix_form(0, 2, callback(bilinear_form_unsym_0_2), HERMES_ANTISYM);
    wf.add_matrix_form(1, 0, callback(newton_bilinear_form_unsym_1_0), HERMES_UNSYM, HERMES_ANY);
    wf.add_matrix_form(1, 1, callback(bilinear_form_sym_0_0_1_1), HERMES_SYM);
    wf.add_matrix_form(1, 1, callback(newton_bilinear_form_unsym_1_1), HERMES_UNSYM, HERMES_ANY);
    wf.add_matrix_form(1, 2, callback(bilinear_form_unsym_1_2), HERMES_ANTISYM);
    wf.add_vector_form(0, callback(newton_F_0), HERMES_ANY, 
                       Tuple<MeshFunction*>(&xvel_prev_time, &yvel_prev_time));
    wf.add_vector_form(1, callback(newton_F_1), HERMES_ANY, 
                       Tuple<MeshFunction*>(&xvel_prev_time, &yvel_prev_time));
    wf.add_vector_form(2, callback(newton_F_2), HERMES_ANY);
  }
  else {
    wf.add_matrix_form(0, 0, callback(bilinear_form_sym_0_0_1_1), HERMES_SYM);
    wf.add_matrix_form(0, 0, callback(simple_bilinear_form_unsym_0_0_1_1), 
                  HERMES_UNSYM, HERMES_ANY, Tuple<MeshFunction*>(&xvel_prev_time, &yvel_prev_time));
    wf.add_matrix_form(1, 1, callback(bilinear_form_sym_0_0_1_1), HERMES_SYM);
    wf.add_matrix_form(1, 1, callback(simple_bilinear_form_unsym_0_0_1_1), 
                  HERMES_UNSYM, HERMES_ANY, Tuple<MeshFunction*>(&xvel_prev_time, &yvel_prev_time));
    wf.add_matrix_form(0, 2, callback(bilinear_form_unsym_0_2), HERMES_ANTISYM);
    wf.add_matrix_form(1, 2, callback(bilinear_form_unsym_1_2), HERMES_ANTISYM);
    wf.add_vector_form(0, callback(simple_linear_form), HERMES_ANY, &xvel_prev_time);
    wf.add_vector_form(1, callback(simple_linear_form), HERMES_ANY, &yvel_prev_time);
  }

  // Initialize the FE problem.
  bool is_linear;
  if (NEWTON) is_linear = false;
  else is_linear = true;
  DiscreteProblem dp(&wf, Tuple<Space *>(&xvel_space, &yvel_space, &p_space), is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize views.
  VectorView vview("velocity [m/s]", new WinGeom(0, 0, 750, 240));
  ScalarView pview("pressure [Pa]", new WinGeom(0, 290, 750, 240));
  vview.set_min_max_range(0, 1.6);
  vview.fix_scale_width(80);
  //pview.set_min_max_range(-0.9, 1.0);
  pview.fix_scale_width(80);
  pview.show_mesh(true);

  // Project the initial condition on the FE space to obtain initial
  // coefficient vector for the Newton's method.
  scalar* coeff_vec = new scalar[Space::get_num_dofs(Tuple<Space *>(&xvel_space, &yvel_space, &p_space))];
  if (NEWTON) {
    info("Projecting initial condition to obtain initial vector for the Newton's method.");
    OGProjection::project_global(Tuple<Space *>(&xvel_space, &yvel_space, &p_space), 
                   Tuple<MeshFunction *>(&xvel_prev_time, &yvel_prev_time, &p_prev_time), 
                   coeff_vec, 
                   matrix_solver, 
                   Tuple<ProjNormType>(vel_proj_norm, vel_proj_norm, p_proj_norm));
  }

  // Time-stepping loop:
  char title[100];
  int num_time_steps = T_FINAL / TAU;
  for (int ts = 1; ts <= num_time_steps; ts++)
  {
    TIME += TAU;
    info("---- Time step %d, time = %g:", ts, TIME);

    // Update time-dependent essential BC are used.
    if (TIME <= STARTUP_TIME) {
      info("Updating time-dependent essential BC.");
      update_essential_bc_values(Tuple<Space *>(&xvel_space, &yvel_space, &p_space));
    }

    if (NEWTON) 
    {
      // Perform Newton's iteration.
      int it = 1;
      while (1)
      {
        // Assemble the Jacobian matrix and residual vector.
        dp.assemble(coeff_vec, matrix, rhs, false);

        // Multiply the residual vector with -1 since the matrix 
        // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
        for (int i = 0; i < ndof; i++) rhs->set(i, -rhs->get(i));
        
        // Calculate the l2-norm of residual vector.
        double res_l2_norm = get_l2_norm(rhs);

        // Info for user.
        info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(Tuple<Space *>(&xvel_space, &yvel_space, &p_space)), res_l2_norm);

        // If l2 norm of the residual vector is within tolerance, or the maximum number 
        // of iteration has been reached, then quit.
        if (res_l2_norm < NEWTON_TOL || it > NEWTON_MAX_ITER) break;

        // Solve the linear system.
        if(!solver->solve())
          error ("Matrix solver failed.\n");

          // Add \deltaY^{n+1} to Y^n.
        for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i];
        
        if (it >= NEWTON_MAX_ITER)
          error ("Newton method did not converge.");

        it++;
      }
  
      // Update previous time level solutions.
      Solution::vector_to_solutions(coeff_vec, Tuple<Space *>(&xvel_space, &yvel_space, &p_space), Tuple<Solution *>(&xvel_prev_time, &yvel_prev_time, &p_prev_time));
    }
    else {
      // Linear solve.
      info("Assembling and solving linear problem.");
      dp.assemble(matrix, rhs, false);
      if(solver->solve()) 
        Solution::vector_to_solutions(solver->get_solution(), Tuple<Space *>(&xvel_space, &yvel_space, &p_space), Tuple<Solution *>(&xvel_prev_time, &yvel_prev_time, &p_prev_time));
      else 
        error ("Matrix solver failed.\n");
    }

    // Show the solution at the end of time step.
    sprintf(title, "Velocity, time %g", TIME);
    vview.set_title(title);
    vview.show(&xvel_prev_time, &yvel_prev_time, HERMES_EPS_LOW);
    sprintf(title, "Pressure, time %g", TIME);
    pview.set_title(title);
    pview.show(&p_prev_time);
 }

  delete [] coeff_vec;
  delete matrix;
  delete rhs;
  delete solver;
  
  // Wait for all views to be closed.
  View::wait();
  return 0;
}
Example #28
0
int main() {
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Create coarse mesh, set Dirichlet BC, enumerate basis functions.
  Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ);

  // Enumerate basis functions, info for user.
  int ndof = Space::get_num_dofs(space);
  info("ndof: %d", ndof);

  // Initialize the weak formulation.
  WeakForm wf;
  wf.add_matrix_form(jacobian);
  wf.add_vector_form(residual);

  // Initialize the FE problem.
  bool is_linear = false;
  DiscreteProblem *dp_coarse = new DiscreteProblem(&wf, space, is_linear);

  // Newton's loop on coarse mesh.
  // Fill vector coeff_vec using dof and coeffs arrays in elements.
  double *coeff_vec_coarse = new double[Space::get_num_dofs(space)];
  get_coeff_vector(space, coeff_vec_coarse);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix_coarse = create_matrix(matrix_solver);
  Vector* rhs_coarse = create_vector(matrix_solver);
  Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse);

  int it = 1;
  while (1) {
    // Obtain the number of degrees of freedom.
    int ndof_coarse = Space::get_num_dofs(space);

    // Assemble the Jacobian matrix and residual vector.
    dp_coarse->assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse);

    // Calculate the l2-norm of residual vector.
    double res_l2_norm = get_l2_norm(rhs_coarse);

    // Info for user.
    info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space), res_l2_norm);

    // If l2 norm of the residual vector is within tolerance, then quit.
    // NOTE: at least one full iteration forced
    //       here because sometimes the initial
    //       residual on fine mesh is too small.
    if(res_l2_norm < NEWTON_TOL_COARSE && it > 1) break;

    // Multiply the residual vector with -1 since the matrix 
    // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
    for(int i=0; i < ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i));

    // Solve the linear system.
    if(!solver_coarse->solve())
      error ("Matrix solver failed.\n");

    // Add \deltaY^{n+1} to Y^n.
    for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i];

    // If the maximum number of iteration has been reached, then quit.
    if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge.");
    
    // Copy coefficients from vector y to elements.
    set_coeff_vector(coeff_vec_coarse, space);

    it++;
  }
  
  // Cleanup.
  delete matrix_coarse;
  delete rhs_coarse;
  delete solver_coarse;
  delete [] coeff_vec_coarse;
  delete dp_coarse;

  // DOF and CPU convergence graphs.
  SimpleGraph graph_dof_est, graph_cpu_est;
  SimpleGraph graph_dof_exact, graph_cpu_exact;

  // Adaptivity loop:
  int as = 1;
  bool done = false;
  do
  {
    info("---- Adaptivity step %d:", as); 

    // Construct globally refined reference mesh and setup reference space.
    Space* ref_space = construct_refined_space(space);

    // Initialize the FE problem. 
    bool is_linear = false;
    DiscreteProblem* dp = new DiscreteProblem(&wf, ref_space, is_linear);

    // Set up the solver, matrix, and rhs according to the solver selection.
    SparseMatrix* matrix = create_matrix(matrix_solver);
    Vector* rhs = create_vector(matrix_solver);
    Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

    // Newton's loop on the fine mesh.
    info("Solving on fine mesh:");

    // Fill vector coeff_vec using dof and coeffs arrays in elements.
    double *coeff_vec = new double[Space::get_num_dofs(ref_space)];
    get_coeff_vector(ref_space, coeff_vec);

    int it = 1;
    while (1) 
    {
      // Obtain the number of degrees of freedom.
      int ndof = Space::get_num_dofs(ref_space);

      // Assemble the Jacobian matrix and residual vector.
      dp->assemble(coeff_vec, matrix, rhs);

      // Calculate the l2-norm of residual vector.
      double res_l2_norm = get_l2_norm(rhs);

      // Info for user.
      info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(ref_space), res_l2_norm);

      // If l2 norm of the residual vector is within tolerance, then quit.
      // NOTE: at least one full iteration forced
      //       here because sometimes the initial
      //       residual on fine mesh is too small.
      if(res_l2_norm < NEWTON_TOL_REF && it > 1) break;

      // Multiply the residual vector with -1 since the matrix 
      // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
      for(int i = 0; i < ndof; i++) rhs->set(i, -rhs->get(i));

      // Solve the linear system.
      if(!solver->solve())
        error ("Matrix solver failed.\n");

      // Add \deltaY^{n+1} to Y^n.
      for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i];

      // If the maximum number of iteration has been reached, then quit.
      if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge.");
      
      // Copy coefficients from vector y to elements.
      set_coeff_vector(coeff_vec, ref_space);

      it++;
    }

    // Starting with second adaptivity step, obtain new coarse 
    // mesh solution via projecting the fine mesh solution.
    if(as > 1)
    {
      info("Projecting the fine mesh solution onto the coarse mesh.");
      // Project the fine mesh solution (defined on space_ref) onto the coarse mesh (defined on space).
      OGProjection::project_global(space, ref_space, matrix_solver);
    }

    // Calculate element errors and total error estimate.
    info("Calculating error estimate.");
    double err_est_array[MAX_ELEM_NUM]; 
    double err_est_rel = calc_err_est(NORM, space, ref_space, err_est_array) * 100;

    // Report results.
    info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%", 
      Space::get_num_dofs(space), Space::get_num_dofs(ref_space), err_est_rel);

    // Time measurement.
    cpu_time.tick();

    // If exact solution available, also calculate exact error.
    if (EXACT_SOL_PROVIDED) 
    {
      // Calculate element errors wrt. exact solution.
      double err_exact_rel = calc_err_exact(NORM, space, exact_sol, NEQ, A, B) * 100;
     
      // Info for user.
      info("Relative error (exact) = %g %%", err_exact_rel);
     
      // Add entry to DOF and CPU convergence graphs.
      graph_dof_exact.add_values(Space::get_num_dofs(space), err_exact_rel);
      graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel);
    }

    // Add entry to DOF and CPU convergence graphs.
    graph_dof_est.add_values(Space::get_num_dofs(space), err_est_rel);
    graph_cpu_est.add_values(cpu_time.accumulated(), err_est_rel);

    // If err_est_rel too large, adapt the mesh.
    if (err_est_rel < NEWTON_TOL_REF) done = true;
    else 
    {
      info("Adapting the coarse mesh.");
      adapt(NORM, ADAPT_TYPE, THRESHOLD, err_est_array, space, ref_space);
    }

    as++;

    // Plot meshes, results, and errors.
    adapt_plotting(space, ref_space, NORM, EXACT_SOL_PROVIDED, exact_sol);

    // Cleanup.
    delete solver;
    delete matrix;
    delete rhs;
    delete ref_space;
    delete dp;
    delete [] coeff_vec;
  }
  while (done == false);

  info("Total running time: %g s", cpu_time.accumulated());

  // Save convergence graphs.
  graph_dof_est.save("conv_dof_est.dat");
  graph_cpu_est.save("conv_cpu_est.dat");
  graph_dof_exact.save("conv_dof_exact.dat");
  graph_cpu_exact.save("conv_cpu_exact.dat");

  return 0;
}
void SimulatedAnnealingOrderTest::test_perform_order_selection(void)
{
    message += "test_perform_order_selection\n";

    std::string str;
    Matrix<double> data;

    Vector<Instances::Use> uses;

    NeuralNetwork nn;

    DataSet ds;

    PerformanceFunctional pf(&nn, &ds);

    TrainingStrategy ts(&pf);

    SimulatedAnnealingOrder sa(&ts);

    SimulatedAnnealingOrder::SimulatedAnnealingOrderResults* results;

    // Test

    str =
            "-1 0\n"
            "-0.9 0\n"
            "-0.8 0\n"
            "-0.7 0\n"
            "-0.6 0\n"
            "-0.5 0\n"
            "-0.4 0\n"
            "-0.3 0\n"
            "-0.2 0\n"
            "-0.1 0\n"
            "0.0 0\n"
            "0.1 0\n"
            "0.2 0\n"
            "0.3 0\n"
            "0.4 0\n"
            "0.5 0\n"
            "0.6 0\n"
            "0.7 0\n"
            "0.8 0\n"
            "0.9 0\n"
            "1 0\n";

    data.parse(str);
    ds.set(data);

    uses.set(21,Instances::Training);
    for (size_t i = 0; i < 11; i++)
        uses[2*i+1] = Instances::Generalization;

    ds.get_instances_pointer()->set_uses(uses);

    nn.set(1,3,1);
    nn.initialize_parameters(0.0);

    pf.set_objective_type(PerformanceFunctional::SUM_SQUARED_ERROR_OBJECTIVE);

    ts.set_main_type(TrainingStrategy::QUASI_NEWTON_METHOD);

    ts.get_quasi_Newton_method_pointer()->set_display(false);

    sa.set_trials_number(1);
    sa.set_maximum_order(7);
    sa.set_selection_performance_goal(1.0);
    sa.set_minimum_temperature(0.0);
    sa.set_display(false);

    results = sa.perform_order_selection();

    assert_true(results->stopping_condition ==
                OrderSelectionAlgorithm::SelectionPerformanceGoal, LOG);

    // Test

    str =
            "-1 -1\n"
            "-0.9 -0.9\n"
            "-0.8 -0.8\n"
            "-0.7 -0.7\n"
            "-0.6 -0.6\n"
            "-0.5 -0.5\n"
            "-0.4 -0.4\n"
            "-0.3 -0.3\n"
            "-0.2 -0.2\n"
            "-0.1 -0.1\n"
            "0.0 0.0\n"
            "0.1 0.1\n"
            "0.2 0.2\n"
            "0.3 0.3\n"
            "0.4 0.4\n"
            "0.5 0.5\n"
            "0.6 0.6\n"
            "0.7 0.7\n"
            "0.8 0.8\n"
            "0.9 0.9\n"
            "1 1\n";

    data.parse(str);
    ds.set(data);

    uses.set(21,Instances::Training);
    for (size_t i = 0; i < 11; i++)
        uses[2*i+1] = Instances::Generalization;

    ds.get_instances_pointer()->set_uses(uses);

    nn.set(1,3,1);
    nn.initialize_parameters(0.0);

    pf.set_objective_type(PerformanceFunctional::SUM_SQUARED_ERROR_OBJECTIVE);

    ts.set_main_type(TrainingStrategy::QUASI_NEWTON_METHOD);

    ts.get_quasi_Newton_method_pointer()->set_display(false);

    sa.set_trials_number(1);
    sa.set_maximum_order(7);
    sa.set_selection_performance_goal(0.0);
    sa.set_minimum_temperature(0.0);
    sa.set_display(false);

    results = sa.perform_order_selection();

    assert_true(results->stopping_condition ==
                OrderSelectionAlgorithm::MaximumSelectionFailures, LOG);

}
Example #30
0
int main() 
{
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Create space, set Dirichlet BC, enumerate basis functions.
  Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ);
  int ndof = Space::get_num_dofs(space);
  info("ndof: %d", ndof);

  // Initialize the weak formulation.
  WeakForm wf;
  wf.add_matrix_form(jacobian);
  wf.add_vector_form(residual);

  // Initialize the FE problem.
  bool is_linear = false;
  DiscreteProblem *dp = new DiscreteProblem(&wf, space, is_linear);

  // Set zero initial condition.
  double *coeff_vec = new double[ndof];
  set_zero(coeff_vec, ndof);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  int it = 1;
  bool success = false;
  while (1) 
  {
    // Obtain the number of degrees of freedom.
    int ndof = Space::get_num_dofs(space);

    // Assemble the Jacobian matrix and residual vector.
    dp->assemble(coeff_vec, matrix, rhs);

    // Calculate the l2-norm of residual vector.
    double res_l2_norm = get_l2_norm(rhs);

    // Info for user.
    info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space), res_l2_norm);

    // If l2 norm of the residual vector is within tolerance, then quit.
    // NOTE: at least one full iteration forced
    //       here because sometimes the initial
    //       residual on fine mesh is too small.
    if(res_l2_norm < NEWTON_TOL && it > 1) break;

    // Multiply the residual vector with -1 since the matrix 
    // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
    for(int i=0; i<ndof; i++) rhs->set(i, -rhs->get(i));

    // Solve the linear system.
    if(!(success = solver->solve()))
      error ("Matrix solver failed.\n");

    // Add \deltaY^{n+1} to Y^n.
    for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i];

    // If the maximum number of iteration has been reached, then quit.
    if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge.");
    
    it++;
  }

  info("Total running time: %g s", cpu_time.accumulated());

  // Test variable.
  info("ndof = %d.", Space::get_num_dofs(space));
  if (success)
  {
    info("Success!");
    return ERROR_SUCCESS;
  }
  else
  {
    info("Failure!");
    return ERROR_FAILURE;
  }
}