keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
2D | hpfem/hermes-examples | 2d-benchmarks-nist/05-battery/main.cpp | .cpp | 6,695 | 197 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the fifth in the series of NIST benchmarks with unknown exact solution.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: -\frac{\partial }{\partial x}\left(p(x, y)\frac{\partial u}{\partial x}\right)
// -\frac{\partial }{\partial y}\left(q(x, y)\frac{\partial u}{\partial y}\right) - f = 0.
//
// Exact solution: unknown.
//
// Domain: square (0, 8.4) x (0, 24), see the file "battery.mesh".
//
// BC: Zero Neumann on left edge, Newton on the rest of the boundary:
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1.0;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("battery.mesh", mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, P_INIT));
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormPoisson("e1", "e2", "e3", "e4", "e5", "Bdy_left", "Bdy_top", "Bdy_right", "Bdy_bottom", mesh));
// Initialize coarse and fine mesh solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>), ref_sln(new Solution<double>);
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
ScalarView sview("Solution", new WinGeom(0, 0, 320, 600));
sview.fix_scale_width(50);
sview.show_mesh(false);
OrderView oview("Polynomial orders", new WinGeom(330, 0, 300, 600));
// DOF and CPU convergence graphs initialization.
SimpleGraph graph_dof, graph_cpu;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Time measurement.
cpu_time.tick();
// Construct globally refined mesh and setup fine mesh space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
// Initialize fine mesh problem.
Hermes::Mixins::Loggable::Static::info("Solving on fine mesh.");
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
newton.set_verbose_output(true);
// Perform Newton's iteration.
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
}
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Time measurement.
cpu_time.tick();
// VTK output.
if (VTK_VISUALIZATION)
{
// Output solution in VTK format.
Views::Linearizer lin(FileExport);
char* title = new char[100];
sprintf(title, "sln-%d.vtk", as);
lin.save_solution_vtk(sln, title, "Potential", false);
Hermes::Mixins::Loggable::Static::info("Solution in VTK format saved to file %s.", title);
// Output mesh and element orders in VTK format.
Views::Orderizer ord;
sprintf(title, "ord-%d.vtk", as);
ord.save_orders_vtk(space, title);
Hermes::Mixins::Loggable::Static::info("Element orders in VTK format saved to file %s.", title);
}
// View the coarse mesh solution and polynomial orders.
if (HERMES_VISUALIZATION)
{
sview.show(sln);
oview.show(space);
}
// Skip visualization time.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%", space->get_num_dofs(), ref_space->get_num_dofs(), err_est_rel);
// Add entry to DOF and CPU convergence graphs.
cpu_time.tick();
graph_cpu.add_values(cpu_time.accumulated(), err_est_rel);
graph_cpu.save("conv_cpu_est.dat");
graph_dof.add_values(space->get_num_dofs(), err_est_rel);
graph_dof.save("conv_dof_est.dat");
// Skip the time spent to save the convergence graphs.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh.
if (err_est_rel < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
done = adaptivity.adapt(&selector);
// Increase the counter of performed adaptivity steps.
if (done == false)
as++;
}
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Show the fine mesh solution - final result.
sview.set_title("Fine mesh solution");
sview.show_mesh(false);
sview.show(ref_sln);
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/05-battery/definitions.cpp | .cpp | 12,864 | 384 | #include "definitions.h"
template<typename Real, typename Scalar>
Scalar CustomMatrixFormVol::matrix_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = Scalar(0);
double p = 0, q = 0;
// integration order calculation.
if (e->elem_marker == -9999) p = q = 1;
else {
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e1").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e2").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_2;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_2;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e3").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_3;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_3;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e4").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_4;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_4;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e5").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_5;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_5;
}
}
for (int i = 0; i < n; i++)
result += wt[i] * (p * u->dx[i] * v->dx[i] + q * u->dy[i] * v->dy[i]);
return result;
}
double CustomMatrixFormVol::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomMatrixFormVol::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* CustomMatrixFormVol::clone() const
{
return new CustomMatrixFormVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomVectorFormVol::vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
double f = 0;
Scalar result = Scalar(0);
if (e->elem_marker == -9999)
f = 1;
else {
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e1").marker)
f = static_cast<CustomWeakFormPoisson*>(wf)->f_1;
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e2").marker)
f = static_cast<CustomWeakFormPoisson*>(wf)->f_2;
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e3").marker)
f = static_cast<CustomWeakFormPoisson*>(wf)->f_3;
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e4").marker)
f = static_cast<CustomWeakFormPoisson*>(wf)->f_4;
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e5").marker)
f = static_cast<CustomWeakFormPoisson*>(wf)->f_5;
}
double p = 0, q = 0;
// integration order calculation.
if (e->elem_marker == -9999) p = q = 1;
else {
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e1").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e2").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_2;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_2;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e3").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_3;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_3;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e4").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_4;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_4;
}
if (e->elem_marker == mesh->get_element_markers_conversion().get_internal_marker("e5").marker)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_5;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_5;
}
}
for (int i = 0; i < n; i++)
result += wt[i] * (p * u_ext[0]->dx[i] * v->dx[i] + q * u_ext[0]->dy[i] * v->dy[i]);
result = result - f * int_v<Real>(n, wt, v);
return result;
}
double CustomVectorFormVol::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomVectorFormVol::clone() const
{
return new CustomVectorFormVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomMatrixFormSurf::matrix_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *u, Func<Real> *v, GeomSurf<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
{
Real x = e->x[i];
Real y = e->y[i];
double p = 0, q = 0, c = 1.;
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_left)
{
if (x == 0.0)
{
if ((y >= 0.0 && y <= 0.8) || (y >= 23.2 && y <= 24.0))
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
}
if ((y >= 1.6 && y <= 3.6) || (y >= 18.8 && y <= 21.2))
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_2;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_2;
}
if (y >= 3.6 && y <= 18.8)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_3;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_3;
}
if ((y >= 0.8 && y <= 1.6) || (y >= 21.2 && y <= 23.2))
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_5;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_5;
}
}
c = static_cast<CustomWeakFormPoisson*>(wf)->c_left;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_right)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
c = static_cast<CustomWeakFormPoisson*>(wf)->c_right;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_bottom)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
c = static_cast<CustomWeakFormPoisson*>(wf)->c_bottom;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_top)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
c = static_cast<CustomWeakFormPoisson*>(wf)->c_top;
}
result += wt[i] * (//p * u->dx[i] * v->val[i] - q * u->dy[i] * v->val[i]
+c * u->val[i] * v->val[i]);
}
return result;
}
double CustomMatrixFormSurf::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomSurf<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomMatrixFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
return Ord(4.0);
}
MatrixFormSurf<double>* CustomMatrixFormSurf::clone() const
{
return new CustomMatrixFormSurf(*this);
}
template<typename Real, typename Scalar>
Scalar CustomVectorFormSurf::vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomSurf<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = Scalar(0);
double g = 1.0;
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_left)
{
g = static_cast<CustomWeakFormPoisson*>(wf)->g_n_left;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_right)
{
g = static_cast<CustomWeakFormPoisson*>(wf)->g_n_right;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_bottom)
{
g = static_cast<CustomWeakFormPoisson*>(wf)->g_n_bottom;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_top)
{
g = static_cast<CustomWeakFormPoisson*>(wf)->g_n_top;
}
for (int i = 0; i < n; i++)
{
Real x = e->x[i];
Real y = e->y[i];
double p = 0, q = 0, c = 1.;
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_left)
{
if (x == 0.0)
{
if ((y >= 0.0 && y <= 0.8) || (y >= 23.2 && y <= 24.0))
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
}
if ((y >= 1.6 && y <= 3.6) || (y >= 18.8 && y <= 21.2))
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_2;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_2;
}
if (y >= 3.6 && y <= 18.8)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_3;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_3;
}
if ((y >= 0.8 && y <= 1.6) || (y >= 21.2 && y <= 23.2))
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_5;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_5;
}
}
c = static_cast<CustomWeakFormPoisson*>(wf)->c_left;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_right)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
c = static_cast<CustomWeakFormPoisson*>(wf)->c_right;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_bottom)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
c = static_cast<CustomWeakFormPoisson*>(wf)->c_bottom;
}
if (this->areas[0] == static_cast<CustomWeakFormPoisson*>(wf)->bdy_top)
{
p = static_cast<CustomWeakFormPoisson*>(wf)->p_1;
q = static_cast<CustomWeakFormPoisson*>(wf)->q_1;
c = static_cast<CustomWeakFormPoisson*>(wf)->c_top;
}
result += wt[i] * (//p * u_ext[0]->dx[i] * v->val[i] - q * u_ext[0]->dy[i] * v->val[i]
+c * u_ext[0]->val[i] * v->val[i]);
}
result = result - g * int_v<Real>(n, wt, v);
return result;
}
double CustomVectorFormSurf::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomSurf<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomVectorFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
return Ord(4.0);
}
VectorFormSurf<double>* CustomVectorFormSurf::clone() const
{
return new CustomVectorFormSurf(*this);
}
CustomWeakFormPoisson::CustomWeakFormPoisson(std::string omega_1, std::string omega_2,
std::string omega_3, std::string omega_4,
std::string omega_5, std::string bdy_left,
std::string bdy_top, std::string bdy_right,
std::string bdy_bottom, MeshSharedPtr mesh) : WeakForm<double>(1),
omega_1(omega_1), omega_2(omega_2), omega_3(omega_3),
omega_4(omega_4), omega_5(omega_5), mesh(mesh),
p_1(25.0),
p_2(7.0),
p_3(5.0),
p_4(0.2),
p_5(0.05),
q_1(25.0),
q_2(0.8),
q_3(0.0001),
q_4(0.2),
q_5(0.05),
f_1(0.0),
f_2(1.0),
f_3(1.0),
f_4(0.0),
f_5(0.0),
bdy_left(bdy_left),
bdy_top(bdy_top),
bdy_right(bdy_right),
bdy_bottom(bdy_bottom),
c_left(0.0),
c_top(1.0),
c_right(2.0),
c_bottom(3.0),
g_n_left(0.0),
g_n_top(3.0),
g_n_right(2.0),
g_n_bottom(1.0)
{
add_matrix_form(new CustomMatrixFormVol(0, 0, mesh));
add_vector_form(new CustomVectorFormVol(0, mesh));
add_matrix_form_surf(new CustomMatrixFormSurf(0, 0, bdy_bottom));
add_matrix_form_surf(new CustomMatrixFormSurf(0, 0, bdy_right));
add_matrix_form_surf(new CustomMatrixFormSurf(0, 0, bdy_top));
add_vector_form_surf(new CustomVectorFormSurf(0, bdy_bottom));
add_vector_form_surf(new CustomVectorFormSurf(0, bdy_top));
add_vector_form_surf(new CustomVectorFormSurf(0, bdy_left));
add_vector_form_surf(new CustomVectorFormSurf(0, bdy_right));
}
WeakForm<double>* CustomWeakFormPoisson::clone() const
{
return new CustomWeakFormPoisson(this->omega_1, this->omega_2,
this->omega_3, this->omega_4,
this->omega_5, this->bdy_left,
this->bdy_top, this->bdy_right,
this->bdy_bottom, this->mesh);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/08-oscillatory/definitions.h | .h | 2,520 | 92 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
/* Right-hand side */
class CustomRightHandSide : public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide(double alpha)
: Hermes::Hermes2DFunction<double>(), alpha(alpha) {};
virtual double value(double x, double y) const;
virtual Ord value (Ord x, Ord y) const;
double alpha;
};
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double alpha)
: ExactSolutionScalar<double>(mesh), alpha(alpha) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, alpha); }
double alpha;
};
/* Weak forms */
class CustomWeakForm : public WeakForm<double>
{
public:
CustomWeakForm(CustomRightHandSide* f);
public:
class CustomMatrixFormVol : public MatrixFormVol<double>
{
public:
CustomMatrixFormVol(int i, int j, double alpha)
: MatrixFormVol<double>(i, j), alpha(alpha) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
double alpha;
};
class CustomVectorFormVol : public VectorFormVol<double>
{
public:
CustomVectorFormVol(int i, CustomRightHandSide* f)
: VectorFormVol<double>(i), f(f) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
VectorFormVol<double>* clone() const;
CustomRightHandSide* f;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/08-oscillatory/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/08-oscillatory/main.cpp | .cpp | 6,817 | 194 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the eight in the series of NIST benchmarks with known exact solutions. It solves
// the Helmholtz equation and has an oscillatory solution.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// The problem is made harder for adaptive algorithms by decreasing the parameter ALPHA.
//
// PDE: -Laplace u - u/(ALPHA + r(x, y)) + f = 0 where r(x, y) = sqrt(x*x + y*y)
//
// Known exact solution, see functions fn() and fndd().
//
// Domain: unit square (0, 1) x (0, 1), see the file square.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
const double alpha = 1 / (10 * M_PI);
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-2;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square_quad.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, alpha));
// Define right-hand side.
CustomRightHandSide f(alpha);
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&f));
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, exact_sln);
double err_exact_rel = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/08-oscillatory/generate_rhs.py | .py | 307 | 16 | from sympy import var, sqrt, sin, pprint, simplify, ccode
var("x y ALPHA")
def laplace(f):
return f.diff(x, 2) + f.diff(y, 2)
r = sqrt(x**2+y**2)
u = sin(1/(ALPHA+r))
lhs = -laplace(u) - u/(ALPHA+r)**4
print "lhs, as a formula:"
pprint(lhs)
print
print "-"*60
print "lhs, as C code:"
print ccode(lhs)
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/08-oscillatory/definitions.cpp | .cpp | 5,306 | 124 | #include "definitions.h"
double CustomRightHandSide::value(double x, double y) const
{
return (-Hermes::sin(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 4)
+ 2 * Hermes::cos(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / (Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 2)*Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))
+ Hermes::pow(x, 2)*Hermes::sin(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / (Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 4)*(Hermes::pow(x, 2) + Hermes::pow(y, 2)))
+ Hermes::pow(y, 2)*Hermes::sin(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / (Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 4)*(Hermes::pow(x, 2) + Hermes::pow(y, 2)))
- Hermes::pow(x, 2)*Hermes::cos(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / (Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 2)*Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (3.0 / 2.0)))
- Hermes::pow(y, 2)*Hermes::cos(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / (Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 2)*Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (3.0 / 2.0)))
- 2 * Hermes::pow(x, 2)*Hermes::cos(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / (Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 3)*(Hermes::pow(x, 2) + Hermes::pow(y, 2)))
- 2 * Hermes::pow(y, 2)*Hermes::cos(1.0 / (alpha + Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0)))) / (Hermes::pow((alpha
+ Hermes::pow((Hermes::pow(x, 2) + Hermes::pow(y, 2)), (1.0 / 2.0))), 3)*(Hermes::pow(x, 2) + Hermes::pow(y, 2))));
}
Ord CustomRightHandSide::value(Ord x, Ord y) const
{
return Ord(10);
}
double CustomExactSolution::value(double x, double y) const
{
double r = Hermes::sqrt(x*x + y*y);
return Hermes::sin(1 / (alpha + r));
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double r = Hermes::sqrt(x*x + y*y);
double h = 1 / (alpha + r);
dx = -Hermes::cos(h) * h * h * x / r;
dy = -Hermes::cos(h) * h * h * y / r;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(10);
}
CustomWeakForm::CustomWeakForm(CustomRightHandSide* f) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new CustomMatrixFormVol(0, 0, f->alpha));
// Residual.
add_vector_form(new CustomVectorFormVol(0, f));
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomMatrixFormVol::matrix_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
{
Scalar x = e->x[i];
Scalar y = e->y[i];
Scalar r = Hermes::sqrt(x*x + y*y);
Scalar h = 1 / (alpha + r);
Scalar grad_u_grad_v = u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i];
val += wt[i] * (grad_u_grad_v - Hermes::pow(h, 4) * u->val[i] * v->val[i]);
}
return val;
}
double CustomWeakForm::CustomMatrixFormVol::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakForm::CustomMatrixFormVol::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* CustomWeakForm::CustomMatrixFormVol::clone() const
{
return new CustomWeakForm::CustomMatrixFormVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomVectorFormVol::vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
{
Scalar x = e->x[i];
Scalar y = e->y[i];
Scalar r = Hermes::sqrt(x*x + y*y);
Scalar h = 1 / (f->alpha + r);
Scalar grad_u_grad_v = u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i];
val += wt[i] * (grad_u_grad_v - Hermes::pow(h, 4) * u_ext[0]->val[i] * v->val[i]);
val -= wt[i] * f->value(e->x[i], e->y[i]) * v->val[i];
}
return val;
}
double CustomWeakForm::CustomVectorFormVol::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakForm::CustomVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomWeakForm::CustomVectorFormVol::clone() const
{
return new CustomWeakForm::CustomVectorFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/07-boundary-line-singularity/definitions.h | .h | 961 | 41 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
/* Right-hand side */
class CustomRightHandSide : public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide(double alpha)
: Hermes::Hermes2DFunction<double>(), alpha(alpha) {};
virtual double value(double x, double y) const;
virtual Ord value (Ord x, Ord y) const;
double alpha;
};
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double alpha)
: ExactSolutionScalar<double>(mesh), alpha(alpha) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, alpha); }
double alpha;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/07-boundary-line-singularity/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/07-boundary-line-singularity/main.cpp | .cpp | 7,002 | 198 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the seventh in the series of NIST benchmarks with known exact solutions.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: -Laplace u + f = 0.
//
// Known exact solution: pow(x, alpha).
// See functions CustomExactSolution::value and CustomExactSolution::derivatives in "exact_solution.cpp".
//
// Domain: unit square (0, 1) x (0, 1), see the file "square_tri" or "square_quad.mesh".
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// "Alpha" greater than or equal to 1/2 determines the strength of the singularity.
// All of the cited references use "alpha" = 0.6.
double alpha = 0.6;
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1.0;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
// Quadrilaterals.
mloader.load("square_quad.mesh", mesh);
// Triangles.
// mloader.load("square_tri.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, alpha));
// Define right-hand side.
CustomRightHandSide f(alpha);
// Initialize weak formulation.
Hermes1DFunction<double> lambda(1.0);
WeakFormSharedPtr<double> wf(new WeakFormsH1::DefaultWeakFormPoisson<double>(HERMES_ANY, &lambda, &f));
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, exact_sln);
double err_exact_rel = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/07-boundary-line-singularity/definitions.cpp | .cpp | 574 | 27 | #include "definitions.h"
double CustomRightHandSide::value(double x, double y) const
{
return alpha * (alpha - 1.) * Hermes::pow(x, alpha - 2.);
}
Ord CustomRightHandSide::value(Ord x, Ord y) const
{
return Ord((int)(alpha + 3.1));
}
double CustomExactSolution::value(double x, double y) const
{
return Hermes::pow(x, alpha);
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = alpha * Hermes::pow(x, alpha - 1.);
dy = 0;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord((int)(alpha + 1));
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly/definitions.h | .h | 5,601 | 163 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Right-hand side */
class CustomWeakForm : public WeakForm<double>
{
class Jacobian : public MatrixFormVol<double>
{
public:
Jacobian() : MatrixFormVol<double>(0, 0) { this->setSymFlag(HERMES_SYM);};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
virtual MatrixFormVol<double>* clone() const { return new Jacobian(); }
};
class Residual : public VectorFormVol<double>
{
const Hermes::Hermes2DFunction<double>* rhs;
public:
Residual(const Hermes::Hermes2DFunction<double>* rhs) : VectorFormVol<double>(0), rhs(rhs) {};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
virtual VectorFormVol<double>* clone() const { return new Residual(rhs); }
};
public:
CustomWeakForm(const Hermes::Hermes2DFunction<double>* rhs)
{
add_matrix_form(new Jacobian);
add_vector_form(new Residual(rhs));
}
};
class CustomRightHandSide : public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide(double alpha, double x_loc, double y_loc, double r_zero)
: Hermes::Hermes2DFunction<double>(), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero)
{ };
virtual double value(double x, double y) const;
virtual Ord value (Ord x, Ord y) const { return Ord(8); }
double alpha, x_loc, y_loc, r_zero;
};
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double alpha, double x_loc, double y_loc, double r_zero)
: ExactSolutionScalar<double>(mesh), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero)
{ };
virtual double value(double x, double y) const {
return atan(alpha * (sqrt(pow(x - x_loc, 2) + pow(y - y_loc, 2)) - r_zero));
};
virtual void derivatives (double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const { return Ord(Ord::get_max_order()); }
virtual MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, alpha, x_loc, y_loc, r_zero); }
double alpha, x_loc, y_loc, r_zero;
};
/* Bilinear form inducing the energy norm */
class EnergyErrorForm : public Adapt<double>::MatrixFormVolError
{
public:
EnergyErrorForm(WeakForm<double> *problem_wf) : Adapt<double>::MatrixFormVolError(0, 0, HERMES_UNSET_NORM)
{
this->form = problem_wf->get_mfvol()[0];
this->wf = problem_wf;
}
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
return this->form->value(n, wt, u_ext, u, v, e, ext);
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return this->form->ord(n, wt, u_ext, u, v, e, ext);
}
virtual MatrixFormVol<double>* clone() const { return new EnergyErrorForm(this->wf); }
private:
const MatrixFormVol<double>* form;
};
/* Linear form for the residual error estimator */
class ResidualErrorForm : public KellyTypeAdapt<double>::ErrorEstimatorForm
{
public:
ResidualErrorForm(CustomRightHandSide* rhs)
: KellyTypeAdapt<double>::ErrorEstimatorForm(0), rhs(rhs)
{ };
double value(int n, double *wt,
Func<double> *u_ext[], Func<double> *u,
GeomVol<double> *e, Func<double>* *ext) const;
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
private:
CustomRightHandSide* rhs;
};
// Linear form for the interface error estimator.
class InterfaceErrorForm : public KellyTypeAdapt<double>::ErrorEstimatorForm
{
public:
InterfaceErrorForm() : KellyTypeAdapt<double>::ErrorEstimatorForm(0) { this->setAsInterface(); };
template<typename Real, typename Scalar>
Real interface_estimator(int n, double *wt,
Func<Scalar> *u_ext[], Func<Scalar> *u,
GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += wt[i] * Hermes::sqr(e->nx[i] * (u->get_dx_central(i) - u->get_dx_neighbor(i)) +
e->ny[i] * (u->get_dy_central(i) - u->get_dy_neighbor(i)));
return result * e->diam / 24.;
}
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, GeomVol<double> *e,
Func<double>* *ext) const
{
return interface_estimator<double, double>(n, wt, u_ext, u, e, ext);
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return interface_estimator<Ord, Ord>(n, wt, u_ext, u, e, ext);
}
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly/main.cpp | .cpp | 10,457 | 291 |
#include "definitions.h"
// This is the ninth in the series of NIST benchmarks with known exact solutions. This benchmark
// has four different versions, use the global variable PROB_PARAM below to switch among them.
// It differs from 09-wave-front in the mesh adaptation method.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: -Laplace u - f = 0
//
// Known exact solution; atan(ALPHA * (sqrt(pow(x - X_LOC, 2) + pow(y - Y_LOC, 2)) - R_ZERO));
// See the class CustomExactSolution.
//
// Domain: unit square (0, 1) x (0, 1), see the file square.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// PARAM determines which parameter values you wish to use
// for the steepness and location of the wave front.
// #| name | ALPHA | X_LOC | Y_LOC | R_ZERO
// 0: mild 20 -0.05 -0.05 0.7
// 1: steep 1000 -0.05 -0.05 0.7
// 2: asymmetric 1000 1.5 0.25 0.92
// 3: well 50 0.5 0.5 0.25
int PARAM = 3;
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Adaptive strategy:
// STRATEGY = 0 ... refine elements until sqrt(THRESHOLD) times total
// error is processed. If more elements have similar errors, refine
// all to keep the mesh symmetric.
// STRATEGY = 1 ... refine all elements whose error is larger
// than THRESHOLD times maximum element error.
// STRATEGY = 2 ... refine all elements whose error is larger
// than THRESHOLD.
const int STRATEGY = 0;
// Maximum allowed level of hanging nodes:
// MESH_REGULARITY = -1 ... arbitrary level hangning nodes (default),
// MESH_REGULARITY = 1 ... at most one-level hanging nodes,
// MESH_REGULARITY = 2 ... at most two-level hanging nodes, etc.
// Note that regular meshes are not supported, this is due to
// their notoriously bad performance.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity (rel. error tolerance between the
// reference mesh and coarse mesh solution in percent).
const double ERR_STOP = 0.5;
// Adaptivity process stops when the number of degrees of freedom grows
// over this limit. This is to prevent h-adaptivity to go on forever.
const int NDOF_STOP = 60000;
// Matrix solver: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
Hermes::MatrixSolverType matrix_solver = Hermes::SOLVER_UMFPACK;
// Add also the norm of the residual to the error estimate of each element.
const bool USE_RESIDUAL_ESTIMATOR = true;
// Use energy norm for error estimate normalization and measuring of exact error.
const bool USE_ENERGY_NORM_NORMALIZATION = false;
// Test if two possible approaches to interface error estimators accumulation give same results.
const bool TEST_ELEMENT_BASED_KELLY = false;
int main(int argc, char* argv[])
{
// Define problem parameters: (x_loc, y_loc) is the center of the circular wave front, R_ZERO is the distance from the
// wave front to the center of the circle, and alpha gives the steepness of the wave front.
double alpha, x_loc, y_loc, r_zero;
switch(PARAM) {
case 0:
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 1:
alpha = 1000;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 2:
alpha = 1000;
x_loc = 1.5;
y_loc = 0.25;
r_zero = 0.92;
break;
case 3:
alpha = 50;
x_loc = 0.5;
y_loc = 0.5;
r_zero = 0.25;
break;
default:
// The same as 0.
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
}
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
// Quadrilaterals.
mloader.load("square_quad.mesh", mesh);
// Triangles.
// mloader.load("square_tri.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
CustomExactSolution exact(mesh, alpha, x_loc, y_loc, r_zero);
// Define right-hand side.
CustomRightHandSide rhs(alpha, x_loc, y_loc, r_zero);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&rhs));
// Equivalent, but slower:
// DefaultWeakFormPoisson<double> wf(Hermes::HERMES_ANY, HERMES_ONE, &rhs);
// Initialize boundary conditions.
DefaultEssentialBCNonConst<double> bc("Bdy", &exact);
EssentialBCs<double> bcs(&bc);
SpaceSharedPtr<double> space(new // Create an H1 space with default shapeset.
H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
Solution<double> sln;
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof, graph_cpu, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, space.get_num_dofs());
cpu_time.tick();
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, &space);
// Initial coefficient vector for the Newton's method.
int ndof = space.get_num_dofs();
double* coeff_vec = new double[ndof];
memset(coeff_vec, 0, ndof * sizeof(double));
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
try
{
newton.solve(coeff_vec);
}
catch(Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Calculate element errors and total error estimate.
Hermes::Hermes2D::BasicKellyAdapt<double> adaptivity(&space);
adaptivity.set_strategy(stoppingCriterion, THRESHOLD);
if (USE_ENERGY_NORM_NORMALIZATION)
adaptivity.set_error_form(new EnergyErrorForm(wf));
if (USE_RESIDUAL_ESTIMATOR)
adaptivity.add_error_estimator_vol(new ResidualErrorForm(&rhs));
double err_est_rel = adaptivity.calc_err_est(sln) * 100;
double err_exact_rel = Global<double>::calc_rel_error(sln, &exact, HERMES_H1_NORM) * 100;
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
if (TEST_ELEMENT_BASED_KELLY)
{
cpu_time.tick();
// Ensure that the two possible approaches to interface error estimators accumulation give same results.
KellyTypeAdapt<double> adaptivity2(&space, false);
adaptivity2.disable_aposteriori_interface_scaling();
adaptivity2.add_error_estimator_surf(new InterfaceErrorForm);
if (USE_ENERGY_NORM_NORMALIZATION)
adaptivity2.set_error_form(new EnergyErrorForm(wf));
if (USE_RESIDUAL_ESTIMATOR)
{
adaptivity2.add_error_estimator_vol(new ResidualErrorForm(&rhs));
adaptivity2.set_volumetric_scaling_const(1./24.);
}
double err_est_rel2 = adaptivity2.calc_err_est(sln) * 100;
double err_exact_rel2 = adaptivity2.calc_err_exact(sln, &exact, false) * 100;
Hermes::Mixins::Loggable::Static::info("err_est_rel_2: %g%%, err_exact_rel_2: %g%%", err_est_rel2, err_exact_rel2);
if (fabs(err_est_rel2 - err_est_rel) >= 1e-13 || fabs(err_exact_rel2 - err_exact_rel) >= 1e-13)
{
Hermes::Mixins::Loggable::Static::info("err_est_rel diff: %1.15g, err_exact_rel diff: %1.15g",
std::abs(err_est_rel2 - err_est_rel), std::abs(err_exact_rel2 - err_exact_rel));
err_est_rel = err_exact_rel = 0; // Exit the adaptivity loop.
}
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
}
// Report results.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the approximate solution and polynomial orders.
sview.show(sln);
oview.show(&space);
// Add entry to DOF and CPU convergence graphs.
graph_dof.add_values(space.get_num_dofs(), err_est_rel);
graph_dof.save("conv_dof_est.dat");
graph_cpu.add_values(accum_time, err_est_rel);
graph_cpu.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space.get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP || space.get_num_dofs() >= NDOF_STOP)
done = true;
else
done = adaptivity.adapt(THRESHOLD, STRATEGY, MESH_REGULARITY);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of performed adaptivity steps.
if (done == false)
as++;
/* else
{
sview.show(sln);
oview.show(&space);
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
}
*/
// Clean up.
delete [] coeff_vec;
}
while (done == false);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly/definitions.cpp | .cpp | 3,547 | 96 | #include "definitions.h"
double CustomWeakForm::Jacobian::value(int n, double* wt,
Func< double >* u_ext[], Func< double >* u, Func< double >* v,
GeomVol< double >* e, Func< double >** ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
return result;
}
Ord CustomWeakForm::Jacobian::ord(int n, double* wt,
Func< Ord >* u_ext[], Func< Ord >* u, Func< Ord >* v,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
return u->dx[0] * v->dx[0] + u->dy[0] * v->dy[0];
}
double CustomWeakForm::Residual::value(int n, double* wt, Func< double >* u_ext[], Func< double >* v,
GeomVol< double >* e, Func< double >** ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * ( u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i] + rhs->value(e->x[i], e->y[i]) * v->val[i] );
return result;
}
Ord CustomWeakForm::Residual::ord(int n, double* wt, Func< Ord >* u_ext[], Func< Ord >* v,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
return u_ext[0]->dx[0] * v->dx[0] + u_ext[0]->dy[0] * v->dy[0] + rhs->value(e->x[0], e->y[0]) * v->val[0];
}
double CustomRightHandSide::value(double x, double y) const
{
double a = pow(x - x_loc, 2);
double b = pow(y - y_loc, 2);
double c = sqrt(a + b);
double d = ((alpha*x - (alpha * x_loc)) * (2*x - (2 * x_loc)));
double e = ((alpha*y - (alpha * y_loc)) * (2*y - (2 * y_loc)));
double f = (pow(alpha*c - (alpha * r_zero), 2) + 1.0);
double g = (alpha * c - (alpha * r_zero));
return +( ((alpha/(c * f)) - (d/(2 * pow(a + b, 1.5) * f))
- ((alpha * d * g)/((a + b) * pow(f, 2))) + (alpha/(c * f))
- (e/(2 * pow(a + b, 1.5) * f))
- ((alpha * e * g)/((a + b) * pow(f, 2)))));
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double a = pow(x - x_loc, 2);
double b = pow(y - y_loc, 2);
double c = sqrt(a + b);
double d = (alpha*x - (alpha * x_loc));
double e = (alpha*y - (alpha * y_loc));
double f = (pow(alpha*c - (alpha * r_zero), 2) + 1.0);
dx = (d/(c * f));
dy = (e/(c * f));
}
double ResidualErrorForm::value(int n, double* wt,
Func< double >* u_ext[], Func< double >* u,
GeomVol< double >* e, Func< double >** ext) const
{
#ifdef H2D_SECOND_DERIVATIVES_ENABLED
double result = 0.;
for (int i = 0; i < n; i++)
result += wt[i] * Hermes::sqr( -rhs->value(e->x[i], e->y[i]) + u->laplace[i] );
return result * Hermes::sqr(e->diam);
#else
throw Hermes::Exceptions::Exception("Define H2D_SECOND_DERIVATIVES_ENABLED in hermes2d_common_defs.h"
"if you want to use second derivatives in weak forms.");
#endif
}
Ord ResidualErrorForm::ord(int n, double* wt,
Func< Ord >* u_ext[], Func< Ord >* u,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
#ifdef H2D_SECOND_DERIVATIVES_ENABLED
return sqr( -rhs->value(e->x[0], e->y[0]) + u->laplace[0] );
#else
throw Hermes::Exceptions::Exception("Define H2D_SECOND_DERIVATIVES_ENABLED in hermes2d_common_defs.h"
"if you want to use second derivatives in weak forms.");
#endif
}
| C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/01-analytic-solution/definitions.h | .h | 986 | 40 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
/* Right-hand side */
class CustomRightHandSide : public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide(double poly_deg)
: Hermes::Hermes2DFunction<double>(), poly_deg(poly_deg) {};
virtual double value(double x, double y) const;
virtual Ord value (Ord x, Ord y) const;
double poly_deg;
};
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double poly_deg)
: ExactSolutionScalar<double>(mesh), poly_deg(poly_deg) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, poly_deg); }
double poly_deg;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/01-analytic-solution/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/01-analytic-solution/main.cpp | .cpp | 6,977 | 198 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the first in the series of NIST benchmarks with known exact solutions.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: -Laplace u - f = 0.
//
// Known exact solution; pow(2, 4*p) * pow(x, p) * pow(1-x, p) * pow(y, p) * pow(1-y, p).
// See functions fn() and fndd() in "exact_solution.cpp".
//
// Domain: unit square (0, 1)x(0, 1), see the file square.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// The exact solution is a polynomial of degree 2*EXACT_SOL_P in the x-direction
// as well as in the y-direction.
double EXACT_SOL_P = 10;
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1.0;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
// Quadrilaterals.
mloader.load("square_quad.mesh", mesh);
// Triangles.
// mloader.load("square_tri.mesh", mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, EXACT_SOL_P));
// Define right-hand side.
CustomRightHandSide f(EXACT_SOL_P);
// Initialize weak formulation.
Hermes1DFunction<double> lambda(1.0);
WeakFormSharedPtr<double> wf(new WeakFormsH1::DefaultWeakFormPoisson<double>(HERMES_ANY, &lambda, &f));
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, exact_sln);
double err_exact_rel = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/01-analytic-solution/definitions.cpp | .cpp | 1,445 | 44 | #include "definitions.h"
double CustomRightHandSide::value(double x, double y) const
{
double a = Hermes::pow(2.0, 4.0*poly_deg);
double b = Hermes::pow(x - 1.0, 8.0);
double c = (38.0*Hermes::pow(x, 2.0) - 38.0*x + 9.0);
double d = Hermes::pow(y - 1.0, poly_deg);
double e = Hermes::pow(y - 1.0, 8.0);
double f = (38.0*Hermes::pow(y, 2.0) - 38.0*y + 9.0);
double g = Hermes::pow(x - 1.0, poly_deg);
return (poly_deg*a*Hermes::pow(x, 8.0)*b*c*Hermes::pow(y, poly_deg)*d
+ poly_deg*a*Hermes::pow(y, 8.0)*e*f*Hermes::pow(x, poly_deg)*g);
}
Ord CustomRightHandSide::value(Ord x, Ord y) const
{
return Ord(8);
}
double CustomExactSolution::value(double x, double y) const
{
return Hermes::pow(2, 4 * poly_deg) * Hermes::pow(x, poly_deg) * Hermes::pow(1 - x, poly_deg)
* Hermes::pow(y, poly_deg) * Hermes::pow(1 - y, poly_deg);
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double A = Hermes::pow((1.0 - y), poly_deg);
double B = Hermes::pow((1.0 - x), poly_deg);
double C = Hermes::pow(y, poly_deg);
double D = Hermes::pow(x, poly_deg);
dx = ((poly_deg * Hermes::pow(16.0, poly_deg)*A*C) / (x - 1.0)
+ (poly_deg*Hermes::pow(16.0, poly_deg)*A*C) / x)*B*D;
dy = ((poly_deg*Hermes::pow(16.0, poly_deg)*B*D) / (y - 1.0)
+ (poly_deg*Hermes::pow(16.0, poly_deg)*B*D) / y)*A*C;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(8);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/06-boundary-layer/definitions.h | .h | 2,550 | 92 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
/* Right-hand side */
class CustomRightHandSide : public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide(double epsilon)
: Hermes::Hermes2DFunction<double>(), epsilon(epsilon) {};
virtual double value(double x, double y) const;
virtual Ord value (Ord x, Ord y) const;
double epsilon;
};
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double epsilon)
: ExactSolutionScalar<double>(mesh), epsilon(epsilon) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, epsilon); }
double epsilon;
};
/* Weak forms */
class CustomWeakForm : public WeakForm<double>
{
public:
CustomWeakForm(CustomRightHandSide* f);
public:
class CustomMatrixFormVol : public MatrixFormVol<double>
{
public:
CustomMatrixFormVol(int i, int j, double epsilon)
: MatrixFormVol<double>(i, j), epsilon(epsilon) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
double epsilon;
};
class CustomVectorFormVol : public VectorFormVol<double>
{
public:
CustomVectorFormVol(int i, CustomRightHandSide* f)
: VectorFormVol<double>(i), f(f) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
VectorFormVol<double>* clone() const;
CustomRightHandSide* f;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/06-boundary-layer/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/06-boundary-layer/main.cpp | .cpp | 6,841 | 195 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the sixth in the series of NIST benchmarks with known exact solutions. It solves
// a problem with boundary layer.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// The problem is made harder for adaptive algorithms by decreasing the (positive) parameter EPSILON.
//
// PDE: -EPSILON Laplace u + 2du/dx + du/dy - f = 0
//
// Known exact solution, see the class CustomExactSolution.
//
// Domain: square (-1, 1) x (-1, 1), see the file square.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
const double epsilon = 1e-1;
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-2;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square_quad.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, ::epsilon));
// Define right-hand side.
CustomRightHandSide f(::epsilon);
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&f));
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, exact_sln);
double err_exact_rel = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.set_linearizer_criterion(LinearizerCriterionFixed(3));
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/06-boundary-layer/generate_rhs.py | .py | 651 | 25 | from sympy import var, sqrt, sin, exp, cos, pprint, pi, simplify, ccode
var("x y EPSILON")
def laplace(f):
return f.diff(x, 2) + f.diff(y, 2)
# exact solution (given)
u = (1 - exp(-(1-x)/EPSILON)) * (1 - exp(-(1-y)/EPSILON)) * cos(pi * (x + y))
# right-hand-side (to be calculated)
rhs = -EPSILON * laplace(u) + 2*u.diff(x, 1) + u.diff(y, 1)
print "rhs, as a formula:"
pprint(rhs)
print
print "-"*60
print "rhs, as C code:"
print ccode(rhs)
# x-derivative of u (to be calculated)
dudx = u.diff(x, 1)
print "dudx, as C code:"
print ccode(dudx)
# y-derivative of u (to be calculated)
dudy = u.diff(y, 1)
print "dudy, as C code:"
print ccode(dudy)
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/06-boundary-layer/definitions.cpp | .cpp | 4,079 | 107 | #include "definitions.h"
double CustomRightHandSide::value(double x, double y) const
{
return -epsilon*(-2 * Hermes::pow(M_PI, 2)*(1 - exp(-(1 - x) / epsilon))*(1 - exp(-(1 - y) / epsilon))*Hermes::cos(M_PI*(x + y))
+ 2 * M_PI*(1 - exp(-(1 - x) / epsilon))*exp(-(1 - y) / epsilon)*Hermes::sin(M_PI*(x + y)) / epsilon
+ 2 * M_PI*(1 - exp(-(1 - y) / epsilon))*exp(-(1 - x) / epsilon)*Hermes::sin(M_PI*(x + y)) / epsilon
- (1 - exp(-(1 - y) / epsilon))*Hermes::cos(M_PI*(x + y))*exp(-(1 - x) / epsilon) / Hermes::pow(epsilon, 2)
- (1 - exp(-(1 - x) / epsilon))*Hermes::cos(M_PI*(x + y))*exp(-(1 - y) / epsilon) / Hermes::pow(epsilon, 2))
- 3 * M_PI*(1 - exp(-(1 - x) / epsilon))*(1 - exp(-(1 - y) / epsilon))*Hermes::sin(M_PI*(x + y))
- 2 * (1 - exp(-(1 - y) / epsilon))*Hermes::cos(M_PI*(x + y))*exp(-(1 - x) / epsilon) / epsilon
- (1 - exp(-(1 - x) / epsilon))*Hermes::cos(M_PI*(x + y))*exp(-(1 - y) / epsilon) / epsilon;
}
Ord CustomRightHandSide::value(Ord x, Ord y) const
{
return Ord(8);
}
double CustomExactSolution::value(double x, double y) const
{
return (1 - exp(-(1 - x) / epsilon)) * (1 - exp(-(1 - y) / epsilon)) * Hermes::cos(M_PI * (x + y));
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
dx = -M_PI*(1 - exp(-(1 - x) / epsilon))*(1 - exp(-(1 - y) / epsilon))*Hermes::sin(M_PI*(x + y))
- (1 - exp(-(1 - y) / epsilon))*Hermes::cos(M_PI*(x + y))*exp(-(1 - x) / epsilon) / epsilon;
dy = -M_PI*(1 - exp(-(1 - x) / epsilon))*(1 - exp(-(1 - y) / epsilon))*Hermes::sin(M_PI*(x + y))
- (1 - exp(-(1 - x) / epsilon))*Hermes::cos(M_PI*(x + y))*exp(-(1 - y) / epsilon) / epsilon;
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(8);
}
CustomWeakForm::CustomWeakForm(CustomRightHandSide* f) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new CustomMatrixFormVol(0, 0, f->epsilon));
// Residual.
add_vector_form(new CustomVectorFormVol(0, f));
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomMatrixFormVol::matrix_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
{
val += wt[i] * epsilon * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
val += wt[i] * (2 * u->dx[i] + u->dy[i]) * v->val[i];
}
return val;
}
double CustomWeakForm::CustomMatrixFormVol::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakForm::CustomMatrixFormVol::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* CustomWeakForm::CustomMatrixFormVol::clone() const
{
return new CustomWeakForm::CustomMatrixFormVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomVectorFormVol::vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
{
val += wt[i] * f->epsilon * (u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i]);
val += wt[i] * (2 * u_ext[0]->dx[i] + u_ext[0]->dy[i]) * v->val[i];
val -= wt[i] * f->value(e->x[i], e->y[i]) * v->val[i];
}
return val;
}
double CustomWeakForm::CustomVectorFormVol::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakForm::CustomVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomWeakForm::CustomVectorFormVol::clone() const
{
return new CustomWeakForm::CustomVectorFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front/definitions.h | .h | 2,843 | 80 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Alternatively, DefaultWeakFormDiffusion may be used. This is just copied from the Kelly version of this benchmark
for one-to-one comparison.
*/
class CustomWeakForm : public WeakForm<double>
{
class Jacobian : public MatrixFormVol<double>
{
public:
Jacobian() : MatrixFormVol<double>(0, 0) { this->setSymFlag(HERMES_SYM); };
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Hermes::Ord ord(int n, double *wt, Func<Hermes::Ord> *u_ext[], Func<Hermes::Ord> *u, Func<Hermes::Ord> *v,
GeomVol<Hermes::Ord> *e, Func<Hermes::Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
};
class Residual : public VectorFormVol<double>
{
const Hermes::Hermes2DFunction<double>* rhs;
public:
Residual(const Hermes::Hermes2DFunction<double>* rhs) : VectorFormVol<double>(0), rhs(rhs) {};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Hermes::Ord ord(int n, double *wt, Func<Hermes::Ord> *u_ext[], Func<Hermes::Ord> *v,
GeomVol<Hermes::Ord> *e, Func<Hermes::Ord>* *ext) const;
VectorFormVol<double>* clone() const;
};
public:
CustomWeakForm(const Hermes::Hermes2DFunction<double>* rhs)
{
add_matrix_form(new Jacobian);
add_vector_form(new Residual(rhs));
}
};
class CustomRightHandSide : public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide(double alpha, double x_loc, double y_loc, double r_zero)
: Hermes::Hermes2DFunction<double>(), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero)
{ };
virtual double value(double x, double y) const;
virtual Ord value (Ord x, Ord y) const { return Ord(8); }
double alpha, x_loc, y_loc, r_zero;
};
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double alpha, double x_loc, double y_loc, double r_zero)
: ExactSolutionScalar<double>(mesh), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero)
{ };
virtual double value(double x, double y) const {
return atan(alpha * (sqrt(pow(x - x_loc, 2) + pow(y - y_loc, 2)) - r_zero));
};
virtual void derivatives (double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const { return Ord(Ord::get_max_order()); }
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, alpha, x_loc, y_loc, r_zero); }
double alpha, x_loc, y_loc, r_zero;
}; | Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front/main.cpp | .cpp | 8,151 | 243 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the ninth in the series of NIST benchmarks with known exact solutions. This benchmark
// has four different versions, use the global variable "PARAM" (below) to switch among them.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: -Laplace u + f = 0
//
// Known exact solution: atan(alpha * (sqrt(pow(x - x_loc, 2) + pow(y - y_loc, 2)) - r_zero))
// See the class CustomExactSolution::value in "definitions.cpp"
//
// Domain: unit square (0, 1) x (0, 1), see the file square_quad.mesh or square_tri.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// PARAM determines which parameter values you wish to use
// for the steepness and location of the wave front.
// | name | alpha | x_loc | y_loc | r_zero
// 0: mild 20 -0.05 -0.05 0.7
// 1: steep 1000 -0.05 -0.05 0.7
// 2: asymmetric 1000 1.5 0.25 0.92
// 3: well 50 0.5 0.5 0.25
int PARAM = 3;
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1.0;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Define problem parameters: (x_loc, y_loc) is the center of the circular wave front, R_ZERO is the distance from the
// wave front to the center of the circle, and alpha gives the steepness of the wave front.
double alpha, x_loc, y_loc, r_zero;
switch (PARAM)
{
case 0:
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 1:
alpha = 1000;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 2:
alpha = 1000;
x_loc = 1.5;
y_loc = 0.25;
r_zero = 0.92;
break;
case 3:
alpha = 50;
x_loc = 0.5;
y_loc = 0.5;
r_zero = 0.25;
break;
default:
// The same as 0.
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
}
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
// Quadrilaterals.
mloader.load("square_quad.mesh", mesh);
// Triangles.
// mloader.load("square_tri.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, alpha, x_loc, y_loc, r_zero));
// Define right-hand side.
CustomRightHandSide rhs(alpha, x_loc, y_loc, r_zero);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&rhs));
// Equivalent, but slower:
// WeakFormsH1::DefaultWeakFormPoisson wf(HERMES_ANY, nullptr, &rhs);
// Initialize boundary conditions.
DefaultEssentialBCNonConst<double> bc("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, exact_sln);
double err_exact_rel = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front/definitions.cpp | .cpp | 2,422 | 74 | #include "definitions.h"
double CustomWeakForm::Jacobian::value(int n, double* wt,
Func<double>* u_ext[], Func<double>* u, Func<double>* v,
GeomVol<double>* e, Func<double>** ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
return result;
}
Ord CustomWeakForm::Jacobian::ord(int n, double* wt,
Func< Ord >* u_ext[], Func< Ord >* u, Func< Ord >* v,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
return u->dx[0] * v->dx[0] + u->dy[0] * v->dy[0];
}
MatrixFormVol<double>* CustomWeakForm::Jacobian::clone() const
{
return new CustomWeakForm::Jacobian(*this);
}
double CustomWeakForm::Residual::value(int n, double* wt, Func<double>* u_ext[], Func<double>* v,
GeomVol<double>* e, Func<double>** ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i] + rhs->value(e->x[i], e->y[i]) * v->val[i]);
return result;
}
Ord CustomWeakForm::Residual::ord(int n, double* wt, Func< Ord >* u_ext[], Func< Ord >* v,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
return u_ext[0]->dx[0] * v->dx[0] + u_ext[0]->dy[0] * v->dy[0] + rhs->value(e->x[0], e->y[0]) * v->val[0];
}
VectorFormVol<double>* CustomWeakForm::Residual::clone() const
{
return new CustomWeakForm::Residual(*this);
}
double CustomRightHandSide::value(double x, double y) const
{
double a = pow(x - x_loc, 2);
double b = pow(y - y_loc, 2);
double c = sqrt(a + b);
double d = ((alpha*x - (alpha * x_loc)) * (2 * x - (2 * x_loc)));
double e = ((alpha*y - (alpha * y_loc)) * (2 * y - (2 * y_loc)));
double f = (pow(alpha*c - (alpha * r_zero), 2) + 1.0);
double g = (alpha * c - (alpha * r_zero));
return +(((alpha / (c * f)) - (d / (2 * pow(a + b, 1.5) * f))
- ((alpha * d * g) / ((a + b) * pow(f, 2))) + (alpha / (c * f))
- (e / (2 * pow(a + b, 1.5) * f))
- ((alpha * e * g) / ((a + b) * pow(f, 2)))));
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double a = pow(x - x_loc, 2);
double b = pow(y - y_loc, 2);
double c = sqrt(a + b);
double d = (alpha*x - (alpha * x_loc));
double e = (alpha*y - (alpha * y_loc));
double f = (pow(alpha*c - (alpha * r_zero), 2) + 1.0);
dx = (d / (c * f));
dy = (e / (c * f));
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/03-linear-elasticity/definitions.h | .h | 8,205 | 286 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
/* Exact solution */
class CustomExactSolutionU : public ExactSolutionScalar<double>
{
public:
CustomExactSolutionU(MeshSharedPtr mesh, double E, double nu, double lambda, double Q)
: ExactSolutionScalar<double>(mesh), E(E), nu(nu), lambda(lambda), Q(Q) {};
double get_angle(double y, double x) const;
double d_theta_dx(double x, double y) const;
double d_theta_dxd_theta_dx(double x, double y) const;
double d_theta_dy(double x, double y) const;
double d_theta_dyd_theta_dy(double x, double y) const;
double d_theta_dxd_theta_dy(double x, double y) const;
double r(double x, double y) const;
double drdx(double x, double y) const;
double drdxdrdx(double x, double y) const;
double drdy(double x, double y) const;
double drdydrdy(double x, double y) const;
double drdxdrdy(double x, double y) const;
double u_r(double x, double y) const;
double du_rdx(double x, double y) const;
double du_rdxdu_rdx(double x, double y) const;
double du_rdy(double x, double y) const;
double du_rdydu_rdy(double x, double y) const;
double du_rdxdu_rdy(double x, double y) const;
double v_r(double x, double y) const;
double dv_rdx(double x, double y) const;
double dv_rdxdv_rdx(double x, double y) const;
double dv_rdy(double x, double y) const;
double dv_rdydv_rdy(double x, double y) const;
double dv_rdxdv_rdy(double x, double y) const;
// \partial^2 u / \partial x^2
double dudxdudx(double x, double y) const;
double dudydudy(double x, double y) const;
double dudxdudy(double x, double y) const;
// \partial^2 v / \partial x^2
double dvdxdvdx(double x, double y) const;
double dvdydvdy(double x, double y) const;
double dvdxdvdy(double x, double y) const;
// Exact solution u(x,y) and its derivatives.
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual MeshFunction<double>* clone() const;
virtual Ord ord (double x, double y) const;
double E, nu, lambda, Q;
};
class CustomExactSolutionV : public ExactSolutionScalar<double>
{
public:
CustomExactSolutionV(MeshSharedPtr mesh, double E, double nu, double lambda, double Q)
: ExactSolutionScalar<double>(mesh), E(E), nu(nu), lambda(lambda), Q(Q) {};
double get_angle(double y, double x) const;
double d_theta_dx(double x, double y) const;
double d_theta_dxd_theta_dx(double x, double y) const;
double d_theta_dy(double x, double y) const;
double d_theta_dyd_theta_dy(double x, double y) const;
double d_theta_dxd_theta_dy(double x, double y) const;
double r(double x, double y) const;
double drdx(double x, double y) const;
double drdxdrdx(double x, double y) const;
double drdy(double x, double y) const;
double drdydrdy(double x, double y) const;
double drdxdrdy(double x, double y) const;
double u_r(double x, double y) const;
double du_rdx(double x, double y) const;
double du_rdxdu_rdx(double x, double y) const;
double du_rdy(double x, double y) const;
double du_rdydu_rdy(double x, double y) const;
double du_rdxdu_rdy(double x, double y) const;
double v_r(double x, double y) const;
double dv_rdx(double x, double y) const;
double dv_rdxdv_rdx(double x, double y) const;
double dv_rdy(double x, double y) const;
double dv_rdydv_rdy(double x, double y) const;
double dv_rdxdv_rdy(double x, double y) const;
// \partial^2 u / \partial x^2
double dudxdudx(double x, double y) const;
double dudydudy(double x, double y) const;
double dudxdudy(double x, double y) const;
// \partial^2 v / \partial x^2
double dvdxdvdx(double x, double y) const;
double dvdydvdy(double x, double y) const;
double dvdxdvdy(double x, double y) const;
// Exact solution u(x,y) and its derivatives.
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual MeshFunction<double>* clone() const;
virtual Ord ord (double x, double y) const;
double E, nu, lambda, Q;
};
/* Weak forms */
class CustomWeakFormElasticityNIST : public WeakForm<double>
{
public:
CustomWeakFormElasticityNIST(double E, double nu, double mu, double lambda);
public:
class CustomMatrixFormVolElasticityNIST_0_0 : public MatrixFormVol<double>
{
public:
CustomMatrixFormVolElasticityNIST_0_0(int i, int j, double E, double nu)
: MatrixFormVol<double>(i, j), E(E), nu(nu) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
double E, nu;
};
class CustomMatrixFormVolElasticityNIST_0_1 : public MatrixFormVol<double>
{
public:
CustomMatrixFormVolElasticityNIST_0_1(int i, int j, double E, double nu)
: MatrixFormVol<double>(i, j), E(E), nu(nu) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
double E, nu;
};
class CustomMatrixFormVolElasticityNIST_1_1 : public MatrixFormVol<double>
{
public:
CustomMatrixFormVolElasticityNIST_1_1(int i, int j, double E, double nu)
: MatrixFormVol<double>(i, j), E(E), nu(nu) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
double E, nu;
};
class CustomVectorFormVolElasticityNIST_0 : public VectorFormVol<double>
{
public:
CustomVectorFormVolElasticityNIST_0(int i, double E, double nu)
: VectorFormVol<double>(i), E(E), nu(nu) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
VectorFormVol<double>* clone() const;
double E, nu;
};
class CustomVectorFormVolElasticityNIST_1 : public VectorFormVol<double>
{
public:
CustomVectorFormVolElasticityNIST_1(int i, double E, double nu)
: VectorFormVol<double>(i), E(E), nu(nu) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
VectorFormVol<double>* clone() const;
double E, nu;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/03-linear-elasticity/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/03-linear-elasticity/main.cpp | .cpp | 10,194 | 264 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the third in the series of NIST benchmarks with known exact solutions.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: Linear elasticity coupled system of two equations given below
//
// -E \frac{1-nu^2}{1-2*nu} \frac{\partial^{2} u}{\partial x^{2}} - E\frac{1-nu^2}{2-2*nu} \frac{\partial^{2} u}{\partial y^{2}}
// -E \frac{1-nu^2}{(1-2*nu)(2-2*nu)} \frac{\partial^{2} v}{\partial x \partial y} - F_{x} = 0
//
// -E \frac{1-nu^2}{2-2*nu} \frac{\partial^{2} v}{\partial x^{2}} - E\frac{1-nu^2}{1-2*nu} \frac{\partial^{2} v}{\partial y^{2}}
// -E \frac{1-nu^2}{(1-2*nu)(2-2*nu)} \frac{\partial^{2} u}{\partial x \partial y} - F_{y} = 0
//
// where F_{x} = F_{y} = 0.
//
// Known exact solution for mode 1:
// u(x, y) = \frac{1}{2G} r^{\lambda}[(k - Q(\lambda + 1))cos(\lambda \theta) - \lambda cos((\lambda - 2) \theta)]
// v(x, y) = \frac{1}{2G} r^{\lambda}[(k + Q(\lambda + 1))sin(\lambda \theta) + \lambda sin((\lambda - 2) \theta)]
// here \lambda = 0.5444837367825, Q = 0.5430755788367.
//
// Known exact solution for mode 2:
// u(x, y) = \frac{1}{2G} r^{\lambda}[(k - Q(\lambda + 1))sin(\lambda \theta) - \lambda sin((\lambda - 2) \theta)]
// v(x, y) = -\frac{1}{2G} r^{\lambda}[(k + Q(\lambda + 1))cos(\lambda \theta) + \lambda cos((\lambda - 2) \theta)]
// here \lambda = 0.9085291898461, Q = -0.2189232362488.
//
// Domain: square (-1, 1)^2, with a slit from (0, 0) to (1, 0).
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// If this is defined, mode-1 solution is calculated, otherwise
// mode-2 solution. See Mitchell's paper for details.
#define MODE_1
// Initial polynomial degree for u.
const int P_INIT_U = 2;
// Initial polynomial degree for v.
const int P_INIT_V = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.6;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1.0;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
// Problem parameters.
// Young modulus.
const double E = 1.0;
// Poisson ratio.
const double nu = 0.3;
#ifdef MODE_1
// lambda for mode-1 solution.
const double lambda = 0.5444837367825;
// mu for mode-1 solution (mu is the same as G)
const double mu = E / (2 * (1 + nu));
// Q for mode-1 solution.
const double Q = 0.5430755788367;
#else
// lambda for mode-2 solution.
const double lambda = 0.9085291898461;
// mu for mode-2 solution (mu is the same as G).
const double mu = E / (2 * (1 + nu));
// Q for mode-2 solution.
const double Q = -0.2189232362488;
#endif
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr u_mesh(new Mesh), v_mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("elasticity.mesh", u_mesh);
// Create initial mesh (master mesh).
v_mesh->copy(u_mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) {
u_mesh->refine_all_elements();
v_mesh->refine_all_elements();
}
// Set exact solution for each displacement component.
MeshFunctionSharedPtr<double> exact_u(new CustomExactSolutionU(u_mesh, E, nu, lambda, Q));
MeshFunctionSharedPtr<double> exact_v(new CustomExactSolutionV(v_mesh, E, nu, lambda, Q));
// Initialize the weak formulation.
// NOTE: We pass all four parameters (temporarily)
// since in Mitchell's paper (NIST benchmarks) they
// are mutually inconsistent.
WeakFormSharedPtr<double> wf(new CustomWeakFormElasticityNIST(E, nu, mu, lambda));
// Initialize boundary conditions.
DefaultEssentialBCNonConst<double> bc_u("Bdy", exact_u);
EssentialBCs<double> bcs_u(&bc_u);
DefaultEssentialBCNonConst<double> bc_v("Bdy", exact_v);
EssentialBCs<double> bcs_v(&bc_v);
// Create H1 spaces with default shapeset for both displacement components.
SpaceSharedPtr<double> u_space(new H1Space<double>(u_mesh, &bcs_u, P_INIT_U));
SpaceSharedPtr<double> v_space(new H1Space<double>(v_mesh, &bcs_v, P_INIT_V));
std::vector<SpaceSharedPtr<double> >spaces({ u_space, v_space });
// Initialize approximate solution.
MeshFunctionSharedPtr<double> u_sln(new Solution<double>());
MeshFunctionSharedPtr<double> u_ref_sln(new Solution<double>());
MeshFunctionSharedPtr<double> v_sln(new Solution<double>());
MeshFunctionSharedPtr<double> v_ref_sln(new Solution<double>());
std::vector<MeshFunctionSharedPtr<double> >slns({ u_sln, v_sln });
std::vector<MeshFunctionSharedPtr<double> >ref_slns({ u_ref_sln, v_ref_sln });
std::vector<MeshFunctionSharedPtr<double> >exact_slns({ exact_u, exact_v });
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView s_view_u("Solution for u", new WinGeom(0, 0, 440, 350));
s_view_u.show_mesh(false);
Views::OrderView o_view_u("Mesh for u", new WinGeom(450, 0, 420, 350));
Views::ScalarView s_view_v("Solution for v", new WinGeom(0, 405, 440, 350));
s_view_v.show_mesh(false);
Views::OrderView o_view_v("Mesh for v", new WinGeom(450, 405, 420, 350));
Views::ScalarView mises_view("Von Mises stress [Pa]", new WinGeom(880, 0, 440, 350));
mises_view.fix_scale_width(50);
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreatorU(u_mesh);
MeshSharedPtr ref_u_mesh = refMeshCreatorU.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorU(u_space, ref_u_mesh);
SpaceSharedPtr<double> ref_u_space = refSpaceCreatorU.create_ref_space();
Mesh::ReferenceMeshCreator refMeshCreatorV(u_mesh);
MeshSharedPtr ref_v_mesh = refMeshCreatorV.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorV(v_space, ref_v_mesh);
SpaceSharedPtr<double> ref_v_space = refSpaceCreatorV.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_u_space, ref_v_space });
int ndof_ref = Space<double>::get_num_dofs(ref_spaces);
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_spaces);
NewtonSolver<double> newton(&dp);
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), ref_spaces, ref_slns);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(spaces, ref_slns, slns);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 2);
error_calculator.calculate_errors(slns, exact_slns);
double err_exact_rel_total = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(slns, ref_slns);
double err_est_rel_total = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(spaces, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
s_view_u.show(u_sln);
o_view_u.show(u_space);
s_view_v.show(v_sln);
o_view_v.show(v_space);
MeshFunctionSharedPtr<double> stress(new VonMisesFilter({ u_sln, v_sln }, lambda, mu));
mises_view.show(stress, H2D_FN_VAL_0, u_sln, v_sln, 0.03);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(Space<double>::get_num_dofs({ u_space, v_space }), err_est_rel_total);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(cpu_time.accumulated(), err_est_rel_total);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(Space<double>::get_num_dofs({ u_space, v_space }), err_exact_rel_total);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel_total);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh.
if (err_est_rel_total < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
done = adaptivity.adapt({ &selector, &selector });
}
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/03-linear-elasticity/definitions.cpp | .cpp | 23,161 | 595 | #include "definitions.h"
double E = 1.0;
double nu = 0.3;
// lambda for mode-1 solution.
double lambda = 0.5444837367825;
// mu for mode-1 solution (mu is the same as G)
double mu = E / (2.0 * (1.0 + nu));
// Q for mode-1 solution.
double Q = 0.5430755788367;
double k = 3.0 - 4.0 * nu;
double A = -E * (1 - nu * nu) / (1 - 2 * nu);
double B = -E * (1 - nu * nu) / (2 - 2 * nu);
double C = -E * (1 - nu * nu) / ((1 - 2 * nu) * (2 - 2 * nu));
double D = 1.0 / (2 * mu);
double u_F = (k - Q * (lambda + 1));
double v_F = (k + Q * (lambda + 1));
double CustomExactSolutionU::get_angle(double y, double x) const
{
double theta = Hermes::atan2(y, x);
if (theta < 0)
theta += 2 * M_PI;
return theta;
}
double CustomExactSolutionU::d_theta_dx(double x, double y) const
{
return -y / (x*x + y*y);
}
double CustomExactSolutionU::d_theta_dxd_theta_dx(double x, double y) const
{
return 2 * x*y / ((x*x + y*y)*(x*x + y*y));
}
double CustomExactSolutionU::d_theta_dy(double x, double y) const
{
return x / (x*x + y*y);
}
double CustomExactSolutionU::d_theta_dyd_theta_dy(double x, double y) const
{
return -2 * x*y / ((x*x + y*y)*(x*x + y*y));
}
double CustomExactSolutionU::d_theta_dxd_theta_dy(double x, double y) const
{
return (y*y - x*x) / ((x*x + y*y)*(x*x + y*y));
}
double CustomExactSolutionU::r(double x, double y) const
{
return Hermes::pow((x*x + y*y), (lambda / 2.0)); // r^labbda
}
double CustomExactSolutionU::drdx(double x, double y) const
{
return lambda * x * Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0));
}
double CustomExactSolutionU::drdxdrdx(double x, double y) const
{
return lambda * (Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0)) + (lambda - 2.0)
* x * x * Hermes::pow((x*x + y*y), (lambda / 2.0 - 2.0)));
}
double CustomExactSolutionU::drdy(double x, double y) const
{
return lambda * y * Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0));
}
double CustomExactSolutionU::drdydrdy(double x, double y) const
{
return lambda * (Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0)) + (lambda - 2.0)
* y * y * Hermes::pow((x*x + y*y), (lambda / 2.0 - 2.0)));
}
double CustomExactSolutionU::drdxdrdy(double x, double y) const
{
return lambda * 2.0 * x * y * (lambda / 2.0 - 1) * Hermes::pow((x*x + y*y),
(lambda / 2.0 - 2.0));
}
double CustomExactSolutionU::u_r(double x, double y) const
{
return (u_F * Hermes::cos(lambda * get_angle(y, x)) - lambda * Hermes::cos((lambda - 2)
* get_angle(y, x)));
}
double CustomExactSolutionU::du_rdx(double x, double y) const
{
return (u_F * (-1) * lambda * Hermes::sin(lambda * get_angle(y, x)) * d_theta_dx(x, y))
- (lambda * (-1) * (lambda - 2) * Hermes::sin((lambda - 2) * get_angle(y, x)) * d_theta_dx(x, y));
}
double CustomExactSolutionU::du_rdxdu_rdx(double x, double y) const
{
return (u_F * (-1) * lambda * (Hermes::sin(lambda * get_angle(y, x)) * d_theta_dxd_theta_dx(x, y)
+ lambda * d_theta_dx(x, y) * d_theta_dx(x, y) * Hermes::cos(lambda * get_angle(y, x))))
- (lambda * (-1) * (lambda - 2) * (Hermes::sin((lambda - 2) * get_angle(y, x))
* d_theta_dxd_theta_dx(x, y) + (lambda - 2) * d_theta_dx(x, y) * d_theta_dx(x, y)
* Hermes::cos((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionU::du_rdy(double x, double y) const
{
return (u_F * (-1) * lambda * Hermes::sin(lambda * get_angle(y, x)) * d_theta_dy(x, y))
- (lambda * (-1) * (lambda - 2) * Hermes::sin((lambda - 2) * get_angle(y, x)) * d_theta_dy(x, y));
}
double CustomExactSolutionU::du_rdydu_rdy(double x, double y) const
{
return (u_F * (-1) * lambda * (Hermes::sin(lambda * get_angle(y, x)) * d_theta_dyd_theta_dy(x, y)
+ lambda * d_theta_dy(x, y) * d_theta_dy(x, y) * Hermes::cos(lambda * get_angle(y, x))))
- (lambda * (-1) * (lambda - 2) * (Hermes::sin((lambda - 2) * get_angle(y, x))
* d_theta_dyd_theta_dy(x, y) + (lambda - 2) * d_theta_dy(x, y) * d_theta_dy(x, y)
* Hermes::cos((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionU::du_rdxdu_rdy(double x, double y) const
{
return (u_F * (-1) * lambda * (Hermes::sin(lambda * get_angle(y, x)) * d_theta_dxd_theta_dy(x, y)
+ lambda * d_theta_dx(x, y) * d_theta_dy(x, y) * Hermes::cos(lambda * get_angle(y, x))))
- (lambda * (-1) * (lambda - 2) * (Hermes::sin((lambda - 2) * get_angle(y, x))
* d_theta_dxd_theta_dy(x, y) + (lambda - 2) * d_theta_dx(x, y) * d_theta_dy(x, y)
* Hermes::cos((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionU::v_r(double x, double y) const
{
return (v_F * Hermes::sin(lambda * get_angle(y, x)) + lambda * Hermes::sin((lambda - 2) * get_angle(y, x)));
}
double CustomExactSolutionU::dv_rdx(double x, double y) const
{
return (v_F * lambda * Hermes::cos(lambda * get_angle(y, x)) * d_theta_dx(x, y))
+ (lambda * (lambda - 2) * Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dx(x, y));
}
double CustomExactSolutionU::dv_rdxdv_rdx(double x, double y) const
{
return (v_F * lambda * (Hermes::cos(lambda * get_angle(y, x)) * d_theta_dxd_theta_dx(x, y)
+ lambda * d_theta_dx(x, y) * d_theta_dx(x, y) * (-1) * Hermes::sin(lambda * get_angle(y, x))))
+ (lambda * (lambda - 2) * (Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dxd_theta_dx(x, y)
+ (lambda - 2) * d_theta_dx(x, y) * d_theta_dx(x, y) * (-1) * Hermes::sin((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionU::dv_rdy(double x, double y) const
{
return (v_F * lambda * Hermes::cos(lambda * get_angle(y, x)) * d_theta_dy(x, y)) + (lambda * (lambda - 2)
* Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dy(x, y));
}
double CustomExactSolutionU::dv_rdydv_rdy(double x, double y) const
{
return (v_F * lambda * (Hermes::cos(lambda * get_angle(y, x)) * d_theta_dyd_theta_dy(x, y)
+ lambda * d_theta_dy(x, y) * d_theta_dy(x, y) * (-1) * Hermes::sin(lambda * get_angle(y, x))))
+ (lambda * (lambda - 2) * (Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dyd_theta_dy(x, y)
+ (lambda - 2) * d_theta_dy(x, y) * d_theta_dy(x, y) * (-1) * Hermes::sin((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionU::dv_rdxdv_rdy(double x, double y) const
{
return (v_F * lambda * (Hermes::cos(lambda * get_angle(y, x)) * d_theta_dxd_theta_dy(x, y)
+ lambda * (-1) * d_theta_dx(x, y) * d_theta_dy(x, y) * Hermes::sin(lambda * get_angle(y, x))))
+ (lambda * (lambda - 2) * (Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dxd_theta_dy(x, y)
+ (lambda - 2) * (-1) * d_theta_dx(x, y) * d_theta_dy(x, y) * Hermes::sin((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionU::dudxdudx(double x, double y) const
{
return D * (drdxdrdx(x, y) * u_r(x, y) + 2 * drdx(x, y) * du_rdx(x, y) + r(x, y) * du_rdxdu_rdx(x, y));
}
double CustomExactSolutionU::dudydudy(double x, double y) const
{
return D * (drdydrdy(x, y) * u_r(x, y) + 2 * drdy(x, y) * du_rdy(x, y) + r(x, y) * du_rdydu_rdy(x, y));
}
double CustomExactSolutionU::dudxdudy(double x, double y) const
{
return D * (drdxdrdy(x, y) * u_r(x, y) + drdx(x, y) * du_rdy(x, y) + drdy(x, y) * du_rdx(x, y) + r(x, y)
* du_rdxdu_rdy(x, y));
}
double CustomExactSolutionU::dvdxdvdx(double x, double y) const
{
return D * (drdxdrdx(x, y) * v_r(x, y) + 2 * drdx(x, y) * dv_rdx(x, y) + r(x, y) * dv_rdxdv_rdx(x, y));
}
double CustomExactSolutionU::dvdydvdy(double x, double y) const
{
return D * (drdydrdy(x, y) * v_r(x, y) + 2 * drdy(x, y) * dv_rdy(x, y) + r(x, y) * dv_rdydv_rdy(x, y));
}
double CustomExactSolutionU::dvdxdvdy(double x, double y) const
{
return D * (drdxdrdy(x, y) * v_r(x, y) + drdx(x, y) * dv_rdy(x, y) + drdy(x, y) * dv_rdx(x, y) + r(x, y)
* dv_rdxdv_rdy(x, y));
}
double CustomExactSolutionU::value(double x, double y) const
{
return D * r(x, y) * u_r(x, y);
}
void CustomExactSolutionU::derivatives(double x, double y, double& dx, double& dy) const
{
dx = D * drdx(x, y) * (u_F * Hermes::cos(lambda * get_angle(y, x)) - lambda * Hermes::cos((lambda - 2) * get_angle(y, x))) +
D * r(x, y) * (u_F * (-1) * lambda * Hermes::sin(lambda * get_angle(y, x)) * d_theta_dx(x, y)) -
D * r(x, y) * (lambda * (-1) * (lambda - 2) * Hermes::sin((lambda - 2) * get_angle(y, x)) * d_theta_dx(x, y));
dy = D * drdy(x, y) * (u_F * Hermes::cos(lambda * get_angle(y, x)) - lambda * Hermes::cos((lambda - 2) * get_angle(y, x))) +
D * r(x, y) * (u_F * (-1) * lambda * Hermes::sin(lambda * get_angle(y, x)) * d_theta_dy(x, y)) -
D * r(x, y) * (lambda * (-1) * (lambda - 2) * Hermes::sin((lambda - 2) * get_angle(y, x)) * d_theta_dy(x, y));
}
Ord CustomExactSolutionU::ord(double x, double y) const
{
return Ord(4.0);
}
MeshFunction<double>* CustomExactSolutionU::clone() const
{
return new CustomExactSolutionU(this->mesh, this->E, this->nu, this->lambda, this->Q);
}
double CustomExactSolutionV::get_angle(double y, double x) const
{
double theta = Hermes::atan2(y, x);
if (theta < 0)
theta += 2 * M_PI;
return theta;
}
double CustomExactSolutionV::d_theta_dx(double x, double y) const
{
return -y / (x*x + y*y);
}
double CustomExactSolutionV::d_theta_dxd_theta_dx(double x, double y) const
{
return 2 * x*y / ((x*x + y*y)*(x*x + y*y));
}
double CustomExactSolutionV::d_theta_dy(double x, double y) const
{
return x / (x*x + y*y);
}
double CustomExactSolutionV::d_theta_dyd_theta_dy(double x, double y) const
{
return -2 * x*y / ((x*x + y*y)*(x*x + y*y));
}
double CustomExactSolutionV::d_theta_dxd_theta_dy(double x, double y) const
{
return (y*y - x*x) / ((x*x + y*y)*(x*x + y*y));
}
double CustomExactSolutionV::r(double x, double y) const
{
return Hermes::pow((x*x + y*y), (lambda / 2.0)); // r^labbda
}
double CustomExactSolutionV::drdx(double x, double y) const
{
return lambda * x * Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0));
}
double CustomExactSolutionV::drdxdrdx(double x, double y) const
{
return lambda * (Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0)) + (lambda - 2.0)
* x * x * Hermes::pow((x*x + y*y), (lambda / 2.0 - 2.0)));
}
double CustomExactSolutionV::drdy(double x, double y) const
{
return lambda * y * Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0));
}
double CustomExactSolutionV::drdydrdy(double x, double y) const
{
return lambda * (Hermes::pow((x*x + y*y), (lambda / 2.0 - 1.0)) + (lambda - 2.0)
* y * y * Hermes::pow((x*x + y*y), (lambda / 2.0 - 2.0)));
}
double CustomExactSolutionV::drdxdrdy(double x, double y) const
{
return lambda * 2.0 * x * y * (lambda / 2.0 - 1) * Hermes::pow((x*x + y*y),
(lambda / 2.0 - 2.0));
}
double CustomExactSolutionV::u_r(double x, double y) const
{
return (u_F * Hermes::cos(lambda * get_angle(y, x)) - lambda * Hermes::cos((lambda - 2)
* get_angle(y, x)));
}
double CustomExactSolutionV::du_rdx(double x, double y) const
{
return (u_F * (-1) * lambda * Hermes::sin(lambda * get_angle(y, x)) * d_theta_dx(x, y))
- (lambda * (-1) * (lambda - 2) * Hermes::sin((lambda - 2) * get_angle(y, x)) * d_theta_dx(x, y));
}
double CustomExactSolutionV::du_rdxdu_rdx(double x, double y) const
{
return (u_F * (-1) * lambda * (Hermes::sin(lambda * get_angle(y, x)) * d_theta_dxd_theta_dx(x, y)
+ lambda * d_theta_dx(x, y) * d_theta_dx(x, y) * Hermes::cos(lambda * get_angle(y, x))))
- (lambda * (-1) * (lambda - 2) * (Hermes::sin((lambda - 2) * get_angle(y, x))
* d_theta_dxd_theta_dx(x, y) + (lambda - 2) * d_theta_dx(x, y) * d_theta_dx(x, y)
* Hermes::cos((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionV::du_rdy(double x, double y) const
{
return (u_F * (-1) * lambda * Hermes::sin(lambda * get_angle(y, x)) * d_theta_dy(x, y))
- (lambda * (-1) * (lambda - 2) * Hermes::sin((lambda - 2) * get_angle(y, x)) * d_theta_dy(x, y));
}
double CustomExactSolutionV::du_rdydu_rdy(double x, double y) const
{
return (u_F * (-1) * lambda * (Hermes::sin(lambda * get_angle(y, x)) * d_theta_dyd_theta_dy(x, y)
+ lambda * d_theta_dy(x, y) * d_theta_dy(x, y) * Hermes::cos(lambda * get_angle(y, x))))
- (lambda * (-1) * (lambda - 2) * (Hermes::sin((lambda - 2) * get_angle(y, x))
* d_theta_dyd_theta_dy(x, y) + (lambda - 2) * d_theta_dy(x, y) * d_theta_dy(x, y)
* Hermes::cos((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionV::du_rdxdu_rdy(double x, double y) const
{
return (u_F * (-1) * lambda * (Hermes::sin(lambda * get_angle(y, x)) * d_theta_dxd_theta_dy(x, y)
+ lambda * d_theta_dx(x, y) * d_theta_dy(x, y) * Hermes::cos(lambda * get_angle(y, x))))
- (lambda * (-1) * (lambda - 2) * (Hermes::sin((lambda - 2) * get_angle(y, x))
* d_theta_dxd_theta_dy(x, y) + (lambda - 2) * d_theta_dx(x, y) * d_theta_dy(x, y)
* Hermes::cos((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionV::v_r(double x, double y) const
{
return (v_F * Hermes::sin(lambda * get_angle(y, x)) + lambda * Hermes::sin((lambda - 2) * get_angle(y, x)));
}
double CustomExactSolutionV::dv_rdx(double x, double y) const
{
return (v_F * lambda * Hermes::cos(lambda * get_angle(y, x)) * d_theta_dx(x, y))
+ (lambda * (lambda - 2) * Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dx(x, y));
}
double CustomExactSolutionV::dv_rdxdv_rdx(double x, double y) const
{
return (v_F * lambda * (Hermes::cos(lambda * get_angle(y, x)) * d_theta_dxd_theta_dx(x, y)
+ lambda * d_theta_dx(x, y) * d_theta_dx(x, y) * (-1) * Hermes::sin(lambda * get_angle(y, x))))
+ (lambda * (lambda - 2) * (Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dxd_theta_dx(x, y)
+ (lambda - 2) * d_theta_dx(x, y) * d_theta_dx(x, y) * (-1) * Hermes::sin((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionV::dv_rdy(double x, double y) const
{
return (v_F * lambda * Hermes::cos(lambda * get_angle(y, x)) * d_theta_dy(x, y)) + (lambda * (lambda - 2)
* Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dy(x, y));
}
double CustomExactSolutionV::dv_rdydv_rdy(double x, double y) const
{
return (v_F * lambda * (Hermes::cos(lambda * get_angle(y, x)) * d_theta_dyd_theta_dy(x, y)
+ lambda * d_theta_dy(x, y) * d_theta_dy(x, y) * (-1) * Hermes::sin(lambda * get_angle(y, x))))
+ (lambda * (lambda - 2) * (Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dyd_theta_dy(x, y)
+ (lambda - 2) * d_theta_dy(x, y) * d_theta_dy(x, y) * (-1) * Hermes::sin((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionV::dv_rdxdv_rdy(double x, double y) const
{
return (v_F * lambda * (Hermes::cos(lambda * get_angle(y, x)) * d_theta_dxd_theta_dy(x, y)
+ lambda * (-1) * d_theta_dx(x, y) * d_theta_dy(x, y) * Hermes::sin(lambda * get_angle(y, x))))
+ (lambda * (lambda - 2) * (Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dxd_theta_dy(x, y)
+ (lambda - 2) * (-1) * d_theta_dx(x, y) * d_theta_dy(x, y) * Hermes::sin((lambda - 2) * get_angle(y, x))));
}
double CustomExactSolutionV::dudxdudx(double x, double y) const
{
return D * (drdxdrdx(x, y) * u_r(x, y) + 2 * drdx(x, y) * du_rdx(x, y) + r(x, y) * du_rdxdu_rdx(x, y));
}
double CustomExactSolutionV::dudydudy(double x, double y) const
{
return D * (drdydrdy(x, y) * u_r(x, y) + 2 * drdy(x, y) * du_rdy(x, y) + r(x, y) * du_rdydu_rdy(x, y));
}
double CustomExactSolutionV::dudxdudy(double x, double y) const
{
return D * (drdxdrdy(x, y) * u_r(x, y) + drdx(x, y) * du_rdy(x, y) + drdy(x, y) * du_rdx(x, y) + r(x, y)
* du_rdxdu_rdy(x, y));
}
double CustomExactSolutionV::dvdxdvdx(double x, double y) const
{
return D * (drdxdrdx(x, y) * v_r(x, y) + 2 * drdx(x, y) * dv_rdx(x, y) + r(x, y) * dv_rdxdv_rdx(x, y));
}
double CustomExactSolutionV::dvdydvdy(double x, double y) const
{
return D * (drdydrdy(x, y) * v_r(x, y) + 2 * drdy(x, y) * dv_rdy(x, y) + r(x, y) * dv_rdydv_rdy(x, y));
}
double CustomExactSolutionV::dvdxdvdy(double x, double y) const
{
return D * (drdxdrdy(x, y) * v_r(x, y) + drdx(x, y) * dv_rdy(x, y) + drdy(x, y) * dv_rdx(x, y) + r(x, y)
* dv_rdxdv_rdy(x, y));
}
double CustomExactSolutionV::value(double x, double y) const
{
return D * r(x, y) * v_r(x, y);
}
void CustomExactSolutionV::derivatives(double x, double y, double& dx, double& dy) const
{
dx = D * drdx(x, y) * (v_F * Hermes::sin(lambda * get_angle(y, x)) + lambda * Hermes::sin((lambda - 2) * get_angle(y, x))) +
D * r(x, y) * (v_F * lambda * Hermes::cos(lambda * get_angle(y, x)) * d_theta_dx(x, y)) +
D * r(x, y) * (lambda * (lambda - 2) * Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dx(x, y));
dy = D * drdy(x, y) * (v_F * Hermes::sin(lambda * get_angle(y, x)) + lambda * Hermes::sin((lambda - 2) * get_angle(y, x))) +
D * r(x, y) * (v_F * lambda * Hermes::cos(lambda * get_angle(y, x)) * d_theta_dy(x, y)) +
D * r(x, y) * (lambda * (lambda - 2) * Hermes::cos((lambda - 2) * get_angle(y, x)) * d_theta_dy(x, y));
}
Ord CustomExactSolutionV::ord(double x, double y) const
{
return Ord(4.0);
}
MeshFunction<double>* CustomExactSolutionV::clone() const
{
return new CustomExactSolutionV(this->mesh, this->E, this->nu, this->lambda, this->Q);
}
CustomWeakFormElasticityNIST::CustomWeakFormElasticityNIST(double E, double nu, double mu, double lambda) : WeakForm<double>(2)
{
// Jacobian.
add_matrix_form(new CustomMatrixFormVolElasticityNIST_0_0(0, 0, E, nu));
add_matrix_form(new CustomMatrixFormVolElasticityNIST_0_1(0, 1, E, nu));
add_matrix_form(new CustomMatrixFormVolElasticityNIST_1_1(1, 1, E, nu));
// Residual.
add_vector_form(new CustomVectorFormVolElasticityNIST_0(0, E, nu));
add_vector_form(new CustomVectorFormVolElasticityNIST_1(1, E, nu));
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_0::matrix_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
val += wt[i] * (A * u->dx[i] * v->dx[i] + B * u->dy[i] * v->dy[i]);
return val;
}
double CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_0::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_0::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_0::clone() const
{
return new CustomMatrixFormVolElasticityNIST_0_0(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_1::matrix_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
val += wt[i] * (C * u->dx[i] * v->dy[i]);
return val;
}
double CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_1::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_1::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_0_1::clone() const
{
return new CustomMatrixFormVolElasticityNIST_0_1(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_1_1::matrix_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
val += wt[i] * (B * u->dx[i] * v->dx[i] + A * u->dy[i] * v->dy[i]);
return val;
}
double CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_1_1::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_1_1::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* CustomWeakFormElasticityNIST::CustomMatrixFormVolElasticityNIST_1_1::clone() const
{
return new CustomMatrixFormVolElasticityNIST_1_1(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_0::vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
{
// Contribution of matrix form 0, 0.
val += wt[i] * (A * u_ext[0]->dx[i] * v->dx[i] + B * u_ext[0]->dy[i] * v->dy[i]);
// Contribution of matrix form 0, 1.
val += wt[i] * (C * u_ext[1]->dx[i] * v->dy[i]);
}
return val;
}
double CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_0::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_0::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_0::clone() const
{
return new CustomVectorFormVolElasticityNIST_0(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_1::vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar val = Scalar(0);
for (int i = 0; i < n; i++)
{
// Contribution of matrix form 1, 0.
val += wt[i] * (C * u_ext[0]->dy[i] * v->dx[i]);
// Contribution of matrix form 1, 1.
val += wt[i] * (B * u_ext[1]->dx[i] * v->dx[i] + A * u_ext[1]->dy[i] * v->dy[i]);
}
return val;
}
double CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_1::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_1::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomWeakFormElasticityNIST::CustomVectorFormVolElasticityNIST_1::clone() const
{
return new CustomVectorFormVolElasticityNIST_1(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly-dealii/definitions.h | .h | 5,921 | 195 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes::Hermes2D;
using namespace WeakFormsH1;
using Hermes::Ord;
/* Right-hand side */
class CustomWeakForm : public WeakForm<double>
{
class Jacobian : public MatrixFormVol<double>
{
public:
Jacobian() : MatrixFormVol<double>(0, 0) { this->setSymFlag(HERMES_SYM); };
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const { return new Jacobian(); }
};
class Residual : public VectorFormVol<double>
{
const Hermes::Hermes2DFunction<double>* rhs;
public:
Residual(const Hermes::Hermes2DFunction<double>* rhs) : VectorFormVol<double>(0), rhs(rhs) {};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
VectorFormVol<double>* clone() const { return new Residual(rhs); }
};
public:
CustomWeakForm(const Hermes::Hermes2DFunction<double>* rhs)
{
add_matrix_form(new Jacobian);
add_vector_form(new Residual(rhs));
}
};
class CustomRightHandSide : public Hermes::Hermes2DFunction<double>
{
public:
CustomRightHandSide(double alpha, double x_loc, double y_loc, double r_zero)
: Hermes::Hermes2DFunction<double>(), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero)
{ };
virtual double value(double x, double y) const;
virtual Ord value (Ord x, Ord y) const { return Ord(8); }
double alpha, x_loc, y_loc, r_zero;
};
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double alpha, double x_loc, double y_loc, double r_zero)
: ExactSolutionScalar<double>(mesh), alpha(alpha), x_loc(x_loc), y_loc(y_loc), r_zero(r_zero)
{ };
virtual double value(double x, double y) const {
return atan(alpha * (sqrt(pow(x - x_loc, 2) + pow(y - y_loc, 2)) - r_zero));
};
virtual void derivatives (double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const { return Ord(Ord::get_max_order()); }
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, alpha, x_loc, y_loc, r_zero); }
double alpha, x_loc, y_loc, r_zero;
};
/* Bilinear form inducing the energy norm */
class EnergyErrorForm : public Adapt<double>::MatrixFormVolError
{
public:
EnergyErrorForm(WeakForm<double> *problem_wf) : Adapt<double>::MatrixFormVolError(0, 0, HERMES_UNSET_NORM)
{
this->form = problem_wf->get_mfvol()[0];
this->wf = problem_wf;
}
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
return this->form->value(n, wt, u_ext, u, v, e, ext);
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return this->form->ord(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* clone() const { return new EnergyErrorForm(wf); }
private:
const MatrixFormVol<double>* form;
};
/* Linear form for the residual error estimator */
class ResidualErrorForm : public KellyTypeAdapt<double>::ErrorEstimatorForm
{
public:
ResidualErrorForm(CustomRightHandSide* rhs)
: KellyTypeAdapt<double>::ErrorEstimatorForm(0), rhs(rhs)
{ };
double value(int n, double *wt,
Func<double> *u_ext[], Func<double> *u,
GeomVol<double> *e, Func<double>* *ext) const;
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u,
GeomVol<Ord> *e, Func<Ord>* *ext) const;
private:
CustomRightHandSide* rhs;
};
class ConvergenceTable
{
public:
void save(const char* filename) const;
void add_column(const std::string& name, const std::string& format) {
columns.push_back(Column(name, format));
}
void add_value(unsigned int col, double x) {
add_value_internal<double>(col, x, "%g");
}
void add_value(unsigned int col, int x) {
add_value_internal<int>(col, x, "%d");
}
int num_rows() const {
return columns[0].data.size();
}
int num_columns() const {
return columns.size();
}
private:
struct Column
{
Column(const std::string& name, const std::string& format)
: label(name), format(format)
{ }
struct Entry
{
union
{
int ivalue;
double dvalue;
};
enum { INT, DOUBLE } data_type;
Entry(int x) : ivalue(x), data_type(INT) {};
Entry(double x) : dvalue(x), data_type(DOUBLE) {};
};
std::string label;
std::string format;
std::vector<Entry> data;
};
std::vector<Column> columns;
template <typename T>
void add_value_internal(unsigned int col, T x, const std::string& default_fmt)
{
if (columns.size() == 0) add_column("", default_fmt);
if (col < 0 || col >= columns.size())
throw Hermes::Exceptions::Exception("Invalid column number.");
columns[col].data.push_back(Column::Entry(x));
}
};
// Convert int to string.
std::string itos(const unsigned int i); | Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly-dealii/main.cpp | .cpp | 10,789 | 365 |
#include "definitions.h"
// This is the ninth in the series of NIST benchmarks with known exact solutions. This benchmark
// has four different versions, use the global variable PROB_PARAM below to switch among them.
// It differs from 09-wave-front in the mesh adaptation method.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: -Laplace u - f = 0
//
// Known exact solution; atan(ALPHA * (sqrt(pow(x - X_LOC, 2) + pow(y - Y_LOC, 2)) - R_ZERO));
// See the class CustomExactSolution.
//
// Domain: unit square (0, 1) x (0, 1), see the file square.mesh->
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// PARAM determines which parameter values you wish to use
// for the steepness and location of the wave front.
// #| name | ALPHA | X_LOC | Y_LOC | R_ZERO
// 0: mild 20 -0.05 -0.05 0.7
// 1: steep 1000 -0.05 -0.05 0.7
// 2: asymmetric 1000 1.5 0.25 0.92
// 3: well 50 0.5 0.5 0.25
int PARAM = 3;
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// Maximum allowed level of hanging nodes:
// MESH_REGULARITY = -1 ... arbitrary level hangning nodes (default),
// MESH_REGULARITY = 1 ... at most one-level hanging nodes,
// MESH_REGULARITY = 2 ... at most two-level hanging nodes, etc.
// Note that regular meshes are not supported, this is due to
// their notoriously bad performance.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity (rel. error tolerance between the
// reference mesh and coarse mesh solution in percent).
const double ERR_STOP = 0.1;
// Adaptivity process stops when the number of degrees of freedom grows
// over this limit. This is to prevent h-adaptivity to go on forever.
const int NDOF_STOP = 60000;
// Matrix solver: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
Hermes::MatrixSolverType matrix_solver = Hermes::SOLVER_UMFPACK;
int main(int argc, char* argv[])
{
// Define problem parameters: (x_loc, y_loc) is the center of the circular wave front, R_ZERO is the distance from the
// wave front to the center of the circle, and alpha gives the steepness of the wave front.
double alpha, x_loc, y_loc, r_zero;
switch(PARAM) {
case 0:
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 1:
alpha = 1000;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 2:
alpha = 1000;
x_loc = 1.5;
y_loc = 0.25;
r_zero = 0.92;
break;
case 3:
alpha = 50;
x_loc = 0.5;
y_loc = 0.5;
r_zero = 0.25;
break;
default:
// The same as 0.
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
}
// Set adaptivity options according to the command line argument.
int refinement_mode;
if (argc != 2)
refinement_mode = 0;
else
{
refinement_mode = atoi(argv[1]);
if (refinement_mode < 1 || refinement_mode > 12)
throw Hermes::Exceptions::Exception("Invalid run case: %d (valid range is [1,12])", refinement_mode);
}
double threshold = 0.3;
// strategy = 0 ... Refine elements until sqrt(threshold) times total error is processed.
// If more elements have similar errors, refine all to keep the mesh symmetric.
int strategy = 0;
// strategy = 1 ... Refine all elements whose error is larger than threshold times max. element error.
// Add also the norm of the residual to the error estimate of each element.
bool use_residual_estimator = false;
// Use energy norm for error estimate normalization and measuring of exact error.
bool use_energy_norm_normalization = false;
switch (refinement_mode)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
{
strategy = 0;
break;
}
case 7 :
case 8 :
case 9 :
case 10:
case 11:
case 12:
{
strategy = 1;
break;
}
}
switch (refinement_mode)
{
case 1:
case 2:
case 3:
case 7:
case 8:
case 9:
{
threshold = 0.3;
break;
}
case 4:
case 5:
case 6:
case 10:
case 11:
case 12:
{
threshold = 0.3*0.3;
break;
}
}
switch (refinement_mode)
{
case 2:
case 3:
case 5:
case 6:
case 8:
case 9:
case 11:
case 12:
{
use_residual_estimator = true;
break;
}
}
switch (refinement_mode)
{
case 3:
case 6:
case 9:
case 12:
{
use_energy_norm_normalization = true;
break;
}
}
double setup_time = 0, assemble_time = 0, solve_time = 0, adapt_time = 0;
// Time measurement.
Hermes::Mixins::TimeMeasurable wall_clock;
// Stop counting time for adaptation.
wall_clock.tick();
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square_quad.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Stop counting time for adaptation.
wall_clock.tick();
adapt_time += wall_clock.last();
// Set exact solution.
CustomExactSolution exact(mesh, alpha, x_loc, y_loc, r_zero);
// Define right-hand side.
CustomRightHandSide rhs(alpha, x_loc, y_loc, r_zero);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(&rhs));
// Equivalent, but slower:
// DefaultWeakFormPoisson<double> wf(Hermes::HERMES_ANY, HERMES_ONE, &rhs);
// Initialize boundary conditions.
DefaultEssentialBCNonConst<double> bc("Bdy", &exact);
EssentialBCs<double> bcs(&bc);
SpaceSharedPtr<double> space(new // Create an H1 space with default shapeset.
H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
Solution<double> sln;
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(800, 0, 400, 400));
sview.show_mesh(false);
sview.set_3d_mode();
sview.set_palette(Views::H2DV_PT_HUESCALE);
sview.fix_scale_width(50);
Views::OrderView oview("Mesh", new Views::WinGeom(0, 0, 800, 800));
oview.set_palette(Views::H2DV_PT_INVGRAYSCALE);
// DOF and CPU convergence graphs.
ConvergenceTable conv_table;
conv_table.add_column(" cycle ", "%6d ");
conv_table.add_column(" H1 error ", " %.4e ");
conv_table.add_column(" ndof ", " %6d ");
conv_table.add_column(" total time ", " %8.3f ");
conv_table.add_column(" setup time ", " %8.3f ");
conv_table.add_column(" assem time ", " %8.3f ");
conv_table.add_column(" solve time ", " %8.3f ");
conv_table.add_column(" adapt time ", " %8.3f ");
wall_clock.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// Adaptivity loop:
int as = 0; bool done = false;
do
{
// Start counting setup time.
wall_clock.tick();
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, &space);
// Actual ndof.
int ndof = space.get_num_dofs();
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
// Setup time continues in NewtonSolver::solve().
try
{
newton.solve();
}
catch(Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Start counting time for adaptation.
wall_clock.tick();
Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, sln);
double err_exact = Global<double>::calc_abs_error(sln, &exact, HERMES_H1_NORM);
// Report results.
Hermes::Mixins::Loggable::Static::info(" Cycle %d:", as);
Hermes::Mixins::Loggable::Static::info(" Number of degrees of freedom: %d", ndof);
Hermes::Mixins::Loggable::Static::info(" H1 error w.r.t. exact soln.: %g", err_exact);
// Stop counting time for adaptation.
wall_clock.tick();
double accum_time = wall_clock.accumulated();
adapt_time += wall_clock.last();
// View the approximate solution and polynomial orders.
//sview.show(sln);
//oview.show(&space);
//Views::View::wait(Views::HERMES_WAIT_KEYPRESS);
conv_table.add_value(0, as);
conv_table.add_value(1, err_exact);
conv_table.add_value(2, ndof);
conv_table.add_value(3, accum_time);
conv_table.add_value(4, setup_time);
conv_table.add_value(5, assemble_time);
conv_table.add_value(6, solve_time);
conv_table.add_value(7, adapt_time);
// Start counting time for adaptation.
wall_clock.tick();
if (err_exact < ERR_STOP)
done = true;
else
{
// Calculate element errors and total error estimate.
Hermes::Hermes2D::BasicKellyAdapt<double> adaptivity(&space);
unsigned int error_flags = HERMES_TOTAL_ERROR_ABS;
if (use_energy_norm_normalization)
{
error_flags |= HERMES_ELEMENT_ERROR_REL;
adaptivity.set_error_form(new EnergyErrorForm(wf));
}
else
error_flags |= HERMES_ELEMENT_ERROR_ABS;
if (use_residual_estimator)
adaptivity.add_error_estimator_vol(new ResidualErrorForm(&rhs));
double err_est_rel = adaptivity.calc_err_est(sln, error_flags);
done = adaptivity.adapt(threshold, strategy, MESH_REGULARITY);
// Stop counting time for adaptation.
wall_clock.tick();
adapt_time += wall_clock.last();
}
// Increase the counter of performed adaptivity steps.
if (done == false)
as++;
else
{
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", wall_clock.accumulated());
Hermes::Mixins::Loggable::Static::info(" Setup: %g s", setup_time);
Hermes::Mixins::Loggable::Static::info(" Assemble: %g s", assemble_time);
Hermes::Mixins::Loggable::Static::info(" Solve: %g s", solve_time);
Hermes::Mixins::Loggable::Static::info(" Adapt: %g s", adapt_time);
//sview.show(sln);
oview.show(&space);
oview.save_screenshot(("final_mesh-"+itos(refinement_mode)+".bmp").c_str());
oview.close();
conv_table.save(("conv_table-"+itos(refinement_mode)+".dat").c_str());
}
}
while (done == false);
// Wait for all views to be closed.
//Views::View::wait();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly-dealii/definitions.cpp | .cpp | 4,765 | 130 | #include "definitions.h"
double CustomWeakForm::Jacobian::value(int n, double* wt,
Func< double >* u_ext[], Func< double >* u, Func< double >* v,
GeomVol< double >* e, Func< double >** ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
return result;
}
Ord CustomWeakForm::Jacobian::ord(int n, double* wt,
Func< Ord >* u_ext[], Func< Ord >* u, Func< Ord >* v,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
return u->dx[0] * v->dx[0] + u->dy[0] * v->dy[0];
}
double CustomWeakForm::Residual::value(int n, double* wt, Func< double >* u_ext[], Func< double >* v,
GeomVol< double >* e, Func< double >** ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * ( u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i] + rhs->value(e->x[i], e->y[i]) * v->val[i] );
return result;
}
Ord CustomWeakForm::Residual::ord(int n, double* wt, Func< Ord >* u_ext[], Func< Ord >* v,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
return u_ext[0]->dx[0] * v->dx[0] + u_ext[0]->dy[0] * v->dy[0] + rhs->value(e->x[0], e->y[0]) * v->val[0];
}
double CustomRightHandSide::value(double x, double y) const
{
double a = pow(x - x_loc, 2);
double b = pow(y - y_loc, 2);
double c = sqrt(a + b);
double d = ((alpha*x - (alpha * x_loc)) * (2*x - (2 * x_loc)));
double e = ((alpha*y - (alpha * y_loc)) * (2*y - (2 * y_loc)));
double f = (pow(alpha*c - (alpha * r_zero), 2) + 1.0);
double g = (alpha * c - (alpha * r_zero));
return +( ((alpha/(c * f)) - (d/(2 * pow(a + b, 1.5) * f))
- ((alpha * d * g)/((a + b) * pow(f, 2))) + (alpha/(c * f))
- (e/(2 * pow(a + b, 1.5) * f))
- ((alpha * e * g)/((a + b) * pow(f, 2)))));
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double a = pow(x - x_loc, 2);
double b = pow(y - y_loc, 2);
double c = sqrt(a + b);
double d = (alpha*x - (alpha * x_loc));
double e = (alpha*y - (alpha * y_loc));
double f = (pow(alpha*c - (alpha * r_zero), 2) + 1.0);
dx = (d/(c * f));
dy = (e/(c * f));
}
double ResidualErrorForm::value(int n, double* wt,
Func< double >* u_ext[], Func< double >* u,
GeomVol< double >* e, Func< double >** ext) const
{
#ifdef H2D_SECOND_DERIVATIVES_ENABLED
double result = 0.;
for (int i = 0; i < n; i++)
result += wt[i] * Hermes::sqr( -rhs->value(e->x[i], e->y[i]) + u->laplace[i] );
return result * Hermes::sqr(e->diam);
#else
throw Hermes::Exceptions::Exception("Define H2D_SECOND_DERIVATIVES_ENABLED in hermes2d_common_defs.h"
"if you want to use second derivatives in weak forms.");
#endif
}
Ord ResidualErrorForm::ord(int n, double* wt,
Func< Ord >* u_ext[], Func< Ord >* u,
GeomVol< Ord >* e, Func< Ord >** ext) const
{
#ifdef H2D_SECOND_DERIVATIVES_ENABLED
return sqr( -rhs->value(e->x[0], e->y[0]) + u->laplace[0] );
#else
throw Hermes::Exceptions::Exception("Define H2D_SECOND_DERIVATIVES_ENABLED in hermes2d_common_defs.h"
"if you want to use second derivatives in weak forms.");
#endif
}
void ConvergenceTable::save(const char* filename) const
{
if (num_columns() == 0) throw Hermes::Exceptions::Exception("No data columns defined.");
for (unsigned int i = 1; i < num_columns(); i++)
if (columns[i].data.size() != num_rows())
throw Hermes::Exceptions::Exception("Incompatible column sizes.");
FILE* f = fopen(filename, "w");
if (f == NULL) throw Hermes::Exceptions::Exception("Error writing to %s.", filename);
for (unsigned int i = 0; i < num_columns(); i++)
fprintf(f, columns[i].label.c_str());
fprintf(f, "\n");
for (int j = 0; j < num_rows(); j++)
{
for (unsigned int i = 0; i < num_columns(); i++)
{
if (columns[i].data[j].data_type == Column::Entry::INT)
fprintf(f, columns[i].format.c_str(), columns[i].data[j].ivalue);
else if (columns[i].data[j].data_type == Column::Entry::DOUBLE)
fprintf(f, columns[i].format.c_str(), columns[i].data[j].dvalue);
}
fprintf(f, "\n");
}
fclose(f);
Hermes::Mixins::Loggable::Static::info("Convergence table saved to file '%s'.", filename);
}
std::string itos(const unsigned int i)
{
std::stringstream s;
s << i;
return s.str();
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/09-wave-front-kelly-dealii/deal.ii/step-6.cc | .cc | 19,469 | 678 | /* $Id: step-6.cc 22321 2010-10-12 21:53:08Z kanschat $ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */
/* $Id: step-6.cc 22321 2010-10-12 21:53:08Z kanschat $ */
/* */
/* Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008, 2010 by the deal.II authors */
/* */
/* This file is subject to QPL and may not be distributed */
/* without copyright and license information. Please refer */
/* to the file deal.II/doc/license.html for the text and */
/* further information on this license. */
// @sect3{Include files}
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>
#include <lac/sparse_matrix.h>
#include <lac/compressed_sparsity_pattern.h>
#include <lac/solver_cg.h>
#include <lac/sparse_direct.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <dofs/dof_handler.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>
#include <numerics/fe_field_function.h>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <fe/fe_q.h>
#include <grid/grid_out.h>
#include <lac/constraint_matrix.h>
#include <grid/grid_refinement.h>
#include <numerics/error_estimator.h>
#include <numerics/vectors.h>
#include <base/table_handler.h>
#include <base/timer.h>
using namespace dealii;
template <int dim>
class SolutionBase
{
public:
SolutionBase(int param);
protected:
double alpha, x_loc, y_loc, r_zero;
};
template <int dim>
SolutionBase<dim>::SolutionBase(int param)
{
switch(param)
{
case 0:
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 1:
alpha = 1000;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
case 2:
alpha = 1000;
x_loc = 1.5;
y_loc = 0.25;
r_zero = 0.92;
break;
case 3:
alpha = 50;
x_loc = 0.5;
y_loc = 0.5;
r_zero = 0.25;
break;
default: // The same as 0.
alpha = 20;
x_loc = -0.05;
y_loc = -0.05;
r_zero = 0.7;
break;
}
}
template <int dim>
class Solution : public Function<dim>,
protected SolutionBase<dim>
{
public:
Solution (int param) : Function<dim>(), SolutionBase<dim>(param) {}
virtual double value (const Point<dim> &p,
const unsigned int component = 0) const;
virtual Tensor<1,dim> gradient (const Point<dim> &p,
const unsigned int component = 0) const;
};
template <>
double Solution<2>::value (const Point<2> &p,
const unsigned int) const
{
return atan(this->alpha * (sqrt(pow(p[0] - this->x_loc, 2) + pow(p[1] - this->y_loc, 2)) - this->r_zero));
}
template <>
Tensor<1,2> Solution<2>::gradient (const Point<2> &p,
const unsigned int) const
{
double grad[2];
double x = p[0];
double y = p[1];
double a = pow(x - this->x_loc, 2);
double b = pow(y - this->y_loc, 2);
double c = sqrt(a + b);
double d = (this->alpha*x - (this->alpha * this->x_loc));
double e = (this->alpha*y - (this->alpha * this->y_loc));
double f = (pow(this->alpha*c - (this->alpha * this->r_zero), 2) + 1.0);
grad[0] = (d/(c * f));
grad[1] = (e/(c * f));
return Tensor<1,2>(grad);
}
template <int dim>
class RightHandSide : public Function<dim>,
protected SolutionBase<dim>
{
public:
RightHandSide (int param) : Function<dim>(), SolutionBase<dim>(param) {}
virtual double value (const Point<dim> &p,
const unsigned int component = 0) const;
};
template <>
double RightHandSide<2>::value (const Point<2> &p,
const unsigned int) const
{
double x = p[0];
double y = p[1];
double a = pow(x - this->x_loc, 2);
double b = pow(y - this->y_loc, 2);
double c = sqrt(a + b);
double d = ((this->alpha*x - (this->alpha * this->x_loc)) * (2*x - (2 * this->x_loc)));
double e = ((this->alpha*y - (this->alpha * this->y_loc)) * (2*y - (2 * this->y_loc)));
double f = (pow(this->alpha*c - (this->alpha * this->r_zero), 2) + 1.0);
double g = (this->alpha * c - (this->alpha * this->r_zero));
return -( ((this->alpha/(c * f)) - (d/(2 * pow(a + b, 1.5) * f))
- ((this->alpha * d * g)/((a + b) * pow(f, 2))) + (this->alpha/(c * f))
- (e/(2 * pow(a + b, 1.5) * f))
- ((this->alpha * e * g)/((a + b) * pow(f, 2)))));
}
enum SolverType { CG, UMFPACK };
template <int dim>
class LaplaceProblem
{
public:
// Refinement modes:
//
// 0 ... global refinement
// 1 ... number, 0.3/0.03
// 2 ... number, 0.3/0
// 3 ... number, 0.3/0.03, squared
// 4 ... number, 0.3/0, squared
// 5 ... number, sqrt(0.3)/0.03, squared
// 6 ... number, sqrt(0.3)/0, squared
// 7 ... fraction, 0.3/0.03
// 8 ... fraction, 0.3/0
// 9 ... fraction, 0.3/0.03, squared
// 10 ... fraction, 0.3/0, squared
// 11 ... fraction, sqrt(0.3)/0.03, squared
// 12 ... fraction, sqrt(0.3)/0, squared
// 13 ... optimized
//
LaplaceProblem (int param, SolverType solver_type, int refinement_mode);
~LaplaceProblem ();
void run (double stop);
private:
void setup_system ();
void assemble_system ();
void solve ();
void refine_grid ();
double process_solution (const unsigned int cycle);
void output_results (const unsigned int cycle) const;
std::string itos(const unsigned int i) const // convert int to string
{
std::stringstream s;
s << i;
return s.str();
}
Triangulation<dim> triangulation;
DoFHandler<dim> dof_handler;
FE_Q<dim> fe;
ConstraintMatrix hanging_node_constraints;
SparsityPattern sparsity_pattern;
SparseMatrix<double> system_matrix;
Vector<double> solution;
Vector<double> system_rhs;
TableHandler convergence_table;
SolverType solver_type;
int refinement_mode;
int param;
};
template <int dim>
LaplaceProblem<dim>::LaplaceProblem (int param, SolverType solver_type, int refinement_mode)
: dof_handler (triangulation), fe (2),
solver_type (solver_type), param (param), refinement_mode (refinement_mode)
{}
template <int dim>
LaplaceProblem<dim>::~LaplaceProblem ()
{
dof_handler.clear ();
}
template <int dim>
void LaplaceProblem<dim>::setup_system ()
{
dof_handler.distribute_dofs (fe);
solution.reinit (dof_handler.n_dofs());
system_rhs.reinit (dof_handler.n_dofs());
hanging_node_constraints.clear ();
DoFTools::make_hanging_node_constraints (dof_handler,
hanging_node_constraints);
hanging_node_constraints.close ();
CompressedSparsityPattern c_sparsity(dof_handler.n_dofs());
DoFTools::make_sparsity_pattern (dof_handler, c_sparsity);
hanging_node_constraints.condense (c_sparsity);
sparsity_pattern.copy_from(c_sparsity);
system_matrix.reinit (sparsity_pattern);
}
template <int dim>
void LaplaceProblem<dim>::assemble_system ()
{
const QGauss<dim> quadrature_formula(6); // 6-point quadrature is the first one which integrates exactly polynomials of orders up to 10. This order is used in Hermes.
FEValues<dim> fe_values (fe, quadrature_formula,
update_values | update_gradients |
update_quadrature_points | update_JxW_values);
const unsigned int dofs_per_cell = fe.dofs_per_cell;
const unsigned int n_q_points = quadrature_formula.size();
FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell);
Vector<double> cell_rhs (dofs_per_cell);
std::vector<unsigned int> local_dof_indices (dofs_per_cell);
const RightHandSide<dim> right_hand_side(param);
std::vector<double> rhs_values (n_q_points);
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active(),
endc = dof_handler.end();
for (; cell!=endc; ++cell)
{
cell_matrix = 0;
cell_rhs = 0;
fe_values.reinit (cell);
right_hand_side.value_list (fe_values.get_quadrature_points(),
rhs_values);
for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
for (unsigned int j=0; j<dofs_per_cell; ++j)
cell_matrix(i,j) += (
fe_values.shape_grad(i,q_point) *
fe_values.shape_grad(j,q_point) *
fe_values.JxW(q_point));
cell_rhs(i) += (fe_values.shape_value(i,q_point) *
rhs_values [q_point] *
fe_values.JxW(q_point));
}
cell->get_dof_indices (local_dof_indices);
for (unsigned int i=0; i<dofs_per_cell; ++i)
{
for (unsigned int j=0; j<dofs_per_cell; ++j)
system_matrix.add (local_dof_indices[i],
local_dof_indices[j],
cell_matrix(i,j));
system_rhs(local_dof_indices[i]) += cell_rhs(i);
}
}
hanging_node_constraints.condense (system_matrix);
hanging_node_constraints.condense (system_rhs);
std::map<unsigned int,double> boundary_values;
VectorTools::interpolate_boundary_values (dof_handler,
0,
Solution<dim>(param),
boundary_values);
MatrixTools::apply_boundary_values (boundary_values,
system_matrix,
solution,
system_rhs);
// Hermes DOFs : dof_handler.n_dof() - boundary_values.size();
}
template <int dim>
void LaplaceProblem<dim>::solve ()
{
if (solver_type == CG)
{
SolverControl solver_control (1000, 1e-12);
SolverCG<> solver (solver_control);
PreconditionSSOR<> preconditioner;
preconditioner.initialize(system_matrix, 1.2);
solver.solve (system_matrix, solution, system_rhs, preconditioner);
}
else if (solver_type == UMFPACK)
{
SparseDirectUMFPACK solver;
solution = system_rhs;
solver.initialize<SparseMatrix<double> >(system_matrix);
solver.solve(solution);
}
hanging_node_constraints.distribute (solution);
}
template <int dim>
void LaplaceProblem<dim>::refine_grid ()
{
Assert (refinement_mod >= 0 && refinement_mode <= 13,
StandardExceptions::ExcIndexRange(refinement_mode, 0, 13));
if (refinement_mode == 0)
{
triangulation.refine_global (1);
return;
}
Vector<float> estimated_error_per_cell (triangulation.n_active_cells());
KellyErrorEstimator<dim>::estimate (dof_handler,
QGauss<dim-1>(3),
typename FunctionMap<dim>::type(),
solution,
estimated_error_per_cell);
switch (refinement_mode)
{
case 3:
case 4:
case 5:
case 6:
case 9:
case 10:
case 11:
case 12:
{
// Use squared element errors.
for (int i = 0; i < estimated_error_per_cell.size(); i++)
estimated_error_per_cell(i) *= estimated_error_per_cell(i);
break;
}
}
switch (refinement_mode)
{
case 1:
case 3:
{
GridRefinement::refine_and_coarsen_fixed_number(triangulation,
estimated_error_per_cell,
0.3, 0.03);
break;
}
case 2:
case 4:
{
GridRefinement::refine_and_coarsen_fixed_number(triangulation,
estimated_error_per_cell,
0.3, 0);
break;
}
case 5:
{
GridRefinement::refine_and_coarsen_fixed_number(triangulation,
estimated_error_per_cell,
sqrt(0.3), 0.03);
break;
}
case 6:
{
GridRefinement::refine_and_coarsen_fixed_number(triangulation,
estimated_error_per_cell,
sqrt(0.3), 0);
break;
}
case 7:
case 9:
{
GridRefinement::refine_and_coarsen_fixed_fraction(triangulation,
estimated_error_per_cell,
0.3, 0.03);
break;
}
case 8:
case 10:
{
GridRefinement::refine_and_coarsen_fixed_fraction(triangulation,
estimated_error_per_cell,
0.3, 0);
break;
}
case 11:
{
GridRefinement::refine_and_coarsen_fixed_fraction(triangulation,
estimated_error_per_cell,
sqrt(0.3), 0.03);
break;
}
case 12:
{
GridRefinement::refine_and_coarsen_fixed_fraction(triangulation,
estimated_error_per_cell,
sqrt(0.3), 0);
break;
}
case 13:
{
GridRefinement::refine_and_coarsen_optimize(triangulation,
estimated_error_per_cell);
break;
}
}
triangulation.execute_coarsening_and_refinement ();
}
template <int dim>
void LaplaceProblem<dim>::output_results (const unsigned int cycle) const
{
std::string filename = "grid-";
filename += itos(cycle);
filename += ".eps";
std::ofstream output (filename.c_str());
GridOut grid_out;
grid_out.write_eps (triangulation, output);
}
template <int dim>
double LaplaceProblem<dim>::process_solution(const unsigned int cycle)
{
Vector<double> difference_per_cell (triangulation.n_active_cells());
VectorTools::integrate_difference ( dof_handler,
solution,
Solution<dim>(param),
difference_per_cell,
QGauss<dim>(13),
VectorTools::H1_norm);
const double H1_error_exact = difference_per_cell.l2_norm();
const unsigned int n_dofs=dof_handler.n_dofs();
std::cout << "Cycle " << cycle << ':'
<< std::endl
<< " Number of degrees of freedom: "
<< n_dofs
<< std::endl
<< " H1 error w.r.t. exact soln.: "
<< H1_error_exact
<< std::endl;
convergence_table.add_value("cycle", cycle);
convergence_table.add_value("H1 error", H1_error_exact);
convergence_table.add_value("ndof", n_dofs);
return H1_error_exact;
}
template <int dim>
void LaplaceProblem<dim>::run (double stop)
{
double setup_time = 0, assemble_time = 0, solve_time = 0, adapt_time = 0;
double t_start = 0, t_end;
double accum_time;
Timer timer;
timer.start();
for (unsigned int cycle=0; true; ++cycle)
{
//std::cout << "Cycle " << cycle << ':' << std::endl;
t_start = timer.wall_time();
if (cycle == 0)
{
GridGenerator::hyper_cube (triangulation, 0, 1);
triangulation.refine_global (2);
}
else
refine_grid ();
t_end = timer.wall_time();
adapt_time += t_end - t_start;
t_start = timer.wall_time();
setup_system ();
t_end = timer.wall_time();
setup_time += t_end - t_start;
t_start = timer.wall_time();
assemble_system ();
t_end = timer.wall_time();
assemble_time += t_end - t_start;
t_start = timer.wall_time();
solve ();
t_end = timer.wall_time();
solve_time += t_end - t_start;
//output_results (cycle);
t_start = timer.wall_time();
double abs_err = process_solution(cycle);
t_end = timer.wall_time();
adapt_time += t_end - t_start;
accum_time = timer.wall_time();
convergence_table.add_value("total time", accum_time);
convergence_table.add_value("setup time", setup_time);
convergence_table.add_value("assem time", assemble_time);
convergence_table.add_value("solve time", solve_time);
convergence_table.add_value("adapt time", adapt_time);
if (abs_err < stop || dof_handler.n_dofs() > 60000)
break;
}
timer.stop();
/*
DataOutBase::EpsFlags eps_flags;
eps_flags.z_scaling = 1./4.;
eps_flags.azimut_angle = 0;
eps_flags.turn_angle = 0;
DataOut<dim> data_out;
data_out.set_flags (eps_flags);
data_out.attach_dof_handler (dof_handler);
data_out.add_data_vector (solution, "solution");
data_out.build_patches ();
std::ofstream output ("final-solution.eps");
data_out.write_eps (output);
*/
GridOut grid_out;
std::ofstream output(("final_mesh-"+itos(refinement_mode)+".eps").c_str());
GridOutFlags::Eps<2> flags(GridOutFlags::Eps<2>::width, 800);
grid_out.set_flags(flags);
grid_out.write_eps (triangulation, output);
convergence_table.set_precision("H1 error", 4);
convergence_table.set_scientific("H1 error", true);
convergence_table.set_precision("total time", 3);
convergence_table.set_precision("setup time", 3);
convergence_table.set_precision("assem time", 3);
convergence_table.set_precision("solve time", 3);
convergence_table.set_precision("adapt time", 3);
std::cout << std::endl;
convergence_table.write_text(std::cout);
std::ofstream fout(("conv_table-"+itos(refinement_mode)+".dat").c_str());
convergence_table.write_text(fout);
fout.close();
}
int main ()
{
try
{
deallog.depth_console (0);
for (int i = 1; i <= 13; i++)
{
LaplaceProblem<2> laplace_problem_2d(3, UMFPACK, i);
laplace_problem_2d.run (0.1);
}
}
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
return 0;
}
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/02-reentrant-corner/definitions.h | .h | 695 | 31 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double alpha)
: ExactSolutionScalar<double>(mesh), alpha(alpha) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
double get_angle(double y, double x) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, alpha); }
double alpha;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/02-reentrant-corner/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/02-reentrant-corner/main.cpp | .cpp | 7,814 | 222 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the second in the series of NIST benchmarks with known exact solutions. This benchmark
// has four different versions, use the global variable PARAM below to switch among them.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// PDE: -Laplace u = 0
//
// Known exact solution: (pow(sqrt(x*x + y*y), alpha) * sin(alpha * atan2(y,x))).
// See functions fn() and fndd() in "exact_solution.cpp".
//
// Domain: square (-1, 1)^2, with a section removed from the clockwise side of the positive x-axis.
//
// BC: Dirichlet, given by exact solution.
//
// The following parameters can be changed:
// PARAM determines which parameter values you wish to use for the strength of the singularity in
// the current (nist-2) Reentrant Corner problem.
// PARAM strength omega alpha
// 0: 1 5*Pi/4 4/5
// 1: 2 3*Pi/2 2/3
// 2: 3 7*Pi/4 4/7
// 3: 4 2*Pi 1/2
int PARAM = 1;
// Initial polynomial degree of mesh elements.
const int P_INIT = 3;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-2;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
double alpha = 0, omega = 0;
switch (PARAM)
{
case 0:
mloader.load("geom0.mesh", mesh);
omega = ((5.0 * M_PI) / 4.0);
alpha = (M_PI / omega);
break;
case 1:
mloader.load("geom1.mesh", mesh);
omega = ((3.0 * M_PI) / 2.0);
alpha = (M_PI / omega);
break;
case 2:
mloader.load("geom2.mesh", mesh);
omega = ((7.0 * M_PI) / 4.0);
alpha = (M_PI / omega);
break;
case 3: mloader.load("geom3.mesh", mesh);
omega = (2.0 * M_PI);
alpha = (M_PI / omega);
break;
default: throw Hermes::Exceptions::Exception("Admissible values of PARAM are 0, 1, 2, 3.");
}
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, alpha));
// Initialize weak formulation.
Hermes1DFunction<double> lambda(1.0);
WeakFormSharedPtr<double> wf(new WeakFormsH1::DefaultWeakFormLaplace<double>(HERMES_ANY, &lambda));
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, exact_sln);
double err_exact_rel = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/02-reentrant-corner/definitions.cpp | .cpp | 973 | 32 | #include "definitions.h"
double CustomExactSolution::value(double x, double y) const
{
return (Hermes::pow(Hermes::sqrt(x*x + y*y), alpha) * Hermes::sin(alpha * get_angle(y, x)));
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double a = Hermes::sqrt(x*x + y*y);
double b = Hermes::pow(a, (alpha - 1.0));
double c = Hermes::pow(a, alpha);
double d = ((y*y) / (x*x) + 1.0);
dx = (((alpha * x * Hermes::sin(alpha * get_angle(y, x)) * b) / a)
- ((alpha * y * Hermes::cos(alpha * get_angle(y, x)) * c) / (Hermes::pow(x, 2.0) *d)));
dy = (((alpha * Hermes::cos(alpha * get_angle(y, x)) * c) / (x * d))
+ ((alpha * y * Hermes::sin(alpha* get_angle(y, x)) * b) / a));
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(10);
}
double CustomExactSolution::get_angle(double y, double x) const
{
double theta = Hermes::atan2(y, x);
if (theta < 0)
theta += 2 * M_PI;
return theta;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/11-kellogg/definitions.h | .h | 889 | 36 | #include "hermes2d.h"
#include "../NIST-util.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
/* Exact solution */
class CustomExactSolution : public ExactSolutionScalar<double>
{
public:
CustomExactSolution(MeshSharedPtr mesh, double sigma, double tau, double rho)
: ExactSolutionScalar<double>(mesh), sigma(sigma), tau(tau), rho(rho) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord (double x, double y) const;
MeshFunction<double>* clone() const { return new CustomExactSolution(mesh, sigma, tau, rho); }
double sigma;
double tau;
double rho;
};
/* Weak forms */
class CustomWeakFormPoisson : public WeakForm<double>
{
public:
CustomWeakFormPoisson(std::string area_1, double r, std::string area_2);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/11-kellogg/plot_graph.py | .py | 898 | 42 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.yscale("log")
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_exact.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (exact)")
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/11-kellogg/main.cpp | .cpp | 7,012 | 197 | #include "definitions.h"
using namespace RefinementSelectors;
// This is the 11th in the series of NIST benchmarks with known exact solutions.
//
// Reference: W. Mitchell, A Collection of 2D Elliptic Problems for Testing Adaptive Algorithms,
// NIST Report 7668, February 2010.
//
// The solution contains a very strong singularity that represents a challenge for most
// adaptive methods. While running this benchmark, note how much the error is underestimated.
//
// PDE: -div(A(x,y) grad u) = 0
// where a(x,y) = R in the first and third quadrant
// = 1 in the second and fourth quadrant
//
// Exact solution: u(x,y) = cos(M_PI*y/2) for x < 0
// u(x,y) = cos(M_PI*y/2) + pow(x, alpha) for x > 0 where alpha > 0.
//
// Domain: Square (-1,1)^2.
//
// BC: Dirichlet given by exact solution.
//
// The following parameters can be changed:
const double R = 161.4476387975881;
const double TAU = 0.1;
const double RHO = M_PI / 4.;
const double SIGMA = -14.92256510455152;
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of Adaptivity.
const double THRESHOLD = 0.3;
// This is a stopping criterion for Adaptivity.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO_H;
// Maximum allowed level of hanging nodes.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
const double ERR_STOP = 5.0;
const CalculatedErrorType errorType = RelativeErrorToGlobalNorm;
// Newton tolerance
const double NEWTON_TOLERANCE = 1e-6;
bool HERMES_VISUALIZATION = false;
bool VTK_VISUALIZATION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square_quad.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set exact solution.
MeshFunctionSharedPtr<double> exact_sln(new CustomExactSolution(mesh, SIGMA, TAU, RHO));
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormPoisson("Mat_0", R, "Mat_1"));
// Initialize boundary conditions
DefaultEssentialBCNonConst<double> bc_essential("Bdy", exact_sln);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Initialize approximate solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
// Initialize refinement selector.
MySelector selector(CAND_LIST);
// Initialize views.
Views::ScalarView sview("Solution", new Views::WinGeom(0, 0, 440, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
Views::OrderView oview("Polynomial orders", new Views::WinGeom(450, 0, 420, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
cpu_time.tick();
// Construct globally refined reference mesh and setup reference space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d (%d DOF):", as, ndof_ref);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Assemble the discrete problem.
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Solution: %g s", cpu_time.last());
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors and total error estimate.
DefaultErrorCalculator<double, HERMES_H1_NORM> error_calculator(errorType, 1);
error_calculator.calculate_errors(sln, exact_sln);
double err_exact_rel = error_calculator.get_total_error_squared() * 100.0;
error_calculator.calculate_errors(sln, ref_sln);
double err_est_rel = error_calculator.get_total_error_squared() * 100.0;
Adapt<double> adaptivity(space, &error_calculator);
adaptivity.set_strategy(&stoppingCriterion);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Error calculation: %g s", cpu_time.last());
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d", space->get_num_dofs(), ref_space->get_num_dofs());
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel);
// Time measurement.
cpu_time.tick();
double accum_time = cpu_time.accumulated();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(space->get_num_dofs(), err_est_rel);
graph_dof_est.save("conv_dof_est.dat");
graph_cpu_est.add_values(accum_time, err_est_rel);
graph_cpu_est.save("conv_cpu_est.dat");
graph_dof_exact.add_values(space->get_num_dofs(), err_exact_rel);
graph_dof_exact.save("conv_dof_exact.dat");
graph_cpu_exact.add_values(accum_time, err_exact_rel);
graph_cpu_exact.save("conv_cpu_exact.dat");
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh. The NDOF test must be here, so that the solution may be visualized
// after ending due to this criterion.
if (err_exact_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
cpu_time.tick();
Hermes::Mixins::Loggable::Static::info("Adaptation: %g s", cpu_time.last());
// Increase the counter of adaptivity steps.
if (done == false)
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-benchmarks-nist/11-kellogg/definitions.cpp | .cpp | 3,771 | 71 | #include "definitions.h"
double CustomExactSolution::value(double x, double y) const
{
double theta = Hermes::atan2(y, x);
if (theta < 0) theta = theta + 2.*M_PI;
double r = Hermes::sqrt(x*x + y*y);
double mu;
if (theta <= M_PI / 2.)
mu = Hermes::cos((M_PI / 2. - sigma)*tau) * Hermes::cos((theta - M_PI / 2. + rho)*tau);
else if (theta <= M_PI)
mu = Hermes::cos(rho*tau) * Hermes::cos((theta - M_PI + sigma)*tau);
else if (theta <= 3.*M_PI / 2.)
mu = Hermes::cos(sigma*tau) * Hermes::cos((theta - M_PI - rho)*tau);
else
mu = Hermes::cos((M_PI / 2. - rho)*tau) * Hermes::cos((theta - 3.*M_PI / 2. - sigma)*tau);
return Hermes::pow(r, tau) * mu;
}
void CustomExactSolution::derivatives(double x, double y, double& dx, double& dy) const
{
double theta = Hermes::atan2(y, x);
if (theta < 0) theta = theta + 2 * M_PI;
double r = Hermes::sqrt(x*x + y*y);
// x-derivative
if (theta <= M_PI / 2.)
dx = tau*x*Hermes::pow(r, (2.*(-1 + tau / 2.))) * Hermes::cos((M_PI / 2. - sigma)*tau) * Hermes::cos(tau*(-M_PI / 2. + rho + theta))
+ (tau*y*Hermes::pow(r, tau)*Hermes::cos((M_PI / 2. - sigma)*tau) * Hermes::sin(tau*(-M_PI / 2. + rho + theta)) / (r*r));
else if (theta <= M_PI)
dx = tau*x * Hermes::pow(r, (2.*(-1 + tau / 2.))) * Hermes::cos(rho*tau) * Hermes::cos(tau*(-M_PI + sigma + theta))
+ (tau*y * Hermes::pow(r, tau) * Hermes::cos(rho*tau) * Hermes::sin(tau*(-M_PI + sigma + theta)) / (r*r));
else if (theta <= 3.*M_PI / 2.)
dx = tau*x * Hermes::pow(r, (2.*(-1 + tau / 2.))) * Hermes::cos(sigma*tau) * Hermes::cos(tau*(-M_PI - rho + theta))
+ (tau*y * Hermes::pow(r, tau) * Hermes::cos(sigma*tau) * Hermes::sin(tau*(-M_PI - rho + theta)) / (r*r));
else
dx = tau*x* Hermes::pow(r, (2 * (-1 + tau / 2.))) * Hermes::cos((M_PI / 2. - rho)*tau) * Hermes::cos(tau*(-3.*M_PI / 2. - sigma + theta))
+ (tau*y*Hermes::pow(r, tau) * Hermes::cos((M_PI / 2. - rho)*tau) * Hermes::sin(tau*(-3.*M_PI / 2. - sigma + theta)) / (r*r));
// y-derivative
if (theta <= M_PI / 2.)
dy = tau*y * Hermes::pow(r, (2 * (-1 + tau / 2.))) * Hermes::cos((M_PI / 2. - sigma)*tau) * Hermes::cos(tau*(-M_PI / 2. + rho + theta))
- (tau * Hermes::pow(r, tau) * Hermes::cos((M_PI / 2. - sigma)*tau) *Hermes::sin(tau*(-M_PI / 2. + rho + theta))*x / (r*r));
else if (theta <= M_PI)
dy = tau*y* Hermes::pow(r, (2 * (-1 + tau / 2.))) * Hermes::cos(rho*tau) * Hermes::cos(tau*(-M_PI + sigma + theta))
- (tau * Hermes::pow(r, tau) * Hermes::cos(rho*tau) * Hermes::sin(tau*(-M_PI + sigma + theta))*x / (r*r));
else if (theta <= 3.*M_PI / 2.)
dy = tau*y * Hermes::pow(r, (2 * (-1 + tau / 2.))) * Hermes::cos(sigma*tau) * Hermes::cos(tau*(-M_PI - rho + theta))
- (tau * Hermes::pow(r, tau) * Hermes::cos(sigma*tau) * Hermes::sin(tau*(-M_PI - rho + theta))*x / (r*r));
else
dy = tau*y * Hermes::pow(r, (2 * (-1 + tau / 2.))) * Hermes::cos((M_PI / 2. - rho)*tau) * Hermes::cos(tau*(-3.*M_PI / 2. - sigma + theta))
- (tau * Hermes::pow(r, tau) * Hermes::cos((M_PI / 2. - rho)*tau) * Hermes::sin(tau*((-3.*M_PI) / 2. - sigma + theta))*x / (r*r));
}
Ord CustomExactSolution::ord(double x, double y) const
{
return Ord(6);
}
CustomWeakFormPoisson::CustomWeakFormPoisson(std::string area_1, double r, std::string area_2) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, area_1, new Hermes1DFunction<double>(r)));
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, area_2, nullptr));
// Residual.
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(0, area_1, new Hermes1DFunction<double>(r)));
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(0, area_2, nullptr));
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/wave-equation/wave-1/definitions.h | .h | 2,178 | 74 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Initial condition */
class CustomInitialConditionWave : public ExactSolutionScalar < double >
{
public:
CustomInitialConditionWave(MeshSharedPtr mesh) : ExactSolutionScalar<double>(mesh) {};
virtual double value(double x, double y) const;
virtual void derivatives(double x, double y, double& dx, double& dy) const;
virtual Ord ord(double x, double y) const;
virtual MeshFunction<double>* clone() const;
};
/* Weak forms */
class CustomWeakFormWave : public WeakForm < double >
{
public:
CustomWeakFormWave(double tau, double c_squared, MeshFunctionSharedPtr<double> u_prev_sln, MeshFunctionSharedPtr<double> v_prev_sln);
private:
class VectorFormVolWave_0 : public VectorFormVol < double >
{
public:
VectorFormVolWave_0() : VectorFormVol<double>(0) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const;
virtual VectorFormVol<double>* clone() const;
};
class VectorFormVolWave_1 : public VectorFormVol < double >
{
public:
VectorFormVolWave_1(double c_squared)
: VectorFormVol<double>(1), c_squared(c_squared) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const;
virtual VectorFormVol<double>* clone() const;
double c_squared;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/wave-equation/wave-1/main.cpp | .cpp | 8,866 | 215 | #include "definitions.h"
// This example solves a simple linear wave equation by converting it
// into a system of two first-order equations in time. Time discretization
// is performed using arbitrary (explicit or implicit, low-order or higher-order)
// Runge-Kutta methods entered via their Butcher's tables.
// For a list of available R-K methods see the file hermes_common/tables.h.
//
// The function rk_time_step_newton() needs more optimisation, see a todo list at
// the beginning of file src/runge-kutta.h.
//
// PDE: \frac{1}{C_SQUARED}\frac{\partial^2 u}{\partial t^2} - \Delta u = 0,
// converted into
//
// \frac{\partial u}{\partial t} = v,
// \frac{\partial v}{\partial t} = C_SQUARED * \Delta u.
//
// BC: u = 0 on the boundary,
// v = 0 on the boundary (u = 0 => \partial u / \partial t = 0).
//
// IC: smooth peak for u, zero for v.
//
// The following parameters can be changed:
// Initial polynomial degree of all elements.
const int P_INIT = 2;
// Refinement.
const int INIT_REF_NUM = 3;
// Time step.
const double INITIAL_TIME_STEP = 1e-2;
// If rel. temporal error is greater than this threshold, decrease time
// step size and repeat time step.
const double time_tol_upper = 100.0;
// If rel. temporal error is less than this threshold, increase time step
// but do not repeat time step (this might need further research).
const double time_tol_lower = 0.1;
// Timestep decrease ratio after unsuccessful nonlinear solve.
double time_step_dec = 0.5;
// Timestep increase ratio after successful nonlinear solve.
double time_step_inc = 2.0;
// Computation will stop if time step drops below this value.
double time_step_min = 1e-8;
// Final time.
const double T_FINAL = 20.;
// Choose one of the following time-integration methods, or define your own Butcher's table. The last number
// in the name of each method is its order. The one before last, if present, is the number of stages.
// Explicit methods:
// Explicit_RK_1, Explicit_RK_2, Explicit_RK_3, Explicit_RK_4.
// Implicit methods:
// Implicit_RK_1, Implicit_Crank_Nicolson_2_2, Implicit_SIRK_2_2, Implicit_ESIRK_2_2, Implicit_SDIRK_2_2,
// Implicit_Lobatto_IIIA_2_2, Implicit_Lobatto_IIIB_2_2, Implicit_Lobatto_IIIC_2_2, Implicit_Lobatto_IIIA_3_4,
// Implicit_Lobatto_IIIB_3_4, Implicit_Lobatto_IIIC_3_4, Implicit_Radau_IIA_3_5, Implicit_SDIRK_5_4.
// Embedded explicit methods:
// Explicit_HEUN_EULER_2_12_embedded.
// Embedded implicit methods:
// Implicit_SDIRK_CASH_3_23_embedded, Implicit_ESDIRK_TRBDF2_3_23_embedded, Implicit_ESDIRK_TRX2_3_23_embedded,
// Implicit_SDIRK_BILLINGTON_3_23_embedded, Implicit_SDIRK_CASH_5_24_embedded, Implicit_SDIRK_CASH_5_34_embedded,
// Implicit_DIRK_ISMAIL_7_45_embedded.
ButcherTableType butcher_table_type = Implicit_RK_1;
// Problem parameters.
// Square of wave speed.
const double C_SQUARED = 100;
int main(int argc, char* argv[])
{
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table_type);
if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Refine towards boundary.
mesh->refine_towards_boundary("Bdy", 1, true);
// Refine once towards vertex #4.
mesh->refine_towards_vertex(4, 1);
// Refine all.
for (int i = 0; i < INIT_REF_NUM; i++)
mesh->refine_all_elements();
// Initialize solutions.
MeshFunctionSharedPtr<double> u_sln(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> v_sln(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > slns({ u_sln, v_sln });
// - previous ones.
MeshFunctionSharedPtr<double> u_prev_sln(new CustomInitialConditionWave(mesh));
MeshFunctionSharedPtr<double> v_prev_sln(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > prev_slns({ u_prev_sln, v_prev_sln });
// - time error functions.
MeshFunctionSharedPtr<double> u_time_error_fn(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> v_time_error_fn(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > time_error_fns({ u_time_error_fn, v_time_error_fn });
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormWave(INITIAL_TIME_STEP, C_SQUARED, u_prev_sln, v_prev_sln));
// Initialize boundary conditions
DefaultEssentialBCConst<double> bc_essential("Bdy", 0.0);
EssentialBCs<double> bcs(&bc_essential);
SpaceSharedPtr<double> u_space(new H1Space<double>(mesh, &bcs, P_INIT));
SpaceSharedPtr<double> v_space(new H1Space<double>(mesh, &bcs, P_INIT));
Hermes::Mixins::Loggable::Static::info("ndof = %d.", Space<double>::get_num_dofs({ u_space, v_space }));
// Initialize views.
ScalarView u_view("Solution u", new WinGeom(0, 0, 500, 400));
u_view.fix_scale_width(50);
ScalarView v_view("Solution v", new WinGeom(510, 0, 500, 400));
v_view.fix_scale_width(50);
ScalarView e_u_view("Temporal error u", new WinGeom(0, 410, 500, 400));
e_u_view.fix_scale_width(50);
ScalarView e_v_view("Temporal error v", new WinGeom(510, 410, 500, 400));
e_v_view.fix_scale_width(50);
// Visualize the solutions.
char title[100];
sprintf(title, "Initial Solution u");
u_view.set_title(title);
u_view.show(u_prev_sln);
sprintf(title, "Initial Solution v");
v_view.set_title(title);
v_view.show(v_prev_sln);
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, { u_space, v_space }, &bt);
runge_kutta.set_verbose_output(true);
// Time stepping loop.
double current_time = INITIAL_TIME_STEP; int ts = 1; double time_step = INITIAL_TIME_STEP;
do
{
// Perform one Runge-Kutta time step according to the selected Butcher's table.
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step (t = %g s, time_step = %g s, stages: %d).",
current_time, time_step, bt.get_size());
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
// If we can, we will be interested in time error.
if (bt.is_embedded())
runge_kutta.rk_time_step_newton(prev_slns, slns, time_error_fns);
else
runge_kutta.rk_time_step_newton(prev_slns, slns);
}
catch (Exceptions::Exception& e)
{
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step failed, decreasing time step.");
current_time -= time_step;
time_step *= time_step_dec;
continue;
if (time_step < time_step_min)
throw Hermes::Exceptions::Exception("Time step became too small.");
e.print_msg();
}
// Time error handling
if (bt.is_embedded())
{
// Show error functions.
e_u_view.show(u_time_error_fn);
e_v_view.show(v_time_error_fn);
// Calculate relative time stepping error and decide whether the
// time step can be accepted. If not, then the time step size is
// reduced and the entire time step repeated. If yes, then another
// check is run, and if the relative error is very low, time step
// is increased.
DefaultNormCalculator<double, HERMES_H1_NORM> normCalculator(2);
normCalculator.calculate_norms(time_error_fns);
double rel_err_time = normCalculator.get_total_norm_squared() * 100.;
Hermes::Mixins::Loggable::Static::info("rel_err_time = %g%%", rel_err_time);
if (rel_err_time > time_tol_upper) {
Hermes::Mixins::Loggable::Static::info("rel_err_time above upper limit %g%% -> decreasing time step from %g to %g days and repeating time step.",
time_tol_upper, time_step, time_step * time_step_dec);
time_step *= time_step_dec;
continue;
}
if (rel_err_time < time_tol_lower) {
Hermes::Mixins::Loggable::Static::info("rel_err_time = below lower limit %g%% -> increasing time step from %g to %g days",
time_tol_lower, time_step, time_step * time_step_inc);
time_step *= time_step_inc;
}
}
// Advance the solutions.
u_prev_sln->copy(u_sln);
v_prev_sln->copy(v_sln);
// Visualize the solutions.
char title[100];
sprintf(title, "Solution u, t = %g", current_time);
u_view.set_title(title);
u_view.show(u_sln);
sprintf(title, "Solution v, t = %g", current_time);
v_view.set_title(title);
v_view.show(v_sln);
// Update time.
current_time += time_step;
} while (current_time < T_FINAL);
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/wave-equation/wave-1/definitions.cpp | .cpp | 2,963 | 92 | #include "definitions.h"
double CustomInitialConditionWave::value(double x, double y) const
{
return exp(-x*x - y*y);
}
void CustomInitialConditionWave::derivatives(double x, double y, double& dx, double& dy) const
{
dx = exp(-x*x - y*y) * (-2 * x);
dy = exp(-x*x - y*y) * (-2 * y);
}
Ord CustomInitialConditionWave::ord(double x, double y) const
{
return Ord(10);
}
MeshFunction<double>* CustomInitialConditionWave::clone() const
{
return new CustomInitialConditionWave(this->mesh);
}
CustomWeakFormWave::CustomWeakFormWave(double tau, double c_squared, MeshFunctionSharedPtr<double> u_prev_sln,
MeshFunctionSharedPtr<double> v_prev_sln) : WeakForm<double>(2)
{
// Volumetric matrix forms.
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<double>(0, 1, HERMES_ANY, new Hermes2DFunction<double>(1.0), HERMES_NONSYM));
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(1, 0, HERMES_ANY, new Hermes1DFunction<double>(-c_squared), HERMES_NONSYM));
// Volumetric surface forms.
add_vector_form(new VectorFormVolWave_0());
add_vector_form(new VectorFormVolWave_1(c_squared));
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormWave::VectorFormVolWave_0::vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += wt[i] * u_ext[1]->val[i] * v->val[i];
return result;
}
double CustomWeakFormWave::VectorFormVolWave_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakFormWave::VectorFormVolWave_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomWeakFormWave::VectorFormVolWave_0::clone() const
{
return new VectorFormVolWave_0(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormWave::VectorFormVolWave_1::vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += wt[i] * (u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i]);
return -c_squared * result;
}
double CustomWeakFormWave::VectorFormVolWave_1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakFormWave::VectorFormVolWave_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomWeakFormWave::VectorFormVolWave_1::clone() const
{
return new VectorFormVolWave_1(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/schroedinger/gross-pitaevski/definitions.h | .h | 2,569 | 81 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
typedef std::complex<double> complex;
/* Initial condition */
class CustomInitialCondition : public ExactSolutionScalar < ::complex >
{
public:
CustomInitialCondition(MeshSharedPtr mesh) : ExactSolutionScalar<::complex>(mesh) {};
virtual void derivatives(double x, double y, std::complex<double> & dx, std::complex<double> & dy) const;
virtual std::complex<double> value(double x, double y) const;
virtual Ord ord(double x, double y) const;
virtual MeshFunction<::complex>* clone() const;
};
/* Weak forms */
class CustomWeakFormGPRK : public WeakForm < ::complex >
{
public:
CustomWeakFormGPRK(double h, double m, double g, double omega);
private:
class CustomFormMatrixFormVol : public MatrixFormVol < ::complex >
{
public:
CustomFormMatrixFormVol(unsigned int i, unsigned int j, double h, double m, double g, double omega)
: MatrixFormVol<::complex>(i, j), h(h), m(m), g(g), omega(omega) {};
template<typename Real, typename Scalar>
Scalar matrix_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual std::complex<double> value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<::complex> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u,
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const;
virtual MatrixFormVol<::complex>* clone() const;
// Members.
double h, m, g, omega;
};
class CustomFormVectorFormVol : public VectorFormVol < ::complex >
{
public:
CustomFormVectorFormVol(int i, double h, double m, double g, double omega)
: VectorFormVol<::complex>(i), h(h), m(m), g(g), omega(omega) {};
template<typename Real, typename Scalar>
Scalar vector_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual std::complex<double> value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<::complex> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const;
virtual VectorFormVol<::complex>* clone() const;
// Members.
double h, m, g, omega;
};
double h, m, g, omega;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/schroedinger/gross-pitaevski/main.cpp | .cpp | 5,777 | 148 | #include "definitions.h"
// This example uses the Newton's method to solve a nonlinear complex-valued
// time-dependent PDE (the Gross-Pitaevski equation describing the behavior
// of Einstein-Bose quantum gases). For time-discretization one can use either
// the first-order implicit Euler method or the second-order Crank-Nicolson
// method.
//
// PDE: non-stationary complex Gross-Pitaevski equation
// describing resonances in Bose-Einstein condensates.
//
// ih \partial \psi/\partial t = -h^2/(2m) \Delta \psi +
// g \psi |\psi|^2 + 1/2 m \omega^2 (x^2 + y^2) \psi.
//
// Domain: square (-1, 1)^2.
//
// BC: homogeneous Dirichlet everywhere on the boundary.
// Number of initial uniform refinements.
const int INIT_REF_NUM = 3;
// Initial polynomial degree.
const int P_INIT = 4;
// Time step.
double time_step = 0.005;
// Time interval length.
const double T_FINAL = 2;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-5;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 100;
// Choose one of the following time-integration methods, or define your own Butcher's table. The last number
// in the name of each method is its order. The one before last, if present, is the number of stages.
// Explicit methods:
// Explicit_RK_1, Explicit_RK_2, Explicit_RK_3, Explicit_RK_4.
// Implicit methods:
// Implicit_RK_1, Implicit_Crank_Nicolson_2_2, Implicit_SIRK_2_2, Implicit_ESIRK_2_2, Implicit_SDIRK_2_2,
// Implicit_Lobatto_IIIA_2_2, Implicit_Lobatto_IIIB_2_2, Implicit_Lobatto_IIIC_2_2, Implicit_Lobatto_IIIA_3_4,
// Implicit_Lobatto_IIIB_3_4, Implicit_Lobatto_IIIC_3_4, Implicit_Radau_IIA_3_5, Implicit_SDIRK_5_4.
// Embedded explicit methods:
// Explicit_HEUN_EULER_2_12_embedded, Explicit_BOGACKI_SHAMPINE_4_23_embedded, Explicit_FEHLBERG_6_45_embedded,
// Explicit_CASH_KARP_6_45_embedded, Explicit_DORMAND_PRINCE_7_45_embedded.
// Embedded implicit methods:
// Implicit_SDIRK_CASH_3_23_embedded, Implicit_ESDIRK_TRBDF2_3_23_embedded, Implicit_ESDIRK_TRX2_3_23_embedded,
// Implicit_SDIRK_BILLINGTON_3_23_embedded, Implicit_SDIRK_CASH_5_24_embedded, Implicit_SDIRK_CASH_5_34_embedded,
// Implicit_DIRK_ISMAIL_7_45_embedded.
ButcherTableType butcher_table_type = Implicit_SDIRK_2_2;
// Problem constants
// Planck constant 6.626068e-34.
const double h = 1;
// Mass of boson.
const double m = 1;
// Coupling constant.
const double g = 1;
// Frequency.
const double omega = 1;
int main(int argc, char* argv[])
{
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table_type);
if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", mesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Convert initial condition into a Solution<::complex>.
MeshFunctionSharedPtr<::complex> psi_time_prev(new CustomInitialCondition(mesh));
MeshFunctionSharedPtr<::complex> psi_time_new(new Solution<::complex>(mesh));
// Initialize the weak formulation.
double current_time = 0;
WeakFormSharedPtr<::complex> wf(new CustomWeakFormGPRK(h, m, g, omega));
// Initialize boundary conditions.
DefaultEssentialBCConst<::complex> bc_essential("Bdy", 0.0);
EssentialBCs<::complex> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<::complex> space(new H1Space<::complex>(mesh, &bcs, P_INIT));
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
// Initialize the FE problem.
DiscreteProblem<::complex> dp(wf, space);
// Initialize views.
ScalarView sview_real("Solution - real part", new WinGeom(0, 0, 600, 500));
ScalarView sview_imag("Solution - imaginary part", new WinGeom(610, 0, 600, 500));
sview_real.fix_scale_width(80);
sview_imag.fix_scale_width(80);
// Initialize Runge-Kutta time stepping.
RungeKutta<::complex> runge_kutta(wf, space, &bt);
// Time stepping:
int ts = 1;
int nstep = (int)(T_FINAL / time_step + 0.5);
for (int ts = 1; ts <= nstep; ts++)
{
// Perform one Runge-Kutta time step according to the selected Butcher's table.
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step (t = %g s, time step = %g s, stages: %d).",
current_time, time_step, bt.get_size());
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
runge_kutta.rk_time_step_newton(psi_time_prev, psi_time_new);
}
catch (Exceptions::Exception& e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
}
// Show the new time level solution.
char title[100];
sprintf(title, "Solution - real part, Time %3.2f s", current_time);
sview_real.set_title(title);
sprintf(title, "Solution - imaginary part, Time %3.2f s", current_time);
sview_imag.set_title(title);
MeshFunctionSharedPtr<double> real(new RealFilter(psi_time_new));
MeshFunctionSharedPtr<double> imag(new ImagFilter(psi_time_new));
sview_real.show(real);
sview_imag.show(imag);
// Copy solution for the new time step.
psi_time_prev->copy(psi_time_new);
// Increase current time and time step counter.
current_time += time_step;
ts++;
}
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/schroedinger/gross-pitaevski/definitions.cpp | .cpp | 3,860 | 98 | #include "definitions.h"
void CustomInitialCondition::derivatives(double x, double y, std::complex<double> & dx, std::complex<double> & dy) const
{
std::complex<double> val = exp(-10 * (x*x + y*y));
dx = val * (-20.0 * x);
dy = val * (-20.0 * y);
}
std::complex<double> CustomInitialCondition::value(double x, double y) const
{
return exp(-10 * (x*x + y*y));
}
Ord CustomInitialCondition::ord(double x, double y) const
{
return Ord(20);
}
MeshFunction<::complex>* CustomInitialCondition::clone() const
{
return new CustomInitialCondition(this->mesh);
}
CustomWeakFormGPRK::CustomWeakFormGPRK(double h, double m, double g, double omega) : WeakForm<::complex>(1)
{
// Jacobian volumetric part.
add_matrix_form(new CustomFormMatrixFormVol(0, 0, h, m, g, omega));
// Residual - volumetric.
add_vector_form(new CustomFormVectorFormVol(0, h, m, g, omega));
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormGPRK::CustomFormMatrixFormVol::matrix_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
std::complex<double> ii = std::complex<double>(0.0, 1.0); // imaginary unit, ii^2 = -1
Scalar result = Scalar(0);
Func<Scalar>* psi_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (h*h / (2 * m*ii*h) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ 2 * g / (ii*h)* u->val[i] * psi_prev_newton->val[i] * conj(psi_prev_newton->val[i]) * v->val[i]
+ (g / ii*h) * psi_prev_newton->val[i] * psi_prev_newton->val[i] * u->val[i] * v->val[i]
+ .5*m*omega*omega / (ii*h) * (e->x[i] * e->x[i] + e->y[i] * e->y[i]) * u->val[i] * v->val[i]);
return result;
}
std::complex<double> CustomWeakFormGPRK::CustomFormMatrixFormVol::value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<::complex> **ext) const
{
return matrix_form_rk<double, std::complex<double> >(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakFormGPRK::CustomFormMatrixFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u,
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form_rk<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<::complex>* CustomWeakFormGPRK::CustomFormMatrixFormVol::clone() const
{
return new CustomFormMatrixFormVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormGPRK::CustomFormVectorFormVol::vector_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const
{
std::complex<double> ii = std::complex<double>(0.0, 1.0); // imaginary unit, ii^2 = -1
Scalar result = Scalar(0);
Func<Scalar>* psi_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (h*h / (2 * m*ii*h) * (psi_prev_newton->dx[i] * v->dx[i] + psi_prev_newton->dy[i] * v->dy[i])
+ 2 * g / (ii*h)* psi_prev_newton->val[i] * psi_prev_newton->val[i] * conj(psi_prev_newton->val[i]) * v->val[i]
+ (g / ii*h) * psi_prev_newton->val[i] * psi_prev_newton->val[i] * psi_prev_newton->val[i] * v->val[i]
+ .5*m*omega*omega / (ii*h) * (e->x[i] * e->x[i] + e->y[i] * e->y[i]) * psi_prev_newton->val[i] * v->val[i]);
return result;
}
std::complex<double> CustomWeakFormGPRK::CustomFormVectorFormVol::value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<::complex> **ext) const
{
return vector_form_rk<double, std::complex<double> >(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakFormGPRK::CustomFormVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return vector_form_rk<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<::complex>* CustomWeakFormGPRK::CustomFormVectorFormVol::clone() const
{
return new CustomFormVectorFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/schroedinger/gross-pitaevski-adapt/definitions.h | .h | 2,545 | 80 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
typedef std::complex<double> complex;
class CustomInitialCondition : public ExactSolutionScalar < ::complex >
{
public:
CustomInitialCondition(MeshSharedPtr mesh) : ExactSolutionScalar<::complex>(mesh) {};
virtual void derivatives(double x, double y, std::complex<double> & dx, std::complex<double> & dy) const;
virtual std::complex<double> value(double x, double y) const;
virtual Ord ord(double x, double y) const;
virtual MeshFunction<::complex>* clone() const;
};
/* Weak forms */
class CustomWeakFormGPRK : public WeakForm < ::complex >
{
public:
CustomWeakFormGPRK(double h, double m, double g, double omega);
private:
class CustomFormMatrixFormVol : public MatrixFormVol < ::complex >
{
public:
CustomFormMatrixFormVol(unsigned int i, unsigned int j, double h, double m, double g, double omega)
: MatrixFormVol<::complex>(i, j), h(h), m(m), g(g), omega(omega) {};
template<typename Real, typename Scalar>
Scalar matrix_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual std::complex<double> value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<::complex> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u,
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const;
virtual MatrixFormVol<::complex>* clone() const;
// Members.
double h, m, g, omega;
};
class CustomFormVectorFormVol : public VectorFormVol < ::complex >
{
public:
CustomFormVectorFormVol(int i, double h, double m, double g, double omega)
: VectorFormVol<::complex>(i), h(h), m(m), g(g), omega(omega) {};
template<typename Real, typename Scalar>
Scalar vector_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual std::complex<double> value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<::complex> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const;
virtual VectorFormVol<::complex>* clone() const;
// Members.
double h, m, g, omega;
};
double h, m, g, omega;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/schroedinger/gross-pitaevski-adapt/plot_graph.py | .py | 557 | 30 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("Error convergence")
pylab.xlabel("Physical time (s)")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("time_error.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="error (est)")
legend()
# initialize new window
pylab.figure()
pylab.title("Problem size")
pylab.xlabel("Physical time (s)")
pylab.ylabel("Number of DOF")
data = numpy.loadtxt("time_dof.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, "-s", label="dof")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-advanced/schroedinger/gross-pitaevski-adapt/main.cpp | .cpp | 15,053 | 360 | #include "definitions.h"
// This example shows how to combine automatic adaptivity with the Newton's
// method for a nonlinear complex-valued time-dependent PDE (the Gross-Pitaevski
// equation describing the behavior of Einstein-Bose quantum gases)
// discretized implicitly in time (via implicit Euler or Crank-Nicolson).
//
// PDE: non-stationary complex Gross-Pitaevski equation
// describing resonances in Bose-Einstein condensates.
//
// ih \partial \psi/\partial t = -h^2/(2m) \Delta \psi +
// g \psi |\psi|^2 + 1/2 m \omega^2 (x^2 + y^2) \psi.
//
// Domain: square (-1, 1)^2.
//
// BC: homogeneous Dirichlet everywhere on the boundary.
//
// Time-stepping: either implicit Euler or Crank-Nicolson.
//
// The following parameters can be changed:
// Number of initial uniform refinements.
const int INIT_REF_NUM = 2;
// Initial polynomial degree.
const int P_INIT = 2;
// Time interval length.
const double T_FINAL = 2.0;
// Time step.
double time_step = 0.005;
// Adaptivity.
// Every UNREF_FREQ time step the mesh is unrefined.
const int UNREF_FREQ = 1;
// 1... mesh reset to basemesh and poly degrees to P_INIT.
// 2... one ref. layer shaved off, poly degrees reset to P_INIT.
// 3... one ref. layer shaved off, poly degrees decreased by one.
const int UNREF_METHOD = 3;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<::complex, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<::complex> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<::complex> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Temporal adaptivity.
// This flag decides whether adaptive time stepping will be done.
// The methods for the adaptive and fixed-step versions are set
// below. An embedded method must be used with adaptive time stepping.
bool ADAPTIVE_TIME_STEP_ON = true;
// If rel. temporal error is greater than this threshold, decrease time
// step size and repeat time step.
const double TIME_ERR_TOL_UPPER = 1.0;
// If rel. temporal error is less than this threshold, increase time step
// but do not repeat time step (this might need further research).
const double TIME_ERR_TOL_LOWER = 0.1;
// Time step increase ratio (applied when rel. temporal error is too small).
const double TIME_STEP_INC_RATIO = 1.1;
// Time step decrease ratio (applied when rel. temporal error is too large).
const double TIME_STEP_DEC_RATIO = 0.8;
// Newton's method.
// Stopping criterion for Newton on coarse mesh.
const double NEWTON_TOL_COARSE = 0.01;
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL_FINE = 0.05;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 50;
// Choose one of the following time-integration methods, or define your own Butcher's table. The last number
// in the name of each method is its order. The one before last, if present, is the number of stages.
// Explicit methods:
// Explicit_RK_1, Explicit_RK_2, Explicit_RK_3, Explicit_RK_4.
// Implicit methods:
// Implicit_RK_1, Implicit_Crank_Nicolson_2_2, Implicit_SIRK_2_2, Implicit_ESIRK_2_2, Implicit_SDIRK_2_2,
// Implicit_Lobatto_IIIA_2_2, Implicit_Lobatto_IIIB_2_2, Implicit_Lobatto_IIIC_2_2, Implicit_Lobatto_IIIA_3_4,
// Implicit_Lobatto_IIIB_3_4, Implicit_Lobatto_IIIC_3_4, Implicit_Radau_IIA_3_5, Implicit_SDIRK_5_4.
// Embedded explicit methods:
// Explicit_HEUN_EULER_2_12_embedded, Explicit_BOGACKI_SHAMPINE_4_23_embedded, Explicit_FEHLBERG_6_45_embedded,
// Explicit_CASH_KARP_6_45_embedded, Explicit_DORMAND_PRINCE_7_45_embedded.
// Embedded implicit methods:
// Implicit_SDIRK_CASH_3_23_embedded, Implicit_ESDIRK_TRBDF2_3_23_embedded, Implicit_ESDIRK_TRX2_3_23_embedded,
// Implicit_SDIRK_BILLINGTON_3_23_embedded, Implicit_SDIRK_CASH_5_24_embedded, Implicit_SDIRK_CASH_5_34_embedded,
// Implicit_DIRK_ISMAIL_7_45_embedded.
ButcherTableType butcher_table_type = Implicit_SDIRK_CASH_3_23_embedded;
// Problem parameters.
// Planck constant 6.626068e-34.
const double h = 1;
// Mass of boson.
const double m = 1;
// Coupling constant.
const double g = 1;
// Frequency.
const double omega = 1;
int main(int argc, char* argv[])
{
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table_type);
if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());
// Turn off adaptive time stepping if R-K method is not embedded.
if (bt.is_embedded() == false && ADAPTIVE_TIME_STEP_ON == true) {
Hermes::Mixins::Loggable::Static::warn("R-K method not embedded, turning off adaptive time stepping.");
ADAPTIVE_TIME_STEP_ON = false;
}
// Load the mesh.
MeshSharedPtr mesh(new Mesh), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", basemesh);
mesh->copy(basemesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Convert initial condition into a Solution<::complex>.
MeshFunctionSharedPtr<::complex> psi_time_prev(new CustomInitialCondition(mesh));
// Initialize the weak formulation.
double current_time = 0;
// Initialize weak formulation.
WeakFormSharedPtr<::complex> wf(new CustomWeakFormGPRK(h, m, g, omega));
// Initialize boundary conditions.
DefaultEssentialBCConst<::complex> bc_essential("Bdy", 0.0);
EssentialBCs<::complex> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<::complex> space(new H1Space<::complex>(mesh, &bcs, P_INIT));
adaptivity.set_space(space);
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
// Create a refinement selector.
H1ProjBasedSelector<::complex> selector(CAND_LIST);
// Visualize initial condition.
char title[100];
ScalarView sview_real("Initial condition - real part", new WinGeom(0, 0, 600, 500));
ScalarView sview_imag("Initial condition - imaginary part", new WinGeom(610, 0, 600, 500));
sview_real.show_mesh(false);
sview_imag.show_mesh(false);
sview_real.fix_scale_width(50);
sview_imag.fix_scale_width(50);
OrderView ord_view("Initial mesh", new WinGeom(445, 0, 440, 350));
ord_view.fix_scale_width(50);
ScalarView time_error_view("Temporal error", new WinGeom(0, 400, 440, 350));
time_error_view.fix_scale_width(50);
time_error_view.fix_scale_width(60);
ScalarView space_error_view("Spatial error", new WinGeom(445, 400, 440, 350));
space_error_view.fix_scale_width(50);
MeshFunctionSharedPtr<double> real(new RealFilter(psi_time_prev));
MeshFunctionSharedPtr<double> imag(new ImagFilter(psi_time_prev));
sview_real.show(real);
sview_imag.show(imag);
ord_view.show(space);
// Graph for time step history.
SimpleGraph time_step_graph;
if (ADAPTIVE_TIME_STEP_ON) Hermes::Mixins::Loggable::Static::info("Time step history will be saved to file time_step_history.dat.");
// Time stepping:
int num_time_steps = (int)(T_FINAL / time_step + 0.5);
for (int ts = 1; ts <= num_time_steps; ts++)
// Time stepping loop.
double current_time = 0.0; int ts = 1;
do
{
Hermes::Mixins::Loggable::Static::info("Begin time step %d.", ts);
// Periodic global derefinement.
if (ts > 1 && ts % UNREF_FREQ == 0)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
switch (UNREF_METHOD) {
case 1: mesh->copy(basemesh);
space->set_uniform_order(P_INIT);
break;
case 2: space->unrefine_all_mesh_elements();
space->set_uniform_order(P_INIT);
break;
case 3: space->unrefine_all_mesh_elements();
space->adjust_element_order(-1, -1, P_INIT, P_INIT);
break;
default: throw Hermes::Exceptions::Exception("Wrong global derefinement method.");
}
ndof = Space<::complex>::get_num_dofs(space);
}
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
// Spatial adaptivity loop. Note: psi_time_prev must not be
// changed during spatial adaptivity.
MeshFunctionSharedPtr<::complex> ref_sln(new Solution<::complex>());
MeshFunctionSharedPtr<::complex> time_error_fn(new Solution<::complex>);
bool done = false;
int as = 1;
double err_est;
do {
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<::complex>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<::complex> ref_space = refSpaceCreator.create_ref_space();
RungeKutta<::complex> runge_kutta(wf, ref_space, &bt);
// Runge-Kutta step on the fine mesh.
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step on fine mesh (t = %g s, time step = %g s, stages: %d).",
current_time, time_step, bt.get_size());
bool verbose = true;
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
runge_kutta.set_newton_max_allowed_iterations(NEWTON_MAX_ITER);
runge_kutta.set_newton_tolerance(NEWTON_TOL_FINE);
runge_kutta.rk_time_step_newton(psi_time_prev, ref_sln, time_error_fn);
}
catch (Exceptions::Exception& e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
}
/* If ADAPTIVE_TIME_STEP_ON == true, estimate temporal error.
If too large or too small, then adjust it and restart the time step. */
double rel_err_time = 0;
if (bt.is_embedded() == true) {
Hermes::Mixins::Loggable::Static::info("Calculating temporal error estimate.");
// Show temporal error.
char title[100];
sprintf(title, "Temporal error est, spatial adaptivity step %d", as);
time_error_view.set_title(title);
time_error_view.show_mesh(false);
MeshFunctionSharedPtr<double> abs_time(new RealFilter(time_error_fn));
MeshFunctionSharedPtr<double> abs_tef(new AbsFilter(abs_time));
time_error_view.show(abs_tef);
DefaultNormCalculator<::complex, HERMES_H1_NORM> normCalculator(1);
rel_err_time = 100. * normCalculator.calculate_norm(time_error_fn) / normCalculator.calculate_norm(ref_sln);
if (ADAPTIVE_TIME_STEP_ON == false)
Hermes::Mixins::Loggable::Static::info("rel_err_time: %g%%", rel_err_time);
}
if (ADAPTIVE_TIME_STEP_ON) {
if (rel_err_time > TIME_ERR_TOL_UPPER) {
Hermes::Mixins::Loggable::Static::info("rel_err_time %g%% is above upper limit %g%%", rel_err_time, TIME_ERR_TOL_UPPER);
Hermes::Mixins::Loggable::Static::info("Decreasing time step from %g to %g s and restarting time step.",
time_step, time_step * TIME_STEP_DEC_RATIO);
time_step *= TIME_STEP_DEC_RATIO;
continue;
}
else if (rel_err_time < TIME_ERR_TOL_LOWER) {
Hermes::Mixins::Loggable::Static::info("rel_err_time = %g%% is below lower limit %g%%", rel_err_time, TIME_ERR_TOL_LOWER);
Hermes::Mixins::Loggable::Static::info("Increasing time step from %g to %g s.", time_step, time_step * TIME_STEP_INC_RATIO);
time_step *= TIME_STEP_INC_RATIO;
continue;
}
else {
Hermes::Mixins::Loggable::Static::info("rel_err_time = %g%% is in acceptable interval (%g%%, %g%%)",
rel_err_time, TIME_ERR_TOL_LOWER, TIME_ERR_TOL_UPPER);
}
// Add entry to time step history graph.
time_step_graph.add_values(current_time, time_step);
time_step_graph.save("time_step_history.dat");
}
/* Estimate spatial errors and perform mesh refinement */
Hermes::Mixins::Loggable::Static::info("Spatial adaptivity step %d.", as);
// Project the fine mesh solution onto the coarse mesh.
MeshFunctionSharedPtr<::complex> sln(new Solution<::complex>);
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation.");
OGProjection<::complex> ogProjection; ogProjection.project_global(space, ref_sln, sln);
// Show spatial error.
sprintf(title, "Spatial error est, spatial adaptivity step %d", as);
MeshFunctionSharedPtr<::complex> space_error_fn(new DiffFilter<::complex>(std::vector<MeshFunctionSharedPtr<::complex> >({ ref_sln, sln })));
space_error_view.set_title(title);
space_error_view.show_mesh(false);
MeshFunctionSharedPtr<double> abs_space(new RealFilter(space_error_fn));
MeshFunctionSharedPtr<double> abs_sef(new AbsFilter(abs_space));
space_error_view.show(abs_sef);
// Calculate element errors and spatial error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating spatial error estimate.");
errorCalculator.calculate_errors(sln, ref_sln);
double err_rel_space = errorCalculator.get_total_error_squared() * 100.;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof: %d, ref_ndof: %d, err_rel_space: %g%%",
Space<::complex>::get_num_dofs(space), Space<::complex>::get_num_dofs(ref_space), err_rel_space);
// If err_est too large, adapt the mesh.
if (err_rel_space < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adaptivity.adapt(&selector);
// Increase the counter of performed adaptivity steps.
as++;
}
} while (done == false);
// Visualize the solution and mesh.
char title[100];
sprintf(title, "Solution - real part, Time %3.2f s", current_time);
sview_real.set_title(title);
sprintf(title, "Solution - imaginary part, Time %3.2f s", current_time);
sview_imag.set_title(title);
MeshFunctionSharedPtr<double> real(new RealFilter(ref_sln));
MeshFunctionSharedPtr<double> imag(new ImagFilter(ref_sln));
sview_real.show(real);
sview_imag.show(imag);
sprintf(title, "Mesh, time %g s", current_time);
ord_view.set_title(title);
ord_view.show(space);
// Copy last reference solution into psi_time_prev.
psi_time_prev->copy(ref_sln);
// Increase current time and counter of time steps.
current_time += time_step;
ts++;
} while (current_time < T_FINAL);
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/schroedinger/gross-pitaevski-adapt/definitions.cpp | .cpp | 3,888 | 98 | #include "definitions.h"
void CustomInitialCondition::derivatives(double x, double y, std::complex<double> & dx, std::complex<double> & dy) const
{
std::complex<double> val = exp(-20 * (x*x + y*y));
dx = val * (-40.0 * x);
dy = val * (-40.0 * y);
}
std::complex<double> CustomInitialCondition::value(double x, double y) const
{
return exp(-20 * (x*x + y*y));
}
Ord CustomInitialCondition::ord(double x, double y) const
{
return Hermes::Ord(exp(-20 * (x*x + y*y)));
}
MeshFunction<::complex>* CustomInitialCondition::clone() const
{
return new CustomInitialCondition(this->mesh);
}
CustomWeakFormGPRK::CustomWeakFormGPRK(double h, double m, double g, double omega) : WeakForm<::complex>(1)
{
// Jacobian volumetric part.
add_matrix_form(new CustomFormMatrixFormVol(0, 0, h, m, g, omega));
// Residual - volumetric.
add_vector_form(new CustomFormVectorFormVol(0, h, m, g, omega));
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormGPRK::CustomFormMatrixFormVol::matrix_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
std::complex<double> ii = std::complex<double>(0.0, 1.0); // imaginary unit, ii^2 = -1
Scalar result = Scalar(0);
Func<Scalar>* psi_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (h*h / (2 * m*ii*h) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ 2 * g / (ii*h)* u->val[i] * psi_prev_newton->val[i] * conj(psi_prev_newton->val[i]) * v->val[i]
+ (g / ii*h) * psi_prev_newton->val[i] * psi_prev_newton->val[i] * u->val[i] * v->val[i]
+ .5*m*omega*omega / (ii*h) * (e->x[i] * e->x[i] + e->y[i] * e->y[i]) * u->val[i] * v->val[i]);
return result;
}
std::complex<double> CustomWeakFormGPRK::CustomFormMatrixFormVol::value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<::complex> **ext) const
{
return matrix_form_rk<double, std::complex<double> >(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakFormGPRK::CustomFormMatrixFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u,
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form_rk<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<::complex>* CustomWeakFormGPRK::CustomFormMatrixFormVol::clone() const
{
return new CustomFormMatrixFormVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormGPRK::CustomFormVectorFormVol::vector_form_rk(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const
{
std::complex<double> ii = std::complex<double>(0.0, 1.0); // imaginary unit, ii^2 = -1
Scalar result = Scalar(0);
Func<Scalar>* psi_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (h*h / (2 * m*ii*h) * (psi_prev_newton->dx[i] * v->dx[i] + psi_prev_newton->dy[i] * v->dy[i])
+ 2 * g / (ii*h)* psi_prev_newton->val[i] * psi_prev_newton->val[i] * conj(psi_prev_newton->val[i]) * v->val[i]
+ (g / ii*h) * psi_prev_newton->val[i] * psi_prev_newton->val[i] * psi_prev_newton->val[i] * v->val[i]
+ .5*m*omega*omega / (ii*h) * (e->x[i] * e->x[i] + e->y[i] * e->y[i]) * psi_prev_newton->val[i] * v->val[i]);
return result;
}
std::complex<double> CustomWeakFormGPRK::CustomFormVectorFormVol::value(int n, double *wt, Func<::complex> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<::complex> **ext) const
{
return vector_form_rk<double, std::complex<double> >(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakFormGPRK::CustomFormVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return vector_form_rk<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<::complex>* CustomWeakFormGPRK::CustomFormVectorFormVol::clone() const
{
return new CustomFormVectorFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group/definitions.h | .h | 928 | 24 | ////// Weak formulation in axisymmetric coordinate system ////////////////////////////////////
#include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::CompleteWeakForms::Diffusion;
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::SupportClasses;
class CustomWeakForm : public DefaultWeakFormSourceIteration<double>
{
public:
CustomWeakForm(
const Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Diffusion::MaterialPropertyMaps& matprop,
std::vector<MeshFunctionSharedPtr<double> >& iterates,
double init_keff, std::string bdy_vacuum);
};
// Integral over the active core.
double integrate(MeshFunctionSharedPtr<double> sln, std::string area);
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group/problem_data.h | .h | 2,500 | 97 | #include "hermes2d.h"
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties;
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Diffusion;
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Definitions;
// Reference k_effective reactor eigenvalue for the material properties below
// and geometry from the file 'reactor.mesh'. For this example, it was obtained
// simplistically by a reference calculation on a 3x uniformly refined mesh
// with uniform distribution of polynomial degrees (=4), with convergence
// tolerance set to 5e-11.
const double REF_K_EFF = 1.1409144;
////// Geometric parameters. /////////////////////////////////////////////////////////////////
// File with initial mesh specification.
const std::string mesh_file = "reactor.mesh";
// Element markers.
const std::string reflector = "reflector";
const std::string core = "core";
// Boundary markers.
const std::string bdy_vacuum = "vacuum boundary";
const std::string bdy_symmetry = "symmetry plane";
////// Physical parameters. /////////////////////////////////////////////////////////////////
const MaterialPropertyMap1 D = material_property_map<rank1>
(
reflector, row(0.0164)(0.0085)(0.00832)(0.00821)
)(
core, row(0.0235)(0.0121)(0.0119)(0.0116)
);
const MaterialPropertyMap1 Sa = material_property_map<rank1>
(
reflector, row(0.00139)(0.000218)(0.00197)(0.0106)
)(
core, row(0.00977)(0.162)(0.156)(0.535)
);
const MaterialPropertyMap1 Sr = material_property_map<rank1>
(
reflector, row(1.77139)(0.533218)(3.31197)(0.0106)
)(
core, row(1.23977)(0.529)(2.436)(0.535)
);
const MaterialPropertyMap1 Sf = material_property_map<rank1>
(
reflector, row(0.0)(0.0)(0.0)(0.0)
)(
core, row(0.00395)(0.0262)(0.0718)(0.346)
);
const MaterialPropertyMap1 nu = material_property_map<rank1>
(
reflector, row(0.0)(0.0)(0.0)(0.0)
)(
core, row(2.49)(2.43)(2.42)(2.42)
);
const MaterialPropertyMap1 chi = material_property_map<rank1>
(
reflector, row(0.0)(0.0)(0.0)(0.0)
)(
core, row(0.9675)(0.03250)(0.0)(0.0)
);
const MaterialPropertyMap2 Ss = material_property_map<rank2>
(
reflector,
mat
(
row(0.0)(0.0)(0.0)(0.0)
)(
row(1.77)(0.0)(0.0)(0.0)
)(
row(0.0)(0.533)(0.0)(0.0)
)(
row(0.0)(0.0)(3.31)(0.0)
)
)(
core,
mat
(
row(0.0)(0.0)(0.0)(0.0)
)(
row(1.23)(0.0)(0.0)(0.0)
)(
row(0.0)(0.367)(0.0)(0.0)
)(
row(0.0)(0.0)(2.28)(0.0)
)
);
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group/main.cpp | .cpp | 7,309 | 202 | #include "definitions.h"
#include "problem_data.h"
// This example solves a 4-group neutron diffusion equation in the reactor core.
// The eigenproblem is solved using power interations.
//
// The reactor neutronics is given by the following eigenproblem:
//
// - \nabla \cdot D_g \nabla \phi_g + \Sigma_{Rg}\phi_g - \sum_{g' \neq g} \Sigma_s^{g'\to g} \phi_{g'} =
// = \frac{\chi_g}{k_{eff}} \sum_{g'} \nu_{g'} \Sigma_{fg'}\phi_{g'}
//
// where 1/k_{eff} is eigenvalue and \phi_g, g = 1,...,4 are eigenvectors (neutron fluxes). The current problem
// is posed in a 3D cylindrical axisymmetric geometry, leading to a 2D problem with r-z as the independent spatial
// coordinates. The corresponding diffusion operator is given by (r = x, z = y):
//
// \nabla \cdot D \nabla \phi = \frac{1}{x} (x D \phi_x)_x + (D \phi_y)_y
//
// BC:
//
// Homogeneous neumann on symmetry axis,
// d \phi_g / d n = - 0.5 \phi_g elsewhere
//
// The eigenproblem is numerically solved using common technique known as the power method (power iterations):
//
// 1) Make an initial estimate of \phi_g and k_{eff}
// 2) For n = 1, 2,...
// solve for \phi_g using previous k_prev
// solve for new k_{eff}
// \int_{Active Core} \sum^4_{g = 1} \nu_{g} \Sigma_{fg}\phi_{g}_{new}
// k_new = k_prev -------------------------------------------------------------------------
// \int_{Active Core} \sum^4_{g = 1} \nu_{g} \Sigma_{fg}\phi_{g}_{prev}
// 3) Stop iterations when
//
// | k_new - k_prev |
// | ----------------- | < epsilon
// | k_new |
//
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 0;
// Initial polynomial degrees for approximation of group fluxes.
const int P_INIT_1 = 1, P_INIT_2 = 1, P_INIT_3 = 1, P_INIT_4 = 1;
// Tolerance for the eigenvalue.
const double ERROR_STOP = 1e-5;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-8;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 100;
// Initial eigenvalue approximation.
double k_eff = 1.0;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load(mesh_file.c_str(), mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
mesh->refine_all_elements();
// Solution variables.
MeshFunctionSharedPtr<double> sln1(new Solution<double>), sln2(new Solution<double>), sln3(new Solution<double>), sln4(new Solution<double>);
std::vector<MeshFunctionSharedPtr<double> > solutions({ sln1, sln2, sln3, sln4 });
// Define initial conditions.
Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
MeshFunctionSharedPtr<double> iter1(new ConstantSolution<double>(mesh, 1.00));
MeshFunctionSharedPtr<double> iter2(new ConstantSolution<double>(mesh, 1.00));
MeshFunctionSharedPtr<double> iter3(new ConstantSolution<double>(mesh, 1.00));
MeshFunctionSharedPtr<double> iter4(new ConstantSolution<double>(mesh, 1.00));
std::vector<MeshFunctionSharedPtr<double> > iterates({ iter1, iter2, iter3, iter4 });
SpaceSharedPtr<double> space1(new H1Space<double>(mesh, P_INIT_1));
SpaceSharedPtr<double> space2(new H1Space<double>(mesh, P_INIT_2));
SpaceSharedPtr<double> space3(new H1Space<double>(mesh, P_INIT_3));
SpaceSharedPtr<double> space4(new H1Space<double>(mesh, P_INIT_4));
std::vector<SpaceSharedPtr<double> > spaces({ space1, space2, space3, space4 });
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
// Initialize views.
ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 600));
ScalarView view2("Neutron flux 2", new WinGeom(350, 0, 320, 600));
ScalarView view3("Neutron flux 3", new WinGeom(700, 0, 320, 600));
ScalarView view4("Neutron flux 4", new WinGeom(1050, 0, 320, 600));
// Do not show meshes, set 3D mode.
view1.show_mesh(false); view1.set_3d_mode(true);
view2.show_mesh(false); view2.set_3d_mode(true);
view3.show_mesh(false); view3.set_3d_mode(true);
view4.show_mesh(false); view4.set_3d_mode(true);
// Load physical data of the problem for the 4 energy groups.
Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Diffusion::MaterialPropertyMaps matprop(4);
matprop.set_D(D);
matprop.set_Sigma_r(Sr);
matprop.set_Sigma_s(Ss);
matprop.set_Sigma_a(Sa);
matprop.set_Sigma_f(Sf);
matprop.set_nu(nu);
matprop.set_chi(chi);
matprop.validate();
// Printing table of material properties.
std::cout << matprop;
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(matprop, iterates, k_eff, bdy_vacuum));
// Initialize Newton solver.
NewtonSolver<double> newton(wf, spaces);
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
// Main power iteration loop:
int it = 1; bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("------------ Power iteration %d:", it);
Hermes::Mixins::Loggable::Static::info("Newton's method.");
// Perform Newton's iteration.
try
{
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.set_jacobian_constant();
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
}
// Debug.
//printf("\n=================================================\n");
//for (int d = 0; d < ndof; d++) printf("%g ", newton.get_sln_vector()[d]);
// Translate the resulting coefficient vector into a Solution.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, solutions);
// Show intermediate solutions.
view1.show(sln1);
view2.show(sln2);
view3.show(sln3);
view4.show(sln4);
// Compute eigenvalue.
MeshFunctionSharedPtr<double> source(new SourceFilter(solutions, &matprop, core));
MeshFunctionSharedPtr<double> source_prev(new SourceFilter(iterates, &matprop, core));
double k_new = k_eff * (integrate(source, core) / integrate(source_prev, core));
Hermes::Mixins::Loggable::Static::info("Largest eigenvalue: %.8g, rel. difference from previous it.: %g", k_new, fabs((k_eff - k_new) / k_new));
// Stopping criterion.
if (fabs((k_eff - k_new) / k_new) < ERROR_STOP) done = true;
// Update eigenvalue.
k_eff = k_new;
((CustomWeakForm*)wf.get())->update_keff(k_eff);
if (!done)
{
// Save solutions for the next iteration.
iter1->copy(sln1);
iter2->copy(sln2);
iter3->copy(sln3);
iter4->copy(sln4);
it++;
}
} while (!done);
// Time measurement.
cpu_time.tick();
// Show solutions.
view1.show(sln1);
view2.show(sln2);
view3.show(sln3);
view4.show(sln4);
// Skip visualization time.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// Print timing information.
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group/definitions.cpp | .cpp | 1,849 | 45 | ////// Weak formulation in axisymmetric coordinate system ////////////////////////////////////
#include "definitions.h"
CustomWeakForm::CustomWeakForm(const Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Diffusion::MaterialPropertyMaps& matprop,
std::vector<MeshFunctionSharedPtr<double> >& iterates, double init_keff, std::string bdy_vacuum)
: Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::CompleteWeakForms::Diffusion::DefaultWeakFormSourceIteration<double>(matprop, iterates[0]->get_mesh(), iterates, init_keff, HERMES_AXISYM_Y)
{
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
add_matrix_form_surf(new Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::ElementaryForms::Diffusion::VacuumBoundaryCondition::Jacobian<double>(g, bdy_vacuum, HERMES_AXISYM_Y));
add_vector_form_surf(new Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::ElementaryForms::Diffusion::VacuumBoundaryCondition::Residual<double>(g, bdy_vacuum, HERMES_AXISYM_Y));
}
}
// Integral over the active core.
double integrate(MeshFunctionSharedPtr<double> sln, std::string area)
{
Quad2D* quad = &g_quad_2d_std;
sln->set_quad_2d(quad);
double integral = 0.0;
Element* e;
MeshSharedPtr mesh = sln->get_mesh();
int marker = mesh->get_element_markers_conversion().get_internal_marker(area).marker;
for_all_active_elements(e, mesh)
{
if (e->marker == marker)
{
update_limit_table(e->get_mode());
sln->set_active_element(e);
RefMap* ru = sln->get_refmap();
int o = 20;
limit_order(o, e->get_mode());
sln->set_quad_order(o, H2D_FN_VAL);
const double *uval = sln->get_fn_values();
double* x = ru->get_phys_x(o);
double result = 0.0;
h1_integrate_expression(x[i] * uval[i]);
integral += result;
}
}
return 2.0 * M_PI * integral;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group-adapt/definitions.h | .h | 6,089 | 151 | ////// Weak formulation in axisymmetric coordinate system ////////////////////////////////////
#include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
using namespace WeakFormsNeutronics::Multigroup::CompleteWeakForms::Diffusion;
class CustomWeakForm : public DefaultWeakFormSourceIteration < double >
{
public:
CustomWeakForm(const MaterialPropertyMaps& matprop,
std::vector<MeshFunctionSharedPtr<double> >& iterates,
double init_keff, std::string bdy_vacuum);
};
// Integral over the active core.
double integrate(MeshFunctionSharedPtr<double> sln, MeshSharedPtr mesh, std::string area);
int get_num_of_neg(MeshFunctionSharedPtr<double> sln);
// Jacobian matrix (same as stiffness matrix since projections are linear).
class H1AxisymProjectionJacobian : public MatrixFormVol < double >
{
public:
H1AxisymProjectionJacobian(int i) : MatrixFormVol<double>(i, i) { this->setSymFlag(HERMES_SYM); };
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
return h1_axisym_projection_biform<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return h1_axisym_projection_biform<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
private:
template<typename Real, typename Scalar>
static Scalar h1_axisym_projection_biform(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext)
{
Scalar result = (Scalar)0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * (u->val[i] * v->val[i] + u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
return result;
}
};
// Residual.
class H1AxisymProjectionResidual : public VectorFormVol < double >
{
public:
H1AxisymProjectionResidual(int i, MeshFunctionSharedPtr<double> ext) : VectorFormVol<double>(i)
{
this->ext.push_back(ext);
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
return h1_axisym_projection_liform<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return h1_axisym_projection_liform<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
private:
template<typename Real, typename Scalar>
Scalar h1_axisym_projection_liform(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = (Scalar)0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ((u_ext[this->i]->val[i] - ext[0]->val[i]) * v->val[i]
+ (u_ext[this->i]->dx[i] - ext[0]->dx[i]) * v->dx[i]
+ (u_ext[this->i]->dy[i] - ext[0]->dy[i]) * v->dy[i]);
return result;
}
};
// Matrix forms for error calculation.
class ErrorForm : public DefaultNormFormVol < double >
{
public:
ErrorForm(unsigned int i, unsigned int j, NormType type) : DefaultNormFormVol<double>(i, j, type, SolutionsDifference) {};
/// Error bilinear form.
virtual double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const;
/// Error bilinear form to estimate order of a function.
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const;
private:
template<typename Real, typename Scalar>
static Scalar l2_error_form_axisym(int n, double *wt, Func<Scalar> *u_ext[], Func<Scalar> *u,
Func<Scalar> *v, GeomVol<Real> *e, Func<Scalar>* *ext)
{
Scalar result = (Scalar)0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * (u->val[i] * conj(v->val[i]));
return result;
}
template<typename Real, typename Scalar>
static Scalar h1_error_form_axisym(int n, double *wt, Func<Scalar> *u_ext[], Func<Scalar> *u,
Func<Scalar> *v, GeomVol<Real> *e, Func<Scalar>* *ext)
{
Scalar result = (Scalar)0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * (u->val[i] * conj(v->val[i]) + u->dx[i] * conj(v->dx[i])
+ u->dy[i] * conj(v->dy[i]));
return result;
}
};
/// \brief Power iteration.
///
/// Starts from an initial guess stored in the argument 'solutions' and updates it by the final result after the iteration
/// has converged, also updating the global eigenvalue 'k_eff'.
///
/// \param[in] hermes2d Class encapsulating global Hermes2D functions.
/// \param[in] spaces Pointers to spaces on which the solutions are defined (one space for each energy group).
/// \param[in] wf Pointer to the weak form of the problem.
/// \param[in,out] solution A set of Solution* pointers to solution components (neutron fluxes in each group).
/// Initial guess for the iteration on input, converged result on output.
/// \param[in] fission_region String specifiying the part of the solution domain where fission occurs.
/// \param[in] tol Relative difference between two successive eigenvalue approximations that stops the iteration.
/// \param[in,out] mat Pointer to a matrix to which the system associated with the power iteration will be assembled.
/// \param[in,out] rhs Pointer to a vector to which the right hand sides of the power iteration will be successively assembled.
/// \param[in] solver Solver for the resulting matrix problem (specified by \c mat and \c rhs).
///
/// \return number of iterations needed for convergence within the specified tolerance.
///
int power_iteration(const MaterialPropertyMaps& matprop,
const std::vector<SpaceSharedPtr<double> >& spaces, DefaultWeakFormSourceIteration<double>* wf,
const std::vector<MeshFunctionSharedPtr<double> >& solution, const std::string& fission_region,
double tol);
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group-adapt/plot_graph.py | .py | 1,257 | 60 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot DOF convergence graph w.r.t. keff
pylab.title("K_eff error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [pcm]")
axis('equal')
data = numpy.loadtxt("conv_dof_keff.dat")
x = data[:, 0]
y = data[:, 1]
semilogx(x, y, '-s', label="k_eff error")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph w.r.t. keff
pylab.title("K_eff error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [pcm]")
axis('equal')
data = numpy.loadtxt("conv_cpu_keff.dat")
x = data[:, 0]
y = data[:, 1]
semilogx(x, y, '-s', label="k_eff error")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group-adapt/problem_data.h | .h | 2,590 | 99 | #include "hermes2d.h"
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties;
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Diffusion;
using namespace Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Definitions;
// Reference k_effective reactor eigenvalue for the material properties below
// and geometry from the file 'reactor.mesh'. For this example, it was obtained
// simplistically by a reference calculation on a 3x uniformly refined mesh
// with uniform distribution of polynomial degrees (=4), with convergence
// tolerance set to 5e-11.
const double REF_K_EFF = 1.1409144;
////// Geometric parameters. /////////////////////////////////////////////////////////////////
// File with initial mesh specification.
const std::string mesh_file = "reactor.mesh";
// Element markers.
const std::string reflector = "reflector";
const std::string core = "core";
// Boundary markers.
const std::string bdy_vacuum = "vacuum boundary";
const std::string bdy_symmetry = "symmetry plane";
////// Physical parameters. /////////////////////////////////////////////////////////////////
// Number of energy discretization intervals ('groups').
const unsigned int N_GROUPS = 4;
const MaterialPropertyMap1 D = material_property_map<rank1>
(
reflector, row(0.0164)(0.0085)(0.00832)(0.00821)
)(
core, row(0.0235)(0.0121)(0.0119)(0.0116)
);
const MaterialPropertyMap1 Sa = material_property_map<rank1>
(
reflector, row(0.00139)(0.000218)(0.00197)(0.0106)
)(
core, row(0.00977)(0.162)(0.156)(0.535)
);
const MaterialPropertyMap1 Sr = material_property_map<rank1>
(
reflector, row(1.77139)(0.533218)(3.31197)(0.0106)
)(
core, row(1.23977)(0.529)(2.436)(0.535)
);
const MaterialPropertyMap1 Sf = material_property_map<rank1>
(
reflector, row(0.0)(0.0)(0.0)(0.0)
)(
core, row(0.00395)(0.0262)(0.0718)(0.346)
);
const MaterialPropertyMap1 nu = material_property_map<rank1>
(
reflector, row(0.0)(0.0)(0.0)(0.0)
)(
core, row(2.49)(2.43)(2.42)(2.42)
);
const MaterialPropertyMap1 chi = material_property_map<rank1>
(
reflector, row(0.0)(0.0)(0.0)(0.0)
)(
core, row(0.9675)(0.03250)(0.0)(0.0)
);
const MaterialPropertyMap2 Ss = material_property_map<rank2>
(
reflector,
mat
(
row(0.0)(0.0)(0.0)(0.0)
)(
row(1.77)(0.0)(0.0)(0.0)
)(
row(0.0)(0.533)(0.0)(0.0)
)(
row(0.0)(0.0)(3.31)(0.0)
)
)(
core,
mat
(
row(0.0)(0.0)(0.0)(0.0)
)(
row(1.23)(0.0)(0.0)(0.0)
)(
row(0.0)(0.367)(0.0)(0.0)
)(
row(0.0)(0.0)(2.28)(0.0)
)
); | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group-adapt/main.cpp | .cpp | 16,884 | 388 | #include "definitions.h"
#include "problem_data.h"
// This example uses automatic adaptivity to solve a 4-group neutron diffusion equation in the reactor core.
// The eigenproblem is solved using power interations.
//
// The reactor neutronics in a general coordinate system is given by the following eigenproblem:
//
// - \nabla \cdot D_g \nabla \phi_g + \Sigma_{Rg}\phi_g - \sum_{g' \neq g} \Sigma_s^{g'\to g} \phi_{g'} =
// = \frac{\chi_g}{k_{eff}} \sum_{g'} \nu_{g'} \Sigma_{fg'}\phi_{g'}
//
// where 1/k_{eff} is eigenvalue and \phi_g, g = 1,...,4 are eigenvectors (neutron fluxes). The current problem
// is posed in a 3D cylindrical axisymmetric geometry, leading to a 2D problem with r-z as the independent spatial
// coordinates. Identifying r = x, z = y, the gradient in the weak form has the same components as in the
// x-y system, while all integrands are multiplied by 2\pi x (determinant of the transformation matrix).
//
// BC:
//
// homogeneous neumann on symmetry axis
// d D_g\phi_g / d n = - 0.5 \phi_g elsewhere
//
// The eigenproblem is numerically solved using common technique known as the power method (power iterations):
//
// 1) Make an initial estimate of \phi_g and k_{eff}
// 2) For n = 1, 2,...
// solve for \phi_g using previous k_prev
// solve for new k_{eff}
// \int_{Active Core} \sum^4_{g = 1} \nu_{g} \Sigma_{fg}\phi_{g}_{new}
// k_new = k_prev -------------------------------------------------------------------------
// \int_{Active Core} \sum^4_{g = 1} \nu_{g} \Sigma_{fg}\phi_{g}_{prev}
// 3) Stop iterations when
//
// | k_new - k_prev |
// | ----------------- | < epsilon
// | k_new |
//
// Author: Milan Hanus (University of West Bohemia, Pilsen, Czech Republic).
// Initial uniform mesh refinement for the individual solution components.
const int INIT_REF_NUM[N_GROUPS] = {
1, 1, 1, 1
};
// Initial polynomial orders for the individual solution components.
const int P_INIT[N_GROUPS] = {
1, 1, 1, 1
};
// Stopping criterion for an adaptivity step.
const double THRESHOLD = 0.3;
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Predefined list of element refinement candidates. Possible values are
// H2D_P_ISO, H2D_P_ANISO, H2D_H_ISO, H2D_H_ANISO, H2D_HP_ISO,
// H2D_HP_ANISO_H, H2D_HP_ANISO_P, H2D_HP_ANISO.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 0.5;
// Adaptivity process stops when the number of adaptation steps grows over
// this limit.
const int MAX_ADAPT_NUM = 30;
// Adaptivity process stops when the number of DOFs grows over
// this limit.
const int NDOF_STOP = 100000;
// Power iteration control.
// Initial eigenvalue approximation.
double k_eff = 1.0;
// Tolerance for eigenvalue convergence on the coarse mesh.
double TOL_PIT_CM = 5e-5;
// Tolerance for eigenvalue convergence on the fine mesh.
double TOL_PIT_RM = 5e-6;
// Macros for simpler reporting (four group case).
#define report_num_dofs(spaces) spaces[0]->get_num_dofs(), spaces[1]->get_num_dofs(),\
spaces[2]->get_num_dofs(), spaces[3]->get_num_dofs(),\
spaces[0]->get_num_dofs() + spaces[1]->get_num_dofs() \
+ spaces[2]->get_num_dofs() + spaces[3]->get_num_dofs()
#define report_errors(errors) errors[0], errors[1], errors[2], errors[3]
int main(int argc, char* argv[])
{
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Load physical data of the problem.
MaterialPropertyMaps matprop(N_GROUPS);
matprop.set_D(D);
matprop.set_Sigma_r(Sr);
matprop.set_Sigma_s(Ss);
matprop.set_Sigma_a(Sa);
matprop.set_Sigma_f(Sf);
matprop.set_nu(nu);
matprop.set_chi(chi);
matprop.validate();
std::cout << matprop;
// Use multimesh, i.e. create one mesh for each energy group.
std::vector<MeshSharedPtr> meshes;
for (unsigned int g = 0; g < matprop.get_G(); g++)
meshes.push_back(MeshSharedPtr(new Mesh()));
// Load the mesh for the 1st group.
MeshReaderH2D mloader;
mloader.load(mesh_file.c_str(), meshes[0]);
for (unsigned int g = 1; g < matprop.get_G(); g++)
{
// Obtain meshes for the 2nd to 4th group by cloning the mesh loaded for the 1st group.
meshes[g]->copy(meshes[0]);
// Initial uniform refinements.
for (int i = 0; i < INIT_REF_NUM[g]; i++)
meshes[g]->refine_all_elements();
}
for (int i = 0; i < INIT_REF_NUM[0]; i++)
meshes[0]->refine_all_elements();
// Create pointers to solutions on coarse and fine meshes and from the latest power iteration, respectively.
std::vector<MeshFunctionSharedPtr<double> > coarse_solutions, fine_solutions;
std::vector<MeshFunctionSharedPtr<double> > power_iterates;
// Initialize all the new solution variables.
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
coarse_solutions.push_back(MeshFunctionSharedPtr<double>(new Solution<double>()));
fine_solutions.push_back(MeshFunctionSharedPtr<double>(new Solution<double>()));
power_iterates.push_back(MeshFunctionSharedPtr<double>(new ConstantSolution<double>(meshes[g], 1.0)));
}
SpaceSharedPtr<double> space1(new H1Space<double>(meshes[0], P_INIT[0]));
SpaceSharedPtr<double> space2(new H1Space<double>(meshes[1], P_INIT[1]));
SpaceSharedPtr<double> space3(new H1Space<double>(meshes[2], P_INIT[2]));
SpaceSharedPtr<double> space4(new H1Space<double>(meshes[3], P_INIT[3]));
// Create the approximation spaces with the default shapeset.
std::vector<SpaceSharedPtr<double> > spaces({ space1, space2, space3, space4 });
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm(matprop, power_iterates, k_eff, bdy_vacuum));
// Initialize the discrete algebraic representation of the problem and its solver.
//
// Create the matrix and right-hand side vector for the solver.
SparseMatrix<double>* mat = create_matrix<double>();
Vector<double>* rhs = create_vector<double>();
// Instantiate the solver itself.
Hermes::Solvers::LinearMatrixSolver<double>* solver = Hermes::Solvers::create_linear_solver<double>(mat, rhs);
// Initialize views.
/* for 1280x800 display */
ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 400));
ScalarView view2("Neutron flux 2", new WinGeom(330, 0, 320, 400));
ScalarView view3("Neutron flux 3", new WinGeom(660, 0, 320, 400));
ScalarView view4("Neutron flux 4", new WinGeom(990, 0, 320, 400));
OrderView oview1("Mesh for group 1", new WinGeom(0, 450, 320, 500));
OrderView oview2("Mesh for group 2", new WinGeom(330, 450, 320, 500));
OrderView oview3("Mesh for group 3", new WinGeom(660, 450, 320, 500));
OrderView oview4("Mesh for group 4", new WinGeom(990, 450, 320, 500));
/* for adjacent 1280x800 and 1680x1050 displays
ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 640, 480));
ScalarView view2("Neutron flux 2", new WinGeom(650, 0, 640, 480));
ScalarView view3("Neutron flux 3", new WinGeom(1300, 0, 640, 480));
ScalarView view4("Neutron flux 4", new WinGeom(1950, 0, 640, 480));
OrderView oview1("Mesh for group 1", new WinGeom(1300, 500, 340, 500));
OrderView oview2("Mesh for group 2", new WinGeom(1650, 500, 340, 500));
OrderView oview3("Mesh for group 3", new WinGeom(2000, 500, 340, 500));
OrderView oview4("Mesh for group 4", new WinGeom(new std::vector<Space<double>(2350, 500, 340, 500)));
*/
std::vector<ScalarView *> sviews({ &view1, &view2, &view3, &view4 });
std::vector<OrderView *> oviews({ &oview1, &oview2, &oview3, &oview4 });
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
sviews[g]->show_mesh(false);
sviews[g]->set_3d_mode(true);
}
// DOF and CPU convergence graphs
GnuplotGraph graph_dof("Error convergence", "NDOF", "log(error)");
graph_dof.add_row("H1 err. est. [%]", "r", "-", "o");
graph_dof.add_row("L2 err. est. [%]", "g", "-", "s");
graph_dof.add_row("Keff err. est. [milli-%]", "b", "-", "d");
graph_dof.set_log_y();
graph_dof.show_legend();
graph_dof.show_grid();
GnuplotGraph graph_dof_evol("Evolution of NDOF", "Adaptation step", "NDOF");
graph_dof_evol.add_row("group 1", "r", "-", "o");
graph_dof_evol.add_row("group 2", "g", "-", "x");
graph_dof_evol.add_row("group 3", "b", "-", "+");
graph_dof_evol.add_row("group 4", "m", "-", "*");
graph_dof_evol.set_log_y();
graph_dof_evol.set_legend_pos("bottom right");
graph_dof_evol.show_grid();
GnuplotGraph graph_cpu("Error convergence", "CPU time [s]", "log(error)");
graph_cpu.add_row("H1 err. est. [%]", "r", "-", "o");
graph_cpu.add_row("L2 err. est. [%]", "g", "-", "s");
graph_cpu.add_row("Keff err. est. [milli-%]", "b", "-", "d");
graph_cpu.set_log_y();
graph_cpu.show_legend();
graph_cpu.show_grid();
// Initialize the refinement selectors.
H1ProjBasedSelector<double> selector(CAND_LIST);
std::vector<RefinementSelectors::Selector<double>*> selectors;
for (unsigned int g = 0; g < matprop.get_G(); g++)
selectors.push_back(&selector);
std::vector<MatrixFormVol<double>*> projection_jacobian;
std::vector<VectorFormVol<double>*> projection_residual;
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
projection_jacobian.push_back(new H1AxisymProjectionJacobian(g));
projection_residual.push_back(new H1AxisymProjectionResidual(g, power_iterates[g]));
}
std::vector<NormType> proj_norms_h1, proj_norms_l2;
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
proj_norms_h1.push_back(HERMES_H1_NORM);
proj_norms_l2.push_back(HERMES_L2_NORM);
}
// Initial power iteration to obtain a coarse estimate of the eigenvalue and the fission source.
Hermes::Mixins::Loggable::Static::info("Coarse mesh power iteration, %d + %d + %d + %d = %d ndof:", report_num_dofs(spaces));
power_iteration(matprop, spaces, (CustomWeakForm*)wf.get(), power_iterates, core, TOL_PIT_CM);
// Adaptivity loop:
int as = 1; bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Construct globally refined meshes and setup reference spaces on them.
std::vector<SpaceSharedPtr<double> > ref_spaces;
std::vector<MeshSharedPtr> ref_meshes;
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
ref_meshes.push_back(MeshSharedPtr(new Mesh()));
MeshSharedPtr ref_mesh = ref_meshes.back();
ref_mesh->copy(spaces[g]->get_mesh());
ref_mesh->refine_all_elements();
int order_increase = 1;
Space<double>::ReferenceSpaceCreator refSpaceCreator(spaces[g], ref_mesh);
ref_spaces.push_back(refSpaceCreator.create_ref_space());
}
#ifdef WITH_PETSC
// PETSc assembling is currently slow for larger matrices, so we switch to
// UMFPACK when matrices of order >8000 start to appear.
if (Space<double>::get_num_dofs(ref_spaces) > 8000 && matrix_solver == SOLVER_PETSC)
{
// Delete the old solver.
delete mat;
delete rhs;
delete solver;
// Create a new one.
matrix_solver = SOLVER_UMFPACK;
mat = create_matrix<double>();
rhs = create_vector<double>();
solver = create_linear_solver<double>(mat, rhs);
}
#endif
// Solve the fine mesh problem.
Hermes::Mixins::Loggable::Static::info("Fine mesh power iteration, %d + %d + %d + %d = %d ndof:", report_num_dofs(ref_spaces));
power_iteration(matprop, ref_spaces, (DefaultWeakFormSourceIteration<double>*)wf.get(), power_iterates, core, TOL_PIT_RM);
// Store the results.
for (unsigned int g = 0; g < matprop.get_G(); g++)
fine_solutions[g]->copy(power_iterates[g]);
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solutions on coarse meshes.");
// This is commented out as the appropriate method was deleted in the commit
// "Cleaning global projections" (b282194946225014faa1de37f20112a5a5d7ab5a).
//OGProjection<double>::project_global(spaces, projection_jacobian, projection_residual, coarse_solutions);
// Time measurement.
cpu_time.tick();
// View the coarse mesh solution and meshes.
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
sviews[g]->show(coarse_solutions[g]);
oviews[g]->show(spaces[g]);
}
// Skip visualization time.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// Report the number of negative eigenfunction values.
Hermes::Mixins::Loggable::Static::info("Num. of negative values: %d, %d, %d, %d",
get_num_of_neg(coarse_solutions[0]), get_num_of_neg(coarse_solutions[1]),
get_num_of_neg(coarse_solutions[2]), get_num_of_neg(coarse_solutions[3]));
// Calculate element errors and total error estimate.
ErrorCalculator<double> H1errorCalculator(RelativeErrorToGlobalNorm);
ErrorCalculator<double> L2errorCalculator(RelativeErrorToGlobalNorm);
Adapt<double> adapt_h1(spaces, &H1errorCalculator, &stoppingCriterion);
Adapt<double> adapt_l2(spaces, &L2errorCalculator, &stoppingCriterion);
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
H1errorCalculator.add_error_form(new ErrorForm(g, g, proj_norms_h1[g]));
L2errorCalculator.add_error_form(new ErrorForm(g, g, proj_norms_l2[g]));
}
// Calculate element errors and error estimates in H1 and L2 norms. Use the H1 estimate to drive adaptivity.
Hermes::Mixins::Loggable::Static::info("Calculating errors.");
H1errorCalculator.calculate_errors(coarse_solutions, fine_solutions);
L2errorCalculator.calculate_errors(coarse_solutions, fine_solutions);
std::vector<double> h1_group_errors = { H1errorCalculator.get_error_squared(0) * 100., H1errorCalculator.get_error_squared(1) * 100., H1errorCalculator.get_error_squared(2) * 100., H1errorCalculator.get_error_squared(3) * 100. };
std::vector<double> l2_group_errors = { L2errorCalculator.get_error_squared(0) * 100., L2errorCalculator.get_error_squared(1) * 100., L2errorCalculator.get_error_squared(2) * 100., L2errorCalculator.get_error_squared(3) * 100. };
double h1_err_est = H1errorCalculator.get_total_error_squared() * 100.;
double l2_err_est = L2errorCalculator.get_total_error_squared() * 100.;
// Time measurement.
cpu_time.tick();
double cta = cpu_time.accumulated();
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d + %d + %d + %d = %d", report_num_dofs(spaces));
// Millipercent eigenvalue error w.r.t. the reference value (see physical_parameters.cpp).
double keff_err = 1e5*fabs(((CustomWeakForm*)wf.get())->get_keff() - REF_K_EFF) / REF_K_EFF;
Hermes::Mixins::Loggable::Static::info("per-group err_est_coarse (H1): %g%%, %g%%, %g%%, %g%%", report_errors(h1_group_errors));
Hermes::Mixins::Loggable::Static::info("per-group err_est_coarse (L2): %g%%, %g%%, %g%%, %g%%", report_errors(l2_group_errors));
Hermes::Mixins::Loggable::Static::info("total err_est_coarse (H1): %g%%", h1_err_est);
Hermes::Mixins::Loggable::Static::info("total err_est_coarse (L2): %g%%", l2_err_est);
Hermes::Mixins::Loggable::Static::info("k_eff err: %g milli-percent", keff_err);
// Add entry to DOF convergence graph.
int ndof_coarse = spaces[0]->get_num_dofs() + spaces[1]->get_num_dofs()
+ spaces[2]->get_num_dofs() + spaces[3]->get_num_dofs();
graph_dof.add_values(0, ndof_coarse, h1_err_est);
graph_dof.add_values(1, ndof_coarse, l2_err_est);
graph_dof.add_values(2, ndof_coarse, keff_err);
// Add entry to CPU convergence graph.
graph_cpu.add_values(0, cta, h1_err_est);
graph_cpu.add_values(1, cta, l2_err_est);
graph_cpu.add_values(2, cta, keff_err);
for (unsigned int g = 0; g < matprop.get_G(); g++)
graph_dof_evol.add_values(g, as, Space<double>::get_num_dofs(spaces[g]));
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh (L2 norm chosen since (weighted integrals of) solution values
// are more important for further analyses than the derivatives.
if (l2_err_est < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adapt_h1.adapt(selectors);
if (spaces[0]->get_num_dofs() + spaces[1]->get_num_dofs()
+ spaces[2]->get_num_dofs() + spaces[3]->get_num_dofs() >= NDOF_STOP)
done = true;
}
as++;
if (as >= MAX_ADAPT_NUM) done = true;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
delete mat;
delete rhs;
delete solver;
graph_dof.save("conv_dof.gp");
graph_cpu.save("conv_cpu.gp");
graph_dof_evol.save("dof_evol.gp");
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/4-group-adapt/definitions.cpp | .cpp | 5,823 | 181 | ////// Weak formulation in axisymmetric coordinate system ////////////////////////////////////
#include "definitions.h"
CustomWeakForm::CustomWeakForm(const MaterialPropertyMaps& matprop,
std::vector<MeshFunctionSharedPtr<double> >& iterates,
double init_keff, std::string bdy_vacuum)
: DefaultWeakFormSourceIteration<double>(matprop, iterates[0]->get_mesh(), iterates, init_keff, HERMES_AXISYM_Y)
{
for (unsigned int g = 0; g < matprop.get_G(); g++)
{
add_matrix_form_surf(new VacuumBoundaryCondition::Jacobian<double>(g, bdy_vacuum, HERMES_AXISYM_Y));
add_vector_form_surf(new VacuumBoundaryCondition::Residual<double>(g, bdy_vacuum, HERMES_AXISYM_Y));
}
}
double ErrorForm::value(int n, double *wt, Func<double> *u_ext[],
Func<double> *u, Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
switch (this->normType)
{
case HERMES_L2_NORM:
return l2_error_form_axisym<double, double>(n, wt, u_ext, u, v, e, ext);
case HERMES_H1_NORM:
return h1_error_form_axisym<double, double>(n, wt, u_ext, u, v, e, ext);
default:
throw Hermes::Exceptions::Exception("Only the H1 and L2 norms are currently implemented.");
return 0.0;
}
}
Ord ErrorForm::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
switch (this->normType)
{
case HERMES_L2_NORM:
return l2_error_form_axisym<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
case HERMES_H1_NORM:
return h1_error_form_axisym<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
default:
throw Hermes::Exceptions::Exception("Only the H1 and L2 norms are currently implemented.");
return Ord();
}
}
// Integral over the active core.
double integrate(MeshFunction<double>* sln, std::string area)
{
Quad2D* quad = &g_quad_2d_std;
sln->set_quad_2d(quad);
double integral = 0.0;
Element* e;
MeshSharedPtr mesh = sln->get_mesh();
int marker = mesh->get_element_markers_conversion().get_internal_marker(area).marker;
for_all_active_elements(e, mesh)
{
if (e->marker == marker)
{
update_limit_table(e->get_mode());
sln->set_active_element(e);
RefMap* ru = sln->get_refmap();
int o = sln->get_fn_order() + ru->get_inv_ref_order();
limit_order(o, e->get_mode());
sln->set_quad_order(o, H2D_FN_VAL);
const double *uval = sln->get_fn_values();
double* x = ru->get_phys_x(o);
double result = 0.0;
h1_integrate_expression(x[i] * uval[i]);
integral += result;
}
}
return 2.0 * M_PI * integral;
}
// Calculate number of negative solution values.
int get_num_of_neg(MeshFunctionSharedPtr<double> sln)
{
Quad2D* quad = &g_quad_2d_std;
sln->set_quad_2d(quad);
Element* e;
const MeshSharedPtr mesh = sln->get_mesh();
int n = 0;
for_all_active_elements(e, mesh)
{
update_limit_table(e->get_mode());
sln->set_active_element(e);
RefMap* ru = sln->get_refmap();
int o = sln->get_fn_order() + ru->get_inv_ref_order();
limit_order(o, e->get_mode());
sln->set_quad_order(o, H2D_FN_VAL);
const double *uval = sln->get_fn_values();
int np = quad->get_num_points(o, e->get_mode());
for (int i = 0; i < np; i++)
if (uval[i] < -1e-12)
n++;
}
return n;
}
int power_iteration(const MaterialPropertyMaps& matprop,
const std::vector<SpaceSharedPtr<double> >& spaces, DefaultWeakFormSourceIteration<double>* wf,
const std::vector<MeshFunctionSharedPtr<double> >& solutions, const std::string& fission_region,
double tol)
{
// Sanity checks.
if (spaces.size() != solutions.size())
throw Hermes::Exceptions::Exception("Spaces and solutions supplied to power_iteration do not match.");
// Number of energy groups.
int G = spaces.size();
// Initialize the discrete problem.
DiscreteProblem<double> dp(wf, spaces);
int ndof = Space<double>::get_num_dofs(spaces);
// The following variables will store pointers to solutions obtained at each iteration and will be needed for
// updating the eigenvalue.
std::vector<MeshFunctionSharedPtr<double> > new_solutions;
for (int g = 0; g < G; g++)
new_solutions.push_back(new Solution<double>(solutions[g]->get_mesh()));
// Initial coefficient vector for the Newton's method.
double* coeff_vec = new double[ndof];
// Force the Jacobian assembling in the first iteration.
bool Jacobian_changed = true;
bool eigen_done = false; int it = 0;
do
{
memset(coeff_vec, 0.0, ndof*sizeof(double));
NewtonSolver<double> newton(&dp);
try
{
newton.solve(coeff_vec);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Convert coefficients vector into a set of Solution pointers.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, new_solutions);
// Update fission sources.
using WeakFormsNeutronics::Multigroup::SupportClasses::SourceFilter;
SourceFilter new_source(new_solutions, &matprop, fission_region);
SourceFilter old_source(solutions, &matprop, fission_region);
// Compute the eigenvalue for current iteration.
double k_new = wf->get_keff() * (integrate(&new_source, fission_region) / integrate(&old_source, fission_region));
Hermes::Mixins::Loggable::Static::info(" dominant eigenvalue (est): %g, rel. difference: %g", k_new, fabs((wf->get_keff() - k_new) / k_new));
// Stopping criterion.
if (fabs((wf->get_keff() - k_new) / k_new) < tol) eigen_done = true;
// Update the final eigenvalue.
wf->update_keff(k_new);
it++;
// Store the new eigenvector approximation in the result.
for (int g = 0; g < G; g++)
solutions[g]->copy(new_solutions[g]);
} while (!eigen_done);
return it;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/saphir/plot_graph.py | .py | 628 | 32 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/saphir/main.cpp | .cpp | 8,110 | 236 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
using namespace RefinementSelectors;
// This is the IAEA EIR-2 benchmark problem. Note the way of handling different material
// parameters. This is an alternative to how this is done in tutorial examples 07 and 12
// and in example "iron-water".
//
// PDE: -div(D(x,y)grad\Phi) + \Sigma_a(x,y)\Phi = Q_{ext}(x,y)
// where D(x, y) is the diffusion coefficient, \Sigma_a(x,y) the absorption cross-section,
// and Q_{ext}(x,y) external sources.
//
// Domain: square (0, L)x(0, L) where L = 30c (see mesh file domain.mesh).
//
// BC: Zero Dirichlet for the right and top edges ("vacuum boundary ").
// Zero Neumann for the left and bottom edges ("reflection boundary").
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.6;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Problem parameters
// Total horizontal length.
double LH = 96;
// First horizontal length.
double LH0 = 18;
// Second horizontal length.
double LH1 = 48;
// Third horizontal length.
double LH2 = 78;
// Total vertical length.
double LV = 96;
// First vertical length.
double LV0 = 18;
// Second vertical length.
double LV1 = 48;
// Third vertical length.
double LV2 = 78;
// Total cross-sections.
double SIGMA_T_1 = 0.60;
double SIGMA_T_2 = 0.48;
double SIGMA_T_3 = 0.70;
double SIGMA_T_4 = 0.85;
double SIGMA_T_5 = 0.90;
// Scattering cross sections.
double SIGMA_S_1 = 0.53;
double SIGMA_S_2 = 0.20;
double SIGMA_S_3 = 0.66;
double SIGMA_S_4 = 0.50;
double SIGMA_S_5 = 0.89;
// Nonzero sources in regions 1 and 3 only.
// Sources in other regions are zero.
double Q_EXT_1 = 1;
double Q_EXT_3 = 1;
// Additional constants
// Diffusion coefficients.
double D_1 = 1 / (3.*SIGMA_T_1);
double D_2 = 1 / (3.*SIGMA_T_2);
double D_3 = 1 / (3.*SIGMA_T_3);
double D_4 = 1 / (3.*SIGMA_T_4);
double D_5 = 1 / (3.*SIGMA_T_5);
// Absorption coefficients.
double SIGMA_A_1 = SIGMA_T_1 - SIGMA_S_1;
double SIGMA_A_2 = SIGMA_T_2 - SIGMA_S_2;
double SIGMA_A_3 = SIGMA_T_3 - SIGMA_S_3;
double SIGMA_A_4 = SIGMA_T_4 - SIGMA_S_4;
double SIGMA_A_5 = SIGMA_T_5 - SIGMA_S_5;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Perform initial uniform mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set essential boundary conditions.
DefaultEssentialBCConst<double> bc_essential(std::vector<std::string>({ "right", "top" }), 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
// Associate element markers (corresponding to physical regions)
// with material properties (diffusion coefficient, absorption
// cross-section, external sources).
std::vector<std::string> regions({ "e1", "e2", "e3", "e4", "e5" });
std::vector<double> D_map({ D_1, D_2, D_3, D_4, D_5 });
std::vector<double> Sigma_a_map({ SIGMA_A_1, SIGMA_A_2, SIGMA_A_3, SIGMA_A_4, SIGMA_A_5 });
std::vector<double> Sources_map({ Q_EXT_1, 0.0, Q_EXT_3, 0.0, 0.0 });
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormsNeutronics::Monoenergetic::Diffusion::DefaultWeakFormFixedSource<double>(regions, D_map, Sigma_a_map, Sources_map));
// Initialize coarse and reference mesh solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>), ref_sln(new Solution<double>);
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
ScalarView sview("Solution", new WinGeom(0, 0, 440, 350));
sview.fix_scale_width(50);
sview.show_mesh(false);
OrderView oview("Polynomial orders", new WinGeom(450, 0, 400, 350));
// DOF and CPU convergence graphs initialization.
SimpleGraph graph_dof, graph_cpu;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1; bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Time measurement.
cpu_time.tick();
// Construct globally refined mesh and setup fine mesh space->
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
// Initialize fine mesh problem.
Hermes::Mixins::Loggable::Static::info("Solving on fine mesh.");
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
//newton.set_verbose_output(false);
// Perform Newton's iteration.
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
}
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Time measurement.
cpu_time.tick();
// Visualize the solution and mesh.
sview.show(sln);
oview.show(space);
// Skip visualization time.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
Adapt<double> adaptivity(space, &errorCalculator, &stoppingCriterion);
bool solutions_for_adapt = true;
errorCalculator.calculate_errors(sln, ref_sln, true);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%",
space->get_num_dofs(), ref_space->get_num_dofs(), err_est_rel);
// Add entry to DOF and CPU convergence graphs.
cpu_time.tick();
graph_cpu.add_values(cpu_time.accumulated(), err_est_rel);
graph_cpu.save("conv_cpu_est.dat");
graph_dof.add_values(space->get_num_dofs(), err_est_rel);
graph_dof.save("conv_dof_est.dat");
// Skip the time spent to save the convergence graphs.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// If err_est too large, adapt the mesh.
if (err_est_rel < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
done = adaptivity.adapt(&selector);
// Increase the counter of performed adaptivity steps.
if (done == false)
as++;
}
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Show the fine mesh solution - final result.
sview.set_title("Fine mesh solution");
sview.show_mesh(false);
sview.show(ref_sln);
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/iron-water/plot_graph.py | .py | 628 | 32 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.title("Error convergence")
pylab.xlabel("CPU time (s)")
pylab.ylabel("Error [%]")
axis('equal')
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="error (est)")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-advanced/neutronics/iron-water/main.cpp | .cpp | 8,634 | 228 |
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
using namespace RefinementSelectors;
// This example is a standard nuclear engineering benchmark describing an external-force-driven
// configuration without fissile materials present, using one-group neutron diffusion approximation.
// It is very similar to example "saphir", the main difference being that the mesh is loaded in
// the ExodusII format (created for example by Cubit).
//
// PDE: -div(D(x,y)grad\Phi) + \Sigma_a(x,y)\Phi = Q_{ext}(x,y)
// where D(x, y) is the diffusion coefficient, \Sigma_a(x,y) the absorption cross-section,
// and Q_{ext}(x,y) external sources.
//
// Domain: square (0, L)x(0, L) where L = 30c (see mesh file domain.mesh).
//
// BC: Zero Dirichlet for the right and top edges ("vacuum boundary").
// Zero Neumann for the left and bottom edges ("reflection boundary").
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 0;
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.6;
// Adaptive strategy:
// STRATEGY = 0 ... refine elements until sqrt(THRESHOLD) times total
// error is processed. If more elements have similar errors, refine
// all to keep the mesh symmetric.
// STRATEGY = 1 ... refine all elements whose error is larger
// than THRESHOLD times maximum element error.
// STRATEGY = 2 ... refine all elements whose error is larger
// than THRESHOLD.
const int STRATEGY = 0;
// Predefined list of element refinement candidates. Possible values are
// H2D_P_ISO, H2D_P_ANISO, H2D_H_ISO, H2D_H_ANISO, H2D_HP_ISO,
// H2D_HP_ANISO_H, H2D_HP_ANISO_P, H2D_HP_ANISO.
const CandList CAND_LIST = H2D_HP_ANISO;
// Maximum allowed level of hanging nodes:
// MESH_REGULARITY = -1 ... arbitrary level hangning nodes (default),
// MESH_REGULARITY = 1 ... at most one-level hanging nodes,
// MESH_REGULARITY = 2 ... at most two-level hanging nodes, etc.
// Note that regular meshes are not supported, this is due to
// their notoriously bad performance.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity (rel. error tolerance between the
// reference mesh and coarse mesh solution in percent).
const double ERR_STOP = 0.01;
// This parameter influences the selection of
// candidates in hp-adaptivity. Default value is 1.0.
const double CONV_EXP = 1.0;
// Adaptivity process stops when the number of degrees of freedom grows
// over this limit. This is to prevent h-adaptivity to go on forever.
const int NDOF_STOP = 60000;
// Problem parameters.
// Edge of square.
double L = 30;
// End of first water region.
double L0 = 0.75*0.5*L;
// End of second water region.
double L1 = 0.5*L;
// End of iron region.
double L2 = 0.75*L;
// Neutron source (nonzero in region 1 only).
double Q_EXT = 1.0;
// Total cross-section.
double SIGMA_T_WATER = 3.33;
double SIGMA_T_IRON = 1.33;
// Scattering ratio.
double C_WATER = 0.994;
double C_IRON = 0.831;
// Diffusion coefficient.
double D_WATER = 1./(3.*SIGMA_T_WATER);
double D_IRON = 1./(3.*SIGMA_T_IRON);
// Absorbing cross-section.
double SIGMA_A_WATER = SIGMA_T_WATER - C_WATER*SIGMA_T_WATER;
double SIGMA_A_IRON = SIGMA_T_IRON - C_IRON*SIGMA_T_IRON;
// Materials.
// Mesh file generated by Cubit - do not convert markers to strings.
const std::string WATER_1 = "1";
const std::string WATER_2 = "2";
const std::string IRON = "3";
// Boundaries.
const std::string ZERO_FLUX_BOUNDARY = "2";
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderExodusII mloader;
if (!mloader.load("iron-water.e", mesh))
throw Hermes::Exceptions::Exception("ExodusII mesh load failed.");
// Perform initial uniform mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Set essential boundary conditions.
DefaultEssentialBCConst<double> bc_essential(ZERO_FLUX_BOUNDARY, 0.0);
EssentialBCs<double> bcs(&bc_essential);
SpaceSharedPtr<double> space(new
// Create an H1 space with default shapeset.
H1Space<double>(mesh, &bcs, P_INIT));
// Initialize coarse and fine mesh solution.
Solution<double> sln, ref_sln;
// Associate element markers (corresponding to physical regions)
// with material properties (diffusion coefficient, absorption
// cross-section, external sources).
std::vector<std::string> regions(WATER_1, WATER_2, IRON);
std::vector<double> D_map(D_WATER, D_WATER, D_IRON);
std::vector<double> Sigma_a_map(SIGMA_A_WATER, SIGMA_A_WATER, SIGMA_A_IRON);
std::vector<double> Sources_map(Q_EXT, 0.0, 0.0);
// Initialize the weak formulation.
WeakFormsNeutronics::Monoenergetic::Diffusion::DefaultWeakFormFixedSource<double>
wf(regions, D_map, Sigma_a_map, Sources_map);
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER);
// Initialize views.
ScalarView sview("Solution", new WinGeom(0, 0, 440, 350));
sview.fix_scale_width(50);
sview.show_mesh(false);
OrderView oview("Polynomial orders", new WinGeom(450, 0, 400, 350));
// DOF and CPU convergence graphs initialization.
SimpleGraph graph_dof, graph_cpu;
// Adaptivity loop:
int as = 1; bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Construct globally refined mesh and setup fine mesh space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
Space<double>* ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = ref_space->get_num_dofs();
// Initialize fine mesh problem.
Hermes::Mixins::Loggable::Static::info("Solving on fine mesh.");
DiscreteProblem<double> dp(wf, ref_space);
NewtonSolver<double> newton(&dp);
newton.set_verbose_output(false);
// Perform Newton's iteration.
try
{
newton.solve();
}
catch(Hermes::Exceptions::Exception e)
{
e.print_msg();
}
// Translate the resulting coefficient vector into the instance of Solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh.");
OGProjection<double> ogProjection;
ogProjection.project_global(space, &ref_sln, sln);
// Visualize the solution and mesh.
sview.show(sln);
oview.show(&space);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
Adapt<double> adaptivity(&space);
bool solutions_for_adapt = true;
double err_est_rel = adaptivity.calc_err_est(sln, &ref_sln, solutions_for_adapt,
HERMES_TOTAL_ERROR_REL | HERMES_ELEMENT_ERROR_REL) * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%",
space.get_num_dofs(), ref_space->get_num_dofs(), err_est_rel);
// If err_est too large, adapt the mesh.
if (err_est_rel < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
done = adaptivity.adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY);
// Increase the counter of performed adaptivity steps.
if (done == false)
as++;
}
if (space.get_num_dofs() >= NDOF_STOP)
done = true;
// Keep the mesh from final step to allow further work with the final fine mesh solution.
if(done == false)
delete ref_space->get_mesh();
delete ref_space;
}
while (done == false);
// Show the fine mesh solution - final result.
sview.set_title("Fine mesh solution");
sview.show_mesh(false);
sview.show(ref_sln);
// Wait for all views to be closed.
Views::View::wait();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/heat-transfer/heat-and-moisture-adapt/definitions.h | .h | 1,406 | 52 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Weak forms */
class CustomWeakFormHeatMoistureRK : public WeakForm<double>
{
public:
CustomWeakFormHeatMoistureRK(double c_TT, double c_ww, double d_TT, double d_Tw, double d_wT, double d_ww,
double k_TT, double k_ww, double T_ext, double w_ext, const std::string bdy_ext);
};
/* Time-dependent Dirichlet condition for temperature */
class EssentialBCNonConst : public EssentialBoundaryCondition<double>
{
public:
EssentialBCNonConst(std::string marker, double reactor_start_time, double temp_initial, double temp_reactor_max);
~EssentialBCNonConst() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
protected:
double reactor_start_time;
double temp_initial;
double temp_reactor_max;
};
/* Custom error forms */
class CustomErrorForm : public NormFormVol<double>
{
public:
CustomErrorForm(int i, int j, double d, double c) : NormFormVol<double>(i, j, SolutionsDifference), d(d), c(c) {};
virtual double value(int n, double *wt, Func<double> *u, Func<double> *v, GeomVol<double> *e) const
{
return d / c * int_grad_u_grad_v<double, double>(n, wt, u, v);
}
double d, c;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/heat-transfer/heat-and-moisture-adapt/forms.cpp | .cpp | 3,319 | 92 | // first equation:
template<typename Real, typename Scalar>
Scalar bilinear_form_sym_0_0(int n, double *wt, Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( (c_TT/TAU) * u->val[i] * v->val[i] + d_TT * (u->dx[i]*v->dx[i] + u->dy[i]*v->dy[i]) );
return result;
}
template<typename Real, typename Scalar>
Scalar bilinear_form_sym_0_1(int n, double *wt, Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( d_Tw * (u->dx[i]*v->dx[i] + u->dy[i]*v->dy[i]) );
return result;
}
template<typename Real, typename Scalar>
Scalar bilinear_form_surf_0_0_ext(int n, double *wt, Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( k_TT * u->val[i] * v->val[i] );
return result;
}
template<typename Real, typename Scalar>
Scalar linear_form_0(int n, double *wt, Func<Real> *u_ext[], Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( (c_TT/TAU) * ext->fn[0]->val[i] * v->val[i] );
return result;
}
template<typename Real, typename Scalar>
Scalar linear_form_surf_0_ext(int n, double *wt, Func<Real> *u_ext[], Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( k_TT * TEMP_EXTERIOR * v->val[i] );
return result;
}
// second equation:
template<typename Real, typename Scalar>
Scalar bilinear_form_sym_1_0(int n, double *wt, Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( d_wT * (u->dx[i]*v->dx[i] + u->dy[i]*v->dy[i]) );
return result;
}
template<typename Real, typename Scalar>
Scalar bilinear_form_sym_1_1(int n, double *wt, Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( (c_ww/TAU) * u->val[i] * v->val[i] + d_ww * (u->dx[i]*v->dx[i] + u->dy[i]*v->dy[i]) );
return result;
}
template<typename Real, typename Scalar>
Scalar bilinear_form_surf_1_1_ext(int n, double *wt, Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( k_ww * u->val[i] * v->val[i] );
return result;
}
template<typename Real, typename Scalar>
Scalar linear_form_1(int n, double *wt, Func<Real> *u_ext[], Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( (c_ww/TAU) * ext->fn[0]->val[i] * v->val[i] );
return result;
}
template<typename Real, typename Scalar>
Scalar linear_form_surf_1_ext(int n, double *wt, Func<Real> *u_ext[], Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * e->x[i] * ( k_ww * MOIST_EXTERIOR * v->val[i] );
return result;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/heat-transfer/heat-and-moisture-adapt/main.cpp | .cpp | 13,027 | 319 | #include "definitions.h"
using namespace RefinementSelectors;
// This example solves adaptively a time-dependent coupled problem of heat and moisture
// transfer in massive concrete walls of a nuclear reactor vessel (simplified axi-symmetric
// geometry).
//
// PDE: Lengthy. See the paper P. Solin, L. Dubcova, J. Kruis: Adaptive hp-FEM with Dynamical
// Meshes for Transient Heat and Moisture Transfer Problems, J. Comput. Appl. Math. 233 (2010) 3103-3112.
//
// The following parameters can be changed:
// Scaling factor for moisture. Since temperature is in hundreds of Kelvins and moisture between
// (0, 1), adaptivity works better when moisture is scaled.
const double W_SCALING_FACTOR = 100.;
// Initial polynomial degrees.
const int P_INIT = 2;
// MULTI = true ... use multi-mesh,
// MULTI = false ... use single-mesh->
// Note: In the single mesh option, the meshes are
// forced to be geometrically the same but the
// polynomial degrees can still vary.
const bool MULTI = true;
// Every UNREF_FREQth time step the mesh is derefined.
const int UNREF_FREQ = 1;
// 1... mesh reset to basemesh and poly degrees to P_INIT.
// 2... one ref. layer shaved off, poly degrees reset to P_INIT.
// 3... one ref. layer shaved off, poly degrees decreased by one.
// and just one polynomial degree subtracted.
const int UNREF_METHOD = 3;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.9;
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Problem parameters.
const double c_TT = 2.18e+6;
const double d_TT = 2.1;
const double d_Tw = 2.37e-2 / W_SCALING_FACTOR;
const double k_TT = 25;
const double c_ww = 24.9;
const double d_wT = 1.78e-10 * W_SCALING_FACTOR;
const double d_ww = 3.02e-8;
const double k_ww = 1.84e-7;
CustomErrorForm cef_0_0(0, 0, d_TT, c_TT);
CustomErrorForm cef_0_1(0, 1, d_Tw, c_TT);
CustomErrorForm cef_1_0(1, 0, d_wT, c_ww);
CustomErrorForm cef_1_1(1, 1, d_ww, c_ww);
// Error calculation & adaptivity.
class MyErrorCalculator : public Hermes::Hermes2D::ErrorCalculator < double >
{
public:
MyErrorCalculator() : Hermes::Hermes2D::ErrorCalculator<double>(RelativeErrorToGlobalNorm)
{
this->add_error_form(&cef_0_0);
this->add_error_form(&cef_0_1);
this->add_error_form(&cef_1_0);
this->add_error_form(&cef_1_1);
}
}
errorCalculator;
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Newton's method
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL = 1e-5;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 50;
// Choose one of the following time-integration methods, or define your own Butcher's table. The last number
// in the name of each method is its order. The one before last, if present, is the number of stages.
// Explicit methods:
// Explicit_RK_1, Explicit_RK_2, Explicit_RK_3, Explicit_RK_4.
// Implicit methods:
// Implicit_RK_1, Implicit_Crank_Nicolson_2_2, Implicit_SIRK_2_2, Implicit_ESIRK_2_2, Implicit_SDIRK_2_2,
// Implicit_Lobatto_IIIA_2_2, Implicit_Lobatto_IIIB_2_2, Implicit_Lobatto_IIIC_2_2, Implicit_Lobatto_IIIA_3_4,
// Implicit_Lobatto_IIIB_3_4, Implicit_Lobatto_IIIC_3_4, Implicit_Radau_IIA_3_5, Implicit_SDIRK_5_4.
// Embedded explicit methods:
// Explicit_HEUN_EULER_2_12_embedded, Explicit_BOGACKI_SHAMPINE_4_23_embedded, Explicit_FEHLBERG_6_45_embedded,
// Explicit_CASH_KARP_6_45_embedded, Explicit_DORMAND_PRINCE_7_45_embedded.
// Embedded implicit methods:
// Implicit_SDIRK_CASH_3_23_embedded, Implicit_ESDIRK_TRBDF2_3_23_embedded, Implicit_ESDIRK_TRX2_3_23_embedded,
// Implicit_SDIRK_BILLINGTON_3_23_embedded, Implicit_SDIRK_CASH_5_24_embedded, Implicit_SDIRK_CASH_5_34_embedded,
// Implicit_DIRK_ISMAIL_7_45_embedded.
ButcherTableType butcher_table_type = Implicit_RK_1;
// Time step and simulation time.
// Time step: 10 days
const double time_step = 10. * 24 * 60 * 60;
// Physical time [seconds].
const double SIMULATION_TIME = 10000 * time_step + 0.001;
// Initial and boundary conditions.
// (Kelvins)
const double T_INITIAL = 293.0;
// (dimensionless)
const double W_INITIAL = 0.9 * W_SCALING_FACTOR;
// (Kelvins)
const double T_EXTERIOR = 293.0;
// (dimensionless)
const double W_EXTERIOR = 0.55 * W_SCALING_FACTOR;
// (Kelvins)
const double T_REACTOR_MAX = 550.0;
// How long does the reactor
// need to warm up linearly from T_INITIAL
// to T_REACTOR_MAX [seconds].
const double REACTOR_START_TIME = 3600 * 24 * 100;
// Physical time in seconds.
double current_time = 0.0;
int main(int argc, char* argv[])
{
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table_type);
if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());
// Load the mesh.
MeshSharedPtr basemesh(new Mesh), T_mesh(new Mesh), w_mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", basemesh);
// Create temperature and moisture meshes.
// This also initializes the multimesh hp-FEM.
T_mesh->copy(basemesh);
w_mesh->copy(basemesh);
// Initialize boundary conditions.
EssentialBCNonConst temp_reactor("bdy_react", REACTOR_START_TIME, T_INITIAL, T_REACTOR_MAX);
EssentialBCs<double> bcs_T(&temp_reactor);
SpaceSharedPtr<double> T_space(new H1Space<double>(T_mesh, &bcs_T, P_INIT));
SpaceSharedPtr<double> w_space(new H1Space<double>(MULTI ? w_mesh : T_mesh, P_INIT));
std::vector<SpaceSharedPtr<double> > spaces({ T_space, w_space });
adaptivity.set_spaces(spaces);
// Define constant initial conditions.
Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
MeshFunctionSharedPtr<double> T_time_prev(new ConstantSolution<double>(T_mesh, T_INITIAL));
MeshFunctionSharedPtr<double> w_time_prev(new ConstantSolution<double>(w_mesh, W_INITIAL));
MeshFunctionSharedPtr<double> T_time_new(new Solution<double>(T_mesh));
MeshFunctionSharedPtr<double> w_time_new(new Solution<double>(w_mesh));
// Solutions.
MeshFunctionSharedPtr<double> T_coarse(new Solution<double>), w_coarse(new Solution<double>);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormHeatMoistureRK(c_TT, c_ww, d_TT, d_Tw, d_wT, d_ww,
k_TT, k_ww, T_EXTERIOR, W_EXTERIOR, "bdy_ext"));
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Geometry and position of visualization windows.
WinGeom* T_sln_win_geom = new WinGeom(0, 0, 300, 450);
WinGeom* w_sln_win_geom = new WinGeom(310, 0, 300, 450);
WinGeom* T_mesh_win_geom = new WinGeom(620, 0, 280, 450);
WinGeom* w_mesh_win_geom = new WinGeom(910, 0, 280, 450);
// Initialize views.
ScalarView T_sln_view("Temperature", T_sln_win_geom);
ScalarView w_sln_view("Moisture (scaled)", w_sln_win_geom);
OrderView T_order_view("Temperature mesh", T_mesh_win_geom);
OrderView w_order_view("Moisture mesh", w_mesh_win_geom);
// Show initial conditions.
T_sln_view.show(T_time_prev);
w_sln_view.show(w_time_prev);
T_order_view.show(T_space);
w_order_view.show(w_space);
// Time stepping loop:
int ts = 1;
while (current_time < SIMULATION_TIME)
{
Hermes::Mixins::Loggable::Static::info("Simulation time = %g s (%d h, %d d, %d y)",
current_time, (int)current_time / 3600,
(int)current_time / (3600 * 24), (int)current_time / (3600 * 24 * 364));
// Update time-dependent essential BCs.
if (current_time <= REACTOR_START_TIME) {
Hermes::Mixins::Loggable::Static::info("Updating time-dependent essential BC.");
Space<double>::update_essential_bc_values({ T_space, w_space }, current_time);
}
// Uniform mesh derefinement.
if (ts > 1 && ts % UNREF_FREQ == 0) {
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
switch (UNREF_METHOD) {
case 1: T_mesh->copy(basemesh);
w_mesh->copy(basemesh);
T_space->set_uniform_order(P_INIT);
w_space->set_uniform_order(P_INIT);
break;
case 2: T_mesh->unrefine_all_elements();
if (MULTI)
w_mesh->unrefine_all_elements();
T_space->set_uniform_order(P_INIT);
w_space->set_uniform_order(P_INIT);
break;
case 3: T_mesh->unrefine_all_elements();
if (MULTI)
w_mesh->unrefine_all_elements();
T_space->adjust_element_order(-1, -1, P_INIT, P_INIT);
w_space->adjust_element_order(-1, -1, P_INIT, P_INIT);
break;
default: throw Hermes::Exceptions::Exception("Wrong global derefinement method.");
}
T_space->assign_dofs();
w_space->assign_dofs();
Space<double>::assign_dofs(spaces);
}
// Spatial adaptivity loop. Note: T_time_prev and w_time_prev must not be changed during
// spatial adaptivity.
bool done = false; int as = 1;
do
{
Hermes::Mixins::Loggable::Static::info("Time step %d, adaptivity step %d:", ts, as);
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreatorU(T_mesh);
MeshSharedPtr ref_T_mesh = refMeshCreatorU.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorT(T_space, ref_T_mesh);
SpaceSharedPtr<double> ref_T_space = refSpaceCreatorT.create_ref_space();
Mesh::ReferenceMeshCreator refMeshCreatorW(w_mesh);
MeshSharedPtr ref_w_mesh = refMeshCreatorW.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorW(w_space, ref_w_mesh);
SpaceSharedPtr<double> ref_w_space = refSpaceCreatorW.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_T_space, ref_w_space });
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, ref_spaces, &bt);
// Perform one Runge-Kutta time step according to the selected Butcher's table.
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).",
current_time, time_step, bt.get_size());
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
runge_kutta.set_newton_max_allowed_iterations(NEWTON_MAX_ITER);
runge_kutta.set_newton_tolerance(NEWTON_TOL);
runge_kutta.rk_time_step_newton({ T_time_prev, w_time_prev }, { T_time_new, w_time_new });
}
catch (Exceptions::Exception& e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
}
// Project the fine mesh solution onto the coarse meshes.
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solutions on coarse meshes for error estimation.");
OGProjection<double>::project_global({ T_space, w_space }, { T_time_new, w_time_new },
{ T_coarse, w_coarse });
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
errorCalculator.calculate_errors({ T_coarse, w_coarse }, { T_time_new, w_time_new });
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%",
Space<double>::get_num_dofs({ T_space, w_space }),
Space<double>::get_num_dofs(ref_spaces), err_est_rel_total);
// If err_est too large, adapt the meshes.
if (err_est_rel_total < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adaptivity.adapt({ &selector, &selector });
// Increase the counter of performed adaptivity steps.
as++;
}
} while (done == false);
// Update time.
current_time += time_step;
// Show new coarse meshes and solutions.
char title[100];
sprintf(title, "Temperature, t = %g days", current_time / 3600. / 24);
T_sln_view.set_title(title);
T_sln_view.show(T_coarse);
sprintf(title, "Moisture (scaled), t = %g days", current_time / 3600. / 24);
w_sln_view.set_title(title);
w_sln_view.show(w_coarse);
T_order_view.show(T_space);
w_order_view.show(w_space);
// Save fine mesh solutions for the next time step.
T_time_prev->copy(T_time_new);
w_time_prev->copy(w_time_new);
ts++;
}
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/heat-transfer/heat-and-moisture-adapt/definitions.cpp | .cpp | 3,263 | 49 | #include "definitions.h"
CustomWeakFormHeatMoistureRK::CustomWeakFormHeatMoistureRK(double c_TT, double c_ww, double d_TT, double d_Tw, double d_wT,
double d_ww, double k_TT, double k_ww, double T_ext, double w_ext, const std::string bdy_ext) : WeakForm<double>(2)
{
// Jacobian - volumetric.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(0, 0, HERMES_ANY, new Hermes1DFunction<double>(-d_TT / c_TT), HERMES_SYM, HERMES_AXISYM_Y));
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(0, 1, HERMES_ANY, new Hermes1DFunction<double>(-d_Tw / c_TT), HERMES_NONSYM, HERMES_AXISYM_Y));
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(1, 0, HERMES_ANY, new Hermes1DFunction<double>(-d_wT / c_ww), HERMES_NONSYM, HERMES_AXISYM_Y));
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(1, 1, HERMES_ANY, new Hermes1DFunction<double>(-d_ww / c_ww), HERMES_SYM, HERMES_AXISYM_Y));
// Jacobian - surface.
add_matrix_form_surf(new WeakFormsH1::DefaultMatrixFormSurf<double>(0, 0, bdy_ext, new Hermes2DFunction<double>(-k_TT / c_TT), HERMES_AXISYM_Y));
add_matrix_form_surf(new WeakFormsH1::DefaultMatrixFormSurf<double>(1, 1, bdy_ext, new Hermes2DFunction<double>(-k_ww / c_ww), HERMES_AXISYM_Y));
// Residual - volumetric
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(0, HERMES_ANY, new Hermes1DFunction<double>(-d_TT / c_TT), HERMES_AXISYM_Y));
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(0, HERMES_ANY, new Hermes1DFunction<double>(-d_Tw / c_TT), HERMES_AXISYM_Y));
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(1, HERMES_ANY, new Hermes1DFunction<double>(-d_wT / c_ww), HERMES_AXISYM_Y));
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(1, HERMES_ANY, new Hermes1DFunction<double>(-d_ww / c_ww), HERMES_AXISYM_Y));
// Residual - surface.
add_vector_form_surf(new WeakFormsH1::DefaultVectorFormSurf<double>(0, bdy_ext, new Hermes2DFunction<double>(k_TT / c_TT * T_ext), HERMES_AXISYM_Y));
add_vector_form_surf(new WeakFormsH1::DefaultResidualSurf<double>(0, bdy_ext, new Hermes2DFunction<double>(-k_TT / c_TT), HERMES_AXISYM_Y));
add_vector_form_surf(new WeakFormsH1::DefaultVectorFormSurf<double>(1, bdy_ext, new Hermes2DFunction<double>(k_ww / c_ww * w_ext), HERMES_AXISYM_Y));
add_vector_form_surf(new WeakFormsH1::DefaultResidualSurf<double>(1, bdy_ext, new Hermes2DFunction<double>(-k_ww / c_ww), HERMES_AXISYM_Y));
}
EssentialBCNonConst::EssentialBCNonConst(std::string marker, double reactor_start_time, double temp_initial, double temp_reactor_max)
: EssentialBoundaryCondition<double>(std::vector<std::string>()), reactor_start_time(reactor_start_time),
temp_initial(temp_initial), temp_reactor_max(temp_reactor_max)
{
markers.push_back(marker);
}
EssentialBCValueType EssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConst::value(double x, double y) const
{
double current_reactor_temperature = temp_reactor_max;
if (current_time < reactor_start_time)
{
current_reactor_temperature = temp_initial + (current_time / reactor_start_time) * (temp_reactor_max - temp_initial);
}
return current_reactor_temperature;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/heat-transfer/wall-on-fire-adapt/definitions.h | .h | 3,281 | 96 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Space-dependent thermal conductivity */
double lambda(double x, double y);
/* Time-dependent fire temperature */
template<typename Real>
Real T_fire_x(Real x);
template<typename Real>
Real T_fire_t(Real t);
/* Weak forms */
class CustomWeakFormHeatRK : public WeakForm < double >
{
public:
CustomWeakFormHeatRK(std::string bdy_fire, std::string bdy_air,
double alpha_fire, double alpha_air, double rho, double heatcap,
double temp_ext_air, double temp_init, double* current_time_ptr);
private:
// This form is custom since it contains space-dependent thermal conductivity.
class CustomJacobianVol : public MatrixFormVol < double >
{
public:
CustomJacobianVol(unsigned int i, unsigned int j, double rho, double heatcap)
: MatrixFormVol<double>(i, j), rho(rho), heatcap(heatcap) {};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const;
// This is needed for the rk_time_step_newton() method.
virtual MatrixFormVol<double>* clone() const;
double rho, heatcap;
};
// This form is custom since it contains space-dependent thermal conductivity.
class CustomFormResidualVol : public VectorFormVol < double >
{
public:
CustomFormResidualVol(int i, double rho, double heatcap)
: VectorFormVol<double>(i), rho(rho), heatcap(heatcap) {};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const;
// Needed for the rk_time_step_newton() method.
virtual VectorFormVol<double>* clone() const;
double rho, heatcap;
};
// Custom due to time-dependent exterior temperature.
class CustomFormResidualSurfFire : public VectorFormSurf < double >
{
public:
CustomFormResidualSurfFire(int i, std::string area, double alpha_fire, double rho,
double heatcap, double* current_time_ptr)
: VectorFormSurf<double>(i), alpha_fire(alpha_fire), rho(rho),
heatcap(heatcap), current_time_ptr(current_time_ptr) {
this->set_area(area);
};
template<typename Real, typename Scalar>
Scalar vector_form_surf(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomSurf<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomSurf<double> *e,
Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord>* *ext) const;
// Needed for the rk_time_step_newton() method.
virtual VectorFormSurf<double>* clone() const;
// Fire temperature as function of x and t.
template<typename Real>
Real T_fire(Real x, Real t) const;
double alpha_fire, rho, heatcap, *current_time_ptr;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/heat-transfer/wall-on-fire-adapt/main.cpp | .cpp | 15,493 | 377 | #include "definitions.h"
// This example models a nonstationary distribution of temperature within a wall
// exposed to ISO fire. Spatial adaptivity is ON by default, adaptivity in time
// can be turned ON and OFF using the flag ADAPTIVE_TIME_STEP_ON.
//
// PDE: non-stationary heat transfer equation
// HEATCAP * RHO * dT/dt - div (LAMBDA grad T) = 0.
// Here LAMBDA(x, y) is an external, user-defined function.
//
// For the sake of using arbitrary RK methods, this equation is written in such
// a way that the time-derivative is on the left and everything else on the right:
//
// dT/dt = div(LAMBDA grad T) / (HEATCAP * RHO)
//
// Domain: rectangle 4.0 x 0.5 (file wall.mesh).
//
// IC: T = TEMP_INIT.
// BC: Bottom edge: LAMBDA * dT/dn = ALPHA_BOTTOM*(T_fire(x, time) - T)
// Vertical edges: dT/dn = 0
// Top edge: LAMBDA * dT/dn = ALPHA_TOP*(TEMP_EXT_AIR - T)
//
// Time-stepping: Arbitrary Runge-Kutta methods (choose one of the predefined
// Butcher's tables below or create your own).
//
// The following parameters can be changed:
// Polynomial degree of all mesh elements.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// Number of initial uniform mesh refinements towards the boundary.
const int INIT_REF_NUM_BDY = 1;
// Time step in seconds.
double time_step = 20;
// Spatial adaptivity.
// Every UNREF_FREQth time step the mesh is derefined.
const int UNREF_FREQ = 1;
// 1... mesh reset to basemesh and poly degrees to P_INIT.
// 2... one ref. layer shaved off, poly degrees reset to P_INIT.
// 3... one ref. layer shaved off, poly degrees decreased by one.
const int UNREF_METHOD = 3;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Temporal adaptivity.
// This flag decides whether adaptive time stepping will be done.
// The methods for the adaptive and fixed-step versions are set
// below. An embedded method must be used with adaptive time stepping.
bool ADAPTIVE_TIME_STEP_ON = false;
// If rel. temporal error is greater than this threshold, decrease time
// step size and repeat time step.
const double TIME_ERR_TOL_UPPER = 1.0;
// If rel. temporal error is less than this threshold, increase time step
// but do not repeat time step (this might need further research).
const double TIME_ERR_TOL_LOWER = 0.5;
// Time step increase ratio (applied when rel. temporal error is too small).
const double TIME_STEP_INC_RATIO = 1.1;
// Time step decrease ratio (applied when rel. temporal error is too large).
const double TIME_STEP_DEC_RATIO = 0.8;
// Space error tolerance.
const double SPACE_ERR_TOL = 10.;
// Newton's method.
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL_COARSE = 0.001;
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL_FINE = 0.005;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 100;
// Choose one of the following time-integration methods, or define your own Butcher's table. The last number
// in the name of each method is its order. The one before last, if present, is the number of stages.
// Explicit methods:
// Explicit_RK_1, Explicit_RK_2, Explicit_RK_3, Explicit_RK_4.
// Implicit methods:
// Implicit_RK_1, Implicit_Crank_Nicolson_2_2, Implicit_SIRK_2_2, Implicit_ESIRK_2_2, Implicit_SDIRK_2_2,
// Implicit_Lobatto_IIIA_2_2, Implicit_Lobatto_IIIB_2_2, Implicit_Lobatto_IIIC_2_2, Implicit_Lobatto_IIIA_3_4,
// Implicit_Lobatto_IIIB_3_4, Implicit_Lobatto_IIIC_3_4, Implicit_Radau_IIA_3_5, Implicit_SDIRK_5_4.
// Embedded explicit methods:
// Explicit_HEUN_EULER_2_12_embedded, Explicit_BOGACKI_SHAMPINE_4_23_embedded, Explicit_FEHLBERG_6_45_embedded,
// Explicit_CASH_KARP_6_45_embedded, Explicit_DORMAND_PRINCE_7_45_embedded.
// Embedded implicit methods:
// Implicit_SDIRK_CASH_3_23_embedded, Implicit_ESDIRK_TRBDF2_3_23_embedded, Implicit_ESDIRK_TRX2_3_23_embedded,
// Implicit_SDIRK_BILLINGTON_3_23_embedded, Implicit_SDIRK_CASH_5_24_embedded, Implicit_SDIRK_CASH_5_34_embedded,
// Implicit_DIRK_ISMAIL_7_45_embedded.
ButcherTableType butcher_table_type = Implicit_SDIRK_CASH_3_23_embedded;
// Boundary markers.
const std::string BDY_FIRE = "Bottom";
const std::string BDY_LEFT = "Left";
const std::string BDY_RIGHT = "Right";
const std::string BDY_AIR = "Top";
// Problem parameters.
// Initial temperature.
const double TEMP_INIT = 20;
// Exterior temperature top;
const double TEMP_EXT_AIR = 20;
// Heat flux coefficient on the bottom edge.
const double ALPHA_FIRE = 25;
// Heat flux coefficient on the top edge.
const double ALPHA_AIR = 8;
// Heat capacity.
const double HEATCAP = 1020;
// Material density.
const double RHO = 2200;
// Length of time interval in seconds.
const double T_FINAL = 18000;
int main(int argc, char* argv[])
{
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table_type);
if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());
// Turn off adaptive time stepping if R-K method is not embedded.
if (bt.is_embedded() == false && ADAPTIVE_TIME_STEP_ON == true) {
Hermes::Mixins::Loggable::Static::warn("R-K method not embedded, turning off adaptive time stepping.");
ADAPTIVE_TIME_STEP_ON = false;
}
// Load the mesh.
MeshSharedPtr mesh(new Mesh), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("wall.mesh", basemesh);
mesh->copy(basemesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary(BDY_RIGHT, 2);
mesh->refine_towards_boundary(BDY_FIRE, INIT_REF_NUM_BDY);
// Initialize essential boundary conditions (none).
EssentialBCs<double> bcs;
// Initialize an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof = Space<double>::get_num_dofs(space);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Convert initial condition into a Solution.
MeshFunctionSharedPtr<double> sln_prev_time(new ConstantSolution<double>(mesh, TEMP_INIT));
// Initialize the weak formulation.
double current_time = 0;
WeakFormSharedPtr<double> wf(new CustomWeakFormHeatRK(BDY_FIRE, BDY_AIR, ALPHA_FIRE, ALPHA_AIR,
RHO, HEATCAP, TEMP_EXT_AIR, TEMP_INIT, ¤t_time));
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, space);
// Create a refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Visualize initial condition.
char title[100];
ScalarView sln_view("Initial condition", new WinGeom(0, 0, 1500, 360));
OrderView ordview("Initial mesh", new WinGeom(0, 410, 1500, 360));
ScalarView time_error_view("Temporal error", new WinGeom(0, 800, 1500, 360));
time_error_view.fix_scale_width(40);
ScalarView space_error_view("Spatial error", new WinGeom(0, 1220, 1500, 360));
space_error_view.fix_scale_width(40);
sln_view.show(sln_prev_time);
ordview.show(space);
// Graph for time step history.
SimpleGraph time_step_graph;
if (ADAPTIVE_TIME_STEP_ON) Hermes::Mixins::Loggable::Static::info("Time step history will be saved to file time_step_history.dat.");
// Class for projections.
OGProjection<double> ogProjection;
// Time stepping loop:
int ts = 1;
do
{
Hermes::Mixins::Loggable::Static::info("Begin time step %d.", ts);
// Periodic global derefinement.
if (ts > 1 && ts % UNREF_FREQ == 0)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
switch (UNREF_METHOD) {
case 1: mesh->copy(basemesh);
space->set_uniform_order(P_INIT);
break;
case 2: space->unrefine_all_mesh_elements();
space->set_uniform_order(P_INIT);
break;
case 3: space->unrefine_all_mesh_elements();
//space->adjust_element_order(-1, P_INIT);
space->adjust_element_order(-1, -1, P_INIT, P_INIT);
break;
default: throw Hermes::Exceptions::Exception("Wrong global derefinement method.");
}
space->assign_dofs();
ndof = Space<double>::get_num_dofs(space);
}
// Spatial adaptivity loop. Note: sln_prev_time must not be
// changed during spatial adaptivity.
MeshFunctionSharedPtr<double> ref_sln(new Solution<double>());
MeshFunctionSharedPtr<double> time_error_fn(new Solution<double>(mesh));
bool done = false; int as = 1;
double err_est;
do {
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
// Initialize Runge-Kutta time stepping on the reference mesh.
RungeKutta<double> runge_kutta(wf, ref_space, &bt);
try
{
ogProjection.project_global(ref_space, sln_prev_time,
sln_prev_time);
}
catch (Exceptions::Exception& e)
{
std::cout << e.what() << std::endl;
Hermes::Mixins::Loggable::Static::error("Projection failed.");
return -1;
}
// Runge-Kutta step on the fine mesh.
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step on fine mesh (t = %g s, tau = %g s, stages: %d).",
current_time, time_step, bt.get_size());
bool verbose = true;
bool jacobian_changed = false;
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
runge_kutta.set_newton_max_allowed_iterations(NEWTON_MAX_ITER);
runge_kutta.set_newton_tolerance(NEWTON_TOL_FINE);
runge_kutta.rk_time_step_newton(sln_prev_time, ref_sln, bt.is_embedded() ? time_error_fn : NULL);
}
catch (Exceptions::Exception& e)
{
std::cout << e.what() << std::endl;
Hermes::Mixins::Loggable::Static::error("Runge-Kutta time step failed");
return -1;
}
/* If ADAPTIVE_TIME_STEP_ON == true, estimate temporal error.
If too large or too small, then adjust it and restart the time step. */
double rel_err_time = 0;
if (bt.is_embedded() == true)
{
Hermes::Mixins::Loggable::Static::info("Calculating temporal error estimate.");
// Show temporal error.
char title[100];
sprintf(title, "Temporal error est, spatial adaptivity step %d", as);
time_error_view.set_title(title);
//time_error_view.show_mesh(false);
time_error_view.show(time_error_fn);
DefaultNormCalculator<double, HERMES_H1_NORM> normCalculator(1);
rel_err_time = 100. * normCalculator.calculate_norm(time_error_fn) / normCalculator.calculate_norm(ref_sln);
if (ADAPTIVE_TIME_STEP_ON == false) Hermes::Mixins::Loggable::Static::info("rel_err_time: %g%%", rel_err_time);
}
if (ADAPTIVE_TIME_STEP_ON)
{
if (rel_err_time > TIME_ERR_TOL_UPPER)
{
Hermes::Mixins::Loggable::Static::info("rel_err_time %g%% is above upper limit %g%%", rel_err_time, TIME_ERR_TOL_UPPER);
Hermes::Mixins::Loggable::Static::info("Decreasing tau from %g to %g s and restarting time step.",
time_step, time_step * TIME_STEP_DEC_RATIO);
time_step *= TIME_STEP_DEC_RATIO;
continue;
}
else if (rel_err_time < TIME_ERR_TOL_LOWER)
{
Hermes::Mixins::Loggable::Static::info("rel_err_time = %g%% is below lower limit %g%%", rel_err_time, TIME_ERR_TOL_LOWER);
Hermes::Mixins::Loggable::Static::info("Increasing tau from %g to %g s.", time_step, time_step * TIME_STEP_INC_RATIO);
time_step *= TIME_STEP_INC_RATIO;
}
else
{
Hermes::Mixins::Loggable::Static::info("rel_err_time = %g%% is in acceptable interval (%g%%, %g%%)",
rel_err_time, TIME_ERR_TOL_LOWER, TIME_ERR_TOL_UPPER);
}
// Add entry to time step history graph.
time_step_graph.add_values(current_time, time_step);
time_step_graph.save("time_step_history.dat");
}
/* Estimate spatial errors and perform mesh refinement */
Hermes::Mixins::Loggable::Static::info("Spatial adaptivity step %d.", as);
// Project the fine mesh solution onto the coarse mesh.
MeshFunctionSharedPtr<double> sln(new Solution<double>());
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation.");
ogProjection.project_global(space, ref_sln, sln);
// Show spatial error.
sprintf(title, "Spatial error est, spatial adaptivity step %d", as);
MeshFunctionSharedPtr<double> space_error_fn(new DiffFilter<double>(std::vector<MeshFunctionSharedPtr<double> >({ ref_sln, sln })));
space_error_view.set_title(title);
//space_error_view.show_mesh(false);
MeshFunctionSharedPtr<double> abs_sef(new AbsFilter(space_error_fn));
space_error_view.show(abs_sef);
// Calculate element errors and spatial error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating spatial error estimate.");
adaptivity.set_space(space);
errorCalculator.calculate_errors(sln, ref_sln);
double err_rel_space = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof: %d, ref_ndof: %d, err_rel_space: %g%%",
Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_rel_space);
// If err_est too large, adapt the mesh.
if (err_rel_space < SPACE_ERR_TOL) done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adaptivity.adapt(&selector);
// Increase the counter of performed adaptivity steps.
as++;
}
} while (done == false);
// Visualize the solution and mesh.
char title[100];
sprintf(title, "Solution, time %g s", current_time);
sln_view.set_title(title);
//sln_view.show_mesh(false);
sln_view.show(ref_sln);
sprintf(title, "Mesh, time %g s", current_time);
ordview.set_title(title);
ordview.show(space);
// Copy last reference solution into sln_prev_time
sln_prev_time->copy(ref_sln);
// Increase current time and counter of time steps.
current_time += time_step;
ts++;
} while (current_time < T_FINAL);
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/heat-transfer/wall-on-fire-adapt/definitions.cpp | .cpp | 4,747 | 139 | #include "definitions.h"
double lambda(double x, double y)
{
return 1.0;
}
template<typename Real>
Real T_fire_x(Real x)
{
return -(1. / 32.) * x*x*x + (3. / 16.) * x*x;
}
template<typename Real>
Real T_fire_t(Real t)
{
if (0. <= t && t <= 100.)
return 0.;
if (100. <= t && t <= 600.)
return 980. / 500. * (t - 100.);
if (600. <= t && t <= 1800.)
return 980.;
if (1800. <= t && t <= 3000.)
return 980. - 980. / 1200. * (t - 1800.);
return 0.;
}
CustomWeakFormHeatRK::CustomWeakFormHeatRK(std::string bdy_fire, std::string bdy_air,
double alpha_fire, double alpha_air, double rho, double heatcap,
double temp_ext_air, double temp_init, double* current_time_ptr) : WeakForm<double>(1)
{
// Jacobian - volumetric part.
add_matrix_form(new CustomJacobianVol(0, 0, rho, heatcap));
// Jacobian - surface part.
add_matrix_form_surf(new WeakFormsH1::DefaultMatrixFormSurf<double>(0, 0, bdy_fire, new Hermes2DFunction<double>(-alpha_fire / (rho*heatcap))));
add_matrix_form_surf(new WeakFormsH1::DefaultMatrixFormSurf<double>(0, 0, bdy_air, new Hermes2DFunction<double>(-alpha_air / (rho*heatcap))));
// Residual - volumetric part.
add_vector_form(new CustomFormResidualVol(0, rho, heatcap));
// Surface residual - bottom boundary.
CustomFormResidualSurfFire* vec_form_surf_1
= new CustomFormResidualSurfFire(0, bdy_fire, alpha_fire, rho, heatcap, current_time_ptr);
add_vector_form_surf(vec_form_surf_1);
// Surface residual - top boundary.
add_vector_form_surf(new WeakFormsH1::DefaultResidualSurf<double>(0, HERMES_ANY, new Hermes2DFunction<double>(-alpha_air / (rho*heatcap))));
add_vector_form_surf(new WeakFormsH1::DefaultVectorFormSurf<double>(0, HERMES_ANY, new Hermes2DFunction<double>(alpha_air* temp_ext_air / (rho*heatcap))));
}
double CustomWeakFormHeatRK::CustomJacobianVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0.;
for (int i = 0; i < n; i++)
{
result += wt[i] * lambda(e->x[i], e->y[i]) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
}
return -result / heatcap / rho;
}
Ord CustomWeakFormHeatRK::CustomJacobianVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return (u->dx[0] * v->dx[0] + u->dy[0] * v->dy[0]) * Ord(5);
}
MatrixFormVol<double>* CustomWeakFormHeatRK::CustomJacobianVol::clone() const
{
return new CustomJacobianVol(*this);
}
double CustomWeakFormHeatRK::CustomFormResidualVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
Func<double>* u_prev_newton = u_ext[0];
double result = 0.;
for (int i = 0; i < n; i++)
{
result += wt[i] * lambda(e->x[i], e->y[i])
* (u_prev_newton->dx[i] * v->dx[i] + u_prev_newton->dy[i] * v->dy[i]);
}
return -result / heatcap / rho;
}
Ord CustomWeakFormHeatRK::CustomFormResidualVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Func<Ord>* u_prev_newton = u_ext[0];
// Return the polynomial order of the gradient increased by five to account for lambda(x, y).
return (u_prev_newton->dx[0] * v->dx[0] + u_prev_newton->dy[0] * v->dy[0]) * Ord(5);
}
VectorFormVol<double>* CustomWeakFormHeatRK::CustomFormResidualVol::clone() const
{
return new CustomFormResidualVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormHeatRK::CustomFormResidualSurfFire::vector_form_surf(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomSurf<Real> *e, Func<Scalar>* *ext) const
{
Func<Scalar>* sln_prev = u_ext[0];
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (T_fire(e->x[i], *current_time_ptr) - sln_prev->val[i]) * v->val[i];
}
return result / heatcap / rho * alpha_fire;
}
double CustomWeakFormHeatRK::CustomFormResidualSurfFire::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomSurf<double> *e, Func<double>* *ext) const
{
return vector_form_surf<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakFormHeatRK::CustomFormResidualSurfFire::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
// Return the polynomial order of the test function 'v' plus three for T_fire_x(x)
return v->val[0] * Ord(3);
}
VectorFormSurf<double>* CustomWeakFormHeatRK::CustomFormResidualSurfFire::clone() const
{
return new CustomFormResidualSurfFire(*this);
}
template<typename Real>
Real CustomWeakFormHeatRK::CustomFormResidualSurfFire::T_fire(Real x, Real t) const
{
return T_fire_x(x) * T_fire_t(t) + 20.;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/advection-diffusion-reaction/linear-dg-adapt/definitions.h | .h | 4,119 | 112 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
class CustomWeakForm : public WeakForm<double>
{
public:
CustomWeakForm(std::string left_bottom_bnd_part, MeshSharedPtr mesh);
WeakForm<double>* clone() const;
private:
class CustomMatrixFormVol : public MatrixFormVol<double>
{
public:
CustomMatrixFormVol(int i, int j) : MatrixFormVol<double>(i, j) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar> **ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord> **ext) const;
MatrixFormVol<double>* clone() const;
};
class CustomVectorFormVol : public VectorFormVol<double>
{
public:
CustomVectorFormVol(int i) : VectorFormVol<double>(i) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v, GeomVol<Real> *e, Func<Scalar> **ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord> **ext) const;
VectorFormVol<double>* clone() const;
template<typename Real>
Real F(Real x, Real y) const;
};
class CustomMatrixFormSurface : public MatrixFormSurf<double>
{
public:
CustomMatrixFormSurface(int i, int j) : MatrixFormSurf<double>(i, j) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u, Func<Real> *v, GeomSurf<Real> *e, Func<Scalar> **ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord> **ext) const;
MatrixFormSurf<double>* clone() const;
};
class CustomMatrixFormInterface : public MatrixFormDG<double>
{
public:
CustomMatrixFormInterface(int i, int j) : MatrixFormDG<double>(i, j)
{
};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, DiscontinuousFunc<Scalar> **u_ext, DiscontinuousFunc<Real> *u, DiscontinuousFunc<Real> *v, InterfaceGeom<Real> *e, DiscontinuousFunc<Scalar> **ext) const;
virtual double value(int n, double *wt, DiscontinuousFunc<double> **u_ext, DiscontinuousFunc<double> *u, DiscontinuousFunc<double> *v, InterfaceGeom<double> *e, DiscontinuousFunc<double> **ext) const;
virtual Ord ord(int n, double *wt, DiscontinuousFunc<Ord> **u_ext, DiscontinuousFunc<Ord> *u, DiscontinuousFunc<Ord> *v, InterfaceGeom<Ord> *e, DiscontinuousFunc<Ord> **ext) const;
MatrixFormDG<double>* clone() const;
};
class CustomVectorFormSurface : public VectorFormSurf<double>
{
public:
CustomVectorFormSurface(int i, std::string left_bottom_bnd_part) : VectorFormSurf<double>(i)
{
this->set_area(left_bottom_bnd_part);
};
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord> **ext) const;
VectorFormSurf<double>* clone() const;
template<typename Real>
Real F(Real x, Real y) const;
};
double calculate_a_dot_v(double x, double y, double vx, double vy) const;
Ord calculate_a_dot_v(Ord x, Ord y, Ord vx, Ord vy) const;
double upwind_flux(double u_cent, double u_neib, double a_dot_n) const;
Ord upwind_flux(Ord u_cent, Ord u_neib, Ord a_dot_n) const;
MeshSharedPtr mesh;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/advection-diffusion-reaction/linear-dg-adapt/main.cpp | .cpp | 4,403 | 124 | #include "definitions.h"
// This example solves a linear advection equation using Dicontinuous Galerkin (DG) method.
// It is intended to show how evalutation of surface matrix forms that take basis functions defined
// on different elements work. It is the same example as linear-advection-dg, but with automatic adaptivity.
//
// PDE: \nabla \cdot (\Beta u) = 0, where \Beta = (-x_2, x_1) / |x| represents a circular counterclockwise flow field.
//
// Domain: Square (0, 1) x (0, 1).
//
// BC: Dirichlet, u = 1 where \Beta(x) \cdot n(x) < 0, that is on[0,0.5] x {0}, and g = 0 anywhere else.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF = 1;
// Initial polynomial degrees of mesh elements in vertical and horizontal directions.
int P_INIT = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.5;
// Use Taylor shapeset - which does not have order > 2 implemented.
// This switches to h-adaptivity & turns on Vertex-based limiting.
bool USE_TAYLOR_SHAPESET = false;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_L2_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = USE_TAYLOR_SHAPESET ? H2D_H_ANISO : H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-2;
int main(int argc, char* args[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF; i++)
mesh->refine_all_elements();
// Create an L2 space.
SpaceSharedPtr<double> fine_space(new L2Space<double>(mesh, USE_TAYLOR_SHAPESET ? std::max(P_INIT, 2) : P_INIT, (USE_TAYLOR_SHAPESET ? (Shapeset*)(new L2ShapesetTaylor) : (Shapeset*)(new L2ShapesetLegendre))));
// Initialize refinement selector.
L2ProjBasedSelector<double> selector(CAND_LIST);
selector.set_error_weights(1., 1., 1.);
MeshFunctionSharedPtr<double> sln(new Solution<double>);
MeshFunctionSharedPtr<double> refsln(new Solution<double>);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm("Bdy_bottom_left", mesh));
ScalarView view1("Solution", new WinGeom(900, 0, 450, 350));
view1.fix_scale_width(60);
// Initialize linear solver.
Hermes::Hermes2D::LinearSolver<double> linear_solver;
linear_solver.set_weak_formulation(wf);
adaptivity.set_space(fine_space);
int as = 1; bool done = false;
do
{
// Construct globally refined reference mesh
// and setup reference space->
Mesh::ReferenceMeshCreator ref_mesh_creator(mesh);
MeshSharedPtr ref_mesh = ref_mesh_creator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refspace_creator(fine_space, ref_mesh, 0);
SpaceSharedPtr<double> refspace = refspace_creator.create_ref_space();
try
{
linear_solver.set_space(refspace);
linear_solver.solve();
if (USE_TAYLOR_SHAPESET)
{
PostProcessing::VertexBasedLimiter limiter(refspace, linear_solver.get_sln_vector(), P_INIT);
refsln = limiter.get_solution();
}
else
{
Solution<double>::vector_to_solution(linear_solver.get_sln_vector(), refspace, refsln);
}
view1.show(refsln);
OGProjection<double>::project_global(fine_space, refsln, sln, HERMES_L2_NORM);
}
catch (Exceptions::Exception& e)
{
std::cout << e.info();
}
catch (std::exception& e)
{
std::cout << e.what();
}
// Calculate element errors and total error estimate.
errorCalculator.calculate_errors(sln, refsln);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
std::cout << "Error: " << err_est_rel << "%." << std::endl;
// If err_est_rel too large, adapt the mesh.
if (err_est_rel < ERR_STOP)
done = true;
else
done = adaptivity.adapt(&selector);
as++;
} while (done == false);
// Wait for keyboard or mouse input.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/advection-diffusion-reaction/linear-dg-adapt/definitions.cpp | .cpp | 6,911 | 193 | #include "definitions.h"
CustomWeakForm::CustomWeakForm(std::string left_bottom_bnd_part, MeshSharedPtr mesh) : WeakForm<double>(1), mesh(mesh)
{
add_matrix_form(new CustomMatrixFormVol(0, 0));
add_vector_form(new CustomVectorFormVol(0));
add_matrix_form_surf(new CustomMatrixFormSurface(0, 0));
add_matrix_form_DG(new CustomMatrixFormInterface(0, 0));
add_vector_form_surf(new CustomVectorFormSurface(0, left_bottom_bnd_part));
}
WeakForm<double>* CustomWeakForm::clone() const
{
return new CustomWeakForm(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomMatrixFormVol::matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u, Func<Real> *v,
GeomVol<Real> *e, Func<Scalar> **ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += -wt[i] * u->val[i] * static_cast<CustomWeakForm*>(wf)->calculate_a_dot_v(e->x[i], e->y[i], v->dx[i], v->dy[i]);
return result;
}
double CustomWeakForm::CustomMatrixFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double> **ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakForm::CustomMatrixFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord> **ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* CustomWeakForm::CustomMatrixFormVol::clone() const
{
return new CustomWeakForm::CustomMatrixFormVol(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomVectorFormVol::vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
GeomVol<Real> *e, Func<Scalar> **ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += wt[i] * F(e->x[i], e->y[i]) * v->val[i];
return result;
}
double CustomWeakForm::CustomVectorFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double> **ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord CustomWeakForm::CustomVectorFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord> **ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormVol<double>* CustomWeakForm::CustomVectorFormVol::clone() const
{
return new CustomWeakForm::CustomVectorFormVol(*this);
}
template<typename Real>
Real CustomWeakForm::CustomVectorFormVol::F(Real x, Real y) const
{
return Real(0);
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomMatrixFormSurface::matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u, Func<Real> *v,
GeomSurf<Real> *e, Func<Scalar> **ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
{
Real x = e->x[i], y = e->y[i];
Real a_dot_n = Real(static_cast<CustomWeakForm*>(wf)->calculate_a_dot_v(x, y, e->nx[i], e->ny[i]));
result += wt[i] * static_cast<CustomWeakForm*>(wf)->upwind_flux(u->val[i], Scalar(0), a_dot_n) * v->val[i];
}
return result;
}
double CustomWeakForm::CustomMatrixFormSurface::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomSurf<double> *e, Func<double> **ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakForm::CustomMatrixFormSurface::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord> **ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormSurf<double>* CustomWeakForm::CustomMatrixFormSurface::clone() const
{
return new CustomWeakForm::CustomMatrixFormSurface(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakForm::CustomMatrixFormInterface::matrix_form(int n, double *wt, DiscontinuousFunc<Scalar>** u_ext, DiscontinuousFunc<Real> *u, DiscontinuousFunc<Real> *v,
InterfaceGeom<Real> *e, DiscontinuousFunc<Scalar> **ext) const
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++) {
Real a_dot_n = static_cast<CustomWeakForm*>(wf)->calculate_a_dot_v(e->x[i], e->y[i], e->nx[i], e->ny[i]);
Real jump_v = (v->fn_central == nullptr ? -v->val_neighbor[i] : v->val[i]);
if (u->fn_central == nullptr)
result += wt[i] * static_cast<CustomWeakForm*>(wf)->upwind_flux(Scalar(0), u->val_neighbor[i], a_dot_n) * jump_v;
else
result += wt[i] * static_cast<CustomWeakForm*>(wf)->upwind_flux(u->val[i], Scalar(0), a_dot_n) * jump_v;
}
return result;
}
double CustomWeakForm::CustomMatrixFormInterface::value(int n, double *wt, DiscontinuousFunc<double> **u_ext, DiscontinuousFunc<double> *u, DiscontinuousFunc<double> *v,
InterfaceGeom<double> *e, DiscontinuousFunc<double> **ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord CustomWeakForm::CustomMatrixFormInterface::ord(int n, double *wt, DiscontinuousFunc<Ord> **u_ext, DiscontinuousFunc<Ord> *u, DiscontinuousFunc<Ord> *v,
InterfaceGeom<Ord> *e, DiscontinuousFunc<Ord> **ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormDG<double>* CustomWeakForm::CustomMatrixFormInterface::clone() const
{
return new CustomWeakForm::CustomMatrixFormInterface(*this);
}
double CustomWeakForm::CustomVectorFormSurface::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomSurf<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++) {
double x = e->x[i], y = e->y[i];
double a_dot_n = static_cast<CustomWeakForm*>(wf)->calculate_a_dot_v(x, y, e->nx[i], e->ny[i]);
// Function values for Dirichlet boundary conditions.
result += -wt[i] * static_cast<CustomWeakForm*>(wf)->upwind_flux(0, 1, a_dot_n) * v->val[i];
}
return result;
}
Ord CustomWeakForm::CustomVectorFormSurface::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord> **ext) const
{
Ord result = Ord(0);
for (int i = 0; i < n; i++)
result += -wt[i] * v->val[i];
return result;
}
VectorFormSurf<double>* CustomWeakForm::CustomVectorFormSurface::clone() const
{
return new CustomWeakForm::CustomVectorFormSurface(*this);
}
template<typename Real>
Real CustomWeakForm::CustomVectorFormSurface::F(Real x, Real y) const
{
return 0;
}
double CustomWeakForm::calculate_a_dot_v(double x, double y, double vx, double vy) const
{
double norm = std::max<double>(1e-12, std::sqrt(sqr(x) + sqr(y)));
return -y / norm*vx + x / norm*vy;
}
Ord CustomWeakForm::calculate_a_dot_v(Ord x, Ord y, Ord vx, Ord vy) const
{
return Ord(10);
}
double CustomWeakForm::upwind_flux(double u_cent, double u_neib, double a_dot_n) const
{
return a_dot_n * (a_dot_n >= 0 ? u_cent : u_neib);
}
Ord CustomWeakForm::upwind_flux(Ord u_cent, Ord u_neib, Ord a_dot_n) const
{
return a_dot_n * (u_cent + u_neib);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/advection-diffusion-reaction/linear/definitions.h | .h | 1,685 | 56 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
class WeakFormLinearAdvectionDiffusion : public WeakForm < double >
{
public:
// Problem parameters.
double const_f;
WeakFormLinearAdvectionDiffusion(bool stabilization_on, bool shock_capturing_on, double b1, double b2, double epsilon);
private:
class MatrixFormVolAdvectionDiffusion : public MatrixFormVol < double >
{
public:
MatrixFormVolAdvectionDiffusion(unsigned int i, unsigned int j, double b1, double b2, double epsilon)
: MatrixFormVol<double>(i, j), b1(b1), b2(b2), epsilon(epsilon) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const;
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
// Members.
double b1, b2, epsilon;
};
// Members.
bool stabilization_on;
bool shock_capturing_on;
};
/* Essential BC */
class EssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConst(std::string marker) : EssentialBoundaryCondition<double>(marker) {};
~EssentialBCNonConst() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/advection-diffusion-reaction/linear/main.cpp | .cpp | 6,379 | 175 | #include "definitions.h"
// This example solves a linear advection diffusion problem using optional
// variational multiscale stabilization. To use the stabilization, you must
// uncomment the definition of H2D_SECOND_DERIVATIVES_ENABLED in h2d_common.h
// and rebuild this example. Note that in our experience, the stabilization
// does only work for linear elements. Nevertheless, we were able to solve the
// problem without stabilization using adaptive hp-FEM.
//
// PDE: div(bu - \epsilon \nabla u) = 0 where b = (b1, b2) is a constant vector.
//
// Domain: Square (0, 1)x(0, 1).
//
// BC: Dirichlet, see the function double essential_bc_values() below.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 1;
// Stabilization on/off (assumes that H2D_SECOND_DERIVATIVES_ENABLED is defined).
const bool STABILIZATION_ON = true;
// Shock capturing on/off.
const bool SHOCK_CAPTURING_ON = true;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// Number of initial uniform mesh refinements in the boundary layer region.
const int INIT_REF_NUM_BDY = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// Predefined list of element refinement candidates.
const CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-1;
// Problem parameters.
// Diffusivity.
const double EPSILON = 0.01;
// Advection direction, div(B) = 0.
const double B1 = 1., B2 = 1.;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square_quad.mesh", mesh);
// mloader.load("square_tri.mesh", mesh);
// Perform initial mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary("Layer", INIT_REF_NUM_BDY);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormLinearAdvectionDiffusion(STABILIZATION_ON, SHOCK_CAPTURING_ON, B1, B2, EPSILON));
// Initialize boundary conditions
DefaultEssentialBCConst<double> bc_rest("Rest", 1.0);
EssentialBCNonConst bc_layer("Layer");
EssentialBCs<double> bcs({ &bc_rest, &bc_layer });
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
WinGeom* sln_win_geom = new WinGeom(0, 0, 440, 350);
WinGeom* mesh_win_geom = new WinGeom(450, 0, 400, 350);
// Initialize coarse and reference mesh solution.
MeshFunctionSharedPtr<double> sln(new Solution<double>), ref_sln(new Solution<double>);
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
ScalarView sview("Solution", new WinGeom(0, 0, 440, 350));
sview.fix_scale_width(50);
sview.show_mesh(false);
OrderView oview("Polynomial orders", new WinGeom(450, 0, 400, 350));
// DOF and CPU convergence graphs initialization.
SimpleGraph graph_dof, graph_cpu;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Adaptivity loop:
int as = 1;
bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Construct globally refined reference mesh and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
// Assemble the reference problem.
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
LinearSolver<double> solver(wf, ref_space);
// Time measurement.
cpu_time.tick();
// Solve the linear system of the reference problem.
// If successful, obtain the solution.
solver.solve();
Solution<double>::vector_to_solution(solver.get_sln_vector(), ref_space, ref_sln);
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
OGProjection<double>::project_global(space, ref_sln, sln);
// Time measurement.
cpu_time.tick();
// View the coarse mesh solution and polynomial orders.
sview.show(sln);
oview.show(space);
// Skip visualization time.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
adaptivity.set_space(space);
errorCalculator.calculate_errors(sln, ref_sln);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%",
Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_est_rel);
// Time measurement.
cpu_time.tick();
// Add entry to DOF and CPU convergence graphs.
graph_dof.add_values(Space<double>::get_num_dofs(space), err_est_rel);
graph_dof.save("conv_dof_est.dat");
graph_cpu.add_values(cpu_time.accumulated(), err_est_rel);
graph_cpu.save("conv_cpu_est.dat");
// If err_est too large, adapt the mesh.
if (err_est_rel < ERR_STOP) done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
done = adaptivity.adapt(&selector);
// Increase the counter of performed adaptivity steps.
if (done == false) as++;
}
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Show the reference solution - the final result.
sview.set_title("Fine mesh solution");
sview.show_mesh(false);
sview.show(ref_sln);
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/advection-diffusion-reaction/linear/definitions.cpp | .cpp | 2,766 | 67 | #include "definitions.h"
WeakFormLinearAdvectionDiffusion::WeakFormLinearAdvectionDiffusion(bool stabilization_on, bool shock_capturing_on, double b1, double b2, double epsilon)
: WeakForm<double>(1), stabilization_on(stabilization_on), shock_capturing_on(shock_capturing_on)
{
add_matrix_form(new MatrixFormVolAdvectionDiffusion(0, 0, b1, b2, epsilon));
}
template<typename Real, typename Scalar>
Scalar WeakFormLinearAdvectionDiffusion::MatrixFormVolAdvectionDiffusion::matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
Scalar result = Scalar(0);
Scalar h_e = e->get_diam_approximation(n);
Real s_c = Real(0.9);
for (int i = 0; i < n; i++)
{
result += wt[i] * (epsilon * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
- (b1 * u->val[i] * v->dx[i] + b2 * u->val[i] * v->dy[i]));
if (static_cast<WeakFormLinearAdvectionDiffusion*>(wf)->shock_capturing_on) {
Real R_squared = Hermes::pow(b1 * u->dx[i] + b2 * u->dy[i], 2.);
Real R = Hermes::sqrt(R_squared); //This just does fabs(b1 * u->dx[i] + b2 * u->dy[i]); but it can be parsed
result += wt[i] * s_c * 0.5 * h_e * R *
(u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]) /
(Hermes::sqrt(Hermes::pow(u->dx[i], 2) + Hermes::pow(u->dy[i], 2)) + 1.e-8);
}
#ifdef H2D_SECOND_DERIVATIVES_ENABLED
if (static_cast<WeakFormLinearAdvectionDiffusion*>(wf)->stabilization_on)
{
double b_norm = Hermes::sqrt(b1*b1 + b2*b2);
Real tau = 1. / Hermes::sqrt(9 * Hermes::pow(4 * epsilon / Hermes::pow(h_e, 2), 2) + Hermes::pow(2 * b_norm / h_e, 2));
result += wt[i] * tau * (-b1 * v->dx[i] - b2 * v->dy[i] + epsilon * v->laplace[i])
* (-b1 * u->dx[i] - b2 * u->dy[i] + epsilon * u->laplace[i]);
}
#endif
}
return result;
}
MatrixFormVol<double>* WeakFormLinearAdvectionDiffusion::MatrixFormVolAdvectionDiffusion::clone() const
{
return new WeakFormLinearAdvectionDiffusion::MatrixFormVolAdvectionDiffusion(*this);
}
double WeakFormLinearAdvectionDiffusion::MatrixFormVolAdvectionDiffusion::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord WeakFormLinearAdvectionDiffusion::MatrixFormVolAdvectionDiffusion::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
EssentialBCValueType EssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConst::value(double x, double y) const
{
return 2 - std::pow(x, 0.1) - std::pow(y, 0.1);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/euler_util.cpp | .cpp | 56,369 | 1,284 | #include "euler_util.h"
#include "limits.h"
#include <limits>
// Calculates energy from other quantities.
double QuantityCalculator::calc_energy(double rho, double rho_v_x, double rho_v_y, double pressure, double kappa)
{
double to_return = pressure / (kappa - 1.0) + (rho_v_x*rho_v_x + rho_v_y*rho_v_y) / (2.0*rho);
if (std::abs(to_return) < 1E-12 || to_return < 0.0)
return 1E-12;
return to_return;
}
// Calculates pressure from other quantities.
double QuantityCalculator::calc_pressure(double rho, double rho_v_x, double rho_v_y, double energy, double kappa)
{
double to_return = (kappa - 1.0) * (energy - (rho_v_x*rho_v_x + rho_v_y*rho_v_y) / (2.0*rho));
if (std::abs(to_return) < 1E-12 || to_return < 0.0)
return 1E-12;
return to_return;
}
// Calculates speed of sound.
double QuantityCalculator::calc_sound_speed(double rho, double rho_v_x, double rho_v_y, double energy, double kappa)
{
double to_return = std::sqrt(kappa * calc_pressure(rho, rho_v_x, rho_v_y, energy, kappa) / rho);
if (std::abs(to_return) < 1E-12 || to_return < 0.0)
return 1E-12;
return to_return;
}
CFLCalculation::CFLCalculation(double CFL_number, double kappa) : CFL_number(CFL_number), kappa(kappa)
{
}
void CFLCalculation::calculate(std::vector<MeshFunctionSharedPtr<double> > solutions, MeshSharedPtr mesh, double & time_step) const
{
// Create spaces of constant functions over the given mesh->
SpaceSharedPtr<double> constant_rho_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_rho_v_x_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_rho_v_y_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_energy_space(new L2Space<double>(mesh, 0));
double* sln_vector = new double[constant_rho_space->get_num_dofs() * 4];
OGProjection<double> ogProjection;
ogProjection.project_global(std::vector<SpaceSharedPtr<double> >({ constant_rho_space, constant_rho_v_x_space, constant_rho_v_y_space, constant_energy_space }), solutions, sln_vector);
// Determine the time step according to the CFL condition.
double min_condition = 0;
Element *e;
for_all_active_elements(e, mesh)
{
AsmList<double> al;
constant_rho_space->get_element_assembly_list(e, &al);
double rho = sln_vector[al.get_dof()[0]];
constant_rho_v_x_space->get_element_assembly_list(e, &al);
double v1 = sln_vector[al.get_dof()[0]] / rho;
constant_rho_v_y_space->get_element_assembly_list(e, &al);
double v2 = sln_vector[al.get_dof()[0]] / rho;
constant_energy_space->get_element_assembly_list(e, &al);
double energy = sln_vector[al.get_dof()[0]];
e->calc_area();
double condition = e->area * CFL_number / (std::sqrt(v1*v1 + v2*v2) + QuantityCalculator::calc_sound_speed(rho, rho*v1, rho*v2, energy, kappa));
if (condition < min_condition || min_condition == 0.)
min_condition = condition;
}
time_step = min_condition;
delete[] sln_vector;
}
void CFLCalculation::calculate_semi_implicit(std::vector<MeshFunctionSharedPtr<double> > solutions, MeshSharedPtr mesh, double & time_step) const
{
// Create spaces of constant functions over the given mesh->
SpaceSharedPtr<double> constant_rho_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_rho_v_x_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_rho_v_y_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_energy_space(new L2Space<double>(mesh, 0));
double* sln_vector = new double[constant_rho_space->get_num_dofs() * 4];
OGProjection<double> ogProjection;
ogProjection.project_global(std::vector<SpaceSharedPtr<double> >({ constant_rho_space, constant_rho_v_x_space, constant_rho_v_y_space, constant_energy_space }), solutions, sln_vector);
// Determine the time step according to the CFL condition.
double min_condition = 0;
Element *e;
double w[4];
for_all_active_elements(e, mesh)
{
AsmList<double> al;
constant_rho_space->get_element_assembly_list(e, &al);
w[0] = sln_vector[al.get_dof()[0]];
constant_rho_v_x_space->get_element_assembly_list(e, &al);
w[1] = sln_vector[al.get_dof()[0]];
constant_rho_v_y_space->get_element_assembly_list(e, &al);
w[2] = sln_vector[al.get_dof()[0]];
constant_energy_space->get_element_assembly_list(e, &al);
w[3] = sln_vector[al.get_dof()[0]];
double edge_length_max_lambda = 0.0;
solutions[0]->set_active_element(e);
for (unsigned int edge_i = 0; edge_i < e->get_nvert(); edge_i++) {
// Initialization.
SurfPos surf_pos;
surf_pos.marker = e->marker;
surf_pos.surf_num = edge_i;
int eo = solutions[1]->get_quad_2d()->get_edge_points(surf_pos.surf_num, 20, e->get_mode());
double3* tan = NULL;
GeomSurf<double>* geom = init_geom_surf(solutions[0]->get_refmap(), surf_pos.surf_num, surf_pos.marker, eo, tan);
int np = solutions[1]->get_quad_2d()->get_num_points(eo, e->get_mode());
// Calculation of the edge length.
double edge_length = std::sqrt(std::pow(e->vn[(edge_i + 1) % e->get_nvert()]->x - e->vn[edge_i]->x, 2) + std::pow(e->vn[(edge_i + 1) % e->get_nvert()]->y - e->vn[edge_i]->y, 2));
// Calculation of the maximum eigenvalue of the matrix P.
double max_eigen_value = 0.0;
for (int point_i = 0; point_i < np; point_i++) {
// Transform to the local coordinates.
double transformed[4];
transformed[0] = w[0];
transformed[1] = geom->nx[point_i] * w[1] + geom->ny[point_i] * w[2];
transformed[2] = -geom->ny[point_i] * w[1] + geom->nx[point_i] * w[2];
transformed[3] = w[3];
// Calc sound speed.
double a = QuantityCalculator::calc_sound_speed(transformed[0], transformed[1], transformed[2], transformed[3], kappa);
// Calc max eigenvalue.
if (transformed[1] / transformed[0] - a > max_eigen_value || point_i == 0)
max_eigen_value = transformed[1] / transformed[0] - a;
if (transformed[1] / transformed[0] > max_eigen_value)
max_eigen_value = transformed[1] / transformed[0];
if (transformed[1] / transformed[0] + a > max_eigen_value)
max_eigen_value = transformed[1] / transformed[0] + a;
}
if (edge_length * max_eigen_value > edge_length_max_lambda || edge_i == 0)
edge_length_max_lambda = edge_length * max_eigen_value;
delete geom;
}
e->calc_area();
double condition = e->area * CFL_number / edge_length_max_lambda;
if (condition < min_condition || min_condition == 0.)
min_condition = condition;
}
time_step = min_condition;
delete[] sln_vector;
}
void CFLCalculation::set_number(double new_CFL_number)
{
this->CFL_number = new_CFL_number;
}
ADEStabilityCalculation::ADEStabilityCalculation(double AdvectionRelativeConstant, double DiffusionRelativeConstant, double epsilon)
: AdvectionRelativeConstant(AdvectionRelativeConstant), DiffusionRelativeConstant(DiffusionRelativeConstant), epsilon(epsilon)
{
}
void ADEStabilityCalculation::calculate(std::vector<MeshFunctionSharedPtr<double> > solutions, MeshSharedPtr mesh, double & time_step)
{
// Create spaces of constant functions over the given mesh->
SpaceSharedPtr<double> constant_rho_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_rho_v_x_space(new L2Space<double>(mesh, 0));
SpaceSharedPtr<double> constant_rho_v_y_space(new L2Space<double>(mesh, 0));
double* sln_vector = new double[constant_rho_space->get_num_dofs() * 3];
OGProjection<double> ogProjection;
ogProjection.project_global({ constant_rho_space, constant_rho_v_x_space, constant_rho_v_y_space }, solutions, sln_vector);
// Determine the time step according to the conditions.
double min_condition_advection = 0.;
double min_condition_diffusion = 0.;
Element *e;
for_all_active_elements(e, mesh)
{
AsmList<double> al;
constant_rho_space->get_element_assembly_list(e, &al);
double rho = sln_vector[al.get_dof()[0]];
constant_rho_v_x_space->get_element_assembly_list(e, &al);
double v1 = sln_vector[al.get_dof()[0] + constant_rho_space->get_num_dofs()] / rho;
constant_rho_v_y_space->get_element_assembly_list(e, &al);
double v2 = sln_vector[al.get_dof()[0] + 2 * constant_rho_space->get_num_dofs()] / rho;
e->calc_area();
e->calc_diameter();
double condition_advection = AdvectionRelativeConstant * e->diameter / std::sqrt(v1*v1 + v2*v2);
double condition_diffusion = DiffusionRelativeConstant * e->area / epsilon;
if (condition_advection < min_condition_advection || min_condition_advection == 0.)
min_condition_advection = condition_advection;
if (condition_diffusion < min_condition_diffusion || min_condition_diffusion == 0.)
min_condition_diffusion = condition_diffusion;
}
time_step = std::min(min_condition_advection, min_condition_diffusion);
delete[] sln_vector;
}
DiscontinuityDetector::DiscontinuityDetector(std::vector<SpaceSharedPtr<double> > spaces,
std::vector<MeshFunctionSharedPtr<double> > solutions) : spaces(spaces), solutions(solutions)
{
for (int i = 0; i < solutions.size(); i++)
this->solutionsInternal.push_back((Solution<double>*)solutions[i].get());
};
DiscontinuityDetector::~DiscontinuityDetector()
{};
KrivodonovaDiscontinuityDetector::KrivodonovaDiscontinuityDetector(std::vector<SpaceSharedPtr<double> > spaces,
std::vector<MeshFunctionSharedPtr<double> > solutions) : DiscontinuityDetector(spaces, solutions)
{
// A check that all meshes are the same in the spaces.
unsigned int mesh0_seq = spaces[0]->get_mesh()->get_seq();
for (unsigned int i = 0; i < spaces.size(); i++)
if (spaces[i]->get_mesh()->get_seq() != mesh0_seq)
throw Hermes::Exceptions::Exception("So far DiscontinuityDetector works only for single mesh->");
mesh = spaces[0]->get_mesh();
};
KrivodonovaDiscontinuityDetector::~KrivodonovaDiscontinuityDetector()
{};
double KrivodonovaDiscontinuityDetector::calculate_h(Element* e, int polynomial_order)
{
double h = std::sqrt(std::pow(e->vn[(0 + 1) % e->get_nvert()]->x - e->vn[0]->x, 2) + std::pow(e->vn[(0 + 1) % e->get_nvert()]->y - e->vn[0]->y, 2));
for (int edge_i = 0; edge_i < e->get_nvert(); edge_i++) {
double edge_length = std::sqrt(std::pow(e->vn[(edge_i + 1) % e->get_nvert()]->x - e->vn[edge_i]->x, 2) + std::pow(e->vn[(edge_i + 1) % e->get_nvert()]->y - e->vn[edge_i]->y, 2));
if (edge_length < h)
h = edge_length;
}
return std::pow(h, (0.5 * (H2D_GET_H_ORDER(spaces[0]->get_element_order(e->id))
+
H2D_GET_V_ORDER(spaces[0]->get_element_order(e->id)))
+ 1) / 2);
}
std::set<int>& KrivodonovaDiscontinuityDetector::get_discontinuous_element_ids()
{
return get_discontinuous_element_ids(1.0);
};
std::set<int>& KrivodonovaDiscontinuityDetector::get_discontinuous_element_ids(double threshold)
{
Element* e;
for_all_active_elements(e, mesh)
{
bool element_inserted = false;
for (int edge_i = 0; edge_i < e->get_nvert() && !element_inserted; edge_i++)
if (calculate_relative_flow_direction(e, edge_i) < 0 && !e->en[edge_i]->bnd)
{
double jumps[4];
calculate_jumps(e, edge_i, jumps);
double diameter_indicator = calculate_h(e, spaces[0]->get_element_order(e->id));
double edge_length = std::sqrt(std::pow(e->vn[(edge_i + 1) % e->get_nvert()]->x - e->vn[edge_i]->x, 2) + std::pow(e->vn[(edge_i + 1) % e->get_nvert()]->y - e->vn[edge_i]->y, 2));
double norms[4];
calculate_norms(e, edge_i, norms);
// Number of component jumps tested.
unsigned int component_checked_number = 1;
for (unsigned int component_i = 0; component_i < component_checked_number; component_i++) {
if (norms[component_i] < 1E-8)
continue;
double discontinuity_detector = jumps[component_i] / (diameter_indicator * edge_length * norms[component_i]);
if (discontinuity_detector > threshold)
{
discontinuous_element_ids.insert(e->id);
element_inserted = true;
break;
}
}
}
}
return discontinuous_element_ids;
};
double KrivodonovaDiscontinuityDetector::calculate_relative_flow_direction(Element* e, int edge_i)
{
// Set active element to the two solutions (density_vel_x, density_vel_y).
solutions[1]->set_active_element(e);
solutions[2]->set_active_element(e);
// Set Geometry.
SurfPos surf_pos;
surf_pos.marker = e->marker;
surf_pos.surf_num = edge_i;
int eo = solutions[1]->get_quad_2d()->get_edge_points(surf_pos.surf_num, 20, e->get_mode());
double3* pt = solutions[1]->get_quad_2d()->get_points(eo, e->get_mode());
int np = solutions[1]->get_quad_2d()->get_num_points(eo, e->get_mode());
double3* tan;
GeomSurf<double>* geom = init_geom_surf(solutions[1]->get_refmap(), surf_pos.surf_num, surf_pos.marker, eo, tan);
double* jwt = new double[np];
for (int i = 0; i < np; i++)
jwt[i] = pt[i][2] * tan[i][2];
// Calculate.
Func<double>* density_vel_x = init_fn(solutions[1].get(), eo);
Func<double>* density_vel_y = init_fn(solutions[2].get(), eo);
double result = 0.0;
for (int point_i = 0; point_i < np; point_i++)
result += jwt[point_i] * density_vel_x->val[point_i] * geom->nx[point_i] + density_vel_y->val[point_i] * geom->ny[point_i];
delete geom;
delete[] jwt;
delete density_vel_x;
delete density_vel_y;
return result;
};
void KrivodonovaDiscontinuityDetector::calculate_jumps(Element* e, int edge_i, double result[4])
{
// Set Geometry.
SurfPos surf_pos;
surf_pos.marker = e->marker;
surf_pos.surf_num = edge_i;
int eo = solutions[0]->get_quad_2d()->get_edge_points(surf_pos.surf_num, 8, e->get_mode());
double3* pt = solutions[0]->get_quad_2d()->get_points(eo, e->get_mode());
int np = solutions[0]->get_quad_2d()->get_num_points(eo, e->get_mode());
// Initialize the NeighborSearch.
NeighborSearch<double> ns(e, mesh);
ns.set_active_edge(edge_i);
// The values to be returned.
result[0] = 0.0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
// Go through all neighbors.
for (int neighbor_i = 0; neighbor_i < ns.get_num_neighbors(); neighbor_i++) {
ns.set_active_segment(neighbor_i);
// Set active element to the solutions.
solutions[0]->set_active_element(e);
solutions[1]->set_active_element(e);
solutions[2]->set_active_element(e);
solutions[3]->set_active_element(e);
// Push all the necessary transformations.
for (unsigned int trf_i = 0; trf_i < ns.get_central_n_trans(neighbor_i); trf_i++) {
solutions[0]->push_transform(ns.get_central_transformations(neighbor_i, trf_i));
solutions[1]->push_transform(ns.get_central_transformations(neighbor_i, trf_i));
solutions[2]->push_transform(ns.get_central_transformations(neighbor_i, trf_i));
solutions[3]->push_transform(ns.get_central_transformations(neighbor_i, trf_i));
}
double3* tan;
GeomSurf<double>* geom = init_geom_surf(solutions[0]->get_refmap(), surf_pos.surf_num, surf_pos.marker, eo, tan);
double* jwt = new double[np];
for (int i = 0; i < np; i++)
jwt[i] = pt[i][2] * tan[i][2];
// Prepare functions on the central element.
Func<double>* density = init_fn(solutions[0].get(), eo);
Func<double>* density_vel_x = init_fn(solutions[1].get(), eo);
Func<double>* density_vel_y = init_fn(solutions[2].get(), eo);
Func<double>* energy = init_fn(solutions[3].get(), eo);
// Set neighbor element to the solutions.
solutions[0]->set_active_element(ns.get_neighb_el());
solutions[1]->set_active_element(ns.get_neighb_el());
solutions[2]->set_active_element(ns.get_neighb_el());
solutions[3]->set_active_element(ns.get_neighb_el());
// Push all the necessary transformations.
for (unsigned int trf_i = 0; trf_i < ns.get_neighbor_n_trans(neighbor_i); trf_i++) {
solutions[0]->push_transform(ns.get_neighbor_transformations(neighbor_i, trf_i));
solutions[1]->push_transform(ns.get_neighbor_transformations(neighbor_i, trf_i));
solutions[2]->push_transform(ns.get_neighbor_transformations(neighbor_i, trf_i));
solutions[3]->push_transform(ns.get_neighbor_transformations(neighbor_i, trf_i));
}
// Prepare functions on the neighbor element.
Func<double>* density_neighbor = init_fn(solutions[0].get(), eo);
Func<double>* density_vel_x_neighbor = init_fn(solutions[1].get(), eo);
Func<double>* density_vel_y_neighbor = init_fn(solutions[2].get(), eo);
Func<double>* energy_neighbor = init_fn(solutions[3].get(), eo);
DiscontinuousFunc<double> density_discontinuous(density, density_neighbor, true);
DiscontinuousFunc<double> density_vel_x_discontinuous(density_vel_x, density_vel_x_neighbor, true);
DiscontinuousFunc<double> density_vel_y_discontinuous(density_vel_y, density_vel_y_neighbor, true);
DiscontinuousFunc<double> energy_discontinuous(energy, energy_neighbor, true);
for (int point_i = 0; point_i < np; point_i++) {
result[0] += jwt[point_i] * std::abs(density_discontinuous.val[point_i] - density_discontinuous.val_neighbor[point_i]);
result[1] += jwt[point_i] * std::abs(density_vel_x_discontinuous.val[point_i] - density_vel_x_discontinuous.val_neighbor[point_i]);
result[2] += jwt[point_i] * std::abs(density_vel_y_discontinuous.val[point_i] - density_vel_y_discontinuous.val_neighbor[point_i]);
result[3] += jwt[point_i] * std::abs(energy_discontinuous.val[point_i] - energy_discontinuous.val_neighbor[point_i]);
}
delete geom;
delete[] jwt;
delete density;
delete density_vel_x;
delete density_vel_y;
delete energy;
delete density_neighbor;
delete density_vel_x_neighbor;
delete density_vel_y_neighbor;
delete energy_neighbor;
}
result[0] = std::abs(result[0]);
result[1] = std::abs(result[1]);
result[2] = std::abs(result[2]);
result[3] = std::abs(result[3]);
};
void KrivodonovaDiscontinuityDetector::calculate_norms(Element* e, int edge_i, double result[4])
{
// Set active element to the solutions.
solutions[0]->set_active_element(e);
solutions[1]->set_active_element(e);
solutions[2]->set_active_element(e);
solutions[3]->set_active_element(e);
// The values to be returned.
result[0] = 0.0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
// Set Geometry.
SurfPos surf_pos;
surf_pos.marker = e->marker;
surf_pos.surf_num = edge_i;
int eo = solutions[0]->get_quad_2d()->get_edge_points(surf_pos.surf_num, 8, e->get_mode());
double3* pt = solutions[0]->get_quad_2d()->get_points(eo, e->get_mode());
int np = solutions[0]->get_quad_2d()->get_num_points(eo, e->get_mode());
double3* tan;
GeomSurf<double>* geom = init_geom_surf(solutions[0]->get_refmap(), surf_pos.surf_num, surf_pos.marker, eo, tan);
double* jwt = new double[np];
for (int i = 0; i < np; i++)
jwt[i] = pt[i][2] * tan[i][2];
// Calculate.
Func<double>* density = init_fn(solutions[0].get(), eo);
Func<double>* density_vel_x = init_fn(solutions[1].get(), eo);
Func<double>* density_vel_y = init_fn(solutions[2].get(), eo);
Func<double>* energy = init_fn(solutions[3].get(), eo);
for (int point_i = 0; point_i < np; point_i++) {
result[0] = std::max(result[0], std::abs(density->val[point_i]));
result[1] = std::max(result[1], std::abs(density_vel_x->val[point_i]));
result[2] = std::max(result[2], std::abs(density_vel_y->val[point_i]));
result[3] = std::max(result[3], std::abs(energy->val[point_i]));
}
delete geom;
delete[] jwt;
delete density;
delete density_vel_x;
delete density_vel_y;
delete energy;
};
KuzminDiscontinuityDetector::KuzminDiscontinuityDetector(std::vector<SpaceSharedPtr<double> > spaces,
std::vector<MeshFunctionSharedPtr<double> > solutions, bool limit_all_orders_independently) : DiscontinuityDetector(spaces, solutions), limit_all_orders_independently(limit_all_orders_independently)
{
// A check that all meshes are the same in the spaces.
unsigned int mesh0_seq = spaces[0]->get_mesh()->get_seq();
for (unsigned int i = 0; i < spaces.size(); i++)
if (spaces[i]->get_mesh()->get_seq() != mesh0_seq)
throw Hermes::Exceptions::Exception("So far DiscontinuityDetector works only for single mesh->");
mesh = spaces[0]->get_mesh();
};
KuzminDiscontinuityDetector::~KuzminDiscontinuityDetector()
{};
std::set<int>& KuzminDiscontinuityDetector::get_discontinuous_element_ids()
{
Element* e;
discontinuous_element_ids.clear();
oscillatory_element_idsRho.clear();
oscillatory_element_idsRhoVX.clear();
oscillatory_element_idsRhoVY.clear();
oscillatory_element_idsRhoE.clear();
for_all_active_elements(e, mesh)
{
if (!limit_all_orders_independently)
if (this->second_order_discontinuous_element_ids.find(e->id) == this->second_order_discontinuous_element_ids.end())
continue;
if (e->get_nvert() == 3)
throw Hermes::Exceptions::Exception("So far this limiter is implemented just for quads.");
double u_c[4], u_dx_c[4], u_dy_c[4];
double x_center, y_center, x_center_ref, y_center_ref;
e->get_center(x_center, y_center);
solutions[0]->get_refmap()->untransform(e, x_center, y_center, x_center_ref, y_center_ref);
find_centroid_values(e, u_c, x_center_ref, y_center_ref);
// Vertex values.
double u_i[4][4];
find_vertex_values(e, u_i);
// Boundaries for alpha_i calculation.
double u_i_min_first_order[4][4];
double u_i_max_first_order[4][4];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
u_i_min_first_order[i][j] = std::numeric_limits<double>::infinity();
u_i_max_first_order[i][j] = -std::numeric_limits<double>::infinity();
}
find_u_i_min_max_first_order(e, u_i_min_first_order, u_i_max_first_order);
// alpha_i calculation.
double alpha_i_first_order[4];
find_alpha_i_first_order(u_i_min_first_order, u_i_max_first_order, u_c, u_i, alpha_i_first_order);
// measure.
for (unsigned int i = 0; i < 4; i++)
{
if (1.0 > alpha_i_first_order[i])
{
// check for sanity.
if (std::abs(u_c[i]) > 1E-12)
discontinuous_element_ids.insert(e->id);
}
if (std::abs(u_c[i]) < 1e-3)
continue;
bool bnd = false;
for (unsigned int j = 0; j < 4; j++)
if (e->en[j]->bnd)
bnd = true;
if (bnd)
continue;
double high_limit = -std::numeric_limits<double>::infinity();
double low_limit = std::numeric_limits<double>::infinity();
for (unsigned int j = 0; j < 4; j++)
{
if (u_i_max_first_order[i][j] > high_limit)
high_limit = u_i_max_first_order[i][j];
if (u_i_min_first_order[i][j] < low_limit)
low_limit = u_i_min_first_order[i][j];
}
if (u_c[i] > high_limit && std::abs(u_c[i] - high_limit) > 1e-3)
{
high_limit = (u_i_max_first_order[i][0] + u_i_max_first_order[i][1] + u_i_max_first_order[i][2] + u_i_max_first_order[i][3] + u_i_min_first_order[i][0] + u_i_min_first_order[i][1] + u_i_min_first_order[i][2] + u_i_min_first_order[i][3]) / 8.0;
switch (i)
{
case 0:
oscillatory_element_idsRho.insert(std::pair<int, double>(e->id, high_limit));
break;
case 1:
oscillatory_element_idsRhoVX.insert(std::pair<int, double>(e->id, high_limit));
break;
case 2:
oscillatory_element_idsRhoVY.insert(std::pair<int, double>(e->id, high_limit));
break;
case 3:
oscillatory_element_idsRhoE.insert(std::pair<int, double>(e->id, high_limit));
break;
}
}
if (u_c[i] < low_limit && std::abs(u_c[i] - low_limit) > 1e-3)
{
low_limit = (u_i_max_first_order[i][0] + u_i_max_first_order[i][1] + u_i_max_first_order[i][2] + u_i_max_first_order[i][3] + u_i_min_first_order[i][0] + u_i_min_first_order[i][1] + u_i_min_first_order[i][2] + u_i_min_first_order[i][3]) / 8.0;
switch (i)
{
case 0:
oscillatory_element_idsRho.insert(std::pair<int, double>(e->id, low_limit));
break;
case 1:
oscillatory_element_idsRhoVX.insert(std::pair<int, double>(e->id, low_limit));
break;
case 2:
oscillatory_element_idsRhoVY.insert(std::pair<int, double>(e->id, low_limit));
break;
case 3:
oscillatory_element_idsRhoE.insert(std::pair<int, double>(e->id, low_limit));
break;
}
}
}
}
return discontinuous_element_ids;
}
std::set<int>& KuzminDiscontinuityDetector::get_second_order_discontinuous_element_ids()
{
Element* e;
for_all_active_elements(e, mesh)
{
if (e->get_nvert() == 3)
throw Hermes::Exceptions::Exception("So far this limiter is implemented just for quads.");
double c_x, c_y;
e->get_center(c_x, c_y);
double*** values = new double**[this->solutions.size()];
for (int i = 0; i < this->solutions.size(); i++)
values[i] = solutionsInternal[i]->get_ref_values_transformed(e, c_x, c_y);
// Vertex values.
double u_d_i[4][4][2];
find_vertex_derivatives(e, u_d_i);
// Boundaries for alpha_i calculation.
double u_d_i_min_second_order[4][4][2];
double u_d_i_max_second_order[4][4][2];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
for (int k = 0; k < 2; k++)
{
u_d_i_min_second_order[i][j][k] = std::numeric_limits<double>::infinity();
u_d_i_max_second_order[i][j][k] = -std::numeric_limits<double>::infinity();
}
find_u_i_min_max_second_order(e, u_d_i_min_second_order, u_d_i_max_second_order);
// alpha_i calculation.
double alpha_i_second_order[4];
find_alpha_i_second_order(u_d_i_min_second_order, u_d_i_max_second_order, values, values, u_d_i, alpha_i_second_order);
// measure.
for (unsigned int i = 0; i < 4; i++)
if (1.0 > alpha_i_second_order[i])
{
// check for sanity.
if (std::abs(values[i][0][1]) > 1E-12 || std::abs(values[i][0][2]) > 1E-12)
second_order_discontinuous_element_ids.insert(e->id);
}
}
return second_order_discontinuous_element_ids;
}
bool KuzminDiscontinuityDetector::get_limit_all_orders_independently()
{
return this->limit_all_orders_independently;
}
void KuzminDiscontinuityDetector::find_centroid_values(Hermes::Hermes2D::Element* e, double u_c[4], double x_ref, double y_ref)
{
for (unsigned int i = 0; i < this->solutions.size(); i++)
u_c[i] = solutionsInternal[i]->get_ref_value_transformed(e, x_ref, y_ref, 0, 0);
}
void KuzminDiscontinuityDetector::find_centroid_derivatives(Hermes::Hermes2D::Element* e, double u_dx_c[4], double u_dy_c[4], double x_ref, double y_ref)
{
for (unsigned int i = 0; i < this->solutions.size(); i++)
{
u_dx_c[i] = solutionsInternal[i]->get_ref_value_transformed(e, x_ref, y_ref, 0, 1);
u_dy_c[i] = solutionsInternal[i]->get_ref_value_transformed(e, x_ref, y_ref, 0, 2);
}
}
void KuzminDiscontinuityDetector::find_second_centroid_derivatives(Hermes::Hermes2D::Element* e, double u_dxx_c[4], double u_dxy_c[4], double u_dyy_c[4])
{
double c_x, c_y;
double c_ref_x, c_ref_y;
if (e->get_nvert() == 3)
{
c_x = (0.33333333333333333) * (e->vn[0]->x + e->vn[1]->x + e->vn[2]->x);
c_y = (0.33333333333333333) * (e->vn[0]->y + e->vn[1]->y + e->vn[2]->y);
}
else
{
c_x = (0.25) * (e->vn[0]->x + e->vn[1]->x + e->vn[2]->x + e->vn[3]->x);
c_y = (0.25) * (e->vn[0]->y + e->vn[1]->y + e->vn[2]->y + e->vn[3]->y);
}
for (unsigned int i = 0; i < this->solutions.size(); i++)
{
solutions[i]->set_active_element(e);
solutions[i]->get_refmap()->untransform(e, c_x, c_y, c_ref_x, c_ref_y);
u_dxx_c[i] = solutionsInternal[i]->get_ref_value_transformed(e, c_ref_x, c_ref_y, 0, 3);
u_dyy_c[i] = solutionsInternal[i]->get_ref_value_transformed(e, c_ref_x, c_ref_y, 0, 4);
u_dxy_c[i] = solutionsInternal[i]->get_ref_value_transformed(e, c_ref_x, c_ref_y, 0, 5);
}
}
void KuzminDiscontinuityDetector::find_vertex_values(Hermes::Hermes2D::Element* e, double vertex_values[4][4])
{
double c_ref_x, c_ref_y;
for (unsigned int i = 0; i < this->solutions.size(); i++)
{
for (unsigned int j = 0; j < e->get_nvert(); j++)
{
solutions[i]->get_refmap()->set_active_element(e);
solutions[i]->get_refmap()->untransform(e, e->vn[j]->x, e->vn[j]->y, c_ref_x, c_ref_y);
vertex_values[i][j] = solutionsInternal[i]->get_ref_value_transformed(e, c_ref_x, c_ref_y, 0, 0);
}
}
}
void KuzminDiscontinuityDetector::find_vertex_derivatives(Hermes::Hermes2D::Element* e, double vertex_derivatives[4][4][2])
{
double c_ref_x, c_ref_y;
for (unsigned int i = 0; i < this->solutions.size(); i++)
{
for (unsigned int j = 0; j < e->get_nvert(); j++)
{
solutions[i]->get_refmap()->set_active_element(e);
solutions[i]->get_refmap()->untransform(e, e->vn[j]->x, e->vn[j]->y, c_ref_x, c_ref_y);
vertex_derivatives[i][j][0] = solutionsInternal[i]->get_ref_value_transformed(e, c_ref_x, c_ref_y, 0, 1);
vertex_derivatives[i][j][1] = solutionsInternal[i]->get_ref_value_transformed(e, c_ref_x, c_ref_y, 0, 2);
}
}
}
void KuzminDiscontinuityDetector::find_u_i_min_max_first_order(Hermes::Hermes2D::Element* e, double u_i_min[4][4], double u_i_max[4][4])
{
for (unsigned int j = 0; j < e->get_nvert(); j++)
{
Hermes::Hermes2D::NeighborSearch<double> ns(e, mesh);
if (e->en[j]->bnd)
continue;
ns.set_active_edge(j);
// First beginning neighbors on every edge.
double u_c[4];
ns.set_active_segment(0);
Element* en = ns.get_neighb_el();
double x_center, y_center, x_center_ref, y_center_ref;
en->get_center(x_center, y_center);
solutions[0]->get_refmap()->untransform(en, x_center, y_center, x_center_ref, y_center_ref);
find_centroid_values(en, u_c, x_center_ref, y_center_ref);
for (unsigned int min_i = 0; min_i < 4; min_i++)
if (u_i_min[min_i][j] > u_c[min_i])
u_i_min[min_i][j] = u_c[min_i];
for (unsigned int max_i = 0; max_i < 4; max_i++)
if (u_i_max[max_i][j] < u_c[max_i])
u_i_max[max_i][j] = u_c[max_i];
// Second end neighbors on every edge.
ns.set_active_segment(ns.get_num_neighbors() - 1);
en = ns.get_neighb_el();
en->get_center(x_center, y_center);
solutions[0]->get_refmap()->untransform(en, x_center, y_center, x_center_ref, y_center_ref);
find_centroid_values(en, u_c, x_center_ref, y_center_ref);
for (unsigned int min_i = 0; min_i < 4; min_i++)
if (u_i_min[min_i][(j + 1) % e->get_nvert()] > u_c[min_i])
u_i_min[min_i][(j + 1) % e->get_nvert()] = u_c[min_i];
for (unsigned int max_i = 0; max_i < 4; max_i++)
if (u_i_max[max_i][(j + 1) % e->get_nvert()] < u_c[max_i])
u_i_max[max_i][(j + 1) % e->get_nvert()] = u_c[max_i];
// Now the hard part, neighbors' neighbors.
/// \todo This is where it fails for triangles, where it is much more complicated to look for elements sharing a vertex.
ns.set_active_segment(0);
Hermes::Hermes2D::NeighborSearch<double> ns_1(ns.get_neighb_el(), mesh);
if (ns.get_neighb_el()->en[(ns.get_neighbor_edge().local_num_of_edge + 1) % ns.get_neighb_el()->get_nvert()]->bnd)
continue;
ns_1.set_active_edge((ns.get_neighbor_edge().local_num_of_edge + 1) % ns.get_neighb_el()->get_nvert());
ns_1.set_active_segment(0);
en = ns_1.get_neighb_el();
en->get_center(x_center, y_center);
solutions[0]->get_refmap()->untransform(en, x_center, y_center, x_center_ref, y_center_ref);
find_centroid_values(en, u_c, x_center_ref, y_center_ref);
for (unsigned int min_i = 0; min_i < 4; min_i++)
if (u_i_min[min_i][j] > u_c[min_i])
u_i_min[min_i][j] = u_c[min_i];
for (unsigned int max_i = 0; max_i < 4; max_i++)
if (u_i_max[max_i][j] < u_c[max_i])
u_i_max[max_i][j] = u_c[max_i];
}
}
void KuzminDiscontinuityDetector::find_alpha_i_first_order(double u_i_min[4][4], double u_i_max[4][4], double u_c[4], double u_i[4][4], double alpha_i[4])
{
for (unsigned int sol_i = 0; sol_i < 4; sol_i++)
{
alpha_i[sol_i] = 1;
for (unsigned int vertex_i = 0; vertex_i < 4; vertex_i++)
{
// Sanity checks.
if (std::abs(u_i[sol_i][vertex_i] - u_c[sol_i]) < 1E-6)
continue;
if (std::abs((u_i_min[sol_i][vertex_i] - u_c[sol_i]) / u_c[sol_i]) > 10)
continue;
if (std::abs((u_i_max[sol_i][vertex_i] - u_c[sol_i]) / u_c[sol_i]) > 10)
continue;
if (u_i[sol_i][vertex_i] < u_c[sol_i])
{
if ((u_i_min[sol_i][vertex_i] - u_c[sol_i]) / (u_i[sol_i][vertex_i] - u_c[sol_i]) < alpha_i[sol_i])
alpha_i[sol_i] = (u_i_min[sol_i][vertex_i] - u_c[sol_i]) / (u_i[sol_i][vertex_i] - u_c[sol_i]);
}
else
{
if ((u_i_max[sol_i][vertex_i] - u_c[sol_i]) / (u_i[sol_i][vertex_i] - u_c[sol_i]) < alpha_i[sol_i])
alpha_i[sol_i] = (u_i_max[sol_i][vertex_i] - u_c[sol_i]) / (u_i[sol_i][vertex_i] - u_c[sol_i]);
}
}
}
}
void KuzminDiscontinuityDetector::find_alpha_i_first_order_real(Hermes::Hermes2D::Element* e, double u_i[4][4], double u_c[4], double u_dx_c[4], double u_dy_c[4], double alpha_i_real[4])
{
double c_x, c_y;
if (e->get_nvert() == 3)
{
c_x = (1 / 3) * (e->vn[0]->x + e->vn[1]->x + e->vn[2]->x);
c_y = (1 / 3) * (e->vn[0]->y + e->vn[1]->y + e->vn[2]->y);
}
else
{
c_x = (1 / 4) * (e->vn[0]->x + e->vn[1]->x + e->vn[2]->x + e->vn[3]->x);
c_y = (1 / 4) * (e->vn[0]->y + e->vn[1]->y + e->vn[2]->y + e->vn[3]->y);
}
alpha_i_real[0] = alpha_i_real[1] = alpha_i_real[2] = alpha_i_real[3] = -std::numeric_limits<double>::infinity();
for (unsigned int sol_i = 0; sol_i < this->solutions.size(); sol_i++)
for (unsigned int vertex_i = 0; vertex_i < e->get_nvert(); vertex_i++)
if ((u_i[sol_i][vertex_i] - u_c[sol_i]) / (u_dx_c[sol_i] * (e->vn[vertex_i]->x - c_x) + u_dy_c[sol_i] * (e->vn[vertex_i]->y - c_y)) > alpha_i_real[sol_i])
alpha_i_real[sol_i] = (u_i[sol_i][vertex_i] - u_c[sol_i]) / (u_dx_c[sol_i] * (e->vn[vertex_i]->x - c_x) + u_dy_c[sol_i] * (e->vn[vertex_i]->y - c_y));
}
void KuzminDiscontinuityDetector::find_u_i_min_max_second_order(Hermes::Hermes2D::Element* e, double u_d_i_min[4][4][2], double u_d_i_max[4][4][2])
{
for (unsigned int j = 0; j < e->get_nvert(); j++)
{
Hermes::Hermes2D::NeighborSearch<double> ns(e, mesh);
if (e->en[j]->bnd)
continue;
ns.set_active_edge(j);
// First beginning neighbors on every edge.
double u_dx_c[4], u_dy_c[4];
ns.set_active_segment(0);
Element* en = ns.get_neighb_el();
double x_center, y_center, x_center_ref, y_center_ref;
en->get_center(x_center, y_center);
solutions[0]->get_refmap()->untransform(en, x_center, y_center, x_center_ref, y_center_ref);
find_centroid_derivatives(en, u_dx_c, u_dy_c, x_center_ref, y_center_ref);
for (unsigned int min_i = 0; min_i < 4; min_i++)
{
if (u_d_i_min[min_i][j][0] > u_dx_c[min_i])
u_d_i_min[min_i][j][0] = u_dx_c[min_i];
if (u_d_i_min[min_i][j][1] > u_dy_c[min_i])
u_d_i_min[min_i][j][1] = u_dy_c[min_i];
}
for (unsigned int max_i = 0; max_i < 4; max_i++)
{
if (u_d_i_max[max_i][j][0] < u_dx_c[max_i])
u_d_i_max[max_i][j][0] = u_dx_c[max_i];
if (u_d_i_max[max_i][j][1] < u_dy_c[max_i])
u_d_i_max[max_i][j][1] = u_dy_c[max_i];
}
// Second end neighbors on every edge.
ns.set_active_segment(ns.get_num_neighbors() - 1);
en = ns.get_neighb_el();
en->get_center(x_center, y_center);
solutions[0]->get_refmap()->untransform(en, x_center, y_center, x_center_ref, y_center_ref);
find_centroid_derivatives(en, u_dx_c, u_dy_c, x_center_ref, y_center_ref);
for (unsigned int min_i = 0; min_i < 4; min_i++)
{
if (u_d_i_min[min_i][(j + 1) % e->get_nvert()][0] > u_dx_c[min_i])
u_d_i_min[min_i][(j + 1) % e->get_nvert()][0] = u_dx_c[min_i];
if (u_d_i_min[min_i][(j + 1) % e->get_nvert()][1] > u_dy_c[min_i])
u_d_i_min[min_i][(j + 1) % e->get_nvert()][1] = u_dy_c[min_i];
}
for (unsigned int max_i = 0; max_i < 4; max_i++)
{
if (u_d_i_max[max_i][(j + 1) % e->get_nvert()][0] < u_dx_c[max_i])
u_d_i_max[max_i][(j + 1) % e->get_nvert()][0] = u_dx_c[max_i];
if (u_d_i_max[max_i][(j + 1) % e->get_nvert()][1] < u_dy_c[max_i])
u_d_i_max[max_i][(j + 1) % e->get_nvert()][1] = u_dy_c[max_i];
}
// Now the hard part, neighbors' neighbors.
/// \todo This is where it fails for triangles, where it is much more complicated to look for elements sharing a vertex.
ns.set_active_segment(0);
Hermes::Hermes2D::NeighborSearch<double> ns_1(ns.get_neighb_el(), mesh);
if (ns.get_neighb_el()->en[(ns.get_neighbor_edge().local_num_of_edge + 1) % ns.get_neighb_el()->get_nvert()]->bnd)
continue;
ns_1.set_active_edge((ns.get_neighbor_edge().local_num_of_edge + 1) % ns.get_neighb_el()->get_nvert());
ns_1.set_active_segment(0);
en = ns_1.get_neighb_el();
en->get_center(x_center, y_center);
solutions[0]->get_refmap()->untransform(en, x_center, y_center, x_center_ref, y_center_ref);
find_centroid_derivatives(en, u_dx_c, u_dy_c, x_center_ref, y_center_ref);
for (unsigned int min_i = 0; min_i < 4; min_i++)
{
if (u_d_i_min[min_i][j][0] > u_dx_c[min_i])
u_d_i_min[min_i][j][0] = u_dx_c[min_i];
if (u_d_i_min[min_i][j][1] > u_dy_c[min_i])
u_d_i_min[min_i][j][1] = u_dy_c[min_i];
}
for (unsigned int max_i = 0; max_i < 4; max_i++)
{
if (u_d_i_max[max_i][j][0] < u_dx_c[max_i])
u_d_i_max[max_i][j][0] = u_dx_c[max_i];
if (u_d_i_max[max_i][j][1] < u_dy_c[max_i])
u_d_i_max[max_i][j][1] = u_dy_c[max_i];
}
}
}
void KuzminDiscontinuityDetector::find_alpha_i_second_order(double u_d_i_min[4][4][2], double u_d_i_max[4][4][2], double*** u_dx_c, double*** u_dy_c, double u_d_i[4][4][2], double alpha_i[4])
{
for (unsigned int sol_i = 0; sol_i < 4; sol_i++)
{
alpha_i[sol_i] = 1;
double u_dx = u_dx_c[sol_i][0][1];
double u_dy = u_dy_c[sol_i][0][2];
for (unsigned int vertex_i = 0; vertex_i < 4; vertex_i++)
{
// Sanity checks.
if (std::abs(u_dx) < 1E-5)
continue;
if (std::abs((u_d_i_min[sol_i][vertex_i][0] - u_dx) / u_dx) > 10)
continue;
if (std::abs((u_d_i_max[sol_i][vertex_i][0] - u_dx) / u_dx) > 10)
continue;
if (std::abs(u_dy) < 1E-5)
continue;
if (std::abs((u_d_i_min[sol_i][vertex_i][1] - u_dy) / u_dy) > 10)
continue;
if (std::abs((u_d_i_max[sol_i][vertex_i][1] - u_dy) / u_dy) > 10)
continue;
// dx.
if (u_d_i[sol_i][vertex_i][0] < u_dx)
{
if ((u_d_i_min[sol_i][vertex_i][0] - u_dx) / (u_d_i[sol_i][vertex_i][0] - u_dx) < alpha_i[sol_i])
alpha_i[sol_i] = (u_d_i_min[sol_i][vertex_i][0] - u_dx) / (u_d_i[sol_i][vertex_i][0] - u_dx);
}
else
{
if ((u_d_i_max[sol_i][vertex_i][0] - u_dx) / (u_d_i[sol_i][vertex_i][0] - u_dx) < alpha_i[sol_i])
alpha_i[sol_i] = (u_d_i_max[sol_i][vertex_i][0] - u_dx) / (u_d_i[sol_i][vertex_i][0] - u_dx);
}
// dy.
if (u_d_i[sol_i][vertex_i][1] < u_dy)
{
if ((u_d_i_min[sol_i][vertex_i][1] - u_dy) / (u_d_i[sol_i][vertex_i][1] - u_dy) < alpha_i[sol_i])
alpha_i[sol_i] = (u_d_i_min[sol_i][vertex_i][1] - u_dy) / (u_d_i[sol_i][vertex_i][1] - u_dy);
}
else
{
if ((u_d_i_max[sol_i][vertex_i][1] - u_dy) / (u_d_i[sol_i][vertex_i][1] - u_dy) < alpha_i[sol_i])
alpha_i[sol_i] = (u_d_i_max[sol_i][vertex_i][1] - u_dy) / (u_d_i[sol_i][vertex_i][1] - u_dy);
}
}
}
}
void KuzminDiscontinuityDetector::find_alpha_i_second_order_real(Hermes::Hermes2D::Element* e, double u_i[4][4][2], double u_dx_c[4], double u_dy_c[4], double u_dxx_c[4], double u_dxy_c[4], double u_dyy_c[4], double alpha_i_real[4])
{
double c_x, c_y;
if (e->get_nvert() == 3)
{
c_x = (1 / 3) * (e->vn[0]->x + e->vn[1]->x + e->vn[2]->x);
c_y = (1 / 3) * (e->vn[0]->y + e->vn[1]->y + e->vn[2]->y);
}
else
{
c_x = (1 / 4) * (e->vn[0]->x + e->vn[1]->x + e->vn[2]->x + e->vn[3]->x);
c_y = (1 / 4) * (e->vn[0]->y + e->vn[1]->y + e->vn[2]->y + e->vn[3]->y);
}
alpha_i_real[0] = alpha_i_real[1] = alpha_i_real[2] = alpha_i_real[3] = -std::numeric_limits<double>::infinity();
for (unsigned int sol_i = 0; sol_i < this->solutions.size(); sol_i++)
for (unsigned int vertex_i = 0; vertex_i < e->get_nvert(); vertex_i++)
{
// dxx + dxy.
if ((u_i[sol_i][vertex_i][0] - u_dx_c[sol_i]) / (u_dxx_c[sol_i] * (e->vn[vertex_i]->x - c_x) + u_dxy_c[sol_i] * (e->vn[vertex_i]->y - c_y)) > alpha_i_real[sol_i])
alpha_i_real[sol_i] = (u_i[sol_i][vertex_i][0] - u_dx_c[sol_i]) / (u_dxx_c[sol_i] * (e->vn[vertex_i]->x - c_x) + u_dxy_c[sol_i] * (e->vn[vertex_i]->y - c_y));
// dyy + dxy.
if ((u_i[sol_i][vertex_i][1] - u_dy_c[sol_i]) / (u_dyy_c[sol_i] * (e->vn[vertex_i]->x - c_x) + u_dxy_c[sol_i] * (e->vn[vertex_i]->y - c_y)) > alpha_i_real[sol_i])
alpha_i_real[sol_i] = (u_i[sol_i][vertex_i][1] - u_dy_c[sol_i]) / (u_dyy_c[sol_i] * (e->vn[vertex_i]->x - c_x) + u_dxy_c[sol_i] * (e->vn[vertex_i]->y - c_y));
}
}
FluxLimiter::FluxLimiter(FluxLimiter::LimitingType type, double* solution_vector, std::vector<SpaceSharedPtr<double> > spaces, bool Kuzmin_limit_all_orders_independently) : solution_vector(solution_vector), spaces(spaces), limitOscillations(false)
{
for (unsigned int sol_i = 0; sol_i < spaces.size(); sol_i++)
limited_solutions.push_back(new Hermes::Hermes2D::Solution<double>(spaces[sol_i]->get_mesh()));
Solution<double>::vector_to_solutions(solution_vector, spaces, limited_solutions);
switch (type)
{
case Krivodonova:
this->detector = new KrivodonovaDiscontinuityDetector(spaces, limited_solutions);
break;
case Kuzmin:
this->detector = new KuzminDiscontinuityDetector(spaces, limited_solutions, Kuzmin_limit_all_orders_independently);
break;
}
};
FluxLimiter::FluxLimiter(FluxLimiter::LimitingType type, std::vector<MeshFunctionSharedPtr<double> > solutions, std::vector<SpaceSharedPtr<double> > spaces, bool Kuzmin_limit_all_orders_independently) : spaces(spaces), limitOscillations(false)
{
for (unsigned int sol_i = 0; sol_i < spaces.size(); sol_i++)
limited_solutions.push_back(new Hermes::Hermes2D::Solution<double>(spaces[sol_i]->get_mesh()));
this->solution_vector = new double[Space<double>::get_num_dofs(spaces)];
OGProjection<double> ogProj;
ogProj.project_global(this->spaces, solutions, this->solution_vector);
Solution<double>::vector_to_solutions(solution_vector, spaces, limited_solutions);
switch (type)
{
case Krivodonova:
this->detector = new KrivodonovaDiscontinuityDetector(spaces, limited_solutions);
break;
case Kuzmin:
this->detector = new KuzminDiscontinuityDetector(spaces, limited_solutions, Kuzmin_limit_all_orders_independently);
break;
}
};
FluxLimiter::~FluxLimiter()
{
delete detector;
};
void FluxLimiter::get_limited_solutions(std::vector<MeshFunctionSharedPtr<double> > solutions_to_limit)
{
for (unsigned int i = 0; i < solutions_to_limit.size(); i++)
solutions_to_limit[i]->copy(this->limited_solutions[i]);
}
int FluxLimiter::limit_according_to_detector(std::vector<SpaceSharedPtr<double> > coarse_spaces_to_limit)
{
std::set<int> discontinuous_elements = this->detector->get_discontinuous_element_ids();
std::set<std::pair<int, double> > oscillatory_element_idsRho = this->detector->get_oscillatory_element_idsRho();
std::set<std::pair<int, double> > oscillatory_element_idsRhoVX = this->detector->get_oscillatory_element_idsRhoVX();
std::set<std::pair<int, double> > oscillatory_element_idsRhoVY = this->detector->get_oscillatory_element_idsRhoVY();
std::set<std::pair<int, double> > oscillatory_element_idsRhoE = this->detector->get_oscillatory_element_idsRhoE();
// First adjust the solution_vector.
int running_dofs = 0;
for (unsigned int space_i = 0; space_i < spaces.size(); space_i++)
{
for (std::set<int>::iterator it = discontinuous_elements.begin(); it != discontinuous_elements.end(); it++)
{
Element* e = spaces[space_i]->get_mesh()->get_element(*it);
AsmList<double> al;
spaces[space_i]->get_element_assembly_list(spaces[space_i]->get_mesh()->get_element(*it), &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++)
if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = 0.0;
}
if (this->limitOscillations)
running_dofs += spaces[space_i]->get_num_dofs();
}
if (limitOscillations)
{
unsigned int space_i = 0;
running_dofs = 0;
for (std::set<std::pair<int, double> >::iterator it = oscillatory_element_idsRho.begin(); it != oscillatory_element_idsRho.end(); it++)
{
Element* e = spaces[space_i]->get_mesh()->get_element(it->first);
AsmList<double> al;
spaces[space_i]->get_element_assembly_list(spaces[space_i]->get_mesh()->get_element(it->first), &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++)
if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = 0.0;
else if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = it->second;
}
running_dofs += spaces[space_i]->get_num_dofs();
space_i = 1;
for (std::set<std::pair<int, double> >::iterator it = oscillatory_element_idsRhoVX.begin(); it != oscillatory_element_idsRhoVX.end(); it++)
{
Element* e = spaces[space_i]->get_mesh()->get_element(it->first);
AsmList<double> al;
spaces[space_i]->get_element_assembly_list(spaces[space_i]->get_mesh()->get_element(it->first), &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++)
if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = 0.0;
else if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = it->second;
}
running_dofs += spaces[space_i]->get_num_dofs();
space_i = 2;
for (std::set<std::pair<int, double> >::iterator it = oscillatory_element_idsRhoVY.begin(); it != oscillatory_element_idsRhoVY.end(); it++)
{
Element* e = spaces[space_i]->get_mesh()->get_element(it->first);
AsmList<double> al;
spaces[space_i]->get_element_assembly_list(spaces[space_i]->get_mesh()->get_element(it->first), &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++)
if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = 0.0;
else if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = it->second;
}
running_dofs += spaces[space_i]->get_num_dofs();
space_i = 3;
for (std::set<std::pair<int, double> >::iterator it = oscillatory_element_idsRhoE.begin(); it != oscillatory_element_idsRhoE.end(); it++)
{
Element* e = spaces[space_i]->get_mesh()->get_element(it->first);
AsmList<double> al;
spaces[space_i]->get_element_assembly_list(spaces[space_i]->get_mesh()->get_element(it->first), &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++)
if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = 0.0;
else if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) == 0)
solution_vector[running_dofs + al.get_dof()[shape_i]] = it->second;
}
}
// Now adjust the solutions.
Solution<double>::vector_to_solutions(solution_vector, spaces, limited_solutions);
if (coarse_spaces_to_limit != std::vector<SpaceSharedPtr<double> >())
{
// Now set the element order to zero.
Element* e;
for_all_elements(e, spaces[0]->get_mesh())
e->visited = false;
for (std::set<int>::iterator it = discontinuous_elements.begin(); it != discontinuous_elements.end(); it++)
{
e = spaces[0]->get_mesh()->get_element(*it);
AsmList<double> al;
spaces[0]->get_element_assembly_list(e, &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++) {
if (H2D_GET_H_ORDER(spaces[0]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0 || H2D_GET_V_ORDER(spaces[0]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 0) {
spaces[0]->get_mesh()->get_element(*it)->visited = true;
bool all_sons_visited = true;
for (unsigned int son_i = 0; son_i < 4; son_i++)
if (!spaces[0]->get_mesh()->get_element(*it)->parent->sons[son_i]->visited)
{
all_sons_visited = false;
break;
}
if (all_sons_visited)
for (unsigned int space_i = 0; space_i < spaces.size(); space_i++)
coarse_spaces_to_limit[space_i]->set_element_order(spaces[space_i]->get_mesh()->get_element(*it)->parent->id, 0);
}
}
}
for (int i = 0; i < coarse_spaces_to_limit.size(); i++)
coarse_spaces_to_limit.at(i)->assign_dofs();
}
return discontinuous_elements.size() + oscillatory_element_idsRho.size() + oscillatory_element_idsRhoVX.size() + oscillatory_element_idsRhoVY.size() + oscillatory_element_idsRhoE.size();
};
void FluxLimiter::limit_second_orders_according_to_detector(std::vector<SpaceSharedPtr<double> > coarse_spaces_to_limit)
{
std::set<int> discontinuous_elements;
if (dynamic_cast<KuzminDiscontinuityDetector*>(this->detector))
discontinuous_elements = static_cast<KuzminDiscontinuityDetector*>(this->detector)->get_second_order_discontinuous_element_ids();
else
throw Hermes::Exceptions::Exception("limit_second_orders_according_to_detector() is to be used only with Kuzmin's vertex based detector.");
// First adjust the solution_vector.
int running_dofs = 0;
for (unsigned int space_i = 0; space_i < spaces.size(); space_i++)
{
for (std::set<int>::iterator it = discontinuous_elements.begin(); it != discontinuous_elements.end(); it++)
{
Element* e = spaces[space_i]->get_mesh()->get_element(*it);
AsmList<double> al;
spaces[space_i]->get_element_assembly_list(spaces[space_i]->get_mesh()->get_element(*it), &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++)
if (H2D_GET_H_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 1 || H2D_GET_V_ORDER(spaces[space_i]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 1)
solution_vector[running_dofs + al.get_dof()[shape_i]] = 0.0;
}
//running_dofs += spaces[space_i]->get_num_dofs();
}
// Now adjust the solutions.
Solution<double>::vector_to_solutions(solution_vector, spaces, limited_solutions);
if (dynamic_cast<KuzminDiscontinuityDetector*>(this->detector))
{
bool Kuzmin_limit_all_orders_independently = dynamic_cast<KuzminDiscontinuityDetector*>(this->detector)->get_limit_all_orders_independently();
delete detector;
this->detector = new KuzminDiscontinuityDetector(spaces, limited_solutions, Kuzmin_limit_all_orders_independently);
}
else
{
delete detector;
this->detector = new KrivodonovaDiscontinuityDetector(spaces, limited_solutions);
}
if (coarse_spaces_to_limit != std::vector<SpaceSharedPtr<double> >()) {
// Now set the element order to zero.
Element* e;
for_all_elements(e, spaces[0]->get_mesh())
e->visited = false;
for (std::set<int>::iterator it = discontinuous_elements.begin(); it != discontinuous_elements.end(); it++) {
AsmList<double> al;
spaces[0]->get_element_assembly_list(spaces[0]->get_mesh()->get_element(*it), &al);
for (unsigned int shape_i = 0; shape_i < al.get_cnt(); shape_i++) {
if (H2D_GET_H_ORDER(spaces[0]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 1 || H2D_GET_V_ORDER(spaces[0]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())) > 1) {
int h_order_to_set = std::min(1, H2D_GET_H_ORDER(spaces[0]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())));
int v_order_to_set = std::min(1, H2D_GET_V_ORDER(spaces[0]->get_shapeset()->get_order(al.get_idx()[shape_i], e->get_mode())));
spaces[0]->get_mesh()->get_element(*it)->visited = true;
bool all_sons_visited = true;
for (unsigned int son_i = 0; son_i < 4; son_i++)
if (!spaces[0]->get_mesh()->get_element(*it)->parent->sons[son_i]->visited)
{
all_sons_visited = false;
break;
}
if (all_sons_visited)
for (unsigned int space_i = 0; space_i < spaces.size(); space_i++)
coarse_spaces_to_limit[space_i]->set_element_order(spaces[space_i]->get_mesh()->get_element(*it)->parent->id, H2D_MAKE_QUAD_ORDER(h_order_to_set, v_order_to_set));
}
}
}
for (int i = 0; i < coarse_spaces_to_limit.size(); i++)
coarse_spaces_to_limit.at(i)->assign_dofs();
}
};
void MachNumberFilter::filter_fn(int n, const std::vector<const double*>& values, double* result)
{
for (int i = 0; i < n; i++)
result[i] = std::sqrt((values.at(1)[i] / values.at(0)[i])*(values.at(1)[i] / values.at(0)[i]) + (values.at(2)[i] / values.at(0)[i])*(values.at(2)[i] / values.at(0)[i]))
/ std::sqrt(kappa * QuantityCalculator::calc_pressure(values.at(0)[i], values.at(1)[i], values.at(2)[i], values.at(3)[i], kappa) / values.at(0)[i]);
}
void PressureFilter::filter_fn(int n, const std::vector<const double*>& values, double* result)
{
for (int i = 0; i < n; i++)
result[i] = (kappa - 1.) * (values.at(3)[i] - (values.at(1)[i] * values.at(1)[i] + values.at(2)[i] * values.at(2)[i]) / (2 * values.at(0)[i]));
}
void VelocityFilter::filter_fn(int n, const std::vector<const double*>& values, double* result)
{
for (int i = 0; i < n; i++)
result[i] = values.at(1)[i] / values.at(0)[i];
}
void EntropyFilter::filter_fn(int n, const std::vector<const double*>& values, double* result)
{
for (int i = 0; i < n; i++)
for (int i = 0; i < n; i++)
result[i] = std::log((QuantityCalculator::calc_pressure(values.at(0)[i], values.at(1)[i], values.at(2)[i], values.at(3)[i], kappa) / p_ext)
/ Hermes::pow((values.at(0)[i] / rho_ext), kappa));
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/forms_implicit.cpp | .cpp | 74,425 | 1,508 | #include "hermes2d.h"
// Numerical fluxes.
#include "numerical_flux.h"
// Utility functions for the Euler equations.
#include "euler_util.h"
class EulerEquationsWeakFormImplicit : public WeakForm<double>
{
public:
// Constructor.
EulerEquationsWeakFormImplicit(NumericalFlux* num_flux, double kappa, double rho_ext,
double v1_ext, double v2_ext, double pressure_ext,
std::string solid_wall_bottom_marker,
std::string solid_wall_top_marker,
std::string inlet_marker, std::string outlet_marker,
Solution<double>* prev_density, Solution<double>* prev_density_vel_x,
Solution<double>* prev_density_vel_y, Solution<double>* prev_energy,
bool preconditioning, int num_of_equations = 4) :
WeakForm<double>(num_of_equations, true), rho_ext(rho_ext), v1_ext(v1_ext), v2_ext(v2_ext),
pressure_ext(pressure_ext), energy_ext(QuantityCalculator::calc_energy(rho_ext,
rho_ext * v1_ext, rho_ext * v2_ext, pressure_ext, kappa)), euler_fluxes(new EulerFluxes(kappa))
{
if(preconditioning)
{
add_matrix_form(new EulerEquationsPreconditioning(0));
add_matrix_form(new EulerEquationsPreconditioning(1));
add_matrix_form(new EulerEquationsPreconditioning(2));
add_matrix_form(new EulerEquationsPreconditioning(3));
}
add_vector_form(new EulerEquationsLinearFormTime(0));
add_vector_form(new EulerEquationsLinearFormTime(1));
add_vector_form(new EulerEquationsLinearFormTime(2));
add_vector_form(new EulerEquationsLinearFormTime(3));
for(unsigned int vector_form_i = 0;vector_form_i < this->vfvol.size();vector_form_i++) {
vfvol.at(vector_form_i)->ext.push_back(prev_density);
vfvol.at(vector_form_i)->ext.push_back(prev_density_vel_x);
vfvol.at(vector_form_i)->ext.push_back(prev_density_vel_y);
vfvol.at(vector_form_i)->ext.push_back(prev_energy);
}
add_vector_form(new EulerEquationsLinearFormDensity());
add_vector_form(new EulerEquationsLinearFormDensityVelX(kappa));
add_vector_form(new EulerEquationsLinearFormDensityVelY(kappa));
add_vector_form(new EulerEquationsLinearFormEnergy(kappa));
add_vector_form_surf(new EulerEquationsLinearFormInterface(0, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormInterface(1, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormInterface(2, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormInterface(3, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(0, solid_wall_bottom_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(1, solid_wall_bottom_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(2, solid_wall_bottom_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(3, solid_wall_bottom_marker, num_flux));
if(solid_wall_bottom_marker != solid_wall_top_marker)
{
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(0, solid_wall_top_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(1, solid_wall_top_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(2, solid_wall_top_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormSolidWall(3, solid_wall_top_marker, num_flux));
}
else
warning("Are you sure that solid wall top and bottom markers should coincide?");
add_vector_form_surf(new EulerEquationsLinearFormInlet(0, inlet_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormInlet(1, inlet_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormInlet(2, inlet_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormInlet(3, inlet_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormOutlet(0, outlet_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormOutlet(1, outlet_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormOutlet(2, outlet_marker, num_flux));
add_vector_form_surf(new EulerEquationsLinearFormOutlet(3, outlet_marker, num_flux));
};
void set_time_step(double tau)
{
this->tau = tau;
}
double get_tau() const
{
return tau;
}
// Destructor.
~EulerEquationsWeakFormImplicit() {};
protected:
class EulerEquationsPreconditioning : public MatrixFormVol<double>
{
public:
EulerEquationsPreconditioning(int i) : MatrixFormVol<double>(i, i) {}
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u, Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
return int_u_v<Real, Scalar>(n, wt, u, v);
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
};
class EulerEquationsLinearFormDensity : public VectorFormVol<double>
{
public:
EulerEquationsLinearFormDensity() : VectorFormVol<double>(0) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v, Geom<Real> *e,
ExtData<Scalar> *ext) const
{
Scalar result = (Scalar)0;
for (int i = 0;i < n;i++) {
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_0_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_0_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_0_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_0_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_0_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_0_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_0_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_0_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
};
class EulerEquationsLinearFormDensityVelX : public VectorFormVol<double>
{
public:
EulerEquationsLinearFormDensityVelX(double kappa)
: VectorFormVol<double>(1), kappa(kappa) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
Scalar result = (Scalar)0;
for (int i = 0;i < n;i++) {
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_1_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_1_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_1_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_1_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_1_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_1_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_1_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_1_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
double kappa;
};
class EulerEquationsLinearFormDensityVelY : public VectorFormVol<double>
{
public:
EulerEquationsLinearFormDensityVelY(double kappa)
: VectorFormVol<double>(2), kappa(kappa) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
Scalar result = (Scalar)0;
for (int i = 0;i < n;i++) {
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_2_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_2_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_2_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_2_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_2_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_2_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_2_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_2_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
double kappa;
};
class EulerEquationsLinearFormEnergy : public VectorFormVol<double>
{
public:
EulerEquationsLinearFormEnergy(double kappa)
: VectorFormVol<double>(3), kappa(kappa) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
Scalar result = (Scalar)0;
for (int i = 0;i < n;i++) {
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_3_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dx[i];
result += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_3_0<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dy[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_3_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dx[i];
result += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_3_1<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_3_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_3_2<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dy[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_1_3_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dx[i];
result += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicit*>(wf))->euler_fluxes->A_2_3_3<Scalar>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], (Scalar)0)
* v->dy[i];
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
double kappa;
};
class EulerEquationsLinearFormTime : public VectorFormVol<double>
{
public:
EulerEquationsLinearFormTime(int i)
: VectorFormVol<double>(i), component_i(i) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
return int_u_v<Real, Scalar>(n, wt, ext->fn[component_i], v)
-
int_u_v<Real, Scalar>(n, wt, u_ext[component_i], v);
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
Geom<Ord> *e, ExtData<Ord> *ext) const
{
if(component_i < 4)
return vector_form<Ord, Ord>(n, wt, u_ext, v, e, ext);
else
return Ord(5);
}
// Member.
int component_i;
};
class EulerEquationsLinearFormInterface : public VectorFormSurf<double>
{
public:
EulerEquationsLinearFormInterface(int i, NumericalFlux* num_flux)
: VectorFormSurf<double>(i, H2D_DG_INNER_EDGE), element(i), num_flux(num_flux) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
double result = 0;
double w_L[4], w_R[4];
for (int i = 0;i < n;i++) {
w_L[0] = u_ext[0]->get_val_central(i);
w_R[0] = u_ext[0]->get_val_neighbor(i);
w_L[1] = u_ext[1]->get_val_central(i);
w_R[1] = u_ext[1]->get_val_neighbor(i);
w_L[2] = u_ext[2]->get_val_central(i);
w_R[2] = u_ext[2]->get_val_neighbor(i);
w_L[3] = u_ext[3]->get_val_central(i);
w_R[3] = u_ext[3]->get_val_neighbor(i);
result -= wt[i] * v->val[i]
* num_flux->numerical_flux_i(element, w_L, w_R, e->nx[i], e->ny[i]);
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
int element;
NumericalFlux* num_flux;
};
class EulerEquationsLinearFormSolidWall : public VectorFormSurf<double>
{
public:
EulerEquationsLinearFormSolidWall(int i, std::string marker, NumericalFlux* num_flux)
: VectorFormSurf<double>(i, marker), element(i), num_flux(num_flux) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
double result = 0;
for (int i = 0;i < n;i++) {
double w_L[4];
w_L[0] = u_ext[0]->val[i];
w_L[1] = u_ext[1]->val[i];
w_L[2] = u_ext[2]->val[i];
w_L[3] = u_ext[3]->val[i];
result -= wt[i] * v->val[i] * num_flux->numerical_flux_solid_wall_i(element,
w_L, e->nx[i], e->ny[i]);
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
int element;
NumericalFlux* num_flux;
};
class EulerEquationsLinearFormInlet : public VectorFormSurf<double>
{
public:
EulerEquationsLinearFormInlet(int i, std::string marker, NumericalFlux* num_flux)
: VectorFormSurf<double>(i, marker), element(i), num_flux(num_flux) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext) const
{
double result = 0;
double w_L[4], w_B[4];
for (int i = 0;i < n;i++) {
// Left (inner) state from the previous time level solution.
w_L[0] = u_ext[0]->val[i];
w_L[1] = u_ext[1]->val[i];
w_L[2] = u_ext[2]->val[i];
w_L[3] = u_ext[3]->val[i];
w_B[0] = static_cast<EulerEquationsWeakFormImplicit*>(wf)->rho_ext;
w_B[1] = static_cast<EulerEquationsWeakFormImplicit*>(wf)->rho_ext
* static_cast<EulerEquationsWeakFormImplicit*>(wf)->v1_ext;
w_B[2] = static_cast<EulerEquationsWeakFormImplicit*>(wf)->rho_ext
* static_cast<EulerEquationsWeakFormImplicit*>(wf)->v2_ext;
w_B[3] = static_cast<EulerEquationsWeakFormImplicit*>(wf)->energy_ext;
result -= wt[i] * v->val[i] * num_flux->numerical_flux_inlet_i(element,
w_L, w_B, e->nx[i], e->ny[i]);
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
int element;
NumericalFlux* num_flux;
};
class EulerEquationsLinearFormOutlet : public VectorFormSurf<double>
{
public:
EulerEquationsLinearFormOutlet(int i, std::string marker, NumericalFlux* num_flux) :
VectorFormSurf<double>(i, marker), element(i), num_flux(num_flux) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
double result = 0;
double w_L[4];
for (int i = 0;i < n;i++) {
w_L[0] = u_ext[0]->val[i];
w_L[1] = u_ext[1]->val[i];
w_L[2] = u_ext[2]->val[i];
w_L[3] = u_ext[3]->val[i];
result -= wt[i] * v->val[i]
* num_flux->numerical_flux_outlet_i(element, w_L,
static_cast<EulerEquationsWeakFormImplicit*>(wf)->pressure_ext,
e->nx[i], e->ny[i]);
}
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
int element;
NumericalFlux* num_flux;
};
// Members.
double rho_ext;
double v1_ext;
double v2_ext;
double pressure_ext;
double energy_ext;
double tau;
EulerFluxes* euler_fluxes;
friend class EulerEquationsWeakFormImplicitCoupled;
};
class EulerEquationsWeakFormImplicitMultiComponent : public WeakForm<double>
{
public:
// Constructor.
EulerEquationsWeakFormImplicitMultiComponent(NumericalFlux* num_flux, double kappa,
double rho_ext, double v1_ext, double v2_ext, double pressure_ext,
std::string solid_wall_bottom_marker, std::string solid_wall_top_marker,
std::string inlet_marker, std::string outlet_marker,
Solution<double>* prev_density, Solution<double>* prev_density_vel_x, Solution<double>* prev_density_vel_y,
Solution<double>* prev_energy, bool preconditioning, bool fvm_only = false, int num_of_equations = 4) :
WeakForm<double>(num_of_equations, true), rho_ext(rho_ext), v1_ext(v1_ext), v2_ext(v2_ext),
pressure_ext(pressure_ext), energy_ext(QuantityCalculator::calc_energy(rho_ext,
rho_ext * v1_ext, rho_ext * v2_ext, pressure_ext, kappa)), euler_fluxes(new EulerFluxes(kappa))
{
std::vector<std::pair<unsigned int, unsigned int> > matrix_coordinates;
matrix_coordinates.push_back(std::pair<unsigned int, unsigned int>(0, 0));
matrix_coordinates.push_back(std::pair<unsigned int, unsigned int>(1, 1));
matrix_coordinates.push_back(std::pair<unsigned int, unsigned int>(2, 2));
matrix_coordinates.push_back(std::pair<unsigned int, unsigned int>(3, 3));
std::vector<std::pair<unsigned int, unsigned int> > matrix_coordinates_precon_vol;
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(0, 0));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(0, 1));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(0, 2));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(0, 3));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(1, 0));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(1, 1));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(1, 2));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(1, 3));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(2, 0));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(2, 1));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(2, 2));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(2, 3));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(3, 0));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(3, 1));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(3, 2));
matrix_coordinates_precon_vol.push_back(std::pair<unsigned int, unsigned int>(3, 3));
std::vector<unsigned int> vector_coordinates;
vector_coordinates.push_back(0);
vector_coordinates.push_back(1);
vector_coordinates.push_back(2);
vector_coordinates.push_back(3);
if(preconditioning)
{ /*
EulerEquationsMatrixFormVol<double>Preconditioning* precon_vol
= new EulerEquationsMatrixFormVol<double>Preconditioning(matrix_coordinates_precon_vol, kappa);
EulerEquationsMatrixFormSurf<double>Preconditioning* precon_surf
= new EulerEquationsMatrixFormSurf<double>Preconditioning(matrix_coordinates, kappa);
add_multicomponent_matrix_form(precon_vol);
add_multicomponent_matrix_form_surf(precon_surf);
*/
add_multicomponent_matrix_form(new EulerEquationsMatrixFormVolPreconditioningSimple(matrix_coordinates));
}
add_multicomponent_vector_form(new EulerEquationsLinearFormTime(vector_coordinates));
add_multicomponent_vector_form_surf(new EulerEquationsLinearFormInterface(vector_coordinates, num_flux));
add_multicomponent_vector_form_surf(new EulerEquationsLinearFormSolidWall(vector_coordinates,
solid_wall_bottom_marker, num_flux));
if(solid_wall_bottom_marker != solid_wall_top_marker)
add_multicomponent_vector_form_surf(new EulerEquationsLinearFormSolidWall(vector_coordinates,
solid_wall_top_marker, num_flux));
add_multicomponent_vector_form_surf(new EulerEquationsLinearFormInlet(vector_coordinates,
inlet_marker, num_flux));
add_multicomponent_vector_form_surf(new EulerEquationsLinearFormOutlet(vector_coordinates,
outlet_marker, num_flux));
for(unsigned int vector_form_i = 0;vector_form_i < this->vfvol_mc.size();vector_form_i++) {
vfvol_mc.at(vector_form_i)->ext.push_back(prev_density);
vfvol_mc.at(vector_form_i)->ext.push_back(prev_density_vel_x);
vfvol_mc.at(vector_form_i)->ext.push_back(prev_density_vel_y);
vfvol_mc.at(vector_form_i)->ext.push_back(prev_energy);
}
if(!fvm_only)
add_multicomponent_vector_form(new EulerEquationsLinearForm(vector_coordinates, kappa));
};
void set_time_step(double tau)
{
this->tau = tau;
}
double get_tau() const
{
return tau;
}
// Destructor.
~EulerEquationsWeakFormImplicitMultiComponent() {};
protected:
class EulerEquationsMatrixFormVolPreconditioning : public MultiComponentMatrixFormVol<double>
{
public:
EulerEquationsMatrixFormVolPreconditioning({coordinates}, kappa(kappa) {}
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, Geom<double> *e,
ExtData<double> *ext,{int i = 0;i < n;i++} {
result_0_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_0_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_0_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_0_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_3_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dx[i];
result_3_0 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dy[i];
result_3_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dx[i];
result_3_1 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_3_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_3_2 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dy[i];
result_3_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_3_3 += wt[i] * u->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
}
result.push_back(result_0_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_0_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_0_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_0_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
Geom<Ord> *e, ExtData<Ord> *ext) const
{
return int_u_v<Ord, Ord>(n, wt, u, v);
}
double kappa;
};
class EulerEquationsMatrixFormSurfPreconditioning : public MultiComponentMatrixFormSurf<double>
{
public:
EulerEquationsMatrixFormSurfPreconditioning({coordinates, H2D_DG_INNER_EDGE},
num_flux(new StegerWarmingNumericalFlux(kappa)) { }
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, Geom<double> *e, ExtData<double> *ext,
std::vector<double>& result) const
{
double result_0_0 = 0;
double result_0_1 = 0;
double result_0_2 = 0;
double result_0_3 = 0;
double result_1_0 = 0;
double result_1_1 = 0;
double result_1_2 = 0;
double result_1_3 = 0;
double result_2_0 = 0;
double result_2_1 = 0;
double result_2_2 = 0;
double result_2_3 = 0;
double result_3_0 = 0;
double result_3_1 = 0;
double result_3_2 = 0;
double result_3_3 = 0;
double result_L[4];
double result_R[4];
double w_L[4], w_R[4];
for (int i = 0;i < n;i++) {
w_L[0] = u_ext[0]->get_val_central(i);
w_R[0] = u_ext[0]->get_val_neighbor(i);
w_L[1] = u_ext[1]->get_val_central(i);
w_R[1] = u_ext[1]->get_val_neighbor(i);
w_L[2] = u_ext[2]->get_val_central(i);
w_R[2] = u_ext[2]->get_val_neighbor(i);
w_L[3] = u_ext[3]->get_val_central(i);
w_R[3] = u_ext[3]->get_val_neighbor(i);
double P_plus_1[4] = {1, 0, 0, 0};
double P_plus_2[4] = {0, 1, 0, 0};
double P_plus_3[4] = {0, 0, 1, 0};
double P_plus_4[4] = {0, 0, 0, 1};
double P_minus_1[4] = {1, 0, 0, 0};
double P_minus_2[4] = {0, 1, 0, 0};
double P_minus_3[4] = {0, 0, 1, 0};
double P_minus_4[4] = {0, 0, 0, 1};
num_flux->P_plus(P_plus_1, w_L, P_plus_1, e->nx[i], e->ny[i]);
num_flux->P_plus(P_plus_2, w_L, P_plus_2, e->nx[i], e->ny[i]);
num_flux->P_plus(P_plus_3, w_L, P_plus_3, e->nx[i], e->ny[i]);
num_flux->P_plus(P_plus_4, w_L, P_plus_4, e->nx[i], e->ny[i]);
num_flux->P_minus(P_minus_1, w_R, P_minus_1, e->nx[i], e->ny[i]);
num_flux->P_minus(P_minus_2, w_R, P_minus_2, e->nx[i], e->ny[i]);
num_flux->P_minus(P_minus_3, w_R, P_minus_3, e->nx[i], e->ny[i]);
num_flux->P_minus(P_minus_4, w_R, P_minus_4, e->nx[i], e->ny[i]);
result_0_0 += wt[i] * (P_plus_1[0] * u->get_val_central(i) + P_minus_1[0]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_0_1 += wt[i] * (P_plus_1[1] * u->get_val_central(i) + P_minus_1[1]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_0_2 += wt[i] * (P_plus_1[2] * u->get_val_central(i) + P_minus_1[2]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_0_3 += wt[i] * (P_plus_1[3] * u->get_val_central(i) + P_minus_1[3]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_1_0 += wt[i] * (P_plus_2[0] * u->get_val_central(i) + P_minus_2[0]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_1_1 += wt[i] * (P_plus_2[1] * u->get_val_central(i) + P_minus_2[1]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_1_2 += wt[i] * (P_plus_2[2] * u->get_val_central(i) + P_minus_2[2]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_1_3 += wt[i] * (P_plus_2[3] * u->get_val_central(i) + P_minus_2[3]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_2_0 += wt[i] * (P_plus_3[0] * u->get_val_central(i) + P_minus_3[0]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_2_1 += wt[i] * (P_plus_3[1] * u->get_val_central(i) + P_minus_3[1]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_2_2 += wt[i] * (P_plus_3[2] * u->get_val_central(i) + P_minus_3[2]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_2_3 += wt[i] * (P_plus_3[3] * u->get_val_central(i) + P_minus_3[3]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_3_0 += wt[i] * (P_plus_4[0] * u->get_val_central(i) + P_minus_4[0]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_3_1 += wt[i] * (P_plus_4[1] * u->get_val_central(i) + P_minus_4[1]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_3_2 += wt[i] * (P_plus_4[2] * u->get_val_central(i) + P_minus_4[2]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
result_3_3 += wt[i] * (P_plus_4[3] * u->get_val_central(i) + P_minus_4[3]
* u->get_val_neighbor(i)) * (v->get_val_central(i) - v->get_val_neighbor(i));
}
result.push_back(result_0_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_0_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_0_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_0_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_1_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_2_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_0 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_1 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_2 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
result.push_back(result_3_3 * static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->get_tau());
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
Geom<Ord> *e, ExtData<Ord> *ext) const
{
Ord result = Ord(0);
for (int i = 0;i < n;i++) {
result += wt[i] * u->get_val_central(i) * v->get_val_central(i);
result += wt[i] * u->get_val_neighbor(i) * v->get_val_neighbor(i);
}
return result;
}
StegerWarmingNumericalFlux* num_flux;
};
class EulerEquationsMatrixFormVolPreconditioningSimple
: public MultiComponentMatrixFormVol<double>
{
public:
EulerEquationsMatrixFormVolPreconditioningSimple({coordinates} {}
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
Geom<double> *e, ExtData<double> *ext,{n, wt, u, v};
result.push_back(result_n);
result.push_back(result_n);
result.push_back(result_n);
result.push_back(result_n);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return int_u_v<Ord, Ord>(n, wt, u, v);
}
};
class EulerEquationsLinearForm : public MultiComponentVectorFormVol<double>
{
public:
EulerEquationsLinearForm({coordinates}, kappa(kappa) { }
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext,{int i = 0;i < n;i++} {
result_0 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_0 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_0 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_0 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_0 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_0_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_1 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_1 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_1_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_2 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_2 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_2_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_3 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dx[i];
result_3 += wt[i] * u_ext[0]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_0<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dy[i];
result_3 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dx[i];
result_3 += wt[i] * u_ext[1]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_1<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
result_3 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_3 += wt[i] * u_ext[2]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_2<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], u_ext[3]->val[i])
* v->dy[i];
result_3 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dx[i];
result_3 += wt[i] * u_ext[3]->val[i]
* (static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_2_3_3<double>(u_ext[0]->val[i], u_ext[1]->val[i], u_ext[2]->val[i], 0)
* v->dy[i];
}
result.push_back(result_0 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_1 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_2 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_3 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const
{
return v->val[0] * v->val[0] * v->val[0] * v->val[0];
}
double kappa;
};
class EulerEquationsLinearFormTime : public MultiComponentVectorFormVol<double>
{
public:
EulerEquationsLinearFormTime({coordinates} {}
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext,{int_u_v<double, double>(n, wt, ext->fn[0], v}
- int_u_v<double, double>(n, wt, u_ext[0], v));
result.push_back(int_u_v<double, double>(n, wt, ext->fn[1], v)
- int_u_v<double, double>(n, wt, u_ext[1], v));
result.push_back(int_u_v<double, double>(n, wt, ext->fn[2], v)
- int_u_v<double, double>(n, wt, u_ext[2], v));
result.push_back(int_u_v<double, double>(n, wt, ext->fn[3], v)
- int_u_v<double, double>(n, wt, u_ext[3], v));
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return int_u_v<Ord, Ord>(n, wt, v, v);
}
};
class EulerEquationsLinearFormInterface : public MultiComponentVectorFormSurf<double>
{
public:
EulerEquationsLinearFormInterface({coordinates, H2D_DG_INNER_EDGE}, num_flux(num_flux) {}
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext,{int i = 0;i < n;i++} {
w_L[0] = u_ext[0]->get_val_central(i);
w_R[0] = u_ext[0]->get_val_neighbor(i);
w_L[1] = u_ext[1]->get_val_central(i);
w_R[1] = u_ext[1]->get_val_neighbor(i);
w_L[2] = u_ext[2]->get_val_central(i);
w_R[2] = u_ext[2]->get_val_neighbor(i);
w_L[3] = u_ext[3]->get_val_central(i);
w_R[3] = u_ext[3]->get_val_neighbor(i);
double flux[4];
num_flux->numerical_flux(flux, w_L, w_R, e->nx[i], e->ny[i]);
#ifdef H2D_EULER_NUM_FLUX_TESTING
double flux_testing_num_flux[4];
double flux_testing_num_flux_conservativity_1[4];
double flux_testing_num_flux_conservativity_2[4];
double flux_testing_flux_1[4];
num_flux->numerical_flux(flux_testing_num_flux, w_L, w_L, e->nx[i], e->ny[i]);
num_flux->numerical_flux(flux_testing_num_flux_conservativity_1, w_L, w_R, e->nx[i], e->ny[i]);
num_flux->numerical_flux(flux_testing_num_flux_conservativity_2, w_R, w_L, -e->nx[i], -e->ny[i]);
for(unsigned int flux_i = 0;flux_i < 4;flux_i++)
if(std::abs(flux_testing_num_flux_conservativity_1[flux_i] + flux_testing_num_flux_conservativity_2[flux_i]) > 1E-4)
if(std::abs((flux_testing_num_flux_conservativity_1[flux_i] + flux_testing_num_flux_conservativity_2[flux_i]) / flux_testing_num_flux_conservativity_1[flux_i]) > 1E-6)
info("Flux is not conservative.");
num_flux->Q(w_L, w_L, e->nx[i], e->ny[i]);
EulerEquationsLinearForm form(std::vector<unsigned int>(), num_flux->kappa);
flux_testing_flux_1[0] = form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_0<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[0]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_1<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[1]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_2<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[2]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_0_3<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[3];
flux_testing_flux_1[1] = form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_0<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[0]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_1<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[1]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_2<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[2]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_1_3<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[3];
flux_testing_flux_1[2] = form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_0<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[0]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_1<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[1]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_2<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[2]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_2_3<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[3];
flux_testing_flux_1[3] = form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_0<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[0]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_1<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[1]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_2<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[2]
+ form.(static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf))->euler_fluxes->A_1_3_3<double>(w_L[0], w_L[1], w_L[2], w_L[3]) * w_L[3];
num_flux->Q_inv(flux_testing_flux_1, flux_testing_flux_1, e->nx[i], e->ny[i]);
for(unsigned int flux_i = 0;flux_i < 4;flux_i++)
if(std::abs(flux_testing_num_flux[flux_i] - flux_testing_flux_1[flux_i]) > 1E-4)
if(std::abs((flux_testing_num_flux[flux_i] - flux_testing_flux_1[flux_i]) / flux_testing_num_flux[flux_i]) > 1E-6)
info("Flux is not consistent.");
#endif
result_0 -= wt[i] * v->val[i] * flux[0];
result_1 -= wt[i] * v->val[i] * flux[1];
result_2 -= wt[i] * v->val[i] * flux[2];
result_3 -= wt[i] * v->val[i] * flux[3];
}
result.push_back(result_0 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_1 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_2 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_3 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
NumericalFlux* num_flux;
};
class EulerEquationsLinearFormSolidWall : public MultiComponentVectorFormSurf<double>
{
public:
EulerEquationsLinearFormSolidWall({coordinates, marker}, num_flux(num_flux) {}
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext,{int i = 0;i < n;i++} {
double w_L[4];
w_L[0] = u_ext[0]->val[i];
w_L[1] = u_ext[1]->val[i];
w_L[2] = u_ext[2]->val[i];
w_L[3] = u_ext[3]->val[i];
double flux[4];
num_flux->numerical_flux_solid_wall(flux, w_L, e->nx[i], e->ny[i]);
result_0 -= wt[i] * v->val[i] * flux[0];
result_1 -= wt[i] * v->val[i] * flux[1];
result_2 -= wt[i] * v->val[i] * flux[2];
result_3 -= wt[i] * v->val[i] * flux[3];
}
result.push_back(result_0 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_1 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_2 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_3 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
NumericalFlux* num_flux;
};
class EulerEquationsLinearFormInlet : public MultiComponentVectorFormSurf<double>
{
public:
EulerEquationsLinearFormInlet({coordinates, marker}, num_flux(num_flux) {}
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext,{int i = 0;i < n;i++} {
// Left (inner) state from the previous time level solution.
w_L[0] = u_ext[0]->val[i];
w_L[1] = u_ext[1]->val[i];
w_L[2] = u_ext[2]->val[i];
w_L[3] = u_ext[3]->val[i];
w_B[0] = static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->rho_ext;
w_B[1] = static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->rho_ext
* static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->v1_ext;
w_B[2] = static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->rho_ext
* static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->v2_ext;
w_B[3] = static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->energy_ext;
double flux[4];
num_flux->numerical_flux_inlet(flux, w_L, w_B, e->nx[i], e->ny[i]);
result_0 -= wt[i] * v->val[i] * flux[0];
result_1 -= wt[i] * v->val[i] * flux[1];
result_2 -= wt[i] * v->val[i] * flux[2];
result_3 -= wt[i] * v->val[i] * flux[3];
}
result.push_back(result_0 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_1 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_2 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_3 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
NumericalFlux* num_flux;
};
class EulerEquationsLinearFormOutlet : public MultiComponentVectorFormSurf<double>
{
public:
EulerEquationsLinearFormOutlet({coordinates, marker}, num_flux(num_flux) {}
void value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext,{int i = 0;i < n;i++} {
w_L[0] = u_ext[0]->val[i];
w_L[1] = u_ext[1]->val[i];
w_L[2] = u_ext[2]->val[i];
w_L[3] = u_ext[3]->val[i];
double flux[4];
num_flux->numerical_flux_outlet(flux, w_L,
static_cast<EulerEquationsWeakFormImplicitMultiComponent*>(wf)->pressure_ext, e->nx[i], e->ny[i]);
result_0 -= wt[i] * v->val[i] * flux[0];
result_1 -= wt[i] * v->val[i] * flux[1];
result_2 -= wt[i] * v->val[i] * flux[2];
result_3 -= wt[i] * v->val[i] * flux[3];
}
result.push_back(result_0 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_1 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_2 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
result.push_back(result_3 * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau());
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e, ExtData<Ord> *ext) const
{
return v->val[0];
}
// Members.
NumericalFlux* num_flux;
};
// Members.
double rho_ext;
double v1_ext;
double v2_ext;
double pressure_ext;
double energy_ext;
double tau;
EulerFluxes* euler_fluxes;
};
// The parameter variant in the constructor has the following meaning:
// 1 - Dirichlet condition (concentration production) on the inlet.
// 2 - Dirichlet condition (concentration production) on the bottom.
// 3 - Dirichlet condition (concentration production) on the top.
class EulerEquationsWeakFormImplicitCoupled : public EulerEquationsWeakFormImplicitMultiComponent
{
public:
// Constructor.
EulerEquationsWeakFormImplicitCoupled(NumericalFlux* num_flux, double kappa,
double rho_ext, double v1_ext, double v2_ext,
double pressure_ext, std::string solid_wall_marker,
std::string inlet_marker, std::string outlet_marker,
std::vector<std::string> natural_bc_concentration_markers,
Solution<double>* prev_density, Solution<double>* prev_density_vel_x,
Solution<double>* prev_density_vel_y, Solution<double>* prev_energy,
Solution<double>* prev_concentration, bool preconditioning, double epsilon, bool fvm_only = false)
: EulerEquationsWeakFormImplicitMultiComponent(num_flux, kappa, rho_ext, v1_ext, v2_ext, pressure_ext,
solid_wall_marker, solid_wall_marker, inlet_marker,
outlet_marker, prev_density, prev_density_vel_x,
prev_density_vel_y, prev_energy, preconditioning, fvm_only, 5) {
if(preconditioning)
add_matrix_form(new EulerEquationsWeakFormImplicit::EulerEquationsPreconditioning(4));
EulerEquationsWeakFormImplicit::EulerEquationsLinearFormTime* linear_form_time = new EulerEquationsWeakFormImplicit::EulerEquationsLinearFormTime(4);
linear_form_time->ext.push_back(prev_density);
linear_form_time->ext.push_back(prev_density_vel_x);
linear_form_time->ext.push_back(prev_density_vel_y);
linear_form_time->ext.push_back(prev_energy);
linear_form_time->ext.push_back(prev_concentration);
add_vector_form(linear_form_time);
add_vector_form(new VectorFormConcentrationDiffusion(4, epsilon));
add_vector_form(new VectorFormConcentrationAdvection(4));
for(unsigned int i = 0;i < natural_bc_concentration_markers.size();i++)
add_vector_form_surf(new VectorFormConcentrationNatural(4, natural_bc_concentration_markers[i]));
add_vector_form_surf(new VectorFormConcentrationInterface (4));
};
EulerEquationsWeakFormImplicitCoupled(NumericalFlux* num_flux, double kappa,
double rho_ext, double v1_ext, double v2_ext,
double pressure_ext, std::string solid_wall_marker_bottom, std::string solid_wall_marker_top,
std::string inlet_marker, std::string outlet_marker,
std::vector<std::string> natural_bc_concentration_markers,
Solution<double>* prev_density, Solution<double>* prev_density_vel_x,
Solution<double>* prev_density_vel_y, Solution<double>* prev_energy,
Solution<double>* prev_concentration, bool preconditioning, double epsilon, bool fvm_only = false)
: EulerEquationsWeakFormImplicitMultiComponent(num_flux, kappa, rho_ext, v1_ext, v2_ext, pressure_ext,
solid_wall_marker_bottom, solid_wall_marker_top, inlet_marker,
outlet_marker, prev_density, prev_density_vel_x,
prev_density_vel_y, prev_energy, preconditioning, fvm_only, 5) {
if(preconditioning)
add_matrix_form(new EulerEquationsWeakFormImplicit::EulerEquationsPreconditioning(4));
EulerEquationsWeakFormImplicit::EulerEquationsLinearFormTime* linear_form_time = new EulerEquationsWeakFormImplicit::EulerEquationsLinearFormTime(4);
linear_form_time->ext.push_back(prev_density);
linear_form_time->ext.push_back(prev_density_vel_x);
linear_form_time->ext.push_back(prev_density_vel_y);
linear_form_time->ext.push_back(prev_energy);
linear_form_time->ext.push_back(prev_concentration);
add_vector_form(linear_form_time);
add_vector_form(new VectorFormConcentrationDiffusion(4, epsilon));
add_vector_form(new VectorFormConcentrationAdvection(4));
for(unsigned int i = 0;i < natural_bc_concentration_markers.size();i++)
add_vector_form_surf(new VectorFormConcentrationNatural(4, natural_bc_concentration_markers[i]));
add_vector_form_surf(new VectorFormConcentrationInterface (4));
};
// Destructor.
~EulerEquationsWeakFormImplicitCoupled() {};
protected:
class VectorFormConcentrationDiffusion : public VectorFormVol<double>
{
public:
VectorFormConcentrationDiffusion(int i, double epsilon)
: VectorFormVol<double>(i), epsilon(epsilon) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
Func<Real>* concentration_prev = u_ext[4];
return - epsilon * int_grad_u_grad_v<Real, Scalar>(n, wt, concentration_prev, v)
* static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return Ord(5);
}
// Member.
double epsilon;
};
class VectorFormConcentrationAdvection : public VectorFormVol<double>
{
public:
VectorFormConcentrationAdvection(int i) : VectorFormVol<double>(i) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
Func<Real>* density_prev = u_ext[0];
Func<Real>* density_vel_x_prev = u_ext[1];
Func<Real>* density_vel_y_prev = u_ext[2];
Func<Real>* concentration_prev = u_ext[4];
Scalar result = 0;
for (int i = 0;i < n;i++)
result += wt[i] * concentration_prev->val[i] * ((density_vel_x_prev->val[i]
* v->dx[i]) + (density_vel_y_prev->val[i] * v->dy[i]))
/ density_prev->val[i];
return result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return Ord(5);
}
};
class VectorFormConcentrationNatural : public VectorFormSurf<double>
{
public:
VectorFormConcentrationNatural(int i, std::string marker)
: VectorFormSurf<double>(i, marker) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
Func<Real>* density_prev = u_ext[0];
Func<Real>* density_vel_x_prev = u_ext[1];
Func<Real>* density_vel_y_prev = u_ext[2];
Func<Real>* concentration_prev = u_ext[4];
Scalar result = 0;
for (int i = 0;i < n;i++)
result += wt[i] * v->val[i] * concentration_prev->val[i]
* (density_vel_x_prev->val[i] * e->nx[i] + density_vel_y_prev->val[i] * e->ny[i])
/ density_prev->val[i];
// (OR: for inlet/outlet) result += wt[i] * v->val[i] * concentration_prev->val[i]
// * (V1_EXT * e->nx[i] + V2_EXT * e->ny[i]);
return - result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
Geom<double> *e, ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return Ord(5);
}
};
class VectorFormConcentrationInterface : public VectorFormSurf<double>
{
public:
VectorFormConcentrationInterface(int i) : VectorFormSurf<double>(i, H2D_DG_INNER_EDGE) {}
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *v,
Geom<Real> *e, ExtData<Scalar> *ext) const
{
Func<Real>* density_prev = u_ext[0];
Func<Real>* density_vel_x_prev = u_ext[1];
Func<Real>* density_vel_y_prev = u_ext[2];
Func<Real>* concentration_prev = u_ext[4];
Scalar result = 0;
for (int i = 0;i < n;i++)
result += 0.5 * wt[i] * (v->get_val_central(i) - v->get_val_neighbor(i)) *
(
(
density_vel_x_prev->get_val_central(i) * concentration_prev->get_val_central(i)
/ density_prev->get_val_central(i)
+
density_vel_x_prev->get_val_neighbor(i) * concentration_prev->get_val_neighbor(i)
/ density_prev->get_val_neighbor(i)
)
);
return - result * static_cast<EulerEquationsWeakFormImplicit*>(wf)->get_tau();
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, Geom<double> *e,
ExtData<double> *ext) const
{
return vector_form<double, double>(n, wt, u_ext, v, e, ext);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, Geom<Ord> *e,
ExtData<Ord> *ext) const
{
return Ord(5);
}
};
};
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/initial_condition.cpp | .cpp | 1,777 | 54 | /// Essential boundary condition for the coupled problem.
class ConcentrationTimedepEssentialBC : public EssentialBoundaryCondition<double> {
public:
ConcentrationTimedepEssentialBC(std::string marker, double constant, double startup_time)
: EssentialBoundaryCondition<double>(std::vector<std::string>()), startup_time(startup_time), constant(constant)
{
markers.push_back(marker);
}
~ConcentrationTimedepEssentialBC() {};
inline EssentialBCValueType get_value_type() const {
return BC_FUNCTION;
}
virtual double value(double x, double y, double n_x, double n_y, double t_x, double t_y) const
{
if(this->get_current_time() < startup_time)
return 0.0;
else
if(this->get_current_time() < 2 * startup_time)
return ((this->get_current_time() - startup_time) / startup_time) * constant;
else
return constant;
}
double startup_time;
double constant;
};
/// Class for Heating induced vortex, linear initial condition.
class InitialSolutionLinearProgress : public ExactSolutionScalar<double>
{
public:
InitialSolutionLinearProgress(MeshSharedPtr mesh, double max, double min, double size) : ExactSolutionScalar<double>(mesh), max(max), min(min), size(size) {};
virtual double value (double x, double y) const {
return min + ((max - min) * (size - y) / size);
};
virtual void derivatives (double x, double y, double& dx, double& dy) const {
dx = 0;
dy = - (max - min) / size;
};
virtual Ord ord(double x, double y) const {
return Ord(1);
}
MeshFunction<double>* clone() const { if(this->get_type() == HERMES_SLN) return Solution<double>::clone(); else return new InitialSolutionLinearProgress(mesh, max, min, size); }
// Value.
double max, min, size;
}; | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/euler-init-main-adapt.cpp | .cpp | 3,194 | 63 | #pragma region 1. Load mesh and initialize spaces.
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load(MESH_FILENAME, mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
mesh->refine_all_elements(0, true);
// Initialize boundary condition types and spaces with default shapesets.
SpaceSharedPtr<double> space_rho(new L2Space<double>(mesh, P_INIT));
SpaceSharedPtr<double> space_rho_v_x(new L2Space<double>(mesh, P_INIT));
SpaceSharedPtr<double> space_rho_v_y(new L2Space<double>(mesh, P_INIT));
SpaceSharedPtr<double> space_e(new L2Space<double>(mesh, P_INIT));
std::vector<SpaceSharedPtr<double> > spaces({ space_rho, space_rho_v_x, space_rho_v_y, space_e });
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
#pragma endregion
#pragma region 2. Initialize solutions.
MeshFunctionSharedPtr<double> sln_rho(new Solution<double>(mesh));
MeshFunctionSharedPtr<double> sln_rho_v_x(new Solution<double> (mesh));
MeshFunctionSharedPtr<double> sln_rho_v_y(new Solution<double> (mesh));
MeshFunctionSharedPtr<double> sln_e(new Solution<double> (mesh));
std::vector<MeshFunctionSharedPtr<double> > slns({ sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e });
MeshFunctionSharedPtr<double> rsln_rho(new Solution<double>(mesh));
MeshFunctionSharedPtr<double> rsln_rho_v_x(new Solution<double> (mesh));
MeshFunctionSharedPtr<double> rsln_rho_v_y(new Solution<double> (mesh));
MeshFunctionSharedPtr<double> rsln_e(new Solution<double> (mesh));
std::vector<MeshFunctionSharedPtr<double> > rslns({ rsln_rho, rsln_rho_v_x, rsln_rho_v_y, rsln_e });
#pragma endregion
#pragma region 3. Filters for visualization of Mach number, pressure + visualization setup.
MeshFunctionSharedPtr<double> Mach_number(new MachNumberFilter(rslns, KAPPA));
MeshFunctionSharedPtr<double> pressure(new PressureFilter(rslns, KAPPA));
ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 300));
ScalarView Mach_number_view("Mach number", new WinGeom(650, 0, 600, 300));
ScalarView eview("Error - density", new WinGeom(0, 330, 600, 300));
ScalarView eview1("Error - momentum", new WinGeom(0, 660, 600, 300));
OrderView order_view("Orders", new WinGeom(650, 330, 600, 300));
#pragma endregion
// Set up CFL calculation class.
CFLCalculation CFL(CFL_NUMBER, KAPPA);
Vector<double>* rhs_stabilization = create_vector<double>(HermesCommonApi.get_integral_param_value(matrixSolverType));
#pragma region 4. Adaptivity setup.
// Initialize refinement selector.
L2ProjBasedSelector<double> selector(CAND_LIST);
selector.set_dof_score_exponent(2.0);
//selector.set_error_weights(1.0, 1.0, 1.0);
// Error calculation.
DefaultErrorCalculator<double, HERMES_L2_NORM> errorCalculator(RelativeErrorToGlobalNorm, 4);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
Adapt<double> adaptivity(spaces, &errorCalculator, &stoppingCriterion);
#pragma endregion | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/euler-time-loop-space-adapt.cpp | .cpp | 7,672 | 190 | std::vector<MeshFunctionSharedPtr<double> > prev_slns({ prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e });
WeakFormSharedPtr<double> wf_stabilization(new EulerEquationsWeakFormStabilization(prev_rho));
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
((EulerEquationsWeakFormSemiImplicit*)(wf.get()))->set_stabilization(prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, NU_1, NU_2);
// Solver.
LinearSolver<double> solver(wf, spaces);
EulerEquationsWeakFormSemiImplicit* wf_ptr = (EulerEquationsWeakFormSemiImplicit*)(wf.get());
#pragma region 6. Time stepping loop.
int iteration = 0;
for(double t = 0.0; t < TIME_INTERVAL_LENGTH; t += time_step_n)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
#pragma region 6.1. Periodic global derefinements.
if (iteration > 1 && iteration % UNREF_FREQ == 0 && REFINEMENT_COUNT > 0)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
REFINEMENT_COUNT = 0;
space_rho->unrefine_all_mesh_elements(true);
space_rho->adjust_element_order(-1, P_INIT);
space_rho_v_x->adjust_element_order(-1, P_INIT);
space_rho_v_y->adjust_element_order(-1, P_INIT);
space_e->adjust_element_order(-1, P_INIT);
Space<double>::assign_dofs(spaces);
}
#pragma endregion
#pragma region 7. Adaptivity loop.
int as = 1; int ndofs_prev = 0; bool done = false;
do
{
// Info.
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Set the current time step.
wf_ptr->set_current_time_step(time_step_n);
#pragma region 7.1. Construct globally refined reference mesh and setup reference space.
int order_increase = CAND_LIST == H2D_HP_ANISO ? 1 : 0;
Mesh::ReferenceMeshCreator refMeshCreatorFlow(mesh);
MeshSharedPtr ref_mesh = refMeshCreatorFlow.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRho(space_rho, ref_mesh, order_increase);
SpaceSharedPtr<double> ref_space_rho = refSpaceCreatorRho.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVx(space_rho_v_x, ref_mesh, order_increase);
SpaceSharedPtr<double> ref_space_rho_v_x = refSpaceCreatorRhoVx.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVy(space_rho_v_y, ref_mesh, order_increase);
SpaceSharedPtr<double> ref_space_rho_v_y = refSpaceCreatorRhoVy.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorE(space_e, ref_mesh, order_increase);
SpaceSharedPtr<double> ref_space_e = refSpaceCreatorE.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_space_rho, ref_space_rho_v_x, ref_space_rho_v_y, ref_space_e });
solver.set_spaces(ref_spaces);
if(ndofs_prev != 0)
if(Space<double>::get_num_dofs(ref_spaces) == ndofs_prev)
selector.set_error_weights(2.0 * selector.get_error_weight_h(), 1.0, 1.0);
else
selector.set_error_weights(1.0, 1.0, 1.0);
ndofs_prev = Space<double>::get_num_dofs(ref_spaces);
// Project the previous time level solution onto the new fine mesh
Hermes::Mixins::Loggable::Static::info("Projecting the previous time level solution onto the new fine mesh.");
OGProjection<double>::project_global(ref_spaces, prev_slns, prev_slns);
#pragma endregion
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
{
SpaceSharedPtr<double> ref_space_stabilization(new L2Space<double>(ref_mesh, 0));
int mesh_size = ref_mesh->get_num_active_elements();
DiscreteProblem<double> dp_stabilization(wf_stabilization, ref_space_stabilization);
dp_stabilization.set_space(ref_space_stabilization);
dp_stabilization.assemble(rhs_stabilization);
if(!wf_ptr->discreteIndicator)
{
wf_ptr->set_discreteIndicator(new bool[mesh_size], mesh_size);
memset(wf_ptr->discreteIndicator, 0, mesh_size * sizeof(bool));
}
Element* e;
for_all_active_elements(e, ref_space_stabilization->get_mesh())
{
AsmList<double> al;
ref_space_stabilization->get_element_assembly_list(e, &al);
if(rhs_stabilization->get(al.get_dof()[0]) >= 1)
wf_ptr->discreteIndicator[e->id] = true;
}
}
// Solve the problem.
solver.solve();
#pragma region *. Get the solution with optional shock capturing.
if(!SHOCK_CAPTURING)
Solution<double>::vector_to_solutions(solver.get_sln_vector(), ref_spaces, rslns);
else
{
if(SHOCK_CAPTURING_TYPE == KRIVODONOVA)
{
FluxLimiter* flux_limiter = new FluxLimiter(FluxLimiter::Krivodonova, solver.get_sln_vector(), ref_spaces);
flux_limiter->limit_according_to_detector();
flux_limiter->get_limited_solutions(rslns);
delete flux_limiter;
}
if(SHOCK_CAPTURING_TYPE == KUZMIN)
{
PostProcessing::VertexBasedLimiter limiter(ref_spaces, solver.get_sln_vector(), 1);
limiter.get_solutions(rslns);
}
}
#pragma endregion
// Calculate time step according to CFL condition.
CFL.calculate(rslns, (ref_spaces)[0]->get_mesh(), time_step_n);
#pragma region 7.2. Project to coarse mesh -> error estimation -> space adaptivity
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
OGProjection<double>::project_global(spaces, rslns, slns, std::vector<NormType>({ HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM }));
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
errorCalculator.calculate_errors(slns, rslns);
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("err_est_rel: %g%%", err_est_rel_total);
// If err_est too large, adapt the mesh.
if (err_est_rel_total < adaptivityErrorStop(iteration))
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
done = adaptivity.adapt({&selector, &selector, &selector, &selector});
REFINEMENT_COUNT++;
as++;
}
#pragma endregion
#pragma region 7.3. Visualization and saving on disk.
if(done && (iteration - 1) % EVERY_NTH_STEP == 0)
{
// Hermes visualization.
if(HERMES_VISUALIZATION)
{
Mach_number->reinit();
pressure->reinit();
pressure_view.show(pressure, 1);
Mach_number_view.show(Mach_number, 1);
order_view.show((ref_spaces)[0]);
}
// Output solution in VTK format.
if(VTK_VISUALIZATION)
{
pressure->reinit();
Linearizer lin(FileExport);
char filename[40];
sprintf(filename, "Pressure-%i.vtk", iteration - 1);
lin.save_solution_vtk(pressure, filename, "Pressure", false);
sprintf(filename, "VelocityX-%i.vtk", iteration - 1);
lin.save_solution_vtk(prev_rho_v_x, filename, "VelocityX", false);
sprintf(filename, "VelocityY-%i.vtk", iteration - 1);
lin.save_solution_vtk(prev_rho_v_y, filename, "VelocityY", false);
sprintf(filename, "Rho-%i.vtk", iteration - 1);
lin.save_solution_vtk(prev_rho, filename, "Rho", false);
}
}
#pragma endregion
}
while (done == false);
#pragma endregion
// Copy the solutions into the previous time level ones.
prev_rho->copy(rsln_rho);
prev_rho_v_x->copy(rsln_rho_v_x);
prev_rho_v_y->copy(rsln_rho_v_y);
prev_e->copy(rsln_e);
}
#pragma endregion
pressure_view.close();
Mach_number_view.close();
return 0; | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/numerical_flux.h | .h | 5,477 | 190 | #ifndef NUMERICAL_FLUX_H
#define NUMERICAL_FLUX_H
#include "euler_util.h"
class NumericalFlux
{
public:
NumericalFlux(double kappa);
/// Calculates all components of the flux.
/// Stores the result in the array result.
virtual void numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny) = 0;
/// Calculates a specified component of the flux.
/// Returns the result.
virtual double numerical_flux_i(int component, double w_L[4], double w_R[4],
double nx, double ny) = 0;
virtual void numerical_flux_solid_wall(double result[4], double w_L[4], double nx, double ny) = 0;
virtual double numerical_flux_solid_wall_i(int component, double w_L[4], double nx, double ny) = 0;
virtual void numerical_flux_inlet(double result[4], double w_L[4], double w_B[4],
double nx, double ny) = 0;
virtual double numerical_flux_inlet_i(int component, double w_L[4], double w_B[4],
double nx, double ny) = 0;
virtual void numerical_flux_outlet(double result[4], double w_L[4], double pressure, double nx, double ny) = 0;
virtual double numerical_flux_outlet_i(int component, double w_L[4], double pressure, double nx, double ny) = 0;
/// Rotates the state_vector into the local coordinate system.
void Q(double result[4], double state_vector[4], double nx, double ny);
/// Rotates the state_vector back from the local coordinate system.
void Q_inv(double result[4], double state_vector[4], double nx, double ny);
void f_1(double result[4], double state[4]);
// Poisson adiabatic ant = c_p/c_v = 1 + R/c_v.
double kappa;
};
class StegerWarmingNumericalFlux : public NumericalFlux
{
public:
StegerWarmingNumericalFlux(double kappa);
virtual void numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny);
virtual double numerical_flux_i(int component, double w_L[4], double w_R[4],
double nx, double ny);
void P_plus(double* result, double w[4], double param[4],
double nx, double ny);
void P_minus(double* result, double w[4], double param[4],
double nx, double ny);
// Also calculates the speed of sound.
void Lambda_plus(double result[4]);
// Also calculates the speed of sound.
void Lambda_minus(double result[4]);
// Calculates all eigenvalues.
void Lambda(double result[4]);
void T_1(double result[4][4]);
void T_2(double result[4][4]);
void T_3(double result[4][4]);
void T_4(double result[4][4]);
void T_inv_1(double result[4][4]);
void T_inv_2(double result[4][4]);
void T_inv_3(double result[4][4]);
void T_inv_4(double result[4][4]);
virtual void numerical_flux_solid_wall(double result[4], double w_L[4], double nx, double ny);
virtual double numerical_flux_solid_wall_i(int component, double w_L[4], double nx, double ny);
virtual void numerical_flux_inlet(double result[4], double w_L[4], double w_B[4],
double nx, double ny);
virtual double numerical_flux_inlet_i(int component, double w_L[4], double w_B[4],
double nx, double ny);
virtual void numerical_flux_outlet(double result[4], double w_L[4], double pressure, double nx, double ny);
virtual double numerical_flux_outlet_i(int component, double w_L[4], double pressure, double nx, double ny);
double* get_q();
protected:
// States.
double q[4];
double q_1[4];
double q_L[4];
double q_R[4];
double q_L_star[4];
double q_R_star[4];
double q_B[4]; // Boundary
// Speeds of sound.
double a;
double a_L;
double a_R;
double a_L_star;
double a_R_star;
double a_B; // Boundary.
// x-velocity, y-velocity, magnitude.
double u, v, V;
};
class VijayasundaramNumericalFlux : public StegerWarmingNumericalFlux
{
public:
VijayasundaramNumericalFlux(double kappa);
EulerFluxes fluxes;
virtual void numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny);
};
class OsherSolomonNumericalFlux : public NumericalFlux
{
public:
OsherSolomonNumericalFlux(double kappa);
virtual void numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny);
virtual double numerical_flux_i(int component, double w_L[4], double w_R[4],
double nx, double ny);
virtual void numerical_flux_solid_wall(double result[4], double w_L[4], double nx, double ny);
virtual double numerical_flux_solid_wall_i(int component, double w_L[4], double nx, double ny);
virtual void numerical_flux_inlet(double result[4], double w_L[4], double w_R[4],
double nx, double ny);
virtual double numerical_flux_inlet_i(int component, double w_L[4], double w_R[4],
double nx, double ny);
virtual void numerical_flux_outlet(double result[4], double w_L[4], double pressure, double nx, double ny);
virtual double numerical_flux_outlet_i(int component, double w_L[4], double pressure, double nx, double ny);
protected:
void calculate_q_1_a_1_a_3();
void calculate_q_L_star();
void calculate_q_3();
void calculate_q_R_star();
// States.
double q_L[4];
double q_R[4];
double q_L_star[4];
double q_R_star[4];
double q_1[4];
double q_3[4];
double q_B[4]; // Boundary
// Speeds of sound.
double a_L;
double a_R;
double a_L_star;
double a_R_star;
double a_1;
double a_3;
double a_B; // Boundary.
// Utility quantities.
double z_L, z_R, s_L, s_R, alpha;
};
#endif | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/euler/numerical_flux.cpp | .cpp | 42,960 | 1,311 | #include "numerical_flux.h"
NumericalFlux::NumericalFlux(double kappa) : kappa(kappa)
{
}
void NumericalFlux::Q(double result[4], double state_vector[4], double nx, double ny)
{
result[0] = state_vector[0];
double temp_result_1 = nx * state_vector[1] + ny * state_vector[2];
double temp_result_2 = -ny * state_vector[1] + nx * state_vector[2];
result[1] = temp_result_1;
result[2] = temp_result_2;
result[3] = state_vector[3];
}
void NumericalFlux::Q_inv(double result[4], double state_vector[4], double nx, double ny)
{
result[0] = state_vector[0];
double temp_result_1 = nx * state_vector[1] - ny * state_vector[2];
double temp_result_2 = ny * state_vector[1] + nx * state_vector[2];
result[1] = temp_result_1;
result[2] = temp_result_2;
result[3] = state_vector[3];
}
void NumericalFlux::f_1(double result[4], double state[4])
{
result[0] = state[1];
result[1] = state[1] * state[1] / state[0] + QuantityCalculator::calc_pressure(state[0], state[1], state[2], state[3], kappa);
result[2] = state[2] * state[1] / state[0];
result[3] = (state[1] / state[0]) * (state[3] + QuantityCalculator::calc_pressure(state[0], state[1], state[2], state[3], kappa));
}
VijayasundaramNumericalFlux::VijayasundaramNumericalFlux(double kappa) : StegerWarmingNumericalFlux(kappa), fluxes(EulerFluxes(kappa))
{
}
void VijayasundaramNumericalFlux::numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny)
{
double result_temp[4];
double result_1, result_2;
double w[4];
w[0] = w_L[0];
w[1] = w_L[1];
w[2] = w_L[2];
w[3] = w_L[3];
result_1 = fluxes.A_1_0_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_0_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_0_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_0_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_0_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_0_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_0_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_0_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[0] = result_1 * nx + result_2 * ny;
result_1 = fluxes.A_1_1_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_1_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_1_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_1_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_1_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_1_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_1_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_1_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[1] = result_1 * nx + result_2 * ny;
result_1 = fluxes.A_1_2_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_2_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_2_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_2_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_2_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_2_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_2_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_2_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[2] = result_1 * nx + result_2 * ny;
result_1 = fluxes.A_1_3_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_3_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_3_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_3_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_3_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_3_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_3_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_3_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[3] = result_1 * nx + result_2 * ny;
//////////////
w[0] = w_R[0];
w[1] = w_R[1];
w[2] = w_R[2];
w[3] = w_R[3];
result_1 = fluxes.A_1_0_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_0_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_0_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_0_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_0_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_0_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_0_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_0_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[0] += result_1 * nx + result_2 * ny;
result_1 = fluxes.A_1_1_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_1_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_1_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_1_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_1_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_1_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_1_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_1_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[1] += result_1 * nx + result_2 * ny;
result_1 = fluxes.A_1_2_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_2_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_2_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_2_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_2_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_2_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_2_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_2_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[2] += result_1 * nx + result_2 * ny;
result_1 = fluxes.A_1_3_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_1_3_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_1_3_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_1_3_3(w[0], w[1], w[2], w[3]) * w[3];
result_2 = fluxes.A_2_3_0(w[0], w[1], w[2], w[3]) * w[0] + fluxes.A_2_3_1(w[0], w[1], w[2], w[3]) * w[1] + fluxes.A_2_3_2(w[0], w[1], w[2], w[3]) * w[2] + fluxes.A_2_3_3(w[0], w[1], w[2], w[3]) * w[3];
result_temp[3] += result_1 * nx + result_2 * ny;
for (unsigned int i = 0; i < 4; i++)
result[i] = result_temp[i] / 2.;
double w_mean[4];
w_mean[0] = w_L[0] + w_R[0];
w_mean[1] = w_L[1] + w_R[1];
w_mean[2] = w_L[2] + w_R[2];
w_mean[3] = w_L[3] + w_R[3];
P_plus(result_temp, w_mean, w_L, nx, ny);
P_minus(result, w_mean, w_R, nx, ny);
for (unsigned int i = 0; i < 4; i++)
result[i] += result_temp[i];
}
StegerWarmingNumericalFlux::StegerWarmingNumericalFlux(double kappa) : NumericalFlux(kappa) {};
void StegerWarmingNumericalFlux::numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny)
{
double result_temp[4];
P_plus(result_temp, w_L, w_L, nx, ny);
P_minus(result, w_R, w_R, nx, ny);
for (unsigned int i = 0; i < 4; i++)
result[i] += result_temp[i];
}
double StegerWarmingNumericalFlux::numerical_flux_i(int component, double w_L[4], double w_R[4],
double nx, double ny)
{
double result[4];
numerical_flux(result, w_L, w_R, nx, ny);
return result[component];
}
void StegerWarmingNumericalFlux::P_plus(double* result, double w[4], double param[4],
double nx, double ny)
{
Q(q, w, nx, ny);
// Initialize the matrices.
double T[4][4];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++)
T[i][j] = 0.0;
double T_inv[4][4];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++)
T_inv[i][j] = 0.0;
// Calculate Lambda^+.
Lambda_plus(result);
// Calculate the necessary rows / columns of T(T_inv).
if (result[0] > 0) {
T_1(T);
T_inv_1(T_inv);
}
if (result[1] > 0) {
T_2(T);
T_inv_2(T_inv);
}
if (result[2] > 0) {
T_3(T);
T_inv_3(T_inv);
}
if (result[3] > 0) {
T_4(T);
T_inv_4(T_inv);
}
// The matrix T * Lambda * T^{-1}
double diag_inv[4][4];
double A_1[4][4];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++)
diag_inv[i][j] = result[i] * T_inv[i][j];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++) {
A_1[i][j] = 0;
for (unsigned int k = 0; k < 4; k++)
A_1[i][j] += T[i][k] * diag_inv[k][j];
}
// Finale.
Q(param, param, nx, ny);
for (unsigned int i = 0; i < 4; i++) {
result[i] = 0;
for (unsigned int j = 0; j < 4; j++)
result[i] += A_1[i][j] * param[j];
}
Q_inv(result, result, nx, ny);
}
void StegerWarmingNumericalFlux::P_minus(double* result, double w[4], double param[4],
double nx, double ny)
{
Q(q, w, nx, ny);
// Initialize the matrices.
double T[4][4];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++)
T[i][j] = 0.0;
double T_inv[4][4];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++)
T_inv[i][j] = 0.0;
// Calculate Lambda^-.
Lambda_minus(result);
// Calculate the necessary rows / columns of T(T_inv).
if (result[0] < 0) {
T_1(T);
T_inv_1(T_inv);
}
if (result[1] < 0) {
T_2(T);
T_inv_2(T_inv);
}
if (result[2] < 0) {
T_3(T);
T_inv_3(T_inv);
}
if (result[3] < 0) {
T_4(T);
T_inv_4(T_inv);
}
// The matrix T * Lambda * T^{-1}
double diag_inv[4][4];
double A_1[4][4];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++)
diag_inv[i][j] = result[i] * T_inv[i][j];
for (unsigned int i = 0; i < 4; i++)
for (unsigned int j = 0; j < 4; j++) {
A_1[i][j] = 0;
for (unsigned int k = 0; k < 4; k++)
A_1[i][j] += T[i][k] * diag_inv[k][j];
}
// Finale.
Q(param, param, nx, ny);
for (unsigned int i = 0; i < 4; i++) {
result[i] = 0;
for (unsigned int j = 0; j < 4; j++)
result[i] += A_1[i][j] * param[j];
}
Q_inv(result, result, nx, ny);
}
void StegerWarmingNumericalFlux::Lambda_plus(double result[4])
{
a = QuantityCalculator::calc_sound_speed(q[0], q[1], q[2], q[3], kappa);
u = q[1] / q[0];
v = q[2] / q[0];
V = u*u + v*v;
result[0] = u - a < 0 ? 0 : u - a;
result[1] = u < 0 ? 0 : u;
result[2] = u < 0 ? 0 : u;
result[3] = u + a < 0 ? 0 : u + a;
}
void StegerWarmingNumericalFlux::Lambda_minus(double result[4])
{
a = QuantityCalculator::calc_sound_speed(q[0], q[1], q[2], q[3], kappa);
u = q[1] / q[0];
v = q[2] / q[0];
V = u*u + v*v;
result[0] = u - a < 0 ? u - a : 0;
result[1] = u < 0 ? u : 0;
result[2] = u < 0 ? u : 0;
result[3] = u + a < 0 ? u + a : 0;
}
void StegerWarmingNumericalFlux::Lambda(double result[4])
{
a = QuantityCalculator::calc_sound_speed(q[0], q[1], q[2], q[3], kappa);
u = q[1] / q[0];
v = q[2] / q[0];
V = u*u + v*v;
result[0] = u - a;
result[1] = u;
result[2] = u;
result[3] = u + a;
}
void StegerWarmingNumericalFlux::T_1(double result[4][4])
{
result[0][0] = 1.0;
result[1][0] = u - a;
result[2][0] = v;
result[3][0] = (V / 2.0) + (a*a / (kappa - 1.0)) - (u * a);
}
void StegerWarmingNumericalFlux::T_2(double result[4][4])
{
result[0][1] = 1.0;
result[1][1] = u;
result[2][1] = v;
result[3][1] = V / 2.0;
}
void StegerWarmingNumericalFlux::T_3(double result[4][4])
{
result[0][2] = 1.0;
result[1][2] = u;
result[2][2] = v - a;
result[3][2] = (V / 2.0) - v * a;
}
void StegerWarmingNumericalFlux::T_4(double result[4][4])
{
result[0][3] = 1.0;
result[1][3] = u + a;
result[2][3] = v;
result[3][3] = (V / 2.0) + (a * a / (kappa - 1.0)) + (u * a);
}
void StegerWarmingNumericalFlux::T_inv_1(double result[4][4])
{
result[0][0] = (1.0 / (a * a)) * (0.5 * (((kappa - 1) * V / 2.0) + u * a));
result[0][1] = (1.0 / (a * a)) * (-(a + u * (kappa - 1.0)) / 2.0);
result[0][2] = (1.0 / (a * a)) * (-(v * (kappa - 1.0)) / 2.0);
result[0][3] = (1.0 / (a * a)) * (kappa - 1.0) / 2.0;
}
void StegerWarmingNumericalFlux::T_inv_2(double result[4][4])
{
result[1][0] = (1.0 / (a * a)) * (a * a - v * a - (kappa - 1.0) * (V / 2.0));
result[1][1] = (1.0 / (a * a)) * u * (kappa - 1.0);
result[1][2] = (1.0 / (a * a)) * (a + v * (kappa - 1.0));
result[1][3] = (1.0 / (a * a)) * (1.0 - kappa);
}
void StegerWarmingNumericalFlux::T_inv_3(double result[4][4])
{
result[2][0] = (1.0 / (a * a)) * v * a;
result[2][1] = (1.0 / (a * a)) * 0.0;
result[2][2] = (1.0 / (a * a)) * (-a);
result[2][3] = (1.0 / (a * a)) * 0.0;
}
void StegerWarmingNumericalFlux::T_inv_4(double result[4][4])
{
result[3][0] = (1.0 / (a * a)) * (0.5 * (((kappa - 1.0) * V / 2.0) - u * a));
result[3][1] = (1.0 / (a * a)) * (a - u * (kappa - 1.0)) / 2.0;
result[3][2] = (1.0 / (a * a)) * (-(v * (kappa - 1.0)) / 2.0);
result[3][3] = (1.0 / (a * a)) * (kappa - 1.0) / 2.0;
}
void StegerWarmingNumericalFlux::numerical_flux_solid_wall(double result[4], double w_L[4], double nx, double ny)
{
Q(q_L, w_L, nx, ny);
a_B = QuantityCalculator::calc_sound_speed(q_L[0], q_L[1], q_L[2], q_L[3], kappa) + ((kappa - 1) * q_L[1] / (2 * q_L[0]));
double rho_B = std::pow(a_B * a_B * q_L[0] / (kappa * QuantityCalculator::calc_pressure(q_L[0], q_L[1], q_L[2], q_L[3], kappa)), (1 / (kappa - 1))) * q_L[0];
q_R[0] = 0;
q_R[1] = rho_B * a_B * a_B / kappa;
q_R[2] = 0;
q_R[3] = 0;
Q_inv(result, q_R, nx, ny);
}
double StegerWarmingNumericalFlux::numerical_flux_solid_wall_i(int component, double w_L[4], double nx, double ny)
{
double result[4];
numerical_flux_solid_wall(result, w_L, nx, ny);
return result[component];
}
void StegerWarmingNumericalFlux::numerical_flux_inlet(double result[4], double w_L[4], double w_B[4],
double nx, double ny)
{
// At the beginning, rotate the states into the local coordinate system and store the left and right state
// so we do not have to pass it around.
Q(q_L, w_L, nx, ny);
Q(q_B, w_B, nx, ny);
// Speeds of sound.
a_L = QuantityCalculator::calc_sound_speed(q_L[0], q_L[1], q_L[2], q_L[3], kappa);
a_B = QuantityCalculator::calc_sound_speed(q_B[0], q_B[1], q_B[2], q_B[3], kappa);
if (q_L[1] / q_L[0] > a_L) {// Supersonic inlet - everything is prescribed.
f_1(result, q_B);
Q_inv(result, result, nx, ny);
return;
}
else {// Subsonic inlet - only rho_b, v_x, v_y are prescribed, pressure is calculated as follows. The pressure is prescribed always so that one can know if the
// inlet is subsonic or supersonic.
double a_1 = a_L + ((kappa - 1) / 2) * (q_L[1] / q_L[0] - q_B[1] / q_B[0]);
q_1[0] = std::pow(a_1 * a_1 * q_L[0] / (kappa * QuantityCalculator::calc_pressure(q_L[0], q_L[1], q_L[2], q_L[3], kappa)), 1 / (kappa - 1)) * q_L[0];
q_1[1] = q_1[0] * q_B[1] / q_B[0];
q_1[2] = q_1[0] * q_L[2] / q_L[0];
q_1[3] = QuantityCalculator::calc_energy(q_1[0], q_1[1], q_1[2], a_1 * a_1 * q_1[0] / kappa, kappa);
if (q_B[1] / q_B[0] < 0)
if (q_B[1] / q_B[0] < a_1) {
f_1(result, q_B);
Q_inv(result, result, nx, ny);
return;
}
else {
double a_l_star = (((kappa - 1) / (kappa + 1)) * q_L[1] / q_L[0]) + 2 * a_L / (kappa + 1);
q_L_star[0] = std::pow(a_l_star / a_L, 2 / (kappa - 1)) * q_L[0];
q_L_star[1] = a_l_star;
q_L_star[2] = q_L_star[0] * q_L[2] / q_L[0];
q_L_star[3] = QuantityCalculator::calc_energy(q_L_star[0], q_L_star[1], q_L_star[2], q_L_star[0] * a_l_star * a_l_star / kappa, kappa);
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_B);
f_1(second1, q_L_star);
f_1(third1, q_1);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] + second1[i] - third1[i];
Q_inv(result, result, nx, ny);
return;
}
else
if (q_B[1] / q_B[0] < a_1) {
f_1(result, q_1);
Q_inv(result, result, nx, ny);
return;
}
else {
double a_l_star = (((kappa - 1) / (kappa + 1)) * q_L[1] / q_L[0]) + 2 * a_L / (kappa + 1);
q_L_star[0] = std::pow(a_l_star / a_L, 2 / (kappa - 1)) * q_L[0];
q_L_star[1] = a_l_star;
q_L_star[2] = q_L_star[0] * q_L[2] / q_L[0];
q_L_star[3] = QuantityCalculator::calc_energy(q_L_star[0], q_L_star[1], q_L_star[2], q_L_star[0] * a_l_star * a_l_star / kappa, kappa);
f_1(result, q_L_star);
Q_inv(result, result, nx, ny);
return;
}
}
}
double StegerWarmingNumericalFlux::numerical_flux_inlet_i(int component, double w_L[4], double w_B[4],
double nx, double ny)
{
double result[4];
numerical_flux_inlet(result, w_L, w_B, nx, ny);
return result[component];
}
void StegerWarmingNumericalFlux::numerical_flux_outlet(double result[4], double w_L[4], double pressure, double nx, double ny)
{
// At the beginning, rotate the states into the local coordinate system and store the left and right state
// so we do not have to pass it around.
Q(q_L, w_L, nx, ny);
double a_L = QuantityCalculator::calc_sound_speed(q_L[0], q_L[1], q_L[2], q_L[3], kappa);
if (q_L[1] / q_L[0] > a_L) {// Supersonic inlet - everything is prescribed.
f_1(result, q_L);
Q_inv(result, result, nx, ny);
return;
}
else {
this->q_B[0] = q_L[0] * std::pow(pressure / QuantityCalculator::calc_pressure(this->q_L[0], this->q_L[1], this->q_L[2], this->q_L[3], kappa), 1 / kappa);
this->q_B[1] = this->q_B[0] * (q_L[1] / q_L[0] + (2 / (kappa - 1)) * (a_L - std::sqrt(kappa * pressure / q_B[0])));
this->q_B[2] = this->q_B[0] * this->q_L[2] / this->q_L[0];
this->q_B[3] = QuantityCalculator::calc_energy(this->q_B[0], this->q_B[1], this->q_B[2], pressure, kappa);
if (q_B[1] / q_B[0] < QuantityCalculator::calc_sound_speed(this->q_B[0], this->q_B[1], this->q_B[2], this->q_B[3], kappa)) {
f_1(result, q_B);
Q_inv(result, result, nx, ny);
return;
}
else {
double a_l_star = (((kappa - 1) / (kappa + 1)) * q_L[1] / q_L[0]) + 2 * a_L / (kappa + 1);
q_L_star[0] = std::pow(a_l_star / a_L, 2 / (kappa - 1)) * q_L[0];
q_L_star[1] = a_l_star;
q_L_star[2] = q_L_star[0] * q_L[2] / q_L[0];
q_L_star[3] = QuantityCalculator::calc_energy(q_L_star[0], q_L_star[1], q_L_star[2], q_L_star[0] * a_l_star * a_l_star / kappa, kappa);
f_1(result, q_L_star);
Q_inv(result, result, nx, ny);
return;
}
}
}
double StegerWarmingNumericalFlux::numerical_flux_outlet_i(int component, double w_L[4], double pressure, double nx, double ny)
{
double result[4];
numerical_flux_outlet(result, w_L, pressure, nx, ny);
return result[component];
}
double* StegerWarmingNumericalFlux::get_q()
{
return q;
}
OsherSolomonNumericalFlux::OsherSolomonNumericalFlux(double kappa) : NumericalFlux(kappa)
{
}
void OsherSolomonNumericalFlux::numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny)
{
// At the beginning, rotate the states into the local coordinate system and store the left and right state
// so we do not have to pass it around.
Q(q_L, w_L, nx, ny);
Q(q_R, w_R, nx, ny);
// Decide what we have to calculate.
// Speeds of sound.
a_L = QuantityCalculator::calc_sound_speed(q_L[0], q_L[1], q_L[2], q_L[3], kappa);
a_R = QuantityCalculator::calc_sound_speed(q_R[0], q_R[1], q_R[2], q_R[3], kappa);
// Check that we can use the following.
double right_hand_side = 0;
if ((q_L[2] / q_L[0]) - (q_R[2] / q_R[0]) > 0)
right_hand_side = (q_L[2] / q_L[0] - q_R[2] / q_R[0] > 0) / 2;
if (a_L + a_R + ((kappa - 1) * (q_L[1] / q_L[0] - q_R[1] / q_R[0]) / 2) <= right_hand_side)
throw Hermes::Exceptions::Exception("Osher-Solomon numerical flux is not possible to construct according to the table.");
// Utility numbers.
this->z_L = (0.5 * (kappa - 1) * q_L[1] / q_L[0]) + a_L;
this->z_R = (0.5 * (kappa - 1) * q_R[1] / q_R[0]) - a_R;
this->s_L = QuantityCalculator::calc_pressure(q_L[0], q_L[1], q_L[2], q_L[3], kappa) / std::pow(q_L[0], kappa);
this->s_R = QuantityCalculator::calc_pressure(q_R[0], q_R[1], q_R[2], q_R[3], kappa) / std::pow(q_R[0], kappa);
this->alpha = std::pow(s_R / s_L, 1 / (2 * kappa));
// We always need to calculate q_1, a_1, a_3, as we are going to decide what to return based on this.
calculate_q_1_a_1_a_3();
// First column in table 3.4.1 on the page 233 in Feist (2003).
if (q_R[1] / q_R[0] >= -a_R && q_L[1] / q_L[0] <= a_L) {
// First row.
if (a_1 <= q_1[1] / q_1[0]) {
calculate_q_L_star();
f_1(result, q_L_star);
Q_inv(result, result, nx, ny);
return;
}
// Second row.
if (0 < q_1[1] / q_1[0] && q_1[1] / q_1[0] < a_1) {
f_1(result, q_1);
Q_inv(result, result, nx, ny);
return;
}
// Third row.
if (-a_3 <= q_1[1] / q_1[0] && q_1[1] / q_1[0] <= 0) {
calculate_q_3();
f_1(result, q_3);
Q_inv(result, result, nx, ny);
return;
}
// Fourth row.
if (q_1[1] / q_1[0] < -a_3) {
calculate_q_R_star();
f_1(result, q_R_star);
Q_inv(result, result, nx, ny);
return;
}
}
// Second column in table 3.4.1 on the page 233 in Feist (2003).
if (q_R[1] / q_R[0] >= -a_R && q_L[1] / q_L[0] > a_L) {
// First row.
if (a_1 <= q_1[1] / q_1[0]) {
f_1(result, q_L);
Q_inv(result, result, nx, ny);
return;
}
// Second row.
if (0 < q_1[1] / q_1[0] && q_1[1] / q_1[0] < a_1) {
calculate_q_L_star();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_L);
f_1(second1, q_L_star);
f_1(third1, q_1);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i];
Q_inv(result, result, nx, ny);
return;
}
// Third row.
if (-a_3 <= q_1[1] / q_1[0] && q_1[1] / q_1[0] <= 0) {
calculate_q_L_star();
calculate_q_3();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_L);
f_1(second1, q_L_star);
f_1(third1, q_3);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i];
Q_inv(result, result, nx, ny);
return;
}
// Fourth row.
if (q_1[1] / q_1[0] < -a_3) {
calculate_q_L_star();
calculate_q_R_star();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_L);
f_1(second1, q_L_star);
f_1(third1, q_R_star);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i];
Q_inv(result, result, nx, ny);
return;
}
}
// Third column in table 3.4.1 on the page 233 in Feist (2003).
if (q_R[1] / q_R[0] < -a_R && q_L[1] / q_L[0] <= a_L) {
// First row.
if (a_1 <= q_1[1] / q_1[0]) {
calculate_q_R_star();
calculate_q_L_star();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_R);
f_1(second1, q_R_star);
f_1(third1, q_L_star);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i];
Q_inv(result, result, nx, ny);
return;
}
// Second row.
if (0 < q_1[1] / q_1[0] && q_1[1] / q_1[0] < a_1) {
calculate_q_R_star();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_R);
f_1(second1, q_R_star);
f_1(third1, q_1);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i];
Q_inv(result, result, nx, ny);
return;
}
// Third row.
if (-a_3 <= q_1[1] / q_1[0] && q_1[1] / q_1[0] <= 0) {
calculate_q_R_star();
calculate_q_3();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_R);
f_1(second1, q_R_star);
f_1(third1, q_3);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i];
return;
}
// Fourth row.
if (q_1[1] / q_1[0] < -a_3) {
f_1(result, q_R);
Q_inv(result, result, nx, ny);
return;
}
}
// Fourth column in table 3.4.1 on the page 233 in Feist (2003).
if (q_R[1] / q_R[0] < -a_R && q_L[1] / q_L[0] > a_L) {
// First row.
if (a_1 <= q_1[1] / q_1[0]) {
calculate_q_R_star();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_L);
f_1(second1, q_R_star);
f_1(third1, q_R);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i];
Q_inv(result, result, nx, ny);
return;
}
// Second row.
if (0 < q_1[1] / q_1[0] && q_1[1] / q_1[0] < a_1) {
calculate_q_R_star();
calculate_q_L_star();
double first1[4];
double second1[4];
double third1[4];
double fourth1[4];
double fifth1[4];
f_1(first1, q_L);
f_1(second1, q_R_star);
f_1(third1, q_R);
f_1(fourth1, q_L_star);
f_1(fifth1, q_1);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i] - fourth1[i] + fifth1[i];
Q_inv(result, result, nx, ny);
return;
}
// Third row.
if (-a_3 <= q_1[1] / q_1[0] && q_1[1] / q_1[0] <= 0) {
calculate_q_R_star();
calculate_q_L_star();
calculate_q_3();
double first1[4];
double second1[4];
double third1[4];
double fourth1[4];
double fifth1[4];
f_1(first1, q_L);
f_1(second1, q_R_star);
f_1(third1, q_R);
f_1(fourth1, q_L_star);
f_1(fifth1, q_3);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] - second1[i] + third1[i] - fourth1[i] + fifth1[i];
Q_inv(result, result, nx, ny);
return;
}
// Fourth row.
if (q_1[1] / q_1[0] < -a_3) {
calculate_q_L_star();
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_L);
f_1(second1, q_R);
f_1(third1, q_L_star);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] + second1[i] - third1[i];
Q_inv(result, result, nx, ny);
return;
}
}
}
void OsherSolomonNumericalFlux::numerical_flux_solid_wall(double result[4], double w_L[4], double nx, double ny)
{
Q(q_L, w_L, nx, ny);
a_B = QuantityCalculator::calc_sound_speed(q_L[0], q_L[1], q_L[2], q_L[3], kappa) + ((kappa - 1) * q_L[1] / (2 * q_L[0]));
double rho_B = std::pow(a_B * a_B * q_L[0] / (kappa * QuantityCalculator::calc_pressure(q_L[0], q_L[1], q_L[2], q_L[3], kappa)), (1 / (kappa - 1))) * q_L[0];
q_R[0] = 0;
q_R[1] = rho_B * a_B * a_B / kappa;
q_R[2] = 0;
q_R[3] = 0;
Q_inv(result, q_R, nx, ny);
}
double OsherSolomonNumericalFlux::numerical_flux_solid_wall_i(int component, double w_L[4], double nx, double ny)
{
double result[4];
numerical_flux_solid_wall(result, w_L, nx, ny);
return result[component];
}
void OsherSolomonNumericalFlux::numerical_flux_inlet(double result[4], double w_L[4], double w_B[4],
double nx, double ny)
{
// At the beginning, rotate the states into the local coordinate system and store the left and right state
// so we do not have to pass it around.
Q(q_L, w_L, nx, ny);
Q(q_B, w_B, nx, ny);
// Speeds of sound.
a_L = QuantityCalculator::calc_sound_speed(q_L[0], q_L[1], q_L[2], q_L[3], kappa);
a_B = QuantityCalculator::calc_sound_speed(q_B[0], q_B[1], q_B[2], q_B[3], kappa);
if (q_L[1] / q_L[0] > a_L) {// Supersonic inlet - everything is prescribed.
f_1(result, q_B);
Q_inv(result, result, nx, ny);
return;
}
else {// Subsonic inlet - only rho_b, v_x, v_y are prescribed, pressure is calculated as follows. The pressure is prescribed always so that one can know if the
// inlet is subsonic or supersonic.
double a_1 = a_L + ((kappa - 1) / 2) * (q_L[1] / q_L[0] - q_B[1] / q_B[0]);
q_1[0] = std::pow(a_1 * a_1 * q_L[0] / (kappa * QuantityCalculator::calc_pressure(q_L[0], q_L[1], q_L[2], q_L[3], kappa)), 1 / (kappa - 1)) * q_L[0];
q_1[1] = q_1[0] * q_B[1] / q_B[0];
q_1[2] = q_1[0] * q_L[2] / q_L[0];
q_1[3] = QuantityCalculator::calc_energy(q_1[0], q_1[1], q_1[2], a_1 * a_1 * q_1[0] / kappa, kappa);
if (q_B[1] / q_B[0] < 0)
if (q_B[1] / q_B[0] < a_1) {
f_1(result, q_B);
Q_inv(result, result, nx, ny);
return;
}
else {
double a_l_star = (((kappa - 1) / (kappa + 1)) * q_L[1] / q_L[0]) + 2 * a_L / (kappa + 1);
q_L_star[0] = std::pow(a_l_star / a_L, 2 / (kappa - 1)) * q_L[0];
q_L_star[1] = a_l_star;
q_L_star[2] = q_L_star[0] * q_L[2] / q_L[0];
q_L_star[3] = QuantityCalculator::calc_energy(q_L_star[0], q_L_star[1], q_L_star[2], q_L_star[0] * a_l_star * a_l_star / kappa, kappa);
double first1[4];
double second1[4];
double third1[4];
f_1(first1, q_B);
f_1(second1, q_L_star);
f_1(third1, q_1);
for (unsigned int i = 0; i < 4; i++)
result[i] = first1[i] + second1[i] - third1[i];
Q_inv(result, result, nx, ny);
return;
}
else
if (q_B[1] / q_B[0] < a_1) {
f_1(result, q_1);
Q_inv(result, result, nx, ny);
return;
}
else {
double a_l_star = (((kappa - 1) / (kappa + 1)) * q_L[1] / q_L[0]) + 2 * a_L / (kappa + 1);
q_L_star[0] = std::pow(a_l_star / a_L, 2 / (kappa - 1)) * q_L[0];
q_L_star[1] = a_l_star;
q_L_star[2] = q_L_star[0] * q_L[2] / q_L[0];
q_L_star[3] = QuantityCalculator::calc_energy(q_L_star[0], q_L_star[1], q_L_star[2], q_L_star[0] * a_l_star * a_l_star / kappa, kappa);
f_1(result, q_L_star);
Q_inv(result, result, nx, ny);
return;
}
}
}
double OsherSolomonNumericalFlux::numerical_flux_inlet_i(int component, double w_L[4], double w_B[4],
double nx, double ny)
{
double result[4];
numerical_flux_inlet(result, w_L, w_B, nx, ny);
return result[component];
}
void OsherSolomonNumericalFlux::numerical_flux_outlet(double result[4], double w_L[4], double pressure, double nx, double ny)
{
// At the beginning, rotate the states into the local coordinate system and store the left and right state
// so we do not have to pass it around.
Q(q_L, w_L, nx, ny);
double a_L = QuantityCalculator::calc_sound_speed(q_L[0], q_L[1], q_L[2], q_L[3], kappa);
if (q_L[1] / q_L[0] > a_L) {// Supersonic inlet - everything is prescribed.
f_1(result, q_L);
Q_inv(result, result, nx, ny);
return;
}
else {
this->q_B[0] = q_L[0] * std::pow(pressure / QuantityCalculator::calc_pressure(this->q_L[0], this->q_L[1], this->q_L[2], this->q_L[3], kappa), 1 / kappa);
this->q_B[1] = this->q_B[0] * (q_L[1] / q_L[0] + (2 / (kappa - 1)) * (a_L - std::sqrt(kappa * pressure / q_B[0])));
this->q_B[2] = this->q_B[0] * this->q_L[2] / this->q_L[0];
this->q_B[3] = QuantityCalculator::calc_energy(this->q_B[0], this->q_B[1], this->q_B[2], pressure, kappa);
if (q_B[1] / q_B[0] < QuantityCalculator::calc_sound_speed(this->q_B[0], this->q_B[1], this->q_B[2], this->q_B[3], kappa)) {
f_1(result, q_B);
Q_inv(result, result, nx, ny);
return;
}
else {
double a_l_star = (((kappa - 1) / (kappa + 1)) * q_L[1] / q_L[0]) + 2 * a_L / (kappa + 1);
q_L_star[0] = std::pow(a_l_star / a_L, 2 / (kappa - 1)) * q_L[0];
q_L_star[1] = a_l_star;
q_L_star[2] = q_L_star[0] * q_L[2] / q_L[0];
q_L_star[3] = QuantityCalculator::calc_energy(q_L_star[0], q_L_star[1], q_L_star[2], q_L_star[0] * a_l_star * a_l_star / kappa, kappa);
f_1(result, q_L_star);
Q_inv(result, result, nx, ny);
return;
}
}
}
double OsherSolomonNumericalFlux::numerical_flux_outlet_i(int component, double w_L[4], double pressure, double nx, double ny)
{
double result[4];
numerical_flux_outlet(result, w_L, pressure, nx, ny);
return result[component];
}
void OsherSolomonNumericalFlux::calculate_q_1_a_1_a_3()
{
this->a_1 = (z_L - z_R) / (1 + alpha);
this->q_1[0] = std::pow(a_1 / a_L, 2 / (kappa - 1)) * q_L[0];
this->q_1[1] = this->q_1[0] * 2 * (z_L - a_1) / (kappa - 1);
this->q_1[2] = this->q_1[0] * this->q_L[2] / this->q_L[0];
this->q_1[3] = QuantityCalculator::calc_energy(this->q_1[0], this->q_1[1], this->q_1[2], a_1 * a_1 * q_1[0] / kappa, kappa);
this->a_3 = alpha * a_1;
}
void OsherSolomonNumericalFlux::calculate_q_L_star()
{
this->a_L_star = 2 * z_L / (kappa + 1);
this->q_L_star[0] = std::pow(a_L_star / a_L, 2 / (kappa - 1)) * q_L[0];
this->q_L_star[1] = this->q_L_star[0] * a_L_star;
this->q_L_star[2] = this->q_1[0] * this->q_L[2] / this->q_L[0];
this->q_L_star[3] = QuantityCalculator::calc_energy(this->q_L_star[0], this->q_L_star[1], this->q_L_star[2], a_L_star * a_L_star * q_L_star[0] / kappa, kappa);
}
void OsherSolomonNumericalFlux::calculate_q_3()
{
// a_3 already calculated.
this->q_3[0] = q_1[0] / (alpha * alpha);
this->q_3[1] = this->q_3[0] * this->q_1[1] / this->q_1[0];
this->q_3[2] = this->q_3[0] * this->q_R[2] / this->q_R[0];
this->q_3[3] = QuantityCalculator::calc_energy(this->q_3[0], this->q_3[1], this->q_3[2], a_3 * a_3 * q_3[0] / kappa, kappa);
}
void OsherSolomonNumericalFlux::calculate_q_R_star()
{
this->a_R_star = -2 * z_R / (kappa + 1);
this->q_R_star[0] = std::pow(a_R_star / a_R, 2 / (kappa - 1)) * q_R[0];
this->q_R_star[1] = this->q_R_star[0] * -a_R_star;
this->q_R_star[2] = this->q_1[0] * this->q_R[2] / this->q_R[0];
this->q_R_star[3] = QuantityCalculator::calc_energy(this->q_R_star[0], this->q_R_star[1], this->q_R_star[2], a_R_star * a_R_star * q_R_star[0] / kappa, kappa);
}
double OsherSolomonNumericalFlux::numerical_flux_i(int component, double w_L[4], double w_R[4],
double nx, double ny)
{
double result[4];
numerical_flux(result, w_L, w_R, nx, ny);
return result[component];
}
/*
double NumericalFlux::f_x(int component, double w0, double w1, double w3, double w4)
{
if (i == 0)
return w1;
else if (i == 1)
return w1*w1/w0 + (kappa - 1.) * (w4 - (w1*w1+w3*w3)/(2*w0));
else if (i == 2)
return w1*w3/w0;
else if (i == 3)
return w1/w0 * (w4 + (kappa - 1.) * (w4 - (w1*w1+w3*w3)/(2*w0)));
throw Hermes::Exceptions::Exception("Invalid index.");
return 0.0;
}
double NumericalFlux::f_z(int component, double w0, double w1, double w3, double w4)
{
if (i == 0)
return w3;
else if (i == 1)
return w3*w1/w0;
else if (i == 2)
return w3*w3/w0 + (kappa - 1.) * (w4 - (w1*w1+w3*w3)/(2*w0));
else if (i == 3)
return w3/w0 * (w4 + (kappa - 1.) * (w4 - (w1*w1+w3*w3)/(2*w0)));
throw Hermes::Exceptions::Exception("Invalid index.");
return 0.0;
}
double NumericalFlux::A_x(int component, int j, double w0, double w1, double w3, double w4)
{
if (i == 0 && j == 0)
return 0;
else if (i == 0 && j == 1)
return 1;
else if (i == 0 && j == 2)
return 0;
else if (i == 0 && j == 3)
return 0;
else if (i == 1 && j == 0)
return -w1*w1/(w0*w0) + (kappa - 1.) * (w1*w1 + w3*w3)/(2 * w0*w0);
else if (i == 1 && j == 1)
return 2*w1/w0 - (kappa - 1.) * w1 / w0;
else if (i == 1 && j == 2)
return - (kappa - 1.) * w3 / w0;
else if (i == 1 && j == 3)
return kappa - 1.;
else if (i == 2 && j == 0)
return -w1*w3/(w0*w0);
else if (i == 2 && j == 1)
return w3/w0;
else if (i == 2 && j == 2)
return w1/w0;
else if (i == 2 && j == 3)
return 0;
else if (i == 3 && j == 0)
return -w1*w4/(w0*w0) - w1/(w0*w0) * (kappa - 1.)
* (w4 - (w1*w1+w3*w3)/(2*w0)) + w1/w0 * (kappa - 1.)
* (w1*w1+w3*w3)/(2*w0*w0);
// or equivalently:
//return w1/w0 * ((kappa - 1.) * (w1*w1+w3*w3)/(w0*w0) - ((kappa - 1.) + 1) * w4/w0);
else if (i == 3 && j == 1)
return w4/w0 + 1/w0 * (kappa - 1.)
* (w4 - (w1*w1+w3*w3)/(2*w0)) - (kappa - 1.)
* w1*w1/(w0*w0);
else if (i == 3 && j == 2)
return - (kappa - 1.) * w1*w3/(w0*w0);
else if (i == 3 && j == 3)
return w1/w0 + (kappa - 1.) * w1/w0;
printf("i=%d, j=%d;\n", i, j);
throw Hermes::Exceptions::Exception("Invalid index.");
return 0.0;
}
double NumericalFlux::A_z(int component, int j, double w0, double w1, double w3, double w4)
{
if (i == 0 && j == 0)
return 0;
else if (i == 0 && j == 1)
return 0;
else if (i == 0 && j == 2)
return 1;
else if (i == 0 && j == 3)
return 0;
else if (i == 1 && j == 0)
return -w3*w1/(w0*w0);
else if (i == 1 && j == 1)
return w3/w0;
else if (i == 1 && j == 2)
return w1/w0;
else if (i == 1 && j == 3)
return 0;
else if (i == 2 && j == 0)
return -w3*w3/(w0*w0) + (kappa - 1.) * (w1*w1 + w3*w3)/(2*w0*w0);
else if (i == 2 && j == 1)
return - (kappa - 1.) * w1 / w0;
else if (i == 2 && j == 2)
return 2*w3/w0 - (kappa - 1.) * w3 / w0;
else if (i == 2 && j == 3)
return (kappa - 1.);
else if (i == 3 && j == 0)
return -w3*w4/(w0*w0) - w3/(w0*w0) * (kappa - 1.)
* (w4 - (w1*w1+w3*w3)/(2*w0)) + w3/w0 * (kappa - 1.)
* (w1*w1+w3*w3)/(2*w0*w0);
// or equivalently:
//return w1/w0 * ((kappa - 1.) * (w1*w1+w3*w3)/(w0*w0) - ((kappa - 1.) + 1) * w4/w0);
else if (i == 3 && j == 1)
return - (kappa - 1.) * w3*w1/(w0*w0);
else if (i == 3 && j == 2)
return w4/w0 + 1/w0 * (kappa - 1.)
* (w4 - (w1*w1+w3*w3)/(2*w0)) - (kappa - 1.)
* w3*w3/(w0*w0);
else if (i == 3 && j == 3)
return w3/w0 + (kappa - 1.) * w3/w0;
throw Hermes::Exceptions::Exception("Invalid index.");
return 0.0;
}
double NumericalFlux::matrix_R(int component, int j, double w0, double w1, double w3, double w4)
{
double rho = w0;
double u = w1/w0;
double w = w3/w0;
double E = w4;
double v2 = u*u+w*w;
double p = (kappa-1)*(E - rho*v2/2);
double c = sqrt(kappa*p/rho);
if (i == 0 && j == 0)
return 1;
else if (i == 0 && j == 1)
return 1;
else if (i == 0 && j == 2)
return 1;
else if (i == 0 && j == 3)
return 1;
else if (i == 1 && j == 0)
return u-c;
else if (i == 1 && j == 1)
return u;
else if (i == 1 && j == 2)
return u;
else if (i == 1 && j == 3)
return u+c;
else if (i == 2 && j == 0)
return w;
else if (i == 2 && j == 1)
return w;
else if (i == 2 && j == 2)
return w-c;
else if (i == 2 && j == 3)
return w;
else if (i == 3 && j == 0)
return v2/2 + c*c/(kappa-1) - u*c;
else if (i == 3 && j == 1)
return v2/2;
else if (i == 3 && j == 2)
return v2/2 - w*c;
else if (i == 3 && j == 3)
return v2/2 + c*c/(kappa-1) + u*c;
printf("i=%d, j=%d;\n", i, j);
throw Hermes::Exceptions::Exception("Invalid index.");
return 0.0;
}
double NumericalFlux::matrix_R_inv(int component, int j, double w0, double w1, double w3, double w4)
{
double rho = w0;
double u = w1/w0;
double w = w3/w0;
double E = w4;
double v2 = u*u+w*w;
double p = (kappa-1)*(E - rho*v2/2);
double c = sqrt(kappa*p/rho);
double result = 0;
if (i == 0 && j == 0)
result = ((kappa-1)*v2/2 + u*c)/2;
else if (i == 0 && j == 1)
result = -(c+u*(kappa-1))/2;
else if (i == 0 && j == 2)
result = -w*(kappa-1)/2;
else if (i == 0 && j == 3)
result = (kappa-1)/2;
else if (i == 1 && j == 0)
result = c*c-c*w-(kappa-1)*v2/2;
else if (i == 1 && j == 1)
result = u*(kappa-1);
else if (i == 1 && j == 2)
result = c+w*(kappa-1);
else if (i == 1 && j == 3)
result = 1-kappa;
else if (i == 2 && j == 0)
result = w*c;
else if (i == 2 && j == 1)
result = 0;
else if (i == 2 && j == 2)
result = -c;
else if (i == 2 && j == 3)
result = 0;
else if (i == 3 && j == 0)
result = ((kappa-1)*v2/2 - u*c)/2;
else if (i == 3 && j == 1)
result = (c-u*(kappa-1))/2;
else if (i == 3 && j == 2)
result = -w*(kappa-1)/2;
else if (i == 3 && j == 3)
result = (kappa-1)/2;
else {
printf("i=%d, j=%d;\n", i, j);
throw Hermes::Exceptions::Exception("Invalid index.");
}
return result/(c*c);
}
double NumericalFlux::matrix_D_minus(int component, int j, double w0, double w1, double w3, double w4)
{
double rho = w0;
double u = w1/w0;
double w = w3/w0;
double E = w4;
double v2 = u*u+w*w;
double p = (kappa-1)*(E - rho*v2/2);
double c = sqrt(kappa*p/rho);
double u_diag = 0;
if (u < 0)
u_diag = u;
if (i == 0 && j == 0)
return u-c;
else if (i == 0 && j == 1)
return 0;
else if (i == 0 && j == 2)
return 0;
else if (i == 0 && j == 3)
return 0;
else if (i == 1 && j == 0)
return 0;
else if (i == 1 && j == 1)
return u_diag;
else if (i == 1 && j == 2)
return 0;
else if (i == 1 && j == 3)
return 0;
else if (i == 2 && j == 0)
return 0;
else if (i == 2 && j == 1)
return 0;
else if (i == 2 && j == 2)
return u_diag;
else if (i == 2 && j == 3)
return 0;
else if (i == 3 && j == 0)
return 0;
else if (i == 3 && j == 1)
return 0;
else if (i == 3 && j == 2)
return 0;
else if (i == 3 && j == 3)
return 0;
printf("i=%d, j=%d;\n", i, j);
throw Hermes::Exceptions::Exception("Invalid index.");
return 0.0;
}
// multiplies two matrices
void NumericalFlux::dot(double result[4][4], double A[4][4], double B[4][4])
{
for (int component=0; i < 4; i++)
for (int j=0; j < 4; j++) {
double sum=0;
for (int k=0; k < 4; k++)
sum += A[i][k] * B[k][j];
result[i][j] = sum;
}
}
// multiplies a matrix and a vector
void NumericalFlux::dot_vector(double result[4], double A[4][4], double B[4])
{
for (int component=0; i < 4; i++) {
double sum=0;
for (int k=0; k < 4; k++)
sum += A[i][k] * B[k];
result[i] = sum;
}
}
// XXX: this matrix should take the normals directly, e.g.
// [cos, sin]
// [-sin, cos]
// becomes
// [nx, ny]
// [-ny, nx]
void NumericalFlux::T_rot(double result[4][4], double beta)
{
for (int component=0; i < 4; i++)
for (int j=0; j < 4; j++)
result[i][j] = 0;
result[0][0] = 1;
result[1][1] = cos(beta);
result[1][2] = sin(beta);
result[2][1] = -sin(beta);
result[2][2] = cos(beta);
result[3][3] = 1;
}
void NumericalFlux::A_minus(double result[4][4], double w0, double w1, double w3, double w4)
{
double _R[4][4];
double _D_minus[4][4];
double _R_inv[4][4];
double _A_minus[4][4];
double _tmp[4][4];
for (int component=0; i < 4; i++)
for (int j=0; j < 4; j++)
_R[i][j] = matrix_R(i, j, w0, w1, w3, w4);
for (int component=0; i < 4; i++)
for (int j=0; j < 4; j++)
_D_minus[i][j] = matrix_D_minus(i, j, w0, w1, w3, w4);
for (int component=0; i < 4; i++)
for (int j=0; j < 4; j++)
_R_inv[i][j] = matrix_R_inv(i, j, w0, w1, w3, w4);
dot(_tmp, _D_minus, _R_inv);
dot(result, _R, _tmp);
}
void NumericalFlux::riemann_solver(double result[4], double w_L[4], double w_R[4])
{
//printf("w_l: %f %f %f %f\n", w_L[0], w_L[1], w_L[2], w_L[3]);
//printf("w_r: %f %f %f %f\n", w_R[0], w_R[1], w_R[2], w_R[3]);
double _tmp1[4][4];
double _tmp2[4][4];
double _tmp3[4];
double _tmp4[4];
A_minus(_tmp1, w_R[0], w_R[1], w_R[2], w_R[3]);
A_minus(_tmp2, w_L[0], w_L[1], w_L[2], w_L[3]);
dot_vector(_tmp3, _tmp1, w_r);
dot_vector(_tmp4, _tmp2, w_l);
for (int component=0; i < 4; i++) {
double _1 = f_x(i, w_L[0], w_L[1], w_L[2], w_L[3]);
double _2 = _tmp3[i];
double _3 = _tmp4[i];
result[i] = _1 + _2 - _3;
}
}
// calculates the iget_nvert()ed flux, for testing purposes
// it should return the same thing as riemann_solver(), only with minus sign
void NumericalFlux::riemann_solver_iget_nvert()(double result[4], double w_L[4], double w_R[4])
{
double m[4][4];
double _w_L[4];
double _w_R[4];
double _tmp[4];
T_rot(m, M_PI);
dot_vector(_w_l, m, w_l);
dot_vector(_w_r, m, w_r);
riemann_solver(_tmp, _w_r, _w_l);
T_rot(m, -M_PI);
dot_vector(result, m, _tmp);
}
// Calculates the numerical flux in the normal (nx, ny) by rotating into the
// local system, solving the Riemann problem and rotating back. It returns the
// state as a 4-component vector.
void NumericalFlux::numerical_flux(double result[4], double w_L[4], double w_R[4],
double nx, double ny)
{
double alpha = atan2(ny, nx);
double mat_rot[4][4];
double mat_rot_inv[4][4];
double w_l_local[4];
double w_r_local[4];
double flux_local[4];
T_rot(mat_rot, alpha);
T_rot(mat_rot_inv, -alpha);
dot_vector(w_l_local, mat_rot, w_l);
dot_vector(w_r_local, mat_rot, w_r);
riemann_solver(flux_local, w_l_local, w_r_local);
dot_vector(result, mat_rot_inv, flux_local);
}
// The same as numerical_flux, but only returns the i-th component:
double NumericalFlux::numerical_flux_i(int component, double w_L[4], double w_R[4],
double nx, double ny)
{
double result[4];
numerical_flux(result, w_l, w_r, nx, ny);
return result[i];
}
*/ | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/euler-time-loop.cpp | .cpp | 7,126 | 169 | #pragma region 4. Filters for visualization of Mach number, pressure + visualization setup.
MeshFunctionSharedPtr<double> Mach_number(new MachNumberFilter(prev_slns, KAPPA));
MeshFunctionSharedPtr<double> pressure(new PressureFilter(prev_slns, KAPPA));
ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 300));
ScalarView Mach_number_view("Mach number", new WinGeom(650, 0, 600, 300));
VectorView V_view("Velocity", new WinGeom(650, 660, 600, 300));
ScalarView eview("Error - density", new WinGeom(0, 330, 600, 300));
ScalarView eview1("Error - momentum", new WinGeom(0, 660, 600, 300));
OrderView order_view("Orders", new WinGeom(650, 330, 600, 300));
#pragma endregion
#pragma region 5. Some stabilization approaches.
WeakFormSharedPtr<double> wf_stabilization(new EulerEquationsWeakFormStabilization(prev_rho));
DiscreteProblem<double> dp_stabilization(wf_stabilization, space_stabilization);
LinearSolver<double> solver(wf, spaces);
EulerEquationsWeakFormSemiImplicit* wf_ptr = (EulerEquationsWeakFormSemiImplicit*)(wf.get());
Vector<double>* rhs_stabilization = create_vector<double>(HermesCommonApi.get_integral_param_value(matrixSolverType));
if (SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
wf_ptr->set_stabilization(prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, NU_1, NU_2);
#pragma endregion
#pragma region 6. Time stepping loop.
int iteration = 0;
for (double t = 0.0; t < TIME_INTERVAL_LENGTH; t += time_step_n)
{
// Info.
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
if (SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
{
int mesh_size = space_stabilization->get_num_dofs();
assert(mesh_size == space_stabilization->get_mesh()->get_num_active_elements());
dp_stabilization.assemble(rhs_stabilization);
if (!wf_ptr->discreteIndicator)
{
wf_ptr->set_discreteIndicator(new bool[mesh_size], mesh_size);
memset(wf_ptr->discreteIndicator, 0, mesh_size * sizeof(bool));
}
Element* e;
for_all_active_elements(e, space_stabilization->get_mesh())
{
AsmList<double> al;
space_stabilization->get_element_assembly_list(e, &al);
if (rhs_stabilization->get(al.get_dof()[0]) >= 1)
wf_ptr->discreteIndicator[e->id] = true;
}
}
// Set the current time step.
wf_ptr->set_current_time_step(time_step_n);
#pragma region *. Get the solution with optional shock capturing.
try
{
// Solve.
solver.solve();
if (!SHOCK_CAPTURING || (P_INIT == 0))
Solution<double>::vector_to_solutions(solver.get_sln_vector(), spaces, prev_slns);
else
{
if (SHOCK_CAPTURING_TYPE == KRIVODONOVA)
{
FluxLimiter* flux_limiter = new FluxLimiter(FluxLimiter::Krivodonova, solver.get_sln_vector(), spaces);
flux_limiter->limit_according_to_detector();
flux_limiter->get_limited_solutions(prev_slns);
delete flux_limiter;
}
if (SHOCK_CAPTURING_TYPE == KUZMIN && P_INIT > 0)
{
if (P_INIT != 1)
throw new Hermes::Exceptions::Exception("P_INIT must be <= 1.");
// Limit conservative variables (in normal circumstances, might be enough).
PostProcessing::VertexBasedLimiter limiter(spaces, solver.get_sln_vector(), P_INIT);
limiter.get_solutions(prev_slns);
// The rest is limiting also the real variables (i.e. velocity, energy density)
int running_dofs = 0;
int ndof = spaces[0]->get_num_dofs();
double* density_sln_vector = limiter.get_solution_vector();
Element* e;
AsmList<double> al_density;
// We do not limit density anymore, it has been limited as a conservative variable already.
for (int component = 1; component < 4; component++)
{
if (spaces[component]->get_num_dofs() != ndof)
throw Exceptions::Exception("Euler code is supposed to be executed on a single mesh.");
double* conservative_vector = limiter.get_solution_vector() + component * ndof;
double* real_vector = new double[ndof];
memset(real_vector, 0, sizeof(double) * ndof);
// Now we put together the vector of real variables
for_all_active_elements(e, spaces[0]->get_mesh())
{
spaces[0]->get_element_assembly_list(e, &al_density);
// Do not get confused by the fact that we use density AsmList for indexing, it is just a technicality, the following three lines calculate the three coordinates for the actual component.
real_vector[al_density.dof[0]] = conservative_vector[al_density.dof[0]] / density_sln_vector[al_density.dof[0]];
real_vector[al_density.dof[1]] = (conservative_vector[al_density.dof[1]] - real_vector[al_density.dof[0]] * density_sln_vector[al_density.dof[1]]) / density_sln_vector[al_density.dof[0]];
real_vector[al_density.dof[2]] = (conservative_vector[al_density.dof[2]] - real_vector[al_density.dof[0]] * density_sln_vector[al_density.dof[2]]) / density_sln_vector[al_density.dof[0]];
}
// Now we normally limit this particular component.
PostProcessing::VertexBasedLimiter real_component_limiter(spaces[0], real_vector, P_INIT);
real_component_limiter.get_solution();
real_vector = real_component_limiter.get_solution_vector();
// And now we just calculate back the conservative variables.
for_all_active_elements(e, spaces[0]->get_mesh())
{
spaces[0]->get_element_assembly_list(e, &al_density);
conservative_vector[al_density.dof[1]] = density_sln_vector[al_density.dof[0]] * real_vector[al_density.dof[1]]
+ density_sln_vector[al_density.dof[1]] * real_vector[al_density.dof[0]];
conservative_vector[al_density.dof[2]] = density_sln_vector[al_density.dof[0]] * real_vector[al_density.dof[2]]
+ density_sln_vector[al_density.dof[2]] * real_vector[al_density.dof[0]];
}
Solution<double>::vector_to_solution(conservative_vector, spaces[0], prev_slns[component]);
}
}
}
CFL.calculate(prev_slns, mesh, time_step_n);
}
catch (std::exception& e) { std::cout << e.what(); }
#pragma endregion
#pragma region *. Visualization
if ((iteration - 1) % EVERY_NTH_STEP == 0)
{
// Hermes visualization.
if (HERMES_VISUALIZATION)
{
Mach_number->reinit();
pressure->reinit();
pressure_view.show(prev_rho, 1);
Mach_number_view.show(Mach_number, 1);
// order_view.show(space_rho);
V_view.show(prev_rho_v_x, prev_rho_v_y, 1, 1);
}
// Output solution in VTK format.
if (VTK_VISUALIZATION)
{
pressure->reinit();
Linearizer lin(FileExport);
char filename[40];
sprintf(filename, "Pressure-%i.vtk", iteration - 1);
lin.save_solution_vtk(pressure, filename, "Pressure", false);
sprintf(filename, "VelocityX-%i.vtk", iteration - 1);
lin.save_solution_vtk(prev_rho_v_x, filename, "VelocityX", false);
sprintf(filename, "VelocityY-%i.vtk", iteration - 1);
lin.save_solution_vtk(prev_rho_v_y, filename, "VelocityY", false);
sprintf(filename, "Rho-%i.vtk", iteration - 1);
lin.save_solution_vtk(prev_rho, filename, "Rho", false);
}
}
#pragma endregion
}
#pragma endregion
return 0;
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/euler-init-main.cpp | .cpp | 1,887 | 32 | #pragma region 1. Load mesh and initialize spaces.
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load(MESH_FILENAME, mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
mesh->refine_all_elements(0, true);
// Initialize boundary condition types and spaces with default shapesets.
SpaceSharedPtr<double> space_rho(new L2Space<double>(mesh, P_INIT, (SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == KUZMIN ? (Shapeset*)new L2ShapesetTaylor : (Shapeset*)new L2Shapeset)));
SpaceSharedPtr<double> space_rho_v_x(new L2Space<double>(mesh, P_INIT, (SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == KUZMIN ? (Shapeset*)new L2ShapesetTaylor : (Shapeset*)new L2Shapeset)));
SpaceSharedPtr<double> space_rho_v_y(new L2Space<double>(mesh, P_INIT, (SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == KUZMIN ? (Shapeset*)new L2ShapesetTaylor : (Shapeset*)new L2Shapeset)));
SpaceSharedPtr<double> space_e(new L2Space<double>(mesh, P_INIT, (SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == KUZMIN ? (Shapeset*)new L2ShapesetTaylor : (Shapeset*)new L2Shapeset)));
SpaceSharedPtr<double> space_stabilization(new L2Space<double>(mesh, 0));
std::vector<SpaceSharedPtr<double> > spaces({ space_rho, space_rho_v_x, space_rho_v_y, space_e });
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
#pragma endregion
#pragma region 2. Initialize solutions.
MeshFunctionSharedPtr<double> sln_rho(new Solution<double>(mesh));
MeshFunctionSharedPtr<double> sln_rho_v_x(new Solution<double>(mesh));
MeshFunctionSharedPtr<double> sln_rho_v_y(new Solution<double>(mesh));
MeshFunctionSharedPtr<double> sln_e(new Solution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > slns({ sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e });
// Set up CFL calculation class.
CFLCalculation CFL(CFL_NUMBER, KAPPA);
#pragma endregion
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/coupling.h | .h | 1,184 | 42 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
enum VelocityComponent
{
velX = 1,
velY = 2
};
class CouplingErrorFormVelocity : public MatrixFormVol<double>
{
public:
CouplingErrorFormVelocity(VelocityComponent component, double c_p);
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *sln_i, Func<double> *sln_j, Geom<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *sln_i, Func<Ord> *sln_j, Geom<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
VelocityComponent component;
double c_p;
};
class CouplingErrorFormTemperature : public MatrixFormVol<double>
{
public:
CouplingErrorFormTemperature(VelocityComponent component, double c_p);
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *sln_i, Func<double> *sln_j, Geom<double> *e, Func<double>* *ext) const;
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *sln_i, Func<Ord> *sln_j, Geom<Ord> *e, Func<Ord>* *ext) const;
MatrixFormVol<double>* clone() const;
VelocityComponent component;
double c_p;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/euler/euler_util.h | .h | 15,487 | 459 | #ifndef EULER_UTIL_H
#define EULER_UTIL_H
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
// Class calculating various quantities
class QuantityCalculator
{
public:
// Calculates energy from other quantities.
static double calc_energy(double rho, double rho_v_x, double rho_v_y, double pressure, double kappa);
// Calculates pressure from other quantities.
static double calc_pressure(double rho, double rho_v_x, double rho_v_y, double energy, double kappa);
// Calculates speed of sound.
static double calc_sound_speed(double rho, double rho_v_x, double rho_v_y, double energy, double kappa);
};
class CFLCalculation
{
public:
CFLCalculation(double CFL_number, double kappa);
// If the time step is necessary to decrease / possible to increase, the value time_step will be rewritten.
void calculate(std::vector<MeshFunctionSharedPtr<double> > solutions, MeshSharedPtr mesh, double & time_step) const;
void calculate_semi_implicit(std::vector<MeshFunctionSharedPtr<double> > solutions, MeshSharedPtr mesh, double & time_step) const;
void set_number(double new_CFL_number);
protected:
double CFL_number;
double kappa;
};
class ADEStabilityCalculation
{
public:
ADEStabilityCalculation(double AdvectionRelativeConstant, double DiffusionRelativeConstant, double epsilon);
// If the time step is necessary to decrease / possible to increase, the value time_step will be rewritten.
void calculate(std::vector<MeshFunctionSharedPtr<double> > solutions, MeshSharedPtr mesh, double & time_step);
protected:
double AdvectionRelativeConstant;
double DiffusionRelativeConstant;
double epsilon;
};
class DiscontinuityDetector
{
public:
/// Constructor.
DiscontinuityDetector(std::vector<SpaceSharedPtr<double> > spaces,
std::vector<MeshFunctionSharedPtr<double> > solutions);
/// Destructor.
~DiscontinuityDetector();
/// Return a reference to the inner structures.
virtual std::set<int>& get_discontinuous_element_ids() = 0;
std::set<std::pair<int, double> >& get_oscillatory_element_idsRho() { return this->oscillatory_element_idsRho; }
std::set<std::pair<int, double> >& get_oscillatory_element_idsRhoVX() { return this->oscillatory_element_idsRhoVX; }
std::set<std::pair<int, double> >& get_oscillatory_element_idsRhoVY() { return this->oscillatory_element_idsRhoVY; }
std::set<std::pair<int, double> >& get_oscillatory_element_idsRhoE() { return this->oscillatory_element_idsRhoE; }
protected:
/// Members.
std::vector<SpaceSharedPtr<double> > spaces;
std::vector<MeshFunctionSharedPtr<double> > solutions;
std::vector<Solution<double>*> solutionsInternal;
std::set<int> discontinuous_element_ids;
std::set<std::pair<int, double> > oscillatory_element_idsRho;
std::set<std::pair<int, double> > oscillatory_element_idsRhoVX;
std::set<std::pair<int, double> > oscillatory_element_idsRhoVY;
std::set<std::pair<int, double> > oscillatory_element_idsRhoE;
MeshSharedPtr mesh;
};
class KrivodonovaDiscontinuityDetector : public DiscontinuityDetector
{
public:
/// Constructor.
KrivodonovaDiscontinuityDetector(std::vector<SpaceSharedPtr<double> > spaces,
std::vector<MeshFunctionSharedPtr<double> > solutions);
/// Destructor.
~KrivodonovaDiscontinuityDetector();
/// Return a reference to the inner structures.
std::set<int>& get_discontinuous_element_ids();
std::set<int>& get_discontinuous_element_ids(double threshold);
protected:
/// Calculates relative (w.r.t. the boundary edge_i of the Element e).
double calculate_relative_flow_direction(Element* e, int edge_i);
/// Calculates jumps of all solution components across the edge edge_i of the Element e.
void calculate_jumps(Element* e, int edge_i, double result[4]);
/// Calculates h.
double calculate_h(Element* e, int polynomial_order);
/// Calculates the norm of the solution on the central element.
void calculate_norms(Element* e, int edge_i, double result[4]);
};
class KuzminDiscontinuityDetector : public DiscontinuityDetector
{
public:
/// Constructor.
KuzminDiscontinuityDetector(std::vector<SpaceSharedPtr<double> > spaces,
std::vector<MeshFunctionSharedPtr<double> > solutions, bool limit_all_orders_independently = false);
/// Destructor.
~KuzminDiscontinuityDetector();
/// Return a reference to the inner structures.
std::set<int>& get_discontinuous_element_ids();
/// Return a reference to the inner structures.
std::set<int>& get_second_order_discontinuous_element_ids();
/// Returns info about the method.
bool get_limit_all_orders_independently();
protected:
/// Center.
void find_centroid_values(Hermes::Hermes2D::Element* e, double u_c[4], double x_ref, double y_ref);
void find_centroid_derivatives(Hermes::Hermes2D::Element* e, double u_dx_c[4], double u_dy_c[4], double x_ref, double y_ref);
void find_second_centroid_derivatives(Hermes::Hermes2D::Element* e, double u_dxx_c[4], double u_dxy_c[4], double u_dyy_c[4]);
/// Vertices.
void find_vertex_values(Hermes::Hermes2D::Element* e, double vertex_values[4][4]);
void find_vertex_derivatives(Hermes::Hermes2D::Element* e, double vertex_derivatives[4][4][2]);
/// Logic - 1st order.
void find_u_i_min_max_first_order(Hermes::Hermes2D::Element* e, double u_i_min[4][4], double u_i_max[4][4]);
void find_alpha_i_first_order(double u_i_min[4][4], double u_i_max[4][4], double u_c[4], double u_i[4][4], double alpha_i[4]);
void find_alpha_i_first_order_real(Hermes::Hermes2D::Element* e, double u_i[4][4], double u_c[4], double u_dx_c[4], double u_dy_c[4], double alpha_i_real[4]);
/// Logic - 2nd order.
void find_u_i_min_max_second_order(Hermes::Hermes2D::Element* e, double u_d_i_min[4][4][2], double u_d_i_max[4][4][2]);
void find_alpha_i_second_order(double u_d_i_min[4][4][2], double u_d_i_max[4][4][2], double*** u_dx_c, double*** u_dy_c, double u_d_i[4][4][2], double alpha_i[4]);
void find_alpha_i_second_order_real(Hermes::Hermes2D::Element* e, double u_i[4][4][2], double u_dx_c[4], double u_dy_c[4], double u_dxx_c[4], double u_dxy_c[4], double u_dyy_c[4], double alpha_i_real[4]);
private:
/// For limiting of second order terms.
std::set<int> second_order_discontinuous_element_ids;
bool limit_all_orders_independently;
};
class FluxLimiter
{
public:
/// Enumeration of types.
/// Used to pick the proper DiscontinuityDetector.
enum LimitingType
{
Krivodonova,
Kuzmin
};
/// Constructor.
FluxLimiter(LimitingType type, double* solution_vector, std::vector<SpaceSharedPtr<double> > spaces, bool Kuzmin_limit_all_orders_independently = false);
FluxLimiter(FluxLimiter::LimitingType type, std::vector<MeshFunctionSharedPtr<double> > solutions, std::vector<SpaceSharedPtr<double> > spaces, bool Kuzmin_limit_all_orders_independently = false);
/// Destructor.
~FluxLimiter();
/// Do the limiting.
/// With the possibility to also limit the spaces from which the spaces in the constructors are refined.
virtual int limit_according_to_detector(std::vector<SpaceSharedPtr<double> > coarse_spaces_to_limit = std::vector<SpaceSharedPtr<double> >());
/// For Kuzmin's detector.
virtual void limit_second_orders_according_to_detector(std::vector<SpaceSharedPtr<double> > coarse_spaces_to_limit = std::vector<SpaceSharedPtr<double> >());
void get_limited_solutions(std::vector<MeshFunctionSharedPtr<double> > solutions_to_limit);
bool limitOscillations;
protected:
/// Members.
double* solution_vector;
std::vector<SpaceSharedPtr<double> > spaces;
DiscontinuityDetector* detector;
std::vector<MeshFunctionSharedPtr<double> > limited_solutions;
};
// Filters.
class MachNumberFilter : public Hermes::Hermes2D::SimpleFilter<double>
{
public:
MachNumberFilter(std::vector<MeshFunctionSharedPtr<double> > solutions, double kappa) : SimpleFilter<double>(solutions), kappa(kappa) {};
~MachNumberFilter()
{
};
MeshFunction<double>* clone() const
{
std::vector<MeshFunctionSharedPtr<double> > slns;
for (int i = 0; i < this->solutions.size(); i++)
slns.push_back(this->solutions[i]->clone());
MachNumberFilter* filter = new MachNumberFilter(slns, this->kappa);
return filter;
}
protected:
virtual void filter_fn(int n, const std::vector<const double*>& values, double* result);
double kappa;
};
class PressureFilter : public Hermes::Hermes2D::SimpleFilter<double>
{
public:
PressureFilter(std::vector<MeshFunctionSharedPtr<double> > solutions, double kappa) : SimpleFilter<double>(solutions), kappa(kappa) {};
~PressureFilter()
{
};
MeshFunction<double>* clone() const
{
std::vector<MeshFunctionSharedPtr<double> > slns;
for (int i = 0; i < this->solutions.size(); i++)
slns.push_back(this->solutions[i]->clone());
PressureFilter* filter = new PressureFilter(slns, this->kappa);
return filter;
}
protected:
virtual void filter_fn(int n, const std::vector<const double*>& values, double* result);
double kappa;
};
class VelocityFilter : public Hermes::Hermes2D::SimpleFilter<double>
{
public:
// Vector of solutions: 0-th position - density, 1-st position - velocity component.
VelocityFilter(std::vector<MeshFunctionSharedPtr<double> > solutions) : SimpleFilter<double>(solutions) {};
~VelocityFilter()
{
};
MeshFunction<double>* clone() const
{
std::vector<MeshFunctionSharedPtr<double> > slns;
for (int i = 0; i < this->solutions.size(); i++)
slns.push_back(this->solutions[i]->clone());
VelocityFilter* filter = new VelocityFilter(slns);
return filter;
}
protected:
virtual void filter_fn(int n, const std::vector<const double*>& values, double* result);
};
class EntropyFilter : public Hermes::Hermes2D::SimpleFilter<double>
{
public:
EntropyFilter(std::vector<MeshFunctionSharedPtr<double> > solutions, double kappa, double rho_ext, double p_ext) : SimpleFilter<double>(solutions), kappa(kappa), rho_ext(rho_ext), p_ext(p_ext) {};
~EntropyFilter()
{
};
MeshFunction<double>* clone() const
{
std::vector<MeshFunctionSharedPtr<double> > slns;
for (int i = 0; i < this->solutions.size(); i++)
slns.push_back(this->solutions[i]->clone());
EntropyFilter* filter = new EntropyFilter(slns, this->kappa, rho_ext, p_ext);
return filter;
}
protected:
virtual void filter_fn(int n, const std::vector<const double*>& values, double* result);
double kappa, rho_ext, p_ext;
};
class EulerFluxes
{
public:
EulerFluxes(double kappa) : kappa(kappa) {}
double A_1_0_0(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(0.0);
}
double A_1_0_1(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(1.0);
}
double A_1_0_2(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(0.0);
}
double A_1_0_3(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(0.0);
}
double A_2_0_0(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(0.0);
}
double A_2_0_1(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(0.0);
}
double A_2_0_2(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(1.0);
}
double A_2_0_3(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(0.0);
}
double A_1_1_0(double rho, double rho_v_x, double rho_v_y, double energy) {
return double(- ((rho_v_x * rho_v_x) / (rho * rho)) + 0.5 * (kappa - 1.0) *
((rho_v_x * rho_v_x + rho_v_y * rho_v_y) / (rho * rho)));
}
double A_1_1_1(double rho, double rho_v_x, double rho_v_y, double energy){
return double((3. - kappa) * (rho_v_x / rho));
}
double A_1_1_2(double rho, double rho_v_x, double rho_v_y, double energy){
return double((1.0 - kappa) * (rho_v_y / rho));
}
double A_1_1_3(double rho, double rho_v_x, double rho_v_y, double energy){
return double(kappa - 1.);
}
double A_2_1_0(double rho, double rho_v_x, double rho_v_y, double energy){
return double(- rho_v_x * rho_v_y / (rho * rho));
}
double A_2_1_1(double rho, double rho_v_x, double rho_v_y, double energy){
return double(rho_v_y / rho);
}
double A_2_1_2(double rho, double rho_v_x, double rho_v_y, double energy){
return double(rho_v_x / rho);
}
double A_2_1_3(double rho, double rho_v_x, double rho_v_y, double energy){
return double(0);
}
double A_1_2_0(double rho, double rho_v_x, double rho_v_y, double energy){
return double(- rho_v_x * rho_v_y / (rho * rho));
}
double A_1_2_1(double rho, double rho_v_x, double rho_v_y, double energy){
return double(rho_v_y / rho);
}
double A_1_2_2(double rho, double rho_v_x, double rho_v_y, double energy){
return double(rho_v_x / rho);
}
double A_1_2_3(double rho, double rho_v_x, double rho_v_y, double energy){
return double(0);
}
double A_2_2_0(double rho, double rho_v_x, double rho_v_y, double energy){
return double(- ((rho_v_y * rho_v_y) / (rho * rho)) + 0.5 * (kappa - 1.0)
* ((rho_v_x * rho_v_x + rho_v_y * rho_v_y) / (rho * rho)));
}
double A_2_2_1(double rho, double rho_v_x, double rho_v_y, double energy){
return double((1.0 - kappa) * (rho_v_x / rho));
}
double A_2_2_2(double rho, double rho_v_x, double rho_v_y, double energy){
return double((3.0 - kappa) * (rho_v_y / rho));
}
double A_2_2_3(double rho, double rho_v_x, double rho_v_y, double energy){
return double(kappa - 1.);
}
double A_1_3_0(double rho, double rho_v_x, double rho_v_y, double energy){
return double((rho_v_x / rho) * (((kappa - 1.0) * ((rho_v_x * rho_v_x + rho_v_y * rho_v_y) / (rho * rho)))
- (kappa * energy / rho)));
}
double A_1_3_1(double rho, double rho_v_x, double rho_v_y, double energy){
return double((kappa * energy / rho) - (kappa - 1.0) * rho_v_x * rho_v_x / (rho * rho)
- 0.5 * (kappa - 1.0) * (rho_v_x * rho_v_x + rho_v_y * rho_v_y) / (rho * rho));
}
double A_1_3_2(double rho, double rho_v_x, double rho_v_y, double energy){
return double((1.0 - kappa) * (rho_v_x * rho_v_y) / (rho * rho));
}
double A_1_3_3(double rho, double rho_v_x, double rho_v_y, double energy){
return double(kappa * (rho_v_x / rho));
}
double A_2_3_0(double rho, double rho_v_x, double rho_v_y, double energy){
return double(- (rho_v_y * energy) / (rho * rho) - (rho_v_y / (rho * rho)) * (kappa - 1.0)
* (energy - ((rho_v_x * rho_v_x + rho_v_y * rho_v_y) / (2 * rho))) + (rho_v_y / rho)
* (kappa - 1.0) * ((rho_v_x * rho_v_x + rho_v_y * rho_v_y) / (2 * rho * rho)));
}
double A_2_3_1(double rho, double rho_v_x, double rho_v_y, double energy){
return double((1.0 - kappa) * (rho_v_x * rho_v_y) / (rho * rho));
}
double A_2_3_2(double rho, double rho_v_x, double rho_v_y, double energy){
return double((energy / rho) + (1 / rho) * (kappa - 1.0) * ( energy - ((rho_v_x * rho_v_x
+ rho_v_y * rho_v_y) / (2 * rho))) + (1.0 - kappa) * ((rho_v_y * rho_v_y) / (rho * rho)));
}
double A_2_3_3(double rho, double rho_v_x, double rho_v_y, double energy){
return double(kappa * rho_v_y / rho);
}
protected:
double kappa;
};
#endif
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/euler/coupling.cpp | .cpp | 2,765 | 102 | #include "coupling.h"
CouplingErrorFormVelocity::CouplingErrorFormVelocity(VelocityComponent component, double c_p)
: MatrixFormVol<double>(component, 4), component(component), c_p(c_p)
{
}
double CouplingErrorFormVelocity::value(int n, double *wt, Func<double> *u_ext[], Func<double> *sln_i, Func<double> *sln_j, Geom<double> *e, Func<double>* *ext) const
{
double result = 0.;
if(component == velX)
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dx[point_i] * c_p;
}
}
else
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dy[point_i] * c_p;
}
}
return result;
}
Ord CouplingErrorFormVelocity::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *sln_i, Func<Ord> *sln_j, Geom<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
if(component == velX)
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dx[point_i] * c_p;
}
}
else
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dy[point_i] * c_p;
}
}
return result;
}
MatrixFormVol<double>* CouplingErrorFormVelocity::clone() const
{
return new CouplingErrorFormVelocity(*this);
}
CouplingErrorFormTemperature::CouplingErrorFormTemperature(VelocityComponent component, double c_p)
: MatrixFormVol<double>(4, component), component(component), c_p(c_p)
{
}
double CouplingErrorFormTemperature::value(int n, double *wt, Func<double> *u_ext[], Func<double> *sln_j, Func<double> *sln_i, Geom<double> *e, Func<double>* *ext) const
{
double result = 0.;
if(component == velX)
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dx[point_i] * c_p;
}
}
else
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dy[point_i] * c_p;
}
}
return result;
}
Ord CouplingErrorFormTemperature::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *sln_j,
Func<Ord> *sln_i, Geom<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
if(component == velX)
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dx[point_i] * c_p;
}
}
else
{
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * sln_i->val[point_i] * sln_j->dy[point_i] * c_p;
}
}
return result;
}
MatrixFormVol<double>* CouplingErrorFormTemperature::clone() const
{
return new CouplingErrorFormTemperature(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/forms_explicit.cpp | .cpp | 33,502 | 893 | #include "hermes2d.h"
// Numerical fluxes.
#include "numerical_flux.h"
// Utility functions for the Euler equations.
#include "euler_util.h"
class EulerEquationsWeakFormStabilization : public WeakForm < double >
{
public:
EulerEquationsWeakFormStabilization(MeshFunctionSharedPtr<double> prev_rho) : WeakForm<double>()
{
this->set_ext(prev_rho);
add_vector_form_DG(new DGVectorFormIndicator());
}
class DGVectorFormIndicator : public VectorFormDG < double >
{
public:
DGVectorFormIndicator()
: VectorFormDG<double>(0)
{
}
double value(int n, double *wt, DiscontinuousFunc<double> *u_ext[], Func<double> *v,
InterfaceGeom<double> *e, DiscontinuousFunc<double>** ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * v->val[i] * (ext[0]->val[i] - ext[0]->val_neighbor[i]) * (ext[0]->val[i] - ext[0]->val_neighbor[i]);
return result / (e->get_diam_approximation(n) * std::pow(e->get_area(n, wt), 0.75));
}
Ord ord(int n, double *wt, DiscontinuousFunc<Ord> *u_ext[], Func<Ord> *v, InterfaceGeom<Ord> *e,
Func<Ord>* *ext) const
{
return v->val[0] * v->val[0] * Ord(6);
}
VectorFormDG<double>* clone() const { return new DGVectorFormIndicator; }
};
};
class EulerEquationsWeakFormSemiImplicit : public WeakForm < double >
{
public:
double kappa;
bool fvm_only;
std::vector<std::string> solid_wall_markers;
std::vector<std::string> inlet_markers;
std::vector<std::string> outlet_markers;
MeshFunctionSharedPtr<double> prev_density;
MeshFunctionSharedPtr<double> prev_density_vel_x;
MeshFunctionSharedPtr<double> prev_density_vel_y;
MeshFunctionSharedPtr<double> prev_energy;
// External state.
std::vector<double> rho_ext;
std::vector<double> v1_ext;
std::vector<double> v2_ext;
std::vector<double> pressure_ext;
std::vector<double> energy_ext;
// Fluxes for calculation.
EulerFluxes* euler_fluxes;
// Discrete indicator in the case of Feistauer limiting.
bool* discreteIndicator;
int discreteIndicatorSize;
// For cache handling.
class EulerEquationsMatrixFormSurfSemiImplicit;
class EulerEquationsMatrixFormSemiImplicitInletOutlet;
bool cacheReadyDG;
bool cacheReadySurf;
double** P_plus_cache_DG;
double** P_minus_cache_DG;
double** P_plus_cache_surf;
double** P_minus_cache_surf;
EulerEquationsWeakFormSemiImplicit(double kappa,
std::vector<double> rho_ext, std::vector<double> v1_ext, std::vector<double> v2_ext, std::vector<double> pressure_ext,
std::vector<std::string> solid_wall_markers, std::vector<std::string> inlet_markers, std::vector<std::string> outlet_markers,
MeshFunctionSharedPtr<double> prev_density, MeshFunctionSharedPtr<double> prev_density_vel_x, MeshFunctionSharedPtr<double> prev_density_vel_y, MeshFunctionSharedPtr<double> prev_energy,
bool fvm_only = false, int num_of_equations = 4) :
WeakForm<double>(num_of_equations),
kappa(kappa), rho_ext(rho_ext), v1_ext(v1_ext), v2_ext(v2_ext), pressure_ext(pressure_ext),
solid_wall_markers(solid_wall_markers), inlet_markers(inlet_markers), outlet_markers(outlet_markers),
prev_density(prev_density), prev_density_vel_x(prev_density_vel_x), prev_density_vel_y(prev_density_vel_y), prev_energy(prev_energy),
fvm_only(fvm_only),
euler_fluxes(new EulerFluxes(kappa)), discreteIndicator(NULL)
{
for (unsigned int inlet_i = 0; inlet_i < inlet_markers.size(); inlet_i++)
energy_ext.push_back(QuantityCalculator::calc_energy(rho_ext[inlet_i], rho_ext[inlet_i] * v1_ext[inlet_i], rho_ext[inlet_i] * v2_ext[inlet_i], pressure_ext[inlet_i], kappa));
P_plus_cache_DG = new double*[13];
P_minus_cache_DG = new double*[13];
P_plus_cache_surf = new double*[13];
P_minus_cache_surf = new double*[13];
for (int coordinate_i = 0; coordinate_i < 13; coordinate_i++)
{
P_plus_cache_DG[coordinate_i] = new double[16];
P_minus_cache_DG[coordinate_i] = new double[16];
P_plus_cache_surf[coordinate_i] = new double[16];
P_minus_cache_surf[coordinate_i] = new double[16];
}
for (int form_i = 0; form_i < 4; form_i++)
{
add_matrix_form(new EulerEquationsBilinearFormTime(form_i));
add_vector_form(new EulerEquationsLinearFormTime(form_i));
for (unsigned int inlet_i = 0; inlet_i < inlet_markers.size(); inlet_i++)
add_vector_form_surf(new EulerEquationsVectorFormSemiImplicitInletOutlet(form_i, rho_ext[inlet_i], v1_ext[inlet_i], v2_ext[inlet_i], energy_ext[inlet_i], inlet_markers[inlet_i], kappa));
for (unsigned int outlet_i = 0; outlet_i < outlet_markers.size(); outlet_i++)
{
// If we specified ext values also for outlets.
if(rho_ext.size() >= outlet_markers.size() + inlet_markers.size())
add_vector_form_surf(new EulerEquationsVectorFormSemiImplicitInletOutlet(form_i, rho_ext[outlet_i + inlet_markers.size()], v1_ext[outlet_i + inlet_markers.size()], v2_ext[outlet_i + inlet_markers.size()], energy_ext[outlet_i + inlet_markers.size()], outlet_markers[outlet_i], kappa));
// Otherwise take the first ext value.
else
add_vector_form_surf(new EulerEquationsVectorFormSemiImplicitInletOutlet(form_i, rho_ext[0], v1_ext[0], v2_ext[0], energy_ext[0], outlet_markers[outlet_i], kappa));
}
for (int form_j = 0; form_j < 4; form_j++)
{
if (!fvm_only)
add_matrix_form(new EulerEquationsBilinearForm(form_i, form_j, euler_fluxes));
add_matrix_form_DG(new EulerEquationsMatrixFormSurfSemiImplicit(form_i, form_j, kappa, euler_fluxes, &this->cacheReadyDG, this->P_plus_cache_DG, this->P_minus_cache_DG));
for (unsigned int inlet_i = 0; inlet_i < inlet_markers.size(); inlet_i++)
{
add_matrix_form_surf(new EulerEquationsMatrixFormSemiImplicitInletOutlet(form_i, form_j, rho_ext[inlet_i], v1_ext[inlet_i], v2_ext[inlet_i], energy_ext[inlet_i], inlet_markers[inlet_i], kappa, &this->cacheReadySurf, this->P_plus_cache_surf, this->P_minus_cache_surf));
}
for (unsigned int outlet_i = 0; outlet_i < outlet_markers.size(); outlet_i++)
{
// If we specified ext values also for outlets.
if (rho_ext.size() >= outlet_markers.size() + inlet_markers.size())
add_matrix_form_surf(new EulerEquationsMatrixFormSemiImplicitInletOutlet(form_i, form_j, rho_ext[outlet_i + inlet_markers.size()], v1_ext[outlet_i + inlet_markers.size()], v2_ext[outlet_i + inlet_markers.size()], energy_ext[outlet_i + inlet_markers.size()], outlet_markers[outlet_i], kappa, &this->cacheReadySurf, this->P_plus_cache_surf, this->P_minus_cache_surf));
// Otherwise take the first ext value.
else
add_matrix_form_surf(new EulerEquationsMatrixFormSemiImplicitInletOutlet(form_i, form_j, rho_ext[0], v1_ext[0], v2_ext[0], energy_ext[0], outlet_markers[outlet_i], kappa, &this->cacheReadySurf, this->P_plus_cache_surf, this->P_minus_cache_surf));
}
add_matrix_form_surf(new EulerEquationsMatrixFormSolidWall(form_i, form_j, solid_wall_markers, kappa));
}
}
this->set_ext({ prev_density, prev_density_vel_x, prev_density_vel_y, prev_energy });
};
virtual ~EulerEquationsWeakFormSemiImplicit()
{
delete this->euler_fluxes;
for (int coordinate_i = 0; coordinate_i < 13; coordinate_i++)
{
delete[] P_plus_cache_DG[coordinate_i];
delete[] P_minus_cache_DG[coordinate_i];
delete[] P_plus_cache_surf[coordinate_i];
delete[] P_minus_cache_surf[coordinate_i];
}
delete[] P_plus_cache_DG;
delete[] P_minus_cache_DG;
delete[] P_plus_cache_surf;
delete[] P_minus_cache_surf;
}
void set_active_edge_state(Element** e, unsigned char isurf)
{
this->cacheReadySurf = false;
}
void set_active_DG_state(Element** e, unsigned char isurf)
{
this->cacheReadyDG = false;
}
WeakForm<double>* clone() const
{
EulerEquationsWeakFormSemiImplicit* wf = new EulerEquationsWeakFormSemiImplicit(this->kappa, this->rho_ext, this->v1_ext, this->v2_ext, this->pressure_ext,
this->solid_wall_markers, this->inlet_markers, this->outlet_markers, this->prev_density, this->prev_density_vel_x, this->prev_density_vel_y, this->prev_energy, this->fvm_only, this->neq);
wf->ext.clear();
for (unsigned int i = 0; i < this->ext.size(); i++)
{
MeshFunctionSharedPtr<double> ext = this->ext[i]->clone();
if (dynamic_cast<Solution<double>*>(this->ext[i].get()))
{
if ((dynamic_cast<Solution<double>*>(this->ext[i].get()))->get_type() == HERMES_SLN)
dynamic_cast<Solution<double>*>(ext.get())->set_type(HERMES_SLN);
}
wf->ext.push_back(ext);
}
wf->set_current_time_step(this->get_current_time_step());
return wf;
}
void cloneMembers(const WeakFormSharedPtr<double>& otherWf)
{
}
void set_stabilization(MeshFunctionSharedPtr<double> prev_density, MeshFunctionSharedPtr<double> prev_density_vel_x, MeshFunctionSharedPtr<double> prev_density_vel_y, MeshFunctionSharedPtr<double> prev_energy, double nu_1, double nu_2)
{
int mfvol_size = this->mfvol.size();
int mfsurf_size = this->mfsurf.size();
add_matrix_form(new EulerEquationsFormStabilizationVol(0, nu_1));
add_matrix_form(new EulerEquationsFormStabilizationVol(1, nu_1));
add_matrix_form(new EulerEquationsFormStabilizationVol(2, nu_1));
add_matrix_form(new EulerEquationsFormStabilizationVol(3, nu_1));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(0, 0, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(0, 1, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(0, 2, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(0, 3, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(1, 0, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(1, 1, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(1, 2, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(1, 3, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(2, 0, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(2, 1, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(2, 2, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(2, 3, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(3, 0, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(3, 1, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(3, 2, nu_2));
add_matrix_form_DG(new EulerEquationsFormStabilizationSurf(3, 3, nu_2));
for (unsigned int matrix_form_i = mfvol_size; matrix_form_i < this->mfvol.size(); matrix_form_i++)
{
mfvol.at(matrix_form_i)->set_ext({ prev_density, prev_density_vel_x, prev_density_vel_y, prev_energy });
}
for (unsigned int matrix_form_i = mfsurf_size; matrix_form_i < this->mfsurf.size(); matrix_form_i++)
{
mfsurf.at(matrix_form_i)->set_ext({ prev_density, prev_density_vel_x, prev_density_vel_y, prev_energy });
}
}
void set_discreteIndicator(bool* discreteIndicator, int size)
{
this->discreteIndicator = discreteIndicator;
this->discreteIndicatorSize = size;
}
class EulerEquationsBilinearFormTime : public MatrixFormVol < double >
{
public:
EulerEquationsBilinearFormTime(int i) : MatrixFormVol<double>(i, i) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
return int_u_v<double, double>(n, wt, u, v);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return int_u_v<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* clone() const { return new EulerEquationsBilinearFormTime(this->i); }
};
class EulerEquationsBilinearForm : public MatrixFormVol < double >
{
public:
EulerEquationsBilinearForm(unsigned int i, unsigned int j, EulerFluxes* fluxes)
: MatrixFormVol<double>(i, j), fluxes(fluxes) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0.;
for (int point_i = 0; point_i < n; point_i++)
{
double rho = ext[0]->val[point_i];
double rho_v_x = ext[1]->val[point_i];
double rho_v_y = ext[2]->val[point_i];
double rho_e = ext[3]->val[point_i];
switch (i)
{
case 0:
switch (j)
{
case 0:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_0_0(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_0_0(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 1:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_0_1(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_0_1(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 2:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_0_2(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_0_2(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 3:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_0_3(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_0_3(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
}
break;
case 1:
switch (j)
{
case 0:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_1_0(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_1_0(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 1:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_1_1(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_1_1(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 2:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_1_2(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_1_2(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 3:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_1_3(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_1_3(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
}
break;
case 2:
switch (j)
{
case 0:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_2_0(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_2_0(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 1:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_2_1(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_2_1(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 2:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_2_2(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_2_2(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
case 3:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_2_3(rho, rho_v_x, rho_v_y, 0) * v->dx[point_i] + fluxes->A_2_2_3(rho, rho_v_x, rho_v_y, 0) * v->dy[point_i]);
break;
}
break;
case 3:
switch (j)
{
case 0:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_3_0(rho, rho_v_x, rho_v_y, rho_e) * v->dx[point_i] + fluxes->A_2_3_0(rho, rho_v_x, rho_v_y, rho_e) * v->dy[point_i]);
break;
case 1:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_3_1(rho, rho_v_x, rho_v_y, rho_e) * v->dx[point_i] + fluxes->A_2_3_1(rho, rho_v_x, rho_v_y, rho_e) * v->dy[point_i]);
break;
case 2:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_3_2(rho, rho_v_x, rho_v_y, rho_e) * v->dx[point_i] + fluxes->A_2_3_2(rho, rho_v_x, rho_v_y, rho_e) * v->dy[point_i]);
break;
case 3:
result += wt[point_i] * u->val[point_i] * (fluxes->A_1_3_3(rho, rho_v_x, rho_v_y, rho_e) * v->dx[point_i] + fluxes->A_2_3_3(rho, rho_v_x, rho_v_y, rho_e) * v->dy[point_i]);
break;
}
}
}
return -result * wf->get_current_time_step();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
MatrixFormVol<double>* clone() const
{
return new EulerEquationsBilinearForm(this->i, this->j, this->fluxes);
}
EulerFluxes* fluxes;
};
class EulerEquationsMatrixFormSurfSemiImplicit : public MatrixFormDG < double >
{
public:
EulerEquationsMatrixFormSurfSemiImplicit(unsigned int i, unsigned int j, double kappa, EulerFluxes* fluxes, bool* cacheReady, double** P_plus_cache, double** P_minus_cache)
: MatrixFormDG<double>(i, j), num_flux(new StegerWarmingNumericalFlux(kappa)), cacheReady(cacheReady), P_plus_cache(P_plus_cache), P_minus_cache(P_minus_cache), fluxes(fluxes)
{
}
virtual ~EulerEquationsMatrixFormSurfSemiImplicit()
{
delete num_flux;
}
double value(int n, double *wt, DiscontinuousFunc<double> **u_ext, DiscontinuousFunc<double> *u,
DiscontinuousFunc<double> *v, InterfaceGeom<double> *e, DiscontinuousFunc<double>* *ext) const
{
double w[4];
double result = 0.;
if (!(*this->cacheReady))
{
for (int point_i = 0; point_i < n; point_i++)
{
{
w[0] = ext[0]->val[point_i];
w[1] = ext[1]->val[point_i];
w[2] = ext[2]->val[point_i];
w[3] = ext[3]->val[point_i];
double e_1_1[4] = { 1, 0, 0, 0 };
double e_2_1[4] = { 0, 1, 0, 0 };
double e_3_1[4] = { 0, 0, 1, 0 };
double e_4_1[4] = { 0, 0, 0, 1 };
num_flux->P_plus(this->P_plus_cache[point_i], w, e_1_1, e->nx[point_i], e->ny[point_i]);
num_flux->P_plus(this->P_plus_cache[point_i] + 4, w, e_2_1, e->nx[point_i], e->ny[point_i]);
num_flux->P_plus(this->P_plus_cache[point_i] + 8, w, e_3_1, e->nx[point_i], e->ny[point_i]);
num_flux->P_plus(this->P_plus_cache[point_i] + 12, w, e_4_1, e->nx[point_i], e->ny[point_i]);
w[0] = ext[0]->val_neighbor[point_i];
w[1] = ext[1]->val_neighbor[point_i];
w[2] = ext[2]->val_neighbor[point_i];
w[3] = ext[3]->val_neighbor[point_i];
double e_1_2[4] = { 1, 0, 0, 0 };
double e_2_2[4] = { 0, 1, 0, 0 };
double e_3_2[4] = { 0, 0, 1, 0 };
double e_4_2[4] = { 0, 0, 0, 1 };
num_flux->P_minus(this->P_minus_cache[point_i], w, e_1_2, e->nx[point_i], e->ny[point_i]);
num_flux->P_minus(this->P_minus_cache[point_i] + 4, w, e_2_2, e->nx[point_i], e->ny[point_i]);
num_flux->P_minus(this->P_minus_cache[point_i] + 8, w, e_3_2, e->nx[point_i], e->ny[point_i]);
num_flux->P_minus(this->P_minus_cache[point_i] + 12, w, e_4_2, e->nx[point_i], e->ny[point_i]);
}
}
*(const_cast<EulerEquationsMatrixFormSurfSemiImplicit*>(this))->cacheReady = true;
}
int index = j * 4 + i;
if (u->val == NULL)
if (v->val == NULL)
for (int point_i = 0; point_i < n; point_i++)
result -= wt[point_i] * (this->P_minus_cache[point_i][index] * u->val_neighbor[point_i]) * v->val_neighbor[point_i];
else
for (int point_i = 0; point_i < n; point_i++)
result += wt[point_i] * (this->P_minus_cache[point_i][index] * u->val_neighbor[point_i]) * v->val[point_i];
else
if (v->val == NULL)
for (int point_i = 0; point_i < n; point_i++)
result -= wt[point_i] * (this->P_plus_cache[point_i][index] * u->val[point_i]) * v->val_neighbor[point_i];
else
for (int point_i = 0; point_i < n; point_i++)
result += wt[point_i] * (this->P_plus_cache[point_i][index] * u->val[point_i]) * v->val[point_i];
return result * wf->get_current_time_step();
}
MatrixFormDG<double>* clone() const
{
EulerEquationsMatrixFormSurfSemiImplicit* form = new EulerEquationsMatrixFormSurfSemiImplicit(this->i, this->j, this->num_flux->kappa, this->fluxes, this->cacheReady, this->P_plus_cache, this->P_minus_cache);
form->wf = this->wf;
return form;
}
bool* cacheReady;
double** P_plus_cache;
double** P_minus_cache;
StegerWarmingNumericalFlux* num_flux;
EulerFluxes* fluxes;
};
class EulerEquationsMatrixFormSemiImplicitInletOutlet : public MatrixFormSurf < double >
{
public:
EulerEquationsMatrixFormSemiImplicitInletOutlet(unsigned int i, unsigned int j, double rho_ext, double v1_ext, double v2_ext, double energy_ext, std::string marker, double kappa, bool* cacheReady, double** P_plus_cache, double** P_minus_cache)
: MatrixFormSurf<double>(i, j), rho_ext(rho_ext), v1_ext(v1_ext), v2_ext(v2_ext), energy_ext(energy_ext), num_flux(new StegerWarmingNumericalFlux(kappa)), cacheReady(cacheReady), P_plus_cache(P_plus_cache), P_minus_cache(P_minus_cache)
{
set_area(marker);
}
EulerEquationsMatrixFormSemiImplicitInletOutlet(unsigned int i, unsigned int j, double rho_ext, double v1_ext, double v2_ext, double energy_ext, std::vector<std::string> markers, double kappa, bool* cacheReady, double** P_plus_cache, double** P_minus_cache)
: MatrixFormSurf<double>(i, j), rho_ext(rho_ext), v1_ext(v1_ext), v2_ext(v2_ext), energy_ext(energy_ext), num_flux(new StegerWarmingNumericalFlux(kappa)), cacheReady(cacheReady), P_plus_cache(P_plus_cache), P_minus_cache(P_minus_cache)
{
set_areas(markers);
}
~EulerEquationsMatrixFormSemiImplicitInletOutlet()
{
delete num_flux;
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomSurf<double> *e, Func<double>* *ext) const
{
double result = 0.;
if (!(*this->cacheReady))
{
for (int point_i = 0; point_i < n; point_i++)
{
double w_B[4], w_L[4], eigenvalues[4], alpha[4], q_ji_star[4], beta[4], q_ji[4], w_ji[4];
// Inner state.
w_L[0] = ext[0]->val[point_i];
w_L[1] = ext[1]->val[point_i];
w_L[2] = ext[2]->val[point_i];
w_L[3] = ext[3]->val[point_i];
// Transformation of the inner state to the local coordinates.
num_flux->Q(num_flux->get_q(), w_L, e->nx[point_i], e->ny[point_i]);
// Initialize the matrices.
double T[4][4];
double T_inv[4][4];
for (unsigned int ai = 0; ai < 4; ai++)
{
for (unsigned int aj = 0; aj < 4; aj++)
{
T[ai][aj] = 0.0;
T_inv[ai][aj] = 0.0;
}
alpha[ai] = 0;
beta[ai] = 0;
q_ji[ai] = 0;
w_ji[ai] = 0;
eigenvalues[ai] = 0;
}
// Calculate Lambda^-.
num_flux->Lambda(eigenvalues);
num_flux->T_1(T);
num_flux->T_2(T);
num_flux->T_3(T);
num_flux->T_4(T);
num_flux->T_inv_1(T_inv);
num_flux->T_inv_2(T_inv);
num_flux->T_inv_3(T_inv);
num_flux->T_inv_4(T_inv);
// "Prescribed" boundary state.
w_B[0] = this->rho_ext;
w_B[1] = this->rho_ext * this->v1_ext;
w_B[2] = this->rho_ext * this->v2_ext;
w_B[3] = this->energy_ext;
num_flux->Q(q_ji_star, w_B, e->nx[point_i], e->ny[point_i]);
for (unsigned int ai = 0; ai < 4; ai++)
for (unsigned int aj = 0; aj < 4; aj++)
alpha[ai] += T_inv[ai][aj] * num_flux->get_q()[aj];
for (unsigned int bi = 0; bi < 4; bi++)
for (unsigned int bj = 0; bj < 4; bj++)
beta[bi] += T_inv[bi][bj] * q_ji_star[bj];
for (unsigned int si = 0; si < 4; si++)
for (unsigned int sj = 0; sj < 4; sj++)
if (eigenvalues[sj] < 0)
q_ji[si] += beta[sj] * T[si][sj];
else
q_ji[si] += alpha[sj] * T[si][sj];
num_flux->Q_inv(w_ji, q_ji, e->nx[point_i], e->ny[point_i]);
double w_temp[4];
w_temp[0] = (w_ji[0] + w_L[0]) / 2;
w_temp[1] = (w_ji[1] + w_L[1]) / 2;
w_temp[2] = (w_ji[2] + w_L[2]) / 2;
w_temp[3] = (w_ji[3] + w_L[3]) / 2;
double e_1[4] = { 1, 0, 0, 0 };
double e_2[4] = { 0, 1, 0, 0 };
double e_3[4] = { 0, 0, 1, 0 };
double e_4[4] = { 0, 0, 0, 1 };
num_flux->P_plus(this->P_plus_cache[point_i], w_temp, e_1, e->nx[point_i], e->ny[point_i]);
num_flux->P_plus(this->P_plus_cache[point_i] + 4, w_temp, e_2, e->nx[point_i], e->ny[point_i]);
num_flux->P_plus(this->P_plus_cache[point_i] + 8, w_temp, e_3, e->nx[point_i], e->ny[point_i]);
num_flux->P_plus(this->P_plus_cache[point_i] + 12, w_temp, e_4, e->nx[point_i], e->ny[point_i]);
}
*(const_cast<EulerEquationsMatrixFormSemiImplicitInletOutlet*>(this))->cacheReady = true;
}
int index = j * 4 + i;
for (int point_i = 0; point_i < n; point_i++)
{
result += wt[point_i] * P_plus_cache[point_i][index] * u->val[point_i] * v->val[point_i];
}
return result * wf->get_current_time_step();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
MatrixFormSurf<double>* clone() const
{
EulerEquationsMatrixFormSemiImplicitInletOutlet* form = new EulerEquationsMatrixFormSemiImplicitInletOutlet(this->i, this->j, this->rho_ext, this->v1_ext, this->v2_ext, this->energy_ext, this->areas, this->num_flux->kappa, this->cacheReady, this->P_plus_cache, this->P_minus_cache);
form->wf = this->wf;
return form;
}
double rho_ext;
double v1_ext;
double v2_ext;
double energy_ext;
bool* cacheReady;
double** P_plus_cache;
double** P_minus_cache;
StegerWarmingNumericalFlux* num_flux;
};
class EulerEquationsVectorFormSemiImplicitInletOutlet : public VectorFormSurf < double >
{
public:
EulerEquationsVectorFormSemiImplicitInletOutlet(int i, double rho_ext, double v1_ext, double v2_ext, double energy_ext, std::string marker, double kappa)
: VectorFormSurf<double>(i), rho_ext(rho_ext), v1_ext(v1_ext), v2_ext(v2_ext), energy_ext(energy_ext),
num_flux(new StegerWarmingNumericalFlux(kappa))
{
set_area(marker);
}
EulerEquationsVectorFormSemiImplicitInletOutlet(int i, double rho_ext, double v1_ext, double v2_ext, double energy_ext, std::vector<std::string> markers, double kappa)
: VectorFormSurf<double>(i), rho_ext(rho_ext), v1_ext(v1_ext), v2_ext(v2_ext), energy_ext(energy_ext),
num_flux(new StegerWarmingNumericalFlux(kappa))
{
set_areas(markers);
}
~EulerEquationsVectorFormSemiImplicitInletOutlet()
{
delete num_flux;
}
double value(int n, double *wt, Func<double> *u_ext[],
Func<double> *v, GeomSurf<double> *e, Func<double>* *ext) const
{
double result = 0.;
double w_B[4], w_L[4], eigenvalues[4], alpha[4], q_ji_star[4], beta[4], q_ji[4], w_ji[4];
for (int point_i = 0; point_i < n; point_i++)
{
// Inner state.
w_L[0] = ext[0]->val[point_i];
w_L[1] = ext[1]->val[point_i];
w_L[2] = ext[2]->val[point_i];
w_L[3] = ext[3]->val[point_i];
// Transformation of the inner state to the local coordinates.
num_flux->Q(num_flux->get_q(), w_L, e->nx[point_i], e->ny[point_i]);
// Initialize the matrices.
double T[4][4];
double T_inv[4][4];
for (unsigned int ai = 0; ai < 4; ai++)
{
for (unsigned int aj = 0; aj < 4; aj++)
{
T[ai][aj] = 0.0;
T_inv[ai][aj] = 0.0;
}
alpha[ai] = 0;
beta[ai] = 0;
q_ji[ai] = 0;
w_ji[ai] = 0;
eigenvalues[ai] = 0;
}
// Calculate Lambda^-.
num_flux->Lambda(eigenvalues);
num_flux->T_1(T);
num_flux->T_2(T);
num_flux->T_3(T);
num_flux->T_4(T);
num_flux->T_inv_1(T_inv);
num_flux->T_inv_2(T_inv);
num_flux->T_inv_3(T_inv);
num_flux->T_inv_4(T_inv);
// "Prescribed" boundary state.
w_B[0] = this->rho_ext;
w_B[1] = this->rho_ext * this->v1_ext;
w_B[2] = this->rho_ext * this->v2_ext;
w_B[3] = this->energy_ext;
num_flux->Q(q_ji_star, w_B, e->nx[point_i], e->ny[point_i]);
for (unsigned int ai = 0; ai < 4; ai++)
for (unsigned int aj = 0; aj < 4; aj++)
alpha[ai] += T_inv[ai][aj] * num_flux->get_q()[aj];
for (unsigned int bi = 0; bi < 4; bi++)
for (unsigned int bj = 0; bj < 4; bj++)
beta[bi] += T_inv[bi][bj] * q_ji_star[bj];
for (unsigned int si = 0; si < 4; si++)
for (unsigned int sj = 0; sj < 4; sj++)
if (eigenvalues[sj] < 0)
q_ji[si] += beta[sj] * T[si][sj];
else
q_ji[si] += alpha[sj] * T[si][sj];
num_flux->Q_inv(w_ji, q_ji, e->nx[point_i], e->ny[point_i]);
double P_minus[4];
double w_temp[4];
w_temp[0] = (w_ji[0] + w_L[0]) / 2;
w_temp[1] = (w_ji[1] + w_L[1]) / 2;
w_temp[2] = (w_ji[2] + w_L[2]) / 2;
w_temp[3] = (w_ji[3] + w_L[3]) / 2;
num_flux->P_minus(P_minus, w_temp, w_ji, e->nx[point_i], e->ny[point_i]);
result += wt[point_i] * (P_minus[i]) * v->val[point_i];
}
return -result * wf->get_current_time_step();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
VectorFormSurf<double>* clone() const
{
EulerEquationsVectorFormSemiImplicitInletOutlet* form = new EulerEquationsVectorFormSemiImplicitInletOutlet(this->i, this->rho_ext, this->v1_ext, this->v2_ext, this->energy_ext, this->areas, this->num_flux->kappa);
form->wf = this->wf;
return form;
}
double rho_ext;
double v1_ext;
double v2_ext;
double energy_ext;
StegerWarmingNumericalFlux* num_flux;
};
class EulerEquationsLinearFormTime : public VectorFormVol < double >
{
public:
EulerEquationsLinearFormTime(int i)
: VectorFormVol<double>(i) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
return int_u_v<double, double>(n, wt, ext[this->i], v);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return int_u_v<Ord, Ord>(n, wt, ext[this->i], v);
}
VectorFormVol<double>* clone() const { return new EulerEquationsLinearFormTime(this->i); }
};
class EulerEquationsMatrixFormSolidWall : public MatrixFormSurf < double >
{
public:
EulerEquationsMatrixFormSolidWall(unsigned int i, unsigned int j, std::vector<std::string> markers, double kappa)
: MatrixFormSurf<double>(i, j), kappa(kappa) { set_areas(markers); }
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomSurf<double> *e, Func<double>* *ext) const
{
double result = 0.;
for (int point_i = 0; point_i < n; point_i++)
{
double rho = ext[0]->val[point_i];
double v_1 = ext[1]->val[point_i] / rho;
double v_2 = ext[2]->val[point_i] / rho;
double P[4][4];
for (unsigned int P_i = 0; P_i < 4; P_i++)
for (unsigned int P_j = 0; P_j < 4; P_j++)
P[P_i][P_j] = 0.0;
P[1][0] = (kappa - 1) * (v_1 * v_1 + v_2 * v_2) * e->nx[point_i] / 2;
P[1][1] = (kappa - 1) * (-v_1) * e->nx[point_i];
P[1][2] = (kappa - 1) * (-v_2) * e->nx[point_i];
P[1][3] = (kappa - 1) * e->nx[point_i];
P[2][0] = (kappa - 1) * (v_1 * v_1 + v_2 * v_2) * e->ny[point_i] / 2;
P[2][1] = (kappa - 1) * (-v_1) * e->ny[point_i];
P[2][2] = (kappa - 1) * (-v_2) * e->ny[point_i];
P[2][3] = (kappa - 1) * e->ny[point_i];
result += wt[point_i] * P[i][j] * u->val[point_i] * v->val[point_i];
}
return result * wf->get_current_time_step();
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
MatrixFormSurf<double>* clone() const
{
EulerEquationsMatrixFormSolidWall* form = new EulerEquationsMatrixFormSolidWall(this->i, this->j, this->areas, this->kappa);
form->wf = this->wf;
return form;
}
// Members.
double kappa;
};
class EulerEquationsFormStabilizationVol : public MatrixFormVol < double >
{
public:
EulerEquationsFormStabilizationVol(int i, double nu_1) : MatrixFormVol<double>(i, i), nu_1(nu_1) {}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0.;
if (static_cast<EulerEquationsWeakFormSemiImplicit*>(wf)->discreteIndicator[e->id])
result = int_grad_u_grad_v<double, double>(n, wt, u, v);
return result * nu_1 * e->get_diam_approximation(n);
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
return int_grad_u_grad_v<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* clone() const
{
EulerEquationsFormStabilizationVol* form = new EulerEquationsFormStabilizationVol(this->i, nu_1);
return form;
}
private:
double nu_1;
};
class EulerEquationsFormStabilizationSurf : public MatrixFormDG < double >
{
public:
EulerEquationsFormStabilizationSurf(unsigned int i, unsigned int j, double nu_2)
: MatrixFormDG<double>(i, j), nu_2(nu_2) {}
double value(int n, double *wt, DiscontinuousFunc<double> **u_ext, DiscontinuousFunc<double> *u,
DiscontinuousFunc<double> *v, InterfaceGeom<double> *e, DiscontinuousFunc<double>* *ext) const
{
double result = 0.;
if (static_cast<EulerEquationsWeakFormSemiImplicit*>(wf)->discreteIndicator[e->central_el->id] && static_cast<EulerEquationsWeakFormSemiImplicit*>(wf)->discreteIndicator[e->neighb_el->id])
{
if (u->val == NULL)
if (v->val == NULL)
for (int point_i = 0; point_i < n; point_i++)
result += wt[i] * (-u->val_neighbor[point_i]) * (-v->val_neighbor[point_i]);
else
for (int point_i = 0; point_i < n; point_i++)
result += wt[i] * (-u->val_neighbor[point_i]) * (v->val[point_i]);
else
if (v->val == NULL)
for (int point_i = 0; point_i < n; point_i++)
result += wt[i] * (u->val[point_i]) * (-v->val_neighbor[point_i]);
else
for (int point_i = 0; point_i < n; point_i++)
result += wt[i] * (u->val[point_i]) * (v->val[point_i]);
}
return result * nu_2;
}
MatrixFormDG<double>* clone() const
{
EulerEquationsFormStabilizationSurf* form = new EulerEquationsFormStabilizationSurf(this->i, this->j, nu_2);
form->wf = this->wf;
return form;
}
double nu_2;
};
}; | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/heating-induced-vortex-adapt/main.cpp | .cpp | 5,008 | 144 | #define HERMES_REPORT_INFO
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
// This example solves the compressible Euler equations using Discontinuous Galerkin method of higher order with adaptivity.
//
// Equations: Compressible Euler equations, perfect gas state equation.
//
// Domain: A square, see file square.mesh->
//
// BC: Solid walls, inlet, no outlet.
//
// IC: Constant state identical to inlet, only with higher pressure.
//
// The following parameters can be changed:
// Visualization.
// Set to "true" to enable Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = true;
// Set to "true" to enable VTK output.
const bool VTK_VISUALIZATION = false;
// Set visual output for every nth step.
const unsigned int EVERY_NTH_STEP = 1;
// Shock capturing.
enum shockCapturingType
{
FEISTAUER,
KUZMIN,
KRIVODONOVA
};
bool SHOCK_CAPTURING = false;
shockCapturingType SHOCK_CAPTURING_TYPE = KUZMIN;
// Quantitative parameter of the discontinuity detector in case of Krivodonova.
double DISCONTINUITY_DETECTOR_PARAM = 1.0;
// Quantitative parameter of the shock capturing in case of Feistauer.
const double NU_1 = 0.1;
const double NU_2 = 0.1;
// Initial polynomial degree.
// Do not change.
const int P_INIT = 0;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// CFL value.
double CFL_NUMBER = 0.1;
// Initial time step.
double time_step_n = 1E-6;
double TIME_INTERVAL_LENGTH = 20.;
// Every UNREF_FREQth time step the mesh is unrefined.
const int UNREF_FREQ = 5;
// Number of mesh refinements between two unrefinements.
// The mesh is not unrefined unless there has been a refinement since
// last unrefinement.
int REFINEMENT_COUNT = 0;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies (see below).
const double THRESHOLD = 0.3;
// Predefined list of element refinement candidates. Possible values are
// H2D_P_ISO, H2D_P_ANISO, H2D_H_ISO, H2D_H_ANISO, H2D_HP_ISO,
// H2D_HP_ANISO_H, H2D_HP_ANISO_P, H2D_HP_ANISO.
CandList CAND_LIST = H2D_HP_ANISO;
// Maximum polynomial degree used. -1 for unlimited.
// See User Documentation for details.
const int MAX_P_ORDER = 1;
// Maximum allowed level of hanging nodes:
// MESH_REGULARITY = -1 ... arbitrary level hangning nodes (default),
// MESH_REGULARITY = 1 ... at most one-level hanging nodes,
// MESH_REGULARITY = 2 ... at most two-level hanging nodes, etc.
// Note that regular meshes are not supported, this is due to
// their notoriously bad performance.
const int MESH_REGULARITY = -1;
// Stopping criterion for adaptivity.
double adaptivityErrorStop(int iteration)
{
if (iteration > 49)
return 0.01;
else
return 0.5 - iteration * 0.01;
}
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 2.0;
// Initial pressure (dimensionless).
const double P_INITIAL_HIGH = 1.5;
// Initial pressure (dimensionless).
const double P_INITIAL_LOW = 1.0;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Initial density (dimensionless).
const double RHO_INITIAL_HIGH = 0.5;
// Initial density (dimensionless).
const double RHO_INITIAL_LOW = 0.3;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 0.0;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
const double MESH_SIZE = 3.0;
// Mesh filename.
const std::string MESH_FILENAME = "square.mesh";
// Boundary markers.
const std::string BDY_INLET = "Inlet";
const std::string BDY_SOLID_WALL = "Solid";
// Weak forms.
#include "../forms_explicit.cpp"
// Initial condition.
#include "../initial_condition.cpp"
int main(int argc, char* argv[])
{
#include "../euler-init-main-adapt.cpp"
// Set initial conditions.
MeshFunctionSharedPtr<double> prev_rho(new InitialSolutionLinearProgress(mesh, RHO_INITIAL_HIGH, RHO_INITIAL_LOW, MESH_SIZE));
MeshFunctionSharedPtr<double> prev_rho_v_x(new ConstantSolution<double>(mesh, 0.0));
MeshFunctionSharedPtr<double> prev_rho_v_y(new ConstantSolution<double>(mesh, 0.0));
MeshFunctionSharedPtr<double> prev_e(new InitialSolutionLinearProgress(mesh, QuantityCalculator::calc_energy(RHO_INITIAL_HIGH, RHO_INITIAL_HIGH * V1_EXT, RHO_INITIAL_HIGH * V2_EXT, P_INITIAL_HIGH, KAPPA), QuantityCalculator::calc_energy(RHO_INITIAL_LOW, RHO_INITIAL_LOW * V1_EXT, RHO_INITIAL_LOW * V2_EXT, P_INITIAL_LOW, KAPPA), MESH_SIZE));
// Initialize weak formulation.
std::vector<std::string> solid_wall_markers({ BDY_SOLID_WALL });
std::vector<std::string> inlet_markers({ BDY_INLET });
std::vector<std::string> outlet_markers;
WeakFormSharedPtr<double> wf(new EulerEquationsWeakFormSemiImplicit(KAPPA, {RHO_EXT}, {V1_EXT}, {V2_EXT}, {P_EXT}, solid_wall_markers,
inlet_markers, outlet_markers, prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e));
#include "../euler-time-loop-space-adapt.cpp"
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/reflected-shock/definitions.h | .h | 199 | 8 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/euler/reflected-shock/main.cpp | .cpp | 3,912 | 120 | #define HERMES_REPORT_INFO
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
// This example solves the compressible Euler equations using a basic
// piecewise-constant finite volume method, or Discontinuous Galerkin
// method of higher order with no adaptivity.
//
// Equations: Compressible Euler equations, perfect gas state equation.
//
// Domain: A rectangular channel, see channel.mesh->
//
// BC: Solid walls, inlet / outlet. In this case there are two inlets (the left, and the upper wall).
//
// IC: Constant state.
//
// The following parameters can be changed:
// Visualization.
// Set to "true" to enable Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = true;
// Set to "true" to enable VTK output.
const bool VTK_VISUALIZATION = true;
// Set visual output for every nth step.
const unsigned int EVERY_NTH_STEP = 1;
// Shock capturing.
enum shockCapturingType
{
FEISTAUER,
KUZMIN,
KRIVODONOVA
};
bool SHOCK_CAPTURING = true;
shockCapturingType SHOCK_CAPTURING_TYPE = KUZMIN;
// Quantitative parameter of the discontinuity detector in case of Krivodonova.
double DISCONTINUITY_DETECTOR_PARAM = 1.0;
// Quantitative parameter of the shock capturing in case of Feistauer.
const double NU_1 = 0.1;
const double NU_2 = 0.1;
// Initial polynomial degree.
// This example will not work if P_INIT > 1.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 4;
// CFL value.
double CFL_NUMBER = 0.5;
// Initial time step.
double time_step_n = 0.01;
double KAPPA = 1.4;
// Equation parameters.
const double RHO_LEFT = 1.0;
const double RHO_TOP = 1.7;
const double V1_LEFT = 2.9;
const double V1_TOP = 2.619334;
const double V2_LEFT = 0.0;
const double V2_TOP = -0.5063;
const double PRESSURE_LEFT = 0.714286;
const double PRESSURE_TOP = 1.52819;
// Initial values
const double RHO_INIT = 1.0;
const double V1_INIT = 2.9;
const double V2_INIT = 0.0;
const double PRESSURE_INIT = 0.714286;
double TIME_INTERVAL_LENGTH = 20.;
// Mesh filename.
#define MESH_FILENAME "channel.mesh"
// Boundary markers.
const std::string BDY_SOLID_WALL = "1";
const std::string BDY_OUTLET = "2";
const std::string BDY_INLET_TOP = "3";
const std::string BDY_INLET_LEFT = "4";
// Weak forms.
#include "../forms_explicit.cpp"
// Initial condition.
#include "../initial_condition.cpp"
int main(int argc, char* argv[])
{
#include "../euler-init-main.cpp"
#pragma region 3. Example-specific setup.
// Initialize boundary conditions.
std::vector<std::string> solid_wall_markers;
solid_wall_markers.push_back(BDY_SOLID_WALL);
std::vector<std::string> inlet_markers({ BDY_INLET_LEFT, BDY_INLET_TOP });
std::vector<double> rho_ext({ RHO_LEFT, RHO_TOP });
std::vector<double> v1_ext({ V1_LEFT, V1_TOP });
std::vector<double> v2_ext({ V2_LEFT, V2_TOP });
std::vector<double> pressure_ext({ PRESSURE_LEFT, PRESSURE_TOP });
std::vector<std::string> outlet_markers({ BDY_OUTLET });
// Set initial conditions.
MeshFunctionSharedPtr<double> prev_rho(new ConstantSolution<double>(mesh, RHO_INIT));
MeshFunctionSharedPtr<double> prev_rho_v_x(new ConstantSolution<double>(mesh, RHO_INIT * V1_INIT));
MeshFunctionSharedPtr<double> prev_rho_v_y(new ConstantSolution<double>(mesh, RHO_INIT * V2_INIT));
MeshFunctionSharedPtr<double> prev_e(new ConstantSolution<double>(mesh, QuantityCalculator::calc_energy(RHO_INIT, RHO_INIT * V1_INIT, RHO_INIT * V2_INIT, PRESSURE_INIT, KAPPA)));
std::vector<MeshFunctionSharedPtr<double> > prev_slns({ prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e });
// Weak formulation.
WeakFormSharedPtr<double> wf(new EulerEquationsWeakFormSemiImplicit(KAPPA, rho_ext, v1_ext, v2_ext, pressure_ext, solid_wall_markers, inlet_markers, outlet_markers, prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, (P_INIT == 0)));
#pragma endregion
#include "../euler-time-loop.cpp"
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/reflected-shock/definitions.cpp | .cpp | 0 | 0 | null | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/heating-flow-coupling/main.cpp | .cpp | 9,217 | 243 | #define HERMES_REPORT_INFO
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Solvers;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::RefinementSelectors;
using namespace Hermes::Hermes2D::Views;
// Visualization.
// Set to "true" to enable Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = true;
// Set to "true" to enable VTK output.
const bool VTK_VISUALIZATION = false;
// Set visual output for every nth step.
const unsigned int EVERY_NTH_STEP = 1;
// Initial polynomial degree.
const int P_INIT_FLOW = 1;
const int P_INIT_HEAT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// Shock capturing.
enum shockCapturingType
{
KUZMIN,
KRIVODONOVA
};
bool SHOCK_CAPTURING = false;
shockCapturingType SHOCK_CAPTURING_TYPE = KUZMIN;
// Quantitative parameter of the discontinuity detector in case of Krivodonova.
double DISCONTINUITY_DETECTOR_PARAM = 1.0;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 1.5;
// Initial pressure (dimensionless).
const double P_INITIAL_HIGH = 1.5;
// Initial pressure (dimensionless).
const double P_INITIAL_LOW = 1.0;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Initial density (dimensionless).
const double RHO_INITIAL_HIGH = 1.0;
// Initial density (dimensionless).
const double RHO_INITIAL_LOW = 0.66;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 0.0;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
// Lambda.
const double LAMBDA = 1e2;
// heat_capacity.
const double C_P = 1e-2;
// CFL value.
const double CFL_NUMBER = 0.1;
// Initial time step.
double time_step = 1E-5;
// Stability for the concentration part.
double ADVECTION_STABILITY_CONSTANT = 1e16;
const double DIFFUSION_STABILITY_CONSTANT = 1e16;
// Boundary markers.
const std::string BDY_INLET = "Inlet";
const std::string BDY_SOLID_WALL = "Solid";
// Area (square) size.
// Must be in accordance with the mesh file.
const double MESH_SIZE = 3.0;
// Weak forms.
#include "../forms_explicit.cpp"
// Initial condition.
#include "../initial_condition.cpp"
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh), mesh_heat(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", mesh);
mesh_heat->copy(mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
{
mesh->refine_all_elements(0, true);
mesh_heat->refine_all_elements(0, true);
}
mesh->refine_all_elements(0, true);
mesh_heat->refine_towards_boundary("Inlet");
mesh_heat->refine_towards_boundary("Inlet");
// Initialize boundary condition types and spaces with default shapesets.
Hermes2D::DefaultEssentialBCConst<double> bc_temp_zero("Solid", 0.0);
Hermes2D::DefaultEssentialBCConst<double> bc_temp_nonzero("Inlet", 1.0);
std::vector<Hermes2D::EssentialBoundaryCondition<double>*> bc_vector(&bc_temp_zero, &bc_temp_nonzero);
EssentialBCs<double> bcs(bc_vector);
SpaceSharedPtr<double> space_rho(new L2Space<double>(mesh, P_INIT_FLOW));
SpaceSharedPtr<double> space_rho_v_x(new L2Space<double>(mesh, P_INIT_FLOW));
SpaceSharedPtr<double> space_rho_v_y(new L2Space<double>(mesh, P_INIT_FLOW));
SpaceSharedPtr<double> space_e(new L2Space<double>(mesh, P_INIT_FLOW));
SpaceSharedPtr<double> space_temp(new H1Space<double>(mesh_heat, &bcs, P_INIT_HEAT));
int ndof = Space<double>::get_num_dofs({space_rho, space_rho_v_x, space_rho_v_y, space_e, space_temp});
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
// Initialize solutions, set initial conditions.
MeshFunctionSharedPtr<double> prev_rho(new InitialSolutionLinearProgress(mesh, RHO_INITIAL_HIGH, RHO_INITIAL_LOW, MESH_SIZE));
MeshFunctionSharedPtr<double> prev_rho_v_x(new ConstantSolution<double> (mesh, 0.0));
MeshFunctionSharedPtr<double> prev_rho_v_y(new ConstantSolution<double> (mesh, 0.0));
MeshFunctionSharedPtr<double> prev_e(new InitialSolutionLinearProgress (mesh, QuantityCalculator::calc_energy(RHO_INITIAL_HIGH, RHO_INITIAL_HIGH * V1_EXT, RHO_INITIAL_HIGH * V2_EXT, P_INITIAL_HIGH, KAPPA), QuantityCalculator::calc_energy(RHO_INITIAL_LOW, RHO_INITIAL_LOW * V1_EXT, RHO_INITIAL_LOW * V2_EXT, P_INITIAL_LOW, KAPPA), MESH_SIZE));
MeshFunctionSharedPtr<double> prev_temp(new ConstantSolution<double> (mesh_heat, 0.0));
// Filters for visualization of Mach number, pressure and entropy.
MeshFunctionSharedPtr<double> pressure(new PressureFilter({prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e}, KAPPA));
MeshFunctionSharedPtr<double> vel_x(new VelocityFilter({prev_rho, prev_rho_v_x}));
MeshFunctionSharedPtr<double> vel_y(new VelocityFilter({prev_rho, prev_rho_v_y}));
ScalarView pressure_view("Pressure", new WinGeom(0, 0, 400, 300));
VectorView velocity_view("Velocity", new WinGeom(0, 400, 400, 300));
ScalarView density_view("Density", new WinGeom(500, 0, 400, 300));
ScalarView temperature_view("Temperature", new WinGeom(500, 400, 400, 300));
// Set up the solver, matrix, and rhs according to the solver selection.
SparseMatrix<double>* matrix = create_matrix<double>();
Vector<double>* rhs = create_vector<double>();
Vector<double>* rhs_stabilization = create_vector<double>();
Hermes::Solvers::LinearMatrixSolver<double>* solver = create_linear_solver<double>( matrix, rhs);
// Set up stability calculation class.
CFLCalculation CFL(CFL_NUMBER, KAPPA);
ADEStabilityCalculation ADES(ADVECTION_STABILITY_CONSTANT, DIFFUSION_STABILITY_CONSTANT, LAMBDA);
// Look for a saved solution on the disk.
int iteration = 0; double t = 0;
// Initialize weak formulation.
std::vector<std::string> solid_wall_markers;
solid_wall_markers.push_back(BDY_SOLID_WALL);
std::vector<std::string> inlet_markers;
inlet_markers.push_back(BDY_INLET);
std::vector<std::string> outlet_markers;
EulerEquationsWeakFormSemiImplicitCoupledWithHeat wf(KAPPA, RHO_EXT, V1_EXT, V2_EXT, P_EXT, solid_wall_markers,
inlet_markers, outlet_markers, prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, prev_temp, LAMBDA, C_P);
// Initialize the FE problem.
std::vector<SpaceSharedPtr<double> > spaces(space_rho, space_rho_v_x, space_rho_v_y, space_e, space_temp);
Space<double>::assign_dofs(spaces);
DiscreteProblem<double> dp(wf, spaces);
dp.set_linear();
// Time stepping loop.
for(; ; t += time_step)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
// Set the current time step.
wf.set_current_time_step(time_step);
// Assemble the stiffness matrix and rhs.
Hermes::Mixins::Loggable::Static::info("Assembling the stiffness matrix and right-hand side vector.");
dp.assemble(matrix, rhs);
// Solve the matrix problem.
Hermes::Mixins::Loggable::Static::info("Solving the matrix problem.");
solver->solve();
if(!SHOCK_CAPTURING)
{
Solution<double>::vector_to_solutions(solver->get_sln_vector(),{space_rho, space_rho_v_x,
space_rho_v_y, space_e, space_temp},{prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, prev_temp});
}
else
{
FluxLimiter* flux_limiter;
if(SHOCK_CAPTURING_TYPE == KUZMIN)
flux_limiter = new FluxLimiter(FluxLimiter::Kuzmin, solver->get_sln_vector(),{space_rho, space_rho_v_x,
space_rho_v_y, space_e}, true);
else
flux_limiter = new FluxLimiter(FluxLimiter::Krivodonova, solver->get_sln_vector(),{space_rho, space_rho_v_x,
space_rho_v_y, space_e});
if(SHOCK_CAPTURING_TYPE == KUZMIN)
flux_limiter->limit_second_orders_according_to_detector();
flux_limiter->limit_according_to_detector();
flux_limiter->get_limited_solutions({prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e});
Solution<double>::vector_to_solution(solver->get_sln_vector() + Space<double>::get_num_dofs({space_rho, space_rho_v_x,
space_rho_v_y, space_e}), space_temp, prev_temp);
}
CFL.calculate_semi_implicit({prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e}, mesh, time_step);
double util_time_step = time_step;
ADES.calculate({prev_rho, prev_rho_v_x, prev_rho_v_y}, mesh, util_time_step);
if(util_time_step < time_step)
time_step = util_time_step;
// Visualization.
if((iteration - 1) % EVERY_NTH_STEP == 0)
{
// Hermes visualization.
if(HERMES_VISUALIZATION)
{
pressure->reinit();
vel_x->reinit();
vel_y->reinit();
pressure_view.show(pressure);
velocity_view.show(vel_x, vel_y);
density_view.show(prev_rho);
temperature_view.show(prev_temp);
}
// Output solution in VTK format.
if(VTK_VISUALIZATION)
{
pressure->reinit();
Linearizer lin_pressure;
char filename[40];
sprintf(filename, "pressure-3D-%i.vtk", iteration - 1);
lin_pressure.save_solution_vtk(pressure, filename, "Pressure", true);
}
}
}
pressure_view.close();
velocity_view.close();
density_view.close();
temperature_view.close();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/forward-step-adapt/main.cpp | .cpp | 4,143 | 119 | #define HERMES_REPORT_INFO
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
// This example solves the compressible Euler equations using Discontinuous Galerkin method of higher order with adaptivity.
//
// Equations: Compressible Euler equations, perfect gas state equation.
//
// Domain: forward facing step, see mesh file ffs.mesh
//
// BC: Solid walls, inlet, no outlet.
//
// IC: Constant state identical to inlet.
//
// The following parameters can be changed:
// Visualization.
// Set to "true" to enable Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = true;
// Set to "true" to enable VTK output.
const bool VTK_VISUALIZATION = false;
// Set visual output for every nth step.
const unsigned int EVERY_NTH_STEP = 1;
// Shock capturing.
enum shockCapturingType
{
FEISTAUER,
KUZMIN,
KRIVODONOVA
};
bool SHOCK_CAPTURING = false;
shockCapturingType SHOCK_CAPTURING_TYPE = KUZMIN;
// Quantitative parameter of the discontinuity detector in case of Krivodonova.
double DISCONTINUITY_DETECTOR_PARAM = 1.0;
// Quantitative parameter of the shock capturing in case of Feistauer.
const double NU_1 = 0.1;
const double NU_2 = 0.1;
// Initial polynomial degree.
const int P_INIT = 0;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 0;
// CFL value.
double CFL_NUMBER = 0.1;
// Initial time step.
double time_step_n = 1E-6;
double TIME_INTERVAL_LENGTH = 20.;
// Adaptivity.
// Every UNREF_FREQth time step the mesh is unrefined.
const int UNREF_FREQ = 10;
// Number of mesh refinements between two unrefinements.
// The mesh is not unrefined unless there has been a refinement since
// last unrefinement.
int REFINEMENT_COUNT = 1;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies (see below).
const double THRESHOLD = 0.6;
// Predefined list of element refinement candidates. Possible values are
// H2D_P_ISO, H2D_P_ANISO, H2D_H_ISO, H2D_H_ANISO, H2D_HP_ISO,
// H2D_HP_ANISO_H, H2D_HP_ANISO_P, H2D_HP_ANISO.
CandList CAND_LIST = H2D_HP_ANISO;
// Stopping criterion for adaptivity.
double adaptivityErrorStop(int iteration)
{
if (iteration > 49)
return 0.01;
else
return 0.5 - iteration * 0.01;
}
// Equation parameters.
const double P_EXT = 1.0; // Exterior pressure (dimensionless).
const double RHO_EXT = 1.4; // Inlet density (dimensionless).
const double V1_EXT = 3.0; // Inlet x-velocity (dimensionless).
const double V2_EXT = 0.0; // Inlet y-velocity (dimensionless).
const double KAPPA = 1.4; // Kappa.
// Mesh filename.
const std::string MESH_FILENAME = "ffs.mesh";
// Boundary markers.
const std::string BDY_SOLID_WALL_BOTTOM = "1";
const std::string BDY_OUTLET = "2";
const std::string BDY_SOLID_WALL_TOP = "3";
const std::string BDY_INLET = "4";
// Weak forms.
#include "../forms_explicit.cpp"
// Initial condition.
#include "../initial_condition.cpp"
int main(int argc, char* argv[])
{
#include "../euler-init-main-adapt.cpp"
// Set initial conditions.
MeshFunctionSharedPtr<double> prev_rho(new ConstantSolution<double>(mesh, RHO_EXT));
MeshFunctionSharedPtr<double> prev_rho_v_x(new ConstantSolution<double>(mesh, RHO_EXT * V1_EXT));
MeshFunctionSharedPtr<double> prev_rho_v_y(new ConstantSolution<double>(mesh, RHO_EXT * V2_EXT));
MeshFunctionSharedPtr<double> prev_e(new ConstantSolution<double>(mesh, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA)));
// Initialize weak formulation.
std::vector<std::string> solid_wall_markers({ BDY_SOLID_WALL_BOTTOM, BDY_SOLID_WALL_TOP });
std::vector<std::string> inlet_markers({ BDY_INLET });
std::vector<std::string> outlet_markers({ BDY_OUTLET });
WeakFormSharedPtr<double> wf(new EulerEquationsWeakFormSemiImplicit(KAPPA, {RHO_EXT}, {V1_EXT}, {V2_EXT}, {P_EXT}, solid_wall_markers,
inlet_markers, outlet_markers, prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e));
#include "../euler-time-loop-space-adapt.cpp"
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/heating-induced-vortex/main.cpp | .cpp | 3,465 | 99 | #define HERMES_REPORT_INFO
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::RefinementSelectors;
using namespace Hermes::Hermes2D::Views;
// Visualization.
// Set to "true" to enable Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = true;
// Set to "true" to enable VTK output.
const bool VTK_VISUALIZATION = false;
// Set visual output for every nth step.
const unsigned int EVERY_NTH_STEP = 1;
// Initial polynomial degree.
const int P_INIT = 0;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 3;
// Shock capturing.
enum shockCapturingType
{
FEISTAUER,
KUZMIN,
KRIVODONOVA
};
bool SHOCK_CAPTURING = false;
shockCapturingType SHOCK_CAPTURING_TYPE = KUZMIN;
// Quantitative parameter of the discontinuity detector in case of Krivodonova.
double DISCONTINUITY_DETECTOR_PARAM = 1.0;
// Quantitative parameter of the shock capturing in case of Feistauer.
const double NU_1 = 0.1;
const double NU_2 = 0.1;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 10.5;
// Initial pressure (dimensionless).
const double P_INITIAL_HIGH = 10.5;
// Initial pressure (dimensionless).
const double P_INITIAL_LOW = 1.0;
// Inlet density (dimensionless).
const double RHO_EXT = 0.5;
// Initial density (dimensionless).
const double RHO_INITIAL_HIGH = 0.5;
// Initial density (dimensionless).
const double RHO_INITIAL_LOW = 0.3;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 0.0;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
// CFL value.
const double CFL_NUMBER = 0.9;
// Initial time step.
double time_step_n = 1E-6;
double TIME_INTERVAL_LENGTH = 20.;
// Mesh filename.
const std::string MESH_FILENAME = "square.mesh";
// Boundary markers.
const std::string BDY_INLET = "Inlet";
const std::string BDY_SOLID_WALL = "Solid";
// Area (square) size.
// Must be in accordance with the mesh file.
const double MESH_SIZE = 3.0;
// Weak forms.
#include "../forms_explicit.cpp"
// Initial condition.
#include "../initial_condition.cpp"
int main(int argc, char* argv[])
{
#include "../euler-init-main.cpp"
// Set initial conditions.
MeshFunctionSharedPtr<double> prev_rho(new InitialSolutionLinearProgress(mesh, RHO_INITIAL_HIGH, RHO_INITIAL_LOW, MESH_SIZE));
MeshFunctionSharedPtr<double> prev_rho_v_x(new ConstantSolution<double>(mesh, 0.0));
MeshFunctionSharedPtr<double> prev_rho_v_y(new ConstantSolution<double>(mesh, 0.0));
MeshFunctionSharedPtr<double> prev_e(new InitialSolutionLinearProgress(mesh, QuantityCalculator::calc_energy(RHO_INITIAL_HIGH, RHO_INITIAL_HIGH * V1_EXT, RHO_INITIAL_HIGH * V2_EXT, P_INITIAL_HIGH, KAPPA), QuantityCalculator::calc_energy(RHO_INITIAL_LOW, RHO_INITIAL_LOW * V1_EXT, RHO_INITIAL_LOW * V2_EXT, P_INITIAL_LOW, KAPPA), MESH_SIZE));
std::vector<MeshFunctionSharedPtr<double> > prev_slns({ prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e });
// Initialize weak formulation.
std::vector<std::string> solid_wall_markers({ BDY_SOLID_WALL });
std::vector<std::string> inlet_markers({ BDY_INLET });
std::vector<std::string> outlet_markers;
WeakFormSharedPtr<double> wf(new EulerEquationsWeakFormSemiImplicit(KAPPA, { RHO_EXT }, { V1_EXT }, { V2_EXT }, { P_EXT }, solid_wall_markers,
inlet_markers, outlet_markers, prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, (P_INIT == 0)));
#include "../euler-time-loop.cpp"
} | C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.