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-advanced/euler/joukowski-profile-adapt/main.cpp | .cpp | 16,892 | 408 | #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: Joukowski profile, see file domain-nurbs.xml.
//
// BC: Solid walls, inlet, 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.
bool SHOCK_CAPTURING = false;
// Quantitative parameter of the discontinuity detector.
double DISCONTINUITY_DETECTOR_PARAM = 1.0;
// For saving/loading of solution.
bool REUSE_SOLUTION = true;
// Initial polynomial degree.
const int P_INIT = 0;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM_VERTEX = 3;
// Number of initial mesh refinements towards the profile.
const int INIT_REF_NUM_BOUNDARY_ANISO = 4;
// CFL value.
double CFL_NUMBER = 0.05;
// Initial time step.
double time_step = 1E-6;
// Adaptivity.
// 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.5;
// 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 = 1;
// 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.
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;
// This parameter influences the selection of
// candidates in hp-adaptivity. Default value is 1.0.
const double CONV_EXP = 1;
// Stopping criterion for adaptivity (rel. error tolerance between the
// fine mesh and coarse mesh solution in percent).
const double ERR_STOP = 1E-4;
// Adaptivity process stops when the number of degrees of freedom grows over
// this limit. This is mainly to prevent h-adaptivity to go on forever.
const int NDOF_STOP = 6200;
// Matrix solver for orthogonal projections: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
MatrixSolverType matrix_solver = SOLVER_UMFPACK;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 7142.8571428571428571428571428571;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 0.01;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
// Boundary markers.
const std::string BDY_INLET = "Inlet";
const std::string BDY_OUTLET = "Outlet";
const std::string BDY_SOLID_WALL_PROFILE = "Solid Profile";
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[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2DXML mloader;
mloader.load("domain-arcs.xml", mesh);
mesh->refine_towards_boundary(BDY_SOLID_WALL_PROFILE, INIT_REF_NUM_BOUNDARY_ANISO, true, true);
mesh->refine_towards_vertex(0, INIT_REF_NUM_VERTEX, true);
MeshView m;
m.show(mesh);
m.wait_for_close();
SpaceSharedPtr<double>space_rho(mesh, P_INIT);
L2Space<double>space_rho_v_x(mesh, P_INIT);
L2Space<double>space_rho_v_y(mesh, P_INIT);
L2Space<double>space_e(new // Initialize boundary condition types and spaces with default shapesets.
L2Space<double>(mesh, P_INIT));
int ndof = Space<double>::get_num_dofs({&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e});
Hermes::Mixins::Loggable::Static::info("Initial coarse ndof: %d", ndof);
// Initialize solutions, set initial conditions.
ConstantSolution<double> sln_rho(mesh, RHO_EXT);
ConstantSolution<double> sln_rho_v_x(mesh, RHO_EXT * V1_EXT);
ConstantSolution<double> sln_rho_v_y(mesh, RHO_EXT * V2_EXT);
ConstantSolution<double> sln_e(mesh, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
ConstantSolution<double> prev_rho(mesh, RHO_EXT);
ConstantSolution<double> prev_rho_v_x(mesh, RHO_EXT * V1_EXT);
ConstantSolution<double> prev_rho_v_y(mesh, RHO_EXT * V2_EXT);
ConstantSolution<double> prev_e(mesh, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
Solution<double> rsln_rho, rsln_rho_v_x, rsln_rho_v_y, rsln_e;
// Initialize weak formulation.
std::vector<std::string> solid_wall_markers;
solid_wall_markers.push_back(BDY_SOLID_WALL);
solid_wall_markers.push_back(BDY_SOLID_WALL_PROFILE);
std::vector<std::string> inlet_markers;
inlet_markers.push_back(BDY_INLET);
std::vector<std::string> outlet_markers;
outlet_markers.push_back(BDY_OUTLET);
EulerEquationsWeakFormSemiImplicit 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);
// Filters for visualization of Mach number, pressure and entropy.
MachNumberFilter Mach_number({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA);
PressureFilter pressure({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA);
EntropyFilter entropy({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA, RHO_EXT, P_EXT);
ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 300));
ScalarView Mach_number_view("Mach number", new WinGeom(700, 0, 600, 300));
ScalarView entropy_production_view("Entropy estimate", new WinGeom(0, 400, 600, 300));
OrderView space_view("Space", new WinGeom(700, 400, 600, 300));
// Initialize refinement selector.
L2ProjBasedSelector<double> selector(CAND_LIST, CONV_EXP, MAX_P_ORDER);
selector.set_error_weights(1.0, 1.0, 1.0);
// Set up CFL calculation class.
CFLCalculation CFL(CFL_NUMBER, KAPPA);
// Look for a saved solution on the disk.
CalculationContinuity<double> continuity(CalculationContinuity<double>::onlyTime);
int iteration = 0; double t = 0;
bool loaded_now = false;
if(REUSE_SOLUTION && continuity.have_record_available())
{
continuity.get_last_record()->load_mesh(mesh);
SpaceSharedPtr<double> *> spaceVector = continuity.get_last_record()->load_spaces(new std::vector<Space<double>({mesh, mesh, mesh, mesh}));
space_rho.copy(spaceVector[0], mesh);
space_rho_v_x.copy(spaceVector[1], mesh);
space_rho_v_y.copy(spaceVector[2], mesh);
space_e.copy(spaceVector[3], mesh);
continuity.get_last_record()->load_time_step_length(time_step);
t = continuity.get_last_record()->get_time() + time_step;
iteration = continuity.get_num() * EVERY_NTH_STEP + 1;
loaded_now = true;
}
// Time stepping loop.
for(; t < 5.0; t += time_step)
{
CFL.set_number(CFL_NUMBER + (t/5.0) * 10.0);
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
// 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);
}
// Adaptivity loop:
int as = 1;
int ndofs_prev = 0;
bool done = false;
do
{
Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
// Construct globally refined reference mesh and setup reference space.
int order_increase = 1;
Mesh::ReferenceMeshCreator refMeshCreatorFlow(mesh);
MeshSharedPtr ref_mesh_flow = refMeshCreatorFlow.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRho(space_rho, ref_mesh_flow, order_increase);
SpaceSharedPtr<double>* ref_space_rho = refSpaceCreatorRho.create_ref_space(new Space<double>());
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVx(space_rho_v_x, ref_mesh_flow, order_increase);
SpaceSharedPtr<double>* ref_space_rho_v_x = refSpaceCreatorRhoVx.create_ref_space(new Space<double>());
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVy(space_rho_v_y, ref_mesh_flow, order_increase);
SpaceSharedPtr<double>* ref_space_rho_v_y = refSpaceCreatorRhoVy.create_ref_space(new Space<double>());
Space<double>::ReferenceSpaceCreator refSpaceCreatorE(space_e, ref_mesh_flow, order_increase);
SpaceSharedPtr<double>* ref_space_e = refSpaceCreatorE.create_ref_space(new Space<double>());
SpaceSharedPtr<double>*> ref_spaces(new std::vector<const Space<double>(ref_space_rho, ref_space_rho_v_x, ref_space_rho_v_y, ref_space_e));
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.");
if(loaded_now)
{
loaded_now = false;
continuity.get_last_record()->load_solutions({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e},
SpaceSharedPtr<double> *>(new std::vector<Space<double>(ref_space_rho, ref_space_rho_v_x, ref_space_rho_v_y, ref_space_e)));
}
else
{
OGProjection<double>::project_global(ref_spaces,{&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e},
std::vector<Solution<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), std::vector<Hermes::Hermes2D::NormType>());
}
// Report NDOFs.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d.",
Space<double>::get_num_dofs({&space_rho, &space_rho_v_x,
space_rho_v_y, &space_e}), Space<double>::get_num_dofs(ref_spaces));
// Assemble the reference problem.
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
DiscreteProblem<double> dp(wf, ref_spaces);
SparseMatrix<double>* matrix = create_matrix<double>();
Vector<double>* rhs = create_vector<double>();
Hermes::Solvers::LinearMatrixSolver<double>* solver = create_linear_solver<double>( matrix, rhs);
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.");
if(solver->solve())
if(!SHOCK_CAPTURING)
Solution<double>::vector_to_solutions(solver->get_sln_vector(), ref_spaces,
std::vector<Solution<double>*>(&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e));
else
{
FluxLimiter flux_limiter(FluxLimiter::Kuzmin, solver->get_sln_vector(), ref_spaces, true);
flux_limiter.limit_second_orders_according_to_detector({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e});
flux_limiter.limit_according_to_detector({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e});
flux_limiter.get_limited_solutions({&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e});
}
else
throw Hermes::Exceptions::Exception("Matrix solver failed.\n");
// 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_rho, &space_rho_v_x,
&space_rho_v_y, &space_e},{&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e},
std::vector<Solution<double>*>(sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e),
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.");
Adapt<double>* adaptivity = new Adapt<double>({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e},{HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM});
double err_est_rel_total = adaptivity->calc_err_est({sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e},
std::vector<Solution<double>*>(&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e)) * 100;
CFL.calculate_semi_implicit({rsln_rho, rsln_rho_v_x, &rsln_rho_v_y, &rsln_e}, ref_space_rho->get_mesh(), time_step);
// 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 < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
if (Space<double>::get_num_dofs({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e}) >= NDOF_STOP)
done = true;
else
{
REFINEMENT_COUNT++;
done = adaptivity->adapt({&selector, &selector, &selector, &selector},
THRESHOLD, STRATEGY, MESH_REGULARITY);
}
if(!done)
as++;
}
// Visualization and saving on disk.
if(done && (iteration - 1) % EVERY_NTH_STEP == 0 && iteration > 1)
{
// Hermes visualization.
if(HERMES_VISUALIZATION)
{
Mach_number.reinit();
pressure.reinit();
entropy.reinit();
pressure_view.show(&pressure);
entropy_production_view.show(&entropy);
Mach_number_view.show(&Mach_number);
pressure_view.save_numbered_screenshot("Pressure-%u.bmp", iteration - 1, true);
Mach_number_view.save_numbered_screenshot("Mach-%u.bmp", iteration - 1, true);
}
// Output solution in VTK format.
if(VTK_VISUALIZATION)
{
pressure.reinit();
Mach_number.reinit();
Linearizer lin;
char filename[40];
sprintf(filename, "Pressure-%i.vtk", iteration - 1);
lin.save_solution_vtk(pressure, filename, "Pressure", false);
sprintf(filename, "Mach number-%i.vtk", iteration - 1);
lin.save_solution_vtk(Mach_number, filename, "MachNumber", false);
}
}
// Clean up.
delete solver;
delete matrix;
delete rhs;
delete adaptivity;
}
while (done == false);
// 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);
}
pressure_view.close();
entropy_production_view.close();
Mach_number_view.close();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/heating-flow-coupling-adapt/main.cpp | .cpp | 17,398 | 384 | #define HERMES_REPORT_INFO
#include "hermes2d.h"
#include "../coupling.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_FLOW = 0;
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 = true;
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 = 1e3;
// heat_capacity.
const double C_P = 1e2;
// heat flux through the inlet.
const double HEAT_FLUX = 1e-3;
// 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;
// Every UNREF_FREQth time step the mesh is unrefined.
const int UNREF_FREQ = 5;
// Adaptivity
int REFINEMENT_COUNT = 0;
const double THRESHOLD = 0.3;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_L2_NORM> errorCalculator(RelativeErrorToGlobalNorm, 5);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
CandList CAND_LIST = H2D_HP_ANISO;
const int MAX_P_ORDER = -1;
const int MESH_REGULARITY = -1;
const double CONV_EXP = 1;
double ERR_STOP = 5.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);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
mesh->refine_all_elements(0, true);
mesh_heat->copy(mesh);
//mesh_heat->refine_towards_boundary("Inlet", 3, false);
//mesh->refine_all_elements(0, true);
// 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));
std::vector<SpaceSharedPtr<double> > spaces(space_rho, space_rho_v_x, space_rho_v_y, space_e, space_temp);
std::vector<SpaceSharedPtr<double> > cspaces(space_rho, space_rho_v_x, space_rho_v_y, space_e, space_temp);
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));
std::vector<MeshFunctionSharedPtr<double> > prev_slns(prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, prev_temp);
std::vector<const MeshFunctionSharedPtr<double> > cprev_slns(prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e, prev_temp);
MeshFunctionSharedPtr<double> sln_rho(new InitialSolutionLinearProgress(mesh, RHO_INITIAL_HIGH, RHO_INITIAL_LOW, MESH_SIZE));
MeshFunctionSharedPtr<double> sln_rho_v_x(new ConstantSolution<double> (mesh, 0.0));
MeshFunctionSharedPtr<double> sln_rho_v_y(new ConstantSolution<double> (mesh, 0.0));
MeshFunctionSharedPtr<double> sln_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> sln_temp(new ConstantSolution<double> (mesh_heat, 0.0));
std::vector<MeshFunctionSharedPtr<double> > slns(sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e, sln_temp);
std::vector<const MeshFunctionSharedPtr<double> > cslns(sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e, sln_temp);
MeshFunctionSharedPtr<double> rsln_rho(new InitialSolutionLinearProgress(mesh, RHO_INITIAL_HIGH, RHO_INITIAL_LOW, MESH_SIZE));
MeshFunctionSharedPtr<double> rsln_rho_v_x(new ConstantSolution<double> (mesh, 0.0));
MeshFunctionSharedPtr<double> rsln_rho_v_y(new ConstantSolution<double> (mesh, 0.0));
MeshFunctionSharedPtr<double> rsln_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> rsln_temp(new ConstantSolution<double> (mesh_heat, 0.0));
std::vector<MeshFunctionSharedPtr<double> > rslns(rsln_rho, rsln_rho_v_x, rsln_rho_v_y, rsln_e, rsln_temp);
std::vector<const MeshFunctionSharedPtr<double> > crslns(rsln_rho, rsln_rho_v_x, rsln_rho_v_y, rsln_e, rsln_temp);
std::vector<SpaceSharedPtr<double> > flow_spaces(space_rho, space_rho_v_x, space_rho_v_y, space_e);
std::vector<MeshFunctionSharedPtr<double> > flow_slns(sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e);
std::vector<MeshFunctionSharedPtr<double> > rflow_slns(rsln_rho, rsln_rho_v_x, rsln_rho_v_y, rsln_e);
// Filters for visualization of Mach number, pressure and entropy.
MeshFunctionSharedPtr<double> pressure(new PressureFilter({rsln_rho, rsln_rho_v_x, rsln_rho_v_y, rsln_e}, KAPPA));
MeshFunctionSharedPtr<double> vel_x(new VelocityFilter({rsln_rho, rsln_rho_v_x}));
MeshFunctionSharedPtr<double> vel_y(new VelocityFilter({rsln_rho, rsln_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);
// Initialize refinement selector.
H1ProjBasedSelector<double> l2_selector(CAND_LIST);
H1ProjBasedSelector<double> h1_selector(CAND_LIST);
// 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.
DiscreteProblem<double> dp(wf, cspaces);
// Time stepping loop.
for(; t < 10.0; t += time_step)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
// 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_temp->unrefine_all_mesh_elements(true);
space_rho->adjust_element_order(-1, P_INIT_FLOW);
space_rho_v_x->adjust_element_order(-1, P_INIT_FLOW);
space_rho_v_y->adjust_element_order(-1, P_INIT_FLOW);
space_e->adjust_element_order(-1, P_INIT_FLOW);
space_temp->adjust_element_order(-1, P_INIT_HEAT);
Space<double>::assign_dofs(spaces);
}
// Set the current time step.
wf.set_current_time_step(time_step);
// 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.
int order_increase = 1;
Mesh::ReferenceMeshCreator refMeshCreatorFlow(mesh);
MeshSharedPtr ref_mesh_flow = refMeshCreatorFlow.create_ref_mesh();
Mesh::ReferenceMeshCreator refMeshCreatorTemperature(mesh_heat);
MeshSharedPtr ref_mesh_heat = refMeshCreatorTemperature.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRho(space_rho, ref_mesh_flow, order_increase);
SpaceSharedPtr<double> ref_space_rho = refSpaceCreatorRho.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVx(space_rho_v_x, ref_mesh_flow, order_increase);
SpaceSharedPtr<double> ref_space_rho_v_x = refSpaceCreatorRhoVx.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVy(space_rho_v_y, ref_mesh_flow, order_increase);
SpaceSharedPtr<double> ref_space_rho_v_y = refSpaceCreatorRhoVy.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorE(space_e, ref_mesh_flow, order_increase);
SpaceSharedPtr<double> ref_space_e = refSpaceCreatorE.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorT(space_temp, ref_mesh_heat, order_increase);
SpaceSharedPtr<double> ref_space_temp = refSpaceCreatorT.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, ref_space_temp);
std::vector<SpaceSharedPtr<double> > cref_spaces(ref_space_rho, ref_space_rho_v_x, ref_space_rho_v_y, ref_space_e, ref_space_temp);
std::vector<SpaceSharedPtr<double> > cref_flow_spaces(ref_space_rho, ref_space_rho_v_x, ref_space_rho_v_y, ref_space_e);
// 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(cref_spaces, prev_slns, prev_slns, std::vector<Hermes::Hermes2D::NormType>(), iteration > 1);
// Report NDOFs.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d.",
Space<double>::get_num_dofs(spaces), Space<double>::get_num_dofs(cref_spaces));
// Assemble the reference problem.
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
DiscreteProblem<double> dp(wf, cref_spaces);
// 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(), cref_spaces, rslns);
}
else
{
FluxLimiter* flux_limiter;
if(SHOCK_CAPTURING_TYPE == KUZMIN)
flux_limiter = new FluxLimiter(FluxLimiter::Kuzmin, solver->get_sln_vector(), cref_flow_spaces, true);
else
flux_limiter = new FluxLimiter(FluxLimiter::Krivodonova, solver->get_sln_vector(), cref_flow_spaces);
if(SHOCK_CAPTURING_TYPE == KUZMIN)
flux_limiter->limit_second_orders_according_to_detector(flow_spaces);
flux_limiter->limit_according_to_detector(flow_spaces);
flux_limiter->get_limited_solutions(rflow_slns);
Solution<double>::vector_to_solution(solver->get_sln_vector() + Space<double>::get_num_dofs(cref_flow_spaces), ref_space_temp, rsln_temp);
}
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
ogProjection.project_global(cspaces, rslns, slns,{HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM, HERMES_H1_NORM});
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
Adapt<double> adaptivity(spaces, &errorCalculator, &stoppingCriterion);
errorCalculator.add_error_form(new CouplingErrorFormVelocity(velX, C_P));
errorCalculator.add_error_form(new CouplingErrorFormVelocity(velY, C_P));
errorCalculator.add_error_form(new CouplingErrorFormTemperature(velX, C_P));
errorCalculator.add_error_form(new CouplingErrorFormTemperature(velY, C_P));
std::vector<double> component_errors;
double error_value = adaptivity.calc_err_est(slns, rslns, &component_errors) * 100;
std::cout << std::endl;
for(int k = 0; k < 5; k ++)
std::cout << k << ':' << component_errors[k] << std::endl;
std::cout << std::endl;
CFL.calculate_semi_implicit(rflow_slns, ref_mesh_flow, time_step);
double util_time_step = time_step;
ADES.calculate({rsln_rho, rsln_rho_v_x, rsln_rho_v_y}, ref_mesh_heat, util_time_step);
if(util_time_step < time_step)
time_step = util_time_step;
// Report results.
Hermes::Mixins::Loggable::Static::info("Error: %g%%.", error_value);
// If err_est too large, adapt the mesh.
if (error_value < ERR_STOP)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse space->");
done = adaptivity.adapt({&l2_selector, &l2_selector, &l2_selector, &l2_selector, &h1_selector});
}
as++;
// 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);
}
}
}
while (!done);
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);
prev_temp->copy(rsln_temp);
}
pressure_view.close();
velocity_view.close();
density_view.close();
temperature_view.close();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/forward-step/main.cpp | .cpp | 4,084 | 127 | #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: 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.
// Do not change this.
const int P_INIT = 0;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// Number of initial localized mesh refinements.
const int INIT_REF_NUM_STEP = 2;
// CFL value.
double CFL_NUMBER = 0.25;
// Initial time step.
double time_step_n = 1E-6;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 1.0;
// Inlet density (dimensionless).
const double RHO_EXT = 1.4;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 3.0;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
double TIME_INTERVAL_LENGTH = 20.;
// 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"
// Criterion for mesh refinement.
int refinement_criterion(Element* e)
{
if (e->vn[2]->y <= 0.4 && e->vn[1]->x <= 0.6)
return 0;
else
return -1;
}
int main(int argc, char* argv[])
{
#include "../euler-init-main.cpp"
// Perform custom initial mesh refinements.
mesh->refine_by_criterion(refinement_criterion, INIT_REF_NUM_STEP);
for (int i = 0; i < spaces.size(); i++)
{
for_all_active_elements_fast(mesh)
{
spaces[i]->set_element_order(e->id, P_INIT);
}
spaces[i]->assign_dofs();
}
for_all_active_elements_fast(mesh)
{
space_stabilization->set_element_order(e->id, 0);
}
space_stabilization->assign_dofs();
// 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)));
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_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, (P_INIT == 0)));
#include "../euler-time-loop.cpp"
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/euler-coupled-adapt/main.cpp | .cpp | 25,672 | 571 | #define HERMES_REPORT_INFO
#include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace RefinementSelectors;
// This example solves the compressible Euler equations coupled with an advection-diffution equation
// using a basic piecewise-constant finite volume method for the flow and continuous FEM for the concentration
// being advected by the flow.
//
// Equations: Compressible Euler equations, perfect gas state equation, advection-diffusion equation.
//
// Domains: Various
//
// BC: Various.
//
// IC: Various.
//
// The following parameters can be changed:
// Semi-implicit scheme.
const bool SEMI_IMPLICIT = true;
// Visualization.
// Set to "true" to enable Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = false;
// 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 = FEISTAUER;
// 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;
// Stability for the concentration part.
double ADVECTION_STABILITY_CONSTANT = 0.5;
const double DIFFUSION_STABILITY_CONSTANT = 1.0;
// Polynomial degree for the Euler equations (for the flow).
const int P_INIT_FLOW = 0;
// Polynomial degree for the concentration.
const int P_INIT_CONCENTRATION = 1;
// CFL value.
double CFL_NUMBER = 0.5;
// Initial and utility time step.
double time_step_n = 1E-5, util_time_step, time_step_after_adaptivity;
// Adaptivity.
// Every UNREF_FREQth time step the mesh is unrefined.
const int UNREF_FREQ = 5;
bool FORCE_UNREF = false;
// Number of mesh refinements between two unrefinements.
// The mesh is not unrefined unless there has been a refinement since
// last unrefinement.
int REFINEMENT_COUNT_FLOW = 0;
// Number of mesh refinements between two unrefinements.
// The mesh is not unrefined unless there has been a refinement since
// last unrefinement.
int REFINEMENT_COUNT_CONCENTRATION = 0;
// 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 = 1;
// 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_FLOW = H2D_HP_ANISO, CAND_LIST_CONCENTRATION = H2D_HP_ANISO;
// Maximum polynomial degree used. -1 for unlimited.
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;
// This parameter influences the selection of
// candidates in hp-adaptivity. Default value is 1.0.
const double CONV_EXP = 1;
// Stopping criterion time steps with the higher tolerance.
int ERR_STOP_REDUCE_TIME_STEP = 10;
// Stopping criterion for adaptivity.
double ERR_STOP_INIT_FLOW = 4.5;
double ERR_STOP_FLOW = 1.0;
// Stopping criterion for adaptivity.
double ERR_STOP_INIT_CONCENTRATION = 15.0;
double ERR_STOP_CONCENTRATION = 5.0;
// Adaptivity process stops when the number of degrees of freedom grows over
// this limit. This is mainly to prevent h-adaptivity to go on forever.
const int NDOF_STOP = 3500;
// Matrix solver for orthogonal projections: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
MatrixSolverType matrix_solver = SOLVER_UMFPACK;
// Number of initial uniform mesh refinements of the mesh for the flow.
unsigned int INIT_REF_NUM_FLOW = 2;
// Number of initial uniform mesh refinements of the mesh for the concentration.
unsigned int INIT_REF_NUM_CONCENTRATION = 2;
// Number of initial mesh refinements of the mesh for the concentration towards the
// part of the boundary where the concentration is prescribed.
unsigned int INIT_REF_NUM_CONCENTRATION_BDY = 1;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 2.5;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 1.25;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
// Concentration on the boundary.
const double CONCENTRATION_EXT = 0.01;
// Start time of the concentration on the boundary.
const double CONCENTRATION_EXT_STARTUP_TIME = 0.0;
// Diffusivity.
const double EPSILON = 0.005;
// Boundary markers.
const std::string BDY_INLET = "1";
const std::string BDY_OUTLET = "2";
const std::string BDY_SOLID_WALL_BOTTOM = "3";
const std::string BDY_SOLID_WALL_TOP = "4";
const std::string BDY_DIRICHLET_CONCENTRATION = "3";
// Weak forms.
#include "../forms_explicit.cpp"
// Initial condition.
#include "../initial_condition.cpp"
int main(int argc, char* argv[])
{
std::vector<std::string> BDY_NATURAL_CONCENTRATION;
BDY_NATURAL_CONCENTRATION.push_back("2");
// Load the mesh.
Mesh basemesh;
MeshReaderH2D mloader;
mloader.load("GAMM-channel.mesh", &basemesh);
// Initialize the meshes.
MeshSharedPtr mesh_flow, mesh_concentration;
mesh_flow.copy(&basemesh);
mesh_concentration.copy(&basemesh);
for(unsigned int i = 0; i < INIT_REF_NUM_CONCENTRATION; i++)
mesh_concentration.refine_all_elements(0, true);
mesh_concentration.refine_towards_boundary(BDY_DIRICHLET_CONCENTRATION, INIT_REF_NUM_CONCENTRATION_BDY, true, true);
for(unsigned int i = 0; i < INIT_REF_NUM_FLOW; i++)
mesh_flow.refine_all_elements(0, true);
// Initialize boundary condition types and spaces with default shapesets.
// For the concentration.
EssentialBCs<double> bcs_concentration;
bcs_concentration.add_boundary_condition(new ConcentrationTimedepEssentialBC(BDY_DIRICHLET_CONCENTRATION, CONCENTRATION_EXT, CONCENTRATION_EXT_STARTUP_TIME));
bcs_concentration.add_boundary_condition(new ConcentrationTimedepEssentialBC(BDY_SOLID_WALL_TOP, 0.0, CONCENTRATION_EXT_STARTUP_TIME));
bcs_concentration.add_boundary_condition(new ConcentrationTimedepEssentialBC(BDY_INLET, 0.0, CONCENTRATION_EXT_STARTUP_TIME));
SpaceSharedPtr<double>space_rho(mesh_flow, P_INIT_FLOW);
L2Space<double>space_rho_v_x(mesh_flow, P_INIT_FLOW);
L2Space<double>space_rho_v_y(mesh_flow, P_INIT_FLOW);
L2Space<double>space_e(mesh_flow, P_INIT_FLOW);
// Space<double> for concentration.
H1Space<double> space_c(new L2Space<double>(mesh_concentration, &bcs_concentration, P_INIT_CONCENTRATION));
int ndof = Space<double>::get_num_dofs({&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e, &space_c});
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
// Initialize solutions, set initial conditions.
ConstantSolution<double> sln_rho(mesh_flow, RHO_EXT);
ConstantSolution<double> sln_rho_v_x(mesh_flow, RHO_EXT * V1_EXT);
ConstantSolution<double> sln_rho_v_y(mesh_flow, RHO_EXT * V2_EXT);
ConstantSolution<double> sln_e(mesh_flow, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
ConstantSolution<double> sln_c(mesh_concentration, 0.0);
ConstantSolution<double> prev_rho(mesh_flow, RHO_EXT);
ConstantSolution<double> prev_rho_stabilization(mesh_flow, RHO_EXT);
ConstantSolution<double> prev_rho_v_x(mesh_flow, RHO_EXT * V1_EXT);
ConstantSolution<double> prev_rho_v_y(mesh_flow, RHO_EXT * V2_EXT);
ConstantSolution<double> prev_e(mesh_flow, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
ConstantSolution<double> prev_c(mesh_concentration, 0.0);
ConstantSolution<double> rsln_rho(mesh_flow, RHO_EXT);
ConstantSolution<double> rsln_rho_v_x(mesh_flow, RHO_EXT * V1_EXT);
ConstantSolution<double> rsln_rho_v_y(mesh_flow, RHO_EXT * V2_EXT);
ConstantSolution<double> rsln_e(mesh_flow, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
ConstantSolution<double> rsln_c(mesh_concentration, 0.0);
// Initialize weak formulation.
WeakForm<double>* wf = NULL;
if(SEMI_IMPLICIT)
{
wf = new EulerEquationsWeakFormSemiImplicitCoupled(KAPPA, RHO_EXT, V1_EXT, V2_EXT, P_EXT, BDY_SOLID_WALL_BOTTOM,
BDY_SOLID_WALL_TOP, BDY_INLET, BDY_OUTLET, BDY_NATURAL_CONCENTRATION, &prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c, EPSILON);
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
static_cast<EulerEquationsWeakFormSemiImplicitCoupled*>(wf)->set_stabilization(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, NU_1, NU_2);
}
else
wf = new EulerEquationsWeakFormExplicitCoupled(KAPPA, RHO_EXT, V1_EXT, V2_EXT, P_EXT, BDY_SOLID_WALL_BOTTOM,
BDY_SOLID_WALL_TOP, BDY_INLET, BDY_OUTLET, BDY_NATURAL_CONCENTRATION, &prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c, EPSILON);
EulerEquationsWeakFormStabilization wf_stabilization(&prev_rho_stabilization);
// Filters for visualization of Mach number, pressure and entropy.
MachNumberFilter Mach_number({&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e}, KAPPA);
PressureFilter pressure({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA);
EntropyFilter entropy({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA, RHO_EXT, P_EXT);
ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 400));
ScalarView Mach_number_view("Mach number", new WinGeom(700, 0, 600, 400));
ScalarView s5("Concentration", new WinGeom(700, 400, 600, 400));
OrderView order_view_flow("Orders - flow", new WinGeom(700, 350, 600, 400));
OrderView order_view_conc("Orders - concentration", new WinGeom(700, 700, 600, 400));
// Initialize refinement selector.
L2ProjBasedSelector<double> l2selector_flow(CAND_LIST_FLOW, CONV_EXP, MAX_P_ORDER);
L2ProjBasedSelector<double> l2selector_concentration(CAND_LIST_CONCENTRATION, CONV_EXP, MAX_P_ORDER);
// Set up CFL calculation class.
CFLCalculation CFL(CFL_NUMBER, KAPPA);
// Set up Advection-Diffusion-Equation stability calculation class.
ADEStabilityCalculation ADES(ADVECTION_STABILITY_CONSTANT, DIFFUSION_STABILITY_CONSTANT, EPSILON);
int iteration = 0; double t = 0; time_step_after_adaptivity = time_step_n;
for(t = 0.0; t < 10.0; t += time_step_after_adaptivity)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
time_step_n = time_step_after_adaptivity;
// After some initial runs, begin really adapting.
if(iteration == ERR_STOP_REDUCE_TIME_STEP)
{
ERR_STOP_INIT_FLOW = ERR_STOP_FLOW;
ERR_STOP_INIT_CONCENTRATION = ERR_STOP_CONCENTRATION;
}
// Periodic global derefinements.
if ((iteration > 1 && iteration % UNREF_FREQ == 0 && (REFINEMENT_COUNT_FLOW > 0 || REFINEMENT_COUNT_CONCENTRATION > 0)) || FORCE_UNREF)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
if(REFINEMENT_COUNT_FLOW > 0)
{
REFINEMENT_COUNT_FLOW = 0;
space_rho.unrefine_all_mesh_elements();
if(CAND_LIST_FLOW == H2D_HP_ANISO)
{
space_rho.adjust_element_order(-1, P_INIT_FLOW);
space_rho_v_x.adjust_element_order(-1, P_INIT_FLOW);
space_rho_v_y.adjust_element_order(-1, P_INIT_FLOW);
space_e.adjust_element_order(-1, P_INIT_FLOW);
}
}
if(REFINEMENT_COUNT_CONCENTRATION > 0)
{
REFINEMENT_COUNT_CONCENTRATION = 0;
space_c.unrefine_all_mesh_elements();
space_c.adjust_element_order(-1, P_INIT_CONCENTRATION);
}
}
// 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.
int order_increase = 0;
if(CAND_LIST_FLOW == H2D_HP_ANISO)
order_increase = 1;
Mesh::ReferenceMeshCreator refMeshCreatorFlow(mesh_flow);
MeshSharedPtr ref_mesh_flow = refMeshCreatorFlow.create_ref_mesh();
Mesh::ReferenceMeshCreator refMeshCreatorConcentration(mesh_concentration);
MeshSharedPtr ref_mesh_concentration = refMeshCreatorConcentration.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorRho(&space_rho, mesh_flow);
SpaceSharedPtr<double>* ref_space_rho = refSpaceCreatorRho.create_ref_space(new Space<double>());
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVx(&space_rho_v_x, mesh_flow);
SpaceSharedPtr<double>* ref_space_rho_v_x = refSpaceCreatorRhoVx.create_ref_space(new Space<double>());
Space<double>::ReferenceSpaceCreator refSpaceCreatorRhoVy(&space_rho_v_y, mesh_flow);
SpaceSharedPtr<double>* ref_space_rho_v_y = refSpaceCreatorRhoVy.create_ref_space(new Space<double>());
Space<double>::ReferenceSpaceCreator refSpaceCreatorE(&space_e, mesh_flow);
SpaceSharedPtr<double>* ref_space_e = refSpaceCreatorE.create_ref_space(new Space<double>());
Space<double>::ReferenceSpaceCreator refSpaceCreatorConcentration(&space_c, mesh_concentration);
SpaceSharedPtr<double>* ref_space_c = refSpaceCreatorConcentration.create_ref_space();
char filename[40];
sprintf(filename, "Flow-mesh-%i-%i.xml", iteration - 1, as - 1);
mloader.save(filename, ref_space_rho->get_mesh());
sprintf(filename, "Concentration-mesh-%i-%i.xml", iteration - 1, as - 1);
mloader.save(filename, ref_space_c->get_mesh());
Space<double>* ref_space_stabilization = refSpaceCreatorRho.create_ref_space();
ref_space_stabilization->set_uniform_order(0);
if(CAND_LIST_FLOW != H2D_HP_ANISO)
ref_space_c->adjust_element_order(new Space<double>(+1, P_INIT_CONCENTRATION));
std::vector<const Space<double> *> ref_spaces(ref_space_rho, ref_space_rho_v_x,
ref_space_rho_v_y, ref_space_e, ref_space_c);
// 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_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c},
std::vector<Solution<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c));
ogProjection.project_global(ref_space_stabilization, &prev_rho, &prev_rho_stabilization);
// Report NDOFs.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d.",
Space<double>::get_num_dofs({&space_rho, &space_rho_v_x,
space_rho_v_y, &space_e, &space_c}), Space<double>::get_num_dofs(ref_spaces));
// Very important, set the meshes for the flow as the same.
ref_space_rho_v_x->get_mesh()->set_seq(ref_space_rho->get_mesh()->get_seq());
ref_space_rho_v_y->get_mesh()->set_seq(ref_space_rho->get_mesh()->get_seq());
ref_space_e->get_mesh()->set_seq(ref_space_rho->get_mesh()->get_seq());
// 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);
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, ref_spaces);
DiscreteProblem<double> dp_stabilization(wf_stabilization, ref_space_stabilization);
bool* discreteIndicator = NULL;
if(SEMI_IMPLICIT)
{
static_cast<EulerEquationsWeakFormSemiImplicitCoupled*>(wf)->set_current_time_step(time_step_n);
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
{
Hermes::Mixins::Loggable::Static::info("Assembling the stabilization right-hand side vector.");
dp_stabilization.assemble(rhs_stabilization);
if(discreteIndicator != NULL)
delete [] discreteIndicator;
discreteIndicator = new bool[ref_space_stabilization->get_mesh()->get_max_element_id() + 1];
for(unsigned int i = 0; i < ref_space_stabilization->get_mesh()->get_max_element_id() + 1; i++)
discreteIndicator[i] = false;
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)
discreteIndicator[e->id] = true;
}
static_cast<EulerEquationsWeakFormSemiImplicitCoupled*>(wf)->set_discreteIndicator(discreteIndicator, ref_space_stabilization->get_mesh()->get_max_element_id() + 1);
}
}
else
static_cast<EulerEquationsWeakFormExplicitCoupled*>(wf)->set_current_time_step(time_step_n);
// Assemble 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.");
FluxLimiter* flux_limiter;
if(solver->solve())
{
if(!SHOCK_CAPTURING || SHOCK_CAPTURING_TYPE == FEISTAUER)
{
Solution<double>::vector_to_solutions(solver->get_sln_vector(), ref_spaces,
std::vector<Solution<double>*>(&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e, &rsln_c));
SpaceSharedPtr<double>*> flow_spaces(new }
else
{
std::vector<const Space<double>(ref_space_rho, ref_space_rho_v_x, ref_space_rho_v_y, ref_space_e));
double* flow_solution_vector = new double[Space<double>::get_num_dofs(flow_spaces)];
OGProjection<double>::project_global(flow_spaces,{&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e}, flow_solution_vector);
if(SHOCK_CAPTURING_TYPE == KUZMIN)
flux_limiter = new FluxLimiter(FluxLimiter::Kuzmin, flow_solution_vector, flow_spaces);
else
flux_limiter = new FluxLimiter(FluxLimiter::Krivodonova, flow_solution_vector, flow_spaces);
flux_limiter->get_limited_solutions({&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e});
}
}
else
throw Hermes::Exceptions::Exception("Matrix solver failed.\n");
Mach_number.reinit();
char filenamea[40];
Linearizer lin_mach;
sprintf(filenamea, "Mach number-3D-%i-%i.vtk", iteration - 1, as);
lin_mach.save_solution_vtk(Mach_number, filenamea, "MachNumber", true);
Linearizer lin_concentration;
sprintf(filenamea, "Concentration-%i-%i.vtk", iteration - 1, as);
lin_concentration.save_solution_vtk(prev_c, filenamea, "Concentration", true);
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
ogProjection.project_global({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e, &space_c},{&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e, &rsln_c},
std::vector<Solution<double>*>(sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e, sln_c),
std::vector<NormType>(HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM));
util_time_step = time_step_n;
if(SEMI_IMPLICIT)
CFL.calculate_semi_implicit({rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e}, const_cast<MeshSharedPtr>(rsln_rho.get_mesh()), util_time_step);
else
CFL.calculate({rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e}, const_cast<MeshSharedPtr>(rsln_rho.get_mesh()), util_time_step);
time_step_after_adaptivity = util_time_step;
ADES.calculate({rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y}, const_cast<MeshSharedPtr>(rsln_rho.get_mesh()), util_time_step);
if(time_step_after_adaptivity > util_time_step)
time_step_after_adaptivity = util_time_step;
ADES.calculate({rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y}, const_cast<MeshSharedPtr>(rsln_c.get_mesh()), util_time_step);
if(time_step_after_adaptivity > util_time_step)
time_step_after_adaptivity = util_time_step;
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimates.");
Adapt<double> adaptivity_flow({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e},{HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM, HERMES_L2_NORM});
double err_est_rel_total_flow = adaptivity_flow.calc_err_est({sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e},
std::vector<Solution<double>*>(&rsln_rho, &rsln_rho_v_x, &rsln_rho_v_y, &rsln_e)) * 100;
Adapt<double> adaptivity_concentration(&space_c, HERMES_L2_NORM);
double err_est_rel_total_concentration = adaptivity_concentration.calc_err_est(sln_c, &rsln_c) * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("Error estimate for the flow part: %g%%", err_est_rel_total_flow);
Hermes::Mixins::Loggable::Static::info("Error estimate for the concentration part: %g%%", err_est_rel_total_concentration);
// If err_est too large, adapt the mesh.
if (err_est_rel_total_flow < ERR_STOP_INIT_FLOW && err_est_rel_total_concentration < ERR_STOP_INIT_CONCENTRATION)
{
done = true;
if(SHOCK_CAPTURING && (SHOCK_CAPTURING_TYPE == KUZMIN || SHOCK_CAPTURING_TYPE == KRIVODONOVA))
{
if(SHOCK_CAPTURING_TYPE == KUZMIN)
flux_limiter->limit_second_orders_according_to_detector();
flux_limiter->limit_according_to_detector();
}
}
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse meshes.");
if(err_est_rel_total_flow > ERR_STOP_INIT_FLOW)
{
done = adaptivity_flow.adapt({&l2selector_flow, &l2selector_flow, &l2selector_flow, &l2selector_flow},
THRESHOLD, STRATEGY, MESH_REGULARITY);
REFINEMENT_COUNT_FLOW++;
}
else
done = true;
if(err_est_rel_total_concentration > ERR_STOP_INIT_CONCENTRATION)
{
if(!adaptivity_concentration.adapt(&l2selector_concentration, THRESHOLD, STRATEGY, MESH_REGULARITY))
done = false;
REFINEMENT_COUNT_CONCENTRATION++;
}
if (Space<double>::get_num_dofs({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e, &space_c}) >= NDOF_STOP)
{
done = true;
Hermes::Mixins::Loggable::Static::info("Maximum number of dofs of the coarse meshes, %i, has been reached, adaptivity loop ends.", Space<double>::get_num_dofs({&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e, &space_c}));
FORCE_UNREF = true;
}
else
// Increase the counter of performed adaptivity steps.
as++;
}
// Clean up.
delete solver;
delete matrix;
delete rhs;
}
while (done == false && as < 5);
// 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);
prev_c.copy(&rsln_c);
// Visualization.
if((iteration - 1) % EVERY_NTH_STEP == 0)
{
// Hermes visualization.
if(HERMES_VISUALIZATION)
{
Mach_number.reinit();
pressure.reinit();
pressure_view.show_mesh(false);
pressure_view.show(&pressure);
pressure_view.set_scale_format("%1.3f");
Mach_number_view.show_mesh(false);
Mach_number_view.set_scale_format("%1.3f");
Mach_number_view.show(&Mach_number);
s5.show_mesh(false);
s5.set_scale_format("%0.3f");
s5.show(&prev_c);
pressure_view.save_numbered_screenshot("pressure%i.bmp", (int)(iteration / 5), true);
Mach_number_view.save_numbered_screenshot("Mach_number%i.bmp", (int)(iteration / 5), true);
s5.save_numbered_screenshot("concentration%i.bmp", (int)(iteration / 5), true);
}
// Output solution in VTK format.
if(VTK_VISUALIZATION)
{
}
}
}
/*
pressure_view.close();
entropy_production_view.close();
Mach_number_view.close();
s5.close();
*/
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/gamm-channel/main.cpp | .cpp | 3,377 | 102 | #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
// Discontinuous Galerkin method of higher order with no adaptivity.
//
// Equations: Compressible Euler equations, perfect gas state equation.
//
// Domain: GAMM channel, see mesh file GAMM-channel.mesh
//
// BC: Solid walls, inlet, outlet.
//
// IC: Constant state identical to inlet.
//
// 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 = 100;
// 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.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 4;
// CFL value.
double CFL_NUMBER = 0.8;
// Initial time step.
double time_step_n = 1E-6;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 2.5;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 1.25;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
double TIME_INTERVAL_LENGTH = 20.;
// Mesh filename.
const std::string MESH_FILENAME = "GAMM-channel.mesh";
// Boundary markers.
const std::string BDY_INLET = "1";
const std::string BDY_OUTLET = "2";
const std::string BDY_SOLID_WALL_BOTTOM = "3";
const std::string BDY_SOLID_WALL_TOP = "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. Insert problem-specific data
// 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)));
std::vector<MeshFunctionSharedPtr<double> > prev_slns({ prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e });
// Initialize boundary conditions.
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 });
// Weak formulation.
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)));
#pragma endregion
#include "../euler-time-loop.cpp"
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/reflected-shock-adapt/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-adapt/main.cpp | .cpp | 8,084 | 208 | #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 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 = 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 = 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.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// CFL value.
double CFL_NUMBER = 0.3;
// 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 = 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 = 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_H_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)
{
return 0.02;
}
// Equation parameters.
const double KAPPA = 1.4;
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;
// Mesh filename.
const std::string 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[])
{
#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, new L2ShapesetTaylor));
SpaceSharedPtr<double> space_rho_v_x(new L2Space<double>(mesh, P_INIT, new L2ShapesetTaylor));
SpaceSharedPtr<double> space_rho_v_y(new L2Space<double>(mesh, P_INIT, new L2ShapesetTaylor));
SpaceSharedPtr<double> space_e(new L2Space<double>(mesh, P_INIT, new L2ShapesetTaylor));
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
// 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)));
// Initialize weak formulation.
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 });
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));
#include "../euler-time-loop-space-adapt.cpp"
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/reflected-shock-adapt/definitions.cpp | .cpp | 0 | 0 | null | C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/joukowski-profile/main.cpp | .cpp | 10,988 | 279 | #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: Joukowski profile, see file domain-nurbs.xml.
//
// BC: Solid walls, inlet, 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;
// For saving/loading of solution.
bool REUSE_SOLUTION = true;
// Initial polynomial degree.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM_VERTEX = 2;
// Number of initial mesh refinements towards the profile.
const int INIT_REF_NUM_BOUNDARY_ANISO = 6;
// CFL value.
double CFL_NUMBER = 0.1;
// Initial time step.
double time_step_n = 1E-6;
// Initial time step.
double time_step_n_minus_one = 1E-6;
// Matrix solver for orthogonal projections:
// SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
MatrixSolverType matrix_solver = SOLVER_UMFPACK;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 7142.8571428571428571428571428571;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 0.01;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
// Boundary markers.
const std::string BDY_INLET = "Inlet";
const std::string BDY_OUTLET = "Outlet";
const std::string BDY_SOLID_WALL_PROFILE = "Solid Profile";
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[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2DXML mloader;
mloader.load("domain-arcs.xml", mesh);
mesh->refine_towards_boundary(BDY_SOLID_WALL_PROFILE, INIT_REF_NUM_BOUNDARY_ANISO);
mesh->refine_towards_vertex(0, INIT_REF_NUM_VERTEX);
SpaceSharedPtr<double> space_rho(mesh, P_INIT);
L2Space<double> space_rho_v_x(mesh, P_INIT);
L2Space<double> space_rho_v_y(mesh, P_INIT);
L2Space<double> space_e(mesh, P_INIT);
L2Space<double> space_stabilization(new // Initialize boundary condition types and spaces with default shapesets.
L2Space<double>(mesh, 0));
int ndof = Space<double>::get_num_dofs({&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e});
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
// Initialize solutions, set initial conditions.
ConstantSolution<double> prev_rho(mesh, RHO_EXT);
ConstantSolution<double> prev_rho_v_x(mesh, RHO_EXT * V1_EXT);
ConstantSolution<double> prev_rho_v_y(mesh, RHO_EXT * V2_EXT);
ConstantSolution<double> prev_e(mesh, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
// Filters for visualization of Mach number, pressure and entropy.
MachNumberFilter Mach_number({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA);
PressureFilter pressure({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA);
EntropyFilter entropy({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA, RHO_EXT, P_EXT);
ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 300));
ScalarView Mach_number_view("Mach number", new WinGeom(700, 0, 600, 300));
ScalarView entropy_production_view("Entropy estimate", new WinGeom(0, 400, 600, 300));
ScalarView s1("prev_rho", new WinGeom(0, 0, 600, 300));
ScalarView s2("prev_rho_v_x", new WinGeom(700, 0, 600, 300));
ScalarView s3("prev_rho_v_y", new WinGeom(0, 400, 600, 300));
ScalarView s4("prev_e", new WinGeom(700, 400, 600, 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 CFL calculation class.
CFLCalculation CFL(CFL_NUMBER, KAPPA);
// Look for a saved solution on the disk.
CalculationContinuity<double> continuity(CalculationContinuity<double>::onlyTime);
int iteration = 0; double t = 0;
if(REUSE_SOLUTION && continuity.have_record_available())
{
continuity.get_last_record()->load_mesh(mesh);
SpaceSharedPtr<double> *> spaceVector = continuity.get_last_record()->load_spaces(new std::vector<Space<double>({mesh, mesh, mesh, mesh}));
space_rho.copy(spaceVector[0], mesh);
space_rho_v_x.copy(spaceVector[1], mesh);
space_rho_v_y.copy(spaceVector[2], mesh);
space_e.copy(spaceVector[3], mesh);
continuity.get_last_record()->load_solutions({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e},{&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e, &space_rho, &space_rho_v_x, &space_rho_v_y, &space_e});
continuity.get_last_record()->load_time_step_length(time_step_n);
t = continuity.get_last_record()->get_time();
iteration = continuity.get_num();
}
// Initialize weak formulation.
std::vector<std::string> solid_wall_markers(BDY_SOLID_WALL, BDY_SOLID_WALL_PROFILE);
std::vector<std::string> inlet_markers;
inlet_markers.push_back(BDY_INLET);
std::vector<std::string> outlet_markers;
outlet_markers.push_back(BDY_OUTLET);
EulerEquationsWeakFormSemiImplicit 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, (P_INIT == 0));
EulerEquationsWeakFormStabilization wf_stabilization(&prev_rho);
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
wf.set_stabilization(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, NU_1, NU_2);
// Initialize the FE problem.
DiscreteProblem<double> dp(wf,{&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e});
DiscreteProblem<double> dp_stabilization(wf_stabilization, &space_stabilization);
// If the FE problem is in fact a FV problem.
if(P_INIT == 0)
dp.set_fvm();
// Time stepping loop.
for(; t < 5.0; t += time_step_n)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
CFL.set_number(0.1 + (t/2.5) * 1000.0);
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
{
assert(space_stabilization.get_num_dofs() == space_stabilization.get_mesh()->get_num_active_elements());
dp_stabilization.assemble(rhs_stabilization);
bool* discreteIndicator = new bool[space_stabilization.get_num_dofs()];
memset(discreteIndicator, 0, space_stabilization.get_num_dofs() * 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)
discreteIndicator[e->id] = true;
}
wf.set_discreteIndicator(discreteIndicator, space_stabilization.get_num_dofs());
}
// Set the current time step.
wf.set_current_time_step(time_step_n);
// 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.");
if(solver->solve())
{
if(!SHOCK_CAPTURING || SHOCK_CAPTURING_TYPE == FEISTAUER)
{
Solution<double>::vector_to_solutions(solver->get_sln_vector(),{&space_rho, &space_rho_v_x,
&space_rho_v_y, &space_e},{&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e});
}
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});
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});
}
}
else
throw Hermes::Exceptions::Exception("Matrix solver failed.\n");
time_step_n_minus_one = time_step_n;
CFL.calculate_semi_implicit({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, mesh, time_step_n);
// Visualization.
if((iteration - 1) % EVERY_NTH_STEP == 0)
{
// Hermes visualization.
if(HERMES_VISUALIZATION)
{
Mach_number.reinit();
pressure.reinit();
entropy.reinit();
pressure_view.show(&pressure);
entropy_production_view.show(&entropy);
Mach_number_view.show(&Mach_number);
pressure_view.save_numbered_screenshot("Pressure-%u.bmp", iteration - 1, true);
Mach_number_view.save_numbered_screenshot("Mach-%u.bmp", iteration - 1, true);
}
// Output solution in VTK format.
if(VTK_VISUALIZATION)
{
pressure.reinit();
Mach_number.reinit();
Linearizer lin_pressure;
char filename[40];
sprintf(filename, "pressure-3D-%i.vtk", iteration - 1);
lin_pressure.save_solution_vtk(pressure, filename, "Pressure", true);
Linearizer lin_mach;
sprintf(filename, "Mach number-3D-%i.vtk", iteration - 1);
lin_mach.save_solution_vtk(Mach_number, filename, "MachNumber", true);
}
}
}
pressure_view.close();
entropy_production_view.close();
Mach_number_view.close();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/euler/gamm-channel-adapt/main.cpp | .cpp | 4,055 | 123 | #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: GAMM channel, see mesh file GAMM-channel.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 = 2;
// CFL value.
double CFL_NUMBER = 0.3;
// Initial time step.
double time_step_n = 1E-6;
// 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_H_ISO;
// Stopping criterion for adaptivity.
double adaptivityErrorStop(int iteration)
{
return 0.007;
}
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 2.5;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 1.25;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
double TIME_INTERVAL_LENGTH = 20.;
// Mesh filename.
const std::string MESH_FILENAME = "GAMM-channel.mesh";
// Boundary markers.
const std::string BDY_INLET = "1";
const std::string BDY_OUTLET = "2";
const std::string BDY_SOLID_WALL_BOTTOM = "3";
const std::string BDY_SOLID_WALL_TOP = "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/euler-coupled/main.cpp | .cpp | 13,364 | 332 | #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 coupled with an advection-diffution equation
// using a basic piecewise-constant finite volume method for the flow and continuous FEM for the concentration
// being advected by the flow.
//
// Equations: Compressible Euler equations, perfect gas state equation, advection-diffusion equation.
//
// Domains: Various
//
// BC: Various.
//
// IC: Various.
//
// The following parameters can be changed:
// Semi-implicit scheme.
const bool SEMI_IMPLICIT = true;
// Visualization.
// Set to "true" to enable Hermes OpenGL visualization.
const bool HERMES_VISUALIZATION = false;
// 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;
// Stability for the concentration part.
double ADVECTION_STABILITY_CONSTANT = 0.05;
const double DIFFUSION_STABILITY_CONSTANT = 0.1;
// Polynomial degree for the Euler equations (for the flow).
const int P_FLOW = 1;
// Polynomial degree for the concentration.
const int P_CONCENTRATION = 2;
// CFL value.
double CFL_NUMBER = 0.1;
// Initial and utility time step.
double time_step_n = 1E-5, util_time_step;
// Matrix solver for orthogonal projections: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
MatrixSolverType matrix_solver = SOLVER_UMFPACK;
// Number of initial uniform mesh refinements of the mesh for the flow.
unsigned int INIT_REF_NUM_FLOW = 3;
// Number of initial uniform mesh refinements of the mesh for the concentration.
unsigned int INIT_REF_NUM_CONCENTRATION = 3;
// Number of initial mesh refinements of the mesh for the concentration towards the
// part of the boundary where the concentration is prescribed.
unsigned int INIT_REF_NUM_CONCENTRATION_BDY = 1;
// Equation parameters.
// Exterior pressure (dimensionless).
const double P_EXT = 2.5;
// Inlet density (dimensionless).
const double RHO_EXT = 1.0;
// Inlet x-velocity (dimensionless).
const double V1_EXT = 1.0;
// Inlet y-velocity (dimensionless).
const double V2_EXT = 0.0;
// Kappa.
const double KAPPA = 1.4;
// Concentration on the boundary.
const double CONCENTRATION_EXT = 0.1;
// Start time of the concentration on the boundary.
const double CONCENTRATION_EXT_STARTUP_TIME = 0.0;
// Diffusivity.
const double EPSILON = 0.01;
// Boundary markers.
const std::string BDY_INLET = "1";
const std::string BDY_OUTLET = "2";
const std::string BDY_SOLID_WALL_BOTTOM = "3";
const std::string BDY_SOLID_WALL_TOP = "4";
const std::string BDY_DIRICHLET_CONCENTRATION = "3";
// Weak forms.
#include "../forms_explicit.cpp"
// Initial condition.
#include "../initial_condition.cpp"
int main(int argc, char* argv[])
{
std::vector<std::string> BDY_NATURAL_CONCENTRATION;
BDY_NATURAL_CONCENTRATION.push_back("2");
// Load the mesh.
Mesh basemesh;
MeshReaderH2D mloader;
mloader.load("GAMM-channel-serial.mesh", &basemesh);
// Initialize the meshes.
MeshSharedPtr mesh_flow, mesh_concentration;
mesh_flow.copy(&basemesh);
mesh_concentration.copy(&basemesh);
for(unsigned int i = 0; i < INIT_REF_NUM_CONCENTRATION; i++)
mesh_concentration.refine_all_elements(0, true);
mesh_concentration.refine_towards_boundary(BDY_DIRICHLET_CONCENTRATION, INIT_REF_NUM_CONCENTRATION_BDY, false);
//mesh_flow.refine_towards_boundary(BDY_DIRICHLET_CONCENTRATION, INIT_REF_NUM_CONCENTRATION_BDY);
for(unsigned int i = 0; i < INIT_REF_NUM_FLOW; i++)
mesh_flow.refine_all_elements(0, true);
// Initialize boundary condition types and spaces with default shapesets.
// For the concentration.
EssentialBCs<double> bcs_concentration;
bcs_concentration.add_boundary_condition(new ConcentrationTimedepEssentialBC(BDY_DIRICHLET_CONCENTRATION, CONCENTRATION_EXT, CONCENTRATION_EXT_STARTUP_TIME));
bcs_concentration.add_boundary_condition(new ConcentrationTimedepEssentialBC(BDY_SOLID_WALL_TOP, 0.0, CONCENTRATION_EXT_STARTUP_TIME));
bcs_concentration.add_boundary_condition(new ConcentrationTimedepEssentialBC(BDY_INLET, 0.0, CONCENTRATION_EXT_STARTUP_TIME));
SpaceSharedPtr<double>space_rho(mesh_flow, P_FLOW);
L2Space<double>space_rho_v_x(mesh_flow, P_FLOW);
L2Space<double>space_rho_v_y(mesh_flow, P_FLOW);
L2Space<double>space_e(mesh_flow, P_FLOW);
L2Space<double> space_stabilization(mesh_flow, 0);
// Space<double> for concentration.
H1Space<double> space_c(new L2Space<double>(mesh_concentration, &bcs_concentration, P_CONCENTRATION));
int ndof = Space<double>::get_num_dofs({&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e, &space_c});
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
// Initialize solutions, set initial conditions.
ConstantSolution<double> sln_rho(mesh_flow, RHO_EXT);
ConstantSolution<double> sln_rho_v_x(mesh_flow, RHO_EXT * V1_EXT);
ConstantSolution<double> sln_rho_v_y(mesh_flow, RHO_EXT * V2_EXT);
ConstantSolution<double> sln_e(mesh_flow, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
ConstantSolution<double> sln_c(mesh_concentration, 0.0);
ConstantSolution<double> prev_rho(mesh_flow, RHO_EXT);
ConstantSolution<double> prev_rho_v_x(mesh_flow, RHO_EXT * V1_EXT);
ConstantSolution<double> prev_rho_v_y(mesh_flow, RHO_EXT * V2_EXT);
ConstantSolution<double> prev_e(mesh_flow, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA));
ConstantSolution<double> prev_c(mesh_concentration, 0.0);
// Initialize weak formulation.
WeakForm<double>* wf = NULL;
if(SEMI_IMPLICIT)
{
wf = new EulerEquationsWeakFormSemiImplicitCoupled(KAPPA, RHO_EXT, V1_EXT, V2_EXT, P_EXT, BDY_SOLID_WALL_BOTTOM,
BDY_SOLID_WALL_TOP, BDY_INLET, BDY_OUTLET, BDY_NATURAL_CONCENTRATION, &prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c, EPSILON, P_FLOW == 0);
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
static_cast<EulerEquationsWeakFormSemiImplicitCoupled*>(wf)->set_stabilization(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, NU_1, NU_2);
}
else
wf = new EulerEquationsWeakFormExplicitCoupled(KAPPA, RHO_EXT, V1_EXT, V2_EXT, P_EXT, BDY_SOLID_WALL_BOTTOM,
BDY_SOLID_WALL_TOP, BDY_INLET, BDY_OUTLET, BDY_NATURAL_CONCENTRATION, &prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, &prev_c, EPSILON, P_FLOW == 0);
EulerEquationsWeakFormStabilization wf_stabilization(&prev_rho);
// Initialize the FE problem.
DiscreteProblem<double> dp(wf,{&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e, &space_c});
DiscreteProblem<double> dp_stabilization(wf_stabilization, &space_stabilization);
bool* discreteIndicator = NULL;
// Filters for visualization of Mach number, pressure and entropy.
MachNumberFilter Mach_number({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA);
PressureFilter pressure({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA);
EntropyFilter entropy({&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e}, KAPPA, RHO_EXT, P_EXT);
ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 400));
ScalarView Mach_number_view("Mach number", new WinGeom(700, 0, 600, 400));
ScalarView s5("Concentration", new WinGeom(700, 400, 600, 400));
// 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 CFL calculation class.
CFLCalculation CFL(CFL_NUMBER, KAPPA);
// Set up Advection-Diffusion-Equation stability calculation class.
ADEStabilityCalculation ADES(ADVECTION_STABILITY_CONSTANT, DIFFUSION_STABILITY_CONSTANT, EPSILON);
int iteration = 0; double t = 0;
for(t = 0.0; t < 100.0; t += time_step_n)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f.", iteration++, t);
if(SEMI_IMPLICIT)
{
static_cast<EulerEquationsWeakFormSemiImplicitCoupled*>(wf)->set_current_time_step(time_step_n);
if(SHOCK_CAPTURING && SHOCK_CAPTURING_TYPE == FEISTAUER)
{
dp_stabilization.assemble(rhs_stabilization);
if(discreteIndicator != NULL)
delete [] discreteIndicator;
discreteIndicator = new bool[space_stabilization.get_mesh()->get_max_element_id() + 1];
for(unsigned int i = 0; i < space_stabilization.get_mesh()->get_max_element_id() + 1; i++)
discreteIndicator[i] = false;
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)
discreteIndicator[e->id] = true;
}
static_cast<EulerEquationsWeakFormSemiImplicitCoupled*>(wf)->set_discreteIndicator(discreteIndicator, space_stabilization.get_num_dofs());
}
}
else
static_cast<EulerEquationsWeakFormExplicitCoupled*>(wf)->set_current_time_step(time_step_n);
// Assemble stiffness matrix and rhs.
Hermes::Mixins::Loggable::Static::info("Assembling the stiffness matrix and right-hand side vector.");
try
{
dp.assemble(matrix, rhs);
}
catch(std::exception& e)
{
std::cout << e.what();
return -1;
}
// Solve the matrix problem.
Hermes::Mixins::Loggable::Static::info("Solving the matrix problem.");
if(solver->solve())
{
if(!SHOCK_CAPTURING || SHOCK_CAPTURING_TYPE == FEISTAUER)
{
Solution<double>::vector_to_solutions(solver->get_sln_vector(),{&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e, &space_c},
std::vector<Solution<double>*>(sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e, sln_c));
}
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});
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});
}
}
else
throw Hermes::Exceptions::Exception("Matrix solver failed.\n");
util_time_step = time_step_n;
if(SEMI_IMPLICIT)
CFL.calculate_semi_implicit({sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e}, mesh_flow, util_time_step);
else
CFL.calculate({sln_rho, sln_rho_v_x, sln_rho_v_y, sln_e}, mesh_flow, util_time_step);
time_step_n = util_time_step;
ADES.calculate({sln_rho, sln_rho_v_x, sln_rho_v_y}, mesh_concentration, util_time_step);
if(util_time_step < time_step_n)
time_step_n = util_time_step;
ADES.calculate({sln_rho, sln_rho_v_x, sln_rho_v_y}, mesh_flow, util_time_step);
if(util_time_step < time_step_n)
time_step_n = util_time_step;
// Copy the solutions into the previous time level ones.
prev_rho.copy(sln_rho);
prev_rho_v_x.copy(sln_rho_v_x);
prev_rho_v_y.copy(sln_rho_v_y);
prev_e.copy(sln_e);
prev_c.copy(sln_c);
// Visualization.
if((iteration - 1) % EVERY_NTH_STEP == 0)
{
// Hermes visualization.
if(HERMES_VISUALIZATION)
{
Mach_number.reinit();
Mach_number_view.show(&Mach_number);
Mach_number_view.save_numbered_screenshot("Mach_number%i.bmp", (int)(iteration / 5), true);
s5.show(&prev_c);
s5.save_numbered_screenshot("concentration%i.bmp", (int)(iteration / 5), true);
}
// Output solution in VTK format.
if(VTK_VISUALIZATION)
{
pressure.reinit();
Mach_number.reinit();
Linearizer lin_pressure;
char filename[40];
sprintf(filename, "pressure-3D-%i.vtk", iteration - 1);
lin_pressure.save_solution_vtk(pressure, filename, "Pressure", true);
Linearizer lin_mach;
sprintf(filename, "Mach number-3D-%i.vtk", iteration - 1);
lin_mach.save_solution_vtk(Mach_number, filename, "MachNumber", true);
Linearizer lin_concentration;
sprintf(filename, "Concentration-%i.vtk", iteration - 1);
lin_concentration.save_solution_vtk(prev_c, filename, "Concentration", true);
}
}
}
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/elasticity/crack/definitions.h | .h | 520 | 17 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::RefinementSelectors;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::WeakFormsElasticity;
using namespace Hermes::Hermes2D::Views;
using namespace RefinementSelectors;
class CustomWeakFormLinearElasticity : public WeakForm <double>
{
public:
CustomWeakFormLinearElasticity(double E, double nu, double rho_g,
std::string surface_force_bdy, double f0, double f1);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/elasticity/crack/main.cpp | .cpp | 11,558 | 282 | #include "definitions.h"
// This example uses adaptive multimesh hp-FEM to solve a simple problem
// of linear elasticity. Note that since both displacement components
// have similar qualitative behavior, the advantage of the multimesh
// discretization is less striking.
//
// PDE: Lame equations of linear elasticity. No external forces, the
// object is loaded with its own weight.
//
// BC: u_1 = u_2 = 0 on Gamma_1 (left edge)
// du_1/dn = du_2/dn = 0 elsewhere, including two horizontal
// cracks inside the domain. The width of the cracks
// is currently zero, it can be set in the mesh file
// via the parameter 'w'.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 0;
// Initial polynomial degree of mesh elements (u-displacement).
const int P_INIT_U1 = 2;
// Initial polynomial degree of mesh elements (v-displacement).
const int P_INIT_U2 = 2;
// true = use multi-mesh, 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;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD_MULTI = 0.35;
const double THRESHOLD_SINGLE = 0.7;
// 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;
// This parameter influences the selection of
// candidates in hp-adaptivity. Default value is 1.0.
const double CONV_EXP = 1.0;
// Stopping criterion for adaptivity.
const double ERR_STOP = 0.0001;
// Adaptivity process stops when the number of degrees of freedom grows.
const int NDOF_STOP = 60000;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-6;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 100;
// Matrix solver: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
MatrixSolverType matrix_solver = SOLVER_UMFPACK;
// Problem parameters.
// Young modulus for steel: 200 GPa.
const double E = 200e9;
// Poisson ratio.
const double nu = 0.3;
// Gravitational acceleration.
const double g1 = -9.81;
// Material density in kg / m^3.
const double rho = 8000;
// Top surface force in x-direction.
const double f0 = 0;
// Top surface force in y-direction.
const double f1 = 0;
int main(int argc, char* argv[])
{
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Load the mesh->
MeshSharedPtr u1_mesh(new Mesh), u2_mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", u1_mesh);
// Perform initial uniform mesh refinement.
for (int i = 0; i < INIT_REF_NUM; i++) u1_mesh->refine_all_elements();
// Create initial mesh for the vertical displacement component.
// This also initializes the multimesh hp-FEM.
u2_mesh->copy(u1_mesh);
// Initialize boundary conditions.
DefaultEssentialBCConst<double> zero_disp("bdy left", 0.0);
EssentialBCs<double> bcs(&zero_disp);
// Create x- and y- displacement space using the default H1 shapeset.
SpaceSharedPtr<double> u1_space(new H1Space<double>(u1_mesh, &bcs, P_INIT_U1));
SpaceSharedPtr<double> u2_space(new H1Space<double>(u2_mesh, &bcs, P_INIT_U2));
Hermes::Mixins::Loggable::Static::info("ndof = %d.", Space<double>::get_num_dofs({u1_space, u2_space}));
// Initialize the weak formulation.
// NOTE; These weak forms are identical to those in example P01-linear/08-system.
CustomWeakFormLinearElasticity wf(E, nu, rho*g1, "bdy rest", f0, f1);
// Initialize the FE problem.
std::vector<SpaceSharedPtr<double> > spaces(u1_space, u2_space);
DiscreteProblem<double> dp(wf, spaces);
// Initialize coarse and reference mesh solutions.
MeshFunctionSharedPtr<double> u1_sln(new Solution<double>), u2_sln(new Solution<double>);
MeshFunctionSharedPtr<double> u1_sln_ref(new Solution<double>), u2_sln_ref(new Solution<double>);
// Initialize refinement selector.
// Error calculation.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 2);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(0.75);
// Adaptivity processor class.
Adapt<double> adaptivity({u1_space, u2_space}, &errorCalculator, &stoppingCriterion);
// Element refinement type refinement_selector.
H1ProjBasedSelector<double> refinement_selector(CAND_LIST);
// Initialize views.
ScalarView s_view_0("Solution (x-displacement)", new WinGeom(0, 0, 700, 150));
s_view_0.show_mesh(false);
ScalarView s_view_1("Solution (y-displacement)", new WinGeom(0, 180, 700, 150));
s_view_1.show_mesh(false);
OrderView o_view_0("Mesh (x-displacement)", new WinGeom(0, 360, 700, 150));
OrderView o_view_1("Mesh (y-displacement)", new WinGeom(0, 540, 700, 150));
ScalarView mises_view("Von Mises stress [Pa]", new WinGeom(300, 405, 700, 250));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est;
// 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 refMeshCreator1(u1_mesh);
MeshSharedPtr ref_u1_mesh = refMeshCreator1.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator1(u1_space, ref_u1_mesh);
SpaceSharedPtr<double> ref_u1_space = refSpaceCreator1.create_ref_space();
Mesh::ReferenceMeshCreator refMeshCreator2(u2_mesh);
MeshSharedPtr ref_u2_mesh = refMeshCreator2.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator2(u2_space, ref_u2_mesh);
SpaceSharedPtr<double> ref_u2_space = refSpaceCreator2.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces(ref_u1_space, ref_u2_space);
int ndof_ref = Space<double>::get_num_dofs(ref_spaces);
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, ref_spaces);
// Initialize Newton solver.
NewtonSolver<double> newton(&dp);
newton.set_verbose_output(true);
// Time measurement.
cpu_time.tick();
// Perform Newton's iteration.
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh->");
try
{
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
}
// Time measurement.
cpu_time.tick();
// Translate the resulting coefficient vector into the Solution sln->
Solution<double>::vector_to_solutions(newton.get_sln_vector(), ref_spaces,
std::vector<MeshFunctionSharedPtr<double> >(u1_sln_ref, u2_sln_ref));
// Project the fine mesh solution onto the coarse mesh->
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh->");
OGProjection<double> ogProjection; ogProjection.project_global({u1_space, u2_space},
std::vector<MeshFunctionSharedPtr<double> >(u1_sln_ref, u2_sln_ref),
std::vector<MeshFunctionSharedPtr<double> >(u1_sln, u2_sln));
// View the coarse mesh solution and polynomial orders.
s_view_0.show(u1_sln);
o_view_0.show(u1_space);
s_view_1.show(u2_sln);
o_view_1.show(u2_space);
// For von Mises stress Filter.
double lambda = (E * nu) / ((1 + nu) * (1 - 2 * nu));
double mu = E / (2 * (1 + nu));
MeshFunctionSharedPtr<double> stress(new VonMisesFilter({u1_sln, u2_sln}, lambda, mu));
mises_view.show(stress, H2D_FN_VAL_0, u1_sln, u2_sln, 1e3);
// Skip visualization time.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
/*
// Register custom forms for error calculation.
errorCalculator.add_error_form(0, 0, bilinear_form_0_0<double, double>, bilinear_form_0_0<Ord, Ord>);
errorCalculator.add_error_form(0, 1, bilinear_form_0_1<double, double>, bilinear_form_0_1<Ord, Ord>);
errorCalculator.add_error_form(1, 0, bilinear_form_1_0<double, double>, bilinear_form_1_0<Ord, Ord>);
errorCalculator.add_error_form(1, 1, bilinear_form_1_1<double, double>, bilinear_form_1_1<Ord, Ord>);
*/
// Calculate error estimate for each solution component and the total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
std::vector<double> err_est_rel;
errorCalculator.calculate_errors({u1_sln, u2_sln},
std::vector<MeshFunctionSharedPtr<double> >(u1_sln_ref, u2_sln_ref));
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Time measurement.
cpu_time.tick();
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse_total: %d, ndof_fine_total: %d, err_est_rel_total: %g%%",
Space<double>::get_num_dofs({u1_space, u2_space}),
Space<double>::get_num_dofs(ref_spaces), err_est_rel_total);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(Space<double>::get_num_dofs({u1_space, u2_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");
// 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({&refinement_selector, &refinement_selector});
}
if (Space<double>::get_num_dofs({u1_space, u2_space}) >= NDOF_STOP) done = true;
// Increase counter.
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Show the reference solution - the final result.
s_view_0.set_title("Fine mesh solution (x-displacement)");
s_view_0.show(u1_sln_ref);
s_view_1.set_title("Fine mesh solution (y-displacement)");
s_view_1.show(u2_sln_ref);
// For von Mises stress Filter.
double lambda = (E * nu) / ((1 + nu) * (1 - 2 * nu));
double mu = E / (2 * (1 + nu));
MeshFunctionSharedPtr<double> stress(new VonMisesFilter({u1_sln_ref, u2_sln_ref}, lambda, mu));
mises_view.show(stress, H2D_FN_VAL_0, u1_sln_ref, u2_sln_ref, 1e3);
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/elasticity/crack/definitions.cpp | .cpp | 1,477 | 27 | #include "definitions.h"
CustomWeakFormLinearElasticity::CustomWeakFormLinearElasticity(double E, double nu, double rho_g,
std::string surface_force_bdy, double f0, double f1) : WeakForm<double>(2)
{
double lambda = (E * nu) / ((1 + nu) * (1 - 2 * nu));
double mu = E / (2 * (1 + nu));
// Jacobian.
add_matrix_form(new DefaultJacobianElasticity_0_0<double>(0, 0, HERMES_ANY, lambda, mu));
add_matrix_form(new DefaultJacobianElasticity_0_1<double>(0, 1, HERMES_ANY, lambda, mu));
add_matrix_form(new DefaultJacobianElasticity_1_1<double>(1, 1, HERMES_ANY, lambda, mu));
// Residual - first equation.
add_vector_form(new DefaultResidualElasticity_0_0<double>(0, HERMES_ANY, lambda, mu));
add_vector_form(new DefaultResidualElasticity_0_1<double>(0, HERMES_ANY, lambda, mu));
// Surface force (first component).
add_vector_form_surf(new DefaultVectorFormSurf<double>(0, surface_force_bdy, new Hermes2DFunction<double>(-f0)));
// Residual - second equation.
add_vector_form(new DefaultResidualElasticity_1_0<double>(1, HERMES_ANY, lambda, mu));
add_vector_form(new DefaultResidualElasticity_1_1<double>(1, HERMES_ANY, lambda, mu));
// Gravity loading in the second vector component.
add_vector_form(new DefaultVectorFormVol<double>(1, HERMES_ANY, new Hermes2DFunction<double>(-rho_g)));
// Surface force (second component).
add_vector_form_surf(new DefaultVectorFormSurf<double>(1, surface_force_bdy, new Hermes2DFunction<double>(-f1)));
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/elasticity/bracket/definitions.h | .h | 465 | 16 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::WeakFormsElasticity;
using namespace Hermes::Hermes2D::Views;
using namespace RefinementSelectors;
class CustomWeakFormLinearElasticity : public WeakForm <double>
{
public:
CustomWeakFormLinearElasticity(double E, double nu, double rho_g,
std::string surface_force_bdy, double f0, double f1);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/elasticity/bracket/main.cpp | .cpp | 9,750 | 247 | #include "definitions.h"
// This example uses adaptive multimesh hp-FEM to solve a simple problem
// of linear elasticity. Note that since both displacement components
// have similar qualitative behavior, the advantage of the multimesh
// discretization is less striking than for example in the tutorial
// example P04-linear-adapt/02-system-adapt.
//
// PDE: Lame equations of linear elasticity, treated as a coupled system
// of two PDEs.
//
// BC: u_1 = u_2 = 0 on Gamma_1 (right edge)
// du_1/dn = f0 on Gamma_2 (top edge)
// du_2/dn = f1 on Gamma_2 (top edge)
// du_1/dn = du_2/dn = 0 elsewhere
//
// The following parameters can be changed:
// Initial polynomial degree of all mesh elements.
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;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD_MULTI = 0.35;
const double THRESHOLD_SINGLE = 0.7;
// Error calculation & adaptivity.
DefaultErrorCalculator<double, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 2);
// Stopping criterion for an adaptivity step.
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(MULTI ? THRESHOLD_MULTI : THRESHOLD_SINGLE);
// 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.
// Young modulus for steel: 200 GPa.
const double E = 200e9;
// Poisson ratio.
const double nu = 0.3;
// Density.
const double rho = 8000.0;
// Gravitational acceleration.
const double g1 = -9.81;
// Top surface force in x-direction.
const double f0 = 0;
// Top surface force in y-direction.
const double f1 = -1e3;
int main(int argc, char* argv[])
{
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Load the mesh->
MeshSharedPtr u1_mesh(new Mesh), u2_mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", u1_mesh);
// Initial mesh refinements.
u1_mesh->refine_element_id(1);
u1_mesh->refine_element_id(4);
// Create initial mesh for the vertical displacement component.
// This also initializes the multimesh hp-FEM.
u2_mesh->copy(u1_mesh);
// Initialize boundary conditions.
DefaultEssentialBCConst<double> zero_disp("bdy_right", 0.0);
EssentialBCs<double> bcs(&zero_disp);
// Create x- and y- displacement space using the default H1 shapeset.
SpaceSharedPtr<double> u1_space(new H1Space<double>(u1_mesh, &bcs, P_INIT));
SpaceSharedPtr<double> u2_space(new H1Space<double>(u2_mesh, &bcs, P_INIT));
Hermes::Mixins::Loggable::Static::info("ndof = %d.", Space<double>::get_num_dofs({u1_space, u2_space}));
// Initialize the weak formulation.
// NOTE; These weak forms are identical to those in example P01-linear/08-system.
CustomWeakFormLinearElasticity wf(E, nu, rho*g1, "bdy_top", f0, f1);
// Initialize the FE problem.
std::vector<SpaceSharedPtr<double> > spaces(u1_space, u2_space);
DiscreteProblem<double> dp(wf, spaces);
// Initialize coarse and reference mesh solutions.
MeshFunctionSharedPtr<double> u1_sln(new Solution<double>), u2_sln(new Solution<double>);
MeshFunctionSharedPtr<double>u1_sln_ref(new Solution<double>), u2_sln_ref(new Solution<double>);
// Initialize refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Initialize views.
ScalarView s_view_0("Solution (x-displacement)", new WinGeom(0, 0, 500, 350));
s_view_0.show_mesh(false);
ScalarView s_view_1("Solution (y-displacement)", new WinGeom(760, 0, 500, 350));
s_view_1.show_mesh(false);
OrderView o_view_0("Mesh (x-displacement)", new WinGeom(410, 0, 440, 350));
OrderView o_view_1("Mesh (y-displacement)", new WinGeom(1170, 0, 440, 350));
ScalarView mises_view("Von Mises stress [Pa]", new WinGeom(0, 405, 500, 350));
// DOF and CPU convergence graphs.
SimpleGraph graph_dof_est, graph_cpu_est;
// 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 refMeshCreator1(u1_mesh);
MeshSharedPtr ref_u1_mesh = refMeshCreator1.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator1(u1_space, ref_u1_mesh);
SpaceSharedPtr<double> ref_u1_space = refSpaceCreator1.create_ref_space();
Mesh::ReferenceMeshCreator refMeshCreator2(u2_mesh);
MeshSharedPtr ref_u2_mesh = refMeshCreator2.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreator2(u2_space, ref_u2_mesh);
SpaceSharedPtr<double> ref_u2_space = refSpaceCreator2.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces(ref_u1_space, ref_u2_space);
int ndof_ref = Space<double>::get_num_dofs(ref_spaces);
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, ref_spaces);
// Initialize Newton solver.
NewtonSolver<double> newton(&dp);
newton.set_verbose_output(true);
// Time measurement.
cpu_time.tick();
// Perform Newton's iteration.
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh->");
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
}
// Time measurement.
cpu_time.tick();
// Translate the resulting coefficient vector into the Solution sln->
Solution<double>::vector_to_solutions(newton.get_sln_vector(), ref_spaces,
std::vector<MeshFunctionSharedPtr<double> >(u1_sln_ref, u2_sln_ref));
// Project the fine mesh solution onto the coarse mesh->
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh->");
OGProjection<double> ogProjection; ogProjection.project_global({u1_space, u2_space},
std::vector<MeshFunctionSharedPtr<double> >(u1_sln_ref, u2_sln_ref),
std::vector<MeshFunctionSharedPtr<double> >(u1_sln, u2_sln));
// View the coarse mesh solution and polynomial orders.
s_view_0.show(u1_sln);
o_view_0.show(u1_space);
s_view_1.show(u2_sln);
o_view_1.show(u2_space);
// For von Mises stress Filter.
double lambda = (E * nu) / ((1 + nu) * (1 - 2 * nu));
double mu = E / (2 * (1 + nu));
MeshFunctionSharedPtr<double> stress(new VonMisesFilter({u1_sln, u2_sln}, lambda, mu));
MeshFunctionSharedPtr<double> limited_stress(new ValFilter(stress, 0.0, 2e5));
mises_view.show(limited_stress, H2D_FN_VAL_0, u1_sln, u2_sln, 0);
// Skip visualization time.
cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);
// Initialize adaptivity.
adaptivity.set_spaces({u1_space, u2_space});
/*
// Register custom forms for error calculation.
errorCalculator.add_error_form(0, 0, bilinear_form_0_0<double, double>, bilinear_form_0_0<Ord, Ord>);
errorCalculator.add_error_form(0, 1, bilinear_form_0_1<double, double>, bilinear_form_0_1<Ord, Ord>);
errorCalculator.add_error_form(1, 0, bilinear_form_1_0<double, double>, bilinear_form_1_0<Ord, Ord>);
errorCalculator.add_error_form(1, 1, bilinear_form_1_1<double, double>, bilinear_form_1_1<Ord, Ord>);
*/
// Calculate error estimate for each solution component and the total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate and exact error.");
errorCalculator.calculate_errors({u1_sln, u2_sln},
std::vector<MeshFunctionSharedPtr<double> >(u1_sln_ref, u2_sln_ref));
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Time measurement.
cpu_time.tick();
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse_total: %d, ndof_fine_total: %d, err_est_rel_total: %g%%",
Space<double>::get_num_dofs({u1_space, u2_space}),
Space<double>::get_num_dofs(ref_spaces), err_est_rel_total);
// Add entry to DOF and CPU convergence graphs.
graph_dof_est.add_values(Space<double>::get_num_dofs({u1_space, u2_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");
// 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});
}
// Increase counter.
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Show the reference solution - the final result.
s_view_0.set_title("Fine mesh solution (x-displacement)");
s_view_0.show(u1_sln_ref);
s_view_1.set_title("Fine mesh solution (y-displacement)");
s_view_1.show(u2_sln_ref);
// For von Mises stress Filter.
double lambda = (E * nu) / ((1 + nu) * (1 - 2 * nu));
double mu = E / (2 * (1 + nu));
MeshFunctionSharedPtr<double> stress(new VonMisesFilter({u1_sln_ref, u2_sln_ref}, lambda, mu));
MeshFunctionSharedPtr<double> limited_stress(new ValFilter(stress, 0.0, 2e5));
mises_view.show(limited_stress, H2D_FN_VAL_0, u1_sln_ref, u2_sln_ref, 0);
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/elasticity/bracket/definitions.cpp | .cpp | 1,477 | 27 | #include "definitions.h"
CustomWeakFormLinearElasticity::CustomWeakFormLinearElasticity(double E, double nu, double rho_g,
std::string surface_force_bdy, double f0, double f1) : WeakForm<double>(2)
{
double lambda = (E * nu) / ((1 + nu) * (1 - 2 * nu));
double mu = E / (2 * (1 + nu));
// Jacobian.
add_matrix_form(new DefaultJacobianElasticity_0_0<double>(0, 0, HERMES_ANY, lambda, mu));
add_matrix_form(new DefaultJacobianElasticity_0_1<double>(0, 1, HERMES_ANY, lambda, mu));
add_matrix_form(new DefaultJacobianElasticity_1_1<double>(1, 1, HERMES_ANY, lambda, mu));
// Residual - first equation.
add_vector_form(new DefaultResidualElasticity_0_0<double>(0, HERMES_ANY, lambda, mu));
add_vector_form(new DefaultResidualElasticity_0_1<double>(0, HERMES_ANY, lambda, mu));
// Surface force (first component).
add_vector_form_surf(new DefaultVectorFormSurf<double>(0, surface_force_bdy, new Hermes2DFunction<double>(-f0)));
// Residual - second equation.
add_vector_form(new DefaultResidualElasticity_1_0<double>(1, HERMES_ANY, lambda, mu));
add_vector_form(new DefaultResidualElasticity_1_1<double>(1, HERMES_ANY, lambda, mu));
// Gravity loading in the second vector component.
add_vector_form(new DefaultVectorFormVol<double>(1, HERMES_ANY, new Hermes2DFunction<double>(-rho_g)));
// Surface force (second component).
add_vector_form_surf(new DefaultVectorFormSurf<double>(1, surface_force_bdy, new Hermes2DFunction<double>(-f1)));
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/elasticity/bracket/generate_constants.py | .py | 682 | 31 | from numpy import arctan, sqrt, pi, sin, cos
t = 0.1 # thickness
l = 0.7 # length
a = sqrt(l**2 - (l - t)**2)
print "a =", a
alpha = arctan(t/l)
print "alpha =", alpha
beta = delta - alpha
print "beta =", beta
gamma = pi/2 - 2*delta
print "gamma =", gamma
delta = arctan(a/(l-t))
print "delta =", delta
print "alpha_deg =", 180*alpha/pi
print "beta_deg =", 180*beta/pi
print "gamma_deg =", 180*gamma/pi
print "delta_deg =", 180*delta/pi
c = (l-t)*sin(alpha)
print "c =", c
d = (l-t)*cos(alpha)
print "d =", d
e = e = (l-t)*sin(delta)
print "e =", e
f = (l-t)*cos(delta)
print "f =", f
q = q = sqrt(2)/2
print "q =", q
print "l_minus_qt =", l - q * t
print "minus_qt =", - q * t
| Python |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/horn-axisym/definitions.h | .h | 434 | 20 | #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;
/* Weak forms */
class CustomWeakFormAcoustics : public WeakForm < ::complex >
{
public:
CustomWeakFormAcoustics(std::string bdy_newton, double rho,
double sound_speed, double omega);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/horn-axisym/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/acoustics/horn-axisym/main.cpp | .cpp | 6,752 | 185 | #include "definitions.h"
// This problem describes the distribution of the vector potential in
// a 2D domain comprising a wire carrying electrical current, air, and
// an iron which is not under voltage.
//
// PDE: -div(1/rho grad p) - omega**2 / (rho c**2) * p = 0.
//
// Domain: Axisymmetric geometry of a horn, see mesh file domain.mesh->
//
// BC: Prescribed pressure on the bottom edge,
// zero Neumann on the walls and on the axis of symmetry,
// Newton matched boundary at outlet 1/rho dp/dn = j omega p / (rho c)
//
// 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 = 2;
// 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;
// Problem parameters.
const double RHO = 1.25;
const double FREQ = 5e3;
const double OMEGA = 2 * M_PI * FREQ;
const double SOUND_SPEED = 353.0;
const std::complex<double> P_SOURCE(1.0, 0.0);
int main(int argc, char* argv[])
{
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
//MeshView mv("Initial mesh", new WinGeom(0, 0, 400, 400));
//mv.show(mesh);
//View::wait(HERMES_WAIT_KEYPRESS);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Initialize boundary conditions.
DefaultEssentialBCConst<::complex> bc_essential("Source", P_SOURCE);
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<::complex>::get_num_dofs(space);
Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
// Initialize the weak formulation.
WeakFormSharedPtr<::complex> wf(new CustomWeakFormAcoustics("Outlet", RHO, SOUND_SPEED, OMEGA));
// Initialize coarse and reference mesh solution.
MeshFunctionSharedPtr<::complex> sln(new Solution<::complex>), ref_sln(new Solution<::complex>);
// Initialize refinement selector.
H1ProjBasedSelector<::complex> selector(CAND_LIST);
// Initialize views.
ScalarView sview_real("Solution - real part", new WinGeom(0, 0, 330, 350));
ScalarView sview_imag("Solution - imaginary part", new WinGeom(400, 0, 330, 350));
sview_real.show_mesh(false);
sview_real.fix_scale_width(50);
sview_imag.show_mesh(false);
sview_imag.fix_scale_width(50);
OrderView oview("Polynomial orders", new WinGeom(400, 0, 300, 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 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();
int ndof_ref = Space<::complex>::get_num_dofs(ref_space);
// Assemble the reference problem.
Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
DiscreteProblem<::complex> dp(wf, ref_space);
// Time measurement.
cpu_time.tick();
// Perform Newton's iteration.
Hermes::Hermes2D::NewtonSolver<::complex> 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 Solution<::complex> sln->
Hermes::Hermes2D::Solution<::complex>::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 reference solution on coarse mesh.");
OGProjection<::complex> ogProjection; ogProjection.project_global(space, ref_sln, sln);
// Time measurement.
cpu_time.tick();
// View the coarse mesh solution and polynomial orders.
MeshFunctionSharedPtr<double> mag(new RealFilter(ref_sln));
sview_real.show(mag);
oview.show(space);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
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<::complex>::get_num_dofs(space), Space<::complex>::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<::complex>::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 counter.
as++;
} while (done == false);
Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
// Show the reference solution - the final result.
MeshFunctionSharedPtr<double> ref_mag(new RealFilter(ref_sln));
sview_real.show(ref_mag);
oview.show(space);
// Output solution in VTK format.
Linearizer lin(FileExport);
bool mode_3D = true;
lin.save_solution_vtk(ref_mag, "sln.vtk", "Acoustic pressure", mode_3D);
Hermes::Mixins::Loggable::Static::info("Solution in VTK format saved to file %s.", "sln.vtk");
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/horn-axisym/definitions.cpp | .cpp | 1,183 | 17 | #include "definitions.h"
CustomWeakFormAcoustics::CustomWeakFormAcoustics(std::string bdy_newton, double rho,
double sound_speed, double omega) : WeakForm<::complex>(1)
{
std::complex<double> ii = std::complex<double>(0.0, 1.0);
// Jacobian.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<::complex>(0, 0, HERMES_ANY, new Hermes1DFunction<::complex>(1.0 / rho), HERMES_SYM));
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<::complex>(0, 0, HERMES_ANY, new Hermes2DFunction<::complex>(-sqr(omega) / rho / sqr(sound_speed)), HERMES_SYM));
add_matrix_form_surf(new WeakFormsH1::DefaultMatrixFormSurf<::complex>(0, 0, bdy_newton, new Hermes2DFunction<::complex>(-ii * omega / rho / sound_speed)));
// Residual.
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<::complex>(0, HERMES_ANY, new Hermes1DFunction<::complex>(1.0 / rho)));
add_vector_form(new WeakFormsH1::DefaultResidualVol<::complex>(0, HERMES_ANY, new Hermes2DFunction<::complex>(-sqr(omega) / rho / sqr(sound_speed))));
add_vector_form_surf(new WeakFormsH1::DefaultResidualSurf<::complex>(0, bdy_newton, new Hermes2DFunction<::complex>(-ii * omega / rho / sound_speed)));
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/wave-propagation/definitions.h | .h | 12,354 | 286 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
#pragma region forms
template<typename Scalar>
class volume_matrix_acoustic_transient_planar_linear_form_1_1 : public MatrixFormVol < Scalar >
{
public:
volume_matrix_acoustic_transient_planar_linear_form_1_1(unsigned int i, unsigned int j, double ac_rho, double ac_vel);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
MatrixFormVol<Scalar>* clone() const;
double ac_rho;
double ac_vel;
};
template<typename Scalar>
class volume_matrix_acoustic_transient_planar_linear_form_1_2 : public MatrixFormVol < Scalar >
{
public:
volume_matrix_acoustic_transient_planar_linear_form_1_2(unsigned int i, unsigned int j, double ac_rho, double ac_vel);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
MatrixFormVol<Scalar>* clone() const;
double ac_rho;
double ac_vel;
};
template<typename Scalar>
class volume_matrix_acoustic_transient_planar_linear_form_2_2 : public MatrixFormVol < Scalar >
{
public:
volume_matrix_acoustic_transient_planar_linear_form_2_2(unsigned int i, unsigned int j, double ac_rho, double ac_vel);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
MatrixFormVol<Scalar>* clone() const;
double ac_rho;
double ac_vel;
};
template<typename Scalar>
class volume_matrix_acoustic_transient_planar_linear_form_2_1 : public MatrixFormVol < Scalar >
{
public:
volume_matrix_acoustic_transient_planar_linear_form_2_1(unsigned int i, unsigned int j, double ac_rho, double ac_vel);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
MatrixFormVol<Scalar>* clone() const;
double ac_rho;
double ac_vel;
};
template<typename Scalar>
class volume_vector_acoustic_transient_planar_linear_form_1_2 : public VectorFormVol < Scalar >
{
public:
volume_vector_acoustic_transient_planar_linear_form_1_2(unsigned int i, double ac_rho, double ac_vel);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
VectorFormVol<Scalar>* clone() const;
double ac_rho;
double ac_vel;
};
template<typename Scalar>
class volume_vector_acoustic_transient_planar_linear_form_2_1 : public VectorFormVol < Scalar >
{
public:
volume_vector_acoustic_transient_planar_linear_form_2_1(unsigned int i, double ac_rho, double ac_vel);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
VectorFormVol<Scalar>* clone() const;
double ac_rho;
double ac_vel;
};
template<typename Scalar>
class surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance : public MatrixFormSurf < Scalar >
{
public:
surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance(unsigned int i, unsigned int j);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u, Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomSurf<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u, Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomSurf<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
MatrixFormSurf<Scalar>* clone() const;
double ac_Z0;
};
#pragma endregion
class MyWeakForm : public WeakForm < double >
{
public:
MyWeakForm(
std::vector<std::string> acoustic_impedance_markers,
std::vector<double> acoustic_impedance_values,
std::vector<MeshFunctionSharedPtr<double> > prev_slns
) : WeakForm<double>(2), acoustic_impedance_markers(acoustic_impedance_markers), acoustic_impedance_values(acoustic_impedance_values), prev_slns(prev_slns)
{
this->set_ext(prev_slns);
double acoustic_density = 1.25;
double acoustic_speed = 343.;
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_1_1<double>(0, 0, acoustic_density, acoustic_speed));
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_1_2<double>(0, 1, acoustic_density, acoustic_speed));
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_2_1<double>(1, 0, acoustic_density, acoustic_speed));
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_2_2<double>(1, 1, acoustic_density, acoustic_speed));
this->add_vector_form(new volume_vector_acoustic_transient_planar_linear_form_1_2<double>(0, acoustic_density, acoustic_speed));
this->add_vector_form(new volume_vector_acoustic_transient_planar_linear_form_2_1<double>(1, acoustic_density, acoustic_speed));
for (int i = 0; i < acoustic_impedance_markers.size(); i++)
{
surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<double>* matrix_form = new surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<double>(0, 1);
matrix_form->set_area(acoustic_impedance_markers[i]);
matrix_form->ac_Z0 = acoustic_impedance_values[i];
this->add_matrix_form_surf(matrix_form);
}
}
MyWeakForm(
std::string acoustic_impedance_marker,
double acoustic_impedance_value,
std::vector<MeshFunctionSharedPtr<double> > prev_slns
) : WeakForm<double>(2), prev_slns(prev_slns)
{
this->set_ext(prev_slns);
double acoustic_density = 1.25;
double acoustic_speed = 343.;
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_1_1<double>(0, 0, acoustic_density, acoustic_speed));
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_1_2<double>(0, 1, acoustic_density, acoustic_speed));
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_2_1<double>(1, 0, acoustic_density, acoustic_speed));
this->add_matrix_form(new volume_matrix_acoustic_transient_planar_linear_form_2_2<double>(1, 1, acoustic_density, acoustic_speed));
this->add_vector_form(new volume_vector_acoustic_transient_planar_linear_form_1_2<double>(0, acoustic_density, acoustic_speed));
this->add_vector_form(new volume_vector_acoustic_transient_planar_linear_form_2_1<double>(1, acoustic_density, acoustic_speed));
surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<double>* matrix_form = new surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<double>(0, 1);
matrix_form->set_area(acoustic_impedance_marker);
matrix_form->ac_Z0 = acoustic_impedance_value;
this->add_matrix_form_surf(matrix_form);
}
std::vector<std::string> acoustic_impedance_markers;
std::vector<double> acoustic_impedance_values;
std::vector<MeshFunctionSharedPtr<double> > prev_slns;
};
class CustomBCValue : public EssentialBoundaryCondition < double >
{
public:
CustomBCValue(std::vector<std::string> markers, double amplitude, double frequency) : EssentialBoundaryCondition <double>(markers), amplitude(amplitude), frequency(frequency)
{
}
CustomBCValue(std::string marker, double amplitude = 1., double frequency = 1000.)
: EssentialBoundaryCondition<double>(marker), amplitude(amplitude), frequency(frequency)
{
}
inline EssentialBCValueType get_value_type() const { return BC_FUNCTION; }
virtual double value(double x, double y) const
{
if (this->frequency * this->current_time >= 1.)
return 0.;
else
return this->amplitude * std::sin(2 * M_PI * this->frequency * this->current_time);
}
double amplitude;
double frequency;
};
class CustomBCDerivative : public EssentialBoundaryCondition < double >
{
public:
CustomBCDerivative(std::vector<std::string> markers, double amplitude, double frequency) : EssentialBoundaryCondition <double>(markers), amplitude(amplitude), frequency(frequency)
{
}
CustomBCDerivative(std::string marker, double amplitude = 1., double frequency = 1000.)
: EssentialBoundaryCondition<double>(marker), amplitude(amplitude), frequency(frequency)
{
}
inline EssentialBCValueType get_value_type() const { return BC_FUNCTION; }
virtual double value(double x, double y) const
{
if (this->frequency * this->current_time >= 1.)
return 0.;
else
return 2 * M_PI * this->frequency * this->amplitude * std::cos(2 * M_PI * this->frequency * this->current_time);
}
double amplitude;
double frequency;
};
template<typename Scalar>
class exact_acoustic_transient_planar_linear_form_1_0_acoustic_pressure : public ExactSolutionScalar < Scalar >
{
public:
exact_acoustic_transient_planar_linear_form_1_0_acoustic_pressure(MeshSharedPtr mesh, double amplitude, double frequency) : ExactSolutionScalar<Scalar>(mesh), amplitude(amplitude), frequency(frequency)
{
}
Scalar value(double x, double y) const
{
return this->amplitude * std::sin(2 * M_PI * this->frequency * this->time);
}
void derivatives(double x, double y, Scalar& dx, Scalar& dy) const {};
Hermes::Ord ord(double x, double y) const
{
return Hermes::Ord(Hermes::Ord::get_max_order());
}
double amplitude;
double frequency;
double time;
};
template<typename Scalar>
class exact_acoustic_transient_planar_linear_form_2_0_acoustic_pressure : public ExactSolutionScalar < Scalar >
{
public:
exact_acoustic_transient_planar_linear_form_2_0_acoustic_pressure(MeshSharedPtr mesh, double amplitude, double frequency) : ExactSolutionScalar<Scalar>(mesh), amplitude(amplitude), frequency(frequency)
{
}
Scalar value(double x, double y) const
{
return 2 * M_PI * this->frequency * this->amplitude * std::cos(2 * M_PI * this->frequency * this->time);
}
void derivatives(double x, double y, Scalar& dx, Scalar& dy) const {};
Hermes::Ord ord(double x, double y) const
{
return Hermes::Ord(Hermes::Ord::get_max_order());
}
double amplitude;
double frequency;
double time;
}; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/wave-propagation/test_acoustic_transient_planar.py | .py | 3,120 | 69 | import agros2d
# problem
problem = agros2d.problem(clear = True)
problem.coordinate_type = "planar"
problem.mesh_type = "triangle"
problem.matrix_solver = "umfpack"
problem.time_step_method = "fixed"
problem.time_method_order = 2
problem.time_method_tolerance = 1
problem.time_total = 0.001
problem.time_steps = 250
# disable view
agros2d.view.mesh.initial_mesh = False
agros2d.view.mesh.solution_mesh = False
agros2d.view.mesh.order = False
agros2d.view.post2d.scalar = False
agros2d.view.post2d.contours = False
agros2d.view.post2d.vectors = False
# fields
# acoustic
acoustic = agros2d.field("acoustic")
acoustic.analysis_type = "transient"
acoustic.initial_condition = 0
acoustic.number_of_refinements = 0
acoustic.polynomial_order = 2
acoustic.linearity_type = "linear"
acoustic.adaptivity_type = "disabled"
# boundaries
acoustic.add_boundary("Matched bundary", "acoustic_impedance", {"acoustic_impedance" : 345*1.25 })
acoustic.add_boundary("Source", "acoustic_pressure", {"acoustic_pressure_real" : { "expression" : "sin(2*pi*(time/(1.0/1000)))" }, "acoustic_pressure_time_derivative" : { "expression" : "2*pi*(1.0/(1.0/1000))*cos(2*pi*(time/(1.0/1000)))" }})
acoustic.add_boundary("Hard wall", "acoustic_normal_acceleration", {"acoustic_normal_acceleration_real" : 0})
acoustic.add_boundary("Soft wall", "acoustic_pressure", {"acoustic_pressure_real" : 0, "acoustic_pressure_time_derivative" : 0})
# materials
acoustic.add_material("Air", {"acoustic_density" : 1.25, "acoustic_speed" : 343})
# geometry
geometry = agros2d.geometry
geometry.add_edge(-0.4, 0.05, 0.1, 0.2, boundaries = {"acoustic" : "Matched bundary"})
geometry.add_edge(0.1, -0.2, -0.4, -0.05, boundaries = {"acoustic" : "Matched bundary"})
geometry.add_edge(-0.4, 0.05, -0.4, -0.05, boundaries = {"acoustic" : "Soft wall"})
geometry.add_edge(-0.18, -0.06, -0.17, -0.05, angle = 90, boundaries = {"acoustic" : "Source"})
geometry.add_edge(-0.17, -0.05, -0.18, -0.04, angle = 90, boundaries = {"acoustic" : "Source"})
geometry.add_edge(-0.18, -0.04, -0.19, -0.05, angle = 90, boundaries = {"acoustic" : "Source"})
geometry.add_edge(-0.19, -0.05, -0.18, -0.06, angle = 90, boundaries = {"acoustic" : "Source"})
geometry.add_edge(0.1, -0.2, 0.1, 0.2, angle = 90, boundaries = {"acoustic" : "Matched bundary"})
geometry.add_edge(0.03, 0.1, -0.04, -0.05, angle = 90, boundaries = {"acoustic" : "Hard wall"})
geometry.add_edge(-0.04, -0.05, 0.08, -0.04, boundaries = {"acoustic" : "Hard wall"})
geometry.add_edge(0.08, -0.04, 0.03, 0.1, boundaries = {"acoustic" : "Hard wall"})
geometry.add_label(-0.0814934, 0.0707097, area = 10e-05, materials = {"acoustic" : "Air"})
geometry.add_label(-0.181474, -0.0504768, materials = {"acoustic" : "none"})
geometry.add_label(0.0314514, 0.0411749, materials = {"acoustic" : "none"})
agros2d.view.zoom_best_fit()
# solve problem
problem.solve()
# point
point = acoustic.local_values(0.042132, -0.072959)
testp = agros2d.test("Acoustic pressure", point["pr"], 0.200436)
# testSPL = agros2d.test("Acoustic sound level", point["SPL"], 77.055706)
print("Test: Acoustic - transient - planar: " + str(testp)) | Python |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/wave-propagation/main.cpp | .cpp | 2,903 | 87 | #include "definitions.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
const int P_INIT = 2;
const double time_step = 4e-5;
const double end_time = 1.;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
std::vector<MeshSharedPtr> meshes({ mesh });
Hermes::Hermes2D::MeshReaderH2DXML mloader;
mloader.load("domain.mesh", meshes);
MeshView m;
m.show(mesh);
std::vector<std::string> soft_boundaries({ "2" });
CustomBCValue custom_bc_value({ "3", "4", "5", "6" }, 1., 1000.);
DefaultEssentialBCConst<double> default_bc_value(soft_boundaries, 0.0);
Hermes::Hermes2D::EssentialBCs<double> bcs_value({ &custom_bc_value, &default_bc_value });
CustomBCDerivative custom_bc_derivative({ "3", "4", "5", "6" }, 1., 1000.);
DefaultEssentialBCConst<double> default_bc_derivative(soft_boundaries, 0.0);
Hermes::Hermes2D::EssentialBCs<double> bcs_derivative({ &custom_bc_derivative, &default_bc_derivative });
SpaceSharedPtr<double> space_value(new Hermes::Hermes2D::H1Space<double>(mesh, &bcs_value, P_INIT));
SpaceSharedPtr<double> space_derivative(new Hermes::Hermes2D::H1Space<double>(mesh, &bcs_derivative, P_INIT));
std::vector<SpaceSharedPtr<double> > spaces({ space_value, space_derivative });
BaseView<double> b;
b.show(space_value);
// Initialize the solution.
MeshFunctionSharedPtr<double> sln_value(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> sln_derivative(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > slns({ sln_value, sln_derivative });
Hermes::Hermes2D::Views::ScalarView viewS("Solution", new Hermes::Hermes2D::Views::WinGeom(50, 50, 1000, 800));
//viewS.set_min_max_range(-1.0, 1.0);
WeakFormSharedPtr<double> wf(new MyWeakForm({ "0", "1", "7" }, { 345 * 1.25, 345 * 1.25, 345 * 1.25 }, slns));
wf->set_current_time_step(time_step);
// Initialize linear solver.
Hermes::Hermes2D::LinearSolver<double> linear_solver(wf, spaces);
linear_solver.set_jacobian_constant();
// Solve the linear problem.
unsigned int iteration = 0;
for (double time = time_step; time < end_time; time += time_step)
{
try
{
Hermes::Mixins::Loggable::Static::info("Iteration: %u, Time: %g.", iteration, time);
Space<double>::update_essential_bc_values(spaces, time);
linear_solver.solve();
// Get the solution vector.
double* sln_vector = linear_solver.get_sln_vector();
// Translate the solution vector into the previously initialized Solution.
Hermes::Hermes2D::Solution<double>::vector_to_solutions(sln_vector, spaces, slns);
// Visualize the solution.
viewS.show(slns[0]);
//viewS.wait_for_keypress();
}
catch (std::exception& e)
{
std::cout << e.what();
return -1;
}
iteration++;
}
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/wave-propagation/definitions.cpp | .cpp | 10,683 | 263 | #include "definitions.h"
template <typename Scalar>
volume_matrix_acoustic_transient_planar_linear_form_1_1<Scalar>::volume_matrix_acoustic_transient_planar_linear_form_1_1(unsigned int i, unsigned int j, double ac_rho, double ac_vel)
: MatrixFormVol<Scalar>(i, j), ac_rho(ac_rho), ac_vel(ac_vel)
{
}
template <typename Scalar>
Scalar volume_matrix_acoustic_transient_planar_linear_form_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar 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 / this->ac_rho;
}
template <typename Scalar>
Hermes::Ord volume_matrix_acoustic_transient_planar_linear_form_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord 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;
}
template <typename Scalar>
MatrixFormVol<Scalar>* volume_matrix_acoustic_transient_planar_linear_form_1_1<Scalar>::clone() const
{
return new volume_matrix_acoustic_transient_planar_linear_form_1_1(*this);
}
template <typename Scalar>
volume_matrix_acoustic_transient_planar_linear_form_1_2<Scalar>::volume_matrix_acoustic_transient_planar_linear_form_1_2(unsigned int i, unsigned int j, double ac_rho, double ac_vel)
: MatrixFormVol<Scalar>(i, j), ac_rho(ac_rho), ac_vel(ac_vel)
{
}
template <typename Scalar>
Scalar volume_matrix_acoustic_transient_planar_linear_form_1_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return result / (ac_rho * ac_vel *ac_vel * this->wf->get_current_time_step());
}
template <typename Scalar>
Hermes::Ord volume_matrix_acoustic_transient_planar_linear_form_1_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return result;
}
template <typename Scalar>
MatrixFormVol<Scalar>* volume_matrix_acoustic_transient_planar_linear_form_1_2<Scalar>::clone() const
{
return new volume_matrix_acoustic_transient_planar_linear_form_1_2(*this);
}
template <typename Scalar>
volume_matrix_acoustic_transient_planar_linear_form_2_2<Scalar>::volume_matrix_acoustic_transient_planar_linear_form_2_2(unsigned int i, unsigned int j, double ac_rho, double ac_vel)
: MatrixFormVol<Scalar>(i, j), ac_rho(ac_rho), ac_vel(ac_vel)
{
}
template <typename Scalar>
Scalar volume_matrix_acoustic_transient_planar_linear_form_2_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return -result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_acoustic_transient_planar_linear_form_2_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return -result;
}
template <typename Scalar>
MatrixFormVol<Scalar>* volume_matrix_acoustic_transient_planar_linear_form_2_2<Scalar>::clone() const
{
return new volume_matrix_acoustic_transient_planar_linear_form_2_2(*this);
}
template <typename Scalar>
volume_matrix_acoustic_transient_planar_linear_form_2_1<Scalar>::volume_matrix_acoustic_transient_planar_linear_form_2_1(unsigned int i, unsigned int j, double ac_rho, double ac_vel)
: MatrixFormVol<Scalar>(i, j), ac_rho(ac_rho), ac_vel(ac_vel)
{
}
template <typename Scalar>
Scalar volume_matrix_acoustic_transient_planar_linear_form_2_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return result / this->wf->get_current_time_step();
}
template <typename Scalar>
Hermes::Ord volume_matrix_acoustic_transient_planar_linear_form_2_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return result;
}
template <typename Scalar>
MatrixFormVol<Scalar>* volume_matrix_acoustic_transient_planar_linear_form_2_1<Scalar>::clone() const
{
return new volume_matrix_acoustic_transient_planar_linear_form_2_1(*this);
}
template <typename Scalar>
volume_vector_acoustic_transient_planar_linear_form_1_2<Scalar>::volume_vector_acoustic_transient_planar_linear_form_1_2(unsigned int i, double ac_rho, double ac_vel)
: VectorFormVol<Scalar>(i), ac_rho(ac_rho), ac_vel(ac_vel)
{
}
template <typename Scalar>
Scalar volume_vector_acoustic_transient_planar_linear_form_1_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * v->val[i] * ext[1]->val[i];
}
return result / (ac_rho * ac_vel * ac_vel * this->wf->get_current_time_step());
}
template <typename Scalar>
Hermes::Ord volume_vector_acoustic_transient_planar_linear_form_1_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * v->val[i] * ext[1]->val[i];
}
return result;
}
template <typename Scalar>
VectorFormVol<Scalar>* volume_vector_acoustic_transient_planar_linear_form_1_2<Scalar>::clone() const
{
return new volume_vector_acoustic_transient_planar_linear_form_1_2(*this);
}
template <typename Scalar>
volume_vector_acoustic_transient_planar_linear_form_2_1<Scalar>::volume_vector_acoustic_transient_planar_linear_form_2_1(unsigned int i, double ac_rho, double ac_vel)
: VectorFormVol<Scalar>(i), ac_rho(ac_rho), ac_vel(ac_vel)
{
}
template <typename Scalar>
Scalar volume_vector_acoustic_transient_planar_linear_form_2_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * v->val[i] * ext[0]->val[i];
}
return result / this->wf->get_current_time_step();
}
template <typename Scalar>
Hermes::Ord volume_vector_acoustic_transient_planar_linear_form_2_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * v->val[i] * ext[0]->val[i];
}
return result;
}
template <typename Scalar>
VectorFormVol<Scalar>* volume_vector_acoustic_transient_planar_linear_form_2_1<Scalar>::clone() const
{
return new volume_vector_acoustic_transient_planar_linear_form_2_1(*this);
}
template <typename Scalar>
surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<Scalar>::surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance(unsigned int i, unsigned int j)
: MatrixFormSurf<Scalar>(i, j)
{
}
template <typename Scalar>
Scalar surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u, Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomSurf<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return result / ac_Z0;
}
template <typename Scalar>
Hermes::Ord surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u, Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomSurf<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * v->val[i];
}
return result;
}
template <typename Scalar>
MatrixFormSurf<Scalar>* surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance<Scalar>::clone() const
{
return new surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance(*this);
}
template class volume_matrix_acoustic_transient_planar_linear_form_1_1 < double > ;
template class volume_matrix_acoustic_transient_planar_linear_form_1_2 < double > ;
template class volume_matrix_acoustic_transient_planar_linear_form_2_2 < double > ;
template class volume_matrix_acoustic_transient_planar_linear_form_2_1 < double > ;
template class volume_vector_acoustic_transient_planar_linear_form_1_2 < double > ;
template class volume_vector_acoustic_transient_planar_linear_form_2_1 < double > ;
template class surface_matrix_acoustic_transient_planar_linear_form_1_2_acoustic_impedance < double > ; | C++ |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/apartment/definitions.h | .h | 430 | 19 | #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;
/* Weak forms */
class CustomWeakFormAcoustics : public WeakForm < ::complex >
{
public:
CustomWeakFormAcoustics(std::string bdy_newton, double rho, double sound_speed, double omega);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/apartment/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/acoustics/apartment/main.cpp | .cpp | 14,364 | 391 | #include "definitions.h"
// This problem describes the distribution of the vector potential in
// a 2D domain comprising a wire carrying electrical current, air, and
// an iron which is not under voltage.
//
// PDE: -div(1/rho grad p) - omega**2 / (rho c**2) * p = 0.
//
// Domain: Floor plan of an existing apartment.
//
// BC: Prescribed pressure at the source.
// Newton matched boundary on the walls.
//
// 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 = 2;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.25;
// 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 RHO = 1.25;
const double FREQ = 5e2;
const double OMEGA = 2 * M_PI * FREQ;
const double SOUND_SPEED = 353.0;
const std::complex<double> P_SOURCE(1.0, 0.0);
enum hpAdaptivityStrategy
{
noSelectionH = 0,
noSelectionHP = 1,
hXORpSelectionBasedOnError = 2,
hORpSelectionBasedOnDOFs = 3,
isoHPSelectionBasedOnDOFs = 4,
anisoHPSelectionBasedOnDOFs = 5
};
class MySelector : public H1ProjBasedSelector < ::complex >
{
public:
MySelector(hpAdaptivityStrategy strategy) : H1ProjBasedSelector<::complex>(cand_list), strategy(strategy)
{
if (strategy == hXORpSelectionBasedOnError)
{
//this->set_error_weights(1.0,1.0,1.0);
}
}
private:
bool select_refinement(Element* element, int order, MeshFunction<::complex>* rsln, ElementToRefine& refinement)
{
switch (strategy)
{
case(noSelectionH) :
{
refinement.split = H2D_REFINEMENT_H;
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][0] =
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][1] =
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][2] =
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][3] =
order;
ElementToRefine::copy_orders(refinement.refinement_polynomial_order, refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H]);
return true;
}
break;
case(noSelectionHP) :
{
int max_allowed_order = this->max_order;
if (this->max_order == H2DRS_DEFAULT_ORDER)
max_allowed_order = H2DRS_MAX_ORDER;
int order_h = H2D_GET_H_ORDER(order), order_v = H2D_GET_V_ORDER(order);
int increased_order_h = std::min(max_allowed_order, order_h + 1), increased_order_v = std::min(max_allowed_order, order_v + 1);
int increased_order;
if (element->is_triangle())
increased_order = refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][0] = H2D_MAKE_QUAD_ORDER(increased_order_h, increased_order_h);
else
increased_order = refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][0] = H2D_MAKE_QUAD_ORDER(increased_order_h, increased_order_v);
refinement.split = H2D_REFINEMENT_H;
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][0] =
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][1] =
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][2] =
refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H][3] =
increased_order;
ElementToRefine::copy_orders(refinement.refinement_polynomial_order, refinement.best_refinement_polynomial_order_type[H2D_REFINEMENT_H]);
return true;
}
case(hXORpSelectionBasedOnError) :
{
//make an uniform order in a case of a triangle
int order_h = H2D_GET_H_ORDER(order), order_v = H2D_GET_V_ORDER(order);
int current_min_order, current_max_order;
this->get_current_order_range(element, current_min_order, current_max_order);
if (current_max_order < std::max(order_h, order_v))
current_max_order = std::max(order_h, order_v);
int last_order_h = std::min(current_max_order, order_h + 1), last_order_v = std::min(current_max_order, order_v + 1);
int last_order = H2D_MAKE_QUAD_ORDER(last_order_h, last_order_v);
//build candidates.
std::vector<Cand> candidates;
candidates.push_back(Cand(H2D_REFINEMENT_P, last_order));
candidates.push_back(Cand(H2D_REFINEMENT_H, order, order, order, order));
this->evaluate_cands_error(candidates, element, rsln);
Cand* best_candidate = (candidates[0].error < candidates[1].error) ? &candidates[0] : &candidates[1];
Cand* best_candidates_specific_type[4];
best_candidates_specific_type[H2D_REFINEMENT_P] = &candidates[0];
best_candidates_specific_type[H2D_REFINEMENT_H] = &candidates[1];
best_candidates_specific_type[2] = NULL;
best_candidates_specific_type[3] = NULL;
//copy result to output
refinement.split = best_candidate->split;
ElementToRefine::copy_orders(refinement.refinement_polynomial_order, best_candidate->p);
for (int i = 0; i < 4; i++)
if (best_candidates_specific_type[i] != NULL)
ElementToRefine::copy_orders(refinement.best_refinement_polynomial_order_type[i], best_candidates_specific_type[i]->p);
ElementToRefine::copy_errors(refinement.errors, best_candidate->errors);
//modify orders in a case of a triangle such that order_v is zero
if (element->is_triangle())
for (int i = 0; i < H2D_MAX_ELEMENT_SONS; i++)
refinement.refinement_polynomial_order[i] = H2D_MAKE_QUAD_ORDER(H2D_GET_H_ORDER(refinement.refinement_polynomial_order[i]), 0);
return true;
}
default:
H1ProjBasedSelector<::complex>::select_refinement(element, order, rsln, refinement);
return true;
break;
}
}
std::vector<Cand> create_candidates(Element* e, int quad_order)
{
std::vector<Cand> candidates;
// Get the current order range.
int current_min_order, current_max_order;
this->get_current_order_range(e, current_min_order, current_max_order);
int order_h = H2D_GET_H_ORDER(quad_order), order_v = H2D_GET_V_ORDER(quad_order);
if (current_max_order < std::max(order_h, order_v))
current_max_order = std::max(order_h, order_v);
int last_order_h = std::min(current_max_order, order_h + 1), last_order_v = std::min(current_max_order, order_v + 1);
int last_order = H2D_MAKE_QUAD_ORDER(last_order_h, last_order_v);
switch (strategy)
{
case(hORpSelectionBasedOnDOFs) :
{
candidates.push_back(Cand(H2D_REFINEMENT_P, quad_order));
}
case(hXORpSelectionBasedOnError) :
{
candidates.push_back(Cand(H2D_REFINEMENT_P, last_order));
candidates.push_back(Cand(H2D_REFINEMENT_H, quad_order, quad_order, quad_order, quad_order));
return candidates;
}
break;
case(isoHPSelectionBasedOnDOFs) :
{
this->cand_list = H2D_HP_ISO;
return H1ProjBasedSelector<::complex>::create_candidates(e, quad_order);
}
break;
case(anisoHPSelectionBasedOnDOFs) :
{
this->cand_list = H2D_HP_ANISO;
return H1ProjBasedSelector<::complex>::create_candidates(e, quad_order);
}
break;
}
}
void evaluate_cands_score(std::vector<Cand>& candidates, Element* e)
{
switch (strategy)
{
case(hXORpSelectionBasedOnError) :
{
if (candidates[0].error > candidates[1].error)
{
candidates[0].score = 0.0;
candidates[1].score = 1.0;
}
else
{
candidates[1].score = 0.0;
candidates[0].score = 1.0;
}
}
break;
default:
{
//calculate score of candidates
Cand& unrefined = candidates[0];
const int num_cands = (int)candidates.size();
unrefined.score = 0;
for (int i = 1; i < num_cands; i++)
{
Cand& cand = candidates[i];
if (cand.error < unrefined.error)
{
double delta_dof = cand.dofs - unrefined.dofs;
candidates[i].score = (log10(unrefined.error) - log10(cand.error)) / delta_dof;
}
else
candidates[i].score = 0;
}
}
}
}
int strategy;
};
int main(int argc, char* argv[])
{
// Initialize refinement selector.
MySelector selector(hORpSelectionBasedOnDOFs);
HermesCommonApi.set_integral_param_value(Hermes::showInternalWarnings, false);
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// 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);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Initialize boundary conditions.
DefaultEssentialBCConst<::complex> bc_essential("Source", P_SOURCE);
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<::complex>::get_num_dofs(space);
//Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
// Initialize the weak formulation.
WeakFormSharedPtr<::complex> wf(new CustomWeakFormAcoustics("Wall", RHO, SOUND_SPEED, OMEGA));
// Initialize coarse and reference mesh solution.
MeshFunctionSharedPtr<::complex> sln(new Solution<::complex>), ref_sln(new Solution<::complex>);
// Initialize views.
ScalarView sview("Acoustic pressure", new WinGeom(600, 0, 600, 350));
sview.show_contours(.2);
ScalarView eview("Error", new WinGeom(600, 377, 600, 350));
sview.show_mesh(false);
sview.fix_scale_width(50);
OrderView oview("Polynomial orders", new WinGeom(1208, 0, 600, 350));
ScalarView ref_view("Refined elements", new WinGeom(1208, 377, 600, 350));
ref_view.show_scale(false);
ref_view.set_min_max_range(0, 2);
// DOF and CPU convergence graphs initialization.
SimpleGraph graph_dof, graph_cpu;
//Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
// Time measurement.
cpu_time.tick();
// Perform Newton's iteration.
Hermes::Hermes2D::NewtonSolver<::complex> newton(wf, space);
newton.set_verbose_output(false);
// Adaptivity loop:
int as = 1;
adaptivity.set_space(space);
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<::complex>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
SpaceSharedPtr<::complex> ref_space = refSpaceCreator.create_ref_space();
int ndof_ref = Space<::complex>::get_num_dofs(ref_space);
wf->set_verbose_output(false);
newton.set_space(ref_space);
// Assemble the reference problem.
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 Solution<::complex> sln->
Hermes::Hermes2D::Solution<::complex>::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 reference solution on coarse mesh.");
OGProjection<::complex> ogProjection; ogProjection.project_global(space, ref_sln, sln);
// Time measurement.
cpu_time.tick();
// View the coarse mesh solution and polynomial orders.
MeshFunctionSharedPtr<double> acoustic_pressure(new RealFilter(sln));
sview.show(acoustic_pressure);
oview.show(space);
// Calculate element errors and total error estimate.
//Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
errorCalculator.calculate_errors(sln, ref_sln);
double err_est_rel = errorCalculator.get_total_error_squared() * 100;
eview.show(errorCalculator.get_errorMeshFunction());
// Report results.
//Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%", Space<::complex>::get_num_dofs(space), Space<::complex>::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<::complex>::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);
ref_view.show(adaptivity.get_refinementInfoMeshFunction());
cpu_time.tick();
std::cout << "Adaptivity step: " << as << ", running CPU time: " << cpu_time.accumulated_str() << std::endl;
}
// Increase counter.
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 magnitude");
MeshFunctionSharedPtr<double> ref_mag(new RealFilter(ref_sln));
sview.show(ref_mag);
// Output solution in VTK format.
Linearizer lin(FileExport);
bool mode_3D = true;
lin.save_solution_vtk(ref_mag, "sln.vtk", "Acoustic pressure", mode_3D);
//Hermes::Mixins::Loggable::Static::info("Solution in VTK format saved to file %s.", "sln.vtk");
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/acoustics/apartment/definitions.cpp | .cpp | 1,181 | 16 | #include "definitions.h"
CustomWeakFormAcoustics::CustomWeakFormAcoustics(std::string bdy_newton, double rho, double sound_speed, double omega) : WeakForm<::complex>(1)
{
std::complex<double> ii = std::complex<double>(0.0, 1.0);
// Jacobian.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<::complex>(0, 0, HERMES_ANY, new Hermes1DFunction<::complex>(1.0 / rho), HERMES_SYM));
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<::complex>(0, 0, HERMES_ANY, new Hermes2DFunction<::complex>(-sqr(omega) / rho / sqr(sound_speed)), HERMES_SYM));
add_matrix_form_surf(new WeakFormsH1::DefaultMatrixFormSurf<::complex>(0, 0, bdy_newton, new Hermes2DFunction<::complex>(-ii * omega / rho / sound_speed)));
// Residual.
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<::complex>(0, HERMES_ANY, new Hermes1DFunction<::complex>(1.0 / rho)));
add_vector_form(new WeakFormsH1::DefaultResidualVol<::complex>(0, HERMES_ANY, new Hermes2DFunction<::complex>(-sqr(omega) / rho / sqr(sound_speed))));
add_vector_form_surf(new WeakFormsH1::DefaultResidualSurf<::complex>(0, bdy_newton, new Hermes2DFunction<::complex>(-ii * omega / rho / sound_speed)));
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/nernst-planck/poisson-timedep-adapt/definitions.h | .h | 177 | 7 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/nernst-planck/poisson-timedep-adapt/timestep_controller.h | .h | 3,734 | 118 | #include "definitions.h"
#define PID_DEFAULT_TOLERANCE 0.25
#define DEFAULT_STEP 0.1
class PidTimestepController {
public:
PidTimestepController(double final_time, bool pid_on = true,
double default_step = DEFAULT_STEP, double tolerance = PID_DEFAULT_TOLERANCE) {
this->delta = tolerance;
this->final_time = final_time;
this->time = 0;
this->step_number = 0;
timestep = new double;
(*timestep) = default_step;
this->pid = pid_on;
finished = false;
};
int get_timestep_number() {return step_number;};
double get_time() {return time;};
// true if next time step can be run, false if the time step must be re-run with smaller time step.
bool end_step(std::vector<MeshFunctionSharedPtr<double> > solutions, std::vector<MeshFunctionSharedPtr<double> > prev_solutions);
void begin_step();
bool has_next();
// reference to the current calculated time step
double *timestep;
private:
bool pid;
double delta;
double final_time;
double time;
int step_number;
std::vector<double> err_vector;
bool finished;
// PID parameters
const static double kp;
const static double kl;
const static double kD;
};
const double PidTimestepController::kp = 0.075;
const double PidTimestepController::kl = 0.175;
const double PidTimestepController::kD = 0.01;
// Usage: do{ begin_step() calculations .... end_step(..);} while(has_next());
void PidTimestepController::begin_step() {
if ((time + (*timestep)) >= final_time) {
Hermes::Mixins::Loggable::Static::info("Time step would exceed the final time... reducing");
(*timestep) = final_time - time;
Hermes::Mixins::Loggable::Static::info("The last time step: %g", *timestep);
finished = true;
}
time += (*timestep);
step_number++;
Hermes::Mixins::Loggable::Static::info("begin_step processed, new step number: %i and cumulative time: %g", step_number, time);
}
bool PidTimestepController::end_step(std::vector<MeshFunctionSharedPtr<double> > solutions,
std::vector<MeshFunctionSharedPtr<double> > prev_solutions)
{
if (pid)
{
unsigned int neq = solutions.size();
if (neq == 0) {
return true;
}
if (prev_solutions.empty()) {
return true;
}
if (neq != prev_solutions.size()) {
throw Hermes::Exceptions::Exception("Inconsistent parameters in PidTimestepController::next(...)");
}
double max_rel_error = 0.0;
for (unsigned int i = 0; i < neq; i++) {
DefaultErrorCalculator<double, HERMES_H1_NORM> temp_error_calculator(RelativeErrorToGlobalNorm, 1);
temp_error_calculator.calculate_errors(solutions[i], prev_solutions[i], false);
double rel_error = temp_error_calculator.get_total_error_squared();
max_rel_error = (rel_error > max_rel_error) ? rel_error : max_rel_error;
Hermes::Mixins::Loggable::Static::info("Solution[%i]: rel error %g, largest relative error %g",
i, rel_error, max_rel_error);
}
err_vector.push_back(max_rel_error);
if (err_vector.size() > 2 && max_rel_error <= delta) {
int size = err_vector.size();
Hermes::Mixins::Loggable::Static::info("Error vector sufficient for adapting...");
double t_coeff = Hermes::pow(err_vector.at(size - 2)/err_vector.at(size-1),kp)
* Hermes::pow(0.25/err_vector.at(size - 1), kl)
* Hermes::pow(err_vector.at(size - 2)*err_vector.at(size - 2)/(err_vector.at(size -1)*err_vector.at(size-3)), kD);
Hermes::Mixins::Loggable::Static::info("Coefficient %g", t_coeff);
(*timestep) = (*timestep)*t_coeff;
Hermes::Mixins::Loggable::Static::info("New time step: %g", *timestep);
}
} // end pid
return true;
}
bool PidTimestepController::has_next() {
return !finished;
}
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/nernst-planck/poisson-timedep-adapt/main.cpp | .cpp | 15,042 | 412 | #include "definitions.h"
#include "timestep_controller.h"
/** \addtogroup e_newton_np_timedep_adapt_system Newton Time-dependant System with Adaptivity
\{
\brief This example shows how to combine the automatic adaptivity with the Newton's method for a nonlinear time-dependent PDE system.
This example shows how to combine the automatic adaptivity with the
Newton's method for a nonlinear time-dependent PDE system.
The time discretization is done using implicit Euler or
Crank Nicholson method (see parameter TIME_DISCR).
The following PDE's are solved:
Nernst-Planck (describes the diffusion and migration of charged particles):
\f[dC/dt - D*div[grad(C)] - K*C*div[grad(\phi)]=0,\f]
where D and K are constants and C is the cation concentration variable,
phi is the voltage variable in the Poisson equation:
\f[ - div[grad(\phi)] = L*(C - C_0),\f]
where \f$C_0\f$, and L are constant (anion concentration). \f$C_0\f$ is constant
anion concentration in the domain and L is material parameter.
So, the equation variables are phi and C and the system describes the
migration/diffusion of charged particles due to applied voltage.
The simulation domain looks as follows:
\verbatim
Top
+----------+
| |
Side| |Side
| |
+----------+
Bottom
\endverbatim
For the Nernst-Planck equation, all the boundaries are natural i.e. Neumann.
Which basically means that the normal derivative is 0:
\f[ BC: -D*dC/dn - K*C*d\phi/dn = 0 \f]
For Poisson equation, boundary 1 has a natural boundary condition
(electric field derivative is 0).
The voltage is applied to the boundaries 2 and 3 (Dirichlet boundaries)
It is possible to adjust system paramter VOLT_BOUNDARY to apply
Neumann boundary condition to 2 (instead of Dirichlet). But by default:
- BC 2: \f$\phi = VOLTAGE\f$
- BC 3: \f$\phi = 0\f$
- BC 1: \f$\frac{d\phi}{dn} = 0\f$
*/
// Parameters to tweak the amount of output to the console.
#define NOSCREENSHOT
// True if scaled dimensionless variables are used, false otherwise.
bool SCALED = true;
/*** Fundamental coefficients ***/
// [m^2/s] Diffusion coefficient.
const double D = 10e-11;
// [J/mol*K] Gas constant.
const double R = 8.31;
// [K] Aboslute temperature.
const double T = 293;
// [s * A / mol] Faraday constant.
const double F = 96485.3415;
// [F/m] Electric permeability.
const double eps = 2.5e-2;
// Mobility of ions.
const double mu = D / (R * T);
// Charge number.
const double z = 1;
// Constant for equation.
const double K = z * mu * F;
// Constant for equation.
const double L = F / eps;
// [mol/m^3] Anion and counterion concentration.
const double C0 = 1200;
// Scaling constants.
// Scaling const, domain thickness [m].
const double l = 200e-6;
// Debye length [m].
double lambda = Hermes::sqrt((eps)*R*T / (2.0*F*F*C0));
double epsilon = lambda / l;
// [V] Applied voltage.
const double VOLTAGE = 1;
const double SCALED_VOLTAGE = VOLTAGE*F / (R*T);
/* Simulation parameters */
const double T_FINAL = 3;
double INIT_TAU = 0.05;
// Size of the time step.
double *TAU = &INIT_TAU;
// Scaling time variables.
//double SCALED_INIT_TAU = INIT_TAU*D/(lambda * l);
//double TIME_SCALING = lambda * l / D;
// Initial polynomial degree of all mesh elements.
const int P_INIT = 2;
// Number of initial refinements.
const int REF_INIT = 3;
// Multimesh?
const bool MULTIMESH = true;
// 1 for implicit Euler, 2 for Crank-Nicolson.
const int TIME_DISCR = 2;
// 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 = 100;
// Every UNREF_FREQth time step the mesh is unrefined.
const int UNREF_FREQ = 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, 2);
// 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;
// Weak forms.
#include "definitions.cpp"
// Boundary markers.
const std::string BDY_SIDE = "Side";
const std::string BDY_TOP = "Top";
const std::string BDY_BOT = "Bottom";
// scaling methods
double scaleTime(double t) {
return SCALED ? t * D / (lambda * l) : t;
}
double scaleVoltage(double phi) {
return SCALED ? phi * F / (R * T) : phi;
}
double scaleConc(double C) {
return SCALED ? C / C0 : C;
}
double physTime(double t) {
return SCALED ? lambda * l * t / D : t;
}
double physConc(double C) {
return SCALED ? C0 * C : C;
}
double physVoltage(double phi) {
return SCALED ? phi * R * T / F : phi;
}
double SCALED_INIT_TAU = scaleTime(INIT_TAU);
int main(int argc, char* argv[]) {
// Load the mesh file.
MeshSharedPtr C_mesh(new Mesh), phi_mesh(new Mesh), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("small.mesh", basemesh);
if (SCALED) {
bool ret = basemesh->rescale(l, l);
if (ret) {
Hermes::Mixins::Loggable::Static::info("SCALED mesh is used");
}
else {
Hermes::Mixins::Loggable::Static::info("UNSCALED mesh is used");
}
}
// When nonadaptive solution, refine the mesh.
basemesh->refine_towards_boundary(BDY_TOP, REF_INIT);
basemesh->refine_towards_boundary(BDY_BOT, REF_INIT - 1);
basemesh->refine_all_elements(1);
basemesh->refine_all_elements(1);
C_mesh->copy(basemesh);
phi_mesh->copy(basemesh);
DefaultEssentialBCConst<double> bc_phi_voltage(BDY_TOP, scaleVoltage(VOLTAGE));
DefaultEssentialBCConst<double> bc_phi_zero(BDY_BOT, scaleVoltage(0.0));
EssentialBCs<double> bcs_phi(std::vector<EssentialBoundaryCondition<double>* >({ &bc_phi_voltage, &bc_phi_zero }));
SpaceSharedPtr<double> C_space(new H1Space<double>(C_mesh, P_INIT));
SpaceSharedPtr<double> phi_space(new H1Space<double>(MULTIMESH ? phi_mesh : C_mesh, &bcs_phi, P_INIT));
std::vector<SpaceSharedPtr<double> > spaces({ C_space, phi_space });
MeshFunctionSharedPtr<double> C_sln(new Solution<double>), C_ref_sln(new Solution<double>);
MeshFunctionSharedPtr<double> phi_sln(new Solution<double>), phi_ref_sln(new Solution<double>);
// Assign initial condition to mesh->
MeshFunctionSharedPtr<double> C_prev_time(new ConstantSolution<double>(C_mesh, scaleConc(C0)));
MeshFunctionSharedPtr<double> phi_prev_time(new ConstantSolution<double>(MULTIMESH ? phi_mesh : C_mesh, 0.0));
// XXX not necessary probably
if (SCALED) {
TAU = &SCALED_INIT_TAU;
}
// The weak form for 2 equations.
WeakForm<double> *wf;
if (TIME_DISCR == 2) {
if (SCALED) {
wf = new ScaledWeakFormPNPCranic(TAU, ::epsilon, C_prev_time, phi_prev_time);
Hermes::Mixins::Loggable::Static::info("Scaled weak form, with time step %g and epsilon %g", *TAU, ::epsilon);
}
else {
wf = new WeakFormPNPCranic(TAU, C0, K, L, D, C_prev_time, phi_prev_time);
}
}
else {
if (SCALED)
throw Hermes::Exceptions::Exception("Forward Euler is not implemented for scaled problem");
wf = new WeakFormPNPEuler(TAU, C0, K, L, D, C_prev_time);
}
DiscreteProblem<double> dp_coarse(wf, spaces);
NewtonSolver<double>* solver_coarse = new NewtonSolver<double>(&dp_coarse);
// Project the initial condition on the FE space to obtain initial
// coefficient vector for the Newton's method.
Hermes::Mixins::Loggable::Static::info("Projecting to obtain initial vector for the Newton's method.");
int ndof = Space<double>::get_num_dofs({ C_space, phi_space });
double* coeff_vec_coarse = new double[ndof];
OGProjection<double>::project_global({ C_space, phi_space }, { C_prev_time, phi_prev_time },
coeff_vec_coarse);
// Create a selector which will select optimal candidate.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Visualization windows.
char title[1000];
ScalarView Cview("Concentration [mol/m3]", new WinGeom(0, 0, 800, 800));
ScalarView phiview("Voltage [V]", new WinGeom(650, 0, 600, 600));
OrderView Cordview("C order", new WinGeom(0, 300, 600, 600));
OrderView phiordview("Phi order", new WinGeom(600, 300, 600, 600));
Cview.show(C_prev_time);
Cordview.show(C_space);
phiview.show(phi_prev_time);
phiordview.show(phi_space);
// Newton's loop on the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Solving on initial coarse mesh");
try
{
solver_coarse->set_max_allowed_iterations(NEWTON_MAX_ITER);
solver_coarse->set_tolerance(NEWTON_TOL_COARSE, Hermes::Solvers::ResidualNormAbsolute);
solver_coarse->solve(coeff_vec_coarse);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
//View::wait(HERMES_WAIT_KEYPRESS);
// Translate the resulting coefficient vector into the Solution<double> sln->
Solution<double>::vector_to_solutions(solver_coarse->get_sln_vector(), { C_space, phi_space },
{ C_sln, phi_sln });
Cview.show(C_sln);
phiview.show(phi_sln);
// Cleanup after the Newton loop on the coarse mesh.
delete solver_coarse;
delete[] coeff_vec_coarse;
// Time stepping loop.
PidTimestepController pid(scaleTime(T_FINAL), true, scaleTime(INIT_TAU));
TAU = pid.timestep;
Hermes::Mixins::Loggable::Static::info("Starting time iteration with the step %g", *TAU);
NewtonSolver<double> solver;
solver.set_weak_formulation(wf);
do {
pid.begin_step();
// Periodic global derefinements.
if (pid.get_timestep_number() > 1 && pid.get_timestep_number() % UNREF_FREQ == 0)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
C_mesh->copy(basemesh);
if (MULTIMESH)
phi_mesh->copy(basemesh);
C_space->set_uniform_order(P_INIT);
phi_space->set_uniform_order(P_INIT);
C_space->assign_dofs();
phi_space->assign_dofs();
}
// Adaptivity loop. Note: C_prev_time and Phi_prev_time must not be changed during spatial adaptivity.
bool done = false; int as = 1;
double err_est;
do {
Hermes::Mixins::Loggable::Static::info("Time step %d, adaptivity step %d:", pid.get_timestep_number(), as);
// Construct globally refined reference mesh
// and setup reference space.
Mesh::ReferenceMeshCreator refMeshCreatorC(C_mesh);
MeshSharedPtr ref_C_mesh = refMeshCreatorC.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorC(C_space, ref_C_mesh);
SpaceSharedPtr<double> ref_C_space = refSpaceCreatorC.create_ref_space();
Mesh::ReferenceMeshCreator refMeshCreatorPhi(phi_mesh);
MeshSharedPtr ref_phi_mesh = refMeshCreatorPhi.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorPhi(phi_space, ref_phi_mesh);
SpaceSharedPtr<double> ref_phi_space = refSpaceCreatorPhi.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_C_space, ref_phi_space });
int ndof_ref = Space<double>::get_num_dofs(ref_spaces);
// Newton's loop on the fine mesh.
Hermes::Mixins::Loggable::Static::info("Solving on fine mesh:");
try
{
solver.set_spaces(ref_spaces);
solver.set_max_allowed_iterations(NEWTON_MAX_ITER);
solver.set_tolerance(NEWTON_TOL_FINE, Hermes::Solvers::ResidualNormAbsolute);
if (as == 1 && pid.get_timestep_number() == 1)
solver.solve(std::vector<MeshFunctionSharedPtr<double> >({ C_sln, phi_sln }));
else
solver.solve(std::vector<MeshFunctionSharedPtr<double> >({ C_ref_sln, phi_ref_sln }));
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Store the result in ref_sln->
Solution<double>::vector_to_solutions(solver.get_sln_vector(), ref_spaces, { C_ref_sln, phi_ref_sln });
// Projecting reference solution onto the coarse mesh
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh.");
OGProjection<double>::project_global({ C_space, phi_space }, { C_ref_sln, phi_ref_sln }, { C_sln, phi_sln });
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
adaptivity.set_spaces({ C_space, phi_space });
errorCalculator.calculate_errors({ C_sln, phi_sln }, { C_ref_sln, phi_ref_sln });
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse_total: %d, ndof_fine_total: %d, err_est_rel: %g%%",
Space<double>::get_num_dofs({ C_space, phi_space }),
Space<double>::get_num_dofs(ref_spaces), err_est_rel_total);
// If err_est too large, adapt the mesh.
if (err_est_rel_total < ERR_STOP) done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adaptivity.adapt({ &selector, &selector });
Hermes::Mixins::Loggable::Static::info("Adapted...");
as++;
}
// Visualize the solution and mesh.
Hermes::Mixins::Loggable::Static::info("Visualization procedures: C");
char title[100];
sprintf(title, "Solution[C], step# %d, step size %g, time %g, phys time %g",
pid.get_timestep_number(), *TAU, pid.get_time(), physTime(pid.get_time()));
Cview.set_title(title);
Cview.show(C_ref_sln);
sprintf(title, "Mesh[C], step# %d, step size %g, time %g, phys time %g",
pid.get_timestep_number(), *TAU, pid.get_time(), physTime(pid.get_time()));
Cordview.set_title(title);
Cordview.show(C_space);
Hermes::Mixins::Loggable::Static::info("Visualization procedures: phi");
sprintf(title, "Solution[phi], step# %d, step size %g, time %g, phys time %g",
pid.get_timestep_number(), *TAU, pid.get_time(), physTime(pid.get_time()));
phiview.set_title(title);
phiview.show(phi_ref_sln);
sprintf(title, "Mesh[phi], step# %d, step size %g, time %g, phys time %g",
pid.get_timestep_number(), *TAU, pid.get_time(), physTime(pid.get_time()));
phiordview.set_title(title);
phiordview.show(phi_space);
//View::wait(HERMES_WAIT_KEYPRESS);
} while (done == false);
pid.end_step({ C_ref_sln, phi_ref_sln }, { C_prev_time, phi_prev_time });
// TODO! Time step reduction when necessary.
// Copy last reference solution into sln_prev_time
C_prev_time->copy(C_ref_sln);
phi_prev_time->copy(phi_ref_sln);
} while (pid.has_next());
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/nernst-planck/poisson-timedep-adapt/definitions.cpp | .cpp | 16,171 | 465 | #include "definitions.h"
class ScaledWeakFormPNPCranic : public WeakForm<double> {
public:
ScaledWeakFormPNPCranic(double* tau, double epsilon,
MeshFunctionSharedPtr<double> C_prev_time, MeshFunctionSharedPtr<double> phi_prev_time) : WeakForm<double>(2) {
for(unsigned int i = 0; i < 2; i++) {
ScaledWeakFormPNPCranic::Residual* vector_form =
new ScaledWeakFormPNPCranic::Residual(i, tau, epsilon);
if(i == 0) {
vector_form->set_ext({C_prev_time, phi_prev_time});
}
add_vector_form(vector_form);
for(unsigned int j = 0; j < 2; j++)
add_matrix_form(new ScaledWeakFormPNPCranic::Jacobian(i, j, tau, epsilon));
}
};
private:
class Jacobian : public MatrixFormVol<double> {
public:
Jacobian(int i, int j, double* tau, double epsilon) : MatrixFormVol<double>(i, j),
i(i), j(j), tau(tau), epsilon(epsilon) {}
template<typename Real, typename Scalar>
Real matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const {
Real result = Real(0);
Func<Scalar>* prev_newton;
switch(i * 10 + j) {
case 0:
prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * (u->val[i] * v->val[i] / *(this->tau) +
this->epsilon * 0.5 * ((u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]) +
u->val[i] * (prev_newton->dx[i] * v->dx[i] + prev_newton->dy[i] * v->dy[i])));
}
return result;
break;
case 1:
prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * (0.5 * this->epsilon * prev_newton->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
}
return result;
break;
case 10:
for (int i = 0; i < n; i++) {
result += wt[i] * ( -1.0/(2 * this->epsilon * this->epsilon) * u->val[i] * v->val[i]);
}
return result;
break;
case 11:
for (int i = 0; i < n; i++) {
result += wt[i] * ( u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
}
return result;
break;
default:
return result;
}
}
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 matrix_form<double, double>(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 matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* clone() const
{
return new Jacobian(*this);
}
// Members.
int i, j;
double* tau;
double epsilon;
};
class Residual : public VectorFormVol<double>
{
public:
Residual(int i, double* tau, double epsilon)
: VectorFormVol<double>(i), i(i), tau(tau), epsilon(epsilon) {}
template<typename Real, typename Scalar>
Real vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const {
Real result = Real(0);
Func<Scalar>* C_prev_time;
Func<Scalar>* phi_prev_time;
Func<Scalar>* C_prev_newton;
Func<Scalar>* phi_prev_newton;
switch(i) {
case 0:
C_prev_time = ext[0];
phi_prev_time = ext[1];
C_prev_newton = u_ext[0];
phi_prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * ((C_prev_newton->val[i] - C_prev_time->val[i]) * v->val[i] / *(this->tau) +
0.5 * this->epsilon * ((C_prev_newton->dx[i] * v->dx[i] + C_prev_newton->dy[i] * v->dy[i]) +
(C_prev_time->dx[i] * v->dx[i] + C_prev_time->dy[i] * v->dy[i]) +
C_prev_newton->val[i] * (phi_prev_newton->dx[i] * v->dx[i] + phi_prev_newton->dy[i] * v->dy[i]) +
C_prev_time->val[i] * (phi_prev_time->dx[i] * v->dx[i] + phi_prev_time->dy[i] * v->dy[i])));
}
return result;
break;
case 1:
C_prev_newton = u_ext[0];
phi_prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * ((phi_prev_newton->dx[i] * v->dx[i] + phi_prev_newton->dy[i] * v->dy[i]) +
v->val[i] * 1 / (2 * this->epsilon * this->epsilon) * (1 - C_prev_newton->val[i]));
}
return result;
break;
default:
return result;
}
}
virtual double 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);
}
virtual Ord 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>* clone() const
{
return new Residual(*this);
}
// Members.
int i;
double* tau;
double epsilon;
};
};
class WeakFormPNPCranic : public WeakForm<double> {
public:
WeakFormPNPCranic(double* tau, double C0, double K, double L, double D,
MeshFunctionSharedPtr<double> C_prev_time, MeshFunctionSharedPtr<double> phi_prev_time) : WeakForm<double>(2) {
for(unsigned int i = 0; i < 2; i++) {
WeakFormPNPCranic::Residual* vector_form =
new WeakFormPNPCranic::Residual(i, tau, C0, K, L, D);
if(i == 0) {
vector_form->set_ext({C_prev_time, phi_prev_time});
}
add_vector_form(vector_form);
for(unsigned int j = 0; j < 2; j++)
add_matrix_form(new WeakFormPNPCranic::Jacobian(
i, j, tau, C0, K, L, D));
}
};
private:
class Jacobian : public MatrixFormVol<double> {
public:
Jacobian(int i, int j, double* tau, double C0, double K, double L, double D) : MatrixFormVol<double>(i, j),
i(i), j(j), tau(tau), C0(C0), L(L), D(D) {}
template<typename Real, typename Scalar>
Real matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const {
Real result = Real(0);
Func<Scalar>* prev_newton;
switch(i * 10 + j) {
case 0:
prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * (u->val[i] * v->val[i] / *(this->tau) +
this->D * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]) +
this->K * u->val[i] * (prev_newton->dx[i] * v->dx[i] + prev_newton->dy[i] * v->dy[i]));
}
return result;
break;
case 1:
prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * (0.5 * this->K * prev_newton->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
}
return result;
break;
case 10:
for (int i = 0; i < n; i++) {
result += wt[i] * ( -this->L * u->val[i] * v->val[i]);
}
return result;
break;
case 11:
for (int i = 0; i < n; i++) {
result += wt[i] * ( u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
}
return result;
break;
default:
return result;
}
}
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 matrix_form<double, double>(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 matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* clone() const
{
return new Jacobian(*this);
}
// Members.
int i, j;
double* tau;
double C0;
double K;
double L;
double D;
};
class Residual : public VectorFormVol<double>
{
public:
Residual(int i, double* tau, double C0, double K, double L, double D)
: VectorFormVol<double>(i), i(i), tau(tau), C0(C0), K(K), L(L), D(D) {}
template<typename Real, typename Scalar>
Real vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const {
Real result = Real(0);
Func<Scalar>* C_prev_time;
Func<Scalar>* phi_prev_time;
Func<Scalar>* C_prev_newton;
Func<Scalar>* phi_prev_newton;
Func<Scalar>* u1_prev_newton;
Func<Scalar>* u2_prev_newton;
switch(i) {
case 0:
C_prev_time = ext[0];
phi_prev_time = ext[1];
C_prev_newton = u_ext[0];
phi_prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * ((C_prev_newton->val[i] - C_prev_time->val[i]) * v->val[i] / *(this->tau) +
0.5 * this->D * (C_prev_newton->dx[i] * v->dx[i] + C_prev_newton->dy[i] * v->dy[i]) +
0.5 * this->D * (C_prev_time->dx[i] * v->dx[i] + C_prev_time->dy[i] * v->dy[i]) +
0.5 * this->K * C_prev_newton->val[i] * (phi_prev_newton->dx[i] * v->dx[i] + phi_prev_newton->dy[i] * v->dy[i]) +
0.5 * this->K * C_prev_time->val[i] * (phi_prev_time->dx[i] * v->dx[i] + phi_prev_time->dy[i] * v->dy[i]));
}
return result;
break;
case 1:
C_prev_newton = u_ext[0];
phi_prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * ((phi_prev_newton->dx[i] * v->dx[i] + phi_prev_newton->dy[i] * v->dy[i]) +
this->L * v->val[i] * (this->C0 - C_prev_newton->val[i]));
}
return result;
break;
default:
return result;
}
}
virtual double 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);
}
virtual Ord 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>* clone() const
{
return new Residual(*this);
}
// Members.
int i;
double* tau;
double C0;
double K;
double L;
double D;
};
};
class WeakFormPNPEuler : public WeakForm<double>
{
public:
WeakFormPNPEuler(double* tau, double C0, double K, double L, double D, MeshFunctionSharedPtr<double> C_prev_time)
: WeakForm<double>(2) {
for(unsigned int i = 0; i < 2; i++) {
WeakFormPNPEuler::Residual* vector_form =
new WeakFormPNPEuler::Residual(i, tau, C0, K, L, D);
if(i == 0)
vector_form->set_ext(C_prev_time);
add_vector_form(vector_form);
for(unsigned int j = 0; j < 2; j++)
add_matrix_form(new WeakFormPNPEuler::Jacobian(i, j, tau, C0, K, L, D));
}
};
private:
class Jacobian : public MatrixFormVol<double>
{
public:
Jacobian(int i, int j, double* tau, double C0, double K, double L, double D)
: MatrixFormVol<double>(i, j), i(i), j(j), tau(tau), C0(C0), K(K), L(L), D(D) {}
template<typename Real, typename Scalar>
Real matrix_form(int n, double *wt, Func<Scalar> *u_ext[], Func<Real> *u,
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const {
Real result = Real(0);
Func<Scalar>* prev_newton;
switch(i * 10 + j) {
case 0:
prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * (u->val[i] * v->val[i] / *(this->tau) +
0.5 * this->D * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]) +
0.5 * this->K * u->val[i] * (prev_newton->dx[i] * v->dx[i] + prev_newton->dy[i] * v->dy[i]));
}
return result;
break;
case 1:
prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * this->K * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]) * prev_newton->val[i];
}
return result;
break;
case 10:
for (int i = 0; i < n; i++) {
result += wt[i] * ( -this->L * u->val[i] * v->val[i]);
}
return result;
break;
case 11:
for (int i = 0; i < n; i++) {
result += wt[i] * ( u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]);
}
return result;
break;
default:
return result;
}
}
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 matrix_form<double, double>(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 matrix_form<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* clone() const
{
return new Jacobian(*this);
}
// Members.
int i, j;
double* tau;
double C0;
double K;
double L;
double D;
};
class Residual : public VectorFormVol<double>
{
public:
Residual(int i, double* tau, double C0, double K, double L, double D)
: VectorFormVol<double>(i), i(i), tau(tau), C0(C0), K(K), L(L), D(D) {}
template<typename Real, typename Scalar>
Real vector_form(int n, double *wt, Func<Scalar> *u_ext[],
Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const {
Real result = Real(0);
Func<Scalar>* C_prev_time;
Func<Scalar>* C_prev_newton;
Func<Scalar>* phi_prev_newton;
Func<Scalar>* u1_prev_newton;
Func<Scalar>* u2_prev_newton;
switch(i) {
case 0:
C_prev_time = ext[0];
C_prev_newton = u_ext[0];
phi_prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * ((C_prev_newton->val[i] - C_prev_time->val[i]) * v->val[i] / *(this->tau) +
this->D * (C_prev_newton->dx[i] * v->dx[i] + C_prev_newton->dy[i] * v->dy[i]) +
this->K * C_prev_newton->val[i] * (phi_prev_newton->dx[i] * v->dx[i] + phi_prev_newton->dy[i] * v->dy[i]));
}
return result;
break;
case 1:
C_prev_newton = u_ext[0];
phi_prev_newton = u_ext[1];
for (int i = 0; i < n; i++) {
result += wt[i] * ((phi_prev_newton->dx[i] * v->dx[i] + phi_prev_newton->dy[i] * v->dy[i]) +
this->L * v->val[i] * (this->C0 - C_prev_newton->val[i]));
}
return result;
break;
default:
return result;
}
}
virtual double 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);
}
virtual Ord 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>* clone() const
{
return new Residual(*this);
}
// Members.
int i;
double* tau;
double C0;
double K;
double L;
double D;
};
};
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/bearing/definitions.h | .h | 11,067 | 326 | #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::WeakFormsH1;
class WeakFormNSSimpleLinearization : public WeakForm < double >
{
public:
WeakFormNSSimpleLinearization(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time);
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step)
: MatrixFormVol<double>(i, j), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) { 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);
MatrixFormVol<double>* clone() const;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormNonsymVel : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymXVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymYVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 VectorFormVolVel : public VectorFormVol < double >
{
public:
VectorFormVolVel(int i, bool Stokes, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), time_step(time_step) {};
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;
protected:
bool Stokes;
double time_step;
};
protected:
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
class WeakFormNSNewton : public WeakForm < double >
{
public:
WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time);
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step)
: MatrixFormVol<double>(i, j), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step) {
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormNonsymVel_0_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_0_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymXVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymYVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 VectorFormNS_0 : public VectorFormVol < double >
{
public:
VectorFormNS_0(int i, bool Stokes, double Reynolds, double time_step) : VectorFormVol<double>(i),
Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) {};
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_1 : public VectorFormVol < double >
{
public:
VectorFormNS_1(int i, bool Stokes, double Reynolds, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) {};
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_2 : public VectorFormVol < double >
{
public:
VectorFormNS_2(int i) : VectorFormVol<double>(i) {};
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;
};
protected:
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
/* Essential boundary conditions */
// Time-dependent surface x-velocity of inner circle.
class EssentialBCNonConstX : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConstX(std::vector<std::string> markers, double vel, double startup_time)
: EssentialBoundaryCondition<double>(markers), startup_time(startup_time), vel(vel) {};
EssentialBCNonConstX(std::string marker, double vel, double startup_time);
~EssentialBCNonConstX() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
protected:
double startup_time;
double vel;
};
// Time-dependent surface y-velocity of inner circle.
class EssentialBCNonConstY : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConstY(std::vector<std::string> markers, double vel, double startup_time)
: EssentialBoundaryCondition<double>(markers), startup_time(startup_time), vel(vel) {};
EssentialBCNonConstY(std::string marker, double vel, double startup_time);
~EssentialBCNonConstY() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
protected:
double startup_time;
double vel;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/bearing/main.cpp | .cpp | 7,825 | 204 | #include "definitions.h"
// Flow in between two circles, inner circle is rotating with surface
// velocity VEL. The time-dependent laminar incompressible Navier-Stokes equations
// are discretized in time via the implicit Euler method. The Newton's method is
// used to solve the nonlinear problem at each time step. We also show how
// to use discontinuous ($L^2$) elements for pressure and thus make the
// velocity discretely divergence-free. Comparison to approximating the
// pressure with the standard (continuous) Taylor-Hood elements is enabled.
//
// PDE: incompressible Navier-Stokes equations in the form
// \partial v / \partial t - \Delta v / Re + (v \cdot \nabla) v + \nabla p = 0,
// div v = 0.
//
// BC: tangential velocity V on Gamma_1 (inner circle),
// zero velocity on Gamma_2 (outer circle).
//
// Geometry: Area in between two concentric circles with radiuses r1 and r2,
// r1 < r2. These radiuses can be changed in the file "domain.mesh".
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 3;
// Number of initial mesh refinements towards inner boundary.
const int INIT_BDY_REF_NUM_INNER = 2;
// Number of initial mesh refinements towards outer boundary.
const int INIT_BDY_REF_NUM_OUTER = 2;
// For application of Stokes flow (creeping flow).
const bool STOKES = false;
// If this is defined, the pressure is approximated using
// discontinuous L2 elements (making the velocity discreetely
// divergence-free, more accurate than using a continuous
// pressure approximation). Otherwise the standard continuous
// elements are used. The results are striking - check the
// tutorial for comparisons.
#define PRESSURE_IN_L2
// Initial polynomial degree for velocity components.
const int P_INIT_VEL = 2;
// Initial polynomial degree for pressure.
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition.
const int P_INIT_PRESSURE = 1;
// Reynolds number.
const double RE = 5000.0;
// Surface velocity of inner circle.
const double VEL = 0.1;
// During this time, surface velocity of the inner circle increases
// gradually from 0 to VEL, then it stays constant.
const double STARTUP_TIME = 1.0;
// Time step.
const double TAU = 10.;
// Time interval length.
const double T_FINAL = 3600.0;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-5;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 10;
// Current time (used in weak forms).
double current_time = 0.;
// Custom function to calculate drag coefficient.
double integrate_over_wall(MeshFunction<double>* meshfn, int marker)
{
Quad2D* quad = &g_quad_2d_std;
meshfn->set_quad_2d(quad);
double integral = 0.0;
Element* e;
MeshSharedPtr mesh = meshfn->get_mesh();
for_all_active_elements(e, mesh)
{
for (int edge = 0; edge < e->get_nvert(); edge++)
{
if ((e->en[edge]->bnd) && (e->en[edge]->marker == marker))
{
update_limit_table(e->get_mode());
RefMap* ru = meshfn->get_refmap();
meshfn->set_active_element(e);
int eo = quad->get_edge_points(edge, quad->get_max_order(e->get_mode()), e->get_mode());
meshfn->set_quad_order(eo, H2D_FN_VAL);
const double *uval = meshfn->get_fn_values();
double3* pt = quad->get_points(eo, e->get_mode());
double3* tan = ru->get_tangent(edge);
for (int i = 0; i < quad->get_num_points(eo, e->get_mode()); i++)
integral += pt[i][2] * uval[i] * tan[i][2];
}
}
}
return integral * 0.5;
}
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain-excentric.mesh", mesh);
//mloader.load("domain-concentric.mesh", mesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
mesh->refine_all_elements();
// Use 'true' for anisotropic refinements.
mesh->refine_towards_boundary("Inner", INIT_BDY_REF_NUM_INNER, false);
// Use 'false' for isotropic refinements.
mesh->refine_towards_boundary("Outer", INIT_BDY_REF_NUM_OUTER, false);
// Initialize boundary conditions.
EssentialBCNonConstX bc_inner_vel_x(std::string("Inner"), VEL, STARTUP_TIME);
EssentialBCNonConstY bc_inner_vel_y(std::string("Inner"), VEL, STARTUP_TIME);
DefaultEssentialBCConst<double> bc_outer_vel(std::string("Outer"), 0.0);
EssentialBCs<double> bcs_vel_x({ &bc_inner_vel_x, &bc_outer_vel });
EssentialBCs<double> bcs_vel_y({ &bc_inner_vel_y, &bc_outer_vel });
// Spaces for velocity components and pressure.
SpaceSharedPtr<double> xvel_space(new H1Space<double>(mesh, &bcs_vel_x, P_INIT_VEL));
SpaceSharedPtr<double> yvel_space(new H1Space<double>(mesh, &bcs_vel_y, P_INIT_VEL));
#ifdef PRESSURE_IN_L2
SpaceSharedPtr<double> p_space(new L2Space<double>(mesh, P_INIT_PRESSURE));
#else
SpaceSharedPtr<double> p_space(new H1Space<double>(mesh, P_INIT_PRESSURE));
#endif
std::vector<SpaceSharedPtr<double> > spaces({ xvel_space, yvel_space, p_space });
// Calculate and report the number of degrees of freedom.
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Define projection norms.
NormType vel_proj_norm = HERMES_H1_NORM;
#ifdef PRESSURE_IN_L2
NormType p_proj_norm = HERMES_L2_NORM;
#else
NormType p_proj_norm = HERMES_H1_NORM;
#endif
// Solutions for the Newton's iteration and time stepping.
Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
MeshFunctionSharedPtr<double> xvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> yvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> p_prev_time(new ZeroSolution<double>(mesh));
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormNSNewton(STOKES, RE, TAU, xvel_prev_time, yvel_prev_time));
// Initialize views.
VectorView vview("velocity [m/s]", new WinGeom(0, 0, 600, 500));
ScalarView pview("pressure [Pa]", new WinGeom(610, 0, 600, 500));
//vview.set_min_max_range(0, 1.6);
vview.fix_scale_width(80);
//pview.set_min_max_range(-0.9, 1.0);
pview.fix_scale_width(80);
pview.show_mesh(true);
// Initialize the FE problem.
Hermes::Hermes2D::NewtonSolver<double> newton(wf, spaces);
newton.set_verbose_output(true);
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
// Time-stepping loop:
char title[100];
int num_time_steps = T_FINAL / TAU;
for (int ts = 1; ts <= num_time_steps; ts++)
{
current_time += TAU;
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time = %g:", ts, current_time);
// Update time-dependent essential BCs.
Hermes::Mixins::Loggable::Static::info("Updating time-dependent essential BC.");
Space<double>::update_essential_bc_values(spaces, current_time);
// Perform Newton's iteration.
Hermes::Mixins::Loggable::Static::info("Solving nonlinear problem:");
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Update previous time level solutions.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, { xvel_prev_time, yvel_prev_time, p_prev_time });
// Show the solution at the end of time step.
sprintf(title, "Velocity, time %g", current_time);
vview.set_title(title);
vview.show(xvel_prev_time, yvel_prev_time);
sprintf(title, "Pressure, time %g", current_time);
pview.set_title(title);
pview.show(p_prev_time);
}
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/bearing/definitions.cpp | .cpp | 19,507 | 530 | #include "definitions.h"
WeakFormNSSimpleLinearization::WeakFormNSSimpleLinearization(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time) : WeakForm<double>(3), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time)
{
BilinearFormSymVel* sym_form_0 = new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_0);
BilinearFormSymVel* sym_form_1 = new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_1);
BilinearFormNonsymVel* nonsym_vel_form_0 = new BilinearFormNonsymVel(0, 0, Stokes);
nonsym_vel_form_0->set_ext(std::vector<MeshFunctionSharedPtr<double> >({ x_vel_previous_time, y_vel_previous_time }));
add_matrix_form(nonsym_vel_form_0);
BilinearFormNonsymVel* nonsym_vel_form_1 = new BilinearFormNonsymVel(1, 1, Stokes);
nonsym_vel_form_1->set_ext(std::vector<MeshFunctionSharedPtr<double> >({ x_vel_previous_time, y_vel_previous_time }));
add_matrix_form(nonsym_vel_form_1);
// Pressure term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymXVelPressure(0, 2));
// Pressure term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymYVelPressure(1, 2));
VectorFormVolVel* vector_vel_form_x = new VectorFormVolVel(0, Stokes, time_step);
vector_vel_form_x->set_ext(x_vel_previous_time);
VectorFormVolVel* vector_vel_form_y = new VectorFormVolVel(1, Stokes, time_step);
vector_vel_form_y->set_ext(y_vel_previous_time);
}
double WeakFormNSSimpleLinearization::BilinearFormSymVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord WeakFormNSSimpleLinearization::BilinearFormSymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext)
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormSymVel::clone() const
{
return new BilinearFormSymVel(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymVel::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 (!Stokes)
{
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
result = int_w_nabla_u_v<double, double>(n, wt, xvel_prev_time, yvel_prev_time, u, v);
}
return result;
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
result = int_w_nabla_u_v<Ord, Ord>(n, wt, xvel_prev_time, yvel_prev_time, u, v);
}
return result;
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymVel::clone() const
{
return new BilinearFormNonsymVel(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::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_dvdx<double, double>(n, wt, u, v);
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::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_dvdx<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::clone() const
{
return new BilinearFormNonsymXVelPressure(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::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_dvdy<double, double>(n, wt, u, v);
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::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_dvdy<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::clone() const
{
return new BilinearFormNonsymYVelPressure(*this);
}
double WeakFormNSSimpleLinearization::VectorFormVolVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
if (!Stokes)
{
Func<double>* vel_prev_time = ext[0]; // this form is used with both velocity components
result = int_u_v<double, double>(n, wt, vel_prev_time, v) / time_step;
}
return result;
}
Ord WeakFormNSSimpleLinearization::VectorFormVolVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* vel_prev_time = ext[0]; // this form is used with both velocity components
result = int_u_v<Ord, Ord>(n, wt, vel_prev_time, v) / time_step;
}
return result;
}
VectorFormVol<double>* WeakFormNSSimpleLinearization::VectorFormVolVel::clone() const
{
return new VectorFormVolVel(*this);
}
WeakFormNSNewton::WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time) : WeakForm<double>(3), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time)
{
/* Jacobian terms - first velocity equation */
// Time derivative in the first velocity equation
// and Laplacian divided by Re in the first velocity equation.
add_matrix_form(new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step));
// First part of the convective term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymVel_0_0(0, 0, Stokes));
// Second part of the convective term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymVel_0_1(0, 1, Stokes));
// Pressure term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymXVelPressure(0, 2));
/* Jacobian terms - second velocity equation, continuity equation */
// Time derivative in the second velocity equation
// and Laplacian divided by Re in the second velocity equation.
add_matrix_form(new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step));
// First part of the convective term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymVel_1_0(1, 0, Stokes));
// Second part of the convective term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymVel_1_1(1, 1, Stokes));
// Pressure term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymYVelPressure(1, 2));
/* Residual - volumetric */
// First velocity equation.
VectorFormNS_0* F_0 = new VectorFormNS_0(0, Stokes, Reynolds, time_step);
F_0->set_ext(x_vel_previous_time);
add_vector_form(F_0);
// Second velocity equation.
VectorFormNS_1* F_1 = new VectorFormNS_1(1, Stokes, Reynolds, time_step);
F_1->set_ext(y_vel_previous_time);
add_vector_form(F_1);
// Continuity equation.
VectorFormNS_2* F_2 = new VectorFormNS_2(2);
add_vector_form(F_2);
}
double WeakFormNSNewton::BilinearFormSymVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord WeakFormNSNewton::BilinearFormSymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormSymVel::clone() const
{
return new BilinearFormSymVel(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_0::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 (!Stokes)
{
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * xvel_prev_newton->dx[i]) * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i]
* u->dy[i]) * v->val[i] + u->val[i] * v->val[i] * xvel_prev_newton->dx[i]);
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_0_0::clone() const
{
return new BilinearFormNonsymVel_0_0(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_1::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 (!Stokes)
{
Func<double>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * xvel_prev_newton->dy[i] * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * xvel_prev_newton->dy[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_0_1::clone() const
{
return new BilinearFormNonsymVel_0_1(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_0::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 (!Stokes)
{
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_1_0::clone() const
{
return new BilinearFormNonsymVel_1_0(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_1::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 (!Stokes)
{
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * yvel_prev_newton->dy[i]) * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * yvel_prev_newton->dy[i]) * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_1_1::clone() const
{
return new BilinearFormNonsymVel_1_1(*this);
}
double WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymXVelPressure::clone() const
{
return new BilinearFormNonsymXVelPressure(*this);
}
double WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymYVelPressure::clone() const
{
return new BilinearFormNonsymYVelPressure(*this);
}
double WeakFormNSNewton::VectorFormNS_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_0::clone() const
{
return new VectorFormNS_0(*this);
}
double WeakFormNSNewton::VectorFormNS_1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* yvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->dx[i] * v->dx[i] + yvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dy[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * yvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * yvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* yvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_1::clone() const
{
return new VectorFormNS_1(*this);
}
double WeakFormNSNewton::VectorFormNS_2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
Ord WeakFormNSNewton::VectorFormNS_2::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_2::clone() const
{
return new VectorFormNS_2(*this);
}
EssentialBCNonConstX::EssentialBCNonConstX(std::string marker, double vel, double startup_time)
: EssentialBoundaryCondition<double>(marker), startup_time(startup_time), vel(vel)
{
}
EssentialBCValueType EssentialBCNonConstX::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConstX::value(double x, double y) const
{
double velocity;
if (current_time <= startup_time) velocity = vel * current_time / startup_time;
else velocity = vel;
double alpha = std::atan2(x, y);
double xvel = velocity*std::cos(alpha);
return xvel;
}
EssentialBCNonConstY::EssentialBCNonConstY(std::string marker, double vel, double startup_time) :
EssentialBoundaryCondition<double>(marker), startup_time(startup_time), vel(vel)
{
}
EssentialBCValueType EssentialBCNonConstY::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConstY::value(double x, double y) const
{
double velocity;
if (current_time <= startup_time) velocity = vel * current_time / startup_time;
else velocity = vel;
double alpha = std::atan2(x, y);
double yvel = -velocity*std::sin(alpha);
return yvel;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/rayleigh-benard/definitions.h | .h | 246 | 9 | #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::WeakFormsH1; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/rayleigh-benard/main.cpp | .cpp | 7,351 | 186 | #include "definitions.h"
// This example solves the Rayleigh-Benard convection problem
// http://en.wikipedia.org/wiki/Rayleigh%E2%80%93B%C3%A9nard_convection.
// In this problem, a steady fluid is heated from the bottom and
// it starts to move. The time-dependent laminar incompressible Navier-Stokes
// equations are coupled with a heat transfer equation and discretized
// in time via the implicit Euler method. The Newton's method is used
// to solve the nonlinear problem at each time step. Flow pressure can be
// approximated using either continuous (H1) elements or discontinuous (L2)
// elements. The L2 elements for pressure make the velocity dicreetely
// divergence-free.
//
// PDE: incompressible Navier-Stokes equations in the form
// \partial v / \partial t = \Delta v / Pr - (v \cdot \nabla) v - \nabla p - Ra(T)Pr(0, -T),
// div v = 0,
// \partial T / \partial t = -v \cdot \nabla T + \Delta T.
//
// BC: velocity... zero on the entire boundary,
// temperature... constant on the bottom,
// zero Neumann on vetrical edges,
// Newton (heat loss) (1 / Pr) * du/dn = ALPHA_AIR * (TEMP_EXT - u) on the top edge.
//
// Geometry: Rectangle (0, Lx) x (0, Ly)... see the file domain.mesh->
//
// The following parameters can be changed:
// If this is defined, the pressure is approximated using
// discontinuous L2 elements (making the velocity discreetely
// divergence-free, more accurate than using a continuous
// pressure approximation). Otherwise the standard continuous
// elements are used. The results are striking - check the
// tutorial for comparisons.
#define PRESSURE_IN_L2
// Initial polynomial degree for velocity components.
const int P_INIT_VEL = 2;
// Initial polynomial degree for pressure.
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition.
const int P_INIT_PRESSURE = 1;
// Initial polynomial degree for temperature.
const int P_INIT_TEMP = 1;
// Time step.
const double time_step = 0.1;
// Time interval length.
const double T_FINAL = 3600.0;
// 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;
// Problem parameters.
// Prandtl number (water has 7.0 around 20 degrees Celsius).
const double Pr = 7.0;
// Rayleigh number.
const double Ra = 100;
const double TEMP_INIT = 20;
const double TEMP_BOTTOM = 25;
// External temperature above the surface of the water.
const double TEMP_EXT = 20;
// Heat transfer coefficient between water and air on top edge.
const double ALPHA_AIR = 5.0;
// Weak forms.
#include "definitions.cpp"
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Initial mesh refinements.
for (int i = 0; i < 3; i++) mesh->refine_all_elements(2);
for (int i = 0; i < 3; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary(HERMES_ANY, 2);
// Initialize boundary conditions.
DefaultEssentialBCConst<double> zero_vel_bc({ "Bottom", "Right", "Top", "Left" }, 0.0);
EssentialBCs<double> bcs_vel_x(&zero_vel_bc);
EssentialBCs<double> bcs_vel_y(&zero_vel_bc);
DefaultEssentialBCConst<double> bc_temp_bottom("Bottom", TEMP_BOTTOM);
EssentialBCs<double> bcs_temp(&bc_temp_bottom);
SpaceSharedPtr<double> xvel_space(new H1Space<double>(mesh, &bcs_vel_x, P_INIT_VEL));
SpaceSharedPtr<double> yvel_space(new H1Space<double>(mesh, &bcs_vel_y, P_INIT_VEL));
#ifdef PRESSURE_IN_L2
SpaceSharedPtr<double> p_space(new L2Space<double>(mesh, P_INIT_PRESSURE));
#else
SpaceSharedPtr<double> p_space(new H1Space<double>(mesh, P_INIT_PRESSURE));
#endif
SpaceSharedPtr<double> t_space(new H1Space<double>(mesh, &bcs_temp, P_INIT_TEMP));
std::vector<SpaceSharedPtr<double> > spaces({ xvel_space, yvel_space, p_space, t_space });
// Calculate and report the number of degrees of freedom.
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Define projection norms.
NormType vel_proj_norm = HERMES_H1_NORM;
#ifdef PRESSURE_IN_L2
NormType p_proj_norm = HERMES_L2_NORM;
#else
NormType p_proj_norm = HERMES_H1_NORM;
#endif
NormType t_proj_norm = HERMES_H1_NORM;
// Solutions for the Newton's iteration and time stepping.
Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
MeshFunctionSharedPtr<double> xvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> yvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> p_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> t_prev_time(new ConstantSolution<double>(mesh, TEMP_INIT));
std::vector<MeshFunctionSharedPtr<double> > slns({ xvel_prev_time, yvel_prev_time, p_prev_time, t_prev_time });
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormRayleighBenard(Pr, Ra, "Top", TEMP_EXT, ALPHA_AIR, time_step,
xvel_prev_time, yvel_prev_time, t_prev_time));
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, spaces);
// Initialize views.
VectorView vview("velocity", new WinGeom(0, 0, 1000, 200));
ScalarView tview("temperature", new WinGeom(0, 255, 1000, 200));
ScalarView pview("pressure", new WinGeom(0, 485, 1000, 200));
//vview.set_min_max_range(0, 1.6);
vview.fix_scale_width(80);
pview.fix_scale_width(80);
tview.fix_scale_width(80);
pview.show_mesh(true);
// Project the initial condition on the FE space to obtain initial
// coefficient vector for the Newton's method.
double* coeff_vec = new double[Space<double>::get_num_dofs(spaces)];
Hermes::Mixins::Loggable::Static::info("Projecting initial condition to obtain initial vector for the Newton's method.");
OGProjection<double>::project_global(spaces, slns, coeff_vec,
std::vector<NormType>({ vel_proj_norm, vel_proj_norm, p_proj_norm, t_proj_norm }));
Hermes::Hermes2D::NewtonSolver<double> newton(&dp);
// Time-stepping loop:
char title[100];
double current_time = 0;
int num_time_steps = T_FINAL / time_step;
for (int ts = 1; ts <= num_time_steps; ts++)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time = %g:", ts, current_time);
// Perform Newton's iteration.
newton.set_verbose_output(true);
try
{
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.solve(coeff_vec);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Update previous time level solutions.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, slns);
// Show the solution at the end of time step.
sprintf(title, "Velocity, time %g", current_time);
vview.set_title(title);
vview.show(xvel_prev_time, yvel_prev_time);
sprintf(title, "Pressure, time %g", current_time);
pview.set_title(title);
pview.show(p_prev_time);
tview.show(t_prev_time);
// Update current time.
current_time += time_step;
}
// Clean up.
delete[] coeff_vec;
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/rayleigh-benard/definitions.cpp | .cpp | 22,362 | 522 | #include "definitions.h"
/* Weak forms */
class WeakFormRayleighBenard : public WeakForm < double >
{
public:
WeakFormRayleighBenard(double Pr, double Ra, std::string bdy_top, double temp_ext, double alpha_air,
double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time, MeshFunctionSharedPtr<double> temp_previous_time)
: WeakForm<double>(4), Pr(Pr), Ra(Ra), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time), temp_previous_time(temp_previous_time) {
/* Jacobian terms - first velocity equation */
// Time derivative in the first velocity equation.
add_matrix_form(new DefaultMatrixFormVol<double>(0, 0, HERMES_ANY, new Hermes2DFunction<double>(1. / time_step)));
// Laplacian divided by Pr in the first velocity equation.
add_matrix_form(new DefaultJacobianDiffusion<double>(0, 0, HERMES_ANY, new Hermes1DFunction<double>(1. / Pr)));
// First part of the convective term in the first velocity equation.
BilinearFormNonsymVel_0_0* nonsym_vel_form_0_0 = new BilinearFormNonsymVel_0_0(0, 0);
add_matrix_form(nonsym_vel_form_0_0);
// Second part of the convective term in the first velocity equation.
BilinearFormNonsymVel_0_1* nonsym_vel_form_0_1 = new BilinearFormNonsymVel_0_1(0, 1);
add_matrix_form(nonsym_vel_form_0_1);
// Pressure term in the first velocity equation.
BilinearFormNonsymXVelPressure* nonsym_velx_pressure_form = new BilinearFormNonsymXVelPressure(0, 2);
add_matrix_form(nonsym_velx_pressure_form);
/* Jacobian terms - second velocity equation, continuity equation */
// Time derivative in the second velocity equation.
add_matrix_form(new DefaultMatrixFormVol<double>(1, 1, HERMES_ANY, new Hermes2DFunction<double>(1. / time_step)));
// Laplacian divided by Pr in the second velocity equation.
add_matrix_form(new DefaultJacobianDiffusion<double>(1, 1, HERMES_ANY, new Hermes1DFunction<double>(1. / Pr)));
// First part of the convective term in the second velocity equation.
BilinearFormNonsymVel_1_0* nonsym_vel_form_1_0 = new BilinearFormNonsymVel_1_0(1, 0);
add_matrix_form(nonsym_vel_form_1_0);
// Second part of the convective term in the second velocity equation.
BilinearFormNonsymVel_1_1* nonsym_vel_form_1_1 = new BilinearFormNonsymVel_1_1(1, 1);
add_matrix_form(nonsym_vel_form_1_1);
// Pressure term in the second velocity equation.
BilinearFormNonsymYVelPressure* nonsym_vely_pressure_form = new BilinearFormNonsymYVelPressure(1, 2);
add_matrix_form(nonsym_vely_pressure_form);
// Temperature term in the second velocity equation.
add_matrix_form(new DefaultMatrixFormVol<double>(1, 3, HERMES_ANY, new Hermes2DFunction<double>(Ra * Pr)));
/* Jacobian terms - temperature equation */
// Time derivative in the temperature equation.
add_matrix_form(new DefaultMatrixFormVol<double>(3, 3, HERMES_ANY, new Hermes2DFunction<double>(1. / time_step)));
// Laplacian in the temperature equation.
add_matrix_form(new DefaultJacobianDiffusion<double>(3, 3));
// First part of temperature advection term.
add_matrix_form(new BilinearFormNonsymTemp_3_0(3, 0));
// Second part of temperature advection term.
add_matrix_form(new BilinearFormNonsymTemp_3_1(3, 1));
// Third part of temperature advection term.
add_matrix_form(new BilinearFormNonsymTemp_3_3(3, 3));
// Surface term generated by the Newton condition on top edge.
add_matrix_form_surf(new DefaultMatrixFormSurf<double>(3, 3, bdy_top, new Hermes2DFunction<double>(alpha_air)));
/* Residual - volumetric */
// First velocity equation.
VectorFormNS_0* F_0 = new VectorFormNS_0(0, Pr, time_step);
F_0->set_ext(x_vel_previous_time);
add_vector_form(F_0);
// Second velocity equation.
VectorFormNS_1* F_1 = new VectorFormNS_1(1, Pr, Ra, time_step);
F_1->set_ext(y_vel_previous_time);
add_vector_form(F_1);
// Continuity equation.
VectorFormNS_2* F_2 = new VectorFormNS_2(2);
add_vector_form(F_2);
// Temperature equation.
VectorFormNS_3* F_3 = new VectorFormNS_3(3, time_step);
F_3->set_ext(temp_previous_time);
add_vector_form(F_3);
add_vector_form_surf(new DefaultVectorFormSurf<double>(3, bdy_top, new Hermes2DFunction<double>(-alpha_air * temp_ext)));
add_vector_form_surf(new CustomResidualSurfConst(3, bdy_top, alpha_air));
};
class BilinearFormNonsymVel_0_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_0(int i, int j) : MatrixFormVol<double>(i, j) {
}
virtual 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;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i]
+ u->val[i] * xvel_prev_newton->dx[i] * v->val[i]);
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i]
+ u->val[i] * xvel_prev_newton->dx[i] * v->val[i]);
return result;
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymVel_0_0(i, j); }
};
class BilinearFormNonsymVel_0_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_1(int i, int j) : MatrixFormVol<double>(i, j) {
}
virtual 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;
Func<double>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * xvel_prev_newton->dy[i] * v->val[i];
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * xvel_prev_newton->dy[i]);
return result;
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymVel_0_1(i, j); }
};
class BilinearFormNonsymVel_1_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_0(int i, int j) : MatrixFormVol<double>(i, j) {
}
virtual 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;
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
return result;
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymVel_1_0(i, j); }
};
class BilinearFormNonsymVel_1_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_1(int i, int j) : MatrixFormVol<double>(i, j) {
}
virtual 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;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i]
+ u->val[i] * yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i]
+ u->val[i] * yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymVel_1_1(i, j); }
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
// The antisym flag is used here to generate a term in the continuity equation.
BilinearFormNonsymXVelPressure(int i, int j) : MatrixFormVol<double>(i, j) {
this->setSymFlag(HERMES_ANTISYM);
}
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 -int_u_dvdx<double, double>(n, wt, u, v);
}
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 -int_u_dvdx<Ord, Ord>(n, wt, u, v);
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymXVelPressure(i, j); }
};
class BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
// The antisym flag is used here to generate a term in the continuity equation.
BilinearFormNonsymYVelPressure(int i, int j) : MatrixFormVol<double>(i, j) {
this->setSymFlag(HERMES_ANTISYM);
}
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 -int_u_dvdy<double, double>(n, wt, u, v);
}
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 -int_u_dvdy<Ord, Ord>(n, wt, u, v);
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymYVelPressure(i, j); }
};
class VectorFormNS_0 : public VectorFormVol < double >
{
public:
VectorFormNS_0(int i, double Pr, double time_step) : VectorFormVol<double>(i), Pr(Pr), time_step(time_step) {
}
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const {
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Pr
- (p_prev_newton->val[i] * v->dx[i]));
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Pr
- (p_prev_newton->val[i] * v->dx[i]));
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
virtual VectorFormVol<double>* clone() const { return new VectorFormNS_0(i, Pr, time_step); }
protected:
double Pr, time_step;
};
class VectorFormNS_1 : public VectorFormVol < double >
{
public:
VectorFormNS_1(int i, double Pr, double Ra, double time_step)
: VectorFormVol<double>(i), Pr(Pr), Ra(Ra), time_step(time_step) {
}
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const {
double result = 0;
Func<double>* yvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
Func<double>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->dx[i] * v->dx[i] + yvel_prev_newton->dy[i] * v->dy[i]) / Pr
- (p_prev_newton->val[i] * v->dy[i]));
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step
+ ((xvel_prev_newton->val[i] * yvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * yvel_prev_newton->dy[i]) * v->val[i])
+ Pr*Ra*temp_prev_newton->val[i] * v->val[i]);
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* yvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
Func<Ord>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Pr
- (p_prev_newton->val[i] * v->dx[i]));
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i])
+ Pr*Ra*temp_prev_newton->val[i] * v->val[i]);
return result;
}
virtual VectorFormVol<double>* clone() const { return new VectorFormNS_1(i, Pr, Ra, time_step); }
protected:
double Pr, Ra, time_step;
};
class VectorFormNS_2 : public VectorFormVol < double >
{
public:
VectorFormNS_2(int i) : VectorFormVol<double>(i) {
}
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const {
double result = 0;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] + yvel_prev_newton->dy[i]) * v->val[i];
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] + yvel_prev_newton->dy[i]) * v->val[i];
return result;
}
virtual VectorFormVol<double>* clone() const { return new VectorFormNS_2(i); }
};
class VectorFormNS_3 : public VectorFormVol < double >
{
public:
VectorFormNS_3(int i, double time_step) : VectorFormVol<double>(i), time_step(time_step) {
}
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const {
double result = 0;
Func<double>* temp_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * (((temp_prev_newton->val[i] - temp_prev_time->val[i]) / time_step
+ xvel_prev_newton->val[i] * temp_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * temp_prev_newton->dy[i]) * v->val[i]
+ temp_prev_newton->dx[i] * v->dx[i] + temp_prev_newton->dy[i] * v->dy[i]
);
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* temp_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * (((temp_prev_newton->val[i] - temp_prev_time->val[i]) / time_step
+ xvel_prev_newton->val[i] * temp_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * temp_prev_newton->dy[i]) * v->val[i]
+ temp_prev_newton->dx[i] * v->dx[i] + temp_prev_newton->dy[i] * v->dy[i]
);
return result;
}
virtual VectorFormVol<double>* clone() const { return new VectorFormNS_3(i, time_step); }
private:
double time_step;
};
class BilinearFormNonsymTemp_3_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymTemp_3_0(int i, int j) : MatrixFormVol<double>(i, j) {
}
virtual 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;
Func<double>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * temp_prev_newton->dx[i] * v->val[i];
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * temp_prev_newton->dx[i] * v->val[i];
return result;
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymTemp_3_0(i, j); }
};
class BilinearFormNonsymTemp_3_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymTemp_3_1(int i, int j) : MatrixFormVol<double>(i, j) {
}
virtual 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;
Func<double>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * temp_prev_newton->dy[i] * v->val[i];
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* temp_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * temp_prev_newton->dy[i] * v->val[i];
return result;
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymTemp_3_1(i, j); }
};
class BilinearFormNonsymTemp_3_3 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymTemp_3_3(int i, int j) : MatrixFormVol<double>(i, j) {
}
virtual 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;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]) * v->val[i];
return result;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]) * v->val[i];
return result;
}
virtual MatrixFormVol<double>* clone() const { return new BilinearFormNonsymTemp_3_3(i, j); }
};
class CustomResidualSurfConst : public VectorFormSurf < double >
{
public:
CustomResidualSurfConst(int i, double coeff = 1.0,
GeomType gt = HERMES_PLANAR)
: VectorFormSurf<double>(i), coeff(coeff), gt(gt) { }
CustomResidualSurfConst(int i, std::string area, double coeff = 1.0,
GeomType gt = HERMES_PLANAR)
: VectorFormSurf<double>(i), coeff(coeff), gt(gt) { 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 {
Scalar result = Scalar(0);
for (int i = 0; i < n; i++) {
result += wt[i] * u_ext[3]->val[i] * v->val[i];
}
return coeff * result;
}
virtual double 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);
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord>* *ext) const {
return vector_form_surf<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
// This is to make the form usable in rk_time_step_newton().
virtual VectorFormSurf<double>* clone() const {
return new CustomResidualSurfConst(*this);
}
private:
double coeff;
GeomType gt;
};
protected:
double Pr, Ra, time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
MeshFunctionSharedPtr<double> temp_previous_time;
}; | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/circular-obstacle-adapt/definitions.h | .h | 10,196 | 314 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
class WeakFormNSSimpleLinearization : public WeakForm < double >
{
public:
WeakFormNSSimpleLinearization(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time);
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step);
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);
virtual MatrixFormVol<double>* clone() const;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormNonsymVel : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel(unsigned int i, unsigned int j, bool Stokes);
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;
protected:
bool Stokes;
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymXVelPressure(int i, int j);
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;
};
class BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymYVelPressure(int i, int j);
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;
};
class VectorFormVolVel : public VectorFormVol < double >
{
public:
VectorFormVolVel(int i, bool Stokes, double time_step);
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;
protected:
bool Stokes;
double time_step;
};
protected:
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
class WeakFormNSNewton : public WeakForm < double >
{
public:
WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time);
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step);
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 BilinearFormSymVel(this->i, this->j, this->Stokes, this->Reynolds, this->time_step);
}
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormNonsymVel_0_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_0(unsigned int i, unsigned int j, bool Stokes);
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 BilinearFormNonsymVel_0_0(this->i, this->j, this->Stokes);
}
protected:
bool Stokes;
};
class BilinearFormNonsymVel_0_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_1(unsigned int i, unsigned int j, bool Stokes);
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 BilinearFormNonsymVel_0_1(this->i, this->j, this->Stokes);
}
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_0(unsigned int i, unsigned int j, bool Stokes);
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 BilinearFormNonsymVel_1_0(this->i, this->j, this->Stokes);
}
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_1(unsigned int i, unsigned int j, bool Stokes);
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 BilinearFormNonsymVel_1_1(this->i, this->j, this->Stokes);
}
protected:
bool Stokes;
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymXVelPressure(int i, int j);
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 BilinearFormNonsymXVelPressure(this->i, this->j);
}
};
class BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymYVelPressure(int i, int j);
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 BilinearFormNonsymYVelPressure(this->i, this->j);
}
};
class VectorFormNS_0 : public VectorFormVol < double >
{
public:
VectorFormNS_0(int i, bool Stokes, double Reynolds, double time_step);
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 VectorFormNS_0(this->i, this->Stokes, this->Reynolds, this->time_step);
}
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_1 : public VectorFormVol < double >
{
public:
VectorFormNS_1(int i, bool Stokes, double Reynolds, double time_step);
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 VectorFormNS_1(this->i, this->Stokes, this->Reynolds, this->time_step);
}
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_2 : public VectorFormVol < double >
{
public:
VectorFormNS_2(int i);
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 VectorFormNS_2(this->i);
}
};
protected:
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
class EssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConst(std::vector<std::string> markers, double vel_inlet, double H, double startup_time)
: EssentialBoundaryCondition<double>(markers), startup_time(startup_time), vel_inlet(vel_inlet), H(H) {};
EssentialBCNonConst(std::string marker, double vel_inlet, double H, double startup_time);
~EssentialBCNonConst() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
protected:
double startup_time;
double vel_inlet;
double H;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/circular-obstacle-adapt/main.cpp | .cpp | 14,706 | 337 | #include "definitions.h"
// The time-dependent laminar incompressible Navier-Stokes equations are
// discretized in time via the implicit Euler method. The Newton's method
// is used to solve the nonlinear problem at each time step. We show how
// to use discontinuous ($L^2$) elements for pressure and thus make the
// velocity discreetely divergence free. Comparison to approximating the
// pressure with the standard (continuous) Taylor-Hood elements is enabled.
// The Reynolds number Re = 200 which is embarrassingly low. You
// can increase it but then you will need to make the mesh finer, and the
// computation will take more time.
//
// PDE: incompressible Navier-Stokes equations in the form
// \partial v / \partial t - \Delta v / Re + (v \cdot \nabla) v + \nabla p = 0,
// div v = 0
//
// BC: u_1 is a time-dependent constant and u_2 = 0 on Gamma_4 (inlet)
// u_1 = u_2 = 0 on Gamma_1 (bottom), Gamma_3 (top) and Gamma_5 (obstacle)
// "do nothing" on Gamma_2 (outlet)
//
// Geometry: Rectangular channel containing an off-axis circular obstacle. The
// radius and position of the circle, as well as other geometry
// parameters can be changed in the mesh file "domain.mesh".
//
// The following parameters can be changed:
// For application of Stokes flow (creeping flow).
const bool STOKES = false;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 0;
// Number of initial mesh refinements towards boundary.
const int INIT_REF_NUM_BDY = 0;
const int INIT_REF_NUM_OBSTACLE = 0;
// If this is defined, the pressure is approximated using
// discontinuous L2 elements (making the velocity discreetely
// divergence-free, more accurate than using a continuous
// pressure approximation). Otherwise the standard continuous
// elements are used. The results are striking - check the
// tutorial for comparisons.
#define PRESSURE_IN_L2
// Initial polynomial degree for velocity components.
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition.
const int P_INIT_VEL = 2;
// Initial polynomial degree for pressure.
const int P_INIT_PRESSURE = 1;
// Adaptivity
// Every UNREF_FREQth time step the mesh is unrefined.
const int UNREF_FREQ = 5;
bool FORCE_DEREFINEMENT = false;
const int NOT_ADAPTING_REF_SPACES_SIZE = 6e4;
const int FORCE_DEREFINEMENT_REF_SPACES_SIZE = 1e5;
// Error calculation & adaptivity.
class CustomErrorCalculator : public DefaultErrorCalculator < double, HERMES_H1_NORM >
{
public:
// Two first components are in the H1 space - we can use the classic class for that, for the last component, we will manually add the L2 norm for pressure.
CustomErrorCalculator(CalculatedErrorType errorType) : DefaultErrorCalculator<double, HERMES_H1_NORM>(errorType, 2)
{
this->add_error_form(new DefaultNormFormVol<double>(2, 2, HERMES_L2_NORM, SolutionsDifference));
}
} errorCalculator(RelativeErrorToGlobalNorm);
// Stopping criterion for an adaptivity step.
const double THRESHOLD = 0.7;
AdaptStoppingCriterionSingleElement<double> stoppingCriterion(THRESHOLD);
// Adaptivity processor class.
Adapt<double> adaptivity(&errorCalculator, &stoppingCriterion);
// 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_H_ISO;
// Stopping criterion for adaptivity.
const double ERR_STOP = 1e-4;
// Problem parameters
// Reynolds number.
const double RE = 200.0;
// Inlet velocity (reached after STARTUP_TIME).
const double VEL_INLET = 1.0;
// During this time, inlet velocity increases gradually
// from 0 to VEL_INLET, then it stays constant.
const double STARTUP_TIME = 1.0;
// Time step.
const double TAU = 0.1;
// Time interval length.
const double T_FINAL = 30000.0;
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL = 0.05;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 20;
// Domain height (necessary to define the parabolic
// velocity profile at inlet).
const double H = 5;
// Boundary markers.
const std::string BDY_BOTTOM = "b1";
const std::string BDY_RIGHT = "b2";
const std::string BDY_TOP = "b3";
const std::string BDY_LEFT = "b4";
const std::string BDY_OBSTACLE = "b5";
// Current time (used in weak forms).
double current_time = 0;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", basemesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
basemesh->refine_all_elements();
basemesh->refine_towards_boundary(BDY_OBSTACLE, INIT_REF_NUM_OBSTACLE, false);
basemesh->refine_towards_boundary(BDY_TOP, INIT_REF_NUM_BDY, false);
basemesh->refine_towards_boundary(BDY_BOTTOM, INIT_REF_NUM_BDY, false);
mesh->copy(basemesh);
// Initialize boundary conditions.
EssentialBCNonConst bc_left_vel_x(BDY_LEFT, VEL_INLET, H, STARTUP_TIME);
DefaultEssentialBCConst<double> bc_other_vel_x({ BDY_BOTTOM, BDY_TOP, BDY_OBSTACLE }, 0.0);
EssentialBCs<double> bcs_vel_x({ &bc_left_vel_x, &bc_other_vel_x });
DefaultEssentialBCConst<double> bc_vel_y({ BDY_LEFT, BDY_BOTTOM, BDY_TOP, BDY_OBSTACLE }, 0.0);
EssentialBCs<double> bcs_vel_y(&bc_vel_y);
SpaceSharedPtr<double> xvel_space(new H1Space<double>(mesh, &bcs_vel_x, P_INIT_VEL));
SpaceSharedPtr<double> yvel_space(new H1Space<double>(mesh, &bcs_vel_y, P_INIT_VEL));
#ifdef PRESSURE_IN_L2
SpaceSharedPtr<double> p_space(new L2Space<double>(mesh, P_INIT_PRESSURE));
#else
SpaceSharedPtr<double> p_space(new H1Space<double>(mesh, P_INIT_PRESSURE));
#endif
std::vector<SpaceSharedPtr<double> > spaces({ xvel_space, yvel_space, p_space });
adaptivity.set_spaces(spaces);
// Calculate and report the number of degrees of freedom.
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Define projection norms.
NormType vel_proj_norm = HERMES_H1_NORM;
#ifdef PRESSURE_IN_L2
NormType p_proj_norm = HERMES_L2_NORM;
#else
NormType p_proj_norm = HERMES_H1_NORM;
#endif
std::vector<NormType> proj_norms({ vel_proj_norm, vel_proj_norm, p_proj_norm });
// Solutions for the Newton's iteration and time stepping.
Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
// Define initial conditions on the
MeshFunctionSharedPtr<double> xvel_ref_sln(new Solution<double>());
MeshFunctionSharedPtr<double> yvel_ref_sln(new Solution<double>());
MeshFunctionSharedPtr<double> p_ref_sln(new Solution<double>());
std::vector<MeshFunctionSharedPtr<double> > ref_slns({ xvel_ref_sln, yvel_ref_sln, p_ref_sln });
MeshFunctionSharedPtr<double> xvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> yvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> p_prev_time(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > prev_time({ xvel_prev_time, yvel_prev_time, p_prev_time });
MeshFunctionSharedPtr<double> xvel_prev_time_projected(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> yvel_prev_time_projected(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> p_prev_time_projected(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > prev_time_projected({ xvel_prev_time_projected, yvel_prev_time_projected, p_prev_time_projected });
MeshFunctionSharedPtr<double> xvel_sln(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> yvel_sln(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> p_sln(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > slns({ xvel_sln, yvel_sln, p_sln });
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormNSNewton(STOKES, RE, TAU, xvel_prev_time_projected, yvel_prev_time_projected));
// Initialize the FE problem.
NewtonSolver<double> newton(wf, spaces);
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.output_matrix();
// Initialize refinement selector.
H1ProjBasedSelector<double> selector_h1(CAND_LIST);
L2ProjBasedSelector<double> selector_l2(CAND_LIST);
std::vector<RefinementSelectors::Selector<double> *> selectors({ &selector_h1, &selector_h1, &selector_l2 });
// Initialize views.
VectorView vview("velocity [m/s]", new WinGeom(0, 0, 500, 220));
ScalarView pview("pressure [Pa]", new WinGeom(520, 0, 500, 220));
ScalarView eview_x("Error - Velocity-x", new WinGeom(0, 250, 500, 220));
ScalarView eview_y("Error - Velocity-y", new WinGeom(520, 250, 500, 220));
ScalarView eview_p("Error - Pressure", new WinGeom(0, 500, 500, 220));
ScalarView aview("Adapted elements", new WinGeom(520, 500, 500, 220));
vview.set_min_max_range(0, 1.6);
vview.fix_scale_width(80);
pview.fix_scale_width(80);
pview.show_mesh(true);
// Time-stepping loop:
char title[100];
int num_time_steps = (int)(T_FINAL / TAU + 0.5);
for (int ts = 1; ts <= num_time_steps; ts++)
{
current_time += TAU;
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time = %g:", ts, current_time);
// Update time-dependent essential BCs.
Hermes::Mixins::Loggable::Static::info("Updating time-dependent essential BC.");
Space<double>::update_essential_bc_values(spaces, current_time);
// Periodic global derefinements.
if ((ts > 1) && (ts % UNREF_FREQ == 0 || FORCE_DEREFINEMENT))
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
mesh->copy(basemesh);
xvel_space->set_uniform_order(P_INIT_VEL);
yvel_space->set_uniform_order(P_INIT_VEL);
p_space->set_uniform_order(P_INIT_PRESSURE);
xvel_space->assign_dofs();
yvel_space->assign_dofs();
p_space->assign_dofs();
FORCE_DEREFINEMENT = false;
}
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 refMeshCreator(mesh);
MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorX(xvel_space, ref_mesh, 0);
SpaceSharedPtr<double> ref_xvel_space = refSpaceCreatorX.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorY(yvel_space, ref_mesh, 0);
SpaceSharedPtr<double> ref_yvel_space = refSpaceCreatorY.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorP(p_space, ref_mesh, 0);
SpaceSharedPtr<double> ref_p_space = refSpaceCreatorP.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_xvel_space, ref_yvel_space, ref_p_space });
Hermes::Mixins::Loggable::Static::info("Updating time-dependent essential BC.");
Space<double>::update_essential_bc_values(ref_spaces, current_time);
// Calculate initial coefficient vector for Newton on the fine mesh.
double* coeff_vec = new double[Space<double>::get_num_dofs(ref_spaces)];
if (ts == 1) {
Hermes::Mixins::Loggable::Static::info("Projecting coarse mesh solution to obtain coefficient vector on new fine mesh.");
OGProjection<double>::project_global(ref_spaces, prev_time, coeff_vec);
}
else {
Hermes::Mixins::Loggable::Static::info("Projecting previous fine mesh solution to obtain coefficient vector on new fine mesh.");
OGProjection<double>::project_global(ref_spaces, prev_time, coeff_vec);
}
Hermes::Mixins::Loggable::Static::info("Projecting previous fine mesh solution to the new mesh - without this, the calculation fails.");
//OGProjection<double>::project_global(ref_spaces, prev_time, prev_time_projected);
// Perform Newton's iteration.
Hermes::Mixins::Loggable::Static::info("Solving nonlinear problem:");
try
{
newton.set_spaces(ref_spaces);
newton.solve(coeff_vec);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
};
// Update previous time level solutions.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), ref_spaces, ref_slns);
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
OGProjection<double> ogProj; ogProj.project_global(spaces, ref_slns, slns, proj_norms);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
errorCalculator.calculate_errors(slns, ref_slns);
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
eview_x.show(errorCalculator.get_errorMeshFunction(0));
eview_y.show(errorCalculator.get_errorMeshFunction(1));
eview_p.show(errorCalculator.get_errorMeshFunction(2));
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof: %d, ref_ndof: %d, err_est_rel: %g%%", Space<double>::get_num_dofs(spaces),
Space<double>::get_num_dofs(ref_spaces), err_est_rel_total);
// Show the solution at the end of time step.
sprintf(title, "Velocity, time %g", current_time);
vview.set_title(title);
vview.show(xvel_ref_sln, yvel_ref_sln);
sprintf(title, "Pressure, time %g", current_time);
pview.set_title(title);
pview.show(p_ref_sln);
// If err_est too large, adapt the mesh.
if (err_est_rel_total < ERR_STOP || Space<double>::get_num_dofs(ref_spaces) > NOT_ADAPTING_REF_SPACES_SIZE)
done = true;
else
{
Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
done = adaptivity.adapt(selectors);
aview.show(adaptivity.get_refinementInfoMeshFunction());
// Increase the counter of performed adaptivity steps.
as++;
if (Space<double>::get_num_dofs(ref_spaces) > FORCE_DEREFINEMENT_REF_SPACES_SIZE)
FORCE_DEREFINEMENT = false;
}
// Clean up.
delete[] coeff_vec;
} while (done == false);
// Copy new time level reference solution into prev_time.
xvel_prev_time->copy(xvel_ref_sln);
yvel_prev_time->copy(yvel_ref_sln);
p_prev_time->copy(p_ref_sln);
}
ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/circular-obstacle-adapt/definitions.cpp | .cpp | 20,303 | 522 | #include "definitions.h"
WeakFormNSSimpleLinearization::WeakFormNSSimpleLinearization(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time) : WeakForm<double>(3), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time)
{
BilinearFormSymVel* sym_form_0 = new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_0);
BilinearFormSymVel* sym_form_1 = new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_1);
BilinearFormNonsymVel* nonsym_vel_form_0 = new BilinearFormNonsymVel(0, 0, Stokes);
nonsym_vel_form_0->set_ext({ x_vel_previous_time, y_vel_previous_time });
add_matrix_form(nonsym_vel_form_0);
BilinearFormNonsymVel* nonsym_vel_form_1 = new BilinearFormNonsymVel(1, 1, Stokes);
nonsym_vel_form_1->set_ext({ x_vel_previous_time, y_vel_previous_time });
add_matrix_form(nonsym_vel_form_1);
BilinearFormNonsymXVelPressure* nonsym_velx_pressure_form = new BilinearFormNonsymXVelPressure(0, 2);
add_matrix_form(nonsym_velx_pressure_form);
BilinearFormNonsymYVelPressure* nonsym_vely_pressure_form = new BilinearFormNonsymYVelPressure(1, 2);
add_matrix_form(nonsym_vely_pressure_form);
VectorFormVolVel* vector_vel_form_x = new VectorFormVolVel(0, Stokes, time_step);
vector_vel_form_x->set_ext(x_vel_previous_time);
VectorFormVolVel* vector_vel_form_y = new VectorFormVolVel(1, Stokes, time_step);
vector_vel_form_y->set_ext(y_vel_previous_time);
}
WeakFormNSSimpleLinearization::BilinearFormSymVel::BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step)
: MatrixFormVol<double>(i, j), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step)
{
this->setSymFlag(HERMES_SYM);
}
double WeakFormNSSimpleLinearization::BilinearFormSymVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord WeakFormNSSimpleLinearization::BilinearFormSymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext)
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormSymVel::clone() const
{
return new BilinearFormSymVel(*this);
}
WeakFormNSSimpleLinearization::BilinearFormNonsymVel::BilinearFormNonsymVel(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes)
{
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymVel::clone() const
{
return new BilinearFormNonsymVel(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymVel::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 (!Stokes) {
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
result = int_w_nabla_u_v<double, double>(n, wt, xvel_prev_time, yvel_prev_time, u, v);
}
return result;
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
result = int_w_nabla_u_v<Ord, Ord>(n, wt, xvel_prev_time, yvel_prev_time, u, v);
}
return result;
}
WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::BilinearFormNonsymXVelPressure(int i, int j)
: MatrixFormVol<double>(i, j)
{
this->setSymFlag(HERMES_ANTISYM);
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::clone() const
{
return new BilinearFormNonsymXVelPressure(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::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_dvdx<double, double>(n, wt, u, v);
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::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_dvdx<Ord, Ord>(n, wt, u, v);
}
WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::BilinearFormNonsymYVelPressure(int i, int j)
: MatrixFormVol<double>(i, j)
{
this->setSymFlag(HERMES_ANTISYM);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::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_dvdy<double, double>(n, wt, u, v);
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::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_dvdy<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::clone() const
{
return new BilinearFormNonsymYVelPressure(*this);
}
WeakFormNSSimpleLinearization::VectorFormVolVel::VectorFormVolVel(int i, bool Stokes, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), time_step(time_step)
{
}
VectorFormVol<double>* WeakFormNSSimpleLinearization::VectorFormVolVel::clone() const
{
return new VectorFormVolVel(*this);
}
double WeakFormNSSimpleLinearization::VectorFormVolVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
if (!Stokes) {
Func<double>* vel_prev_time = ext[0]; // this form is used with both velocity components
result = int_u_v<double, double>(n, wt, vel_prev_time, v) / time_step;
}
return result;
}
Ord WeakFormNSSimpleLinearization::VectorFormVolVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* vel_prev_time = ext[0]; // this form is used with both velocity components
result = int_u_v<Ord, Ord>(n, wt, vel_prev_time, v) / time_step;
}
return result;
}
WeakFormNSNewton::WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time) : WeakForm<double>(3), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time)
{
BilinearFormSymVel* sym_form_0 = new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_0);
BilinearFormSymVel* sym_form_1 = new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_1);
BilinearFormNonsymVel_0_0* nonsym_vel_form_0_0 = new BilinearFormNonsymVel_0_0(0, 0, Stokes);
add_matrix_form(nonsym_vel_form_0_0);
BilinearFormNonsymVel_0_1* nonsym_vel_form_0_1 = new BilinearFormNonsymVel_0_1(0, 1, Stokes);
add_matrix_form(nonsym_vel_form_0_1);
BilinearFormNonsymVel_1_0* nonsym_vel_form_1_0 = new BilinearFormNonsymVel_1_0(1, 0, Stokes);
add_matrix_form(nonsym_vel_form_1_0);
BilinearFormNonsymVel_1_1* nonsym_vel_form_1_1 = new BilinearFormNonsymVel_1_1(1, 1, Stokes);
add_matrix_form(nonsym_vel_form_1_1);
BilinearFormNonsymXVelPressure* nonsym_velx_pressure_form = new BilinearFormNonsymXVelPressure(0, 2);
add_matrix_form(nonsym_velx_pressure_form);
BilinearFormNonsymYVelPressure* nonsym_vely_pressure_form = new BilinearFormNonsymYVelPressure(1, 2);
add_matrix_form(nonsym_vely_pressure_form);
VectorFormNS_0* F_0 = new VectorFormNS_0(0, Stokes, Reynolds, time_step);
F_0->set_ext({ x_vel_previous_time, y_vel_previous_time });
add_vector_form(F_0);
VectorFormNS_1* F_1 = new VectorFormNS_1(1, Stokes, Reynolds, time_step);
F_1->set_ext({ x_vel_previous_time, y_vel_previous_time });
add_vector_form(F_1);
VectorFormNS_2* F_2 = new VectorFormNS_2(2);
add_vector_form(F_2);
}
WeakFormNSNewton::BilinearFormSymVel::BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step)
: MatrixFormVol<double>(i, j), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step)
{
this->setSymFlag(HERMES_SYM);
}
double WeakFormNSNewton::BilinearFormSymVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord WeakFormNSNewton::BilinearFormSymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
WeakFormNSNewton::BilinearFormNonsymVel_0_0::BilinearFormNonsymVel_0_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes)
{
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_0::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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i]
* u->dy[i]) * v->val[i] + u->val[i] * v->val[i] * xvel_prev_newton->dx[i]);
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i]
* u->dy[i]) * v->val[i] + u->val[i] * v->val[i] * xvel_prev_newton->dx[i]);
}
return result;
}
WeakFormNSNewton::BilinearFormNonsymVel_0_1::BilinearFormNonsymVel_0_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes)
{
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_1::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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * xvel_prev_newton->dy[i]);
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * xvel_prev_newton->dy[i]);
}
return result;
}
WeakFormNSNewton::BilinearFormNonsymVel_1_0::BilinearFormNonsymVel_1_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes)
{
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_0::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 (!Stokes) {
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * yvel_prev_newton->dx[i]);
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * yvel_prev_newton->dx[i]);
}
return result;
}
WeakFormNSNewton::BilinearFormNonsymVel_1_1::BilinearFormNonsymVel_1_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes)
{
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_1::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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i] + u->val[i]
* v->val[i] * yvel_prev_newton->dy[i]);
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i] + u->val[i]
* v->val[i] * yvel_prev_newton->dy[i]);
}
return result;
}
WeakFormNSNewton::BilinearFormNonsymXVelPressure::BilinearFormNonsymXVelPressure(int i, int j)
: MatrixFormVol<double>(i, j)
{
this->setSymFlag(HERMES_ANTISYM);
}
double WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<Ord, Ord>(n, wt, u, v);
}
WeakFormNSNewton::BilinearFormNonsymYVelPressure::BilinearFormNonsymYVelPressure(int i, int j)
: MatrixFormVol<double>(i, j)
{
this->setSymFlag(HERMES_ANTISYM);
}
double WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<Ord, Ord>(n, wt, u, v);
}
WeakFormNSNewton::VectorFormNS_0::VectorFormNS_0(int i, bool Stokes, double Reynolds, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step)
{
}
double WeakFormNSNewton::VectorFormNS_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
WeakFormNSNewton::VectorFormNS_1::VectorFormNS_1(int i, bool Stokes, double Reynolds, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step)
{
}
double WeakFormNSNewton::VectorFormNS_1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->dx[i] * v->dx[i] + yvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dy[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * yvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * yvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
WeakFormNSNewton::VectorFormNS_2::VectorFormNS_2(int i) : VectorFormVol<double>(i)
{
}
double WeakFormNSNewton::VectorFormNS_2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
Ord WeakFormNSNewton::VectorFormNS_2::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
EssentialBCNonConst::EssentialBCNonConst(std::string marker, double vel_inlet, double H, double startup_time)
: EssentialBoundaryCondition<double>(marker), startup_time(startup_time), vel_inlet(vel_inlet), H(H)
{
}
EssentialBCValueType EssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConst::value(double x, double y) const {
double val_y = vel_inlet * y*(H - y) / (H / 2.) / (H / 2.);
if (current_time <= startup_time)
return val_y * current_time / startup_time;
else
return val_y;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/heat-subdomains/definitions.h | .h | 25,143 | 714 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* These numbers must be compatible with mesh file */
// These numbers must be compatible with mesh file.
const double H = 1.0;
const double OBSTACLE_DIAMETER = 0.3 * 1.4142136;
const double HOLE_MID_X = 0.5;
const double HOLE_MID_Y = 0.5;
/* Custom initial condition for temperature*/
class CustomInitialConditionTemperature : public ExactSolutionScalar < double >
{
public:
CustomInitialConditionTemperature(MeshSharedPtr mesh, double mid_x, double mid_y, double radius, double temp_fluid, double temp_graphite);
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;
// Members.
double mid_x, mid_y, radius, temp_fluid, temp_graphite;
};
/* Weak forms */
class CustomWeakFormHeatAndFlow : public WeakForm < double >
{
public:
CustomWeakFormHeatAndFlow(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time, MeshFunctionSharedPtr<double> T_prev_time, double heat_source, double specific_heat_graphite,
double specific_heat_fluid, double rho_graphite, double rho_fluid, double thermal_conductivity_graphite,
double thermal_conductivity_fluid, bool simple_temp_advection);
class BilinearFormTime : public MatrixFormVol < double >
{
public:
BilinearFormTime(unsigned int i, unsigned int j, std::string area, double time_step) : MatrixFormVol<double>(i, j), time_step(time_step) {
this->set_area(area);
}
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 = int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormTime(*this);
}
protected:
// Members.
double time_step;
};
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step) : MatrixFormVol<double>(i, j), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step) {
this->setSymFlag(sym);
}
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 = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormSymVel(*this);
}
protected:
// Members.
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormUnSymVel_0_0 : public MatrixFormVol < double >
{
public:
BilinearFormUnSymVel_0_0(unsigned int i, unsigned int j, bool Stokes) : MatrixFormVol<double>(i, j), Stokes(Stokes) {
}
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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i]
* u->dy[i]) * v->val[i] + u->val[i] * v->val[i] * xvel_prev_newton->dx[i]);
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i]
* u->dy[i]) * v->val[i] + u->val[i] * v->val[i] * xvel_prev_newton->dx[i]);
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormUnSymVel_0_0(*this);
}
protected:
// Members.
bool Stokes;
};
class BilinearFormUnSymVel_0_1 : public MatrixFormVol < double >
{
public:
BilinearFormUnSymVel_0_1(unsigned int i, unsigned int j, bool Stokes) : MatrixFormVol<double>(i, j), Stokes(Stokes) {
}
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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * xvel_prev_newton->dy[i]);
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * xvel_prev_newton->dy[i]);
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormUnSymVel_0_1(*this);
}
protected:
// Members.
bool Stokes;
};
class BilinearFormUnSymVel_1_0 : public MatrixFormVol < double >
{
public:
BilinearFormUnSymVel_1_0(unsigned int i, unsigned int j, bool Stokes) : MatrixFormVol<double>(i, j), Stokes(Stokes) {
}
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 (!Stokes) {
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * yvel_prev_newton->dx[i]);
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (u->val[i] * v->val[i] * yvel_prev_newton->dx[i]);
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormUnSymVel_1_0(*this);
}
protected:
// Members.
bool Stokes;
};
class BilinearFormUnSymVel_1_1 : public MatrixFormVol < double >
{
public:
BilinearFormUnSymVel_1_1(unsigned int i, unsigned int j, bool Stokes) : MatrixFormVol<double>(i, j), Stokes(Stokes) {
}
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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i] + u->val[i]
* v->val[i] * yvel_prev_newton->dy[i]);
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i] + u->val[i]
* v->val[i] * yvel_prev_newton->dy[i]);
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormUnSymVel_1_1(*this);
}
protected:
// Members.
bool Stokes;
};
class BilinearFormUnSymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormUnSymXVelPressure(int i, int j) : MatrixFormVol<double>(i, j) {
this->setSymFlag(HERMES_ANTISYM);
}
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_dvdx<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_dvdx<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormUnSymXVelPressure(*this);
}
};
class BilinearFormUnSymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormUnSymYVelPressure(int i, int j) : MatrixFormVol<double>(i, j) {
this->setSymFlag(HERMES_ANTISYM);
}
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_dvdy<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_dvdy<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* clone() const
{
return new BilinearFormUnSymYVelPressure(*this);
}
};
class CustomJacobianTempAdvection_3_0 : public MatrixFormVol < double >
{
public:
CustomJacobianTempAdvection_3_0(unsigned int i, unsigned int j, std::string area) : MatrixFormVol<double>(i, j)
{
this->set_area(area);
}
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;
Func<double>* T_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * T_prev_newton->dx[i] * v->val[i];
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* T_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * T_prev_newton->dx[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new CustomJacobianTempAdvection_3_0(*this);
}
};
class CustomJacobianTempAdvection_3_3_simple : public MatrixFormVol < double >
{
public:
CustomJacobianTempAdvection_3_3_simple(unsigned int i, unsigned int j, std::string area) : MatrixFormVol<double>(i, j)
{
this->set_area(area);
}
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;
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_time->val[i] * u->dx[i] + yvel_prev_time->val[i] * u->dy[i]) * v->val[i];
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_time->val[i] * u->dx[i] + yvel_prev_time->val[i] * u->dy[i]) * v->val[i];
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new CustomJacobianTempAdvection_3_3_simple(*this);
}
};
class CustomJacobianTempAdvection_3_1 : public MatrixFormVol < double >
{
public:
CustomJacobianTempAdvection_3_1(unsigned int i, unsigned int j, std::string area) : MatrixFormVol<double>(i, j)
{
this->set_area(area);
}
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;
Func<double>* T_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * T_prev_newton->dy[i] * v->val[i];
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* T_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
{
result += wt[i] * u->val[i] * T_prev_newton->dy[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new CustomJacobianTempAdvection_3_1(*this);
}
};
class CustomJacobianTempAdvection_3_3 : public MatrixFormVol < double >
{
public:
CustomJacobianTempAdvection_3_3(unsigned int i, unsigned int j, std::string area) : MatrixFormVol<double>(i, j)
{
this->set_area(area);
}
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;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i];
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]) * v->val[i];
}
return result;
}
MatrixFormVol<double>* clone() const
{
return new CustomJacobianTempAdvection_3_3(*this);
}
};
class VectorFormTime : public VectorFormVol < double >
{
public:
VectorFormTime(int i, std::string area, double time_step) : VectorFormVol<double>(i), time_step(time_step)
{
this->set_area(area);
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
Func<double>* func_prev_time = ext[0];
double result = (int_u_v<double, double>(n, wt, u_ext[3], v) - int_u_v<double, double>(n, wt, func_prev_time, v)) / time_step;
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Func<Ord>* func_prev_time = ext[0];
Ord result = (int_u_v<Ord, Ord>(n, wt, u_ext[3], v) - int_u_v<Ord, Ord>(n, wt, func_prev_time, v)) / time_step;
return result;
}
VectorFormVol<double>* clone() const
{
return new VectorFormTime(*this);
}
protected:
// Members.
double time_step;
};
class CustomResidualTempAdvection : public VectorFormVol < double >
{
public:
CustomResidualTempAdvection(int i, std::string area) : VectorFormVol<double>(i)
{
this->set_area(area);
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* T_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_newton->val[i] * T_prev_newton->dx[i] + yvel_prev_newton->val[i] * T_prev_newton->dy[i]) * v->val[i];
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* T_prev_newton = u_ext[3];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_newton->val[i] * T_prev_newton->dx[i] + yvel_prev_newton->val[i] * T_prev_newton->dy[i]) * v->val[i];
}
return result;
}
VectorFormVol<double>* clone() const
{
return new CustomResidualTempAdvection(*this);
}
};
class CustomResidualTempAdvection_simple : public VectorFormVol < double >
{
public:
CustomResidualTempAdvection_simple(int i, std::string area) : VectorFormVol<double>(i)
{
this->set_area(area);
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
Func<double>* T_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_time->val[i] * T_prev_newton->dx[i] + yvel_prev_time->val[i] * T_prev_newton->dy[i]) * v->val[i];
}
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
Func<Ord>* T_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
{
result += wt[i] * (xvel_prev_time->val[i] * T_prev_newton->dx[i] + yvel_prev_time->val[i] * T_prev_newton->dy[i]) * v->val[i];
}
return result;
}
VectorFormVol<double>* clone() const
{
return new CustomResidualTempAdvection_simple(*this);
}
};
class VectorFormNS_0 : public VectorFormVol < double >
{
public:
VectorFormNS_0(int i, bool Stokes, double Reynolds, double time_step) : VectorFormVol<double>(i), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step)
{
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds - (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i] + yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds - (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i] + yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
VectorFormVol<double>* clone() const
{
return new VectorFormNS_0(*this);
}
protected:
// Members.
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_1 : public VectorFormVol < double >
{
public:
VectorFormNS_1(int i, bool Stokes, double Reynolds, double time_step) : VectorFormVol<double>(i), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) {
}
double value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->dx[i] * v->dx[i] + yvel_prev_newton->dy[i] * v->dy[i]) / Reynolds - (p_prev_newton->val[i] * v->dy[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * yvel_prev_newton->dx[i] + yvel_prev_newton->val[i] * yvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds - (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * yvel_prev_newton->dx[i] + yvel_prev_newton->val[i] * yvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
VectorFormVol<double>* clone() const
{
return new VectorFormNS_1(*this);
}
protected:
// Members.
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_2 : public VectorFormVol < double >
{
public:
VectorFormNS_2(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{
double result = 0;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
VectorFormVol<double>* clone() const
{
return new VectorFormNS_2(*this);
}
};
protected:
// Members.
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
class EssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConst(std::vector<std::string> markers, double vel_inlet, double H, double startup_time) :
EssentialBoundaryCondition<double>(markers), vel_inlet(vel_inlet), H(H), startup_time(startup_time) {};
EssentialBCNonConst(std::string marker, double vel_inlet, double H, double startup_time) :
EssentialBoundaryCondition<double>(std::vector<std::string>()), vel_inlet(vel_inlet), H(H), startup_time(startup_time) {
markers.push_back(marker);
};
~EssentialBCNonConst() {};
virtual EssentialBCValueType get_value_type() const {
return BC_FUNCTION;
};
virtual double value(double x, double y) const {
double val_y = vel_inlet * y*(H - y) / (H / 2.) / (H / 2.); // Parabolic profile.
//double val_y = vel_inlet; // Constant profile.
if (current_time <= startup_time)
return val_y * current_time / startup_time;
else
return val_y;
};
protected:
// Members.
double vel_inlet;
double H;
double startup_time;
};
bool point_in_graphite(double x, double y);
int element_in_graphite(Element* e);
int element_in_fluid(Element* e);
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/heat-subdomains/main.cpp | .cpp | 10,938 | 236 | #include "definitions.h"
// This example shows the use of subdomains. It models a round graphite object that is
// heated through internal heat sources and cooled with a fluid (air or water) flowing
// past it. This model is semi-realistic, double-check all parameter values and equations
// before using it for your applications. NOTE: The file definitions.h contains numbers
// that need to be compatible with the mesh file.
// If true, then just Stokes equation will be considered, not Navier-Stokes.
const bool STOKES = false;
// If defined, pressure elements will be discontinuous (L2),
// otherwise continuous (H1).
#define PRESSURE_IN_L2
// Initial polynomial degree for velocity components.
const int P_INIT_VEL = 2;
// Initial polynomial degree for pressure.
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition.
const int P_INIT_PRESSURE = 1;
// Initial polynomial degree for temperature.
const int P_INIT_TEMPERATURE = 1;
// Initial uniform mesh refinements.
const int INIT_REF_NUM_TEMPERATURE_GRAPHITE = 2;
const int INIT_REF_NUM_TEMPERATURE_FLUID = 3;
const int INIT_REF_NUM_FLUID = 3;
const int INIT_REF_NUM_BDY_GRAPHITE = 1;
const int INIT_REF_NUM_BDY_WALL = 1;
// Problem parameters.
// Inlet velocity (reached after STARTUP_TIME).
const double VEL_INLET = 0.1;
// Initial temperature.
const double TEMPERATURE_INIT_FLUID = 20.0;
const double TEMPERATURE_INIT_GRAPHITE = 100.0;
// Correct is 1.004e-6 (at 20 deg Celsius) but then RE = 2.81713e+06 which
// is too much for this simple model, so we use a larger viscosity. Note
// that kinematic viscosity decreases with rising temperature.
const double KINEMATIC_VISCOSITY_FLUID = 15.68e-6; // Water has 1.004e-2.
// We found a range of 25 - 470, but this is another
// number that one needs to be careful about.
const double THERMAL_CONDUCTIVITY_GRAPHITE = 450;
// At 25 deg Celsius.
const double THERMAL_CONDUCTIVITY_FLUID = 0.025; // Water has 0.6.
// Density of graphite from Wikipedia, one should be
// careful about this number.
const double RHO_GRAPHITE = 2220;
const double RHO_FLUID = 1.1839; // Water has 1000.0.
// Also found on Wikipedia.
const double SPECIFIC_HEAT_GRAPHITE = 711;
const double SPECIFIC_HEAT_FLUID = 1012.0; // Water has 4187.0
// Heat source in graphite. This value is not realistic.
const double HEAT_SOURCE_GRAPHITE = 1e6;
// During this time, inlet velocity increases gradually
// from 0 to VEL_INLET, then it stays constant.
const double STARTUP_TIME = 1.0;
// Time step.
const double time_step = 0.5;
// Time interval length.
const double T_FINAL = 30000.0;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-4;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 10;
// Matrix solver: SOLVER_AMESOS, SOLVER_AZTECOO, SOLVER_MUMPS,
// SOLVER_PETSC, SOLVER_SUPERLU, SOLVER_UMFPACK.
Hermes::MatrixSolverType matrix_solver = Hermes::SOLVER_UMFPACK;
// Temperature advection treatment.
// true... velocity from previous time level is used in temperature
// equation (which makes it linear).
// false... full Newton's method is used.
bool SIMPLE_TEMPERATURE_ADVECTION = false;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh_whole_domain(new Mesh), mesh_with_hole(new Mesh);
std::vector<MeshSharedPtr> meshes({ mesh_whole_domain, mesh_with_hole });
MeshReaderH2DXML mloader;
mloader.load("domain.xml", meshes);
// Temperature mesh: Initial uniform mesh refinements in graphite.
meshes[0]->refine_by_criterion(element_in_graphite, INIT_REF_NUM_TEMPERATURE_GRAPHITE);
// Temperature mesh: Initial uniform mesh refinements in fluid.
meshes[0]->refine_by_criterion(element_in_fluid, INIT_REF_NUM_TEMPERATURE_FLUID);
// Fluid mesh: Initial uniform mesh refinements.
for (int i = 0; i < INIT_REF_NUM_FLUID; i++)
meshes[1]->refine_all_elements();
// Initial refinements towards boundary of graphite.
for (unsigned int meshes_i = 0; meshes_i < meshes.size(); meshes_i++)
meshes[meshes_i]->refine_towards_boundary("Inner Wall", INIT_REF_NUM_BDY_GRAPHITE);
// Initial refinements towards the top and bottom edges.
for (unsigned int meshes_i = 0; meshes_i < meshes.size(); meshes_i++)
meshes[meshes_i]->refine_towards_boundary("Outer Wall", INIT_REF_NUM_BDY_WALL);
// Initialize boundary conditions.
EssentialBCNonConst bc_inlet_vel_x("Inlet", VEL_INLET, H, STARTUP_TIME);
DefaultEssentialBCConst<double> bc_other_vel_x(std::vector<std::string>({ "Outer Wall", "Inner Wall" }), 0.0);
EssentialBCs<double> bcs_vel_x({ &bc_inlet_vel_x, &bc_other_vel_x });
DefaultEssentialBCConst<double> bc_vel_y(std::vector<std::string>({ "Inlet", "Outer Wall", "Inner Wall" }), 0.0);
EssentialBCs<double> bcs_vel_y(&bc_vel_y);
EssentialBCs<double> bcs_pressure;
DefaultEssentialBCConst<double> bc_temperature(std::vector<std::string>({ "Outer Wall", "Inlet" }), 20.0);
EssentialBCs<double> bcs_temperature(&bc_temperature);
// Spaces for velocity components, pressure and temperature.
SpaceSharedPtr<double> xvel_space(new H1Space<double>(mesh_with_hole, &bcs_vel_x, P_INIT_VEL));
SpaceSharedPtr<double> yvel_space(new H1Space<double>(mesh_with_hole, &bcs_vel_y, P_INIT_VEL));
#ifdef PRESSURE_IN_L2
SpaceSharedPtr<double> p_space(new L2Space<double>(mesh_with_hole, P_INIT_PRESSURE));
#else
SpaceSharedPtr<double> p_space(new H1Space<double>(mesh_with_hole, &bcs_pressure, P_INIT_PRESSURE));
#endif
SpaceSharedPtr<double> temperature_space(new H1Space<double>(mesh_whole_domain, &bcs_temperature, P_INIT_TEMPERATURE));
std::vector<SpaceSharedPtr<double> > all_spaces({ xvel_space, yvel_space, p_space, temperature_space });
// Calculate and report the number of degrees of freedom.
int ndof = Space<double>::get_num_dofs(all_spaces);
// Define projection norms.
NormType vel_proj_norm = HERMES_H1_NORM;
#ifdef PRESSURE_IN_L2
NormType p_proj_norm = HERMES_L2_NORM;
#else
NormType p_proj_norm = HERMES_H1_NORM;
#endif
NormType temperature_proj_norm = HERMES_H1_NORM;
std::vector<NormType> all_proj_norms = std::vector<NormType>({ vel_proj_norm, vel_proj_norm, p_proj_norm, temperature_proj_norm });
// Initial conditions and such.
Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
MeshFunctionSharedPtr<double> xvel_prev_time(new ZeroSolution<double>(mesh_with_hole)), yvel_prev_time(new ZeroSolution<double>(mesh_with_hole)), p_prev_time(new ZeroSolution<double>(mesh_with_hole));
MeshFunctionSharedPtr<double> temperature_init_cond(new CustomInitialConditionTemperature(mesh_whole_domain, HOLE_MID_X, HOLE_MID_Y,
0.5*OBSTACLE_DIAMETER, TEMPERATURE_INIT_FLUID, TEMPERATURE_INIT_GRAPHITE));
MeshFunctionSharedPtr<double> temperature_prev_time(new Solution<double>);
std::vector<MeshFunctionSharedPtr<double> > initial_solutions = std::vector<MeshFunctionSharedPtr<double> >({ xvel_prev_time, yvel_prev_time, p_prev_time, temperature_init_cond });
std::vector<MeshFunctionSharedPtr<double> > all_solutions = std::vector<MeshFunctionSharedPtr<double> >({ xvel_prev_time, yvel_prev_time, p_prev_time, temperature_prev_time });
// Project all initial conditions on their FE spaces to obtain aninitial
// coefficient vector for the Newton's method. We use local projection
// to avoid oscillations in temperature on the graphite-fluid interface
// FIXME - currently the LocalProjection only does the lowest-order part (linear
// interpolation) at the moment. Higher-order part needs to be added.
double* coeff_vec = new double[ndof];
Hermes::Mixins::Loggable::Static::info("Projecting initial condition to obtain initial vector for the Newton's method.");
OGProjection<double> ogProjection;
ogProjection.project_global(all_spaces, initial_solutions, coeff_vec, all_proj_norms);
// Translate the solution vector back to Solutions. This is needed to replace
// the discontinuous initial condition for temperature_prev_time with its projection.
Solution<double>::vector_to_solutions(coeff_vec, all_spaces, all_solutions);
// Calculate Reynolds number.
double reynolds_number = VEL_INLET * OBSTACLE_DIAMETER / KINEMATIC_VISCOSITY_FLUID;
Hermes::Mixins::Loggable::Static::info("RE = %g", reynolds_number);
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormHeatAndFlow(STOKES, reynolds_number, time_step, xvel_prev_time, yvel_prev_time, temperature_prev_time,
HEAT_SOURCE_GRAPHITE, SPECIFIC_HEAT_GRAPHITE, SPECIFIC_HEAT_FLUID, RHO_GRAPHITE, RHO_FLUID,
THERMAL_CONDUCTIVITY_GRAPHITE, THERMAL_CONDUCTIVITY_FLUID, SIMPLE_TEMPERATURE_ADVECTION));
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, all_spaces);
// Initialize the Newton solver.
NewtonSolver<double> newton(&dp);
// Initialize views.
Views::VectorView vview("velocity [m/s]", new Views::WinGeom(0, 0, 700, 360));
Views::ScalarView pview("pressure [Pa]", new Views::WinGeom(0, 415, 700, 350));
Views::ScalarView tempview("temperature [C]", new Views::WinGeom(0, 795, 700, 350));
//vview.set_min_max_range(0, 0.5);
vview.fix_scale_width(80);
//pview.set_min_max_range(-0.9, 1.0);
pview.fix_scale_width(80);
pview.show_mesh(false);
tempview.fix_scale_width(80);
tempview.show_mesh(false);
// Time-stepping loop:
char title[100];
int num_time_steps = T_FINAL / time_step;
double current_time = 0.0;
for (int ts = 1; ts <= num_time_steps; ts++)
{
current_time += time_step;
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time = %g:", ts, current_time);
// Update time-dependent essential BCs.
if (current_time <= STARTUP_TIME)
{
Hermes::Mixins::Loggable::Static::info("Updating time-dependent essential BC.");
Space<double>::update_essential_bc_values(all_spaces, current_time);
}
// Perform Newton's iteration.
Hermes::Mixins::Loggable::Static::info("Solving nonlinear problem:");
bool verbose = true;
// Perform Newton's iteration and translate the resulting coefficient vector into previous time level solutions.
newton.set_verbose_output(verbose);
try
{
newton.solve(coeff_vec);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
};
{
Solution<double>::vector_to_solutions(newton.get_sln_vector(), all_spaces, all_solutions);
}
// Show the solution at the end of time step.
sprintf(title, "Velocity [m/s], time %g s", current_time);
vview.set_title(title);
//vview.show(xvel_prev_time, yvel_prev_time);
sprintf(title, "Pressure [Pa], time %g s", current_time);
pview.set_title(title);
pview.show(p_prev_time);
sprintf(title, "Temperature [C], time %g s", current_time);
tempview.set_title(title);
tempview.show(temperature_prev_time);
}
delete[] coeff_vec;
// Wait for all views to be closed.
Views::View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/heat-subdomains/definitions.cpp | .cpp | 6,626 | 164 | #include "definitions.h"
/* Custom initial condition for temperature*/
CustomInitialConditionTemperature::CustomInitialConditionTemperature(MeshSharedPtr mesh, double mid_x, double mid_y, double radius, double temp_fluid, double temp_graphite)
: ExactSolutionScalar<double>(mesh), mid_x(mid_x), mid_y(mid_y), radius(radius), temp_fluid(temp_fluid), temp_graphite(temp_graphite) {}
double CustomInitialConditionTemperature::value(double x, double y) const
{
bool in_graphite = (std::sqrt(sqr(mid_x - x) + sqr(mid_y - y)) < radius);
double temp = temp_fluid;
if (in_graphite) temp = temp_graphite;
return temp;
}
void CustomInitialConditionTemperature::derivatives(double x, double y, double& dx, double& dy) const
{
dx = 0;
dy = 0;
}
Ord CustomInitialConditionTemperature::ord(double x, double y) const
{
return Ord(1);
}
MeshFunction<double>* CustomInitialConditionTemperature::clone() const
{
return new CustomInitialConditionTemperature(this->mesh, this->mid_x, this->mid_y, this->radius, this->temp_fluid, this->temp_graphite);
}
/* Weak forms */
CustomWeakFormHeatAndFlow::CustomWeakFormHeatAndFlow(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time, MeshFunctionSharedPtr<double> T_prev_time, double heat_source, double specific_heat_graphite,
double specific_heat_fluid, double rho_graphite, double rho_fluid, double thermal_conductivity_graphite, double thermal_conductivity_fluid,
bool simple_temp_advection)
: WeakForm<double>(4), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time), y_vel_previous_time(y_vel_previous_time)
{
// For passing to forms.
std::vector<MeshFunctionSharedPtr<double> > ext({ x_vel_previous_time, y_vel_previous_time });
// Jacobian - flow part.
add_matrix_form(new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step));
add_matrix_form(new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step));
add_matrix_form(new BilinearFormUnSymVel_0_0(0, 0, Stokes));
add_matrix_form(new BilinearFormUnSymVel_0_1(0, 1, Stokes));
add_matrix_form(new BilinearFormUnSymVel_1_0(1, 0, Stokes));
add_matrix_form(new BilinearFormUnSymVel_1_1(1, 1, Stokes));
add_matrix_form(new BilinearFormUnSymXVelPressure(0, 2));
add_matrix_form(new BilinearFormUnSymYVelPressure(1, 2));
// Jacobian - temperature part.
// Contribution from implicit Euler.
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<double>(3, 3, "Fluid", new Hermes2DFunction<double>(1.0 / time_step), HERMES_NONSYM));
add_matrix_form(new WeakFormsH1::DefaultMatrixFormVol<double>(3, 3, "Graphite", new Hermes2DFunction<double>(1.0 / time_step), HERMES_NONSYM));
// Contribution from temperature diffusion.
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(3, 3, "Fluid", new Hermes1DFunction<double>(thermal_conductivity_fluid / (rho_fluid * specific_heat_fluid)), HERMES_NONSYM));
add_matrix_form(new WeakFormsH1::DefaultJacobianDiffusion<double>(3, 3, "Graphite",
new Hermes1DFunction<double>(thermal_conductivity_graphite / (rho_graphite * specific_heat_graphite)), HERMES_NONSYM));
// Contribution from temperature advection - only in fluid.
if (simple_temp_advection)
{
CustomJacobianTempAdvection_3_3_simple* cjta_3_3_simple = new CustomJacobianTempAdvection_3_3_simple(3, 3, "Fluid");
cjta_3_3_simple->set_ext(ext);
add_matrix_form(cjta_3_3_simple);
}
else
{
add_matrix_form(new CustomJacobianTempAdvection_3_0(3, 0, "Fluid"));
add_matrix_form(new CustomJacobianTempAdvection_3_1(3, 1, "Fluid"));
add_matrix_form(new CustomJacobianTempAdvection_3_3(3, 3, "Fluid"));
}
// Residual - flow part.
VectorFormNS_0* F_0 = new VectorFormNS_0(0, Stokes, Reynolds, time_step);
F_0->set_ext(ext);
add_vector_form(F_0);
VectorFormNS_1* F_1 = new VectorFormNS_1(1, Stokes, Reynolds, time_step);
F_1->set_ext(ext);
add_vector_form(F_1);
VectorFormNS_2* F_2 = new VectorFormNS_2(2);
add_vector_form(F_2);
// Residual - temperature part.
// Contribution from implicit Euler method.
VectorFormTime *vft = new VectorFormTime(3, "Fluid", time_step);
vft->set_ext(T_prev_time);
add_vector_form(vft);
vft = new VectorFormTime(3, "Graphite", time_step);
vft->set_ext(T_prev_time);
add_vector_form(vft);
// Contribution from temperature diffusion.
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(3, "Fluid", new Hermes1DFunction<double>(thermal_conductivity_fluid / (rho_fluid * specific_heat_fluid))));
add_vector_form(new WeakFormsH1::DefaultResidualDiffusion<double>(3, "Graphite", new Hermes1DFunction<double>(thermal_conductivity_graphite / (rho_graphite * specific_heat_graphite))));
// Contribution from heat sources.
add_vector_form(new WeakFormsH1::DefaultVectorFormVol<double>(3, "Graphite", new Hermes::Hermes2DFunction<double>(-heat_source / (rho_graphite * specific_heat_graphite))));
// Contribution from temperature advection.
if (simple_temp_advection)
{
CustomResidualTempAdvection_simple* crta_simple = new CustomResidualTempAdvection_simple(3, "Fluid");
crta_simple->set_ext(ext);
add_vector_form(crta_simple);
}
else add_vector_form(new CustomResidualTempAdvection(3, "Fluid"));
};
bool point_in_graphite(double x, double y)
{
double dist_from_center = std::sqrt(sqr(x - HOLE_MID_X) + sqr(y - HOLE_MID_Y));
if (dist_from_center < 0.5 * OBSTACLE_DIAMETER) return true;
else return false;
}
int element_in_graphite(Element* e)
{
// Calculate element center.
int nvert;
if (e->is_triangle()) nvert = 3;
else nvert = 4;
double elem_center_x = 0, elem_center_y = 0;
for (int i = 0; i < nvert; i++)
{
elem_center_x += e->vn[i]->x;
elem_center_y += e->vn[i]->y;
}
elem_center_x /= nvert;
elem_center_y /= nvert;
// Check if center is in graphite.
if (point_in_graphite(elem_center_x, elem_center_y))
{
return 0; // 0... refine uniformly.
}
else
{
return -1; //-1... do not refine.
}
}
int element_in_fluid(Element* e)
{
// Calculate element center.
int nvert;
if (e->is_triangle()) nvert = 3;
else nvert = 4;
double elem_center_x = 0, elem_center_y = 0;
for (int i = 0; i < nvert; i++)
{
elem_center_x += e->vn[i]->x;
elem_center_y += e->vn[i]->y;
}
elem_center_x /= nvert;
elem_center_y /= nvert;
// Check if center is in graphite.
if (point_in_graphite(elem_center_x, elem_center_y))
{
return -1; //-1... do not refine.
}
else
{
return 0; // 0... refine uniformly.
}
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/driven-cavity/definitions.h | .h | 7,823 | 231 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
class WeakFormNSNewton : public WeakForm < double >
{
public:
WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time);
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step)
: MatrixFormVol<double>(i, j), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step) {
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormNonsymVel_0_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_0_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymXVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymYVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 VectorFormNS_0 : public VectorFormVol < double >
{
public:
VectorFormNS_0(int i, bool Stokes, double Reynolds, double time_step) : VectorFormVol<double>(i),
Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) {};
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_1 : public VectorFormVol < double >
{
public:
VectorFormNS_1(int i, bool Stokes, double Reynolds, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) {};
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_2 : public VectorFormVol < double >
{
public:
VectorFormNS_2(int i) : VectorFormVol<double>(i) {};
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;
};
protected:
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
/* Essential boundary conditions */
// Time-dependent surface x-velocity of inner circle.
class EssentialBCNonConstX : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConstX(std::vector<std::string> markers, double vel, double startup_time)
: EssentialBoundaryCondition<double>(markers), startup_time(startup_time), vel(vel) {};
EssentialBCNonConstX(std::string marker, double vel, double startup_time)
: EssentialBoundaryCondition<double>(marker), startup_time(startup_time), vel(vel) {};
~EssentialBCNonConstX() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
protected:
double startup_time;
double vel;
};
// Time-dependent surface y-velocity of inner circle.
class EssentialBCNonConstY : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConstY(std::vector<std::string> markers, double vel, double startup_time)
: EssentialBoundaryCondition<double>(markers), startup_time(startup_time), vel(vel) {};
EssentialBCNonConstY(std::string marker, double vel, double startup_time)
: EssentialBoundaryCondition<double>(marker), startup_time(startup_time), vel(vel) {};
~EssentialBCNonConstY() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
protected:
double startup_time;
double vel;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/driven-cavity/main.cpp | .cpp | 7,454 | 200 | #include "definitions.h"
// Flow inside a rotating circle. Both the flow and the circle are not moving
// at the beginning. As the circle starts to rotate at increasing speed. also
// the flow starts to move. We use time-dependent laminar incompressible Navier-Stokes
// equations discretized in time via the implicit Euler method. The Newton's method
// is used to solve the nonlinear problem at each time step.
//
// PDE: incompressible Navier-Stokes equations in the form
// \partial v / \partial t - \Delta v / Re + (v \cdot \nabla) v + \nabla p = 0,
// div v = 0.
//
// BC: tangential velocity V on the boundary.
//
// Geometry: A circular domain.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// Number of initial mesh refinements towards boundary.
const int INIT_BDY_REF_NUM_INNER = 2;
// For application of Stokes flow (creeping flow).
const bool STOKES = false;
// If this is defined, the pressure is approximated using
// discontinuous L2 elements (making the velocity discreetely
// divergence-free, more accurate than using a continuous
// pressure approximation). Otherwise the standard continuous
// elements are used. The results are striking - check the
// tutorial for comparisons.
#define PRESSURE_IN_L2
// Initial polynomial degree for velocity components.
const int P_INIT_VEL = 2;
// Initial polynomial degree for pressure.
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition.
const int P_INIT_PRESSURE = 1;
// Reynolds number.
const double RE = 5000.0;
// Surface velocity of inner circle.
const double VEL = 0.1;
// During this time, surface velocity of the inner circle increases
// gradually from 0 to VEL, then it stays constant.
const double STARTUP_TIME = 10.0;
// Time step.
const double TAU = 1.0;
// Time interval length.
const double T_FINAL = 3600.0;
// 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;
// Current time (used in weak forms).
double current_time = 0;
// Custom function to calculate drag coefficient.
double integrate_over_wall(MeshFunction<double>* meshfn, int marker)
{
Quad2D* quad = &g_quad_2d_std;
meshfn->set_quad_2d(quad);
double integral = 0.0;
Element* e;
MeshSharedPtr mesh = meshfn->get_mesh();
for_all_active_elements(e, mesh)
{
for (int edge = 0; edge < e->get_nvert(); edge++)
{
if ((e->en[edge]->bnd) && (e->en[edge]->marker == marker))
{
update_limit_table(e->get_mode());
RefMap* ru = meshfn->get_refmap();
meshfn->set_active_element(e);
int eo = quad->get_edge_points(edge, quad->get_max_order(e->get_mode()), e->get_mode());
meshfn->set_quad_order(eo, H2D_FN_VAL);
const double *uval = meshfn->get_fn_values();
double3* pt = quad->get_points(eo, e->get_mode());
double3* tan = ru->get_tangent(edge);
for (int i = 0; i < quad->get_num_points(eo, e->get_mode()); i++)
integral += pt[i][2] * uval[i] * tan[i][2];
}
}
}
return integral * 0.5;
}
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
//mloader.load("domain-concentric.mesh", mesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary({ "Bdy-1", "Bdy-2", "Bdy-3", "Bdy-4" },
INIT_BDY_REF_NUM_INNER, false); // True for anisotropic refinement.
// Initialize boundary conditions.
EssentialBCNonConstX bc_vel_x({ "Bdy-1", "Bdy-2", "Bdy-3", "Bdy-4" }, VEL, STARTUP_TIME);
EssentialBCNonConstY bc_vel_y({ "Bdy-1", "Bdy-2", "Bdy-3", "Bdy-4" }, VEL, STARTUP_TIME);
EssentialBCs<double> bcs_vel_x(&bc_vel_x);
EssentialBCs<double> bcs_vel_y(&bc_vel_y);
SpaceSharedPtr<double> xvel_space(new H1Space<double>(mesh, &bcs_vel_x, P_INIT_VEL));
SpaceSharedPtr<double> yvel_space(new H1Space<double>(mesh, &bcs_vel_y, P_INIT_VEL));
#ifdef PRESSURE_IN_L2
SpaceSharedPtr<double> p_space(new L2Space<double>(mesh, P_INIT_PRESSURE));
#else
SpaceSharedPtr<double> p_space(new H1Space<double>(mesh, P_INIT_PRESSURE));
#endif
std::vector<SpaceSharedPtr<double> > spaces({ xvel_space, yvel_space, p_space });
// Calculate and report the number of degrees of freedom.
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Define projection norms.
NormType vel_proj_norm = HERMES_H1_NORM;
#ifdef PRESSURE_IN_L2
NormType p_proj_norm = HERMES_L2_NORM;
#else
NormType p_proj_norm = HERMES_H1_NORM;
#endif
// Solutions for the Newton's iteration and time stepping.
Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
MeshFunctionSharedPtr<double> xvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> yvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> p_prev_time(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > slns_prev_time({ xvel_prev_time, yvel_prev_time, p_prev_time });
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormNSNewton(STOKES, RE, TAU, xvel_prev_time, yvel_prev_time));
// Initialize views.
MeshView mview("Mesh", new WinGeom(0, 520, 600, 500));
mview.show(mesh);
VectorView vview("velocity [m/s]", new WinGeom(0, 0, 600, 500));
ScalarView pview("pressure [Pa]", new WinGeom(610, 0, 600, 500));
//vview.set_min_max_range(0, 1.6);
vview.fix_scale_width(80);
//pview.set_min_max_range(-0.9, 1.0);
pview.fix_scale_width(80);
pview.show_mesh(true);
// Initialize the FE problem.
Hermes::Hermes2D::NewtonSolver<double> newton(wf, spaces);
newton.set_max_steps_with_reused_jacobian(0);
newton.set_min_allowed_damping_coeff(1e-8);
newton.set_initial_auto_damping_coeff(.5);
newton.set_sufficient_improvement_factor(1.3);
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
// Time-stepping loop:
char title[100];
int num_time_steps = T_FINAL / TAU;
for (int ts = 1; ts <= num_time_steps; ts++)
{
current_time += TAU;
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time = %g:", ts, current_time);
// Update time-dependent essential BCs.
Hermes::Mixins::Loggable::Static::info("Updating time-dependent essential BC.");
Space<double>::update_essential_bc_values(spaces, current_time);
// Perform Newton's iteration.
Hermes::Mixins::Loggable::Static::info("Solving nonlinear problem:");
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
};
// Update previous time level solutions.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, slns_prev_time);
// Show the solution at the end of time step.
sprintf(title, "Pressure, time %g", current_time);
pview.set_title(title);
pview.show(p_prev_time);
sprintf(title, "Velocity, time %g", current_time);
vview.set_title(title);
vview.show(xvel_prev_time, yvel_prev_time);
}
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/driven-cavity/definitions.cpp | .cpp | 13,498 | 367 | #include "definitions.h"
WeakFormNSNewton::WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time) : WeakForm<double>(3), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time)
{
/* Jacobian terms - first velocity equation */
// Time derivative in the first velocity equation
// and Laplacian divided by Re in the first velocity equation.
add_matrix_form(new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step));
// First part of the convective term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymVel_0_0(0, 0, Stokes));
// Second part of the convective term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymVel_0_1(0, 1, Stokes));
// Pressure term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymXVelPressure(0, 2));
/* Jacobian terms - second velocity equation, continuity equation */
// Time derivative in the second velocity equation
// and Laplacian divided by Re in the second velocity equation.
add_matrix_form(new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step));
// First part of the convective term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymVel_1_0(1, 0, Stokes));
// Second part of the convective term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymVel_1_1(1, 1, Stokes));
// Pressure term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymYVelPressure(1, 2));
/* Residual - volumetric */
// First velocity equation.
VectorFormNS_0* F_0 = new VectorFormNS_0(0, Stokes, Reynolds, time_step);
F_0->set_ext(x_vel_previous_time);
add_vector_form(F_0);
// Second velocity equation.
VectorFormNS_1* F_1 = new VectorFormNS_1(1, Stokes, Reynolds, time_step);
F_1->set_ext(y_vel_previous_time);
add_vector_form(F_1);
// Continuity equation.
VectorFormNS_2* F_2 = new VectorFormNS_2(2);
add_vector_form(F_2);
}
double WeakFormNSNewton::BilinearFormSymVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord WeakFormNSNewton::BilinearFormSymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormSymVel::clone() const
{
return new BilinearFormSymVel(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_0::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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * xvel_prev_newton->dx[i]) * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i]
* u->dy[i]) * v->val[i] + u->val[i] * v->val[i] * xvel_prev_newton->dx[i]);
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_0_0::clone() const
{
return new BilinearFormNonsymVel_0_0(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_1::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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * xvel_prev_newton->dy[i] * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * xvel_prev_newton->dy[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_0_1::clone() const
{
return new BilinearFormNonsymVel_0_1(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_0::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 (!Stokes) {
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_1_0::clone() const
{
return new BilinearFormNonsymVel_1_0(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_1::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 (!Stokes) {
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * yvel_prev_newton->dy[i]) * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes) {
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * yvel_prev_newton->dy[i]) * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_1_1::clone() const
{
return new BilinearFormNonsymVel_1_1(*this);
}
double WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymXVelPressure::clone() const
{
return new BilinearFormNonsymXVelPressure(*this);
}
double WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymYVelPressure::clone() const
{
return new BilinearFormNonsymYVelPressure(*this);
}
double WeakFormNSNewton::VectorFormNS_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_0::clone() const
{
return new VectorFormNS_0(*this);
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_1::clone() const
{
return new VectorFormNS_1(*this);
}
double WeakFormNSNewton::VectorFormNS_1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* yvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->dx[i] * v->dx[i] + yvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dy[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * yvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * yvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* yvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
double WeakFormNSNewton::VectorFormNS_2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_2::clone() const
{
return new VectorFormNS_2(*this);
}
Ord WeakFormNSNewton::VectorFormNS_2::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
EssentialBCValueType EssentialBCNonConstX::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConstX::value(double x, double y) const
{
double velocity;
if (current_time <= startup_time) velocity = vel * current_time / startup_time;
else velocity = vel;
double alpha = std::atan2(x, y);
double xvel = velocity*std::cos(alpha);
return xvel;
}
EssentialBCValueType EssentialBCNonConstY::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConstY::value(double x, double y) const
{
double velocity;
if (current_time <= startup_time) velocity = vel * current_time / startup_time;
else velocity = vel;
double alpha = std::atan2(x, y);
double yvel = -velocity*std::sin(alpha);
return yvel;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/circular-obstacle/definitions.h | .h | 10,449 | 303 | #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::WeakFormsH1;
class WeakFormNSSimpleLinearization : public WeakForm < double >
{
public:
WeakFormNSSimpleLinearization(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time);
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step)
: MatrixFormVol<double>(i, j), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) { 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);
MatrixFormVol<double>* clone() const;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormNonsymVel : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymXVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymYVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 VectorFormVolVel : public VectorFormVol < double >
{
public:
VectorFormVolVel(int i, bool Stokes, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), time_step(time_step) {};
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;
protected:
bool Stokes;
double time_step;
};
protected:
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
class WeakFormNSNewton : public WeakForm < double >
{
public:
WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time);
class BilinearFormSymVel : public MatrixFormVol < double >
{
public:
BilinearFormSymVel(unsigned int i, unsigned int j, bool Stokes, double Reynolds, double time_step)
: MatrixFormVol<double>(i, j), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step) {
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class BilinearFormNonsymVel_0_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_0_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_0_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_0 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_0(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymVel_1_1 : public MatrixFormVol < double >
{
public:
BilinearFormNonsymVel_1_1(unsigned int i, unsigned int j, bool Stokes)
: MatrixFormVol<double>(i, j), Stokes(Stokes) {};
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;
protected:
bool Stokes;
};
class BilinearFormNonsymXVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymXVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 BilinearFormNonsymYVelPressure : public MatrixFormVol < double >
{
public:
BilinearFormNonsymYVelPressure(int i, int j) : MatrixFormVol<double>(i, j) { this->setSymFlag(HERMES_ANTISYM); };
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 VectorFormNS_0 : public VectorFormVol < double >
{
public:
VectorFormNS_0(int i, bool Stokes, double Reynolds, double time_step) : VectorFormVol<double>(i),
Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) {};
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_1 : public VectorFormVol < double >
{
public:
VectorFormNS_1(int i, bool Stokes, double Reynolds, double time_step)
: VectorFormVol<double>(i), Stokes(Stokes), Reynolds(Reynolds), time_step(time_step) {};
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;
protected:
bool Stokes;
double Reynolds;
double time_step;
};
class VectorFormNS_2 : public VectorFormVol < double >
{
public:
VectorFormNS_2(int i) : VectorFormVol<double>(i) {};
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;
};
protected:
bool Stokes;
double Reynolds;
double time_step;
MeshFunctionSharedPtr<double> x_vel_previous_time;
MeshFunctionSharedPtr<double> y_vel_previous_time;
};
class EssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConst(std::vector<std::string> markers, double vel_inlet, double H, double startup_time)
: EssentialBoundaryCondition<double>(markers), startup_time(startup_time), vel_inlet(vel_inlet), H(H) {};
EssentialBCNonConst(std::string marker, double vel_inlet, double H, double startup_time);
~EssentialBCNonConst() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
protected:
double startup_time;
double vel_inlet;
double H;
}; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/circular-obstacle/main.cpp | .cpp | 7,352 | 194 | #include "definitions.h"
// The time-dependent laminar incompressible Navier-Stokes equations are
// discretized in time via the implicit Euler method. If NEWTON == true,
// the Newton's method is used to solve the nonlinear problem at each time
// step. We also show how to use discontinuous ($L^2$) elements for pressure
// and thus make the velocity discreetely divergence free. Comparison to
// approximating the pressure with the standard (continuous) Taylor-Hood elements
// is enabled. The Reynolds number Re = 200 which is embarrassingly low. You
// can increase it but then you will need to make the mesh finer, and the
// computation will take more time.
//
// PDE: incompressible Navier-Stokes equations in the form
// \partial v / \partial t - \Delta v / Re + (v \cdot \nabla) v + \nabla p = 0,
// div v = 0.
//
// BC: u_1 is a time-dependent constant and u_2 = 0 on Gamma_4 (inlet),
// u_1 = u_2 = 0 on Gamma_1 (bottom), Gamma_3 (top) and Gamma_5 (obstacle),
// "do nothing" on Gamma_2 (outlet).
//
// Geometry: Rectangular channel containing an off-axis circular obstacle. The
// radius and position of the circle, as well as other geometry
// parameters can be changed in the mesh file "domain.mesh".
//
// 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;
// For application of Stokes flow (creeping flow).
const bool STOKES = false;
// If this is defined, the pressure is approximated using
// discontinuous L2 elements (making the velocity discreetely
// divergence-free, more accurate than using a continuous
// pressure approximation). Otherwise the standard continuous
// elements are used. The results are striking - check the
// tutorial for comparisons.
#define PRESSURE_IN_L2
// Initial polynomial degree for velocity components.
const int P_INIT_VEL = 2;
// Initial polynomial degree for pressure.
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition.
const int P_INIT_PRESSURE = 1;
// Reynolds number.
const double RE = 2000.0;
// Inlet velocity (reached after STARTUP_TIME).
const double VEL_INLET = 1.0;
// During this time, inlet velocity increases gradually
// from 0 to VEL_INLET, then it stays constant.
const double STARTUP_TIME = 1.0;
// Time step.
const double TAU = 0.1;
// Time interval length.
const double T_FINAL = 30000.0;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-4;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 50;
// Domain height - necessary to define the parabolic
// velocity profile at inlet (if relevant).
const double H = 5;
// Boundary markers.
const std::string BDY_BOTTOM = "b1";
const std::string BDY_RIGHT = "b2";
const std::string BDY_TOP = "b3";
const std::string BDY_LEFT = "b4";
const std::string BDY_OBSTACLE = "b5";
// Current time (used in weak forms).
double current_time = 0;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Initial mesh refinements.
mesh->refine_all_elements();
mesh->refine_all_elements();
mesh->refine_towards_boundary(BDY_OBSTACLE, 2, false);
// 'true' stands for anisotropic refinements.
mesh->refine_towards_boundary(BDY_TOP, 2, true);
mesh->refine_towards_boundary(BDY_BOTTOM, 2, true);
// Show mesh.
MeshView mv;
mv.show(mesh);
Hermes::Mixins::Loggable::Static::info("Close mesh window to continue.");
// Initialize boundary conditions.
EssentialBCNonConst bc_left_vel_x(BDY_LEFT, VEL_INLET, H, STARTUP_TIME);
DefaultEssentialBCConst<double> bc_other_vel_x({ BDY_BOTTOM, BDY_TOP, BDY_OBSTACLE }, 0.0);
EssentialBCs<double> bcs_vel_x({ &bc_left_vel_x, &bc_other_vel_x });
DefaultEssentialBCConst<double> bc_vel_y({ BDY_LEFT, BDY_BOTTOM, BDY_TOP, BDY_OBSTACLE }, 0.0);
EssentialBCs<double> bcs_vel_y(&bc_vel_y);
SpaceSharedPtr<double> xvel_space(new H1Space<double>(mesh, &bcs_vel_x, P_INIT_VEL));
SpaceSharedPtr<double> yvel_space(new H1Space<double>(mesh, &bcs_vel_y, P_INIT_VEL));
#ifdef PRESSURE_IN_L2
SpaceSharedPtr<double> p_space(new L2Space<double>(mesh, P_INIT_PRESSURE));
#else
SpaceSharedPtr<double> p_space(new H1Space<double>(mesh, P_INIT_PRESSURE));
#endif
std::vector<SpaceSharedPtr<double> > spaces({ xvel_space, yvel_space, p_space });
// Calculate and report the number of degrees of freedom.
int ndof = Space<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Define projection norms.
NormType vel_proj_norm = HERMES_H1_NORM;
#ifdef PRESSURE_IN_L2
NormType p_proj_norm = HERMES_L2_NORM;
#else
NormType p_proj_norm = HERMES_H1_NORM;
#endif
// Solutions for the Newton's iteration and time stepping.
Hermes::Mixins::Loggable::Static::info("Setting zero initial conditions.");
MeshFunctionSharedPtr<double> xvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> yvel_prev_time(new ZeroSolution<double>(mesh));
MeshFunctionSharedPtr<double> p_prev_time(new ZeroSolution<double>(mesh));
// Initialize weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormNSNewton(STOKES, RE, TAU, xvel_prev_time, yvel_prev_time));
// Initialize the FE problem.
Hermes::Hermes2D::NewtonSolver<double> newton(wf, spaces);
Hermes::Mixins::Loggable::Static::info("Solving nonlinear problem:");
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.set_jacobian_constant();
// Initialize views.
VectorView vview("velocity [m/s]", new WinGeom(0, 0, 750, 240));
ScalarView pview("pressure [Pa]", new WinGeom(0, 290, 750, 240));
vview.set_min_max_range(0, 1.6);
vview.fix_scale_width(80);
//pview.set_min_max_range(-0.9, 1.0);
pview.fix_scale_width(80);
pview.show_mesh(true);
// Time-stepping loop:
char title[100];
int num_time_steps = T_FINAL / TAU;
for (int ts = 1; ts <= num_time_steps; ts++)
{
current_time += TAU;
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time = %g:", ts, current_time);
// Update time-dependent essential BCs.
if (current_time <= STARTUP_TIME) {
Hermes::Mixins::Loggable::Static::info("Updating time-dependent essential BC.");
Space<double>::update_essential_bc_values(spaces, current_time);
}
// Perform Newton's iteration.
try
{
newton.solve();
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
};
// Update previous time level solutions.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, { xvel_prev_time, yvel_prev_time, p_prev_time });
// Visualization.
// Hermes visualization.
if (HERMES_VISUALIZATION)
{
// Show the solution at the end of time step.
sprintf(title, "Velocity, time %g", current_time);
vview.set_title(title);
vview.show(xvel_prev_time, yvel_prev_time);
sprintf(title, "Pressure, time %g", current_time);
pview.set_title(title);
pview.show(p_prev_time);
}
}
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/navier-stokes/circular-obstacle/definitions.cpp | .cpp | 18,941 | 509 | #include "definitions.h"
WeakFormNSSimpleLinearization::WeakFormNSSimpleLinearization(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time) : WeakForm<double>(3), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time)
{
BilinearFormSymVel* sym_form_0 = new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_0);
BilinearFormSymVel* sym_form_1 = new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step);
add_matrix_form(sym_form_1);
BilinearFormNonsymVel* nonsym_vel_form_0 = new BilinearFormNonsymVel(0, 0, Stokes);
nonsym_vel_form_0->set_ext({ x_vel_previous_time, y_vel_previous_time });
add_matrix_form(nonsym_vel_form_0);
BilinearFormNonsymVel* nonsym_vel_form_1 = new BilinearFormNonsymVel(1, 1, Stokes);
nonsym_vel_form_1->set_ext({ x_vel_previous_time, y_vel_previous_time });
add_matrix_form(nonsym_vel_form_1);
// Pressure term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymXVelPressure(0, 2));
// Pressure term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymYVelPressure(1, 2));
VectorFormVolVel* vector_vel_form_x = new VectorFormVolVel(0, Stokes, time_step);
vector_vel_form_x->set_ext(x_vel_previous_time);
VectorFormVolVel* vector_vel_form_y = new VectorFormVolVel(1, Stokes, time_step);
vector_vel_form_y->set_ext(y_vel_previous_time);
}
double WeakFormNSSimpleLinearization::BilinearFormSymVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord WeakFormNSSimpleLinearization::BilinearFormSymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext)
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormSymVel::clone() const
{
return new BilinearFormSymVel(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymVel::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 (!Stokes)
{
Func<double>* xvel_prev_time = ext[0];
Func<double>* yvel_prev_time = ext[1];
result = int_w_nabla_u_v<double, double>(n, wt, xvel_prev_time, yvel_prev_time, u, v);
}
return result;
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* yvel_prev_time = ext[1];
result = int_w_nabla_u_v<Ord, Ord>(n, wt, xvel_prev_time, yvel_prev_time, u, v);
}
return result;
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymVel::clone() const
{
return new BilinearFormNonsymVel(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::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_dvdx<double, double>(n, wt, u, v);
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::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_dvdx<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymXVelPressure::clone() const
{
return new BilinearFormNonsymXVelPressure(*this);
}
double WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::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_dvdy<double, double>(n, wt, u, v);
}
Ord WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::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_dvdy<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSSimpleLinearization::BilinearFormNonsymYVelPressure::clone() const
{
return new BilinearFormNonsymYVelPressure(*this);
}
double WeakFormNSSimpleLinearization::VectorFormVolVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
if (!Stokes)
{
Func<double>* vel_prev_time = ext[0]; // this form is used with both velocity components
result = int_u_v<double, double>(n, wt, vel_prev_time, v) / time_step;
}
return result;
}
Ord WeakFormNSSimpleLinearization::VectorFormVolVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* vel_prev_time = ext[0]; // this form is used with both velocity components
result = int_u_v<Ord, Ord>(n, wt, vel_prev_time, v) / time_step;
}
return result;
}
VectorFormVol<double>* WeakFormNSSimpleLinearization::VectorFormVolVel::clone() const
{
return new VectorFormVolVel(*this);
}
WeakFormNSNewton::WeakFormNSNewton(bool Stokes, double Reynolds, double time_step, MeshFunctionSharedPtr<double> x_vel_previous_time,
MeshFunctionSharedPtr<double> y_vel_previous_time) : WeakForm<double>(3), Stokes(Stokes),
Reynolds(Reynolds), time_step(time_step), x_vel_previous_time(x_vel_previous_time),
y_vel_previous_time(y_vel_previous_time)
{
/* Jacobian terms - first velocity equation */
// Time derivative in the first velocity equation
// and Laplacian divided by Re in the first velocity equation.
add_matrix_form(new BilinearFormSymVel(0, 0, Stokes, Reynolds, time_step));
// First part of the convective term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymVel_0_0(0, 0, Stokes));
// Second part of the convective term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymVel_0_1(0, 1, Stokes));
// Pressure term in the first velocity equation.
add_matrix_form(new BilinearFormNonsymXVelPressure(0, 2));
/* Jacobian terms - second velocity equation, continuity equation */
// Time derivative in the second velocity equation
// and Laplacian divided by Re in the second velocity equation.
add_matrix_form(new BilinearFormSymVel(1, 1, Stokes, Reynolds, time_step));
// First part of the convective term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymVel_1_0(1, 0, Stokes));
// Second part of the convective term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymVel_1_1(1, 1, Stokes));
// Pressure term in the second velocity equation.
add_matrix_form(new BilinearFormNonsymYVelPressure(1, 2));
/* Residual - volumetric */
// First velocity equation.
VectorFormNS_0* F_0 = new VectorFormNS_0(0, Stokes, Reynolds, time_step);
F_0->set_ext(x_vel_previous_time);
add_vector_form(F_0);
// Second velocity equation.
VectorFormNS_1* F_1 = new VectorFormNS_1(1, Stokes, Reynolds, time_step);
F_1->set_ext(y_vel_previous_time);
add_vector_form(F_1);
// Continuity equation.
VectorFormNS_2* F_2 = new VectorFormNS_2(2);
add_vector_form(F_2);
}
double WeakFormNSNewton::BilinearFormSymVel::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
double result = int_grad_u_grad_v<double, double>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<double, double>(n, wt, u, v) / time_step;
return result;
}
Ord WeakFormNSNewton::BilinearFormSymVel::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = int_grad_u_grad_v<Ord, Ord>(n, wt, u, v) / Reynolds;
if (!Stokes)
result += int_u_v<Ord, Ord>(n, wt, u, v) / time_step;
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormSymVel::clone() const
{
return new BilinearFormSymVel(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_0::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 (!Stokes)
{
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * xvel_prev_newton->dx[i]) * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->val[i] * u->dx[i] + yvel_prev_newton->val[i]
* u->dy[i]) * v->val[i] + u->val[i] * v->val[i] * xvel_prev_newton->dx[i]);
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_0_0::clone() const
{
return new BilinearFormNonsymVel_0_0(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_0_1::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 (!Stokes)
{
Func<double>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * xvel_prev_newton->dy[i] * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_0_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * xvel_prev_newton->dy[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_0_1::clone() const
{
return new BilinearFormNonsymVel_0_1(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_0::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 (!Stokes)
{
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * u->val[i] * yvel_prev_newton->dx[i] * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_1_0::clone() const
{
return new BilinearFormNonsymVel_1_0(*this);
}
double WeakFormNSNewton::BilinearFormNonsymVel_1_1::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 (!Stokes)
{
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * yvel_prev_newton->dy[i]) * v->val[i];
}
return result;
}
Ord WeakFormNSNewton::BilinearFormNonsymVel_1_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Ord result = Ord(0);
if (!Stokes)
{
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->val[i] * u->dx[i]
+ yvel_prev_newton->val[i] * u->dy[i]
+ u->val[i] * yvel_prev_newton->dy[i]) * v->val[i];
}
return result;
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymVel_1_1::clone() const
{
return new BilinearFormNonsymVel_1_1(*this);
}
double WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymXVelPressure::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_dvdx<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymXVelPressure::clone() const
{
return new BilinearFormNonsymXVelPressure(*this);
}
double WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<double, double>(n, wt, u, v);
}
Ord WeakFormNSNewton::BilinearFormNonsymYVelPressure::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_dvdy<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* WeakFormNSNewton::BilinearFormNonsymYVelPressure::clone() const
{
return new BilinearFormNonsymYVelPressure(*this);
}
double WeakFormNSNewton::VectorFormNS_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((xvel_prev_newton->val[i] - xvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_0::clone() const
{
return new VectorFormNS_0(*this);
}
double WeakFormNSNewton::VectorFormNS_1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* yvel_prev_time = ext[0];
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
Func<double>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((yvel_prev_newton->dx[i] * v->dx[i] + yvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dy[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * yvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * yvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
Ord WeakFormNSNewton::VectorFormNS_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* yvel_prev_time = ext[0];
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
Func<Ord>* p_prev_newton = u_ext[2];
for (int i = 0; i < n; i++)
result += wt[i] * ((xvel_prev_newton->dx[i] * v->dx[i] + xvel_prev_newton->dy[i] * v->dy[i]) / Reynolds
- (p_prev_newton->val[i] * v->dx[i]));
if (!Stokes)
for (int i = 0; i < n; i++)
result += wt[i] * (((yvel_prev_newton->val[i] - yvel_prev_time->val[i]) * v->val[i] / time_step)
+ ((xvel_prev_newton->val[i] * xvel_prev_newton->dx[i]
+ yvel_prev_newton->val[i] * xvel_prev_newton->dy[i]) * v->val[i]));
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_1::clone() const
{
return new VectorFormNS_1(*this);
}
double WeakFormNSNewton::VectorFormNS_2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* xvel_prev_newton = u_ext[0];
Func<double>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
Ord WeakFormNSNewton::VectorFormNS_2::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
Func<Ord>* xvel_prev_newton = u_ext[0];
Func<Ord>* yvel_prev_newton = u_ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * (xvel_prev_newton->dx[i] * v->val[i] + yvel_prev_newton->dy[i] * v->val[i]);
return result;
}
VectorFormVol<double>* WeakFormNSNewton::VectorFormNS_2::clone() const
{
return new VectorFormNS_2(*this);
}
EssentialBCNonConst::EssentialBCNonConst(std::string marker, double vel_inlet, double H, double startup_time)
: EssentialBoundaryCondition<double>(marker), startup_time(startup_time), vel_inlet(vel_inlet), H(H)
{
}
EssentialBCValueType EssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConst::value(double x, double y) const {
//double val_y = vel_inlet * y*(H-y) / (H/2.)/(H/2.); // parabolic profile
double val_y = vel_inlet; // constant profile
if (current_time <= startup_time)
return val_y * current_time / startup_time;
else
return val_y;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/constitutive.h | .h | 19,616 | 478 | #define HERMES_REPORT_ALL
class ConstitutiveRelations
{
public:
ConstitutiveRelations(double alpha, double theta_s, double theta_r, double k_s) : alpha(alpha), theta_s(theta_s), theta_r(theta_r), k_s(k_s)
{}
virtual double K(double h) = 0;
virtual double dKdh(double h) = 0;
virtual double ddKdhh(double h) = 0;
virtual double C(double h) = 0;
virtual double dCdh(double h) = 0;
virtual double ddCdhh(double h) = 0;
protected:
double alpha, theta_s, theta_r, k_s;
};
class ConstitutiveRelationsGardner : public ConstitutiveRelations
{
public:
ConstitutiveRelationsGardner(double alpha, double theta_s, double theta_r, double k_s) : ConstitutiveRelations(alpha, theta_s, theta_r, k_s)
{}
// K (Gardner).
double K(double h)
{
if (h < 0) return k_s*exp(alpha*h);
else return k_s;
}
// dK/dh (Gardner).
double dKdh(double h)
{
if (h < 0) return k_s*alpha*exp(alpha*h);
else return 0;
}
// ddK/dhh (Gardner).
double ddKdhh(double h)
{
if (h < 0) return k_s*alpha*alpha*exp(alpha*h);
else return 0;
}
// C (Gardner).
double C(double h)
{
if (h < 0) return alpha*(theta_s - theta_r)*exp(alpha*h);
else return alpha*(theta_s - theta_r);
}
// dC/dh (Gardner).
double dCdh(double h)
{
if (h < 0) return alpha*(theta_s - theta_r)*alpha*exp(alpha*h);
else return 0;
}
// ddC/dhh (Gardner).
double ddCdhh(double h)
{
if (h < 0) return alpha * alpha * (theta_s - theta_r) * alpha * exp(alpha * h);
else return 0;
}
};
class ConstitutiveRelationsGenuchten : public ConstitutiveRelations
{
public:
ConstitutiveRelationsGenuchten(double alpha, double m, double n, double theta_s, double theta_r, double k_s, double storativity) : ConstitutiveRelations(alpha, theta_s, theta_r, k_s), m(m), n(n), storativity(storativity)
{}
// K (van Genuchten).
double K(double h)
{
if (h < 0) return
k_s*std::pow((1 + std::pow((-alpha*h), n)), (-m / 2))*std::pow((1 -
std::pow((-alpha*h), (m*n))*std::pow((1 + std::pow((-alpha*h), n)), (-m))), 2);
else return k_s;
}
// dK/dh (van Genuchten).
double dKdh(double h)
{
if (h < 0) return
k_s*std::pow((1 + std::pow((-alpha*h), n)), (-m / 2))*(1 -
std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)))*(-2 * m*n*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / h +
2 * m*n*std::pow((-alpha*h), n)*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (h*(1 + std::pow((-alpha*h), n)))) -
k_s*m*n*std::pow((-alpha*h), n)*std::pow((1 + std::pow((-alpha*h), n)), (-m / 2))*std::pow((1 -
std::pow((-alpha*h), (m*n))*std::pow((1 + std::pow((-alpha*h), n)), (-m))), 2) / (2 * h*(1 +
std::pow((-alpha*h), n)));
else return 0;
}
// ddK/dhh (van Genuchten).
double ddKdhh(double h)
{
if (h < 0) return
k_s*std::pow((1 + std::pow((-alpha*h), n)), (-m / 2))*(1 -
std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)))*(-2 * std::pow(m, 2)*std::pow(n, 2)*std::pow((-alpha*h), (m*n))*std::pow((1
+ std::pow((-alpha*h), n)), (-m)) / std::pow(h, 2) +
2 * m*n*std::pow((-alpha*h), (m*n))*std::pow((1 + std::pow((-alpha*h), n)), (-m)) / std::pow(h, 2)
- 2 * m*n*std::pow((-alpha*h), n)*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (std::pow(h, 2)*(1 + std::pow((-alpha*h), n))) -
2 * m*std::pow(n, 2)*std::pow((-alpha*h), (2 * n))*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (std::pow(h, 2)*std::pow((1 + std::pow((-alpha*h), n)), 2)) -
2 * std::pow(m, 2)*std::pow(n, 2)*std::pow((-alpha*h), (2 * n))*std::pow((-alpha*h), (m*n))*std::pow((1
+ std::pow((-alpha*h), n)), (-m)) / (std::pow(h, 2)*std::pow((1 + std::pow((-alpha*h), n)), 2)) +
2 * m*std::pow(n, 2)*std::pow((-alpha*h), n)*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (std::pow(h, 2)*(1 + std::pow((-alpha*h), n))) +
4 * std::pow(m, 2)*std::pow(n, 2)*std::pow((-alpha*h), n)*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (std::pow(h, 2)*(1 + std::pow((-alpha*h), n)))) +
k_s*std::pow((1 + std::pow((-alpha*h), n)), (-m / 2))*(-m*n*std::pow((-alpha*h), (m*n))*std::pow((1
+ std::pow((-alpha*h), n)), (-m)) / h +
m*n*std::pow((-alpha*h), n)*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (h*(1 +
std::pow((-alpha*h), n))))*(-2 * m*n*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / h +
2 * m*n*std::pow((-alpha*h), n)*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (h*(1 + std::pow((-alpha*h), n)))) -
k_s*m*n*std::pow((-alpha*h), n)*std::pow((1 + std::pow((-alpha*h), n)), (-m / 2))*(1 -
std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)))*(-2 * m*n*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / h +
2 * m*n*std::pow((-alpha*h), n)*std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m)) / (h*(1 + std::pow((-alpha*h), n)))) / (h*(1 +
std::pow((-alpha*h), n))) + k_s*m*n*std::pow((-alpha*h), n)*std::pow((1 +
std::pow((-alpha*h), n)), (-m / 2))*std::pow((1 - std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m))), 2) / (2 * std::pow(h, 2)*(1 + std::pow((-alpha*h), n))) +
k_s*m*std::pow(n, 2)*std::pow((-alpha*h), (2 * n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m / 2))*std::pow((1 - std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m))), 2) / (2 * std::pow(h, 2)*std::pow((1 +
std::pow((-alpha*h), n)), 2)) - k_s*m*std::pow(n, 2)*std::pow((-alpha*h), n)*std::pow((1 +
std::pow((-alpha*h), n)), (-m / 2))*std::pow((1 - std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m))), 2) / (2 * std::pow(h, 2)*(1 + std::pow((-alpha*h), n))) +
k_s*std::pow(m, 2)*std::pow(n, 2)*std::pow((-alpha*h), (2 * n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m / 2))*std::pow((1 - std::pow((-alpha*h), (m*n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m))), 2) / (4 * std::pow(h, 2)*std::pow((1 +
std::pow((-alpha*h), n)), 2));
else return 0;
}
// C (van Genuchten).
double C(double h)
{
if (h < 0) return
storativity*std::pow((1 + std::pow((-alpha*h), n)), (-m))*(theta_s - theta_r) / theta_s -
m*n*std::pow((-alpha*h), n)*std::pow((1 + std::pow((-alpha*h), n)), (-m))*(theta_s - theta_r) / (h*(1 + std::pow((-alpha*h), n)));
else return storativity;
}
// dC/dh (van Genuchten).
double dCdh(double h)
{
if (h < 0) return
m*n*std::pow((-alpha*h), n)*std::pow((1 + std::pow((-alpha*h), n)), (-m))*(theta_s - theta_r) / (std::pow(h, 2)*(1 + std::pow((-alpha*h), n))) + m*std::pow(n, 2)*std::pow((-alpha*h), (2 * n))*std::pow((1 +
std::pow((-alpha*h), n)), (-m))*(theta_s - theta_r) / (std::pow(h, 2)*std::pow((1 + std::pow((-alpha*h), n)), 2)) + std::pow(m, 2)*std::pow(n, 2)*std::pow((-alpha*h), (2 * n))*std::pow((1 + std::pow((-alpha*h), n)), (-m))*(theta_s - theta_r) / (std::pow(h, 2)*
std::pow((1 + std::pow((-alpha*h), n)), 2)) - m*std::pow(n, 2)*std::pow((-alpha*h), n)*std::pow((1 + std::pow((-alpha*h), n)), (-m))*(theta_s - theta_r) / (std::pow(h, 2)*(1 + std::pow((-alpha*h), n))) -
m*n*storativity*std::pow((-alpha*h), n)*std::pow((1 + std::pow((-alpha*h), n)), (-m))*(theta_s - theta_r) / (theta_s*h*(1 + std::pow((-alpha*h), n)));
else return 0;
}
// ddC/dhh (Gardner).
/// \todo This is not correct, the correct relation should be here.
// it is e.g. used in basic-rk-newton.
double ddCdhh(double h)
{
return 0.0;
}
protected:
double m, n, storativity;
};
class ConstitutiveRelationsGenuchtenWithLayer : public ConstitutiveRelationsGenuchten
{
public:
ConstitutiveRelationsGenuchtenWithLayer(int constitutive_table_method, int num_inside_pts, double low_limit, double table_precision,
double table_limit, double* k_s_vals, double* alpha_vals, double* n_vals, double* m_vals, double* theta_r_vals, double* theta_s_vals, double* storativity_vals) : ConstitutiveRelationsGenuchten(0, 0, 0, 0, 0, 0, 0), constitutive_table_method(constitutive_table_method),
num_inside_pts(num_inside_pts), polynomials_ready(false), low_limit(low_limit), table_precision(table_precision), table_limit(table_limit), k_s_vals(k_s_vals), alpha_vals(alpha_vals), n_vals(n_vals), m_vals(m_vals), theta_r_vals(theta_r_vals), theta_s_vals(theta_s_vals), storativity_vals(storativity_vals), constitutive_tables_ready(false),
polynomials_allocated(false), k_table(NULL), dKdh_table(NULL), ddKdhh_table(NULL), c_table(NULL), dCdh_table(NULL), polynomials(NULL), pol_search_help(NULL), k_pols(NULL), c_pols(NULL)
{}
ConstitutiveRelationsGenuchtenWithLayer(double alpha, double m, double n, double theta_s, double theta_r, double k_s, double storativity, int constitutive_table_method, int num_inside_pts, double low_limit, double table_precision,
double table_limit, double* k_s_vals, double* alpha_vals, double* n_vals, double* m_vals, double* theta_r_vals, double* theta_s_vals, double* storativity_vals)
: ConstitutiveRelationsGenuchten(alpha, m, n, theta_s, theta_r, k_s, storativity), constitutive_table_method(constitutive_table_method),
num_inside_pts(num_inside_pts), polynomials_ready(false), low_limit(low_limit), table_precision(table_precision), table_limit(table_limit), k_s_vals(k_s_vals), alpha_vals(alpha_vals), n_vals(n_vals), m_vals(m_vals), theta_r_vals(theta_r_vals), theta_s_vals(theta_s_vals), storativity_vals(storativity_vals), constitutive_tables_ready(false),
polynomials_allocated(false), k_table(NULL), dKdh_table(NULL), ddKdhh_table(NULL), c_table(NULL), dCdh_table(NULL), polynomials(NULL), pol_search_help(NULL), k_pols(NULL), c_pols(NULL)
{}
// This function uses Horner scheme to efficiently evaluate values of
// polynomials in approximating K(h) function close to full saturation.
double horner(double *pol, double x, int n) {
double px = 0.0;
for (int i = 0; i < n; i++) {
px = px*x + pol[n - 1 - i];
}
return px;
}
// K (van Genuchten).
double K(double h) {
return K(h, 0);
}
double K(double h, int layer)
{
double value;
int location;
if (h > low_limit && h < 0 && polynomials_ready && constitutive_table_method == 1) {
return horner(polynomials[layer][0], h, (6 + num_inside_pts));
}
else
{
if (constitutive_table_method == 0 || !constitutive_tables_ready || h < table_limit) {
alpha = alpha_vals[layer];
n = n_vals[layer];
m = m_vals[layer];
k_s = k_s_vals[layer];
theta_r = theta_r_vals[layer];
theta_s = theta_s_vals[layer];
storativity = storativity_vals[layer];
if (h < 0) return
k_s*(std::pow(1 - std::pow(-(alpha*h), m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m), 2) /
std::pow(1 + std::pow(-(alpha*h), n), m / 2.));
else return k_s;
}
else if (h < 0 && constitutive_table_method == 1) {
location = -int(h / table_precision);
value = (k_table[layer][location + 1] - k_table[layer][location])*(-h / table_precision - location) + k_table[layer][location];
return value;
}
else if (h < 0 && constitutive_table_method == 2) {
location = pol_search_help[int(-h)];
return horner(k_pols[location][layer][0], h, 6);
}
else return k_s_vals[layer];
}
}
// dK/dh (van Genuchten).
double dKdh(double h) {
return dKdh(h, 0);
}
double dKdh(double h, int layer)
{
double value;
int location;
if (h > low_limit && h < 0 && polynomials_ready && constitutive_table_method == 1) {
return horner(polynomials[layer][1], h, (5 + num_inside_pts));
}
else
{
if (constitutive_table_method == 0 || !constitutive_tables_ready || h < table_limit) {
alpha = alpha_vals[layer];
n = n_vals[layer];
m = m_vals[layer];
k_s = k_s_vals[layer];
theta_r = theta_r_vals[layer];
theta_s = theta_s_vals[layer];
storativity = storativity_vals[layer];
if (h < 0) return
k_s*((alpha*std::pow(-(alpha*h), -1 + n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m / 2.)*
std::pow(1 - std::pow(-(alpha*h), m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m), 2)*m*n) / 2. +
(2 * (1 - std::pow(-(alpha*h), m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m))*
(-(alpha*std::pow(-(alpha*h), -1 + n + m*n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*m*n) +
(alpha*std::pow(-(alpha*h), -1 + m*n)*m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m))) /
std::pow(1 + std::pow(-(alpha*h), n), m / 2.));
else return 0;
}
else if (h < 0 && constitutive_table_method == 1) {
location = -int(h / table_precision);
value = (dKdh_table[layer][location + 1] - dKdh_table[layer][location])*(-h / table_precision - location) + dKdh_table[layer][location];
return value;
}
else if (h < 0 && constitutive_table_method == 2) {
location = pol_search_help[int(-h)];
return horner(k_pols[location][layer][1], h, 5);
}
else return 0;
}
}
// ddK/dhh (van Genuchten).
double ddKdhh(double h) {
return ddKdhh(h, 0);
}
double ddKdhh(double h, int layer)
{
int location;
double value;
if (h > low_limit && h < 0 && polynomials_ready && constitutive_table_method == 1) {
return horner(polynomials[layer][2], h, (4 + num_inside_pts));
}
else
{
if (constitutive_table_method == 0 || !constitutive_tables_ready || h < table_limit) {
alpha = alpha_vals[layer];
n = n_vals[layer];
m = m_vals[layer];
k_s = k_s_vals[layer];
theta_r = theta_r_vals[layer];
theta_s = theta_s_vals[layer];
storativity = storativity_vals[layer];
if (h < 0) return
k_s*(-(std::pow(alpha, 2)*std::pow(-(alpha*h), -2 + n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m / 2.)*
std::pow(1 - std::pow(-(alpha*h), m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m), 2)*m*(-1 + n)*n) / 2.\
- (std::pow(alpha, 2)*std::pow(-(alpha*h), -2 + 2 * n)*
std::pow(1 + std::pow(-(alpha*h), n), -2 - m / 2.)*
std::pow(1 - std::pow(-(alpha*h), m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m), 2)*(-1 - m / 2.)*m*
std::pow(n, 2)) / 2. + 2 * alpha*std::pow(-(alpha*h), -1 + n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m / 2.)*
(1 - std::pow(-(alpha*h), m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m))*m*n*
(-(alpha*std::pow(-(alpha*h), -1 + n + m*n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*m*n) +
(alpha*std::pow(-(alpha*h), -1 + m*n)*m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m)) +
(2 * std::pow(-(alpha*std::pow(-(alpha*h), -1 + n + m*n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*m*n) +
(alpha*std::pow(-(alpha*h), -1 + m*n)*m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m), 2)) /
std::pow(1 + std::pow(-(alpha*h), n), m / 2.) +
(2 * (1 - std::pow(-(alpha*h), m*n) /
std::pow(1 + std::pow(-(alpha*h), n), m))*
(std::pow(alpha, 2)*std::pow(-(alpha*h), -2 + 2 * n + m*n)*
std::pow(1 + std::pow(-(alpha*h), n), -2 - m)*(-1 - m)*m*
std::pow(n, 2) + std::pow(alpha, 2)*
std::pow(-(alpha*h), -2 + n + m*n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*std::pow(m, 2)*
std::pow(n, 2) - (std::pow(alpha, 2)*
std::pow(-(alpha*h), -2 + m*n)*m*n*(-1 + m*n)) /
std::pow(1 + std::pow(-(alpha*h), n), m) +
std::pow(alpha, 2)*std::pow(-(alpha*h), -2 + n + m*n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*m*n*
(-1 + n + m*n))) / std::pow(1 + std::pow(-(alpha*h), n), m / 2.));
else return 0;
}
else if (h < 0 && constitutive_table_method == 1) {
location = -int(h / table_precision);
value = (ddKdhh_table[layer][location + 1] -
ddKdhh_table[layer][location])*(-h / table_precision - location) + ddKdhh_table[layer][location];
return value;
}
else if (h < 0 && constitutive_table_method == 2) {
location = pol_search_help[int(-h)];
return horner(k_pols[location][layer][2], h, 4);
}
else return 0;
}
}
// C (van Genuchten).
double C(double h) {
return C(h, 0);
}
double C(double h, int layer)
{
int location;
double value;
if (constitutive_table_method == 0 || !constitutive_tables_ready || h < table_limit) {
alpha = alpha_vals[layer];
n = n_vals[layer];
m = m_vals[layer];
k_s = k_s_vals[layer];
theta_r = theta_r_vals[layer];
theta_s = theta_s_vals[layer];
storativity = storativity_vals[layer];
if (h < 0) return
alpha*std::pow(-(alpha*h), -1 + n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*m*n*(theta_s - theta_r) +
(storativity*((theta_s - theta_r) / std::pow(1 + std::pow(-(alpha*h), n), m) +
theta_r)) / theta_s;
else return storativity;
}
else if (h < 0 && constitutive_table_method == 1) {
location = -int(h / table_precision);
value = (c_table[layer][location + 1] - c_table[layer][location])*(-h / table_precision - location) + c_table[layer][location];
return value;
}
else if (h < 0 && constitutive_table_method == 2) {
location = pol_search_help[int(-h)];
return horner(c_pols[location][layer][0], h, 4);
}
else return storativity_vals[layer];
}
// dC/dh (van Genuchten).
double dCdh(double h) {
return dCdh(h, 0);
}
double dCdh(double h, int layer)
{
int location;
double value;
if (constitutive_table_method == 0 || !constitutive_tables_ready || h < table_limit) {
alpha = alpha_vals[layer];
n = n_vals[layer];
m = m_vals[layer];
k_s = k_s_vals[layer];
theta_r = theta_r_vals[layer];
theta_s = theta_s_vals[layer];
storativity = storativity_vals[layer];
if (h < 0) return
-(std::pow(alpha, 2)*std::pow(-(alpha*h), -2 + n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*m*(-1 + n)*n*
(theta_s - theta_r)) - std::pow(alpha, 2)*std::pow(-(alpha*h), -2 + 2 * n)*
std::pow(1 + std::pow(-(alpha*h), n), -2 - m)*(-1 - m)*m*std::pow(n, 2)*
(theta_s - theta_r) + (alpha*std::pow(-(alpha*h), -1 + n)*
std::pow(1 + std::pow(-(alpha*h), n), -1 - m)*m*n*storativity*
(theta_s - theta_r)) / theta_s;
else return 0;
}
else if (h < 0 && constitutive_table_method == 1) {
location = -int(h / table_precision);
value = (dCdh_table[layer][location + 1] -
dCdh_table[layer][location])*(-h / table_precision - location) + dCdh_table[layer][location];
return value;
}
else if (h < 0 && constitutive_table_method == 2) {
location = pol_search_help[int(-h)];
return horner(c_pols[location][layer][1], h, 3);
}
else return 0;
}
int constitutive_table_method, num_inside_pts;
bool polynomials_ready;
double low_limit;
double table_precision;
double table_limit;
double* k_s_vals;
double* alpha_vals;
double* n_vals;
double* m_vals;
double* theta_r_vals;
double* theta_s_vals;
double* storativity_vals;
bool constitutive_tables_ready;
bool polynomials_allocated;
double** k_table;
double** dKdh_table;
double** ddKdhh_table;
double** c_table;
double** dCdh_table;
double*** polynomials;
int* pol_search_help;
double**** k_pols;
double**** c_pols;
};
bool init_polynomials(int n, double low_limit, double *points, int n_inside_points, int layer, ConstitutiveRelationsGenuchtenWithLayer* constitutive, int material_count, int num_of_intervals, double* intervals_4_approx);
bool get_constitutive_tables(int method, ConstitutiveRelationsGenuchtenWithLayer* constitutive, int material_count); | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-ie-newton/definitions.h | .h | 2,128 | 77 | #include "hermes2d.h"
#include "../constitutive.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
/* Custom non-constant Dirichlet condition */
class CustomEssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
CustomEssentialBCNonConst(std::vector<std::string>(markers))
: EssentialBoundaryCondition<double>(markers)
{
}
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
};
/* Weak forms */
class CustomWeakFormRichardsIE : public WeakForm < double >
{
public:
CustomWeakFormRichardsIE(double time_step, MeshFunctionSharedPtr<double> h_time_prev, ConstitutiveRelations* constitutive);
private:
class CustomJacobianFormVol : public MatrixFormVol < double >
{
public:
CustomJacobianFormVol(unsigned int i, unsigned int j, double time_step)
: MatrixFormVol<double>(i, j), time_step(time_step)
{
}
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;
double time_step;
};
class CustomResidualFormVol : public VectorFormVol < double >
{
public:
CustomResidualFormVol(int i, double time_step)
: VectorFormVol<double>(i), time_step(time_step) {};
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 time_step;
};
ConstitutiveRelations* constitutive;
WeakForm<double>* clone() const
{
CustomWeakFormRichardsIE* wf = new CustomWeakFormRichardsIE(*this);
wf->constitutive = this->constitutive;
return wf;
}
}; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-ie-newton/main.cpp | .cpp | 4,864 | 145 | #include "definitions.h"
// This example solves a simple version of the time-dependent
// Richard's equation using the backward Euler method in time
// combined with the Newton's method in each time step. It describes
// infiltration into an initially dry soil. The example has a exact
// solution that is given in terms of a Fourier series (see a paper
// by Tracy). The exact solution is not used here.
//
// PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0
// where K(h) = K_S*exp(alpha*h) for h < 0,
// K(h) = K_S for h >= 0,
// C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0,
// C(h) = alpha*(theta_s - theta_r) for h >= 0.
//
// Domain: square (0, 100)^2.
//
// BC: Dirichlet, given by the initial condition.
// IC: Flat in all elements except the top layer, within this
// layer the solution rises linearly to match the Dirichlet condition.
//
// NOTE: The pressure head 'h' is between -1000 and 0. For convenience, we
// increase it by an offset H_OFFSET = 1000. In this way we can start
// from a zero coefficient vector.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_GLOB_REF_NUM = 3;
// Number of initial refinements towards boundary.
const int INIT_REF_NUM_BDY = 5;
// Initial polynomial degree.
const int P_INIT = 2;
// Time step.
double time_step = 5e-4;
// Time interval length.
const double T_FINAL = 0.4;
// Problem parameters.
double K_S = 20.464;
double ALPHA = 0.001;
double THETA_R = 0;
double THETA_S = 0.45;
double M, N, STORATIVITY;
// Constitutive relations.
enum CONSTITUTIVE_RELATIONS {
CONSTITUTIVE_GENUCHTEN, // Van Genuchten.
CONSTITUTIVE_GARDNER // Gardner.
};
// Use van Genuchten's constitutive relations, or Gardner's.
CONSTITUTIVE_RELATIONS constitutive_relations_type = CONSTITUTIVE_GARDNER;
// Newton's method.
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-6;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 100;
const double DAMPING_COEFF = 1.0;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", mesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY);
// Initialize boundary conditions.
CustomEssentialBCNonConst bc_essential({ "Bottom", "Right", "Top", "Left" });
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Zero initial solutions. This is why we use H_OFFSET.
MeshFunctionSharedPtr<double> h_time_prev(new ZeroSolution<double>(mesh));
// Initialize views.
ScalarView view("Initial condition", new WinGeom(0, 0, 600, 500));
view.fix_scale_width(80);
// Visualize the initial condition.
view.show(h_time_prev);
// Initialize the constitutive relations.
ConstitutiveRelations* constitutive_relations;
if (constitutive_relations_type == CONSTITUTIVE_GENUCHTEN)
constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY);
else
constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S);
// Initialize the weak formulation.
double current_time = 0;
WeakFormSharedPtr<double> wf(new CustomWeakFormRichardsIE(time_step, h_time_prev, constitutive_relations));
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, space);
// Initialize Newton solver.
NewtonSolver<double> newton(&dp);
newton.set_verbose_output(true);
// Time stepping:
int ts = 1;
do
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f s", ts, current_time);
// Perform Newton's iteration.
try
{
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
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 Solution<double> sln->
Solution<double>::vector_to_solution(newton.get_sln_vector(), space, h_time_prev);
// Visualize the solution.
char title[100];
sprintf(title, "Time %g s", current_time);
view.set_title(title);
view.show(h_time_prev);
// Increase current time and time step counter.
current_time += time_step;
ts++;
} while (current_time < T_FINAL);
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-ie-newton/definitions.cpp | .cpp | 3,838 | 94 | #include "definitions.h"
// The pressure head is raised by H_OFFSET
// so that the initial condition can be taken
// as the zero vector. Note: the resulting
// pressure head will also be greater than the
// true one by this offset.
double H_OFFSET = 1000;
/* Custom non-constant Dirichlet condition */
EssentialBCValueType CustomEssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double CustomEssentialBCNonConst::value(double x, double y) const
{
return x*(100. - x) / 2.5 * y / 100 - 1000. + H_OFFSET;
}
/* Custom weak forms */
CustomWeakFormRichardsIE::CustomWeakFormRichardsIE(double time_step, MeshFunctionSharedPtr<double> h_time_prev, ConstitutiveRelations* constitutive) : WeakForm<double>(1), constitutive(constitutive)
{
// Jacobian volumetric part.
CustomJacobianFormVol* jac_form_vol = new CustomJacobianFormVol(0, 0, time_step);
jac_form_vol->set_ext(h_time_prev);
add_matrix_form(jac_form_vol);
// Residual - volumetric.
CustomResidualFormVol* res_form_vol = new CustomResidualFormVol(0, time_step);
res_form_vol->set_ext(h_time_prev);
add_vector_form(res_form_vol);
}
double CustomWeakFormRichardsIE::CustomJacobianFormVol::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;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
result += wt[i] * (static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->dCdh(h_val_i) * u->val[i] * (h_prev_newton->val[i] - h_prev_time->val[i])
* v->val[i] + static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->C(h_val_i) * u->val[i] * v->val[i]
+ static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->dKdh(h_val_i) * u->val[i] * (h_prev_newton->dx[i] * v->dx[i]
+ h_prev_newton->dy[i] * v->dy[i]) * time_step
+ static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->K(h_val_i) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]) * time_step
- static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->ddKdhh(h_val_i) * u->val[i] * h_prev_newton->dy[i] * v->val[i] * time_step
- static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->dKdh(h_val_i) * u->dy[i] * v->val[i] * time_step
);
}
return result;
}
Ord CustomWeakFormRichardsIE::CustomJacobianFormVol::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>* CustomWeakFormRichardsIE::CustomJacobianFormVol::clone() const
{
return new CustomJacobianFormVol(*this);
}
double CustomWeakFormRichardsIE::CustomResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
result += wt[i] * (static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->C(h_val_i) * (h_val_i - (h_prev_time->val[i] - H_OFFSET)) * v->val[i]
+ static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->K(h_val_i) * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i]) * time_step
- static_cast<CustomWeakFormRichardsIE*>(wf)->constitutive->dKdh(h_val_i) * h_prev_newton->dy[i] * v->val[i] * time_step
);
}
return result;
}
Ord CustomWeakFormRichardsIE::CustomResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
VectorFormVol<double>* CustomWeakFormRichardsIE::CustomResidualFormVol::clone() const
{
return new CustomResidualFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-adapt/definitions.h | .h | 17,758 | 449 | #include "hermes2d.h"
#include "../constitutive.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
// The first part of the file dontains forms for the Newton's
// method. Forms for Picard are in the second part.
/*** INITIAL CONDITION ***/
class InitialSolutionRichards : public ExactSolutionScalar < double >
{
public:
InitialSolutionRichards(MeshSharedPtr mesh, double constant)
: ExactSolutionScalar<double>(mesh), constant(constant) {};
virtual double value(double x, double y) const {
return constant;
}
virtual void derivatives(double x, double y, double& dx, double& dy) const {
dx = 0.0;
dy = 0.0;
};
virtual Ord ord(double x, double y) const {
return Ord(0);
}
virtual MeshFunction<double>* clone() const
{
return new InitialSolutionRichards(mesh, constant);
}
// Value.
double constant;
};
class ExactSolutionPoisson : public ExactSolutionScalar < double >
{
public:
ExactSolutionPoisson(MeshSharedPtr mesh) : ExactSolutionScalar<double>(mesh) {};
virtual double value(double x, double y) const {
return x*x + y*y;
}
virtual void derivatives(double x, double y, double& dx, double& dy) const {
dx = 2 * x;
dy = 2 * y;
};
virtual MeshFunction<double>* clone() const
{
return new ExactSolutionPoisson(mesh);
}
virtual Ord ord(double x, double y) const {
return Ord(2);
}
};
/*** NEWTON ***/
class WeakFormRichardsNewtonEuler : public WeakForm < double >
{
public:
WeakFormRichardsNewtonEuler(ConstitutiveRelationsGenuchtenWithLayer* relations, double tau, MeshFunctionSharedPtr<double> prev_time_sln, MeshSharedPtr mesh)
: WeakForm<double>(1), mesh(mesh), relations(relations) {
JacobianFormNewtonEuler* jac_form = new JacobianFormNewtonEuler(0, 0, relations, tau);
jac_form->set_ext(prev_time_sln);
add_matrix_form(jac_form);
ResidualFormNewtonEuler* res_form = new ResidualFormNewtonEuler(0, relations, tau);
res_form->set_ext(prev_time_sln);
add_vector_form(res_form);
}
private:
class JacobianFormNewtonEuler : public MatrixFormVol < double >
{
public:
JacobianFormNewtonEuler(unsigned int i, unsigned int j, ConstitutiveRelationsGenuchtenWithLayer* relations, double tau)
: MatrixFormVol<double>(i, j), tau(tau), relations(relations) { }
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 {
std::string elem_marker = static_cast<WeakFormRichardsNewtonEuler*>(wf)->mesh->get_element_markers_conversion().get_user_marker(e->elem_marker).marker;
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (
relations->C(h_prev_newton->val[i], atoi(elem_marker.c_str())) * u->val[i] * v->val[i] / tau
+ relations->dCdh(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* u->val[i] * h_prev_newton->val[i] * v->val[i] / tau
- relations->dCdh(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* u->val[i] * h_prev_time->val[i] * v->val[i] / tau
+ relations->K(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ relations->dKdh(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* u->val[i] *
(h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- relations->dKdh(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* u->dy[i] * v->val[i]
- relations->ddKdhh(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* u->val[i] * h_prev_newton->dy[i] * v->val[i]
);
return result;
}
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 matrix_form<double, double>(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 Ord(30);
}
MatrixFormVol<double>* clone() const
{
JacobianFormNewtonEuler* form = new JacobianFormNewtonEuler(i, j, relations, tau);
form->wf = this->wf;
return form;
}
// Members.
double tau;
ConstitutiveRelationsGenuchtenWithLayer* relations;
};
class ResidualFormNewtonEuler : public VectorFormVol < double >
{
public:
ResidualFormNewtonEuler(int i, ConstitutiveRelationsGenuchtenWithLayer* relations, double tau)
: VectorFormVol<double>(i), tau(tau), relations(relations) { }
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 {
std::string elem_marker = static_cast<WeakFormRichardsNewtonEuler*>(wf)->mesh->get_element_markers_conversion().get_user_marker(e->elem_marker).marker;
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * (
relations->C(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* (h_prev_newton->val[i] - h_prev_time->val[i]) * v->val[i] / tau
+ relations->K(h_prev_newton->val[i], atoi(elem_marker.c_str()))
* (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- relations->dKdh(h_prev_newton->val[i], atoi(elem_marker.c_str())) * h_prev_newton->dy[i] * v->val[i]
);
}
return result;
}
virtual double 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);
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
return Ord(30);
}
VectorFormVol<double>* clone() const
{
ResidualFormNewtonEuler* form = new ResidualFormNewtonEuler(i, relations, tau);
form->wf = this->wf;
return form;
}
// Members.
double tau;
ConstitutiveRelationsGenuchtenWithLayer* relations;
};
MeshSharedPtr mesh;
ConstitutiveRelationsGenuchtenWithLayer* relations;
WeakForm<double>* clone() const
{
WeakFormRichardsNewtonEuler* wf = new WeakFormRichardsNewtonEuler(*this);
wf->relations = this->relations;
return wf;
}
};
class WeakFormRichardsNewtonCrankNicolson : public WeakForm < double >
{
public:
WeakFormRichardsNewtonCrankNicolson(ConstitutiveRelationsGenuchtenWithLayer* relations, double tau, MeshFunctionSharedPtr<double> prev_time_sln, MeshSharedPtr mesh) : WeakForm<double>(1), relations(relations), mesh(mesh) {
JacobianFormNewtonCrankNicolson* jac_form = new JacobianFormNewtonCrankNicolson(0, 0, relations, tau);
jac_form->set_ext(prev_time_sln);
add_matrix_form(jac_form);
ResidualFormNewtonCrankNicolson* res_form = new ResidualFormNewtonCrankNicolson(0, relations, tau);
res_form->set_ext(prev_time_sln);
add_vector_form(res_form);
}
private:
class JacobianFormNewtonCrankNicolson : public MatrixFormVol < double >
{
public:
JacobianFormNewtonCrankNicolson(unsigned int i, unsigned int j, ConstitutiveRelationsGenuchtenWithLayer* relations, double tau)
: MatrixFormVol<double>(i, j), tau(tau), relations(relations) { }
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 {
std::string elem_marker = static_cast<WeakFormRichardsNewtonCrankNicolson*>(wf)->mesh->get_element_markers_conversion().get_user_marker(e->elem_marker).marker;
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * 0.5 * ( // implicit Euler part:
relations->C(h_prev_newton->val[i], atoi(elem_marker.c_str())) * u->val[i] * v->val[i] / tau
+ relations->dCdh(h_prev_newton->val[i], atoi(elem_marker.c_str())) * u->val[i] * h_prev_newton->val[i] * v->val[i] / tau
- relations->dCdh(h_prev_newton->val[i], atoi(elem_marker.c_str())) * u->val[i] * h_prev_time->val[i] * v->val[i] / tau
+ relations->K(h_prev_newton->val[i], atoi(elem_marker.c_str())) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ relations->dKdh(h_prev_newton->val[i], atoi(elem_marker.c_str())) * u->val[i] *
(h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- relations->dKdh(h_prev_newton->val[i], atoi(elem_marker.c_str())) * u->dy[i] * v->val[i]
- relations->ddKdhh(h_prev_newton->val[i], atoi(elem_marker.c_str())) * u->val[i] * h_prev_newton->dy[i] * v->val[i]
)
+ wt[i] * 0.5 * ( // explicit Euler part,
relations->C(h_prev_time->val[i], atoi(elem_marker.c_str())) * u->val[i] * v->val[i] / tau
);
return result;
}
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 matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* clone() const
{
JacobianFormNewtonCrankNicolson* form = new JacobianFormNewtonCrankNicolson(i, j, relations, tau);
form->wf = this->wf;
return form;
}
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 Ord(30);
}
// Members.
double tau;
ConstitutiveRelationsGenuchtenWithLayer* relations;
};
class ResidualFormNewtonCrankNicolson : public VectorFormVol < double >
{
public:
ResidualFormNewtonCrankNicolson(int i, ConstitutiveRelationsGenuchtenWithLayer* relations, double tau) : VectorFormVol<double>(i), tau(tau), relations(relations) { }
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 {
double result = 0;
std::string elem_marker = static_cast<WeakFormRichardsNewtonCrankNicolson*>(wf)->mesh->get_element_markers_conversion().get_user_marker(e->elem_marker).marker;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * 0.5 * ( // implicit Euler part
relations->C(h_prev_newton->val[i], atoi(elem_marker.c_str())) * (h_prev_newton->val[i] - h_prev_time->val[i]) * v->val[i] / tau
+ relations->K(h_prev_newton->val[i], atoi(elem_marker.c_str())) * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- relations->dKdh(h_prev_newton->val[i], atoi(elem_marker.c_str())) * h_prev_newton->dy[i] * v->val[i]
)
+ wt[i] * 0.5 * ( // explicit Euler part
relations->C(h_prev_time->val[i], atoi(elem_marker.c_str())) * (h_prev_newton->val[i] - h_prev_time->val[i]) * v->val[i] / tau
+ relations->K(h_prev_time->val[i], atoi(elem_marker.c_str())) * (h_prev_time->dx[i] * v->dx[i] + h_prev_time->dy[i] * v->dy[i])
- relations->dKdh(h_prev_time->val[i], atoi(elem_marker.c_str())) * h_prev_time->dy[i] * v->val[i]
);
}
return result;
}
virtual double 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);
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
return Ord(30);
}
VectorFormVol<double>* clone() const
{
ResidualFormNewtonCrankNicolson* form = new ResidualFormNewtonCrankNicolson(i, relations, tau);
form->wf = this->wf;
return form;
}
// Members.
double tau;
ConstitutiveRelationsGenuchtenWithLayer* relations;
};
MeshSharedPtr mesh;
ConstitutiveRelationsGenuchtenWithLayer* relations;
WeakForm<double>* clone() const
{
WeakFormRichardsNewtonCrankNicolson* wf = new WeakFormRichardsNewtonCrankNicolson(*this);
wf->relations = this->relations;
return wf;
}
};
class WeakFormRichardsPicardEuler : public WeakForm < double >
{
public:
WeakFormRichardsPicardEuler(ConstitutiveRelationsGenuchtenWithLayer* relations, double tau, MeshFunctionSharedPtr<double> prev_picard_sln, MeshFunctionSharedPtr<double> prev_time_sln, MeshSharedPtr mesh) : WeakForm<double>(1), relations(relations), mesh(mesh) {
JacobianFormPicardEuler* jac_form = new JacobianFormPicardEuler(0, 0, relations, tau);
jac_form->set_ext(prev_picard_sln);
add_matrix_form(jac_form);
ResidualFormPicardEuler* res_form = new ResidualFormPicardEuler(0, relations, tau);
res_form->set_ext(prev_picard_sln);
res_form->set_ext(prev_time_sln);
add_vector_form(res_form);
}
private:
class JacobianFormPicardEuler : public MatrixFormVol < double >
{
public:
JacobianFormPicardEuler(unsigned int i, unsigned int j, ConstitutiveRelationsGenuchtenWithLayer* relations, double tau)
: MatrixFormVol<double>(i, j), tau(tau), relations(relations) { }
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 {
std::string elem_marker = static_cast<WeakFormRichardsPicardEuler*>(wf)->mesh->get_element_markers_conversion().get_user_marker(e->elem_marker).marker;
double result = 0;
Func<double>* h_prev_picard = ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * (relations->C(h_prev_picard->val[i], atoi(elem_marker.c_str())) * u->val[i] * v->val[i] / tau
+ relations->K(h_prev_picard->val[i], atoi(elem_marker.c_str())) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
- relations->dKdh(h_prev_picard->val[i], atoi(elem_marker.c_str())) * u->dy[i] * v->val[i]);
}
return result;
}
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 matrix_form<double, double>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormVol<double>* clone() const
{
JacobianFormPicardEuler* form = new JacobianFormPicardEuler(i, j, relations, tau);
form->wf = this->wf;
return form;
}
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 Ord(30);
}
// Members.
double tau;
ConstitutiveRelationsGenuchtenWithLayer* relations;
};
class ResidualFormPicardEuler : public VectorFormVol < double >
{
public:
ResidualFormPicardEuler(int i, ConstitutiveRelationsGenuchtenWithLayer* relations, double tau) : VectorFormVol<double>(i), tau(tau), relations(relations) { }
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 {
std::string elem_marker = static_cast<WeakFormRichardsPicardEuler*>(wf)->mesh->get_element_markers_conversion().get_user_marker(e->elem_marker).marker;
double result = 0;
Func<double>* h_prev_picard = ext[0];
Func<double>* h_prev_time = ext[1];
for (int i = 0; i < n; i++)
result += wt[i] * relations->C(h_prev_picard->val[i], atoi(elem_marker.c_str())) * h_prev_time->val[i] * v->val[i] / tau;
return result;
}
virtual double 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);
}
VectorFormVol<double>* clone() const
{
ResidualFormPicardEuler* form = new ResidualFormPicardEuler(i, relations, tau);
form->wf = this->wf;
return form;
}
virtual Ord ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const {
return Ord(30);
}
// Members.
double tau;
ConstitutiveRelationsGenuchtenWithLayer* relations;
};
MeshSharedPtr mesh;
ConstitutiveRelationsGenuchtenWithLayer* relations;
WeakForm<double>* clone() const
{
WeakFormRichardsPicardEuler* wf = new WeakFormRichardsPicardEuler(*this);
wf->relations = this->relations;
return wf;
}
};
class RichardsEssentialBC : public EssentialBoundaryCondition < double > {
public:
RichardsEssentialBC(std::string marker, double h_elevation, double pulse_end_time, double h_init, double startup_time) :
EssentialBoundaryCondition<double>(std::vector<std::string>()), h_elevation(h_elevation), pulse_end_time(pulse_end_time), h_init(h_init), startup_time(startup_time)
{
markers.push_back(marker);
}
~RichardsEssentialBC() {}
inline EssentialBCValueType get_value_type() const { return BC_FUNCTION; }
virtual double value(double x, double y) const {
if (current_time < startup_time)
return h_init + current_time / startup_time*(h_elevation - h_init);
else if (current_time > pulse_end_time)
return h_init;
else
return h_elevation;
}
// Member.
double h_elevation;
double pulse_end_time;
double h_init;
double startup_time;
}; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-adapt/extras.cpp | .cpp | 14,101 | 415 | #include "definitions.h"
using namespace std;
//Debugging matrix printer.
bool printmatrix(double** A, int n, int m){
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
printf(" %lf ", A[i][j]);
}
printf(" \n");
}
printf("----------------------------------\n");
return true;
}
//Debugging vector printer.
bool printvector(double* vect, int n){
for (int i = 0; i < n; i++){
printf(" %lf ", vect[i]);
}
printf("\n");
printf("----------------------------------\n");
return true;
}
// Creates a table of precalculated constitutive functions.
bool get_constitutive_tables(int method, ConstitutiveRelationsGenuchtenWithLayer* constitutive, int material_count)
{
Hermes::Mixins::Loggable::Static::info("Creating tables of constitutive functions (complicated real exponent relations).");
// Table values dimension.
int bound = int(-constitutive->table_limit / constitutive->table_precision) + 1;
// Allocating arrays.
constitutive->k_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->k_table[i] = new double[bound];
}
constitutive->dKdh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->dKdh_table[i] = new double[bound];
}
constitutive->dKdh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->dKdh_table[i] = new double[bound];
}
constitutive->c_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->c_table[i] = new double[bound];
}
//If Newton method (method==1) selected constitutive function derivations are required.
if (method == 1){
constitutive->dCdh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->dCdh_table[i] = new double[bound];
}
constitutive->ddKdhh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->ddKdhh_table[i] = new double[bound];
}
}
// Calculate and save K(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving K(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->k_table[j][i] = constitutive->K(-constitutive->table_precision*i, j);
}
}
// Calculate and save dKdh(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving dKdh(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->dKdh_table[j][i] = constitutive->dKdh(-constitutive->table_precision*i, j);
}
}
// Calculate and save C(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving C(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->c_table[j][i] = constitutive->C(-constitutive->table_precision*i, j);
}
}
//If Newton method (method==1) selected constitutive function derivations are required.
if (method == 1){
// Calculate and save ddKdhh(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving ddKdhh(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->ddKdhh_table[j][i] = constitutive->ddKdhh(-constitutive->table_precision*i, j);
}
}
// Calculate and save dCdh(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving dCdh(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->dCdh_table[j][i] = constitutive->dCdh(-constitutive->table_precision*i, j);
}
}
}
return true;
}
// Simple Gaussian elimination for full matrices called from init_polynomials().
bool gem_full(double** A, double* b, double* X, int n){
int i, j, k;
double** aa;
double dotproduct, tmp;
aa = new double*[n];
for (i = 0; i < n; i++){
aa[i] = new double[n + 1];
}
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
aa[i][j] = A[i][j];
}
aa[i][n] = b[i];
}
for (j = 0; j < (n - 1); j++){
for (i = j + 1; i < n; i++){
tmp = aa[i][j] / aa[j][j];
for (k = 0; k < (n + 1); k++){
aa[i][k] = aa[i][k] - tmp*aa[j][k];
}
}
}
for (i = n - 1; i > -1; i--){
dotproduct = 0.0;
for (j = i + 1; j < n; j++){
dotproduct = dotproduct + aa[i][j] * X[j];
}
X[i] = (aa[i][n] - dotproduct) / aa[i][i];
}
delete[]aa;
return true;
}
// Initialize polynomial approximation of constitutive relations close to full saturation for constitutive->constitutive_table_method=1.
// For constitutive->constitutive_table_method=2 all constitutive functions are approximated by polynomials, K(h) function by quintic spline, C(h)
// function by cubic splines. Discretization is managed by variable int num_of_intervals and double* intervals_4_approx.
// ------------------------------------------------------------------------------
// For constitutive->constitutive_table_method=1 this function requires folowing arguments:
// n - degree of polynomials
// low_limit - start point of the polynomial approximation
// points - array of points inside the interval bounded by <low_limit, 0> to improve the accuracy, at least one is recommended.
// An approriate amount of points related to the polynomial degree should be selected.
// n_inside_point - number of inside points
// layer - material to be considered.
//------------------------------------------------------------------------------
// For constitutive->constitutive_table_method=2, all parameters are obtained from global definitions.
bool init_polynomials(int n, double low_limit, double *points, int n_inside_points, int layer, ConstitutiveRelationsGenuchtenWithLayer* constitutive, int material_count, int num_of_intervals, double* intervals_4_approx)
{
double** Aside;
double* Bside;
double* X;
switch (constitutive->constitutive_table_method)
{
// no approximation
case 0:
break;
// polynomial approximation only for the the K(h) function surroundings close to zero
case 1:
if (constitutive->polynomials_allocated == false){
constitutive->polynomials = new double**[material_count];
for (int i = 0; i < material_count; i++){
constitutive->polynomials[i] = new double*[3];
}
for (int i = 0; i < material_count; i++){
for (int j = 0; j < 3; j++){
constitutive->polynomials[i][j] = new double[n_inside_points + 6];
}
}
constitutive->polynomials_allocated = true;
}
Aside = new double*[n + n_inside_points];
Bside = new double[n + n_inside_points];
for (int i = 0; i < n; i++){
Aside[i] = new double[n + n_inside_points];
}
// Evaluate the first three rows of the matrix (zero, first and second derivative at point low_limit).
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
Aside[i][j] = 0.0;
}
}
for (int i = 0; i < n; i++){
Aside[3][i] = pow(low_limit, i);
Aside[4][i] = i*pow(low_limit, i - 1);
Aside[5][i] = i*(i - 1)*pow(low_limit, i - 2);
}
Bside[3] = constitutive->K(low_limit, layer);
Bside[4] = constitutive->dKdh(low_limit, layer);
Bside[5] = constitutive->ddKdhh(low_limit, layer);
// Evaluate the second three rows of the matrix (zero, first and second derivative at point zero).
Aside[0][0] = 1.0;
// For the both first and second derivative it does not really matter what value is placed there.
Aside[1][1] = 1.0;
Aside[2][2] = 2.0;
Bside[0] = constitutive->K(0.0, layer);
Bside[1] = 0.0;
Bside[2] = 0.0;
for (int i = 6; i < (6 + n_inside_points); i++){
for (int j = 0; j < n; j++) {
Aside[i][j] = pow(points[i - 6], j);
}
printf("poradi, %i %lf %lf \n", i, constitutive->K(points[i - 6], layer), points[i - 6]);
Bside[i] = constitutive->K(points[i - 6], layer);
printf("layer, %i \n", layer);
}
gem_full(Aside, Bside, constitutive->polynomials[layer][0], (n_inside_points + 6));
for (int i = 1; i < 3; i++){
for (int j = 0; j < (n_inside_points + 5); j++){
constitutive->polynomials[layer][i][j] = (j + 1)*constitutive->polynomials[layer][i - 1][j + 1];
}
constitutive->polynomials[layer][i][n_inside_points + 6 - i] = 0.0;
}
delete[] Aside;
delete[] Bside;
break;
// polynomial approximation for all functions at interval (table_limit, 0)
case 2:
int pts = 0;
if (constitutive->polynomials_allocated == false) {
// K(h) function is approximated by quintic spline.
constitutive->k_pols = new double***[num_of_intervals];
//C(h) function is approximated by cubic spline.
constitutive->c_pols = new double***[num_of_intervals];
for (int i = 0; i < num_of_intervals; i++){
constitutive->k_pols[i] = new double**[material_count];
constitutive->c_pols[i] = new double**[material_count];
for (int j = 0; j < material_count; j++){
constitutive->k_pols[i][j] = new double*[3];
constitutive->c_pols[i][j] = new double*[2];
for (int k = 0; k < 3; k++) {
constitutive->k_pols[i][j][k] = new double[6 + pts];
if (k < 2)
constitutive->c_pols[i][j][k] = new double[5];
}
}
}
// //allocate constitutive->pol_search_help array -- an index array with locations for particular pressure head functions
constitutive->pol_search_help = new int[int(-constitutive->table_limit) + 1];
for (int i = 0; i<int(-constitutive->table_limit); i++){
for (int j = 0; j<num_of_intervals; j++){
if (j < 1) {
if (-i > intervals_4_approx[j]) {
constitutive->pol_search_help[i] = j;
break;
}
}
else {
if (-i > intervals_4_approx[j] && -i <= intervals_4_approx[j - 1]) {
constitutive->pol_search_help[i] = j;
break;
}
}
}
}
constitutive->polynomials_allocated = true;
}
//create matrix
Aside = new double*[6 + pts];
for (int i = 0; i < (6 + pts); i++){
Aside[i] = new double[6 + pts];
}
Bside = new double[6 + pts];
for (int i = 0; i < num_of_intervals; i++) {
if (i < 1){
for (int j = 0; j < 3; j++){
for (int k = 0; k < (6 + pts); k++){
Aside[j][k] = 0.0;
}
}
// Evaluate the second three rows of the matrix (zero, first and second derivative at point zero).
Aside[0][0] = 1.0;
// For the both first and second derivative it does not really matter what value is placed there.
Aside[1][1] = 1.0;
Aside[2][2] = 2.0;
}
else {
for (int j = 0; j < (6 + pts); j++){
Aside[0][j] = pow(intervals_4_approx[i - 1], j);
Aside[1][j] = j*pow(intervals_4_approx[i - 1], j - 1);
Aside[2][j] = j*(j - 1)*pow(intervals_4_approx[i - 1], j - 2);
}
}
for (int j = 0; j < (6 + pts); j++){
Aside[3][j] = pow(intervals_4_approx[i], j);
Aside[4][j] = j*pow(intervals_4_approx[i], j - 1);
Aside[5][j] = j*(j - 1)*pow(intervals_4_approx[i], j - 2);
switch (pts) {
case 0:
break;
case 1:
if (i > 0) {
Aside[6][j] = pow((intervals_4_approx[i] + intervals_4_approx[i - 1]) / 2, j);
}
else {
Aside[6][j] = pow((intervals_4_approx[i]) / 2, j);
}
break;
default:
printf("too many of inside points in polynomial approximation; not implemented!!! (check extras.cpp) \n");
exit(1);
}
}
//Evaluate K(h) function.
if (i < 1){
Bside[0] = constitutive->K(0.0, layer);
Bside[1] = 0.0;
Bside[2] = 0.0;
}
else {
Bside[0] = constitutive->K(intervals_4_approx[i - 1], layer);
Bside[1] = constitutive->dKdh(intervals_4_approx[i - 1], layer);
Bside[2] = constitutive->ddKdhh(intervals_4_approx[i - 1], layer);
}
Bside[3] = constitutive->K(intervals_4_approx[i], layer);
Bside[4] = constitutive->dKdh(intervals_4_approx[i], layer);
Bside[5] = constitutive->ddKdhh(intervals_4_approx[i], layer);
switch (pts) {
case 0:
break;
case 1:
if (i > 0) {
Bside[6] = constitutive->K((intervals_4_approx[i] + intervals_4_approx[i - 1]) / 2, layer);
}
else {
Bside[6] = constitutive->K((intervals_4_approx[i]) / 2, layer);
}
break;
}
gem_full(Aside, Bside, constitutive->k_pols[i][layer][0], (6 + pts));
for (int j = 1; j < 3; j++){
for (int k = 0; k < 5; k++){
constitutive->k_pols[i][layer][j][k] = (k + 1)*constitutive->k_pols[i][layer][j - 1][k + 1];
}
constitutive->k_pols[i][layer][j][6 - j] = 0.0;
}
//Evaluate C(h) functions.
if (i < 1){
Bside[0] = constitutive->C(0.0, layer);
Bside[1] = constitutive->dCdh(0.0, layer);
}
else {
Bside[0] = constitutive->C(intervals_4_approx[i - 1], layer);
Bside[1] = constitutive->dCdh(intervals_4_approx[i - 1], layer);
}
//The first two lines of the matrix Aside stays the same.
for (int j = 0; j < 4; j++){
Aside[2][j] = pow(intervals_4_approx[i], j);
Aside[3][j] = j*pow(intervals_4_approx[i], j - 1);
}
Bside[2] = constitutive->C(intervals_4_approx[i], layer);
Bside[3] = constitutive->dCdh(intervals_4_approx[i], layer);
gem_full(Aside, Bside, constitutive->c_pols[i][layer][0], 4);
for (int k = 0; k < 5; k++){
constitutive->c_pols[i][layer][1][k] = (k + 1)*constitutive->c_pols[i][layer][0][k + 1];
}
constitutive->c_pols[i][layer][1][5] = 0.0;
}
delete[] Aside;
delete[] Bside;
break;
}
return true;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-adapt/main.cpp | .cpp | 20,846 | 503 | #include "definitions.h"
// This example uses adaptivity with dynamical meshes to solve
// the time-dependent Richard's equation. The time discretization
// is backward Euler or Crank-Nicolson, and the nonlinear solver
// in each time step is either Newton or Picard.
//
// PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0
// where K(h) = K_S*exp(alpha*h) for h < 0,
// K(h) = K_S for h >= 0,
// C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0,
// C(h) = alpha*(theta_s - theta_r) for h >= 0.
//
// Picard's linearization: C(h^k)dh^{k+1}/dt - div(K(h^k)grad(h^{k+1})) - (dK/dh(h^k))*(dh^{k+1}/dy) = 0
// Note: the index 'k' does not refer to time stepping.
// Newton's method is more involved, see the file definitions.cpp.
//
// Domain: rectangle (0, 8) x (0, 6.5).
// Units: length: cm
// time: days
//
// BC: Dirichlet, given by the initial condition.
//
// The following parameters can be changed:
// Choose full domain or half domain.
// const char* mesh_file = "domain-full.mesh";
std::string mesh_file = "domain-half.mesh";
// Methods.
// 1 = Newton, 2 = Picard.
const int ITERATIVE_METHOD = 1;
// 1 = implicit Euler, 2 = Crank-Nicolson.
const int TIME_INTEGRATION = 1;
// Adaptive time stepping.
// Time step (in days).
double time_step = 0.5;
// Timestep decrease ratio after unsuccessful nonlinear solve.
double time_step_dec = 0.5;
// Timestep increase ratio after successful nonlinear solve.
double time_step_inc = 1.1;
// Computation will stop if time step drops below this value.
double time_step_min = 1e-8;
// Maximal time step.
double time_step_max = 1.0;
// Elements orders and initial refinements.
// Initial 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 mesh refinements towards the top edge.
const int INIT_REF_NUM_BDY_TOP = 0;
// Adaptivity.
// Every UNREF_FREQth 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<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-2;
// Constitutive relations.
enum CONSTITUTIVE_RELATIONS {
CONSTITUTIVE_GENUCHTEN, // Van Genuchten.
CONSTITUTIVE_GARDNER // Gardner.
};
// Use van Genuchten's constitutive relations, or Gardner's.
CONSTITUTIVE_RELATIONS constitutive_relations_type = CONSTITUTIVE_GENUCHTEN;
// Newton's and Picard's methods.
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL = 1e-5;
// Maximum allowed number of Newton iterations.
int NEWTON_MAX_ITER = 10;
// Stopping criterion for Picard on fine mesh.
const double PICARD_TOL = 1e-2;
// Maximum allowed number of Picard iterations.
int PICARD_MAX_ITER = 23;
// Times.
// Start-up time for time-dependent Dirichlet boundary condition.
const double STARTUP_TIME = 5.0;
// Time interval length.
const double T_FINAL = 1000.0;
// Time interval of the top layer infiltration.
const double PULSE_END_TIME = 1000.0;
// Global time variable.
double current_time = time_step;
// Problem parameters.
// Initial pressure head.
double H_INIT = -15.0;
// Top constant pressure head -- an infiltration experiment.
double H_ELEVATION = 10.0;
double K_S_vals[4] = { 350.2, 712.8, 1.68, 18.64 };
double ALPHA_vals[4] = { 0.01, 1.0, 0.01, 0.01 };
double N_vals[4] = { 2.5, 2.0, 1.23, 2.5 };
double M_vals[4] = { 0.864, 0.626, 0.187, 0.864 };
double THETA_R_vals[4] = { 0.064, 0.0, 0.089, 0.064 };
double THETA_S_vals[4] = { 0.14, 0.43, 0.43, 0.24 };
double STORATIVITY_vals[4] = { 0.1, 0.1, 0.1, 0.1 };
// Precalculation of constitutive tables.
const int MATERIAL_COUNT = 4;
// 0 - constitutive functions are evaluated directly (slow performance).
// 1 - constitutive functions are linearly approximated on interval
// <TABLE_LIMIT; LOW_LIMIT> (very efficient CPU utilization less
// efficient memory consumption (depending on TABLE_PRECISION)).
// 2 - constitutive functions are aproximated by quintic splines.
const int CONSTITUTIVE_TABLE_METHOD = 2;
/* Use only if CONSTITUTIVE_TABLE_METHOD == 2 */
// Number of intervals.
const int NUM_OF_INTERVALS = 16;
// Low limits of intervals approximated by quintic splines.
double INTERVALS_4_APPROX[16] =
{ -1.0, -2.0, -3.0, -4.0, -5.0, -8.0, -10.0, -12.0,
-15.0, -20.0, -30.0, -50.0, -75.0, -100.0, -300.0, -1000.0 };
// This array contains for each integer of h function appropriate polynomial ID.
// First DIM is the interval ID, second DIM is the material ID,
// third DIM is the derivative degree, fourth DIM are the coefficients.
/* END OF Use only if CONSTITUTIVE_TABLE_METHOD == 2 */
/* Use only if CONSTITUTIVE_TABLE_METHOD == 1 */
// Limit of precalculated functions (should be always negative value lower
// then the lowest expect value of the solution (consider DMP!!)
double TABLE_LIMIT = -1000.0;
// Precision of precalculated table use 1.0, 0,1, 0.01, etc.....
const double TABLE_PRECISION = 0.1;
bool CONSTITUTIVE_TABLES_READY = false;
// Polynomial approximation of the K(h) function close to saturation.
// This function has singularity in its second derivative.
// First dimension is material ID
// Second dimension is the polynomial derivative.
// Third dimension are the polynomial's coefficients.
double*** POLYNOMIALS;
// Lower bound of K(h) function approximated by polynomials.
const double LOW_LIMIT = -1.0;
const int NUM_OF_INSIDE_PTS = 0;
/* END OF Use only if CONSTITUTIVE_TABLE_METHOD == 1 */
// Boundary markers.
const std::string BDY_TOP = "1";
const std::string BDY_RIGHT = "2";
const std::string BDY_BOTTOM = "3";
const std::string BDY_LEFT = "4";
// Main function.
int main(int argc, char* argv[])
{
ConstitutiveRelationsGenuchtenWithLayer constitutive_relations(CONSTITUTIVE_TABLE_METHOD, NUM_OF_INSIDE_PTS, LOW_LIMIT, TABLE_PRECISION, TABLE_LIMIT, K_S_vals, ALPHA_vals, N_vals, M_vals, THETA_R_vals, THETA_S_vals, STORATIVITY_vals);
// Either use exact constitutive relations (slow) (method 0) or precalculate
// their linear approximations (faster) (method 1) or
// precalculate their quintic polynomial approximations (method 2) -- managed by
// the following loop "Initializing polynomial approximation".
if (CONSTITUTIVE_TABLE_METHOD == 1)
constitutive_relations.constitutive_tables_ready = get_constitutive_tables(1, &constitutive_relations, MATERIAL_COUNT); // 1 stands for the Newton's method.
// The van Genuchten + Mualem K(h) function is approximated by polynomials close
// to zero in case of CONSTITUTIVE_TABLE_METHOD==1.
// In case of CONSTITUTIVE_TABLE_METHOD==2, all constitutive functions are approximated by polynomials.
Hermes::Mixins::Loggable::Static::info("Initializing polynomial approximations.");
for (int i = 0; i < MATERIAL_COUNT; i++)
{
// Points to be used for polynomial approximation of K(h).
double* points = new double[NUM_OF_INSIDE_PTS];
init_polynomials(6 + NUM_OF_INSIDE_PTS, LOW_LIMIT, points, NUM_OF_INSIDE_PTS, i, &constitutive_relations, MATERIAL_COUNT, NUM_OF_INTERVALS, INTERVALS_4_APPROX);
}
constitutive_relations.polynomials_ready = true;
if (CONSTITUTIVE_TABLE_METHOD == 2)
{
constitutive_relations.constitutive_tables_ready = true;
//Assign table limit to global definition.
constitutive_relations.table_limit = INTERVALS_4_APPROX[NUM_OF_INTERVALS - 1];
}
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Load the mesh.
MeshSharedPtr mesh(new Mesh), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load(mesh_file.c_str(), basemesh);
// Perform initial mesh refinements.
mesh->copy(basemesh);
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements(0, true);
mesh->refine_towards_boundary(BDY_TOP, INIT_REF_NUM_BDY_TOP, true, true);
// Initialize boundary conditions.
RichardsEssentialBC bc_essential(BDY_TOP, H_ELEVATION, PULSE_END_TIME, H_INIT, STARTUP_TIME);
EssentialBCs<double> bcs(&bc_essential);
// Create 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);
// Create a selector which will select optimal candidate.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Solutions for the time stepping and the Newton's method.
MeshFunctionSharedPtr<double> sln(new Solution<double>), ref_sln(new Solution<double>);
MeshFunctionSharedPtr<double> sln_prev_time(new InitialSolutionRichards(mesh, H_INIT));
MeshFunctionSharedPtr<double> sln_prev_iter(new InitialSolutionRichards(mesh, H_INIT));
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf;
if (ITERATIVE_METHOD == 1) {
if (TIME_INTEGRATION == 1) {
Hermes::Mixins::Loggable::Static::info("Creating weak formulation for the Newton's method (implicit Euler in time).");
wf.reset(new WeakFormRichardsNewtonEuler(&constitutive_relations, time_step, sln_prev_time, mesh));
}
else {
Hermes::Mixins::Loggable::Static::info("Creating weak formulation for the Newton's method (Crank-Nicolson in time).");
wf.reset(new WeakFormRichardsNewtonCrankNicolson(&constitutive_relations, time_step, sln_prev_time, mesh));
}
}
else {
if (TIME_INTEGRATION == 1) {
Hermes::Mixins::Loggable::Static::info("Creating weak formulation for the Picard's method (implicit Euler in time).");
wf.reset(new WeakFormRichardsPicardEuler(&constitutive_relations, time_step, sln_prev_iter, sln_prev_time, mesh));
}
else {
Hermes::Mixins::Loggable::Static::info("Creating weak formulation for the Picard's method (Crank-Nicolson in time).");
throw Hermes::Exceptions::Exception("Not implemented yet.");
}
}
// Error estimate and discrete problem size as a function of physical time.
SimpleGraph graph_time_err_est, graph_time_err_exact,
graph_time_dof, graph_time_cpu, graph_time_step;
// Visualize the projection and mesh.
ScalarView view("Initial condition", new WinGeom(0, 0, 630, 350));
view.fix_scale_width(50);
OrderView ordview("Initial mesh", new WinGeom(640, 0, 600, 350));
view.show(sln_prev_time);
ordview.show(space);
//MeshView mview("Mesh", new WinGeom(840, 0, 600, 350));
//mview.show(mesh);
//View::wait();
// Time stepping loop.
int num_time_steps = (int)(T_FINAL / time_step + 0.5);
for (int ts = 1; ts <= num_time_steps; ts++)
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d:", ts);
// Time measurement.
cpu_time.tick();
// 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: mesh->unrefine_all_elements();
space->set_uniform_order(P_INIT);
break;
case 3: mesh->unrefine_all_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 touched during adaptivity.
bool done = false;
int as = 1;
double err_est_rel;
do
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time step lenght %g, time %g (days), adaptivity step %d:", ts, time_step, current_time, 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();
ndof = Space<double>::get_num_dofs(ref_space);
// Next we need to calculate the reference solution.
// Newton's method:
if (ITERATIVE_METHOD == 1) {
double* coeff_vec = new double[ref_space->get_num_dofs()];
// Calculate initial coefficient vector for Newton on the fine mesh.
if (as == 1 && ts == 1) {
Hermes::Mixins::Loggable::Static::info("Projecting coarse mesh solution to obtain initial vector on new fine mesh.");
OGProjection<double>::project_global(ref_space, sln_prev_time, coeff_vec);
}
else {
Hermes::Mixins::Loggable::Static::info("Projecting previous fine mesh solution to obtain initial vector on new fine mesh.");
OGProjection<double>::project_global(ref_space, ref_sln, coeff_vec);
}
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, ref_space);
// Perform Newton's iteration on the reference mesh. If necessary,
// reduce time step to make it converge, but then restore time step
// size to its original value.
Hermes::Mixins::Loggable::Static::info("Performing Newton's iteration (tau = %g days):", time_step);
bool success, verbose = true;
double* save_coeff_vec = new double[ndof];
// Save coefficient vector.
for (int i = 0; i < ndof; i++)
save_coeff_vec[i] = coeff_vec[i];
bc_essential.set_current_time(current_time);
// Perform Newton's iteration.
Hermes::Mixins::Loggable::Static::info("Solving nonlinear problem:");
Hermes::Hermes2D::NewtonSolver<double> newton(&dp);
newton.set_sufficient_improvement_factor(1.1);
bool newton_converged = false;
while (!newton_converged)
{
try
{
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.solve(coeff_vec);
newton_converged = true;
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
newton_converged = false;
};
if (!newton_converged)
{
// Restore solution from the beginning of time step.
for (int i = 0; i < ndof; i++) coeff_vec[i] = save_coeff_vec[i];
// Reducing time step to 50%.
Hermes::Mixins::Loggable::Static::info("Reducing time step size from %g to %g days for the rest of this time step.",
time_step, time_step * time_step_dec);
time_step *= time_step_dec;
// If time_step less than the prescribed minimum, stop.
if (time_step < time_step_min) throw Hermes::Exceptions::Exception("Time step dropped below prescribed minimum value.");
}
}
// Delete the saved coefficient vector.
delete[] save_coeff_vec;
// Translate the resulting coefficient vector
// into the desired reference solution.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
// Cleanup.
delete[] coeff_vec;
}
else {
// Calculate initial condition for Picard on the fine mesh.
if (as == 1 && ts == 1) {
Hermes::Mixins::Loggable::Static::info("Projecting coarse mesh solution to obtain initial vector on new fine mesh.");
OGProjection<double>::project_global(ref_space, sln_prev_time, sln_prev_iter);
}
else {
Hermes::Mixins::Loggable::Static::info("Projecting previous fine mesh solution to obtain initial vector on new fine mesh.");
OGProjection<double>::project_global(ref_space, ref_sln, sln_prev_iter);
}
// Perform Picard iteration on the reference mesh. If necessary,
// reduce time step to make it converge, but then restore time step
// size to its original value.
Hermes::Mixins::Loggable::Static::info("Performing Picard's iteration (tau = %g days):", time_step);
bool verbose = true;
bc_essential.set_current_time(current_time);
PicardSolver<double> picard(wf, ref_space);
picard.set_verbose_output(verbose);
picard.set_max_allowed_iterations(PICARD_MAX_ITER);
picard.set_tolerance(PICARD_TOL, Hermes::Solvers::SolutionChangeRelative);
while (true)
{
try
{
picard.solve(sln_prev_iter);
Solution<double>::vector_to_solution(picard.get_sln_vector(), ref_space, ref_sln);
break;
}
catch (std::exception& e)
{
std::cout << e.what();
// Restore solution from the beginning of time step.
sln_prev_iter->copy(sln_prev_time);
// Reducing time step to 50%.
Hermes::Mixins::Loggable::Static::info("Reducing time step size from %g to %g days for the rest of this time step", time_step, time_step * time_step_inc);
time_step *= time_step_dec;
// If time_step less than the prescribed minimum, stop.
if (time_step < time_step_min) throw Hermes::Exceptions::Exception("Time step dropped below prescribed minimum value.");
}
}
}
/*** ADAPTIVITY ***/
// Project the fine mesh solution on the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error calculation.");
if (space->get_mesh() == NULL) throw Hermes::Exceptions::Exception("it is NULL");
OGProjection<double>::project_global(space, ref_sln, sln);
// Calculate element errors.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
adaptivity.set_space(space);
// Calculate error estimate wrt. fine mesh solution.
errorCalculator.calculate_errors(sln, ref_sln);
err_est_rel = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, space_err_est_rel: %g%%",
Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_est_rel);
// If space_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);
as++;
}
} while (!done);
// Add entries to graphs.
graph_time_err_est.add_values(current_time, err_est_rel);
graph_time_err_est.save("time_error_est.dat");
graph_time_dof.add_values(current_time, Space<double>::get_num_dofs(space));
graph_time_dof.save("time_dof.dat");
graph_time_cpu.add_values(current_time, cpu_time.accumulated());
graph_time_cpu.save("time_cpu.dat");
graph_time_step.add_values(current_time, time_step);
graph_time_step.save("time_step_history.dat");
// Visualize the solution and mesh.
char title[100];
sprintf(title, "Solution, time %g days", current_time);
view.set_title(title);
view.show(sln);
sprintf(title, "Mesh, time %g days", current_time);
ordview.set_title(title);
ordview.show(space);
// Save complete Solution.
char* filename = new char[100];
sprintf(filename, "outputs/tsln_%f.dat", current_time);
// Copy new reference level solution into sln_prev_time
// This starts new time step.
sln_prev_time->copy(ref_sln);
// Updating time step. Note that time_step might have been reduced during adaptivity.
current_time += time_step;
// Increase time step.
if (time_step*time_step_inc < time_step_max) {
Hermes::Mixins::Loggable::Static::info("Increasing time step from %g to %g days.", time_step, time_step * time_step_inc);
time_step *= time_step_inc;
}
}
// Wait for all views to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-adapt/definitions.cpp | .cpp | 24 | 1 | #include "definitions.h" | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-ie-picard/definitions.h | .h | 2,124 | 77 | #include "hermes2d.h"
#include "../constitutive.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
/* Custom non-constant Dirichlet condition */
class CustomEssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
CustomEssentialBCNonConst(std::vector<std::string>(markers))
: EssentialBoundaryCondition<double>(markers)
{
}
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
};
/* Weak forms */
class CustomWeakFormRichardsIEPicard : public WeakForm < double >
{
public:
CustomWeakFormRichardsIEPicard(double time_step, MeshFunctionSharedPtr<double> h_time_prev, ConstitutiveRelations* constitutive);
private:
class CustomJacobian : public MatrixFormVol < double >
{
public:
CustomJacobian(unsigned int i, unsigned int j, double time_step)
: MatrixFormVol<double>(i, j), time_step(time_step) {};
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;
double time_step;
};
class CustomResidual : public VectorFormVol < double >
{
public:
CustomResidual(int i, double time_step)
: VectorFormVol<double>(i), time_step(time_step)
{
}
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 time_step;
};
ConstitutiveRelations* constitutive;
WeakForm<double>* clone() const
{
CustomWeakFormRichardsIEPicard* wf = new CustomWeakFormRichardsIEPicard(*this);
wf->constitutive = this->constitutive;
return wf;
}
}; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-ie-picard/main.cpp | .cpp | 4,673 | 140 | #include "definitions.h"
// This example is similar to basic-ie-newton except it uses the
// Picard's method in each time step.
//
// PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0
// where K(h) = K_S*exp(alpha*h) for h < 0,
// K(h) = K_S for h >= 0,
// C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0,
// C(h) = alpha*(theta_s - theta_r) for h >= 0.
//
// Domain: square (0, 100)^2.
//
// BC: Dirichlet, given by the initial condition.
// IC: Flat in all elements except the top layer, within this
// layer the solution rises linearly to match the Dirichlet condition.
//
// NOTE: The pressure head 'h' is between -1000 and 0. For convenience, we
// increase it by an offset H_OFFSET = 1000. In this way we can start
// from a zero coefficient vector.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_GLOB_REF_NUM = 3;
// Number of initial refinements towards boundary.
const int INIT_REF_NUM_BDY = 5;
// Initial polynomial degree.
const int P_INIT = 2;
// Time step.
double time_step = 5e-4;
// Time interval length.
const double T_FINAL = 0.4;
// Problem parameters.
double K_S = 20.464;
double ALPHA = 0.001;
double THETA_R = 0;
double THETA_S = 0.45;
double M, N, STORATIVITY;
// Constitutive relations.
enum CONSTITUTIVE_RELATIONS {
CONSTITUTIVE_GENUCHTEN, // Van Genuchten.
CONSTITUTIVE_GARDNER // Gardner.
};
// Use van Genuchten's constitutive relations, or Gardner's.
CONSTITUTIVE_RELATIONS constitutive_relations_type = CONSTITUTIVE_GARDNER;
// Picard's method.
// Number of last iterations used.
const int PICARD_NUM_LAST_ITER_USED = 3;
// Parameter for the Anderson acceleration.
const double PICARD_ANDERSON_BETA = 1.0;
// Stopping criterion for the Picard's method.
const double PICARD_TOL = 1e-6;
// Maximum allowed number of Picard iterations.
const int PICARD_MAX_ITER = 100;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", mesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY);
// Initialize boundary conditions.
CustomEssentialBCNonConst bc_essential(std::vector<std::string>({ "Bottom", "Right", "Top", "Left" }));
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Zero initial solutions. This is why we use H_OFFSET.
MeshFunctionSharedPtr<double> h_time_prev(new ConstantSolution<double>(mesh, 0.));
// Initialize views.
ScalarView view("Initial condition", new WinGeom(0, 0, 600, 500));
view.fix_scale_width(80);
// Initialize the constitutive relations.
ConstitutiveRelations* constitutive_relations;
if (constitutive_relations_type == CONSTITUTIVE_GENUCHTEN)
constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY);
else
constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S);
// Initialize the weak formulation.
double current_time = 0;
WeakFormSharedPtr<double> wf(new CustomWeakFormRichardsIEPicard(time_step, h_time_prev, constitutive_relations));
// Initialize the Picard solver.
PicardSolver<double> picard(wf, space);
picard.set_verbose_output(true);
// Time stepping:
int ts = 1;
do
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f s", ts, current_time);
// Perform the Picard's iteration (Anderson acceleration on by default).
picard.set_max_allowed_iterations(PICARD_MAX_ITER);
picard.set_num_last_vector_used(PICARD_NUM_LAST_ITER_USED);
picard.set_anderson_beta(PICARD_ANDERSON_BETA);
try
{
picard.solve();
}
catch (std::exception& e)
{
std::cout << e.what();
}
// Translate the coefficient vector into a Solution.
Solution<double>::vector_to_solution(picard.get_sln_vector(), space, h_time_prev);
// Increase current time and time step counter.
current_time += time_step;
ts++;
// Visualize the solution.
char title[100];
sprintf(title, "Time %g s", current_time);
view.set_title(title);
view.show(h_time_prev);
} while (current_time < T_FINAL);
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-ie-picard/definitions.cpp | .cpp | 3,046 | 89 | #include "definitions.h"
// The pressure head is raised by H_OFFSET
// so that the initial condition can be taken
// as the zero vector. Note: the resulting
// pressure head will also be greater than the
// true one by this offset.
double H_OFFSET = 1e3;
/* Custom non-constant Dirichlet condition */
EssentialBCValueType CustomEssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double CustomEssentialBCNonConst::value(double x, double y) const
{
return x*(100. - x) / 2.5 * y / 100 - 1000. + H_OFFSET;
}
/* Custom weak forms */
CustomWeakFormRichardsIEPicard::CustomWeakFormRichardsIEPicard(double time_step, MeshFunctionSharedPtr<double> h_time_prev, ConstitutiveRelations* constitutive) : WeakForm<double>(1), constitutive(constitutive)
{
// Jacobian.
CustomJacobian* matrix_form = new CustomJacobian(0, 0, time_step);
matrix_form->set_ext(h_time_prev);
add_matrix_form(matrix_form);
// Residual.
CustomResidual* vector_form = new CustomResidual(0, time_step);
vector_form->set_ext(h_time_prev);
add_vector_form(vector_form);
}
double CustomWeakFormRichardsIEPicard::CustomJacobian::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;
Func<double>* h_prev_picard = u_ext[0];
for (int i = 0; i < n; i++)
{
double h_prev_picard_i = h_prev_picard->val[i] - 0.;
result += wt[i] * (static_cast<CustomWeakFormRichardsIEPicard*>(wf)->constitutive->C(h_prev_picard_i) * u->val[i] * v->val[i]
+ static_cast<CustomWeakFormRichardsIEPicard*>(wf)->constitutive->K(h_prev_picard_i) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]) * time_step
- static_cast<CustomWeakFormRichardsIEPicard*>(wf)->constitutive->dKdh(h_prev_picard_i) * u->dy[i] * v->val[i] * time_step
);
}
return result;
}
Ord CustomWeakFormRichardsIEPicard::CustomJacobian::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>* CustomWeakFormRichardsIEPicard::CustomJacobian::clone() const
{
return new CustomJacobian(*this);
}
double CustomWeakFormRichardsIEPicard::CustomResidual::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* h_prev_picard = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++)
{
double h_prev_picard_i = h_prev_picard->val[i] - 0.;
double h_prev_time_i = h_prev_time->val[i] - 0.;
result += wt[i] * static_cast<CustomWeakFormRichardsIEPicard*>(wf)->constitutive->C(h_prev_picard_i) * (h_prev_time_i)* v->val[i];
}
return result;
}
Ord CustomWeakFormRichardsIEPicard::CustomResidual::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
VectorFormVol<double>* CustomWeakFormRichardsIEPicard::CustomResidual::clone() const
{
return new CustomResidual(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-rk/definitions.h | .h | 2,435 | 85 | #include "hermes2d.h"
#include "../constitutive.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
/* Custom non-constant Dirichlet condition */
class RichardsEssentialBC : public EssentialBoundaryCondition < double > {
public:
RichardsEssentialBC(std::string marker, double h_elevation, double pulse_end_time, double h_init, double startup_time) :
EssentialBoundaryCondition<double>(std::vector<std::string>()), h_elevation(h_elevation), pulse_end_time(pulse_end_time), h_init(h_init), startup_time(startup_time)
{
markers.push_back(marker);
}
~RichardsEssentialBC() {}
inline EssentialBCValueType get_value_type() const { return BC_FUNCTION; }
virtual double value(double x, double y) const {
if (current_time < startup_time)
return h_init + current_time / startup_time*(h_elevation - h_init);
else if (current_time > pulse_end_time)
return h_init;
else
return h_elevation;
}
// Member.
double h_elevation;
double pulse_end_time;
double h_init;
double startup_time;
};
/* Weak forms */
class CustomWeakFormRichardsRK : public WeakForm < double >
{
public:
CustomWeakFormRichardsRK(ConstitutiveRelations* constitutive);
private:
class CustomJacobianFormVol : public MatrixFormVol < double >
{
public:
CustomJacobianFormVol(unsigned int i, unsigned int j, ConstitutiveRelations* constitutive)
: MatrixFormVol<double>(i, j), constitutive(constitutive)
{
}
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;
ConstitutiveRelations* constitutive;
};
class CustomResidualFormVol : public VectorFormVol < double >
{
public:
CustomResidualFormVol(int i, ConstitutiveRelations* constitutive)
: VectorFormVol<double>(i), constitutive(constitutive)
{
}
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;
ConstitutiveRelations* constitutive;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-rk/extras.cpp | .cpp | 13,236 | 415 | #include "definitions.h"
using namespace std;
//Debugging matrix printer.
bool printmatrix(double** A, int n, int m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf(" %lf ", A[i][j]);
}
printf(" \n");
}
printf("----------------------------------\n");
return true;
}
//Debugging vector printer.
bool printvector(double* vect, int n) {
for (int i = 0; i < n; i++) {
printf(" %lf ", vect[i]);
}
printf("\n");
printf("----------------------------------\n");
return true;
}
// Creates a table of precalculated constitutive functions.
bool get_constitutive_tables(int method, ConstitutiveRelationsGenuchtenWithLayer* constitutive, int material_count)
{
Hermes::Mixins::Loggable::Static::info("Creating tables of constitutive functions (complicated real exponent relations).");
// Table values dimension.
int bound = int(-constitutive->table_limit / constitutive->table_precision) + 1;
// Allocating arrays.
constitutive->k_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->k_table[i] = new double[bound];
}
constitutive->dKdh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->dKdh_table[i] = new double[bound];
}
constitutive->dKdh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->dKdh_table[i] = new double[bound];
}
constitutive->c_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->c_table[i] = new double[bound];
}
//If Newton method (method==1) selected constitutive function derivations are required.
if (method == 1) {
constitutive->dCdh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->dCdh_table[i] = new double[bound];
}
constitutive->ddKdhh_table = new double*[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->ddKdhh_table[i] = new double[bound];
}
}
// Calculate and save K(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving K(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->k_table[j][i] = constitutive->K(-constitutive->table_precision*i, j);
}
}
// Calculate and save dKdh(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving dKdh(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->dKdh_table[j][i] = constitutive->dKdh(-constitutive->table_precision*i, j);
}
}
// Calculate and save C(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving C(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->c_table[j][i] = constitutive->C(-constitutive->table_precision*i, j);
}
}
//If Newton method (method==1) selected constitutive function derivations are required.
if (method == 1) {
// Calculate and save ddKdhh(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving ddKdhh(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->ddKdhh_table[j][i] = constitutive->ddKdhh(-constitutive->table_precision*i, j);
}
}
// Calculate and save dCdh(h).
Hermes::Mixins::Loggable::Static::info("Calculating and saving dCdh(h).");
for (int j = 0; j < material_count; j++) {
for (int i = 0; i < bound; i++) {
constitutive->dCdh_table[j][i] = constitutive->dCdh(-constitutive->table_precision*i, j);
}
}
}
return true;
}
// Simple Gaussian elimination for full matrices called from init_polynomials().
bool gem_full(double** A, double* b, double* X, int n) {
int i, j, k;
double** aa;
double dotproduct, tmp;
aa = new double*[n];
for (i = 0; i < n; i++) {
aa[i] = new double[n + 1];
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
aa[i][j] = A[i][j];
}
aa[i][n] = b[i];
}
for (j = 0; j < (n - 1); j++) {
for (i = j + 1; i < n; i++) {
tmp = aa[i][j] / aa[j][j];
for (k = 0; k < (n + 1); k++) {
aa[i][k] = aa[i][k] - tmp*aa[j][k];
}
}
}
for (i = n - 1; i > -1; i--) {
dotproduct = 0.0;
for (j = i + 1; j < n; j++) {
dotproduct = dotproduct + aa[i][j] * X[j];
}
X[i] = (aa[i][n] - dotproduct) / aa[i][i];
}
delete[]aa;
return true;
}
// Initialize polynomial approximation of constitutive relations close to full saturation for constitutive->constitutive_table_method=1.
// For constitutive->constitutive_table_method=2 all constitutive functions are approximated by polynomials, K(h) function by quintic spline, C(h)
// function by cubic splines. Discretization is managed by variable int num_of_intervals and double* intervals_4_approx.
// ------------------------------------------------------------------------------
// For constitutive->constitutive_table_method=1 this function requires folowing arguments:
// n - degree of polynomials
// low_limit - start point of the polynomial approximation
// points - array of points inside the interval bounded by <low_limit, 0> to improve the accuracy, at least one is recommended.
// An approriate amount of points related to the polynomial degree should be selected.
// n_inside_point - number of inside points
// layer - material to be considered.
//------------------------------------------------------------------------------
// For constitutive->constitutive_table_method=2, all parameters are obtained from global definitions.
bool init_polynomials(int n, double low_limit, double *points, int n_inside_points, int layer, ConstitutiveRelationsGenuchtenWithLayer* constitutive, int material_count, int num_of_intervals, double* intervals_4_approx)
{
double** Aside;
double* Bside;
double* X;
switch (constitutive->constitutive_table_method)
{
// no approximation
case 0:
break;
// polynomial approximation only for the the K(h) function surroundings close to zero
case 1:
if (constitutive->polynomials_allocated == false) {
constitutive->polynomials = new double**[material_count];
for (int i = 0; i < material_count; i++) {
constitutive->polynomials[i] = new double*[3];
}
for (int i = 0; i < material_count; i++) {
for (int j = 0; j < 3; j++) {
constitutive->polynomials[i][j] = new double[n_inside_points + 6];
}
}
constitutive->polynomials_allocated = true;
}
Aside = new double*[n + n_inside_points];
Bside = new double[n + n_inside_points];
for (int i = 0; i < n; i++) {
Aside[i] = new double[n + n_inside_points];
}
// Evaluate the first three rows of the matrix (zero, first and second derivative at point low_limit).
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Aside[i][j] = 0.0;
}
}
for (int i = 0; i < n; i++) {
Aside[3][i] = pow(low_limit, i);
Aside[4][i] = i*pow(low_limit, i - 1);
Aside[5][i] = i*(i - 1)*pow(low_limit, i - 2);
}
Bside[3] = constitutive->K(low_limit, layer);
Bside[4] = constitutive->dKdh(low_limit, layer);
Bside[5] = constitutive->ddKdhh(low_limit, layer);
// Evaluate the second three rows of the matrix (zero, first and second derivative at point zero).
Aside[0][0] = 1.0;
// For the both first and second derivative it does not really matter what value is placed there.
Aside[1][1] = 1.0;
Aside[2][2] = 2.0;
Bside[0] = constitutive->K(0.0, layer);
Bside[1] = 0.0;
Bside[2] = 0.0;
for (int i = 6; i < (6 + n_inside_points); i++) {
for (int j = 0; j < n; j++) {
Aside[i][j] = pow(points[i - 6], j);
}
printf("poradi, %i %lf %lf \n", i, constitutive->K(points[i - 6], layer), points[i - 6]);
Bside[i] = constitutive->K(points[i - 6], layer);
printf("layer, %i \n", layer);
}
gem_full(Aside, Bside, constitutive->polynomials[layer][0], (n_inside_points + 6));
for (int i = 1; i < 3; i++) {
for (int j = 0; j < (n_inside_points + 5); j++) {
constitutive->polynomials[layer][i][j] = (j + 1)*constitutive->polynomials[layer][i - 1][j + 1];
}
constitutive->polynomials[layer][i][n_inside_points + 6 - i] = 0.0;
}
delete[] Aside;
delete[] Bside;
break;
// polynomial approximation for all functions at interval (table_limit, 0)
case 2:
int pts = 0;
if (constitutive->polynomials_allocated == false) {
// K(h) function is approximated by quintic spline.
constitutive->k_pols = new double***[num_of_intervals];
//C(h) function is approximated by cubic spline.
constitutive->c_pols = new double***[num_of_intervals];
for (int i = 0; i < num_of_intervals; i++) {
constitutive->k_pols[i] = new double**[material_count];
constitutive->c_pols[i] = new double**[material_count];
for (int j = 0; j < material_count; j++) {
constitutive->k_pols[i][j] = new double*[3];
constitutive->c_pols[i][j] = new double*[2];
for (int k = 0; k < 3; k++) {
constitutive->k_pols[i][j][k] = new double[6 + pts];
if (k < 2)
constitutive->c_pols[i][j][k] = new double[5];
}
}
}
// //allocate constitutive->pol_search_help array -- an index array with locations for particular pressure head functions
constitutive->pol_search_help = new int[int(-constitutive->table_limit) + 1];
for (int i = 0; i <= int(-constitutive->table_limit); i++) {
for (int j = 0; j < num_of_intervals; j++) {
if (j < 1) {
if (-i > intervals_4_approx[j]) {
constitutive->pol_search_help[i] = j;
break;
}
}
else {
if (-i >= intervals_4_approx[j] && -i <= intervals_4_approx[j - 1]) {
constitutive->pol_search_help[i] = j;
break;
}
}
}
}
constitutive->polynomials_allocated = true;
}
//create matrix
Aside = new double*[6 + pts];
for (int i = 0; i < (6 + pts); i++) {
Aside[i] = new double[6 + pts];
}
Bside = new double[6 + pts];
for (int i = 0; i < num_of_intervals; i++) {
if (i < 1) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < (6 + pts); k++) {
Aside[j][k] = 0.0;
}
}
// Evaluate the second three rows of the matrix (zero, first and second derivative at point zero).
Aside[0][0] = 1.0;
// For the both first and second derivative it does not really matter what value is placed there.
Aside[1][1] = 1.0;
Aside[2][2] = 2.0;
}
else {
for (int j = 0; j < (6 + pts); j++) {
Aside[0][j] = pow(intervals_4_approx[i - 1], j);
Aside[1][j] = j*pow(intervals_4_approx[i - 1], j - 1);
Aside[2][j] = j*(j - 1)*pow(intervals_4_approx[i - 1], j - 2);
}
}
for (int j = 0; j < (6 + pts); j++) {
Aside[3][j] = pow(intervals_4_approx[i], j);
Aside[4][j] = j*pow(intervals_4_approx[i], j - 1);
Aside[5][j] = j*(j - 1)*pow(intervals_4_approx[i], j - 2);
switch (pts) {
case 0:
break;
case 1:
if (i > 0) {
Aside[6][j] = pow((intervals_4_approx[i] + intervals_4_approx[i - 1]) / 2, j);
}
else {
Aside[6][j] = pow((intervals_4_approx[i]) / 2, j);
}
break;
default:
printf("too many of inside points in polynomial approximation; not implemented!!! (check extras.cpp) \n");
exit(1);
}
}
//Evaluate K(h) function.
if (i < 1) {
Bside[0] = constitutive->K(0.0, layer);
Bside[1] = 0.0;
Bside[2] = 0.0;
}
else {
Bside[0] = constitutive->K(intervals_4_approx[i - 1], layer);
Bside[1] = constitutive->dKdh(intervals_4_approx[i - 1], layer);
Bside[2] = constitutive->ddKdhh(intervals_4_approx[i - 1], layer);
}
Bside[3] = constitutive->K(intervals_4_approx[i], layer);
Bside[4] = constitutive->dKdh(intervals_4_approx[i], layer);
Bside[5] = constitutive->ddKdhh(intervals_4_approx[i], layer);
switch (pts) {
case 0:
break;
case 1:
if (i > 0) {
Bside[6] = constitutive->K((intervals_4_approx[i] + intervals_4_approx[i - 1]) / 2, layer);
}
else {
Bside[6] = constitutive->K((intervals_4_approx[i]) / 2, layer);
}
break;
}
gem_full(Aside, Bside, constitutive->k_pols[i][layer][0], (6 + pts));
for (int j = 1; j < 3; j++) {
for (int k = 0; k < 5; k++) {
constitutive->k_pols[i][layer][j][k] = (k + 1)*constitutive->k_pols[i][layer][j - 1][k + 1];
}
constitutive->k_pols[i][layer][j][6 - j] = 0.0;
}
//Evaluate C(h) functions.
if (i < 1) {
Bside[0] = constitutive->C(0.0, layer);
Bside[1] = constitutive->dCdh(0.0, layer);
}
else {
Bside[0] = constitutive->C(intervals_4_approx[i - 1], layer);
Bside[1] = constitutive->dCdh(intervals_4_approx[i - 1], layer);
}
//The first two lines of the matrix Aside stays the same.
for (int j = 0; j < 4; j++) {
Aside[2][j] = pow(intervals_4_approx[i], j);
Aside[3][j] = j*pow(intervals_4_approx[i], j - 1);
}
Bside[2] = constitutive->C(intervals_4_approx[i], layer);
Bside[3] = constitutive->dCdh(intervals_4_approx[i], layer);
gem_full(Aside, Bside, constitutive->c_pols[i][layer][0], 4);
for (int k = 0; k < 5; k++) {
constitutive->c_pols[i][layer][1][k] = (k + 1)*constitutive->c_pols[i][layer][0][k + 1];
}
constitutive->c_pols[i][layer][1][5] = 0.0;
}
delete[] Aside;
delete[] Bside;
break;
}
return true;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-rk/main.cpp | .cpp | 13,560 | 326 | #include "definitions.h"
// This example solves the time-dependent Richard's equation using
// adaptive time integration (no dynamical meshes in space yet).
// Many different time stepping methods can be used. The nonlinear
// solver in each time step is the Newton's method.
//
// PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0
// where K(h) = K_S*exp(alpha*h) for h < 0,
// K(h) = K_S for h >= 0,
// C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0,
// C(h) = alpha*(theta_s - theta_r) for h >= 0.
//
// Domain: rectangle (0, 8) x (0, 6.5).
// Units: length: cm
// time: days
//
// BC: Dirichlet, given by the initial condition.
//
// The following parameters can be changed:
// Choose full domain or half domain.
//const char* mesh_file = "domain-full.mesh";
const char* mesh_file = "domain-half.mesh";
// Adaptive time stepping.
// Time step (in days).
double time_step = .001;
// If rel. temporal error is greater than this threshold, decrease time
// step size and repeat time step.
const double time_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_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;
// Elements orders and initial refinements.
// Initial polynomial degree of mesh elements.
const int P_INIT = 2;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 2;
// Number of initial mesh refinements towards the top edge.
const int INIT_REF_NUM_BDY_TOP = 1;
// 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;
// Newton's method.
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-6;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 10;
const double DAMPING_COEFF = 1.;
// Times.
// Start-up time for time-dependent Dirichlet boundary condition.
const double STARTUP_TIME = 5.0;
// Time interval length.
const double T_FINAL = 1000.0;
// Time interval of the top layer infiltration.
const double PULSE_END_TIME = 1000.0;
// Global time variable.
double current_time = 0;
// Problem parameters.
// Initial pressure head.
double H_INIT = -15.0;
// Top constant pressure head -- an infiltration experiment.
double H_ELEVATION = 10.0;
double K_S_vals[4] = { 350.2, 712.8, 1.68, 18.64 };
double ALPHA_vals[4] = { 0.01, 1.0, 0.01, 0.01 };
double N_vals[4] = { 2.5, 2.0, 1.23, 2.5 };
double M_vals[4] = { 0.864, 0.626, 0.187, 0.864 };
double THETA_R_vals[4] = { 0.064, 0.0, 0.089, 0.064 };
double THETA_S_vals[4] = { 0.14, 0.43, 0.43, 0.24 };
double STORATIVITY_vals[4] = { 0.1, 0.1, 0.1, 0.1 };
// Precalculation of constitutive tables.
const int MATERIAL_COUNT = 4;
// 0 - constitutive functions are evaluated directly (slow performance).
// 1 - constitutive functions are linearly approximated on interval
// <TABLE_LIMIT; LOW_LIMIT> (very efficient CPU utilization less
// efficient memory consumption (depending on TABLE_PRECISION)).
// 2 - constitutive functions are aproximated by quintic splines.
const int CONSTITUTIVE_TABLE_METHOD = 2;
/* Use only if CONSTITUTIVE_TABLE_METHOD == 2 */
// Number of intervals.
const int NUM_OF_INTERVALS = 16;
// Low limits of intervals approximated by quintic splines.
double INTERVALS_4_APPROX[16] =
{ -1.0, -2.0, -3.0, -4.0, -5.0, -8.0, -10.0, -12.0,
-15.0, -20.0, -30.0, -50.0, -75.0, -100.0, -300.0, -1000.0 };
// This array contains for each integer of h function appropriate polynomial ID.
// First DIM is the interval ID, second DIM is the material ID,
// third DIM is the derivative degree, fourth DIM are the coefficients.
/* END OF Use only if CONSTITUTIVE_TABLE_METHOD == 2 */
/* Use only if CONSTITUTIVE_TABLE_METHOD == 1 */
// Limit of precalculated functions (should be always negative value lower
// then the lowest expect value of the solution (consider DMP!!)
double TABLE_LIMIT = -1000.0;
// Precision of precalculated table use 1.0, 0,1, 0.01, etc.....
const double TABLE_PRECISION = 0.1;
bool CONSTITUTIVE_TABLES_READY = false;
// Polynomial approximation of the K(h) function close to saturation.
// This function has singularity in its second derivative.
// First dimension is material ID
// Second dimension is the polynomial derivative.
// Third dimension are the polynomial's coefficients.
double*** POLYNOMIALS;
// Lower bound of K(h) function approximated by polynomials.
const double LOW_LIMIT = -1.0;
const int NUM_OF_INSIDE_PTS = 0;
/* END OF Use only if CONSTITUTIVE_TABLE_METHOD == 1 */
bool POLYNOMIALS_READY = false;
bool POLYNOMIALS_ALLOCATED = false;
// Global variables for forms.
double K_S, ALPHA, THETA_R, THETA_S, N, M, STORATIVITY;
Hermes::Hermes2D::Mesh* mesh_internal;
// Main function.
int main(int argc, char* argv[])
{
ConstitutiveRelationsGenuchtenWithLayer constitutive_relations(CONSTITUTIVE_TABLE_METHOD, NUM_OF_INSIDE_PTS, LOW_LIMIT, TABLE_PRECISION, TABLE_LIMIT, K_S_vals, ALPHA_vals, N_vals, M_vals, THETA_R_vals, THETA_S_vals, STORATIVITY_vals);
// Either use exact constitutive relations (slow) (method 0) or precalculate
// their linear approximations (faster) (method 1) or
// precalculate their quintic polynomial approximations (method 2) -- managed by
// the following loop "Initializing polynomial approximation".
if (CONSTITUTIVE_TABLE_METHOD == 1)
constitutive_relations.constitutive_tables_ready = get_constitutive_tables(1, &constitutive_relations, MATERIAL_COUNT); // 1 stands for the Newton's method.
// The van Genuchten + Mualem K(h) function is approximated by polynomials close
// to zero in case of CONSTITUTIVE_TABLE_METHOD==1.
// In case of CONSTITUTIVE_TABLE_METHOD==2, all constitutive functions are approximated by polynomials.
Hermes::Mixins::Loggable::Static::info("Initializing polynomial approximations.");
for (int i = 0; i < MATERIAL_COUNT; i++)
{
// Points to be used for polynomial approximation of K(h).
double* points = new double[NUM_OF_INSIDE_PTS];
init_polynomials(6 + NUM_OF_INSIDE_PTS, LOW_LIMIT, points, NUM_OF_INSIDE_PTS, i, &constitutive_relations, MATERIAL_COUNT, NUM_OF_INTERVALS, INTERVALS_4_APPROX);
}
constitutive_relations.polynomials_ready = true;
if (CONSTITUTIVE_TABLE_METHOD == 2)
{
constitutive_relations.constitutive_tables_ready = true;
//Assign table limit to global definition.
constitutive_relations.table_limit = INTERVALS_4_APPROX[NUM_OF_INTERVALS - 1];
}
// 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), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load(mesh_file, basemesh);
mesh_internal = mesh.get();
// Perform initial mesh refinements.
mesh->copy(basemesh);
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY_TOP);
// Initialize boundary conditions.
RichardsEssentialBC bc_essential("Top", H_ELEVATION, PULSE_END_TIME, H_INIT, STARTUP_TIME);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Convert initial condition into a Solution.
MeshFunctionSharedPtr<double> h_time_prev(new ZeroSolution<double>(mesh)), h_time_new(new ZeroSolution<double>(mesh)), time_error_fn(new ZeroSolution<double>(mesh));
// Initialize views.
ScalarView view("Initial condition", new WinGeom(0, 0, 600, 500));
view.fix_scale_width(80);
// Visualize the initial condition.
view.show(h_time_prev);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormRichardsRK(&constitutive_relations));
// Visualize the projection and mesh.
ScalarView sview("Initial condition", new WinGeom(0, 0, 400, 350));
sview.fix_scale_width(50);
sview.show(h_time_prev);
ScalarView eview("Temporal error", new WinGeom(405, 0, 400, 350));
eview.fix_scale_width(50);
eview.show(time_error_fn);
OrderView oview("Initial mesh", new WinGeom(810, 0, 350, 350));
oview.show(space);
// Graph for time step history.
SimpleGraph time_step_graph;
Hermes::Mixins::Loggable::Static::info("Time step history will be saved to file time_step_history.dat.");
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, space, &bt);
runge_kutta.set_verbose_output(true);
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.set_newton_damping_coeff(DAMPING_COEFF);
// Time stepping:
int ts = 1;
do
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f s", ts, current_time);
Space<double>::update_essential_bc_values(space, current_time);
// 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_step(time_step);
runge_kutta.set_time(current_time);
runge_kutta.rk_time_step_newton(h_time_prev, h_time_new, time_error_fn);
}
catch (Exceptions::Exception& e)
{
Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step failed, decreasing time step size from %g to %g days.",
time_step, time_step * time_step_dec);
time_step *= time_step_dec;
if (time_step < time_step_min)
throw Hermes::Exceptions::Exception("Time step became too small.");
continue;
}
// Copy solution for the new time step.
h_time_prev->copy(h_time_new);
// Show error function.
char title[100];
sprintf(title, "Temporal error, t = %g", current_time);
eview.set_title(title);
eview.show(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(1);
normCalculator.calculate_norm(time_error_fn);
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;
}
// Add entry to the timestep graph.
time_step_graph.add_values(current_time, time_step);
time_step_graph.save("time_step_history.dat");
// Update time.
current_time += time_step;
// Show the new time level solution.
sprintf(title, "Solution, t = %g", current_time);
sview.set_title(title);
sview.show(h_time_new);
oview.show(space);
// Save complete Solution.
char filename[100];
sprintf(filename, "outputs/tsln_%f.dat", current_time);
// Save solution for the next time step.
h_time_prev->copy(h_time_new);
// Increase time step counter.
ts++;
} while (current_time < T_FINAL);
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/capillary-barrier-rk/definitions.cpp | .cpp | 3,767 | 118 | #include "definitions.h"
// The pressure head is raised by H_OFFSET
// so that the initial condition can be taken
// as the zero vector. Note: the resulting
// pressure head will also be greater than the
// true one by this offset.
double H_OFFSET = 1000;
/* Custom weak forms */
CustomWeakFormRichardsRK::CustomWeakFormRichardsRK(ConstitutiveRelations* constitutive) : WeakForm<double>(1)
{
// Jacobian volumetric part.
CustomJacobianFormVol* jac_form_vol = new CustomJacobianFormVol(0, 0, constitutive);
add_matrix_form(jac_form_vol);
// Residual - volumetric.
CustomResidualFormVol* res_form_vol = new CustomResidualFormVol(0, constitutive);
add_vector_form(res_form_vol);
}
double CustomWeakFormRichardsRK::CustomJacobianFormVol::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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
if (std::abs(h_val_i + 1000.) < 1e-7)
{
result += -9.8877216176350985e-05;
continue;
}
double C = constitutive->C(h_val_i);
double K = constitutive->K(h_val_i);
double dCdh = constitutive->dCdh(h_val_i);
double dKdh = constitutive->dKdh(h_val_i);
double ddCdhh = constitutive->ddCdhh(h_val_i);
double ddKdhh = constitutive->ddKdhh(h_val_i);
double C2 = C * C;
double a1_1 = (dKdh * C - dCdh * K) / C2;
double a1_2 = K / C;
double a2_1 = ((dKdh * dCdh + K * ddCdhh) * C2
- 2 * K * C * dCdh * dCdh) / (C2 * C2);
double a2_2 = 2 * K * dCdh / C2;
double a3_1 = (ddKdhh * C - dKdh * dCdh) / C2;
double a3_2 = dKdh / C;
result += wt[i] * (-a1_1 * u->val[i] * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- a1_2 * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ a2_1 * u->val[i] * v->val[i] * (h_prev_newton->dx[i] * h_prev_newton->dx[i]
+ h_prev_newton->dy[i] * h_prev_newton->dy[i])
+ a2_2 * v->val[i] * (u->dx[i] * h_prev_newton->dx[i]
+ u->dy[i] * h_prev_newton->dy[i])
+ a3_1 * u->val[i] * v->val[i] * h_prev_newton->dy[i]
+ a3_2 * v->val[i] * u->dy[i]
);
}
return result;
}
Ord CustomWeakFormRichardsRK::CustomJacobianFormVol::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>* CustomWeakFormRichardsRK::CustomJacobianFormVol::clone() const
{
CustomJacobianFormVol* toReturn = new CustomJacobianFormVol(*this);
return toReturn;
}
double CustomWeakFormRichardsRK::CustomResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
if (std::abs(h_val_i + 1000.) < 1e-7)
continue;
double C = constitutive->C(h_val_i);
double K = constitutive->K(h_val_i);
double dCdh = constitutive->dCdh(h_val_i);
double dKdh = constitutive->dKdh(h_val_i);
double r1 = (K / C);
double r2 = K * dCdh / (C * C);
double r3 = dKdh / C;
result += wt[i] * (-r1 * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
+ r2 * v->val[i] * (h_prev_newton->dx[i] * h_prev_newton->dx[i]
+ h_prev_newton->dy[i] * h_prev_newton->dy[i])
+ r3 * v->val[i] * h_prev_newton->dy[i]
);
}
return result;
}
Ord CustomWeakFormRichardsRK::CustomResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
VectorFormVol<double>* CustomWeakFormRichardsRK::CustomResidualFormVol::clone() const
{
return new CustomResidualFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-rk-newton/definitions.h | .h | 2,161 | 78 | #include "hermes2d.h"
#include "../constitutive.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
/* Custom non-constant Dirichlet condition */
class CustomEssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
CustomEssentialBCNonConst(std::vector<std::string>(markers))
: EssentialBoundaryCondition<double>(markers)
{
}
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
};
/* Weak forms */
class CustomWeakFormRichardsRK : public WeakForm < double >
{
public:
CustomWeakFormRichardsRK(ConstitutiveRelations* constitutive);
private:
class CustomJacobianFormVol : public MatrixFormVol < double >
{
public:
CustomJacobianFormVol(unsigned int i, unsigned int j, ConstitutiveRelations* constitutive)
: MatrixFormVol<double>(i, j), constitutive(constitutive)
{
}
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;
ConstitutiveRelations* constitutive;
};
class CustomResidualFormVol : public VectorFormVol < double >
{
public:
CustomResidualFormVol(int i, ConstitutiveRelations* constitutive)
: VectorFormVol<double>(i), constitutive(constitutive)
{
}
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;
ConstitutiveRelations* constitutive;
};
ConstitutiveRelations* constitutive;
WeakForm<double>* clone() const
{
CustomWeakFormRichardsRK* wf = new CustomWeakFormRichardsRK(*this);
wf->constitutive = this->constitutive;
return wf;
}
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-rk-newton/main.cpp | .cpp | 6,649 | 169 | #include "definitions.h"
// This example solves the Tracy problem with arbitrary Runge-Kutta
// methods in time.
//
// PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0
// where K(h) = K_S*exp(alpha*h) for h < 0,
// K(h) = K_S for h >= 0,
// C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0,
// C(h) = alpha*(theta_s - theta_r) for h >= 0.
//
// Domain: square (0, 100)^2.
//
// BC: Dirichlet, given by the initial condition.
// IC: Flat in all elements except the top layer, within this
// layer the solution rises linearly to match the Dirichlet condition.
//
// NOTE: The pressure head 'h' is between -1000 and 0. For convenience, we
// increase it by an offset H_OFFSET = 1000. In this way we can start
// from a zero coefficient vector.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_GLOB_REF_NUM = 3;
// Number of initial refinements towards boundary.
const int INIT_REF_NUM_BDY = 5;
// Initial polynomial degree.
const int P_INIT = 2;
// Time step.
double time_step = 5e-5;
// Time interval length.
const double T_FINAL = 0.4;
// Problem parameters.
double K_S = 20.464;
double ALPHA = 0.001;
double THETA_R = 0;
double THETA_S = 0.45;
double M, N, STORATIVITY;
// Constitutive relations.
enum CONSTITUTIVE_RELATIONS {
CONSTITUTIVE_GENUCHTEN, // Van Genuchten.
CONSTITUTIVE_GARDNER // Gardner.
};
// Use van Genuchten's constitutive relations, or Gardner's.
CONSTITUTIVE_RELATIONS constitutive_relations_type = CONSTITUTIVE_GARDNER;
// Newton's method.
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-6;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 500;
const double DAMPING_COEFF = .5;
// 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_Crank_Nicolson_2_2;
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_GLOB_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY);
// Initialize boundary conditions.
CustomEssentialBCNonConst bc_essential(std::vector<std::string>({ "Bottom", "Right", "Top", "Left" }));
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Zero initial solutions. This is why we use H_OFFSET.
MeshFunctionSharedPtr<double> h_time_prev(new ZeroSolution<double>(mesh)), h_time_new(new ZeroSolution<double>(mesh));
// Initialize views.
ScalarView view("Initial condition", new WinGeom(0, 0, 600, 500));
view.fix_scale_width(80);
// Visualize the initial condition.
view.show(h_time_prev);
// Initialize the constitutive relations.
ConstitutiveRelations* constitutive_relations;
if (constitutive_relations_type == CONSTITUTIVE_GENUCHTEN)
constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY);
else
constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormRichardsRK(constitutive_relations));
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, space, &bt);
runge_kutta.set_verbose_output(true);
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.set_newton_damping_coeff(DAMPING_COEFF);
// Time stepping:
double current_time = 0;
int ts = 1;
do
{
Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f s", ts, current_time);
// 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.rk_time_step_newton(h_time_prev, h_time_new);
}
catch (Exceptions::Exception& e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
}
// Copy solution for the new time step.
h_time_prev->copy(h_time_new);
// Increase current time.
current_time += time_step;
// Visualize the solution.
char title[100];
sprintf(title, "Time %3.2f s", current_time);
view.set_title(title);
view.show(h_time_prev);
// Increase time step counter.
ts++;
} while (current_time < T_FINAL);
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-rk-newton/definitions.cpp | .cpp | 4,329 | 108 | #include "definitions.h"
// The pressure head is raised by H_OFFSET
// so that the initial condition can be taken
// as the zero vector. Note: the resulting
// pressure head will also be greater than the
// true one by this offset.
double H_OFFSET = 1000;
/* Custom non-constant Dirichlet condition */
EssentialBCValueType CustomEssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double CustomEssentialBCNonConst::value(double x, double y) const
{
return x*(100. - x) / 2.5 * y / 100 - 1000. + H_OFFSET;
}
/* Custom weak forms */
CustomWeakFormRichardsRK::CustomWeakFormRichardsRK(ConstitutiveRelations* constitutive) : WeakForm<double>(1), constitutive(constitutive)
{
// Jacobian volumetric part.
CustomJacobianFormVol* jac_form_vol = new CustomJacobianFormVol(0, 0, constitutive);
add_matrix_form(jac_form_vol);
// Residual - volumetric.
CustomResidualFormVol* res_form_vol = new CustomResidualFormVol(0, constitutive);
add_vector_form(res_form_vol);
}
double CustomWeakFormRichardsRK::CustomJacobianFormVol::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;
Func<double>* h_prev_newton = u_ext[this->previous_iteration_space_index];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
double C2 = constitutive->C(h_val_i) * constitutive->C(h_val_i);
double a1_1 = (constitutive->dKdh(h_val_i) * constitutive->C(h_val_i) - constitutive->dCdh(h_val_i) * constitutive->K(h_val_i)) / C2;
double a1_2 = constitutive->K(h_val_i) / constitutive->C(h_val_i);
double a2_1 = ((constitutive->dKdh(h_val_i) * constitutive->dCdh(h_val_i) + constitutive->K(h_val_i) * constitutive->ddCdhh(h_val_i)) * C2
- 2 * constitutive->K(h_val_i) * constitutive->C(h_val_i) * constitutive->dCdh(h_val_i) * constitutive->dCdh(h_val_i)) / (C2 * C2);
double a2_2 = 2 * constitutive->K(h_val_i) * constitutive->dCdh(h_val_i) / C2;
double a3_1 = (constitutive->ddKdhh(h_val_i) * constitutive->C(h_val_i) - constitutive->dKdh(h_val_i) * constitutive->dCdh(h_val_i)) / C2;
double a3_2 = constitutive->dKdh(h_val_i) / constitutive->C(h_val_i);
result += wt[i] * (-a1_1 * u->val[i] * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- a1_2 * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ a2_1 * u->val[i] * v->val[i] * (h_prev_newton->dx[i] * h_prev_newton->dx[i]
+ h_prev_newton->dy[i] * h_prev_newton->dy[i])
+ a2_2 * v->val[i] * (u->dx[i] * h_prev_newton->dx[i]
+ u->dy[i] * h_prev_newton->dy[i])
+ a3_1 * u->val[i] * v->val[i] * h_prev_newton->dy[i]
+ a3_2 * v->val[i] * u->dy[i]
);
}
return result;
}
Ord CustomWeakFormRichardsRK::CustomJacobianFormVol::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>* CustomWeakFormRichardsRK::CustomJacobianFormVol::clone() const
{
return new CustomJacobianFormVol(*this);
}
double CustomWeakFormRichardsRK::CustomResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* h_prev_newton = u_ext[this->previous_iteration_space_index];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
double r1 = (constitutive->K(h_val_i) / constitutive->C(h_val_i));
double r2 = constitutive->K(h_val_i) * constitutive->dCdh(h_val_i) / (constitutive->C(h_val_i) * constitutive->C(h_val_i));
double r3 = constitutive->dKdh(h_val_i) / constitutive->C(h_val_i);
result += wt[i] * (-r1 * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
+ r2 * v->val[i] * (h_prev_newton->dx[i] * h_prev_newton->dx[i]
+ h_prev_newton->dy[i] * h_prev_newton->dy[i])
+ r3 * v->val[i] * h_prev_newton->dy[i]
);
}
return result;
}
Ord CustomWeakFormRichardsRK::CustomResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
VectorFormVol<double>* CustomWeakFormRichardsRK::CustomResidualFormVol::clone() const
{
return new CustomResidualFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-rk-newton-adapt/definitions.h | .h | 2,215 | 78 | #include "hermes2d.h"
#include "../constitutive.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::WeakFormsH1;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Custom non-constant Dirichlet condition */
class CustomEssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
CustomEssentialBCNonConst(std::vector<std::string>(markers))
: EssentialBoundaryCondition<double>(markers)
{
}
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
};
/* Weak forms */
class CustomWeakFormRichardsRK : public WeakForm < double >
{
public:
CustomWeakFormRichardsRK(ConstitutiveRelations* constitutive);
private:
class CustomJacobianFormVol : public MatrixFormVol < double >
{
public:
CustomJacobianFormVol(unsigned int i, unsigned int j, ConstitutiveRelations* constitutive)
: MatrixFormVol<double>(i, j), constitutive(constitutive)
{
}
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;
ConstitutiveRelations* constitutive;
};
class CustomResidualFormVol : public VectorFormVol < double >
{
public:
CustomResidualFormVol(int i, ConstitutiveRelations* constitutive)
: VectorFormVol<double>(i), constitutive(constitutive)
{
}
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;
ConstitutiveRelations* constitutive;
};
ConstitutiveRelations* constitutive;
WeakForm<double>* clone() const
{
CustomWeakFormRichardsRK* wf = new CustomWeakFormRichardsRK(*this);
wf->constitutive = this->constitutive;
return wf;
}
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-rk-newton-adapt/plot_graph.py | .py | 666 | 32 | # import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
pylab.title("Number of DOF as a function of physical time")
pylab.xlabel("Physical time")
pylab.ylabel("Number of DOF")
axis('equal')
data = numpy.loadtxt("conv_dof_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="hp-FEM")
legend()
# initialize new window
pylab.figure()
# plot CPU convergence graph
pylab.title("CPU time as a function of physical time")
pylab.xlabel("Physical time")
pylab.ylabel("CPU time")
axis('equal')
data = numpy.loadtxt("conv_cpu_est.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, '-s', label="hp-FEM")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-advanced/richards/basic-rk-newton-adapt/main.cpp | .cpp | 11,162 | 277 | #include "definitions.h"
// This example uses adaptivity with dynamical meshes to solve
// the Tracy problem with arbitrary Runge-Kutta methods in time.
//
// PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0
// where K(h) = K_S*exp(alpha*h) for h < 0,
// K(h) = K_S for h >= 0,
// C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0,
// C(h) = alpha*(theta_s - theta_r) for h >= 0.
//
// Domain: square (0, 100)^2.
//
// BC: Dirichlet, given by the initial condition.
// IC: Flat in all elements except the top layer, within this
// layer the solution rises linearly to match the Dirichlet condition.
//
// NOTE: The pressure head 'h' is between -1000 and 0. For convenience, we
// increase it by an offset H_OFFSET = 1000. In this way we can start
// from a zero coefficient vector.
//
// The following parameters can be changed:
// Number of initial uniform mesh refinements.
const int INIT_GLOB_REF_NUM = 1;
// Number of initial refinements towards boundary.
const int INIT_REF_NUM_BDY = 6;
// Initial polynomial degree.
const int P_INIT = 2;
// Time step.
double time_step = 5e-5;
// Time interval length.
const double T_FINAL = 0.4;
// This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies.
const double THRESHOLD = 0.5;
// 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.
double K_S = 20.464;
double ALPHA = 0.001;
double THETA_R = 0;
double THETA_S = 0.45;
double M, N, STORATIVITY;
// Constitutive relations.
enum CONSTITUTIVE_RELATIONS {
CONSTITUTIVE_GENUCHTEN, // Van Genuchten.
CONSTITUTIVE_GARDNER // Gardner.
};
// Use van Genuchten's constitutive relations, or Gardner's.
CONSTITUTIVE_RELATIONS constitutive_relations_type = CONSTITUTIVE_GARDNER;
// Adaptivity
// Every UNREF_FREQth 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.
// and just one polynomial degree subtracted.
const int UNREF_METHOD = 3;
// Newton's method.
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-6;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 500;
const double DAMPING_COEFF = .9;
// 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;
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), basemesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("square.mesh", basemesh);
mesh->copy(basemesh);
// Initial mesh refinements.
for (int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY);
// Initialize boundary conditions.
CustomEssentialBCNonConst bc_essential({ "Bottom", "Right", "Top", "Left" });
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof_coarse = Space<double>::get_num_dofs(space);
adaptivity.set_space(space);
Hermes::Mixins::Loggable::Static::info("ndof_coarse = %d.", ndof_coarse);
// Zero initial solution. This is why we use H_OFFSET.
MeshFunctionSharedPtr<double> h_time_prev(new ZeroSolution<double>(mesh)), h_time_new(new ZeroSolution<double>(mesh));
// Initialize the constitutive relations.
ConstitutiveRelations* constitutive_relations;
if (constitutive_relations_type == CONSTITUTIVE_GENUCHTEN)
constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY);
else
constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormRichardsRK(constitutive_relations));
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, space, &bt);
runge_kutta.set_verbose_output(true);
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.set_newton_damping_coeff(DAMPING_COEFF);
// Create a refinement selector.
H1ProjBasedSelector<double> selector(CAND_LIST);
// Visualize initial condition.
char title[100];
ScalarView view("Initial condition", new WinGeom(0, 0, 440, 350));
OrderView ordview("Initial mesh", new WinGeom(445, 0, 440, 350));
view.show(h_time_prev);
ordview.show(space);
// DOF and CPU convergence graphs initialization.
SimpleGraph graph_dof, graph_cpu;
// Time measurement.
Hermes::Mixins::TimeMeasurable cpu_time;
cpu_time.tick();
// Time stepping loop.
double current_time = 0; int ts = 1;
do
{
// 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: mesh->unrefine_all_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.");
}
space->assign_dofs();
ndof_coarse = Space<double>::get_num_dofs(space);
}
// Spatial adaptivity loop. Note: h_time_prev must not be changed
// during spatial adaptivity.
bool done = false; int as = 1;
double err_est;
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 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 = Space<double>::get_num_dofs(ref_space);
// Time measurement.
cpu_time.tick();
// 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_space(ref_space);
runge_kutta.set_time(current_time);
runge_kutta.rk_time_step_newton(h_time_prev, h_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 mesh.
MeshFunctionSharedPtr<double> sln_coarse(new Solution<double>);
Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation.");
OGProjection<double>::project_global(space, h_time_new, sln_coarse);
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
errorCalculator.calculate_errors(sln_coarse, h_time_new, true);
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;
// Report results.
Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_ref: %d, err_est_rel: %g%%",
Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_est_rel_total);
// Time measurement.
cpu_time.tick();
// If err_est too large, adapt the mesh.
if (err_est_rel_total < 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);
// Add entry to DOF and CPU convergence graphs.
graph_dof.add_values(current_time, Space<double>::get_num_dofs(space));
graph_dof.save("conv_dof_est.dat");
graph_cpu.add_values(current_time, cpu_time.accumulated());
graph_cpu.save("conv_cpu_est.dat");
// Visualize the solution and mesh.
char title[100];
sprintf(title, "Solution, time %g", current_time);
view.set_title(title);
view.show_mesh(false);
view.show(h_time_new);
sprintf(title, "Mesh, time %g", current_time);
ordview.set_title(title);
ordview.show(space);
// Copy last reference solution into h_time_prev.
h_time_prev->copy(h_time_new);
// 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/richards/basic-rk-newton-adapt/definitions.cpp | .cpp | 4,259 | 108 | #include "definitions.h"
// The pressure head is raised by H_OFFSET
// so that the initial condition can be taken
// as the zero vector. Note: the resulting
// pressure head will also be greater than the
// true one by this offset.
double H_OFFSET = 1000;
/* Custom non-constant Dirichlet condition */
EssentialBCValueType CustomEssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double CustomEssentialBCNonConst::value(double x, double y) const
{
return x*(100. - x) / 2.5 * y / 100 - 1000. + H_OFFSET;
}
/* Custom weak forms */
CustomWeakFormRichardsRK::CustomWeakFormRichardsRK(ConstitutiveRelations* constitutive) : WeakForm<double>(1), constitutive(constitutive)
{
// Jacobian volumetric part.
CustomJacobianFormVol* jac_form_vol = new CustomJacobianFormVol(0, 0, constitutive);
add_matrix_form(jac_form_vol);
// Residual - volumetric.
CustomResidualFormVol* res_form_vol = new CustomResidualFormVol(0, constitutive);
add_vector_form(res_form_vol);
}
double CustomWeakFormRichardsRK::CustomJacobianFormVol::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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
double C2 = constitutive->C(h_val_i) * constitutive->C(h_val_i);
double a1_1 = (constitutive->dKdh(h_val_i) * constitutive->C(h_val_i) - constitutive->dCdh(h_val_i) * constitutive->K(h_val_i)) / C2;
double a1_2 = constitutive->K(h_val_i) / constitutive->C(h_val_i);
double a2_1 = ((constitutive->dKdh(h_val_i) * constitutive->dCdh(h_val_i) + constitutive->K(h_val_i) * constitutive->ddCdhh(h_val_i)) * C2
- 2 * constitutive->K(h_val_i) * constitutive->C(h_val_i) * constitutive->dCdh(h_val_i) * constitutive->dCdh(h_val_i)) / (C2 * C2);
double a2_2 = 2 * constitutive->K(h_val_i) * constitutive->dCdh(h_val_i) / C2;
double a3_1 = (constitutive->ddKdhh(h_val_i) * constitutive->C(h_val_i) - constitutive->dKdh(h_val_i) * constitutive->dCdh(h_val_i)) / C2;
double a3_2 = constitutive->dKdh(h_val_i) / constitutive->C(h_val_i);
result += wt[i] * (-a1_1 * u->val[i] * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- a1_2 * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ a2_1 * u->val[i] * v->val[i] * (h_prev_newton->dx[i] * h_prev_newton->dx[i]
+ h_prev_newton->dy[i] * h_prev_newton->dy[i])
+ a2_2 * v->val[i] * (u->dx[i] * h_prev_newton->dx[i]
+ u->dy[i] * h_prev_newton->dy[i])
+ a3_1 * u->val[i] * v->val[i] * h_prev_newton->dy[i]
+ a3_2 * v->val[i] * u->dy[i]
);
}
return result;
}
Ord CustomWeakFormRichardsRK::CustomJacobianFormVol::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>* CustomWeakFormRichardsRK::CustomJacobianFormVol::clone() const
{
return new CustomJacobianFormVol(*this);
}
double CustomWeakFormRichardsRK::CustomResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e,
Func<double>* *ext) const
{
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++)
{
double h_val_i = h_prev_newton->val[i] - H_OFFSET;
double r1 = (constitutive->K(h_val_i) / constitutive->C(h_val_i));
double r2 = constitutive->K(h_val_i) * constitutive->dCdh(h_val_i) / (constitutive->C(h_val_i) * constitutive->C(h_val_i));
double r3 = constitutive->dKdh(h_val_i) / constitutive->C(h_val_i);
result += wt[i] * (-r1 * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
+ r2 * v->val[i] * (h_prev_newton->dx[i] * h_prev_newton->dx[i]
+ h_prev_newton->dy[i] * h_prev_newton->dy[i])
+ r3 * v->val[i] * h_prev_newton->dy[i]
);
}
return result;
}
Ord CustomWeakFormRichardsRK::CustomResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return Ord(10);
}
VectorFormVol<double>* CustomWeakFormRichardsRK::CustomResidualFormVol::clone() const
{
return new CustomResidualFormVol(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/seepage-adapt/definitions.h | .h | 20,821 | 698 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
// Global variables for forms.
double K_S, ALPHA, THETA_R, THETA_S, N, M;
// Problem parameters.
const double TAU = 5e-3; // Time step.
const double STARTUP_TIME = 1.1e-2; // Start-up time for time-dependent Dirichlet boundary condition.
const double T_FINAL = 5.0; // Time interval length.
double TIME = 0; // Global time variable initialized with first time step.
double H_INIT = -9.5; // Initial pressure head.
double H_ELEVATION = 5.2;
double K_S_1 = 0.108;
double K_S_3 = 0.0048;
double K_S_2 = 0.0168;
double K_S_4 = 1.061;
double ALPHA_1 = 0.01;
double ALPHA_3 = 0.005;
double ALPHA_2 = 0.01;
double ALPHA_4 = 0.05;
double THETA_R_1 = 0.1020;
double THETA_R_2 = 0.09849;
double THETA_R_3 = 0.08590;
double THETA_R_4 = 0.08590;
double THETA_S_1 = 0.4570;
double THETA_S_2 = 0.4510;
double THETA_S_3 = 0.4650;
double THETA_S_4 = 0.5650;
double N_1 = 1.982;
double N_2 = 1.632;
double N_3 = 5.0;
double N_4 = 5.0;
double M_1 = 0.49546;
double M_2 = 0.38726;
double M_3 = 0.8;
double M_4 = 0.8;
// Boundary markers.
const std::string BDY_1 = "1";
const std::string BDY_2 = "2";
const std::string BDY_3 = "3";
const std::string BDY_4 = "4";
const std::string BDY_5 = "5";
const std::string BDY_6 = "6";
class CustomWeakForm : public WeakForm<double>
{
CustomWeakForm(int TIME_INTEGRATION, MeshFunctionSharedPtr<double> prev_sln)
{
this->set_ext(prev_sln);
if (TIME_INTEGRATION == 1) {
this->add_matrix_form(new JacobianFormVolEuler(0, 0));
this->add_matrix_form_surf(new JacobianFormSurf1Euler(0, 0));
this->mfsurf.back()->set_area(BDY_1);
this->add_matrix_form_surf(new JacobianFormSurf4Euler(0, 0));
this->mfsurf.back()->set_area(BDY_4);
this->add_matrix_form_surf(new JacobianFormSurf6Euler(0, 0));
this->mfsurf.back()->set_area(BDY_6);
this->add_vector_form(new ResidualFormVolEuler(0));
this->add_vector_form_surf(new ResidualFormSurf1Euler(0));
this->vfsurf.back()->set_area(BDY_1);
this->add_vector_form_surf(new ResidualFormSurf4Euler(0));
this->vfsurf.back()->set_area(BDY_4);
this->add_vector_form_surf(new ResidualFormSurf6Euler(0));
this->vfsurf.back()->set_area(BDY_6);
}
else
{
this->add_matrix_form(new JacobianFormVolCrankNicolson(0, 0));
this->add_matrix_form_surf(new JacobianFormSurf1CrankNicolson(0, 0));
this->mfsurf.back()->set_area(BDY_1);
this->add_matrix_form_surf(new JacobianFormSurf4CrankNicolson(0, 0));
this->mfsurf.back()->set_area(BDY_4);
this->add_matrix_form_surf(new JacobianFormSurf6CrankNicolson(0, 0));
this->mfsurf.back()->set_area(BDY_6);
this->add_vector_form(new ResidualFormVolCrankNicolson(0));
this->add_vector_form_surf(new ResidualFormSurf1CrankNicolson(0));
this->vfsurf.back()->set_area(BDY_1);
this->add_vector_form_surf(new ResidualFormSurf4CrankNicolson(0));
this->vfsurf.back()->set_area(BDY_4);
this->add_vector_form_surf(new ResidualFormSurf6CrankNicolson(0));
this->vfsurf.back()->set_area(BDY_6);
}
}
class JacobianFormVolEuler : public MatrixFormVol<double>
{
public:
JacobianFormVolEuler(int i, int j) : MatrixFormVol<double>(i, j)
{
}
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
double x = e->x[0];
double y = e->x[1];
if (is_in_mat_1(x,y)) {
K_S = K_S_1;
ALPHA = ALPHA_1;
THETA_R = THETA_R_1;
THETA_S = THETA_R_1;
N = N_1;
M = M_1;
}
if (is_in_mat_2(x,y)) {
K_S = K_S_2;
ALPHA = ALPHA_2;
THETA_R = THETA_R_2;
THETA_S = THETA_R_2;
N = N_2;
M = M_2;
}
if (is_in_mat_3(x,y)) {
K_S = K_S_3;
ALPHA = ALPHA_3;
THETA_R = THETA_R_3;
THETA_S = THETA_R_3;
N = N_3;
M = M_3;
}
if (is_in_mat_4(x,y)) {
K_S = K_S_4;
ALPHA = ALPHA_4;
THETA_R = THETA_R_4;
THETA_S = THETA_R_4;
N = N_4;
M = M_4;
}
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * (
C(h_prev_newton->val[i]) * u->val[i] * v->val[i] / TAU
+ dCdh(h_prev_newton->val[i]) * u->val[i] * h_prev_newton->val[i] * v->val[i] / TAU
- dCdh(h_prev_newton->val[i]) * u->val[i] * h_prev_time->val[i] * v->val[i] / TAU
+ K(h_prev_newton->val[i]) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ dKdh(h_prev_newton->val[i]) * u->val[i] *
(h_prev_newton->dx[i]*v->dx[i] + h_prev_newton->dy[i]*v->dy[i])
- dKdh(h_prev_newton->val[i]) * u->dy[i] * v->val[i]
- ddKdhh(h_prev_newton->val[i]) * u->val[i] * h_prev_newton->dy[i] * v->val[i]
);
return result;
}
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 Ord(20);
}
MatrixFormVol<double>* clone() const
{
return new JacobianFormVolEuler();
}
};
class JacobianFormVolCrankNicolson : public MatrixFormVol<double>
{
public:
JacobianFormVolCrankNicolson(int i, int j) : MatrixFormVol<double>(i, j)
{
}
virtual double value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
double x = e->x[0];
double y = e->x[1];
if (is_in_mat_1(x,y)) {
K_S = K_S_1;
ALPHA = ALPHA_1;
THETA_R = THETA_R_1;
THETA_S = THETA_R_1;
N = N_1;
M = M_1;
}
if (is_in_mat_2(x,y)) {
K_S = K_S_2;
ALPHA = ALPHA_2;
THETA_R = THETA_R_2;
THETA_S = THETA_R_2;
N = N_2;
M = M_2;
}
if (is_in_mat_3(x,y)) {
K_S = K_S_3;
ALPHA = ALPHA_3;
THETA_R = THETA_R_3;
THETA_S = THETA_R_3;
N = N_3;
M = M_3;
}
if (is_in_mat_4(x,y)) {
K_S = K_S_4;
ALPHA = ALPHA_4;
THETA_R = THETA_R_4;
THETA_S = THETA_R_4;
N = N_4;
M = M_4;
}
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++)
result += wt[i] * 0.5 * ( // implicit Euler part:
C(h_prev_newton->val[i]) * u->val[i] * v->val[i] / TAU
+ dCdh(h_prev_newton->val[i]) * u->val[i] * h_prev_newton->val[i] * v->val[i] / TAU
- dCdh(h_prev_newton->val[i]) * u->val[i] * h_prev_time->val[i] * v->val[i] / TAU
+ K(h_prev_newton->val[i]) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])
+ dKdh(h_prev_newton->val[i]) * u->val[i] *
(h_prev_newton->dx[i]*v->dx[i] + h_prev_newton->dy[i]*v->dy[i])
- dKdh(h_prev_newton->val[i]) * u->dy[i] * v->val[i]
- ddKdhh(h_prev_newton->val[i]) * u->val[i] * h_prev_newton->dy[i] * v->val[i]
)
+ wt[i] * 0.5 * ( // explicit Euler part,
C(h_prev_time->val[i]) * u->val[i] * v->val[i] / TAU
);
return result;
}
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 Ord(20);
}
MatrixFormVol<double>* clone() const
{
return new JacobianFormVolEuler(this->i, this->j);
}
};
class JacobianFormSurf1Euler : public MatrixFormSurf<double>
{
public:
JacobianFormSurf1Euler(int i, int j) : MatrixFormSurf<double>(i, j)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * dKdh(h_prev_newton->val[i]) * u->val[i] * v->val[i];
}
return result;
}
virtual 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(20);
}
MatrixFormSurf<double>* clone() const
{
return new JacobianFormSurf1Euler(this->i, this->j);
}
};
class JacobianFormSurf1CrankNicolson : public MatrixFormSurf<double>
{
public:
JacobianFormSurf1CrankNicolson(int i, int j) : MatrixFormSurf<double>(i, j)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
// Just the implicit Euler contributes:
result += wt[i] * 0.5 * dKdh(h_prev_newton->val[i]) * u->val[i] * v->val[i];
}
return result;
}
virtual 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(20);
}
MatrixFormSurf<double>* clone() const
{
return new JacobianFormSurf1CrankNicolson(this->i, this->j);
}
};
class JacobianFormSurf4Euler : public MatrixFormSurf<double>
{
public:
JacobianFormSurf4Euler(int i, int j) : MatrixFormSurf<double>(i, j)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result -= wt[i] * dKdh(h_prev_newton->val[i]) * u->val[i] * v->val[i];
}
return result;
}
virtual 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(20);
}
MatrixFormSurf<double>* clone() const
{
return new JacobianFormSurf4Euler(this->i, this->j);
}
};
class JacobianFormSurf4CrankNicolson : public MatrixFormSurf<double>
{
public:
JacobianFormSurf4CrankNicolson(int i, int j) : MatrixFormSurf<double>(i, j)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
// Just the implicit Euler contributes:
result -= wt[i] * 0.5 * dKdh(h_prev_newton->val[i]) * u->val[i] * v->val[i];
}
return result;
}
virtual 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(20);
}
MatrixFormSurf<double>* clone() const
{
return new JacobianFormSurf4CrankNicolson(this->i, this->j);
}
};
class JacobianFormSurf6Euler : public MatrixFormSurf<double>
{
public:
JacobianFormSurf6Euler(int i, int j) : MatrixFormSurf<double>(i, j)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * dKdh(h_prev_newton->val[i]) * u->val[i] * v->val[i];
}
return result;
}
virtual 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(20);
}
MatrixFormSurf<double>* clone() const
{
return new JacobianFormSurf6Euler(this->i, this->j);
}
};
class JacobianFormSurf6CrankNicolson : public MatrixFormSurf<double>
{
public:
JacobianFormSurf6CrankNicolson(int i, int j) : MatrixFormSurf<double>(i, j)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
// Just the implicit Euler contributes:
for (int i = 0; i < n; i++) {
result += wt[i] * 0.5 * dKdh(h_prev_newton->val[i]) * u->val[i] * v->val[i];
}
return result;
}
virtual 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(20);
}
MatrixFormSurf<double>* clone() const
{
return new JacobianFormSurf6CrankNicolson(this->i, this->j);
}
};
class ResidualFormVolEuler : public VectorFormVol<double>
{
public:
ResidualFormVolEuler(int i) : VectorFormVol<double>(i)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * (
C(h_prev_newton->val[i]) * (h_prev_newton->val[i] - h_prev_time->val[i]) * v->val[i] / TAU
+ K(h_prev_newton->val[i]) * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- dKdh(h_prev_newton->val[i]) * h_prev_newton->dy[i] * v->val[i]
);
}
return result;
}
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 Ord(20);
}
VectorFormVol<double>* clone() const
{
return new ResidualFormVolEuler(this->i);
}
};
class ResidualFormVolCrankNicolson : public VectorFormVol<double>
{
public:
ResidualFormVolCrankNicolson(int i) : VectorFormVol<double>(i)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * 0.5 * ( // implicit Euler part
C(h_prev_newton->val[i]) * (h_prev_newton->val[i] - h_prev_time->val[i]) * v->val[i] / TAU
+ K(h_prev_newton->val[i]) * (h_prev_newton->dx[i] * v->dx[i] + h_prev_newton->dy[i] * v->dy[i])
- dKdh(h_prev_newton->val[i]) * h_prev_newton->dy[i] * v->val[i]
)
+ wt[i] * 0.5 * ( // explicit Euler part
C(h_prev_time->val[i]) * (h_prev_newton->val[i] - h_prev_time->val[i]) * v->val[i] / TAU
+ K(h_prev_time->val[i]) * (h_prev_time->dx[i] * v->dx[i] + h_prev_time->dy[i] * v->dy[i])
- dKdh(h_prev_time->val[i]) * h_prev_time->dy[i] * v->val[i]
);
}
return result;
}
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 Ord(20);
}
VectorFormVol<double>* clone() const
{
return new ResidualFormVolEuler(this->i);
}
};
class ResidualFormSurf1Euler : public VectorFormSurf<double>
{
public:
ResidualFormSurf1Euler(int i) : VectorFormSurf<double>(i)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * K(h_prev_newton->val[i]) * v->val[i];
}
return result;
}
virtual 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(20);
}
VectorFormSurf<double>* clone() const
{
return new ResidualFormSurf1Euler(this->i);
}
};
class ResidualFormSurf1CrankNicolson : public VectorFormSurf<double>
{
public:
ResidualFormSurf1CrankNicolson(int i) : VectorFormSurf<double>(i)
{
}
virtual double value(GeomSurf n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
double result = 0;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * 0.5 * (K(h_prev_newton->val[i]) + K(h_prev_time->val[i])) * v->val[i];
}
return result;
}
virtual 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(20);
}
VectorFormSurf<double>* clone() const
{
return new ResidualFormSurf1CrankNicolson(this->i);
}
};
class ResidualFormSurf4Euler : public VectorFormSurf<double>
{
public:
ResidualFormSurf4Euler(int i) : VectorFormSurf<double>(i)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result -= wt[i] * K(h_prev_newton->val[i]) * v->val[i];
}
return result;
}
virtual 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(20);
}
VectorFormSurf<double>* clone() const
{
return new ResidualFormSurf4Euler(this->i);
}
};
class ResidualFormSurf4CrankNicolson : public VectorFormSurf<double>
{
public:
ResidualFormSurf4CrankNicolson(int i) : VectorFormSurf<double>(i)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++) {
result -= wt[i] * 0.5 * (K(h_prev_newton->val[i]) + K(h_prev_time->val[i]))* v->val[i];
}
return result;
}
virtual 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(20);
}
VectorFormSurf<double>* clone() const
{
return new ResidualFormSurf4CrankNicolson(this->i, this->j);
}
};
class ResidualFormSurf6Euler : public VectorFormSurf<double>
{
public:
ResidualFormSurf6Euler(int i) : VectorFormSurf<double>(i)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * (q_function() + K(h_prev_newton->val[i])) * v->val[i];
}
return result;
}
virtual 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(20);
}
VectorFormSurf<double>* clone() const
{
return new ResidualFormSurf6Euler(this->i);
}
};
class ResidualFormSurf6CrankNicolson : public VectorFormSurf<double>
{
public:
ResidualFormSurf6CrankNicolson(int i) : VectorFormSurf<double>(i)
{
}
virtual 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;
Func<double>* h_prev_newton = u_ext[0];
Func<double>* h_prev_time = ext[0];
for (int i = 0; i < n; i++) {
result += wt[i] * (q_function() + 0.5 * (K(h_prev_newton->val[i]) + K(h_prev_time->val[i]))) * v->val[i];
}
return result;
}
virtual 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(20);
}
VectorFormSurf<double>* clone() const
{
return new ResidualFormSurf6CrankNicolson(this->i);
}
};
}; | Unknown |
2D | hpfem/hermes-examples | 2d-advanced/richards/seepage-adapt/constitutive_genuchten.cpp | .cpp | 4,722 | 113 | // K (van Genuchten).
double K(double h)
{
double alpha;
double n;
double m;
alpha = ALPHA;
n = N;
m = M;
if (h < 0) return
K_S*pow((1 + pow((-alpha*h),n)),(-m/2))*pow((1 -
pow((-alpha*h),(m*n))*pow((1 + pow((-alpha*h),n)),(-m))),2) ;
else return K_S;
}
// dK/dh (van Genuchten).
double dKdh(double h)
{
double alpha;
double n;
double m;
alpha = ALPHA;
n = N;
m = M;
if (h < 0) return
K_S*pow((1 + pow((-alpha*h),n)),(-m/2))*(1 -
pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m)))*(-2*m*n*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/h +
2*m*n*pow((-alpha*h),n)*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(h*(1 + pow((-alpha*h),n)))) -
K_S*m*n*pow((-alpha*h),n)*pow((1 + pow((-alpha*h),n)),(-m/2))*pow((1 -
pow((-alpha*h),(m*n))*pow((1 + pow((-alpha*h),n)),(-m))),2)/(2*h*(1 +
pow((-alpha*h),n))) ;
else return 0;
}
// ddK/dhh (van Genuchten).
double ddKdhh(double h)
{
double alpha;
double n;
double m;
alpha = ALPHA;
n = N;
m = M;
if (h < 0) return
K_S*pow((1 + pow((-alpha*h),n)),(-m/2))*(1 -
pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m)))*(-2*pow(m,2)*pow(n,2)*pow((-alpha*h),(m*n))*pow((1
+ pow((-alpha*h),n)),(-m))/pow(h,2) +
2*m*n*pow((-alpha*h),(m*n))*pow((1 + pow((-alpha*h),n)),(-m))/pow(h,2)
- 2*m*n*pow((-alpha*h),n)*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(pow(h,2)*(1 + pow((-alpha*h),n))) -
2*m*pow(n,2)*pow((-alpha*h),(2*n))*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(pow(h,2)*pow((1 + pow((-alpha*h),n)),2)) -
2*pow(m,2)*pow(n,2)*pow((-alpha*h),(2*n))*pow((-alpha*h),(m*n))*pow((1
+ pow((-alpha*h),n)),(-m))/(pow(h,2)*pow((1 + pow((-alpha*h),n)),2)) +
2*m*pow(n,2)*pow((-alpha*h),n)*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(pow(h,2)*(1 + pow((-alpha*h),n))) +
4*pow(m,2)*pow(n,2)*pow((-alpha*h),n)*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(pow(h,2)*(1 + pow((-alpha*h),n)))) +
K_S*pow((1 + pow((-alpha*h),n)),(-m/2))*(-m*n*pow((-alpha*h),(m*n))*pow((1
+ pow((-alpha*h),n)),(-m))/h +
m*n*pow((-alpha*h),n)*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(h*(1 +
pow((-alpha*h),n))))*(-2*m*n*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/h +
2*m*n*pow((-alpha*h),n)*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(h*(1 + pow((-alpha*h),n)))) -
K_S*m*n*pow((-alpha*h),n)*pow((1 + pow((-alpha*h),n)),(-m/2))*(1 -
pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m)))*(-2*m*n*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/h +
2*m*n*pow((-alpha*h),n)*pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))/(h*(1 + pow((-alpha*h),n))))/(h*(1 +
pow((-alpha*h),n))) + K_S*m*n*pow((-alpha*h),n)*pow((1 +
pow((-alpha*h),n)),(-m/2))*pow((1 - pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))),2)/(2*pow(h,2)*(1 + pow((-alpha*h),n))) +
K_S*m*pow(n,2)*pow((-alpha*h),(2*n))*pow((1 +
pow((-alpha*h),n)),(-m/2))*pow((1 - pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))),2)/(2*pow(h,2)*pow((1 +
pow((-alpha*h),n)),2)) - K_S*m*pow(n,2)*pow((-alpha*h),n)*pow((1 +
pow((-alpha*h),n)),(-m/2))*pow((1 - pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))),2)/(2*pow(h,2)*(1 + pow((-alpha*h),n))) +
K_S*pow(m,2)*pow(n,2)*pow((-alpha*h),(2*n))*pow((1 +
pow((-alpha*h),n)),(-m/2))*pow((1 - pow((-alpha*h),(m*n))*pow((1 +
pow((-alpha*h),n)),(-m))),2)/(4*pow(h,2)*pow((1 +
pow((-alpha*h),n)),2)) ;
else return 0;
}
// C (van Genuchten).
double C(double h)
{
if (h < 0) return
STORATIVITY*pow((1 + pow((-ALPHA*h),N)),(-M))*(THETA_S - THETA_R)/THETA_S -
M*N*pow((-ALPHA*h),N)*pow((1 + pow((-ALPHA*h),N)),(-M))*(THETA_S - THETA_R)/(h*(1 + pow((-ALPHA*h),N)));
else return STORATIVITY;
}
// dC/dh (van Genuchten).
double dCdh(double h)
{
if (h < 0) return
M*N*pow((-ALPHA*h),N)*pow((1 + pow((-ALPHA*h),N)),(-M))*(THETA_S - THETA_R)/(pow(h,2)*(1 + pow((-ALPHA*h),N))) + M*pow(N,2)*pow((-ALPHA*h),(2*N))*pow((1 +
pow((-ALPHA*h),N)),(-M))*(THETA_S - THETA_R)/(pow(h,2)*pow((1 + pow((-ALPHA*h),N)),2)) + pow(M,2)*pow(N,2)*pow((-ALPHA*h),(2*N))*pow((1 + pow((-ALPHA*h),N)),(-M))*(THETA_S - THETA_R)/(pow(h,2)*
pow((1 + pow((-ALPHA*h),N)),2)) - M*pow(N,2)*pow((-ALPHA*h),N)*pow((1 + pow((-ALPHA*h),N)),(-M))*(THETA_S - THETA_R)/(pow(h,2)*(1 + pow((-ALPHA*h),N))) -
M*N*STORATIVITY*pow((-ALPHA*h),N)*pow((1 + pow((-ALPHA*h),N)),(-M))*(THETA_S - THETA_R)/(THETA_S*h*(1 + pow((-ALPHA*h),N))) ;
else return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/seepage-adapt/main.cpp | .cpp | 12,877 | 355 | #include "definitions.h"
// This example uses adaptivity with dynamical meshes to solve
// the time-dependent Richard's equation. The time discretization
// is backward Euler or Crank-Nicolson, and the Newton's method
// is applied to solve the nonlinear problem in each time step.
//
// PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0
// where K(h) = K_S*exp(alpha*h) for h < 0,
// K(h) = K_S for h >= 0,
// C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0,
// C(h) = alpha*(theta_s - theta_r) for h >= 0.
//
// Domain: rectangle (0, 8) x (0, 6.5).
//
// BC: Dirichlet, given by the initial condition.
// IC: See the function init_cond().
//
// The parameters are located in definitions.h.
// Use van Genuchten's constitutive relations, or Gardner's.
// #define CONSTITUTIVE_GENUCHTEN
// Initial polynomial degree of all mesh elements.
const int P_INIT = 1;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 0;
// Number of initial mesh refinements towards the top edge.
const int INIT_REF_NUM_BDY = 0;
// 1... implicit Euler, 2... Crank-Nicolson.
const int TIME_INTEGRATION = 2;
// Adaptivity
// Every UNREF_FREQth 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;
// 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 = 1;
// 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;
// This parameter influences the selection of
// candidates in hp-adaptivity. Default value is 1.0.
const double CONV_EXP = 1.0;
// Stopping criterion for adaptivity.
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;
// Newton's method
// Stopping criterion for Newton on fine mesh.
const double NEWTON_TOL = 0.0005;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 50;
// Maximum value, used in function q_function();
double Q_MAX_VALUE = 0.07;
double q_function() {
if (STARTUP_TIME > TIME) return Q_MAX_VALUE * TIME / STARTUP_TIME;
else return Q_MAX_VALUE;
}
double STORATIVITY = 0.05;
// Material properties.
bool is_in_mat_1(double x, double y) {
if (y >= -0.5) return true;
else return false;
}
bool is_in_mat_2(double x, double y) {
if (y >= -1.0 && y < -0.5) return true;
else return false;
}
bool is_in_mat_4(double x, double y) {
if (x >= 1.0 && x <= 3.0 && y >= -2.5 && y < -1.5) return true;
else return false;
}
bool is_in_mat_3(double x, double y) {
if (!is_in_mat_1(x, y) && !is_in_mat_2(x, y) && !is_in_mat_4(x, y)) return true;
else return false;
}
#ifdef CONSTITUTIVE_GENUCHTEN
#include "constitutive_genuchten.cpp"
#else
#include "constitutive_gardner.cpp"
#endif
// Initial condition.
double init_cond(double x, double y, double& dx, double& dy) {
dx = 0;
dy = -1;
return -y + H_INIT;
}
// Essential (Dirichlet) boundary condition values.
double essential_bc_values(double x, double y, double time)
{
if (STARTUP_TIME > time) return -y + H_INIT + time/STARTUP_TIME*H_ELEVATION;
else return -y + H_INIT + H_ELEVATION;
}
int main(int argc, char* argv[])
{
// Time measurement.
TimePeriod cpu_time;
cpu_time.tick();
// Load the mesh.
MeshSharedPtr mesh, basemesh;
MeshReaderH2D mloader;
mloader.load("domain.mesh", &basemesh);
// Perform initial mesh refinements.
mesh->copy(&basemesh);
for(int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
mesh->refine_towards_boundary(BDY_3, INIT_REF_NUM_BDY);
// Initialize boundary conditions.
BCTypes bc_types;
bc_types.add_bc_dirichlet(BDY_3);
bc_types.add_bc_neumann({BDY_2, BDY_5});
bc_types.add_bc_newton({BDY_1, BDY_4, BDY_6});
// Enter Dirichlet boundary values.
BCValues bc_values(&TIME);
bc_values.add_timedep_function(BDY_3, essential_bc_values);
SpaceSharedPtr<double> space(new // Create an H1 space with default shapeset.
H1Space<double>(mesh, &bc_types, &bc_values, P_INIT));
int ndof = Space<double>::get_num_dofs(&space);
info("ndof = %d.", ndof);
SpaceSharedPtr<double> init_space(&basemesh, &bc_types, &bc_values, P_INIT);
// Create a selector which will select optimal candidate.
H1ProjBasedSelector<double> selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER);
// Solutions for the time stepping and the Newton's method.
Solution<double> sln, ref_sln, sln_prev_time;
// Initialize views.
char title_init[200];
sprintf(title_init, "Projection of initial condition");
ScalarView* view_init = new ScalarView(title_init, new WinGeom(0, 0, 410, 300));
sprintf(title_init, "Initial mesh");
OrderView* ordview_init = new OrderView(title_init, new WinGeom(420, 0, 350, 300));
view_init->fix_scale_width(80);
// Adapt mesh to represent initial condition with given accuracy.
info(new // Create an H1 space for the initial coarse mesh solution.
H1Space<double>("Mesh adaptivity to an exact function:"));
int as = 1; bool done = false;
do
{
// Setup space for the reference solution.
Space<double>*rspace = Space<double>::construct_refined_space(init_space);
// Assign the function f() to the fine mesh.
ref_sln.set_exact(rspace->get_mesh(), init_cond);
// Project the function f() on the coarse mesh.
OGProjection<double>::project_global(init_space, ref_sln, sln_prev_time);
// Calculate element errors and total error estimate.
Adapt adaptivity(init_space);
double err_est_rel = adaptivity.calc_err_est(sln_prev_time, &ref_sln) * 100;
info("Step %d, ndof %d, proj_error %g%%", as, Space<double>::get_num_dofs(init_space), err_est_rel);
// If err_est_rel too large, adapt the mesh.
if (err_est_rel < ERR_STOP) done = true;
else {
double to_be_processed = 0;
done = adaptivity.adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY, to_be_processed);
if (Space<double>::get_num_dofs(init_space) >= NDOF_STOP) done = true;
view_init->show(sln_prev_time);
char title_init[100];
sprintf(title_init, "Initial mesh, step %d", as);
ordview_init->set_title(title_init);
ordview_init->show(init_space);
}
as++;
}
while (done == false);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakForm);
// Error estimate and discrete problem size as a function of physical time.
SimpleGraph graph_time_err_est, graph_time_err_exact, graph_time_dof, graph_time_cpu;
// Visualize the projection and mesh.
ScalarView view("Initial condition", new WinGeom(0, 0, 440, 350));
OrderView ordview("Initial mesh", new WinGeom(450, 0, 400, 350));
view.show(sln_prev_time);
ordview.show(&space);
// Time stepping loop.
int num_time_steps = (int)(T_FINAL/TAU + 0.5);
for(int ts = 1; ts <= num_time_steps; ts++)
{
// Time measurement.
cpu_time.tick();
// Updating current time.
TIME = ts*TAU;
info("---- Time step %d:", ts);
// Periodic global derefinement.
if (ts > 1 && ts % UNREF_FREQ == 0)
{
info("Global mesh derefinement.");
switch (UNREF_METHOD) {
case 1: mesh->copy(&basemesh);
space.set_uniform_order(P_INIT);
break;
case 2: mesh->unrefine_all_elements();
space.set_uniform_order(P_INIT);
break;
case 3: mesh->unrefine_all_elements();
//space.adjust_element_order(-1, P_INIT);
space.adjust_element_order(-1, -1, P_INIT, P_INIT);
break;
default: error("Wrong global derefinement method.");
}
ndof = Space<double>::get_num_dofs(&space);
}
// Spatial adaptivity loop. Note; sln_prev_time must not be changed
// during spatial adaptivity.
bool done = false;
int as = 1;
do
{
info("---- Time step %d, adaptivity step %d:", ts, as);
// Construct globally refined reference mesh
// and setup reference space.
Space<double>* ref_space = Space<double>::construct_refined_space(&space);
double* coeff_vec = new double[ref_space->get_num_dofs()];
// Calculate initial coefficient vector for Newton on the fine mesh.
if (as == 1 && ts == 1) {
info("Projecting coarse mesh solution to obtain initial vector on new fine mesh.");
OGProjection<double>::project_global(ref_space, sln_prev_time, coeff_vec);
}
else {
info("Projecting previous fine mesh solution to obtain initial vector on new fine mesh.");
OGProjection<double>::project_global(ref_space, ref_sln, coeff_vec);
delete ref_sln.get_mesh();
}
// Initialize the FE problem.
bool is_linear = false;
DiscreteProblem<double> dp(wf, ref_space, is_linear);
// Perform Newton's iteration.
info("Solving nonlinear problem:");
bool verbose = true;
if (!solve_newton(coeff_vec, &dp,
NEWTON_TOL, NEWTON_MAX_ITER, verbose)) error("Newton's iteration failed.");
// Translate the resulting coefficient vector into the actual solutions.
Solution<double>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);
// Project the fine mesh solution on the coarse mesh.
info("Projecting fine mesh solution on coarse mesh for error calculation.");
OGProjection<double>::project_global(space, &ref_sln, sln);
// Calculate element errors.
info("Calculating error estimate.");
Adapt<double>* adaptivity = new Adapt<double>(&space, HERMES_H1_NORM);
// Calculate error estimate wrt. fine mesh solution.
double err_est_rel = adaptivity->calc_err_est(sln, &ref_sln) * 100;
// Report results.
info("ndof_coarse: %d, ndof_fine: %d, space_err_est_rel: %g%%",
Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_est_rel);
// Add entries to convergence graphs.
graph_time_err_est.add_values(ts*TAU, err_est_rel);
graph_time_err_est.save("time_err_est.dat");
graph_time_dof.add_values(ts*TAU, Space<double>::get_num_dofs(&space));
graph_time_dof.save("time_dof.dat");
graph_time_cpu.add_values(ts*TAU, cpu_time.accumulated());
graph_time_cpu.save("time_cpu.dat");
// If space_err_est too large, adapt the mesh.
if (err_est_rel < ERR_STOP) done = true;
else {
info("Adapting coarse mesh.");
done = adaptivity->adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY);
if (Space<double>::get_num_dofs(&space) >= NDOF_STOP) {
done = true;
break;
}
as++;
}
// Cleanup.
delete [] coeff_vec;
delete adaptivity;
delete ref_space;
}
while (!done);
// Visualize the solution and mesh.
char title[100];
sprintf(title, "Solution, time level %d", ts);
view.set_title(title);
view.show(sln);
sprintf(title, "Mesh, time level %d", ts);
ordview.set_title(title);
ordview.show(&space);
// Copy new time level solution into sln_prev_time.
sln_prev_time.copy(ref_sln);
}
// Wait for all views to be closed.
View::wait();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/seepage-adapt/constitutive_gardner.cpp | .cpp | 634 | 37 | // K (Gardner).
double K(double h)
{
if (h < 0) return K_S*exp(ALPHA*h);
else return K_S;
}
// dK/dh (Gardner).
double dKdh(double h)
{
if (h < 0) return K_S*ALPHA*exp(ALPHA*h);
else return 0;
}
// ddK/dhh (Gardner).
double ddKdhh(double h)
{
if (h < 0) return K_S*ALPHA*ALPHA*exp(ALPHA*h);
else return 0;
}
// C (Gardner).
double C(double h)
{
if (h < 0) return ALPHA*(THETA_S - THETA_R)*exp(ALPHA*h);
else return ALPHA*(THETA_S - THETA_R);
// else return STORATIVITY;
}
// dC/dh (Gardner).
double dCdh(double h)
{
if (h < 0) return ALPHA*(THETA_S - THETA_R)*ALPHA*exp(ALPHA*h);
else return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/seepage-adapt/constitutive.cpp | .cpp | 3,703 | 115 | // K (Gardner).
double K_Gardner(double h)
{
if (h < 0) return K_S*exp(ALPHA*h);
else return K_S;
}
// K (van Genuchten).
double K(double h)
{
if (h < 0) return (1-pow(-ALPHA*h,M*N)*pow((1+pow(-ALPHA*h,N)),-M))*
(1-pow(-ALPHA*h,M*N)*pow((1+pow(-ALPHA*h,N)),-M))/
(pow(1 + pow(-ALPHA*h,N),M/2));
else return K_S;
}
// dK/dh (Gardner).
double dKdh_Gardner(double h)
{
if (h < 0) return K_S*ALPHA*exp(ALPHA*h);
else return 0;
}
// dK/dh (van Genuchten).
double dKdh(double h)
{
if (h < 0) return (ALPHA*pow(-(ALPHA*h),-1 + N)*pow(1 + pow(-(ALPHA*h),N),-1 - M/2.)*
pow(1 - pow(-(ALPHA*h),M*N)/pow(1 + pow(-(ALPHA*h),N),M),
2)*M*N)/2. + (2*(1 -
pow(-(ALPHA*h),M*N)/pow(1 + pow(-(ALPHA*h),N),M))*
(-(ALPHA*pow(-(ALPHA*h),-1 + N + M*N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M)*M*N) +
(ALPHA*pow(-(ALPHA*h),-1 + M*N)*M*N)/
pow(1 + pow(-(ALPHA*h),N),M)))/
pow(1 + pow(-(ALPHA*h),N),M/2.) ;
else return 0;
}
// ddK/dhh (Gardner).
double ddKdhh_Gardner(double h)
{
if (h < 0) return K_S*ALPHA*ALPHA*exp(ALPHA*h);
else return 0;
}
// ddK/dhh (van Genuchten).
double ddKdhh(double h)
{
if (h < 0) return -(pow(ALPHA,2)*pow(-(ALPHA*h),-2 + N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M/2.)*
pow(1 - pow(-(ALPHA*h),M*N)/pow(1 + pow(-(ALPHA*h),N),M),
2)*M*(-1 + N)*N)/2. -
(pow(ALPHA,2)*pow(-(ALPHA*h),-2 + 2*N)*
pow(1 + pow(-(ALPHA*h),N),-2 - M/2.)*
pow(1 - pow(-(ALPHA*h),M*N)/pow(1 + pow(-(ALPHA*h),N),M),
2)*(-1 - M/2.)*M*pow(N,2))/2. +
2*ALPHA*pow(-(ALPHA*h),-1 + N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M/2.)*
(1 - pow(-(ALPHA*h),M*N)/pow(1 + pow(-(ALPHA*h),N),M))*M*N*
(-(ALPHA*pow(-(ALPHA*h),-1 + N + M*N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M)*M*N) +
(ALPHA*pow(-(ALPHA*h),-1 + M*N)*M*N)/
pow(1 + pow(-(ALPHA*h),N),M)) +
(2*pow(-(ALPHA*pow(-(ALPHA*h),-1 + N + M*N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M)*M*N) +
(ALPHA*pow(-(ALPHA*h),-1 + M*N)*M*N)/
pow(1 + pow(-(ALPHA*h),N),M),2))/
pow(1 + pow(-(ALPHA*h),N),M/2.) +
(2*(1 - pow(-(ALPHA*h),M*N)/pow(1 + pow(-(ALPHA*h),N),M))*
(pow(ALPHA,2)*pow(-(ALPHA*h),-2 + 2*N + M*N)*
pow(1 + pow(-(ALPHA*h),N),-2 - M)*(-1 - M)*M*pow(N,2)
+ pow(ALPHA,2)*pow(-(ALPHA*h),-2 + N + M*N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M)*pow(M,2)*pow(N,2)
- (pow(ALPHA,2)*pow(-(ALPHA*h),-2 + M*N)*M*N*(-1 + M*N))/
pow(1 + pow(-(ALPHA*h),N),M) +
pow(ALPHA,2)*pow(-(ALPHA*h),-2 + N + M*N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M)*M*N*(-1 + N + M*N)))/
pow(1 + pow(-(ALPHA*h),N),M/2.) ;
else return 0;
}
// C (Gardner).
double C_Gardner(double h)
{
if (h < 0) return ALPHA*(THETA_S - THETA_R)*exp(ALPHA*h);
else return ALPHA*(THETA_S - THETA_R);
}
// C (van Genuchten).
double C(double h)
{
if (h < 0) return ALPHA*pow(-(ALPHA*h),-1 + N)*pow(1 + pow(-(ALPHA*h),N),-1 - M)*M*N*(THETA_S - THETA_R) +
(THETA_S-THETA_R)/pow(1+pow(-ALPHA*h,N),M)/THETA_S*STORATIVITY;
else return STORATIVITY;
}
// dC/dh (Gardner).
double dCdh_Gardner(double h)
{
if (h < 0) return ALPHA*(THETA_S - THETA_R)*ALPHA*exp(ALPHA*h);
else return 0;
}
// dC/dh (van Genuchten).
double dCdh(double h)
{
if (h < 0) return (-(pow(ALPHA,2)*pow(-(ALPHA*h),-2 + N)*
pow(1 + pow(-(ALPHA*h),N),-1 - M)*M*(-1 + N)*N) -
pow(ALPHA,2)*pow(-(ALPHA*h),-2 + 2*N)*
pow(1 + pow(-(ALPHA*h),N),-2 - M)*(-1 - M)*M*pow(N,2) +
ALPHA*pow(-(ALPHA*h),-1 + N)*pow(1 + pow(-(ALPHA*h),N),-1
- M)*M*N/THETA_S*STORATIVITY)*(THETA_S - THETA_R) ;
else return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/richards/seepage-adapt/definitions.cpp | .cpp | 0 | 0 | null | C++ |
2D | hpfem/hermes-examples | 2d-advanced/helmholtz/waveguide/definitions.h | .h | 10,046 | 277 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Essential boundary conditions */
class EssentialBCNonConst : public EssentialBoundaryCondition < double >
{
public:
EssentialBCNonConst(std::string marker);
~EssentialBCNonConst() {};
virtual EssentialBCValueType get_value_type() const;
virtual double value(double x, double y) const;
};
/* Weak forms */
class WeakFormHelmholtz : public WeakForm < double >
{
public:
WeakFormHelmholtz(double eps, double mu, double omega, double sigma, double beta, double E0, double h);
void set_parameters(double eps, double mu, double omega, double sigma, double beta, double E0, double h)
{
this->delete_all();
// Jacobian.
add_matrix_form(new MatrixFormHelmholtzEquation_real_real(0, 0, eps, omega, mu));
add_matrix_form(new MatrixFormHelmholtzEquation_real_imag(0, 1, mu, omega, sigma));
add_matrix_form(new MatrixFormHelmholtzEquation_imag_real(1, 0, mu, omega, sigma));
add_matrix_form(new MatrixFormHelmholtzEquation_imag_imag(1, 1, eps, mu, omega));
add_matrix_form_surf(new MatrixFormSurfHelmholtz_real_imag(0, 1, "0", beta));
add_matrix_form_surf(new MatrixFormSurfHelmholtz_imag_real(1, 0, "0", beta));
// Residual.
add_vector_form(new VectorFormHelmholtzEquation_real(0, eps, omega, mu, sigma));
add_vector_form(new VectorFormHelmholtzEquation_imag(1, eps, omega, mu, sigma));
add_vector_form_surf(new VectorFormSurfHelmholtz_real(0, "0", beta));
add_vector_form_surf(new VectorFormSurfHelmholtz_imag(1, "0", beta));
}
private:
class MatrixFormHelmholtzEquation_real_real : public MatrixFormVol < double >
{
public:
MatrixFormHelmholtzEquation_real_real(unsigned int i, unsigned int j, double eps, double omega, double mu)
: MatrixFormVol<double>(i, j), eps(eps), omega(omega), mu(mu) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Real> *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 eps;
double omega;
double mu;
};
class MatrixFormHelmholtzEquation_real_imag : public MatrixFormVol < double >
{
// Members.
double mu;
double omega;
double sigma;
public:
MatrixFormHelmholtzEquation_real_imag(unsigned int i, unsigned int j, double mu, double omega, double sigma)
: MatrixFormVol<double>(i, j), mu(mu), omega(omega), sigma(sigma) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Real> *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 MatrixFormHelmholtzEquation_imag_real : public MatrixFormVol < double >
{
// Members.
double mu;
double omega;
double sigma;
public:
MatrixFormHelmholtzEquation_imag_real(unsigned int i, unsigned int j, double mu, double omega, double sigma)
: MatrixFormVol<double>(i, j), mu(mu), omega(omega), sigma(sigma) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Real> *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 MatrixFormHelmholtzEquation_imag_imag : public MatrixFormVol < double >
{
public:
MatrixFormHelmholtzEquation_imag_imag(unsigned int i, unsigned int j, double eps, double mu, double omega)
: MatrixFormVol<double>(i, j), eps(eps), mu(mu), omega(omega) {};
template<typename Real, typename Scalar>
Scalar matrix_form(int n, double *wt, Func<Real> *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 eps;
double mu;
double omega;
};
class MatrixFormSurfHelmholtz_real_imag : public MatrixFormSurf < double >
{
private:
double beta;
public:
MatrixFormSurfHelmholtz_real_imag(unsigned int i, unsigned int j, std::string area, double beta)
: MatrixFormSurf<double>(i, j), beta(beta){ this->set_area(area); };
template<typename Real, typename Scalar>
Scalar matrix_form_surf(int n, double *wt, Func<Real> *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 MatrixFormSurfHelmholtz_imag_real : public MatrixFormSurf < double >
{
private:
double beta;
public:
MatrixFormSurfHelmholtz_imag_real(unsigned int i, unsigned int j, std::string area, double beta)
: MatrixFormSurf<double>(i, j), beta(beta){ this->set_area(area); };
template<typename Real, typename Scalar>
Scalar matrix_form_surf(int n, double *wt, Func<Real> *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 VectorFormHelmholtzEquation_real : public VectorFormVol < double >
{
public:
VectorFormHelmholtzEquation_real(int i, double eps, double omega, double mu, double sigma)
: VectorFormVol<double>(i), eps(eps), omega(omega), mu(mu), sigma(sigma) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Real> *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;
// Members.
double eps;
double omega;
double mu;
double sigma;
};
class VectorFormHelmholtzEquation_imag : public VectorFormVol < double >
{
public:
VectorFormHelmholtzEquation_imag(int i, double eps, double omega, double mu, double sigma)
: VectorFormVol<double>(i), eps(eps), omega(omega), mu(mu), sigma(sigma) {};
template<typename Real, typename Scalar>
Scalar vector_form(int n, double *wt, Func<Real> *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;
// Members.
double eps;
double omega;
double mu;
double sigma;
};
class VectorFormSurfHelmholtz_real : public VectorFormSurf < double >
{
private:
double beta;
public:
VectorFormSurfHelmholtz_real(int i, std::string area, double beta)
: VectorFormSurf<double>(i), beta(beta) { this->set_area(area); };
template<typename Real, typename Scalar>
Scalar vector_form_surf(int n, double *wt, Func<Real> *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;
VectorFormSurf<double>* clone() const;
};
class VectorFormSurfHelmholtz_imag : public VectorFormSurf < double >
{
private:
double beta;
public:
VectorFormSurfHelmholtz_imag(int i, std::string area, double beta)
: VectorFormSurf<double>(i), beta(beta) { this->set_area(area); };
template<typename Real, typename Scalar>
Scalar vector_form_surf(int n, double *wt, Func<Real> *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;
VectorFormSurf<double>* clone() const;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/helmholtz/waveguide/main.cpp | .cpp | 5,604 | 165 | #include "definitions.h"
// This example shows how to model harmonic steady state in parallel plate waveguide.
// The complex-valued Helmholtz equation is solved by decomposing it into two equations
// for the real and imaginary part of the E field. Two typical boundary conditions used in
// high-frequency problems are demonstrated.
//
// PDE: Helmholtz equation for electric field
//
// -Laplace E - omega^2*mu*epsilon*E + j*omega*sigma*mu*E = 0
//
// BC: Gamma_1 (perfect)
// ----------------------------
// Gamma_3 (left) | | Gamma_4 (impedance)
// ----------------------------
// Gamma_2 (perfect)
//
// 1) Perfect conductor boundary condition Ex = 0 on Gamma_1 and Gamma_2.
// 2) Essential (Dirichlet) boundary condition on Gamma_3
// Ex(y) = E_0 * cos(y*M_PI/h), where h is height of the waveguide.
// 3) Impedance boundary condition on Gamma_4
// dE/dn = j*beta*E.
//
// The following parameters can be changed:
// Initial polynomial degree of all elements.
const int P_INIT = 4;
// Number of initial mesh refinements.
const int INIT_REF_NUM = 3;
// Newton's method.
const double NEWTON_TOL = 1e-8;
const int NEWTON_MAX_ITER = 100;
// Problem parameters.
// Relative permittivity.
const double epsr = 1.0;
// Permittivity of vacuum F/m.
const double eps0 = 8.85418782e-12;
const double eps = epsr * eps0;
// Relative permeablity.
const double mur = 1.0;
// Permeability of vacuum H/m.
const double mu0 = 4 * M_PI*1e-7;
const double mu = mur * mu0;
// Frequency MHz.
double frequency = 12e9;
// Angular velocity.
double omega = 2 * M_PI * frequency;
// Conductivity Ohm/m.
const double sigma = 0;
// Propagation constant.
const double beta = 54;
// Input electric intensity.
const double E0 = 100;
// Height of waveguide.
const double h = 1.0;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2DXML mloader;
mloader.load("initial.xml", mesh);
// Show the mesh.
MeshView m_view;
m_view.show(mesh);
// Refine the mesh.
mesh->refine_all_elements();
// Initialize boundary conditions
DefaultEssentialBCConst<double> bc1({ "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" }, 0.0);
EssentialBCNonConst bc2("1");
DefaultEssentialBCConst<double> bc3("1", 0.0);
EssentialBCs<double> bcs({ &bc1, &bc2 });
EssentialBCs<double> bcs_im({ &bc1, &bc3 });
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> e_r_space(new H1Space<double>(mesh, &bcs, P_INIT));
SpaceSharedPtr<double> e_i_space(new H1Space<double>(mesh, &bcs_im, P_INIT));
int ndof = Space<double>::get_num_dofs(e_r_space);
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new WeakFormHelmholtz(eps, mu, omega, sigma, beta, E0, h));
wf->set_verbose_output(false);
// Initialize the FE problem.
std::vector<SpaceSharedPtr<double> > spaces({ e_r_space, e_i_space });
// Initialize the solutions.
MeshFunctionSharedPtr<double> e_r_sln(new Solution<double>), e_i_sln(new Solution<double>);
// Initial coefficient vector for the Newton's method.
ndof = Space<double>::get_num_dofs({ e_r_space, e_i_space });
Hermes::Hermes2D::NewtonSolver<double> newton(wf, spaces);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
ScalarView viewEr("Er [V/m]", new WinGeom(600, 0, 700, 200));
viewEr.get_linearizer()->set_criterion(LinearizerCriterionFixed(2));
viewEr.show_mesh(false);
ScalarView viewEi("Ei [V/m]", new WinGeom(600, 220, 700, 200));
viewEi.get_linearizer()->set_criterion(LinearizerCriterionFixed(2));
ScalarView viewMagnitude("Magnitude of E [V/m]", new WinGeom(30, 30, 1000, 350));
viewMagnitude.show_mesh(false);
//viewMagnitude.show_contours(200., 0.);
viewMagnitude.get_linearizer()->set_criterion(LinearizerCriterionFixed(2));
int it = 1;
while (true)
{
std::cout << "Frequency: " << frequency << " Hz" << std::endl;
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 Solutions.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), { e_r_space, e_i_space }, { e_r_sln, e_i_sln });
// Visualize the solution.
//viewEr.show(e_r_sln);
//viewEr.save_numbered_screenshot("real_part%i.bmp", it, true);
//viewEi.show(e_i_sln);
//viewEi.save_numbered_screenshot("imaginary_part%i.bmp", it, true);
MeshFunctionSharedPtr<double> magnitude(new MagFilter<double>(std::vector<MeshFunctionSharedPtr<double> >({ e_r_sln, e_i_sln })));
viewMagnitude.show(magnitude);
viewMagnitude.save_numbered_screenshot("magnitude%i.bmp", it, true);
char* change_state = new char[1000];
std::cout << "Done?";
std::cin >> change_state;
if (!strcmp(change_state, "y"))
break;
std::cout << std::endl;
std::cout << "Frequency change [1e9 Hz]: ";
double frequency_change;
std::cin.sync();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.sync();
std::cin >> frequency_change;
frequency += 1e9 * frequency_change;
omega = 2 * M_PI * frequency;
((WeakFormHelmholtz*)(wf.get()))->set_parameters(eps, mu, omega, sigma, beta, E0, h);
newton.set_weak_formulation(wf);
it++;
}
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/helmholtz/waveguide/definitions.cpp | .cpp | 11,360 | 285 | #include "definitions.h"
EssentialBCNonConst::EssentialBCNonConst(std::string marker)
: EssentialBoundaryCondition<double>(std::vector<std::string>())
{
markers.push_back(marker);
}
EssentialBCValueType EssentialBCNonConst::get_value_type() const
{
return BC_FUNCTION;
}
double EssentialBCNonConst::value(double x, double y) const
{
return 100 * std::cos(y*M_PI / 0.1);
}
WeakFormHelmholtz::WeakFormHelmholtz(double eps, double mu, double omega, double sigma, double beta,
double E0, double h) : WeakForm<double>(2)
{
// Jacobian.
add_matrix_form(new MatrixFormHelmholtzEquation_real_real(0, 0, eps, omega, mu));
add_matrix_form(new MatrixFormHelmholtzEquation_real_imag(0, 1, mu, omega, sigma));
add_matrix_form(new MatrixFormHelmholtzEquation_imag_real(1, 0, mu, omega, sigma));
add_matrix_form(new MatrixFormHelmholtzEquation_imag_imag(1, 1, eps, mu, omega));
add_matrix_form_surf(new MatrixFormSurfHelmholtz_real_imag(0, 1, "0", beta));
add_matrix_form_surf(new MatrixFormSurfHelmholtz_imag_real(1, 0, "0", beta));
// Residual.
add_vector_form(new VectorFormHelmholtzEquation_real(0, eps, omega, mu, sigma));
add_vector_form(new VectorFormHelmholtzEquation_imag(1, eps, omega, mu, sigma));
add_vector_form_surf(new VectorFormSurfHelmholtz_real(0, "0", beta));
add_vector_form_surf(new VectorFormSurfHelmholtz_imag(1, "0", beta));
}
/* Jacobian forms */
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_real::matrix_form(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
return int_grad_u_grad_v<Real, Scalar>(n, wt, u, v) - sqr(omega) * mu * eps * int_u_v<Real, Scalar>(n, wt, u, v);
}
double WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_real::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 WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_real::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>* WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_real::clone() const
{
return new WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_real(*this);
}
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_imag::matrix_form(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
return -omega * mu * sigma * int_u_v<Real, Scalar>(n, wt, u, v);
}
double WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_imag::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 WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_imag::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>* WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_imag::clone() const
{
return new WeakFormHelmholtz::MatrixFormHelmholtzEquation_real_imag(*this);
}
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_real::matrix_form(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
return omega * mu * sigma * int_u_v<Real, Scalar>(n, wt, u, v);
}
double WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_real::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 WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_real::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>* WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_real::clone() const
{
return new WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_real(*this);
}
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_imag::matrix_form(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
return int_grad_u_grad_v<Real, Scalar>(n, wt, u, v) - sqr(omega) * mu * eps * int_u_v<Real, Scalar>(n, wt, u, v);
}
double WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_imag::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 WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_imag::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>* WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_imag::clone() const
{
return new WeakFormHelmholtz::MatrixFormHelmholtzEquation_imag_imag(*this);
}
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::MatrixFormSurfHelmholtz_real_imag::matrix_form_surf(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, GeomSurf<Real> *e, Func<Scalar>* *ext) const
{
return beta * int_u_v<Real, Scalar>(n, wt, u, v);
}
double WeakFormHelmholtz::MatrixFormSurfHelmholtz_real_imag::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_surf<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord WeakFormHelmholtz::MatrixFormSurfHelmholtz_real_imag::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_surf<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormSurf<double>* WeakFormHelmholtz::MatrixFormSurfHelmholtz_real_imag::clone() const
{
return new WeakFormHelmholtz::MatrixFormSurfHelmholtz_real_imag(*this);
}
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::MatrixFormSurfHelmholtz_imag_real::matrix_form_surf(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *u, Func<Real> *v, GeomSurf<Real> *e, Func<Scalar>* *ext) const
{
return -beta*int_u_v<Real, Scalar>(n, wt, u, v);
}
double WeakFormHelmholtz::MatrixFormSurfHelmholtz_imag_real::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_surf<double, double>(n, wt, u_ext, u, v, e, ext);
}
Ord WeakFormHelmholtz::MatrixFormSurfHelmholtz_imag_real::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_surf<Ord, Ord>(n, wt, u_ext, u, v, e, ext);
}
MatrixFormSurf<double>* WeakFormHelmholtz::MatrixFormSurfHelmholtz_imag_real::clone() const
{
return new WeakFormHelmholtz::MatrixFormSurfHelmholtz_imag_real(*this);
}
/* Residual forms */
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::VectorFormHelmholtzEquation_real::vector_form(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
return int_grad_u_grad_v<Real, Scalar>(n, wt, u_ext[0], v)
- sqr(omega) * mu * eps * int_u_v<Real, Scalar>(n, wt, u_ext[0], v)
- omega * mu * sigma * int_u_v<Real, Scalar>(n, wt, u_ext[1], v);
}
double WeakFormHelmholtz::VectorFormHelmholtzEquation_real::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 WeakFormHelmholtz::VectorFormHelmholtzEquation_real::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>* WeakFormHelmholtz::VectorFormHelmholtzEquation_real::clone() const
{
return new WeakFormHelmholtz::VectorFormHelmholtzEquation_real(*this);
}
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::VectorFormHelmholtzEquation_imag::vector_form(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *v, GeomVol<Real> *e, Func<Scalar>* *ext) const
{
return omega * mu * sigma * int_u_v<Real, Scalar>(n, wt, u_ext[0], v)
- sqr(omega) * mu * eps * int_u_v<Real, Scalar>(n, wt, u_ext[1], v)
+ int_grad_u_grad_v<Real, Scalar>(n, wt, u_ext[1], v);
}
double WeakFormHelmholtz::VectorFormHelmholtzEquation_imag::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 WeakFormHelmholtz::VectorFormHelmholtzEquation_imag::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>* WeakFormHelmholtz::VectorFormHelmholtzEquation_imag::clone() const
{
return new WeakFormHelmholtz::VectorFormHelmholtzEquation_imag(*this);
}
// Surface vector forms.
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::VectorFormSurfHelmholtz_real::vector_form_surf(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *v, GeomSurf<Real> *e, Func<Scalar>* *ext) const
{
return beta * int_u_v<Real, Scalar>(n, wt, u_ext[1], v);
}
double WeakFormHelmholtz::VectorFormSurfHelmholtz_real::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 WeakFormHelmholtz::VectorFormSurfHelmholtz_real::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
return vector_form_surf<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormSurf<double>* WeakFormHelmholtz::VectorFormSurfHelmholtz_real::clone() const
{
return new WeakFormHelmholtz::VectorFormSurfHelmholtz_real(*this);
}
template<typename Real, typename Scalar>
Scalar WeakFormHelmholtz::VectorFormSurfHelmholtz_imag::vector_form_surf(int n, double *wt,
Func<Real> *u_ext[], Func<Real> *v, GeomSurf<Real> *e, Func<Scalar>* *ext) const
{
return -beta*int_u_v<Real, Scalar>(n, wt, u_ext[0], v);
}
double WeakFormHelmholtz::VectorFormSurfHelmholtz_imag::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 WeakFormHelmholtz::VectorFormSurfHelmholtz_imag::ord(int n, double *wt, Func<Ord> *u_ext[],
Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord>* *ext) const
{
return vector_form_surf<Ord, Ord>(n, wt, u_ext, v, e, ext);
}
VectorFormSurf<double>* WeakFormHelmholtz::VectorFormSurfHelmholtz_imag::clone() const
{
return new WeakFormHelmholtz::VectorFormSurfHelmholtz_imag(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/maxwell-debye-rk/definitions.h | .h | 7,507 | 222 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Global function alpha */
double alpha(double omega, double k);
/* Initial condition for E */
class CustomInitialConditionE : public ExactSolutionVector < double >
{
public:
CustomInitialConditionE(MeshSharedPtr mesh, double time, double omega, double k_x, double k_y)
: ExactSolutionVector<double>(mesh), time(time), omega(omega), k_x(k_x), k_y(k_y) {};
virtual Scalar2<double> value(double x, double y) const;
virtual void derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const;
virtual Ord ord(double x, double y) const;
virtual MeshFunction<double>* clone() const { return new CustomInitialConditionE(mesh, time, omega, k_x, k_y); }
double time, omega, k_x, k_y;
};
/* Initial condition for H */
class CustomInitialConditionH : public ExactSolutionScalar < double >
{
public:
CustomInitialConditionH(MeshSharedPtr mesh, double time, double omega, double k_x, double k_y)
: ExactSolutionScalar<double>(mesh), time(time), omega(omega), k_x(k_x), k_y(k_y) {};
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 { return new CustomInitialConditionH(mesh, time, omega, k_x, k_y); }
double time, omega, k_x, k_y;
};
/* Initial condition for P */
class CustomInitialConditionP : public ExactSolutionVector < double >
{
public:
CustomInitialConditionP(MeshSharedPtr mesh, double time, double omega, double k_x, double k_y)
: ExactSolutionVector<double>(mesh), time(time), omega(omega), k_x(k_x), k_y(k_y) {};
virtual Scalar2<double> value(double x, double y) const;
virtual void derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const;
virtual Ord ord(double x, double y) const;
virtual MeshFunction<double>* clone() const { return new CustomInitialConditionP(mesh, time, omega, k_x, k_y); }
double time, omega, k_x, k_y;
};
/* Weak forms */
class CustomWeakFormMD : public WeakForm < double >
{
public:
CustomWeakFormMD(double omega, double k_x, double k_y, double mu_0,
double eps_0, double eps_inf, double eps_q, double tau);
private:
class MatrixFormVolMD_0_0 : public MatrixFormVol < double >
{
public:
MatrixFormVolMD_0_0(double eps_q, double tau)
: MatrixFormVol<double>(0, 0), eps_q(eps_q), tau(tau) {};
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;
double eps_q, tau;
};
class MatrixFormVolMD_0_1 : public MatrixFormVol < double >
{
public:
MatrixFormVolMD_0_1(double eps_0, double eps_inf) : MatrixFormVol<double>(0, 1), eps_0(eps_0), eps_inf(eps_inf) {};
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;
double eps_0, eps_inf;
};
class MatrixFormVolMD_0_2 : public MatrixFormVol < double >
{
public:
MatrixFormVolMD_0_2(double eps_0, double eps_inf, double tau) : MatrixFormVol<double>(0, 2), eps_0(eps_0), eps_inf(eps_inf), tau(tau) {};
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;
double eps_0, eps_inf, tau;
};
class MatrixFormVolMD_1_0 : public MatrixFormVol < double >
{
public:
MatrixFormVolMD_1_0(double mu_0) : MatrixFormVol<double>(1, 0), mu_0(mu_0) {};
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;
double mu_0;
};
class MatrixFormVolMD_2_0 : public MatrixFormVol < double >
{
public:
MatrixFormVolMD_2_0(double eps_0, double eps_inf, double eps_q, double tau) : MatrixFormVol<double>(2, 0), eps_0(eps_0), eps_inf(eps_inf), eps_q(eps_q), tau(tau) {};
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;
double eps_0, eps_inf, eps_q, tau;
};
class MatrixFormVolMD_2_2 : public MatrixFormVol < double >
{
public:
MatrixFormVolMD_2_2(double tau) : MatrixFormVol<double>(2, 2), tau(tau) {};
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;
double tau;
};
class VectorFormVolMD_0 : public VectorFormVol < double >
{
public:
VectorFormVolMD_0(double eps_0, double eps_inf, double eps_q, double tau) : VectorFormVol<double>(0), eps_0(eps_0), eps_inf(eps_inf), eps_q(eps_q), tau(tau) {};
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 eps_0, eps_inf, eps_q, tau;
};
class VectorFormVolMD_1 : public VectorFormVol < double >
{
public:
VectorFormVolMD_1(double mu_0) : VectorFormVol<double>(1), mu_0(mu_0) {};
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 mu_0;
};
class VectorFormVolMD_2 : public VectorFormVol < double >
{
public:
VectorFormVolMD_2(double eps_0, double eps_inf, double eps_q, double tau) : VectorFormVol<double>(2), eps_0(eps_0), eps_inf(eps_inf), eps_q(eps_q), tau(tau) {};
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 eps_0, eps_inf, eps_q, tau;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/maxwell-debye-rk/main.cpp | .cpp | 15,007 | 348 | #include "definitions.h"
// This example is a simple test case for the Debye-Maxwell model solved in terms of
// E, H and P. Here E is electric field (vector), H magnetic field (scalar), and P
// electric polarization (vector). The example comes with a known exact solution.
// Time discretization is performed using an arbitrary Runge-Kutta method.
//
// PDE system:
//
// \frac{partial H}{\partial t} + \frac{1}{\mu_0} \curl E = 0,
// \frac{\partial E}{\partial t} - \frac{1}{\epsilon_0 \epsilon_\infty} \curl H
// + \frac{\epsilon_q - 1}{\tau}E - \frac{1}{\tau} P = 0,
// \frac{\partial P}{\partial t} - \frac{(\epsilon_q - 1)\epsilon_0 \epsilon_\infty}{\tau} E
// + \frac{1}{\tau} P = 0.
//
// Domain: Square (0, 1) x (0, 1).
//
// BC: Perfect conductor for E and P.
//
// IC: Prescribed functions for E, H and P.
//
// 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 = 2;
// Time step.
const double time_step = 0.00001;
// Final time.
const double T_FINAL = 35.0;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-4;
// 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 = Implicit_RK_1;
//ButcherTableType butcher_table = Implicit_SDIRK_2_2;
// 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.5;
// Error calculation & adaptivity.
class CustomErrorCalculator : public ErrorCalculator < double >
{
public:
// Two first components are in the H1 space - we can use the classic class for that, for the last component, we will manually add the L2 norm for pressure.
CustomErrorCalculator(CalculatedErrorType errorType) : ErrorCalculator<double>(errorType)
{
this->add_error_form(new DefaultNormFormVol<double>(0, 0, HERMES_HCURL_NORM, Hermes::Hermes2D::SolutionsDifference));
this->add_error_form(new DefaultNormFormVol<double>(1, 1, HERMES_H1_NORM, Hermes::Hermes2D::SolutionsDifference));
this->add_error_form(new DefaultNormFormVol<double>(2, 2, HERMES_HCURL_NORM, Hermes::Hermes2D::SolutionsDifference));
}
} errorCalculator(RelativeErrorToGlobalNorm);
// 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.
// Permeability of free space.
const double MU_0 = 1.0;
// Permittivity of free space.
const double EPS_0 = 1.0;
// Permittivity at infinite frequency.
const double EPS_INF = 1.0;
// Permittivity at zero frequency.
const double EPS_S = 2.0;
// EPS_Q.
const double EPS_Q = EPS_S / EPS_INF;
// Relaxation time of the medium.
const double TAU = 1.0;
// Angular frequency. Depends on wave number K. Must satisfy:
// omega^3 - 2 omega^2 + K^2 M_PI^2 omega - K^2 M_PI^2 = 0.
// WARNING; Choosing wrong omega may lead to K**2 < 0.
const double OMEGA = 1.5;
// Wave vector direction (will be normalized to be compatible
// with omega).
double K_x = 1.0;
double K_y = 1.0;
int main(int argc, char* argv[])
{
try
{
// Sanity check for omega.
double K_squared = Hermes::sqr(OMEGA / M_PI) * (OMEGA - 2) / (1 - OMEGA);
if (K_squared <= 0) throw Hermes::Exceptions::Exception("Wrong choice of omega, K_squared < 0!");
double K_norm_coeff = std::sqrt(K_squared) / std::sqrt(Hermes::sqr(K_x) + Hermes::sqr(K_y));
Hermes::Mixins::Loggable::Static::info("Wave number K = %g", std::sqrt(K_squared));
K_x *= K_norm_coeff;
K_y *= K_norm_coeff;
// Wave number.
double K = std::sqrt(Hermes::sqr(K_x) + Hermes::sqr(K_y));
// Choose a Butcher's table or define your own.
ButcherTable bt(butcher_table);
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 E_mesh(new Mesh), H_mesh(new Mesh), P_mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", E_mesh);
mloader.load("domain.mesh", H_mesh);
mloader.load("domain.mesh", P_mesh);
// Perform initial mesh refinemets.
for (int i = 0; i < INIT_REF_NUM; i++)
{
E_mesh->refine_all_elements();
H_mesh->refine_all_elements();
P_mesh->refine_all_elements();
}
// Initialize solutions.
double current_time = 0;
MeshFunctionSharedPtr<double> E_time_prev(new CustomInitialConditionE(E_mesh, current_time, OMEGA, K_x, K_y));
MeshFunctionSharedPtr<double> H_time_prev(new CustomInitialConditionH(H_mesh, current_time, OMEGA, K_x, K_y));
MeshFunctionSharedPtr<double> P_time_prev(new CustomInitialConditionP(P_mesh, current_time, OMEGA, K_x, K_y));
std::vector<MeshFunctionSharedPtr<double> > slns_time_prev({ E_time_prev, H_time_prev, P_time_prev });
MeshFunctionSharedPtr<double> E_time_new(new Solution<double>(E_mesh)), H_time_new(new Solution<double>(H_mesh)), P_time_new(new Solution<double>(P_mesh));
MeshFunctionSharedPtr<double> E_time_new_coarse(new Solution<double>(E_mesh)), H_time_new_coarse(new Solution<double>(H_mesh)), P_time_new_coarse(new Solution<double>(P_mesh));
std::vector<MeshFunctionSharedPtr<double> > slns_time_new({ E_time_new, H_time_new, P_time_new });
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormMD(OMEGA, K_x, K_y, MU_0, EPS_0, EPS_INF, EPS_Q, TAU));
// Initialize boundary conditions
DefaultEssentialBCConst<double> bc_essential("Bdy", 0.0);
EssentialBCs<double> bcs(&bc_essential);
SpaceSharedPtr<double> E_space(new HcurlSpace<double>(E_mesh, &bcs, P_INIT));
SpaceSharedPtr<double> H_space(new H1Space<double>(H_mesh, NULL, P_INIT));
//L2Space<double> H_space(mesh, P_INIT));
SpaceSharedPtr<double> P_space(new HcurlSpace<double>(P_mesh, &bcs, P_INIT));
std::vector<SpaceSharedPtr<double> > spaces = std::vector<SpaceSharedPtr<double> >({ E_space, H_space, P_space });
// Initialize views.
ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350));
E1_view.fix_scale_width(50);
ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350));
E2_view.fix_scale_width(50);
ScalarView H_view("Solution H", new WinGeom(0, 410, 400, 350));
H_view.fix_scale_width(50);
ScalarView P1_view("Solution P1", new WinGeom(410, 410, 400, 350));
P1_view.fix_scale_width(50);
ScalarView P2_view("Solution P2", new WinGeom(820, 410, 400, 350));
P2_view.fix_scale_width(50);
// Visualize initial conditions.
char title[100];
sprintf(title, "E1 - Initial Condition");
E1_view.set_title(title);
E1_view.show(E_time_prev, H2D_FN_VAL_0);
sprintf(title, "E2 - Initial Condition");
E2_view.set_title(title);
E2_view.show(E_time_prev, H2D_FN_VAL_1);
sprintf(title, "H - Initial Condition");
H_view.set_title(title);
H_view.show(H_time_prev);
sprintf(title, "P1 - Initial Condition");
P1_view.set_title(title);
P1_view.show(P_time_prev, H2D_FN_VAL_0);
sprintf(title, "P2 - Initial Condition");
P2_view.set_title(title);
P2_view.show(P_time_prev, H2D_FN_VAL_1);
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, spaces, &bt);
runge_kutta.set_newton_max_allowed_iterations(NEWTON_MAX_ITER);
runge_kutta.set_newton_tolerance(NEWTON_TOL);
runge_kutta.set_verbose_output(true);
// Initialize refinement selector.
H1ProjBasedSelector<double> H1selector(CAND_LIST);
HcurlProjBasedSelector<double> HcurlSelector(CAND_LIST);
// Time stepping loop.
int ts = 1;
do
{
// Perform one Runge-Kutta time step according to the selected Butcher's table.
Hermes::Mixins::Loggable::Static::info("\nRunge-Kutta time step (t = %g s, time_step = %g s, stages: %d).",
current_time, time_step, bt.get_size());
// Periodic global derefinements.
if (ts > 1 && ts % UNREF_FREQ == 0 && REFINEMENT_COUNT > 0)
{
Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
REFINEMENT_COUNT = 0;
E_space->unrefine_all_mesh_elements(true);
H_space->unrefine_all_mesh_elements(true);
P_space->unrefine_all_mesh_elements(true);
E_space->adjust_element_order(-1, P_INIT);
H_space->adjust_element_order(-1, P_INIT);
P_space->adjust_element_order(-1, P_INIT);
E_space->assign_dofs();
H_space->assign_dofs();
P_space->assign_dofs();
}
// 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.
int order_increase = 1;
Mesh::ReferenceMeshCreator refMeshCreatorE(E_mesh);
Mesh::ReferenceMeshCreator refMeshCreatorH(H_mesh);
Mesh::ReferenceMeshCreator refMeshCreatorP(P_mesh);
MeshSharedPtr ref_mesh_E = refMeshCreatorE.create_ref_mesh();
MeshSharedPtr ref_mesh_H = refMeshCreatorH.create_ref_mesh();
MeshSharedPtr ref_mesh_P = refMeshCreatorP.create_ref_mesh();
Space<double>::ReferenceSpaceCreator refSpaceCreatorE(E_space, ref_mesh_E, order_increase);
SpaceSharedPtr<double> ref_space_E = refSpaceCreatorE.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorH(H_space, ref_mesh_H, order_increase);
SpaceSharedPtr<double> ref_space_H = refSpaceCreatorH.create_ref_space();
Space<double>::ReferenceSpaceCreator refSpaceCreatorP(P_space, ref_mesh_P, order_increase);
SpaceSharedPtr<double> ref_space_P = refSpaceCreatorP.create_ref_space();
std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_space_E, ref_space_H, ref_space_P });
int ndof = Space<double>::get_num_dofs(ref_spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
try
{
runge_kutta.set_spaces(ref_spaces);
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
runge_kutta.rk_time_step_newton(slns_time_prev, slns_time_new);
}
catch (Exceptions::Exception& e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
}
// Visualize the solutions.
char title[100];
sprintf(title, "E1, t = %g", current_time + time_step);
E1_view.set_title(title);
E1_view.show(E_time_new, H2D_FN_VAL_0);
sprintf(title, "E2, t = %g", current_time + time_step);
E2_view.set_title(title);
E2_view.show(E_time_new, H2D_FN_VAL_1);
sprintf(title, "H, t = %g", current_time + time_step);
H_view.set_title(title);
H_view.show(H_time_new);
sprintf(title, "P1, t = %g", current_time + time_step);
P1_view.set_title(title);
P1_view.show(P_time_new, H2D_FN_VAL_0);
sprintf(title, "P2, t = %g", current_time + time_step);
P2_view.set_title(title);
P2_view.show(P_time_new, H2D_FN_VAL_1);
// Project the fine mesh solution onto the coarse mesh.
Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
OGProjection<double>::project_global({ E_space, H_space, P_space }, { E_time_new, H_time_new, P_time_new }, { E_time_new_coarse, H_time_new_coarse, P_time_new_coarse });
// Calculate element errors and total error estimate.
Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
adaptivity.set_spaces({ E_space, H_space, P_space });
errorCalculator.calculate_errors({ E_time_new_coarse, H_time_new_coarse, P_time_new_coarse }, { E_time_new, H_time_new, P_time_new });
double err_est_rel_total = errorCalculator.get_total_error_squared() * 100.;
// Report results.
Hermes::Mixins::Loggable::Static::info("Error estimate: %g%%", err_est_rel_total);
// If err_est too large, adapt the mesh.
if (err_est_rel_total < ERR_STOP)
{
Hermes::Mixins::Loggable::Static::info("Error estimate under the specified threshold -> moving to next time step.");
done = true;
}
else
{
Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
REFINEMENT_COUNT++;
done = adaptivity.adapt({ &HcurlSelector, &H1selector, &HcurlSelector });
if (!done)
as++;
}
} while (!done);
//View::wait();
E_time_prev->copy(E_time_new);
H_time_prev->copy(H_time_new);
P_time_prev->copy(P_time_new);
// Update time.
current_time += time_step;
ts++;
} while (current_time < T_FINAL);
// Wait for the view to be closed.
View::wait();
}
catch (std::exception& e)
{
std::cout << e.what();
}
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/maxwell-debye-rk/definitions.cpp | .cpp | 11,472 | 325 | #include "definitions.h"
template<typename Real, typename Scalar>
static Scalar int_e_f(int n, double *wt, Func<Real> *u, Func<Real> *v)
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += wt[i] * (u->val0[i] * conj(v->val0[i]) + u->val1[i] * conj(v->val1[i]));
return result;
}
/* Global function alpha */
double alpha(double omega, double k)
{
return Hermes::sqr(omega) - omega + Hermes::sqr(k) * Hermes::sqr(M_PI);
}
// **************
Scalar2<double> CustomInitialConditionE::value(double x, double y) const
{
double val_0 = -omega*k_y*exp(-omega*time) * std::cos(k_x * M_PI * x) * std::sin(k_y * M_PI * y);
double val_1 = omega*k_x*exp(-omega*time) * std::sin(k_x * M_PI * x) * std::cos(k_y * M_PI * y);
return Scalar2<double>(val_0, val_1);
}
void CustomInitialConditionE::derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const
{
dx[0] = -omega*k_y*exp(-omega*time) * (-1.0*std::sin(k_x * M_PI * x)*k_x*M_PI) * std::sin(k_y * M_PI * y);
dx[1] = omega*k_x*exp(-omega*time) * std::cos(k_x * M_PI * x)*k_x*M_PI * std::cos(k_y * M_PI * y);
dy[0] = -omega*k_y*exp(-omega*time) * std::cos(k_x * M_PI * x) * std::cos(k_y * M_PI * y)*k_y*M_PI;
dy[1] = omega*k_x*exp(-omega*time) * std::sin(k_x * M_PI * x) * (-1.0*std::sin(k_y * M_PI * y)*k_y*M_PI);
}
Ord CustomInitialConditionE::ord(double x, double y) const
{
return Ord(20);
}
// **************
double CustomInitialConditionH::value(double x, double y) const
{
double k_squared = Hermes::sqr(k_x) + Hermes::sqr(k_y);
return k_squared * M_PI * exp(-omega*time) * std::cos(k_x * M_PI * x) * std::cos(k_y * M_PI * y);
}
void CustomInitialConditionH::derivatives(double x, double y, double& dx, double& dy) const
{
double k_squared = Hermes::sqr(k_x) + Hermes::sqr(k_y);
dx = k_squared * M_PI * exp(-omega*time) * (-1.0*std::sin(k_x * M_PI * x)*k_x*M_PI) * std::cos(k_y * M_PI * y);
dy = k_squared * M_PI * exp(-omega*time) * std::cos(k_x * M_PI * x) * (-1.0*std::sin(k_y * M_PI * y)*k_y*M_PI);
}
Ord CustomInitialConditionH::ord(double x, double y) const
{
return Ord(20);
}
// **************
Scalar2<double> CustomInitialConditionP::value(double x, double y) const
{
double k_squared = Hermes::sqr(k_x) + Hermes::sqr(k_y);
double k = std::sqrt(k_squared);
double val_0 = alpha(omega, k)*k_y*exp(-omega*time) * std::cos(k_x * M_PI * x) * std::sin(k_y * M_PI * y);
double val_1 = -k_x*alpha(omega, k)*exp(-omega*time) * std::sin(k_x * M_PI * x) * std::cos(k_y * M_PI * y);
return Scalar2<double>(val_0, val_1);
}
void CustomInitialConditionP::derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const
{
double k_squared = std::abs(Hermes::sqr(k_x) + Hermes::sqr(k_y));
double k = std::sqrt(k_squared);
dx[0] = alpha(omega, k)*k_y*exp(-omega*time) * (-1.0*std::sin(k_x * M_PI * x)*k_x*M_PI) * std::sin(k_y * M_PI * y);
dx[1] = -k_x*alpha(omega, k)*exp(-omega*time) * std::cos(k_x * M_PI * x)*k_x*M_PI * std::cos(k_y * M_PI * y);
dy[0] = alpha(omega, k)*k_y*exp(-omega*time) * std::cos(k_x * M_PI * x) * std::cos(k_y * M_PI * y)*k_y*M_PI;
dy[1] = -k_x*alpha(omega, k)*exp(-omega*time) * std::sin(k_x * M_PI * x) * (-1.0*std::sin(k_y * M_PI * y)*k_y*M_PI);
}
Ord CustomInitialConditionP::ord(double x, double y) const
{
return Ord(20);
}
// **************
CustomWeakFormMD::CustomWeakFormMD(double omega, double k_x, double k_y, double mu_0,
double eps_0, double eps_inf, double eps_q, double tau) : WeakForm<double>(3)
{
// Stationary Jacobian.
add_matrix_form(new MatrixFormVolMD_0_0(eps_q, tau));
add_matrix_form(new MatrixFormVolMD_0_1(eps_0, eps_inf));
add_matrix_form(new MatrixFormVolMD_0_2(eps_0, eps_inf, tau));
add_matrix_form(new MatrixFormVolMD_1_0(mu_0));
add_matrix_form(new MatrixFormVolMD_2_0(eps_0, eps_inf, eps_q, tau));
add_matrix_form(new MatrixFormVolMD_2_2(tau));
// Stationary Residual.
add_vector_form(new VectorFormVolMD_0(eps_0, eps_inf, eps_q, tau));
add_vector_form(new VectorFormVolMD_1(mu_0));
add_vector_form(new VectorFormVolMD_2(eps_0, eps_inf, eps_q, tau));
}
// **************
double CustomWeakFormMD::MatrixFormVolMD_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 -(eps_q - 1) / tau * int_e_f<double, double>(n, wt, u, v);
}
Ord CustomWeakFormMD::MatrixFormVolMD_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 -(eps_q - 1) / tau * int_e_f<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* CustomWeakFormMD::MatrixFormVolMD_0_0::clone() const
{
return new MatrixFormVolMD_0_0(*this);
}
// **************
double CustomWeakFormMD::MatrixFormVolMD_0_1::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;
// int \curl u \dot v
for (int i = 0; i < n; i++)
{
result += wt[i] * (-u->dy[i] * v->val0[i] + u->dx[i] * v->val1[i]);
}
return result * (1.0 / eps_0 / eps_inf);
}
Ord CustomWeakFormMD::MatrixFormVolMD_0_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-u->dy[i] * v->val0[i] + u->dx[i] * v->val1[i]);
}
return result * (1.0 / eps_0 / eps_inf);
}
MatrixFormVol<double>* CustomWeakFormMD::MatrixFormVolMD_0_1::clone() const
{
return new MatrixFormVolMD_0_1(*this);
}
// **************
double CustomWeakFormMD::MatrixFormVolMD_0_2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return (1.0 / eps_0 / eps_inf / tau) * int_e_f<double, double>(n, wt, u, v);
}
Ord CustomWeakFormMD::MatrixFormVolMD_0_2::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return (1.0 / eps_0 / eps_inf / tau) * int_e_f<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* CustomWeakFormMD::MatrixFormVolMD_0_2::clone() const
{
return new MatrixFormVolMD_0_2(*this);
}
// **************
double CustomWeakFormMD::MatrixFormVolMD_1_0::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;
// int \curl u \dot v
for (int i = 0; i < n; i++)
{
result += wt[i] * (u->curl[i] * v->val[i]);
}
return result * (-1.0 / mu_0);
}
Ord CustomWeakFormMD::MatrixFormVolMD_1_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Ord result = Ord(0);
// int \curl u \dot v
for (int i = 0; i < n; i++)
{
result += wt[i] * (u->curl[i] * v->val[i]);
}
return result * (-1.0 / mu_0);
}
MatrixFormVol<double>* CustomWeakFormMD::MatrixFormVolMD_1_0::clone() const
{
return new MatrixFormVolMD_1_0(*this);
}
// **************
double CustomWeakFormMD::MatrixFormVolMD_2_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return (eps_q - 1)*eps_0*eps_inf / tau * int_e_f<double, double>(n, wt, u, v);
}
Ord CustomWeakFormMD::MatrixFormVolMD_2_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return (eps_q - 1)*eps_0*eps_inf / tau * int_e_f<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* CustomWeakFormMD::MatrixFormVolMD_2_0::clone() const
{
return new MatrixFormVolMD_2_0(*this);
}
// **************
double CustomWeakFormMD::MatrixFormVolMD_2_2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return (-1.0 / tau) * int_e_f<double, double>(n, wt, u, v);
}
Ord CustomWeakFormMD::MatrixFormVolMD_2_2::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return (-1.0 / tau) * int_e_f<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* CustomWeakFormMD::MatrixFormVolMD_2_2::clone() const
{
return new MatrixFormVolMD_2_2(*this);
}
// **************
double CustomWeakFormMD::VectorFormVolMD_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
Func<double>* E_prev_newton = u_ext[0];
Func<double>* H_prev_newton = u_ext[1];
Func<double>* P_prev_newton = u_ext[2];
double int_curl_H_v = 0;
for (int i = 0; i < n; i++)
{
int_curl_H_v += wt[i] * (-H_prev_newton->dy[i] * v->val0[i] + H_prev_newton->dx[i] * v->val1[i]);
}
return -(eps_q - 1) / tau * int_e_f<double, double>(n, wt, E_prev_newton, v)
+ (1.0 / eps_0 / eps_inf) * int_curl_H_v
+ (1.0 / eps_0 / eps_inf / tau) * int_e_f<double, double>(n, wt, P_prev_newton, v);
}
Ord CustomWeakFormMD::VectorFormVolMD_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Func<Ord>* E_prev_newton = u_ext[0];
Func<Ord>* H_prev_newton = u_ext[1];
Func<Ord>* P_prev_newton = u_ext[2];
Ord int_curl_H_v = Ord(0);
for (int i = 0; i < n; i++)
{
int_curl_H_v += wt[i] * (-H_prev_newton->dy[i] * v->val0[i] + H_prev_newton->dx[i] * v->val1[i]);
}
return -(eps_q - 1) / tau * int_e_f<Ord, Ord>(n, wt, E_prev_newton, v)
+ (1.0 / eps_0 / eps_inf) * int_curl_H_v
+ (1.0 / eps_0 / eps_inf / tau) * int_e_f<Ord, Ord>(n, wt, P_prev_newton, v);
}
VectorFormVol<double>* CustomWeakFormMD::VectorFormVolMD_0::clone() const
{
return new VectorFormVolMD_0(*this);
}
// **************
double CustomWeakFormMD::VectorFormVolMD_1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
Func<double>* E_prev_newton = u_ext[0];
double int_curl_E_v = 0;
for (int i = 0; i < n; i++)
{
int_curl_E_v += wt[i] * (E_prev_newton->curl[i] * v->val[i]);
}
return (-1.0 / mu_0) * int_curl_E_v;
}
Ord CustomWeakFormMD::VectorFormVolMD_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Func<Ord>* E_prev_newton = u_ext[0];
Ord int_curl_E_v = Ord(0);
for (int i = 0; i < n; i++)
{
int_curl_E_v += wt[i] * (E_prev_newton->curl[i] * v->val[i]);
}
return (-1.0 / mu_0) * int_curl_E_v;
}
VectorFormVol<double>* CustomWeakFormMD::VectorFormVolMD_1::clone() const
{
return new VectorFormVolMD_1(*this);
}
// **************
double CustomWeakFormMD::VectorFormVolMD_2::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
Func<double>* E_prev_newton = u_ext[0];
Func<double>* P_prev_newton = u_ext[2];
return (eps_q - 1)*eps_0*eps_inf / tau * int_e_f<double, double>(n, wt, E_prev_newton, v)
- (1.0 / tau) * int_e_f<double, double>(n, wt, P_prev_newton, v);
}
Ord CustomWeakFormMD::VectorFormVolMD_2::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e,
Func<Ord>* *ext) const
{
Func<Ord>* E_prev_newton = u_ext[0];
Func<Ord>* P_prev_newton = u_ext[2];
return (eps_q - 1)*eps_0*eps_inf / tau * int_e_f<Ord, Ord>(n, wt, E_prev_newton, v)
- (1.0 / tau) * int_e_f<Ord, Ord>(n, wt, P_prev_newton, v);
}
VectorFormVol<double>* CustomWeakFormMD::VectorFormVolMD_2::clone() const
{
return new VectorFormVolMD_2(*this);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/magnetostatics-actuator/definitions.h | .h | 1,186 | 34 | #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::WeakFormsH1;
using namespace Hermes::Hermes2D::WeakFormsMaxwell;
/* Weak forms */
class CustomWeakFormMagnetostatics : public WeakForm < double >
{
public:
CustomWeakFormMagnetostatics(std::string material_iron_1, std::string material_iron_2,
CubicSpline* mu_inv_iron, std::string material_air,
std::string material_copper, double mu_vacuum,
double current_density, int order_inc = 3);
};
class FilterFluxDensity : public Hermes::Hermes2D::DXDYFilter < double >
{
public:
FilterFluxDensity(std::vector<MeshFunctionSharedPtr<double> > solutions);
virtual Func<double>* get_pt_value(double x, double y, bool use_MeshHashGrid = false, Element* e = NULL);
virtual MeshFunction<double>* clone() const;
protected:
void filter_fn(int n, double* x, double* y, const std::vector<const double *>& values, const std::vector<const double *>& dx, const std::vector<const double *>& dy, double* rslt, double* rslt_dx, double* rslt_dy);
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/magnetostatics-actuator/main.cpp | .cpp | 5,390 | 145 | #include "definitions.h"
// This example shows how to handle stiff nonlinear problems.
//
// PDE: magnetostatics with nonlinear magnetic permeability
// curl[1/mu curl u] = current_density.
// The following parameters can be changed:
// Initial polynomial degree.
const int P_INIT = 3;
// Stopping criterion for the Newton's method.
const double NEWTON_TOL = 1e-8;
// Maximum allowed number of Newton iterations.
const int NEWTON_MAX_ITER = 1000;
// Number between 0 and 1 to damp Newton's iterations.
const double NEWTON_DAMPING = 1.0;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 0;
// Problem parameters.
double MU_VACUUM = 4. * M_PI * 1e-7;
// Constant initial condition for the magnetic potential.
double INIT_COND = 0.0;
// Volume source term.
double CURRENT_DENSITY = 1e9;
// Material and boundary markers.
const std::string MAT_AIR = "e2";
const std::string MAT_IRON_1 = "e0";
const std::string MAT_IRON_2 = "e3";
const std::string MAT_COPPER = "e1";
const std::string BDY_DIRICHLET = "bdy";
int main(int argc, char* argv[])
{
// Define nonlinear magnetic permeability via a cubic spline.
std::vector<double> mu_inv_pts({ 0.0, 0.5, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9, 3.0, 5.0, 10.0 });
std::vector<double> mu_inv_val({ 1 / 1500.0, 1 / 1480.0, 1 / 1440.0, 1 / 1400.0, 1 / 1300.0, 1 / 1150.0, 1 / 950.0, 1 / 750.0, 1 / 250.0, 1 / 180.0, 1 / 175.0, 1 / 150.0, 1 / 20.0, 1 / 10.0, 1 / 5.0 });
// Create the cubic spline (and plot it for visual control).
double bc_left = 0.0;
double bc_right = 0.0;
bool first_der_left = false;
bool first_der_right = false;
bool extrapolate_der_left = false;
bool extrapolate_der_right = false;
CubicSpline mu_inv_iron(mu_inv_pts, mu_inv_val, bc_left, bc_right, first_der_left, first_der_right,
extrapolate_der_left, extrapolate_der_right);
Hermes::Mixins::Loggable::Static::info("Saving cubic spline into a Pylab file spline.dat.");
// The interval of definition of the spline will be
// extended by "interval_extension" on both sides.
double interval_extension = 1.0;
bool plot_derivative = false;
mu_inv_iron.calculate_coeffs();
mu_inv_iron.plot("spline.dat", interval_extension, plot_derivative);
plot_derivative = true;
mu_inv_iron.plot("spline_der.dat", interval_extension, plot_derivative);
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("actuator.mesh", mesh);
// View the mesh.
MeshView m_view;
m_view.show(mesh);
// Perform initial mesh refinements.
for (int i = 0; i < INIT_REF_NUM; i++)
mesh->refine_all_elements();
// Initialize boundary conditions.
DefaultEssentialBCConst<double> bc_essential(BDY_DIRICHLET, 0.0);
EssentialBCs<double> bcs(&bc_essential);
// Create an H1 space with default shapeset.
SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
int ndof = space->get_num_dofs();
Hermes::Mixins::Loggable::Static::info("ndof: %d", ndof);
// Initialize the weak formulation
// This determines the increase of integration order
// for the axisymmetric term containing 1/r. Default is 3.
int order_inc = 3;
WeakFormSharedPtr<double> wf(new CustomWeakFormMagnetostatics(MAT_IRON_1, MAT_IRON_2, &mu_inv_iron, MAT_AIR, MAT_COPPER, MU_VACUUM, CURRENT_DENSITY, order_inc));
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, space);
// Initialize the solution.
MeshFunctionSharedPtr<double> sln(new ConstantSolution<double>(mesh, INIT_COND));
// Project the initial condition on the FE space to obtain initial
// coefficient vector for the Newton's method.
Hermes::Mixins::Loggable::Static::info("Projecting to obtain initial vector for the Newton's method.");
// Perform Newton's iteration.
Hermes::Hermes2D::NewtonSolver<double> newton(&dp);
newton.set_initial_auto_damping_coeff(0.5);
newton.set_sufficient_improvement_factor(1.1);
newton.set_necessary_successful_steps_to_increase(1);
newton.set_sufficient_improvement_factor_jacobian(0.5);
newton.set_max_steps_with_reused_jacobian(5);
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
try
{
newton.solve(sln);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
return 1;
};
// Translate the resulting coefficient vector into the Solution sln.
Solution<double>::vector_to_solution(newton.get_sln_vector(), space, sln);
// Visualise the solution and mesh.
ScalarView s_view1("Vector potential", new WinGeom(0, 0, 350, 450));
s_view1.show_mesh(false);
s_view1.show(sln);
ScalarView s_view2("Flux density", new WinGeom(360, 0, 350, 450));
MeshFunctionSharedPtr<double> flux_density(new FilterFluxDensity(std::vector<MeshFunctionSharedPtr<double> >({ sln, sln })));
s_view2.show_mesh(false);
s_view2.show(flux_density);
// Output solution in VTK format.
Linearizer lin(FileExport);
bool mode_3D = true;
lin.save_solution_vtk(flux_density, "sln.vtk", "Flux-density", mode_3D);
Hermes::Mixins::Loggable::Static::info("Solution in VTK format saved to file %s.", "sln.vtk");
OrderView o_view("Mesh", new WinGeom(720, 0, 350, 450));
o_view.show(space);
// Wait for all views to be closed.
View::wait();
return 0;
}
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/magnetostatics-actuator/definitions.cpp | .cpp | 2,051 | 45 | #include "definitions.h"
CustomWeakFormMagnetostatics::CustomWeakFormMagnetostatics(std::string material_iron_1, std::string material_iron_2,
CubicSpline* mu_inv_iron, std::string material_air,
std::string material_copper, double mu_vacuum,
double current_density, int order_inc) : WeakForm<double>(1)
{
// Jacobian.
add_matrix_form(new DefaultJacobianMagnetostatics<double>(0, 0, std::vector<std::string>({ material_air, material_copper }),
1.0, nullptr, HERMES_NONSYM, HERMES_AXISYM_Y, order_inc));
add_matrix_form(new DefaultJacobianMagnetostatics<double>(0, 0, std::vector<std::string>({ material_iron_1, material_iron_2 }), 1.0,
mu_inv_iron, HERMES_NONSYM, HERMES_AXISYM_Y, order_inc));
// Residual.
add_vector_form(new DefaultResidualMagnetostatics<double>(0, std::vector<std::string>({ material_air, material_copper }),
1.0, nullptr, HERMES_AXISYM_Y, order_inc));
add_vector_form(new DefaultResidualMagnetostatics<double>(0, std::vector<std::string>({ material_iron_1, material_iron_2 }), 1.0,
mu_inv_iron, HERMES_AXISYM_Y, order_inc));
add_vector_form(new DefaultVectorFormVol<double>(0, material_copper, new Hermes2DFunction<double>(-current_density * mu_vacuum)));
}
FilterFluxDensity::FilterFluxDensity(std::vector<MeshFunctionSharedPtr<double> > solutions)
: DXDYFilter<double>(solutions)
{
}
Func<double>* FilterFluxDensity::get_pt_value(double x, double y, bool use_MeshHashGrid, Element* e)
{
return new Func<double>();
}
MeshFunction<double>* FilterFluxDensity::clone() const
{
std::vector<MeshFunctionSharedPtr<double> > fns;
for (int i = 0; i < this->solutions.size(); i++)
fns.push_back(this->solutions[i]->clone());
return new FilterFluxDensity(fns);
}
void FilterFluxDensity::filter_fn(int n, double* x, double* y, const std::vector<const double *>& values, const std::vector<const double *>& dx, const std::vector<const double *>& dy, double* rslt, double* rslt_dx, double* rslt_dy)
{
for (int i = 0; i < n; i++)
{
rslt[i] = std::sqrt(sqr(dy[0][i]) + sqr(dx[0][i]));
}
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/magnetostatics-actuator/plot_spline.py | .py | 299 | 18 | # import libraries
import numpy, pylab
from pylab import *
data = numpy.loadtxt("spline.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, '-o', label="cubic spline")
data = numpy.loadtxt("spline_der.dat")
x = data[:, 0]
y = data[:, 1]
plot(x, y, '-*', label="derivative")
legend()
# finalize
show()
| Python |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/resonator-time-domain-II-ie/definitions.h | .h | 4,008 | 124 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Weak forms */
class CustomWeakFormWaveIE : public WeakForm < double >
{
public:
CustomWeakFormWaveIE(double tau, double c_squared, MeshFunctionSharedPtr<double> E_prev_sln, MeshFunctionSharedPtr<double> F_prev_sln);
private:
class MatrixFormVolWave_0_0 : public MatrixFormVol < double >
{
public:
MatrixFormVolWave_0_0(double tau) : MatrixFormVol<double>(0, 0), tau(tau) { 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;
double tau;
};
class MatrixFormVolWave_0_1 : public MatrixFormVol < double >
{
public:
MatrixFormVolWave_0_1() : MatrixFormVol<double>(0, 1) {};
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 MatrixFormVolWave_1_0 : public MatrixFormVol < double >
{
public:
MatrixFormVolWave_1_0(double c_squared)
: MatrixFormVol<double>(1, 0), c_squared(c_squared) {};
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 c_squared;
};
class MatrixFormVolWave_1_1 : public MatrixFormVol < double >
{
public:
MatrixFormVolWave_1_1(double tau) : MatrixFormVol<double>(1, 1), tau(tau) { 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;
double tau;
};
class VectorFormVolWave_0 : public VectorFormVol < double >
{
public:
VectorFormVolWave_0(double tau) : VectorFormVol<double>(0), tau(tau) {};
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 tau;
};
class VectorFormVolWave_1 : public VectorFormVol < double >
{
public:
VectorFormVolWave_1(double tau, double c_squared)
: VectorFormVol<double>(1), tau(tau), c_squared(c_squared) {};
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 tau, c_squared;
};
};
/* Initial condition for E */
class CustomInitialConditionWave : public ExactSolutionVector < double >
{
public:
CustomInitialConditionWave(MeshSharedPtr mesh) : ExactSolutionVector<double>(mesh) {};
virtual Scalar2<double> value(double x, double y) const;
virtual void derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const;
virtual Ord ord(double x, double y) const;
MeshFunction<double>* clone() const;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/resonator-time-domain-II-ie/main.cpp | .cpp | 5,421 | 149 | #include "definitions.h"
// This example solves a time-domain resonator problem for the Maxwell's equation.
// It is very similar to resonator-time-domain-I but B is eliminated from the
// equations, thus converting the first-order system into one second -order
// equation in time. The second-order equation in time is decomposed back into
// a first-order system in time in the standard way (see example wave-1). Time
// discretization is performed using the implicit Euler method.
//
// PDE: \frac{1}{SPEED_OF_LIGHT**2}\frac{\partial^2 E}{\partial t^2} + curl curl E = 0,
// converted into
//
// \frac{\partial E}{\partial t} - F = 0,
// \frac{\partial F}{\partial t} + SPEED_OF_LIGHT**2 * curl curl E = 0.
//
// Approximated by
//
// \frac{E^{n+1} - E^{n}}{tau} - F^{n+1} = 0,
// \frac{F^{n+1} - F^{n}}{tau} + SPEED_OF_LIGHT**2 * curl curl E^{n+1} = 0.
//
// Domain: Square (-pi/2, pi/2) x (-pi/2, pi/2)... See mesh file domain.mesh->
//
// BC: E \times \nu = 0 on the boundary (perfect conductor),
// F \times \nu = 0 on the boundary (E \times \nu = 0 => \partial E / \partial t \times \nu = 0).
//
// IC: Prescribed wave for E, zero for F.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 6;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// Time step.
const double time_step = 0.05;
// Final time.
const double T_FINAL = 35.0;
// 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;
// Problem parameters.
// Square of wave speed.
const double C_SQUARED = 1;
int main(int argc, char* argv[])
{
// Load the mesh.
MeshSharedPtr mesh(new Mesh);
MeshReaderH2D mloader;
mloader.load("domain.mesh", mesh);
// Perform initial mesh refinemets.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Initialize solutions.
MeshFunctionSharedPtr<double> E_sln(new CustomInitialConditionWave(mesh));
MeshFunctionSharedPtr<double> F_sln(new ZeroSolutionVector<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > slns({ E_sln, F_sln });
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormWaveIE(time_step, C_SQUARED, E_sln, F_sln));
// Initialize boundary conditions
DefaultEssentialBCConst<double> bc_essential("Perfect conductor", 0.0);
EssentialBCs<double> bcs(&bc_essential);
SpaceSharedPtr<double> E_space(new HcurlSpace<double>(mesh, &bcs, P_INIT));
SpaceSharedPtr<double> F_space(new HcurlSpace<double>(mesh, &bcs, P_INIT));
std::vector<SpaceSharedPtr<double> > spaces = std::vector<SpaceSharedPtr<double> >({ E_space, F_space });
int ndof = HcurlSpace<double>::get_num_dofs(spaces);
Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);
// Initialize the FE problem.
DiscreteProblem<double> dp(wf, spaces);
// Project the initial condition on the FE space to obtain initial
// coefficient vector for the Newton's method.
// NOTE: If you want to start from the zero vector, just define
// coeff_vec to be a vector of ndof zeros (no projection is needed).
Hermes::Mixins::Loggable::Static::info("Projecting to obtain initial vector for the Newton's method.");
double* coeff_vec = new double[ndof];
OGProjection<double>::project_global(spaces, slns, coeff_vec);
// Initialize Newton solver.
NewtonSolver<double> newton(&dp);
// Initialize views.
ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350));
E1_view.fix_scale_width(50);
ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350));
E2_view.fix_scale_width(50);
ScalarView F1_view("Solution F1", new WinGeom(0, 410, 400, 350));
F1_view.fix_scale_width(50);
ScalarView F2_view("Solution F2", new WinGeom(410, 410, 400, 350));
F2_view.fix_scale_width(50);
// Time stepping loop.
double current_time = 0; int ts = 1;
do
{
// Perform one implicit Euler time step.
Hermes::Mixins::Loggable::Static::info("Implicit Euler time step (t = %g s, time_step = %g s).", current_time, time_step);
// Perform Newton's iteration.
try
{
newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
newton.set_tolerance(NEWTON_TOL, Hermes::Solvers::ResidualNormAbsolute);
newton.solve(coeff_vec);
}
catch (Hermes::Exceptions::Exception e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Newton's iteration failed.");
}
// Translate the resulting coefficient vector into Solutions.
Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, slns);
// Visualize the solutions.
char title[100];
sprintf(title, "E1, t = %g", current_time + time_step);
E1_view.set_title(title);
E1_view.show(E_sln, H2D_FN_VAL_0);
sprintf(title, "E2, t = %g", current_time + time_step);
E2_view.set_title(title);
E2_view.show(E_sln, H2D_FN_VAL_1);
sprintf(title, "F1, t = %g", current_time + time_step);
F1_view.set_title(title);
F1_view.show(F_sln, H2D_FN_VAL_0);
sprintf(title, "F2, t = %g", current_time + time_step);
F2_view.set_title(title);
F2_view.show(F_sln, H2D_FN_VAL_1);
//View::wait();
// 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/maxwell/resonator-time-domain-II-ie/definitions.cpp | .cpp | 6,494 | 180 | #include "definitions.h"
template<typename Real, typename Scalar>
static Scalar int_e_f(int n, double *wt, Func<Real> *u, Func<Real> *v)
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += wt[i] * (u->val0[i] * conj(v->val0[i]) + u->val1[i] * conj(v->val1[i]));
return result;
}
template<typename Real, typename Scalar>
static Scalar int_curl_e_curl_f(int n, double *wt, Func<Real> *u, Func<Real> *v)
{
Scalar result = Scalar(0);
for (int i = 0; i < n; i++)
result += wt[i] * (u->curl[i] * conj(v->curl[i]));
return result;
}
CustomWeakFormWaveIE::CustomWeakFormWaveIE(double tau, double c_squared, MeshFunctionSharedPtr<double> E_prev_sln, MeshFunctionSharedPtr<double> F_prev_sln) : WeakForm<double>(2)
{
// Jacobian.
add_matrix_form(new MatrixFormVolWave_0_0(tau));
add_matrix_form(new MatrixFormVolWave_0_1);
add_matrix_form(new MatrixFormVolWave_1_0(c_squared));
add_matrix_form(new MatrixFormVolWave_1_1(tau));
// Residual.
VectorFormVolWave_0* vector_form_0 = new VectorFormVolWave_0(tau);
vector_form_0->set_ext(E_prev_sln);
add_vector_form(vector_form_0);
VectorFormVolWave_1* vector_form_1 = new VectorFormVolWave_1(tau, c_squared);
vector_form_1->set_ext(F_prev_sln);
add_vector_form(vector_form_1);
}
double CustomWeakFormWaveIE::MatrixFormVolWave_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 int_e_f<double, double>(n, wt, u, v) / tau;
}
Ord CustomWeakFormWaveIE::MatrixFormVolWave_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 int_e_f<Ord, Ord>(n, wt, u, v) / tau;
}
MatrixFormVol<double>* CustomWeakFormWaveIE::MatrixFormVolWave_0_0::clone() const
{
return new CustomWeakFormWaveIE::MatrixFormVolWave_0_0(*this);
}
double CustomWeakFormWaveIE::MatrixFormVolWave_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 -int_e_f<double, double>(n, wt, u, v);
}
Ord CustomWeakFormWaveIE::MatrixFormVolWave_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 -int_e_f<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* CustomWeakFormWaveIE::MatrixFormVolWave_0_1::clone() const
{
return new CustomWeakFormWaveIE::MatrixFormVolWave_0_1(*this);
}
double CustomWeakFormWaveIE::MatrixFormVolWave_1_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double>* *ext) const
{
return c_squared * int_curl_e_curl_f<double, double>(n, wt, u, v);
}
Ord CustomWeakFormWaveIE::MatrixFormVolWave_1_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
return c_squared * int_curl_e_curl_f<Ord, Ord>(n, wt, u, v);
}
MatrixFormVol<double>* CustomWeakFormWaveIE::MatrixFormVolWave_1_0::clone() const
{
return new CustomWeakFormWaveIE::MatrixFormVolWave_1_0(*this);
}
double CustomWeakFormWaveIE::MatrixFormVolWave_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 int_e_f<double, double>(n, wt, u, v) / tau;
}
Ord CustomWeakFormWaveIE::MatrixFormVolWave_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 int_e_f<Ord, Ord>(n, wt, u, v) / tau;
}
MatrixFormVol<double>* CustomWeakFormWaveIE::MatrixFormVolWave_1_1::clone() const
{
return new CustomWeakFormWaveIE::MatrixFormVolWave_1_1(*this);
}
double CustomWeakFormWaveIE::VectorFormVolWave_0::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
Func<double>* E_prev_newton = u_ext[0];
Func<double>* F_prev_newton = u_ext[1];
Func<double>* E_prev_time = ext[0];
return int_e_f<double, double>(n, wt, E_prev_newton, v) / tau
- int_e_f<double, double>(n, wt, E_prev_time, v) / tau
- int_e_f<double, double>(n, wt, F_prev_newton, v);
}
Ord CustomWeakFormWaveIE::VectorFormVolWave_0::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Func<Ord>* E_prev_newton = u_ext[0];
Func<Ord>* F_prev_newton = u_ext[1];
Func<Ord>* E_prev_time = ext[0];
return int_e_f<Ord, Ord>(n, wt, E_prev_newton, v) / tau
- int_e_f<Ord, Ord>(n, wt, E_prev_time, v) / tau
- int_e_f<Ord, Ord>(n, wt, F_prev_newton, v);
}
VectorFormVol<double>* CustomWeakFormWaveIE::VectorFormVolWave_0::clone() const
{
return new CustomWeakFormWaveIE::VectorFormVolWave_0(*this);
}
double CustomWeakFormWaveIE::VectorFormVolWave_1::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double>* *ext) const
{
Func<double>* E_prev_newton = u_ext[0];
Func<double>* F_prev_newton = u_ext[1];
Func<double>* F_prev_time = ext[0];
return int_e_f<double, double>(n, wt, F_prev_newton, v) / tau
- int_e_f<double, double>(n, wt, F_prev_time, v) / tau
+ c_squared * int_curl_e_curl_f<double, double>(n, wt, E_prev_newton, v);
}
Ord CustomWeakFormWaveIE::VectorFormVolWave_1::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord>* *ext) const
{
Func<Ord>* E_prev_newton = u_ext[0];
Func<Ord>* F_prev_newton = u_ext[1];
Func<Ord>* F_prev_time = ext[0];
return int_e_f<Ord, Ord>(n, wt, F_prev_newton, v) / tau
- int_e_f<Ord, Ord>(n, wt, F_prev_time, v) / tau
+ c_squared * int_curl_e_curl_f<Ord, Ord>(n, wt, E_prev_newton, v);
}
VectorFormVol<double>* CustomWeakFormWaveIE::VectorFormVolWave_1::clone() const
{
return new CustomWeakFormWaveIE::VectorFormVolWave_1(*this);
}
Scalar2<double> CustomInitialConditionWave::value(double x, double y) const
{
return Scalar2<double>(std::sin(x) * std::cos(y), -std::cos(x) * std::sin(y));
}
void CustomInitialConditionWave::derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const
{
dx[0] = std::cos(x) * std::cos(y);
dx[1] = std::sin(x) * std::sin(y);
dy[0] = -std::sin(x) * std::sin(y);
dy[1] = -std::cos(x) * std::cos(y);
}
Ord CustomInitialConditionWave::ord(double x, double y) const
{
return Ord(20);
}
MeshFunction<double>* CustomInitialConditionWave::clone() const
{
return new CustomInitialConditionWave(this->mesh);
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/profile-conductor/definitions.h | .h | 32,103 | 611 | #include "hermes2d.h"
using namespace Hermes;
using namespace Hermes::Hermes2D;
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4 : public MatrixFormVol<Scalar>
{
public:
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4<Scalar>* clone() const;
private:
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4 : public VectorFormVol<Scalar>
{
public:
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4<Scalar>* clone() const;
private:
unsigned int j;
};
template<typename Scalar>
class surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current : public VectorFormSurf<Scalar>
{
public:
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>* clone() const;
private:
unsigned int j;
double Jr;
double Ji;
};
template<typename Scalar>
class surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current : public VectorFormSurf<Scalar>
{
public:
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current(unsigned int i, unsigned int j, int offsetI, int offsetJ);
virtual Scalar value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const;
virtual Hermes::Ord ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const;
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current<Scalar>* clone() const;
private:
unsigned int j;
double Jr;
double Ji;
};
template<typename Scalar>
class exact_magnetic_harmonic_planar_linear_harmonic_essential_1_1_0_magnetic_potential : public ExactSolutionScalarAgros<Scalar>
{
public:
exact_magnetic_harmonic_planar_linear_harmonic_essential_1_1_0_magnetic_potential(Hermes::Hermes2D::MeshSharedPtr mesh);
Scalar value(double x, double y) const;
void derivatives(double x, double y, Scalar& dx, Scalar& dy) const;
Hermes::Ord ord(double x, double y) const
{
return Hermes::Ord(Hermes::Ord::get_max_order());
}
private:
double Ar;
double Ai;
};
template<typename Scalar>
class exact_magnetic_harmonic_planar_linear_harmonic_essential_2_2_0_magnetic_potential : public ExactSolutionScalarAgros<Scalar>
{
public:
exact_magnetic_harmonic_planar_linear_harmonic_essential_2_2_0_magnetic_potential(Hermes::Hermes2D::MeshSharedPtr mesh);
Scalar value(double x, double y) const;
void derivatives(double x, double y, Scalar& dx, Scalar& dy) const;
Hermes::Ord ord(double x, double y) const
{
return Hermes::Ord(Hermes::Ord::get_max_order());
}
private:
double Ar;
double Ai;
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/profile-conductor/main.cpp | .cpp | 0 | 0 | null | C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/profile-conductor/definitions.cpp | .cpp | 69,070 | 1,430 | #include "definitions.h"
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i] + u->val[i] * v->dx[i] / e->x[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i] + u->val[i] * v->dx[i] / e->x[i]));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_1_1_1_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i] + u->val[i] * v->dx[i] / e->x[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[14]->val[i] * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i] + u->val[i] * v->dx[i] / e->x[i]));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_laplace_2_2_2_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ((ext[5]->val[i] - e->y[i] * ext[7]->val[i])*v->dx[i] + (ext[6]->val[i] + e->x[i] * ext[7]->val[i])*v->dy[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ((ext[5]->val[i] - e->y[i] * ext[7]->val[i])*v->dx[i] + (ext[6]->val[i] + e->x[i] * ext[7]->val[i])*v->dy[i]));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ext[6]->val[i] * v->dy[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ext[6]->val[i] * v->dy[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_1_1_1_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ((ext[5]->val[i] - e->y[i] * ext[7]->val[i])*v->dx[i] + (ext[6]->val[i] + e->x[i] * ext[7]->val[i])*v->dy[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ((ext[5]->val[i] - e->y[i] * ext[7]->val[i])*v->dx[i] + (ext[6]->val[i] + e->x[i] * ext[7]->val[i])*v->dy[i]));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ext[6]->val[i] * v->dy[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[2]->val[i] * u->val[i] * ext[6]->val[i] * v->dy[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_velocity_2_2_2_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_1_2_1_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_gamma_2_1_2_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i] / (2 * M_PI*(e->x[i] + 1e-12)));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i] / (2 * M_PI*(e->x[i] + 1e-12)));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_4_1_4(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i] / (2 * M_PI*(e->x[i] + 1e-12)));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i] * v->val[i] / (2 * M_PI*(e->x[i] + 1e-12)));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_2_3_2_3(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_1_3_1(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * ext[10]->val[i] * u->val[i]);
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_4_2_4_2(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (tern(ext[10]->val[i]>0, -2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i], 1));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (tern(ext[10]->val[i]>0, -2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i], 1));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3<Scalar>::volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (tern(ext[10]->val[i]>0, -2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] / (2 * M_PI*(e->x[i] + 1e-12)), 1));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (tern(ext[10]->val[i]>0, -2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i] / (2 * M_PI*(e->x[i] + 1e-12)), 1));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3<Scalar>* volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_axisymmetric_linear_harmonic_current_3_3_3_3(*this);
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4<Scalar>::volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: MatrixFormVolAgros<Scalar>(i, j, offsetI, offsetJ)
{
}
template <typename Scalar>
Scalar volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *u,
Hermes::Hermes2D::Func<double> *v, Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (tern(ext[10]->val[i]>0, 2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i], 1));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *u,
Hermes::Hermes2D::Func<Hermes::Ord> *v, Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (tern(ext[10]->val[i]>0, 2 * M_PI*this->m_markerSource->fieldInfo()->frequency()*ext[2]->val[i] * u->val[i], 1));
}
return result;
}
template <typename Scalar>
volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4<Scalar>* volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4<Scalar>::clone() const
{
//return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[3]->val[i] * ext[14]->val[i] * (-ext[16]->val[i] * v->dx[i] + ext[17]->val[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[3]->val[i] * ext[14]->val[i] * (-ext[16]->val[i] * v->dx[i] + ext[17]->val[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>* volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[3]->val[i] * ext[14]->val[i] * (-ext[16]->val[i] * v->dx[i] + ext[17]->val[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-ext[3]->val[i] * ext[14]->val[i] * (-ext[16]->val[i] * v->dx[i] + ext[17]->val[i] * v->dy[i]));
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>* volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_remanence_1_1(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1<Scalar>::volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[8]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[8]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1<Scalar>* volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1<Scalar>::volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[8]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[8]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1<Scalar>* volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_1_1_current_1_1(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2<Scalar>::volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[9]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[9]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2<Scalar>* volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2<Scalar>::volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[9]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[9]->val[i] * v->val[i]);
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2<Scalar>* volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_rhs_2_2_current_2_2(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3<Scalar>::volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[10]->val[i] * (ext[12]->val[i] / this->markerVolume() - ext[9]->val[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[10]->val[i] * (ext[12]->val[i] / this->markerVolume() - ext[9]->val[i]));
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3<Scalar>* volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3<Scalar>::volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[10]->val[i] * (ext[12]->val[i] / this->markerVolume() - ext[9]->val[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[10]->val[i] * (ext[12]->val[i] / this->markerVolume() - ext[9]->val[i]));
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3<Scalar>* volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_axisymmetric_linear_harmonic_vec_current_3_3_3_3(*this);
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4<Scalar>::volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4(unsigned int i, unsigned int j, int offsetI, int offsetJ, int* offsetPreviousTimeExt, int* offsetCouplingExt)
: VectorFormVolAgros<Scalar>(i, offsetI, offsetJ, offsetPreviousTimeExt, offsetCouplingExt), j(j)
{
}
template <typename Scalar>
Scalar volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[10]->val[i] * (ext[11]->val[i] / this->markerVolume() - ext[8]->val[i]));
}
return result;
}
template <typename Scalar>
Hermes::Ord volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (ext[10]->val[i] * (ext[11]->val[i] / this->markerVolume() - ext[8]->val[i]));
}
return result;
}
template <typename Scalar>
volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4<Scalar>* volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4<Scalar>::clone() const
{
//return new volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4(this->i, this->j, this->m_offsetI, this->m_offsetJ, this->m_offsetPreviousTimeExt, this->m_offsetCouplingExt);
return new volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4(*this);
}
template <typename Scalar>
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: VectorFormSurfAgros<Scalar>(i, offsetI, offsetJ), j(j)
{
}
template <typename Scalar>
Scalar surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomVol<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-Jr*v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomVol<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-Jr*v->val[i]);
}
return result;
}
template <typename Scalar>
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>* surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::clone() const
{
//return new surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current(*this);
}
template <typename Scalar>
surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: VectorFormSurfAgros<Scalar>(i, offsetI, offsetJ), j(j)
{
}
template <typename Scalar>
Scalar surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomSurf<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-Jr*v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomSurf<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-Jr*v->val[i]);
}
return result;
}
template <typename Scalar>
surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>* surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current<Scalar>::clone() const
{
//return new surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new surface_vector_magnetic_harmonic_axisymmetric_linear_harmonic_current_1_1_1_magnetic_surface_current(*this);
}
template <typename Scalar>
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current<Scalar>::surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current(unsigned int i, unsigned int j, int offsetI, int offsetJ)
: VectorFormSurfAgros<Scalar>(i, offsetI, offsetJ), j(j)
{
}
template <typename Scalar>
Scalar surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current<Scalar>::value(int n, double *wt, Hermes::Hermes2D::Func<Scalar> *u_ext[], Hermes::Hermes2D::Func<double> *v,
Hermes::Hermes2D::GeomSurf<double> *e, Hermes::Hermes2D::Func<Scalar> **ext) const
{
Scalar result = 0;
for (int i = 0; i < n; i++)
{
result += wt[i] * (-Ji*v->val[i]);
}
return result;
}
template <typename Scalar>
Hermes::Ord surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current<Scalar>::ord(int n, double *wt, Hermes::Hermes2D::Func<Hermes::Ord> *u_ext[], Hermes::Hermes2D::Func<Hermes::Ord> *v,
Hermes::Hermes2D::GeomSurf<Hermes::Ord> *e, Hermes::Hermes2D::Func<Hermes::Ord> **ext) const
{
Hermes::Ord result(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (-Ji*v->val[i]);
}
return result;
}
template <typename Scalar>
surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current<Scalar>* surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current<Scalar>::clone() const
{
//return new surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current(this->i, this->j, this->m_offsetI, this->m_offsetJ);
return new surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current(*this);
}
template <typename Scalar>
exact_magnetic_harmonic_planar_linear_harmonic_essential_1_1_0_magnetic_potential<Scalar>::exact_magnetic_harmonic_planar_linear_harmonic_essential_1_1_0_magnetic_potential(Hermes::Hermes2D::MeshSharedPtr mesh)
: ExactSolutionScalarAgros<Scalar>(mesh)
{
}
template <typename Scalar>
Scalar exact_magnetic_harmonic_planar_linear_harmonic_essential_1_1_0_magnetic_potential<Scalar>::value(double x, double y) const
{
Scalar result = Ar;
return result;
}
template <typename Scalar>
void exact_magnetic_harmonic_planar_linear_harmonic_essential_1_1_0_magnetic_potential<Scalar>::derivatives(double x, double y, Scalar& dx, Scalar& dy) const
{
}
template <typename Scalar>
exact_magnetic_harmonic_planar_linear_harmonic_essential_2_2_0_magnetic_potential<Scalar>::exact_magnetic_harmonic_planar_linear_harmonic_essential_2_2_0_magnetic_potential(Hermes::Hermes2D::MeshSharedPtr mesh)
: ExactSolutionScalarAgros<Scalar>(mesh)
{
}
template <typename Scalar>
Scalar exact_magnetic_harmonic_planar_linear_harmonic_essential_2_2_0_magnetic_potential<Scalar>::value(double x, double y) const
{
Scalar result = Ai;
return result;
}
template <typename Scalar>
void exact_magnetic_harmonic_planar_linear_harmonic_essential_2_2_0_magnetic_potential<Scalar>::derivatives(double x, double y, Scalar& dx, Scalar& dy) const
{
}
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_1_1_1_1<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_laplace_2_2_2_2<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_1_1_1_1<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_velocity_2_2_2_2<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_1_2_1_2<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_gamma_2_1_2_1<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_1_4_1_4<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_2_3_2_3<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_1_3_1<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_2_4_2<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_3_3_3_3<double>;
template class volume_matrix_magnetic_harmonic_planar_linear_harmonic_current_4_4_4_4<double>;
template class volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_remanence_1_1<double>;
template class volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_1_1_current_1_1<double>;
template class volume_vector_magnetic_harmonic_planar_linear_harmonic_rhs_2_2_current_2_2<double>;
template class volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_3_3_3_3<double>;
template class volume_vector_magnetic_harmonic_planar_linear_harmonic_vec_current_4_4_4_4<double>;
template class exact_magnetic_harmonic_planar_linear_harmonic_essential_1_1_0_magnetic_potential<double>;
template class exact_magnetic_harmonic_planar_linear_harmonic_essential_2_2_0_magnetic_potential<double>;
template class surface_vector_magnetic_harmonic_planar_linear_harmonic_current_1_1_1_magnetic_surface_current<double>;
template class surface_vector_magnetic_harmonic_planar_linear_harmonic_current_2_2_2_magnetic_surface_current<double>;
| C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/resonator-time-domain-I/definitions.h | .h | 3,520 | 114 | #include "hermes2d.h"
/* Namespaces used */
using namespace Hermes;
using namespace Hermes::Hermes2D;
using namespace Hermes::Hermes2D::Views;
using namespace Hermes::Hermes2D::RefinementSelectors;
/* Initial condition for E */
class CustomInitialConditionWave : public ExactSolutionVector < double >
{
public:
CustomInitialConditionWave(MeshSharedPtr mesh) : ExactSolutionVector<double>(mesh) {};
virtual Scalar2<double> value(double x, double y) const;
virtual void derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const;
virtual Ord ord(double x, double y) const;
MeshFunction<double>* clone() const;
};
/* Weak forms */
class CustomWeakFormWave : public WeakForm < double >
{
public:
CustomWeakFormWave(double c_squared);
private:
class MatrixFormVolWave_0_1 : public MatrixFormVol < double >
{
public:
MatrixFormVolWave_0_1(double c_squared)
: MatrixFormVol<double>(0, 1), c_squared(c_squared) {};
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 c_squared;
};
class MatrixFormVolWave_1_0 : public MatrixFormVol < double >
{
public:
MatrixFormVolWave_1_0()
: MatrixFormVol<double>(1, 0) {};
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 VectorFormVolWave_0 : public VectorFormVol < double >
{
public:
VectorFormVolWave_0(double c_squared)
: VectorFormVol<double>(0), 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;
};
class VectorFormVolWave_1 : public VectorFormVol < double >
{
public:
VectorFormVolWave_1()
: VectorFormVol<double>(1) {};
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;
};
};
| Unknown |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/resonator-time-domain-I/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/maxwell/resonator-time-domain-I/main.cpp | .cpp | 5,623 | 139 | #include "definitions.h"
// This example shows how to discretize the first-order time-domain Maxwell's equations
// with vector-valued E (an Hcurl function) and double B (an H1 function). Time integration
// is done using an arbitrary R-K method (see below).
//
// PDE: \partial E / \partial t - SPEED_OF_LIGHT**2 * curl B = 0,
// \partial B / \partial t + curl E = 0.
//
// Note: curl E = \partial E_2 / \partial x - \partial E_1 / \partial y
// curl B = (\partial B / \partial y, - \partial B / \partial x)
//
// Domain: square (-pi/2, pi/2)^2.
//
// BC: perfect conductor for E on the entire boundary, no BC for B.
//
// The following parameters can be changed:
// Initial polynomial degree of mesh elements.
const int P_INIT = 6;
// Number of initial uniform mesh refinements.
const int INIT_REF_NUM = 1;
// Time step.
const double time_step = 0.05;
// Final time.
const double T_FINAL = 35.0;
// 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;
// Problem parameters.
// Square of wave speed.
const double C_SQUARED = 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("domain.mesh", mesh);
// Perform initial mesh refinemets.
for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
// Initialize solutions.
MeshFunctionSharedPtr<double> E_sln(new CustomInitialConditionWave(mesh));
MeshFunctionSharedPtr<double> B_sln(new ZeroSolution<double>(mesh));
std::vector<MeshFunctionSharedPtr<double> > slns({ E_sln, B_sln });
// Initialize the weak formulation.
WeakFormSharedPtr<double> wf(new CustomWeakFormWave(C_SQUARED));
// Initialize boundary conditions
DefaultEssentialBCConst<double> bc_essential("Perfect conductor", 0.0);
EssentialBCs<double> bcs_E(&bc_essential);
SpaceSharedPtr<double> E_space(new HcurlSpace<double>(mesh, &bcs_E, P_INIT));
EssentialBCs<double> bcs_B;
// Create x- and y- displacement space using the default H1 shapeset.
SpaceSharedPtr<double> B_space(new H1Space<double>(mesh, &bcs_B, P_INIT));
std::vector<SpaceSharedPtr<double> > spaces({ E_space, B_space });
std::vector<SpaceSharedPtr<double> > spaces_mutable({ E_space, B_space });
Hermes::Mixins::Loggable::Static::info("ndof = %d.", Space<double>::get_num_dofs(spaces));
// Initialize views.
ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350));
E1_view.fix_scale_width(50);
ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350));
E2_view.fix_scale_width(50);
ScalarView B_view("Solution B", new WinGeom(0, 405, 400, 350));
B_view.fix_scale_width(50);
// Initialize Runge-Kutta time stepping.
RungeKutta<double> runge_kutta(wf, spaces, &bt);
// Time stepping loop.
double current_time = time_step; int ts = 1;
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());
bool jacobian_changed = false;
bool verbose = true;
try
{
runge_kutta.set_time(current_time);
runge_kutta.set_time_step(time_step);
runge_kutta.rk_time_step_newton(slns, slns);
}
catch (Exceptions::Exception& e)
{
e.print_msg();
throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
}
// Visualize the solutions.
char title[100];
sprintf(title, "E1, t = %g", current_time);
E1_view.set_title(title);
E1_view.show(E_sln, H2D_FN_VAL_0);
sprintf(title, "E2, t = %g", current_time);
E2_view.set_title(title);
E2_view.show(E_sln, H2D_FN_VAL_1);
sprintf(title, "B, t = %g", current_time);
B_view.set_title(title);
B_view.show(B_sln, H2D_FN_VAL_0);
// Update time.
current_time += time_step;
ts++;
} while (current_time < T_FINAL);
// Wait for the view to be closed.
View::wait();
return 0;
} | C++ |
2D | hpfem/hermes-examples | 2d-advanced/maxwell/resonator-time-domain-I/definitions.cpp | .cpp | 4,898 | 156 | #include "definitions.h"
using namespace WeakFormsHcurl;
Scalar2<double> CustomInitialConditionWave::value(double x, double y) const
{
return Scalar2<double>(std::sin(x) * std::cos(y), -std::cos(x) * std::sin(y));
}
void CustomInitialConditionWave::derivatives(double x, double y, Scalar2<double>& dx, Scalar2<double>& dy) const
{
dx[0] = std::cos(x) * std::cos(y);
dx[1] = std::sin(x) * std::sin(y);
dy[0] = -std::sin(x) * std::sin(y);
dy[1] = -std::cos(x) * std::cos(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 c_squared) : WeakForm<double>(2)
{
// Jacobian.
add_matrix_form(new MatrixFormVolWave_0_1(c_squared));
add_matrix_form(new MatrixFormVolWave_1_0);
// Residual.
add_vector_form(new VectorFormVolWave_0(c_squared));
add_vector_form(new VectorFormVolWave_1());
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormWave::MatrixFormVolWave_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 result = Scalar(0);
for (int i = 0; i < n; i++)
{
result += wt[i] * (u->dy[i] * v->val0[i] - u->dx[i] * v->val1[i]);
}
return c_squared * result;
}
double CustomWeakFormWave::MatrixFormVolWave_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 CustomWeakFormWave::MatrixFormVolWave_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>* CustomWeakFormWave::MatrixFormVolWave_0_1::clone() const
{
return new MatrixFormVolWave_0_1(*this);
}
template<typename Real, typename Scalar>
Scalar CustomWeakFormWave::MatrixFormVolWave_1_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 result = Scalar(0);
for (int i = 0; i < n; i++)
{
result -= wt[i] * u->curl[i] * v->val[i];
}
return result;
}
double CustomWeakFormWave::MatrixFormVolWave_1_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 CustomWeakFormWave::MatrixFormVolWave_1_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>* CustomWeakFormWave::MatrixFormVolWave_1_0::clone() const
{
return new MatrixFormVolWave_1_0(*this);
}
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);
Func<Scalar>* sln_prev = u_ext[1];
for (int i = 0; i < n; i++)
{
result += wt[i] * (sln_prev->dy[i] * v->val0[i] - sln_prev->dx[i] * v->val1[i]);
}
return c_squared * 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);
Func<Scalar>* sln_prev = u_ext[0];
for (int i = 0; i < n; i++)
{
result -= wt[i] * sln_prev->curl[i] * v->val[i];
}
return 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++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.