id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,537,103
|
lex_01.cc
|
hyperdeal_hyperdeal/tests/utilities/lex_01.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test hyperdeal::Utilities::decompose.
#include <hyper.deal/base/utilities.h>
#include "../tests.h"
int
main()
{
initlog();
for (unsigned int i = 0; i < 20; i++)
{
const auto result = hyperdeal::Utilities::lex_to_pair(i, 5, 4);
deallog << i << " (" << result.first << " " << result.second << ")"
<< std::endl;
}
}
| 1,007
|
C++
|
.cc
| 28
| 33.392857
| 73
| 0.572456
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,104
|
decompose_01.cc
|
hyperdeal_hyperdeal/tests/utilities/decompose_01.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test hyperdeal::Utilities::decompose.
#include <hyper.deal/base/utilities.h>
#include "../tests.h"
int
main()
{
initlog();
for (unsigned int i = 1; i <= 56 /*SuperMUC - Phase 2*/; i++)
{
const auto result = hyperdeal::Utilities::decompose(i);
deallog << i << " (" << result.first << " " << result.second << ")"
<< std::endl;
}
}
| 1,023
|
C++
|
.cc
| 28
| 33.964286
| 73
| 0.575329
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,105
|
fefaceevalutation_02.cc
|
hyperdeal_hyperdeal/tests/matrix_free/fefaceevalutation_02.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test FEFaceEvaluation::read_dof_values() for ECL/FCL and for different
// orientations.
#include <deal.II/base/function.h>
#include <deal.II/base/mpi.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <hyper.deal/base/mpi.h>
#include <hyper.deal/base/utilities.h>
#include <hyper.deal/grid/grid_generator.h>
#include <hyper.deal/matrix_free/evaluation_kernels.h>
#include <hyper.deal/matrix_free/fe_evaluation_face.h>
#include <hyper.deal/numerics/vector_tools.h>
#include <ios>
#include "../tests_functions.h"
#include "../tests_mf.h"
using namespace dealii;
template <int DIM, typename Number = double>
class ExactSolution : public dealii::Function<DIM, Number>
{
public:
ExactSolution(const double direction)
: dealii::Function<DIM, Number>(1)
, direction(direction)
{}
virtual double
value(const dealii::Point<DIM> &p, const unsigned int = 1) const
{
return p[direction];
}
private:
const unsigned int direction;
};
template <
int dim_x,
int dim_v,
int degree,
int n_points,
typename Number = double,
typename VectorizedArrayType = dealii::VectorizedArray<double, 1>,
typename VectorType = dealii::LinearAlgebra::distributed::Vector<double>>
void
test(const MPI_Comm &comm)
{
const auto sizes = hyperdeal::Utilities::decompose(
dealii::Utilities::MPI::n_mpi_processes(comm));
const unsigned int size_x = sizes.first;
const unsigned int size_v = sizes.second;
MPI_Comm comm_global =
hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v);
if (comm_global != MPI_COMM_NULL)
{
MPI_Comm comm_sm = MPI_COMM_SELF;
hyperdeal::MatrixFreeWrapper<dim_x, dim_v, Number, VectorizedArrayType>
matrixfree_wrapper(comm_global, comm_sm, size_x, size_v);
hyperdeal::Parameters p;
p.triangulation_type = "fullydistributed";
p.degree = degree;
p.mapping_degree = 1;
p.do_collocation = false;
p.do_ghost_faces = true;
p.do_buffering = false;
p.use_ecl = true;
matrixfree_wrapper.init(p, [&](auto &tria_x, auto &tria_v) {
hyperdeal::GridGenerator::hyper_cube(tria_x, tria_v, false, 0);
});
const auto &matrix_free = matrixfree_wrapper.get_matrix_free();
hyperdeal::FEEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
phi(matrix_free, 0, 0, 0, 0);
hyperdeal::FEEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
phi_cell_inv(matrix_free, 0, 0, 0, 0);
hyperdeal::FEFaceEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
phi_m(matrix_free, true, 0, 0, 0, 0);
static const int dim = dim_x + dim_v;
deallog.push("dim_x=" + std::to_string(dim_x) + ":" +
std::to_string(dim_v));
for (int direction = 0; direction < dim; ++direction)
{
deallog.push("dir=" + std::to_string(direction));
VectorType vec;
matrix_free.initialize_dof_vector(vec, 0, true, true);
std::shared_ptr<dealii::Function<dim, Number>> solution(
new ExactSolution<dim, Number>(direction));
hyperdeal::VectorTools::interpolate<degree, n_points>(
solution, matrix_free, vec, 0, 0, 2, 2);
deallog.push("FCL");
matrix_free.template loop<VectorType, VectorType>(
[&](const auto &, auto &, const auto &, const auto) {},
[&](const auto &, auto &, const auto &, const auto) {
},
[&](const auto &, auto &, const auto &src, const auto face) {
deallog.push("dir=" + std::to_string(face.macro));
phi_m.reinit(face);
phi_m.read_dof_values(src);
VectorizedArrayType *data_ptr1 = phi_m.get_data_ptr();
dealii::internal::FEEvaluationImplBasisChange<
dealii::internal::EvaluatorVariant::evaluate_evenodd,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::do_forward(1,
matrix_free.get_matrix_free_x()
.get_shape_info()
.data.front()
.shape_values_eo,
data_ptr1,
data_ptr1);
std::set<unsigned int> failed;
for (unsigned int q = 0;
q < dealii::Utilities::pow<unsigned int>(n_points, dim - 1);
++q)
{
if (std::abs(phi_m.get_quadrature_point(q)[direction][0] -
phi_m.get_data_ptr()[q][0]) > 1e-8)
failed.insert(q);
}
if (failed.empty())
deallog << "succeeded!" << std::endl;
else
{
deallog << " failed!" << std::endl;
}
deallog.pop();
},
vec,
vec,
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values,
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values);
deallog.pop();
deallog.push("ECL");
matrix_free.template loop_cell_centric<VectorType, VectorType>(
[&](const auto &, auto &, const auto &src, const auto cell) {
phi.reinit(cell);
phi.read_dof_values(src);
VectorizedArrayType *data_ptr = phi.get_data_ptr();
VectorizedArrayType *data_ptr1 = phi_m.get_data_ptr();
dealii::internal::FEEvaluationImplBasisChange<
dealii::internal::EvaluatorVariant::evaluate_evenodd,
dealii::internal::EvaluatorQuantity::value,
dim,
degree + 1,
n_points>::do_forward(1,
matrix_free.get_matrix_free_x()
.get_shape_info()
.data.front()
.shape_values_eo,
data_ptr,
data_ptr);
VectorizedArrayType *buffer = phi_cell_inv.get_data_ptr();
for (auto i = 0u;
i < dealii::Utilities::pow<unsigned int>(n_points, dim);
i++)
buffer[i] = data_ptr[i];
for (auto face = 0u; face < dim * 2; face++)
{
deallog.push("dir=" + std::to_string(face));
phi_m.reinit(cell, face);
hyperdeal::internal::FEFaceNormalEvaluationImpl<dim_x,
dim_v,
n_points - 1,
Number>::
template interpolate_quadrature<true, false>(
1,
dealii::EvaluationFlags::values,
matrix_free.get_matrix_free_x().get_shape_info(),
/*out=*/phi_cell_inv.get_data_ptr(),
/*in=*/data_ptr1,
face);
std::set<unsigned int> failed;
for (unsigned int q = 0;
q <
dealii::Utilities::pow<unsigned int>(n_points, dim - 1);
++q)
{
if (std::abs(phi_m.get_quadrature_point(q)[direction][0] -
phi_m.get_data_ptr()[q][0]) > 1e-8)
failed.insert(q);
}
if (failed.empty())
deallog << "succeeded!" << std::endl;
else
{
deallog << "failed!" << std::endl;
}
deallog.pop();
}
},
vec,
vec,
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values);
deallog.pop();
deallog.pop();
}
deallog.pop();
MPI_Comm_free(&comm_global);
}
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
const MPI_Comm comm = MPI_COMM_WORLD;
test<1, 1, 3, 4>(comm);
test<2, 1, 3, 4>(comm);
test<1, 2, 3, 4>(comm);
test<1, 3, 3, 4>(comm);
test<2, 2, 3, 4>(comm);
test<3, 1, 3, 4>(comm);
test<2, 3, 3, 4>(comm);
test<3, 2, 3, 4>(comm);
test<3, 3, 3, 4>(comm);
}
| 10,093
|
C++
|
.cc
| 243
| 27.699588
| 80
| 0.489932
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,106
|
fefaceevalutation_01.cc
|
hyperdeal_hyperdeal/tests/matrix_free/fefaceevalutation_01.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test FEFaceEvaluation::read_dof_values() for ECL/FCL and for different
// orientations.
#include <deal.II/base/function.h>
#include <deal.II/base/mpi.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <hyper.deal/base/mpi.h>
#include <hyper.deal/base/utilities.h>
#include <hyper.deal/grid/grid_generator.h>
#include <hyper.deal/matrix_free/fe_evaluation_face.h>
#include <hyper.deal/numerics/vector_tools.h>
#include <ios>
#include "../tests_functions.h"
#include "../tests_mf.h"
using namespace dealii;
template <int DIM, typename Number = double>
class ExactSolution : public dealii::Function<DIM, Number>
{
public:
ExactSolution(const double time = 0.)
: dealii::Function<DIM, Number>(1, time)
, wave_number(2.)
{
advection[0] = 1. * 0.0;
if (DIM > 1)
advection[1] = 0.15 * 0.0;
if (DIM > 2)
advection[2] = -0.05 * 0.0;
if (DIM > 3)
advection[3] = -0.10;
if (DIM > 4)
advection[4] = -0.15;
if (DIM > 5)
advection[5] = 0.5;
}
virtual double
value(const dealii::Point<DIM> &p, const unsigned int = 1) const
{
double t = this->get_time();
const dealii::Tensor<1, DIM> position = p - t * advection;
double result = std::sin(wave_number * position[0] * dealii::numbers::PI);
for (unsigned int d = 1; d < DIM; ++d)
result *= std::cos(wave_number * position[d] * dealii::numbers::PI);
return result;
}
dealii::Tensor<1, DIM>
get_transport_direction() const
{
return advection;
}
private:
dealii::Tensor<1, DIM> advection;
const double wave_number;
};
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType,
typename VectorType>
void
test(const MPI_Comm &comm, const unsigned int o1, const unsigned int o2)
{
const auto sizes = hyperdeal::Utilities::decompose(
dealii::Utilities::MPI::n_mpi_processes(comm));
const unsigned int size_x = sizes.first;
const unsigned int size_v = sizes.second;
MPI_Comm comm_global =
hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v);
if (comm_global != MPI_COMM_NULL)
{
MPI_Comm comm_sm = MPI_COMM_SELF;
hyperdeal::MatrixFreeWrapper<dim_x, dim_v, Number, VectorizedArrayType>
matrixfree_wrapper(comm_global, comm_sm, size_x, size_v);
hyperdeal::Parameters p;
p.triangulation_type = "fullydistributed";
p.degree = degree;
p.mapping_degree = 1;
p.do_collocation = false;
p.do_ghost_faces = true;
p.do_buffering = false;
p.use_ecl = true;
matrixfree_wrapper.init(p, [&](auto &tria_x, auto &tria_v) {
dealii::Point<dim_x> left_x(-1, -1, -1);
dealii::Point<dim_x> right_x(+1, +1, +1);
dealii::Point<dim_v> left_v(-1, -1, -1);
dealii::Point<dim_v> right_v(+1, +1, +1);
hyperdeal::GridGenerator::orientated_hyper_cube(tria_x,
tria_v,
0,
left_x,
right_x,
true,
o1,
0,
left_v,
right_v,
true,
o2);
});
const auto &matrix_free = matrixfree_wrapper.get_matrix_free();
VectorType vec;
matrix_free.initialize_dof_vector(vec, 0, true, true);
static const int dim = dim_x + dim_v;
std::shared_ptr<dealii::Function<dim, Number>> solution(
new ExactSolution<dim, Number>);
hyperdeal::VectorTools::interpolate<degree, n_points>(
solution, matrix_free, vec, 0, 0, 2, 2);
hyperdeal::FEEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
phi(matrix_free, 0, 0, 0, 0);
hyperdeal::FEFaceEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
phi_m(matrix_free, true, 0, 0, 0, 0);
hyperdeal::FEFaceEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
phi_p(matrix_free, false, 0, 0, 0, 0);
{
deallog << "FCL - Orientation (" << o1 << "," << o2 << "): ";
std::set<unsigned int> failed;
matrix_free.template loop<VectorType, VectorType>(
[&](const auto &, auto &, const auto &, const auto) {},
[&](const auto &, auto &, const auto &src, const auto face) {
phi_m.reinit(face);
phi_m.read_dof_values(src);
phi_p.reinit(face);
phi_p.read_dof_values(src);
for (unsigned int q = 0;
q < dealii::Utilities::pow<unsigned int>(n_points, dim - 1);
++q)
{
if (std::abs(phi_p.get_data_ptr()[q] -
phi_m.get_data_ptr()[q])[0] > 1e-8)
failed.insert(face.macro);
}
},
[&](const auto &, auto &, const auto &, const auto) {},
vec,
vec,
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values,
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values);
if (failed.empty())
deallog << "succeeded!" << std::endl;
else
{
deallog << " failed!" << std::endl;
}
}
{
deallog << "ECL - Orientation (" << o1 << "," << o2 << "): ";
std::set<std::pair<unsigned int, unsigned int>> failed;
matrix_free.template loop_cell_centric<VectorType, VectorType>(
[&](const auto &, auto &, const auto &src, const auto cell) {
phi.reinit(cell);
phi.read_dof_values(src);
for (auto face = 0u; face < dim * 2; face++)
{
phi_m.reinit(cell, face);
phi_m.read_dof_values(src);
phi_p.reinit(cell, face);
phi_p.read_dof_values(src);
for (unsigned int q = 0;
q <
dealii::Utilities::pow<unsigned int>(n_points, dim - 1);
++q)
{
if (std::abs(phi_p.get_data_ptr()[q] -
phi.get_data_ptr()
[matrix_free.get_shape_info()
.face_to_cell_index_nodal[face][q]])[0] >
1e-8 &&
std::abs(phi_p.get_data_ptr()[q] -
phi_m.get_data_ptr()[q])[0] > 1e-8)
failed.insert({cell.macro, face});
}
}
},
vec,
vec,
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values);
if (failed.empty())
deallog << "succeeded!" << std::endl;
else
{
for (auto i : failed)
deallog << i.first << "/" << i.second << " ";
deallog << " failed!" << std::endl;
}
}
MPI_Comm_free(&comm_global);
}
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
const MPI_Comm comm = MPI_COMM_WORLD;
for (unsigned int i = 0; i < 16; ++i)
for (unsigned int j = 0; j < 16; ++j)
test<3,
3,
3,
4,
double,
dealii::VectorizedArray<double, 1>,
dealii::LinearAlgebra::distributed::Vector<double>>(comm, i, j);
}
| 9,247
|
C++
|
.cc
| 237
| 26.628692
| 79
| 0.482932
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,107
|
poisson_03.cc
|
hyperdeal_hyperdeal/tests/poisson/poisson_03.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test hyperdeal::Utilities::decompose.
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/subscriptor.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/manifold_lib.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/matrix_free/fe_evaluation.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <deal.II/multigrid/mg_coarse.h>
#include <deal.II/multigrid/mg_matrix.h>
#include <deal.II/multigrid/mg_smoother.h>
#include <deal.II/multigrid/mg_transfer_matrix_free.h>
#include <deal.II/multigrid/multigrid.h>
#include "../tests.h"
using namespace dealii;
#include <hyper.deal/../../examples/vlasov_poisson/include/poisson.h>
const MPI_Comm comm = MPI_COMM_WORLD;
template <int dim,
int fe_degree,
int n_q_points_1d = fe_degree + 1,
typename Number = double,
typename VectorizedArrayType = VectorizedArray<Number>>
void
test(const bool do_test_multigrid)
{
using MatrixFreeType = MatrixFree<dim, Number, VectorizedArrayType>;
using VectorType = LinearAlgebra::distributed::Vector<Number>;
using MatrixType =
LaplaceOperator<dim, fe_degree, n_q_points_1d, Number, VectorizedArrayType>;
// create triangulation
std::shared_ptr<Triangulation<dim>> tria;
const auto create_grid = [](auto &tria) {
const double R = 6.2;
const double r = 2.0;
dealii::GridGenerator::torus(tria, R, r);
tria.reset_all_manifolds();
tria.set_manifold(1, TorusManifold<3>(R, r));
tria.set_manifold(0,
CylindricalManifold<3>(Tensor<1, 3>({0., 1., 0.}),
Point<3>()));
tria.set_manifold(2,
CylindricalManifold<3>(Tensor<1, 3>({0., 1., 0.}),
Point<3>()));
tria.refine_global(2);
};
if (true)
{
dealii::Triangulation<dim> tria_serial(
dealii::Triangulation<dim>::limit_level_difference_at_vertices);
create_grid(tria_serial);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria_serial, false);
dealii::GridTools::partition_multigrid_levels(tria_serial);
const auto construction_data = dealii::TriangulationDescription::
Utilities::create_description_from_triangulation(
tria_serial,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
tria.reset(new parallel::fullydistributed::Triangulation<dim>(comm));
const auto manifold_ids = tria_serial.get_manifold_ids();
for (const auto manifold_id : manifold_ids)
if (manifold_id != dealii::numbers::flat_manifold_id)
{
auto manifold = tria_serial.get_manifold(manifold_id).clone();
if (auto temp =
dynamic_cast<dealii::TransfiniteInterpolationManifold<dim> *>(
manifold.get()))
temp->initialize(*tria);
tria->set_manifold(manifold_id, *manifold);
}
tria->create_triangulation(construction_data);
}
else
{
tria.reset(new dealii::Triangulation<dim>(
dealii::Triangulation<
dim>::MeshSmoothing::limit_level_difference_at_vertices));
create_grid(*tria);
}
#if true
dealii::GridOut grid_out;
grid_out.write_mesh_per_processor_as_vtu(*tria, "grid");
#endif
// create dof handler
DoFHandler<dim> dof(*tria);
FE_DGQ<dim> fe(fe_degree);
dof.distribute_dofs(fe);
dof.distribute_mg_dofs();
// create matrix free
MatrixFreeType matrix_free;
QGauss<1> quad(n_q_points_1d);
MappingQ<dim> mapping(fe_degree + 1);
AffineConstraints<Number> constraints;
constraints.close();
typename MatrixFreeType::AdditionalData data;
data.mapping_update_flags_inner_faces = update_gradients | update_JxW_values;
data.mapping_update_flags_boundary_faces =
update_gradients | update_JxW_values;
matrix_free.reinit(mapping, dof, constraints, quad, data);
// create vectors
LinearAlgebra::distributed::Vector<Number> sol, in;
matrix_free.initialize_dof_vector(sol);
matrix_free.initialize_dof_vector(in);
in = 1.0;
// create operator
MatrixType fine_matrix;
fine_matrix.initialize(matrix_free, LaplaceOperatorBCType::DBC);
std::shared_ptr<PoissonSolverBase<VectorType>> solver;
// create solver and solve
if (do_test_multigrid == false) // solve with PCG + Chebychev preconditioner
{
solver.reset(new PoissonSolver<MatrixType>(fine_matrix));
}
else // solve with PCG + multigrid preconditioner
{
const unsigned int min_level = 0;
const unsigned int max_level = tria->n_global_levels() - 1;
auto level_matrix_free_ =
std::make_shared<MGLevelObject<MatrixFreeType>>(min_level, max_level);
auto mg_matrices_ =
std::make_shared<MGLevelObject<MatrixType>>(min_level, max_level);
auto &level_matrix_free = *level_matrix_free_;
auto &mg_matrices = *mg_matrices_;
// initialize levels
for (unsigned int level = min_level; level <= max_level; level++)
{
// ... initialize matrix_free
data.mg_level = level;
level_matrix_free[level].reinit(
mapping, dof, constraints, quad, data);
// ... initialize level operator
mg_matrices[level].initialize(level_matrix_free[level],
LaplaceOperatorBCType::DBC);
}
solver.reset(new PoissonSolverMG<MatrixType>(fine_matrix,
level_matrix_free_,
mg_matrices_));
}
solver->solve(sol, in);
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
for (unsigned int i = 0; i <= 1; i++)
{
test<3, 1, 2, double>(true);
test<3, 2, 3, double>(true);
}
}
| 7,056
|
C++
|
.cc
| 175
| 33.834286
| 80
| 0.644519
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,108
|
poisson_02.cc
|
hyperdeal_hyperdeal/tests/poisson/poisson_02.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test hyperdeal::Utilities::decompose.
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/subscriptor.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/matrix_free/fe_evaluation.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <deal.II/multigrid/mg_coarse.h>
#include <deal.II/multigrid/mg_matrix.h>
#include <deal.II/multigrid/mg_smoother.h>
#include <deal.II/multigrid/mg_transfer_matrix_free.h>
#include <deal.II/multigrid/multigrid.h>
#include <deal.II/numerics/vector_tools.h>
#include "../tests.h"
using namespace dealii;
#include <hyper.deal/../../examples/vlasov_poisson/include/poisson.h>
const MPI_Comm comm = MPI_COMM_WORLD;
template <int DIM, typename Number = double>
class ExactSolution : public dealii::Function<DIM, Number>
{
public:
ExactSolution(const double time = 0.)
: dealii::Function<DIM, Number>(1, time)
, wave_number(1.)
{}
virtual double
value(const dealii::Point<DIM> &p, const unsigned int = 1) const
{
double result = std::sin(wave_number * p[0] * dealii::numbers::PI);
for (unsigned int d = 1; d < DIM; ++d)
result *= std::cos(wave_number * p[d] * dealii::numbers::PI);
return result;
}
dealii::Tensor<1, DIM>
get_transport_direction() const
{
return advection;
}
private:
dealii::Tensor<1, DIM> advection;
const double wave_number;
};
template <int dim,
int fe_degree,
int n_q_points_1d = fe_degree + 1,
typename Number = double,
typename VectorizedArrayType = VectorizedArray<Number>>
void
test(const bool do_test_multigrid)
{
using MatrixFreeType = MatrixFree<dim, Number, VectorizedArrayType>;
using VectorType = LinearAlgebra::distributed::Vector<Number>;
using MatrixType =
LaplaceOperator<dim, fe_degree, n_q_points_1d, Number, VectorizedArrayType>;
// create triangulation
std::shared_ptr<Triangulation<dim>> tria;
const auto apply_periodicity = [&](dealii::Triangulation<dim> *tria,
const Number & left,
const Number & right,
const int counter) {
std::vector<dealii::GridTools::PeriodicFacePair<
typename dealii::Triangulation<dim>::cell_iterator>>
periodic_faces;
auto cell = tria->begin();
auto endc = tria->end();
for (; cell != endc; ++cell)
{
for (unsigned int face_number = 0;
face_number < dealii::GeometryInfo<dim>::faces_per_cell;
++face_number)
{
// clang-format off
// x-direction
if ((dim >= 1) && (std::fabs(cell->face(face_number)->center()(0) - left) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(0 + counter);
if ((dim >= 1) && (std::fabs(cell->face(face_number)->center()(0) - right) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(1 + counter);
// y-direction
if ((dim >= 2) && (std::fabs(cell->face(face_number)->center()(1) - left) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(2 + counter);
if ((dim >= 2) && (std::fabs(cell->face(face_number)->center()(1) - right) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(3 + counter);
// z-direction
if ((dim >= 3) && (std::fabs(cell->face(face_number)->center()(2) - left) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(4 + counter);
if ((dim >= 3) && (std::fabs(cell->face(face_number)->center()(2) - right) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(5 + counter);
// clang-format on
}
}
// x-direction
if (dim >= 1)
dealii::GridTools::collect_periodic_faces(
*tria, 0 + counter, 1 + counter, 0, periodic_faces);
// y-direction
if (dim >= 2)
dealii::GridTools::collect_periodic_faces(
*tria, 2 + counter, 3 + counter, 1, periodic_faces);
// z-direction
if (dim >= 3)
dealii::GridTools::collect_periodic_faces(
*tria, 4 + counter, 5 + counter, 2, periodic_faces);
tria->add_periodicity(periodic_faces);
};
auto create_grid = [&](auto &tria) {
GridGenerator::hyper_cube(tria);
apply_periodicity(&tria, 0, 1, 0);
tria.refine_global(2);
};
if (false)
{
dealii::Triangulation<dim> tria_serial(
dealii::Triangulation<dim>::limit_level_difference_at_vertices);
create_grid(tria_serial);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria_serial, false);
dealii::GridTools::partition_multigrid_levels(tria_serial);
const auto construction_data = dealii::TriangulationDescription::
Utilities::create_description_from_triangulation(
tria_serial,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
tria.reset(new parallel::fullydistributed::Triangulation<dim>(comm));
tria->create_triangulation(construction_data);
}
else
{
tria.reset(new dealii::Triangulation<dim>(
dealii::Triangulation<
dim>::MeshSmoothing::limit_level_difference_at_vertices));
create_grid(*tria);
}
// create dof handler
DoFHandler<dim> dof(*tria);
FE_DGQ<dim> fe(fe_degree);
dof.distribute_dofs(fe);
dof.distribute_mg_dofs();
// create matrix free
MatrixFreeType matrix_free;
QGauss<1> quad(n_q_points_1d);
MappingQ<dim> mapping(fe_degree + 1);
AffineConstraints<Number> constraints;
constraints.close();
typename MatrixFreeType::AdditionalData data;
data.mapping_update_flags_inner_faces = update_gradients | update_JxW_values;
data.mapping_update_flags_boundary_faces =
update_gradients | update_JxW_values;
matrix_free.reinit(mapping, dof, constraints, quad, data);
// create vectors
LinearAlgebra::distributed::Vector<Number> sol, in;
matrix_free.initialize_dof_vector(sol);
matrix_free.initialize_dof_vector(in);
in = 1.0;
VectorTools::interpolate(dof, ExactSolution<dim, Number>(), in);
in.add(-in.mean_value()); // [TODO]: periodic
// create operator
MatrixType fine_matrix;
fine_matrix.initialize(matrix_free, LaplaceOperatorBCType::PBC);
std::shared_ptr<PoissonSolverBase<VectorType>> solver;
// create solver and solve
if (do_test_multigrid == false) // solve with PCG + Chebychev preconditioner
{
solver.reset(new PoissonSolver<MatrixType>(fine_matrix));
}
else // solve with PCG + multigrid preconditioner
{
const unsigned int min_level = 0;
const unsigned int max_level = tria->n_global_levels() - 1;
auto level_matrix_free_ =
std::make_shared<MGLevelObject<MatrixFreeType>>(min_level, max_level);
auto mg_matrices_ =
std::make_shared<MGLevelObject<MatrixType>>(min_level, max_level);
auto &level_matrix_free = *level_matrix_free_;
auto &mg_matrices = *mg_matrices_;
// initialize levels
for (unsigned int level = min_level; level <= max_level; level++)
{
// ... initialize matrix_free
data.mg_level = level;
level_matrix_free[level].reinit(
mapping, dof, constraints, quad, data);
// ... initialize level operator
mg_matrices[level].initialize(level_matrix_free[level],
LaplaceOperatorBCType::PBC);
}
solver.reset(new PoissonSolverMG<MatrixType>(fine_matrix,
level_matrix_free_,
mg_matrices_));
}
solver->solve(sol, in);
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
for (unsigned int i = 0; i <= 1; i++)
test<1, 1, 2, double>(i);
}
| 9,196
|
C++
|
.cc
| 222
| 34.518018
| 102
| 0.621931
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,109
|
poisson_01.cc
|
hyperdeal_hyperdeal/tests/poisson/poisson_01.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test hyperdeal::Utilities::decompose.
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/subscriptor.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/matrix_free/fe_evaluation.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <deal.II/multigrid/mg_coarse.h>
#include <deal.II/multigrid/mg_matrix.h>
#include <deal.II/multigrid/mg_smoother.h>
#include <deal.II/multigrid/mg_transfer_matrix_free.h>
#include <deal.II/multigrid/multigrid.h>
#include "../tests.h"
using namespace dealii;
#include <hyper.deal/../../examples/vlasov_poisson/include/poisson.h>
const MPI_Comm comm = MPI_COMM_WORLD;
template <int dim,
int fe_degree,
int n_q_points_1d = fe_degree + 1,
typename Number = double,
typename VectorizedArrayType = VectorizedArray<Number>>
void
test(const bool do_test_multigrid)
{
using MatrixFreeType = MatrixFree<dim, Number, VectorizedArrayType>;
using VectorType = LinearAlgebra::distributed::Vector<Number>;
using MatrixType =
LaplaceOperator<dim, fe_degree, n_q_points_1d, Number, VectorizedArrayType>;
// create triangulation
std::shared_ptr<Triangulation<dim>> tria;
auto create_grid = [](auto &tria) {
GridGenerator::hyper_cube(tria);
tria.refine_global(2);
};
if (false)
{
dealii::Triangulation<dim> tria_serial(
dealii::Triangulation<dim>::limit_level_difference_at_vertices);
create_grid(tria_serial);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria_serial, false);
dealii::GridTools::partition_multigrid_levels(tria_serial);
const auto construction_data = dealii::TriangulationDescription::
Utilities::create_description_from_triangulation(
tria_serial,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
tria.reset(new parallel::fullydistributed::Triangulation<dim>(comm));
tria->create_triangulation(construction_data);
}
else
{
tria.reset(new dealii::Triangulation<dim>(
dealii::Triangulation<
dim>::MeshSmoothing::limit_level_difference_at_vertices));
create_grid(*tria);
}
// create dof handler
DoFHandler<dim> dof(*tria);
FE_DGQ<dim> fe(fe_degree);
dof.distribute_dofs(fe);
dof.distribute_mg_dofs();
// create matrix free
MatrixFreeType matrix_free;
QGauss<1> quad(n_q_points_1d);
MappingQ<dim> mapping(fe_degree + 1);
AffineConstraints<Number> constraints;
constraints.close();
typename MatrixFreeType::AdditionalData data;
data.mapping_update_flags_inner_faces = update_gradients | update_JxW_values;
data.mapping_update_flags_boundary_faces =
update_gradients | update_JxW_values;
matrix_free.reinit(mapping, dof, constraints, quad, data);
// create vectors
LinearAlgebra::distributed::Vector<Number> sol, in;
matrix_free.initialize_dof_vector(sol);
matrix_free.initialize_dof_vector(in);
in = 1.0;
// create operator
MatrixType fine_matrix;
fine_matrix.initialize(matrix_free, LaplaceOperatorBCType::DBC);
std::shared_ptr<PoissonSolverBase<VectorType>> solver;
// create solver and solve
if (do_test_multigrid == false) // solve with PCG + Chebychev preconditioner
{
solver.reset(new PoissonSolver<MatrixType>(fine_matrix));
}
else // solve with PCG + multigrid preconditioner
{
const unsigned int min_level = 0;
const unsigned int max_level = tria->n_global_levels() - 1;
auto level_matrix_free_ =
std::make_shared<MGLevelObject<MatrixFreeType>>(min_level, max_level);
auto mg_matrices_ =
std::make_shared<MGLevelObject<MatrixType>>(min_level, max_level);
auto &level_matrix_free = *level_matrix_free_;
auto &mg_matrices = *mg_matrices_;
// initialize levels
for (unsigned int level = min_level; level <= max_level; level++)
{
// ... initialize matrix_free
data.mg_level = level;
level_matrix_free[level].reinit(
mapping, dof, constraints, quad, data);
// ... initialize level operator
mg_matrices[level].initialize(level_matrix_free[level],
LaplaceOperatorBCType::DBC);
}
solver.reset(new PoissonSolverMG<MatrixType>(fine_matrix,
level_matrix_free_,
mg_matrices_));
}
solver->solve(sol, in);
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
for (unsigned int i = 0; i <= 1; i++)
{
test<2, 1, 2, double>(true);
test<2, 2, 3, double>(true);
test<3, 1, 2, double>(true);
test<3, 2, 3, double>(true);
}
}
| 5,963
|
C++
|
.cc
| 150
| 34.26
| 80
| 0.66326
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,110
|
memory_consumpition_01.cc
|
hyperdeal_hyperdeal/tests/base/memory_consumpition_01.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test shared memory functionality.
#include <deal.II/base/mpi.h>
#include <hyper.deal/base/memory_consumption.h>
#include "../tests.h"
using namespace dealii;
void
test(const MPI_Comm &comm)
{
hyperdeal::MemoryConsumption m1("m1", 1000);
hyperdeal::MemoryConsumption m2("m2");
m2.insert(m1);
m2.insert("m3", 9000);
m1.print(comm, deallog);
deallog << std::endl;
m2.print(comm, deallog);
deallog << std::endl;
m1.print(comm, deallog);
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
const MPI_Comm comm = MPI_COMM_WORLD;
test(comm);
}
| 1,317
|
C++
|
.cc
| 40
| 30.95
| 72
| 0.639241
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,111
|
time_integrators_04.cc
|
hyperdeal_hyperdeal/tests/time_discretization/time_integrators_04.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test integration of a simple ODE: y' = y*sin(t)^2
// Its exact solution is y(t) = y0 * exp( (t - sin(t)*cos(t))/2 )
#include <deal.II/distributed/tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_renumbering.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/lac/trilinos_parallel_block_vector.h>
#include <deal.II/lac/trilinos_vector.h>
#include <hyper.deal/base/time_integrators.h>
#include <hyper.deal/base/time_integrators.templates.h>
#include <tuple>
#include "../tests.h"
const auto comm = MPI_COMM_WORLD;
template <typename VectorType, bool is_block_vector>
std::tuple<VectorType, VectorType, VectorType>
construct_vectors()
{
// Small values to get a meaningful partitioning
constexpr int dim = 2;
constexpr int subdivisions = 4;
constexpr int degree = 1;
// Set up a mock system
parallel::distributed::Triangulation<dim> tria(comm);
GridGenerator::subdivided_hyper_cube(tria, subdivisions, 0, 1);
DoFHandler<dim> dof_handler(tria);
if constexpr (is_block_vector)
{
constexpr auto n_blocks = 2;
const FESystem<dim> fe(FE_Q<dim>(degree), 1, FE_Q<dim>(degree), 1);
dof_handler.distribute_dofs(fe);
DoFRenumbering::block_wise(dof_handler);
const auto dofs_per_block =
DoFTools::count_dofs_per_fe_block(dof_handler);
const auto locally_owned_indices =
dof_handler.locally_owned_dofs().split_by_block(dofs_per_block);
const auto locally_relevant_indices =
DoFTools::extract_locally_relevant_dofs(dof_handler)
.split_by_block(dofs_per_block);
VectorType vct_Ki(locally_owned_indices, comm);
VectorType vct_Ti(locally_owned_indices, comm);
VectorType vct_y(locally_owned_indices, comm);
return std::make_tuple(vct_Ki, vct_Ti, vct_y);
}
else
{
const FE_Q<dim> fe(degree);
dof_handler.distribute_dofs(fe);
const auto locally_owned_indices = dof_handler.locally_owned_dofs();
const auto locally_relevant_indices =
DoFTools::extract_locally_relevant_dofs(dof_handler);
VectorType vct_Ki(locally_owned_indices, comm);
VectorType vct_Ti(locally_owned_indices, comm);
VectorType vct_y(locally_owned_indices, comm);
return std::make_tuple(vct_Ki, vct_Ti, vct_y);
}
}
template <typename Number, typename VectorType, bool is_block_vector = false>
void
test()
{
using Integrator =
hyperdeal::LowStorageRungeKuttaIntegrator<Number, VectorType>;
const auto Niters = 100;
const Number dt = 0.1;
const Number y0 = 1.0;
auto [vct_Ki, vct_Ti, vct_y] =
construct_vectors<VectorType, is_block_vector>();
Integrator integrator(vct_Ki, vct_Ti, "rk45", /*only_Ti_is_ghosted=*/true);
// Initial condition
for (const auto i : vct_y.locally_owned_elements())
vct_y(i) = 1.0;
// Integration loop
const auto rhs =
[](const VectorType &src, VectorType &dst, const Number time) {
const auto time_factor = Utilities::fixed_power<2>(std::sin(time));
for (const auto i : src.locally_owned_elements())
{
dst(i) = src(i) * time_factor;
}
};
for (auto it = 0; it < Niters; ++it)
{
const auto current_t = dt * it;
integrator.perform_time_step(vct_y, current_t, dt, rhs);
}
// Print solution
for (const auto i : vct_y.locally_owned_elements())
deallog << i << " = " << vct_y(i) << std::endl;
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
test<double, dealii::TrilinosWrappers::MPI::Vector>();
deallog << std::endl;
MPI_Barrier(comm);
test<double,
dealii::TrilinosWrappers::MPI::BlockVector,
/*is_block_vector=*/true>();
return 0;
}
| 4,564
|
C++
|
.cc
| 119
| 34.352941
| 77
| 0.663496
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,112
|
time_integrators_02.cc
|
hyperdeal_hyperdeal/tests/time_discretization/time_integrators_02.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test integration of a simple ODE: y' = y*sin(t)^2
// Its exact solution is y(t) = y0 * exp( (t - sin(t)*cos(t))/2 )
#include <deal.II/distributed/tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_renumbering.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/lac/la_parallel_block_vector.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <hyper.deal/base/time_integrators.h>
#include <tuple>
#include "../tests.h"
const auto comm = MPI_COMM_WORLD;
template <typename VectorType, bool is_block_vector>
std::tuple<VectorType, VectorType, VectorType>
construct_vectors()
{
// Small values to get a meaningful partitioning
constexpr int dim = 2;
constexpr int subdivisions = 4;
constexpr int degree = 1;
// Set up a mock system
parallel::distributed::Triangulation<dim> tria(comm);
GridGenerator::subdivided_hyper_cube(tria, subdivisions, 0, 1);
DoFHandler<dim> dof_handler(tria);
if constexpr (is_block_vector)
{
constexpr auto n_blocks = 2;
const FESystem<dim> fe(FE_Q<dim>(degree), 1, FE_Q<dim>(degree), 1);
dof_handler.distribute_dofs(fe);
DoFRenumbering::block_wise(dof_handler);
const auto dofs_per_block =
DoFTools::count_dofs_per_fe_block(dof_handler);
const auto locally_owned_indices =
dof_handler.locally_owned_dofs().split_by_block(dofs_per_block);
const auto locally_relevant_indices =
DoFTools::extract_locally_relevant_dofs(dof_handler)
.split_by_block(dofs_per_block);
VectorType vct_Ki(locally_owned_indices, comm);
VectorType vct_Ti(locally_owned_indices, locally_relevant_indices, comm);
VectorType vct_y(locally_owned_indices, locally_relevant_indices, comm);
return std::make_tuple(vct_Ki, vct_Ti, vct_y);
}
else
{
const FE_Q<dim> fe(degree);
dof_handler.distribute_dofs(fe);
const auto locally_owned_indices = dof_handler.locally_owned_dofs();
const auto locally_relevant_indices =
DoFTools::extract_locally_relevant_dofs(dof_handler);
VectorType vct_Ki(locally_owned_indices, comm);
VectorType vct_Ti(locally_owned_indices, locally_relevant_indices, comm);
VectorType vct_y(locally_owned_indices, locally_relevant_indices, comm);
return std::make_tuple(vct_Ki, vct_Ti, vct_y);
}
}
template <typename Number, typename VectorType, bool is_block_vector = false>
void
test()
{
using Integrator =
hyperdeal::LowStorageRungeKuttaIntegrator<Number, VectorType>;
const auto Niters = 100;
const Number dt = 0.1;
const Number y0 = 1.0;
auto [vct_Ki, vct_Ti, vct_y] =
construct_vectors<VectorType, is_block_vector>();
Integrator integrator(vct_Ki, vct_Ti, "rk45", /*only_Ti_is_ghosted=*/true);
// Initial condition
for (const auto i : vct_y.locally_owned_elements())
vct_y(i) = 1.0;
// Integration loop
const auto rhs =
[](const VectorType &src, VectorType &dst, const Number time) {
const auto time_factor = Utilities::fixed_power<2>(std::sin(time));
for (const auto i : src.locally_owned_elements())
{
dst(i) = src(i) * time_factor;
}
};
for (auto it = 0; it < Niters; ++it)
{
const auto current_t = dt * it;
integrator.perform_time_step(vct_y, current_t, dt, rhs);
}
// Print solution
for (const auto i : vct_y.locally_owned_elements())
deallog << i << " = " << vct_y(i) << std::endl;
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
test<double, dealii::LinearAlgebra::distributed::Vector<double>>();
deallog << std::endl;
MPI_Barrier(comm);
test<double,
dealii::LinearAlgebra::distributed::BlockVector<double>,
/*is_block_vector=*/true>();
return 0;
}
| 4,635
|
C++
|
.cc
| 118
| 35.254237
| 79
| 0.666444
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,113
|
time_integrators_01.cc
|
hyperdeal_hyperdeal/tests/time_discretization/time_integrators_01.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test number of stages of time integrators.
#include <deal.II/lac/la_parallel_vector.h>
#include <hyper.deal/base/time_integrators.h>
#include "../tests.h"
int
main()
{
initlog();
using Number = double;
using VectorType = dealii::LinearAlgebra::distributed::Vector<Number>;
using Integrator =
hyperdeal::LowStorageRungeKuttaIntegrator<Number, VectorType>;
VectorType vct_Ki, vct_Ti;
deallog << Integrator(vct_Ki, vct_Ti, "rk33").n_stages() << std::endl;
deallog << Integrator(vct_Ki, vct_Ti, "rk45").n_stages() << std::endl;
deallog << Integrator(vct_Ki, vct_Ti, "rk47").n_stages() << std::endl;
deallog << Integrator(vct_Ki, vct_Ti, "rk59").n_stages() << std::endl;
}
| 1,353
|
C++
|
.cc
| 32
| 40.3125
| 72
| 0.641006
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,114
|
time_integrators_03.cc
|
hyperdeal_hyperdeal/tests/time_discretization/time_integrators_03.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test integration of a simple ODE: y' = y*sin(t)^2
// Its exact solution is y(t) = y0 * exp( (t - sin(t)*cos(t))/2 )
#include <deal.II/distributed/tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_renumbering.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/lac/petsc_block_vector.h>
#include <deal.II/lac/petsc_vector.h>
#include <hyper.deal/base/time_integrators.h>
#include <hyper.deal/base/time_integrators.templates.h>
#include <tuple>
#include "../tests.h"
const auto comm = MPI_COMM_WORLD;
template <typename VectorType, bool is_block_vector>
std::tuple<VectorType, VectorType, VectorType>
construct_vectors()
{
// Small values to get a meaningful partitioning
constexpr int dim = 2;
constexpr int subdivisions = 4;
constexpr int degree = 1;
// Set up a mock system
parallel::distributed::Triangulation<dim> tria(comm);
GridGenerator::subdivided_hyper_cube(tria, subdivisions, 0, 1);
DoFHandler<dim> dof_handler(tria);
if constexpr (is_block_vector)
{
constexpr auto n_blocks = 2;
const FESystem<dim> fe(FE_Q<dim>(degree), 1, FE_Q<dim>(degree), 1);
dof_handler.distribute_dofs(fe);
DoFRenumbering::block_wise(dof_handler);
const auto dofs_per_block =
DoFTools::count_dofs_per_fe_block(dof_handler);
const auto locally_owned_indices =
dof_handler.locally_owned_dofs().split_by_block(dofs_per_block);
const auto locally_relevant_indices =
DoFTools::extract_locally_relevant_dofs(dof_handler)
.split_by_block(dofs_per_block);
VectorType vct_Ki(locally_owned_indices, comm);
VectorType vct_Ti(locally_owned_indices, comm);
VectorType vct_y(locally_owned_indices, comm);
return std::make_tuple(vct_Ki, vct_Ti, vct_y);
}
else
{
const FE_Q<dim> fe(degree);
dof_handler.distribute_dofs(fe);
const auto locally_owned_indices = dof_handler.locally_owned_dofs();
const auto locally_relevant_indices =
DoFTools::extract_locally_relevant_dofs(dof_handler);
VectorType vct_Ki(locally_owned_indices, comm);
VectorType vct_Ti(locally_owned_indices, comm);
VectorType vct_y(locally_owned_indices, comm);
return std::make_tuple(vct_Ki, vct_Ti, vct_y);
}
}
template <typename Number, typename VectorType, bool is_block_vector = false>
void
test()
{
using Integrator =
hyperdeal::LowStorageRungeKuttaIntegrator<Number, VectorType>;
const auto Niters = 100;
const Number dt = 0.1;
const Number y0 = 1.0;
auto [vct_Ki, vct_Ti, vct_y] =
construct_vectors<VectorType, is_block_vector>();
Integrator integrator(vct_Ki, vct_Ti, "rk45", /*only_Ti_is_ghosted=*/true);
// Initial condition
for (const auto i : vct_y.locally_owned_elements())
vct_y(i) = 1.0;
// Integration loop
const auto rhs =
[](const VectorType &src, VectorType &dst, const Number time) {
const auto time_factor = Utilities::fixed_power<2>(std::sin(time));
for (const auto i : src.locally_owned_elements())
{
dst(i) = src(i) * time_factor;
}
};
for (auto it = 0; it < Niters; ++it)
{
const auto current_t = dt * it;
integrator.perform_time_step(vct_y, current_t, dt, rhs);
}
// Print solution
for (const auto i : vct_y.locally_owned_elements())
deallog << i << " = " << vct_y(i) << std::endl;
}
int
main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
MPILogInitAll all;
test<double, dealii::PETScWrappers::MPI::Vector>();
deallog << std::endl;
MPI_Barrier(comm);
test<double,
dealii::PETScWrappers::MPI::BlockVector,
/*is_block_vector=*/true>();
return 0;
}
| 4,543
|
C++
|
.cc
| 119
| 34.176471
| 77
| 0.662116
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,115
|
grid_generator.cc
|
hyperdeal_hyperdeal/source/grid/grid_generator.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/grid/manifold_lib.h>
#include <hyper.deal/grid/grid_generator.h>
namespace hyperdeal
{
/**
* TODO: replace shared_ptr!
*/
namespace GridGenerator
{
namespace internal
{
template <int dim_>
void
apply_periodicity(dealii::Triangulation<dim_> *tria,
const dealii::Point<dim_> & left,
const dealii::Point<dim_> & right,
const int counter = 0)
{
std::vector<dealii::GridTools::PeriodicFacePair<
typename dealii::Triangulation<dim_>::cell_iterator>>
periodic_faces;
auto cell = tria->begin();
auto endc = tria->end();
for (; cell != endc; ++cell)
{
for (unsigned int face_number = 0;
face_number < dealii::GeometryInfo<dim_>::faces_per_cell;
++face_number)
{
// x-direction
if ((dim_ >= 1) &&
(std::fabs(cell->face(face_number)->center()(0) - left[0]) <
1e-12))
cell->face(face_number)->set_all_boundary_ids(0 + counter);
if ((dim_ >= 1) &&
(std::fabs(cell->face(face_number)->center()(0) -
right[0]) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(1 + counter);
// y-direction
if ((dim_ >= 2) &&
(std::fabs(cell->face(face_number)->center()(1) - left[1]) <
1e-12))
cell->face(face_number)->set_all_boundary_ids(2 + counter);
if ((dim_ >= 2) &&
(std::fabs(cell->face(face_number)->center()(1) -
right[1]) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(3 + counter);
// z-direction
if ((dim_ >= 3) &&
(std::fabs(cell->face(face_number)->center()(2) - left[2]) <
1e-12))
cell->face(face_number)->set_all_boundary_ids(4 + counter);
if ((dim_ >= 3) &&
(std::fabs(cell->face(face_number)->center()(2) -
right[2]) < 1e-12))
cell->face(face_number)->set_all_boundary_ids(5 + counter);
}
}
// x-direction
if (dim_ >= 1)
dealii::GridTools::collect_periodic_faces(
*tria, 0 + counter, 1 + counter, 0, periodic_faces);
// y-direction
if (dim_ >= 2)
dealii::GridTools::collect_periodic_faces(
*tria, 2 + counter, 3 + counter, 1, periodic_faces);
// z-direction
if (dim_ >= 3)
dealii::GridTools::collect_periodic_faces(
*tria, 4 + counter, 5 + counter, 2, periodic_faces);
tria->add_periodicity(periodic_faces);
}
template <int dim_>
void
apply_periodicity(dealii::Triangulation<dim_> *tria,
const int counter = 0,
const double left = 0.0,
const double right = 1.0)
{
// clang-format off
const dealii::Point< dim_ > point_left = dim_ == 1 ? dealii::Point< dim_ >(left) : (dim_ == 2 ? dealii::Point< dim_ >(left, left) : dealii::Point< dim_ >(left, left, left));
const dealii::Point< dim_ > point_right = dim_ == 1 ? dealii::Point< dim_ >(right) : (dim_ == 2 ? dealii::Point< dim_ >(right, right) : dealii::Point< dim_ >(right, right, right));
// clang-format on
apply_periodicity(tria, counter, point_left, point_right);
}
template <int dim>
class DeformedCubeManifold : public dealii::ChartManifold<dim, dim, dim>
{
public:
DeformedCubeManifold(const dealii::Point<dim> left,
const dealii::Point<dim> right,
const double deformation = 0.1,
const unsigned int frequency = 2)
: left(left[0])
, right(right[0])
, deformation(deformation)
, frequency(frequency)
{
const auto check = [](const auto &points) {
for (unsigned int d = 1; d < dim; ++d)
if (points[0] != points[d])
return false;
return true;
};
AssertThrow(check(left),
dealii::StandardExceptions::ExcInternalError());
AssertThrow(check(right),
dealii::StandardExceptions::ExcInternalError());
}
DeformedCubeManifold(const double left,
const double right,
const double deformation = 0.1,
const unsigned int frequency = 2)
: left(left)
, right(right)
, deformation(deformation)
, frequency(frequency)
{}
dealii::Point<dim>
push_forward(const dealii::Point<dim> &chart_point) const override
{
double sinval = deformation;
for (unsigned int d = 0; d < dim; ++d)
sinval *= std::sin(frequency * dealii::numbers::PI *
(chart_point(d) - left) / (right - left));
dealii::Point<dim> space_point;
for (unsigned int d = 0; d < dim; ++d)
space_point(d) = chart_point(d) + sinval;
return space_point;
}
dealii::Point<dim>
pull_back(const dealii::Point<dim> &space_point) const override
{
dealii::Point<dim> x = space_point;
dealii::Point<dim> one;
for (unsigned int d = 0; d < dim; ++d)
one(d) = 1.;
// Newton iteration to solve the nonlinear equation given by the point
dealii::Tensor<1, dim> sinvals;
for (unsigned int d = 0; d < dim; ++d)
sinvals[d] = std::sin(frequency * dealii::numbers::PI *
(x(d) - left) / (right - left));
double sinval = deformation;
for (unsigned int d = 0; d < dim; ++d)
sinval *= sinvals[d];
dealii::Tensor<1, dim> residual = space_point - x - sinval * one;
unsigned int its = 0;
while (residual.norm() > 1e-12 && its < 100)
{
dealii::Tensor<2, dim> jacobian;
for (unsigned int d = 0; d < dim; ++d)
jacobian[d][d] = 1.;
for (unsigned int d = 0; d < dim; ++d)
{
double sinval_der = deformation * frequency / (right - left) *
dealii::numbers::PI *
std::cos(frequency * dealii::numbers::PI *
(x(d) - left) / (right - left));
for (unsigned int e = 0; e < dim; ++e)
if (e != d)
sinval_der *= sinvals[e];
for (unsigned int e = 0; e < dim; ++e)
jacobian[e][d] += sinval_der;
}
x += dealii::invert(jacobian) * residual;
for (unsigned int d = 0; d < dim; ++d)
sinvals[d] = std::sin(frequency * dealii::numbers::PI *
(x(d) - left) / (right - left));
sinval = deformation;
for (unsigned int d = 0; d < dim; ++d)
sinval *= sinvals[d];
residual = space_point - x - sinval * one;
++its;
}
AssertThrow(residual.norm() < 1e-12,
dealii::StandardExceptions::ExcMessage(
"Newton for point did not converge."));
return x;
}
std::unique_ptr<dealii::Manifold<dim>>
clone() const override
{
return std::make_unique<DeformedCubeManifold<dim>>(left,
right,
deformation,
frequency);
}
private:
const double left;
const double right;
const double deformation;
const unsigned int frequency;
};
} // namespace internal
template <int dim_x, int dim_v>
void
subdivided_hyper_rectangle(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int & n_refinements_x,
const std::vector<unsigned int> &repetitions_x,
const dealii::Point<dim_x> & left_x,
const dealii::Point<dim_x> & right_x,
const bool do_periodic_x,
const unsigned int & n_refinements_v,
const std::vector<unsigned int> &repetitions_v,
const dealii::Point<dim_v> & left_v,
const dealii::Point<dim_v> & right_v,
const bool do_periodic_v,
const bool with_internal_deformation)
{
if (auto triangulation_x =
dynamic_cast<dealii::parallel::distributed::Triangulation<dim_x> *>(
&*tria_x))
{
if (auto triangulation_v = dynamic_cast<
dealii::parallel::distributed::Triangulation<dim_v> *>(
&*tria_v))
{
dealii::GridGenerator::subdivided_hyper_rectangle(
*triangulation_x, repetitions_x, left_x, right_x);
dealii::GridGenerator::subdivided_hyper_rectangle(
*triangulation_v, repetitions_v, left_v, right_v);
if (do_periodic_x)
internal::apply_periodicity(triangulation_x, left_x, right_x);
if (do_periodic_v)
internal::apply_periodicity(triangulation_v,
left_v,
right_v,
2 * dim_x);
if (with_internal_deformation)
{
static internal::DeformedCubeManifold<dim_x> manifold(
left_x, right_x);
triangulation_x->set_all_manifold_ids(1);
triangulation_x->set_manifold(1, manifold);
}
if (with_internal_deformation)
{
static internal::DeformedCubeManifold<dim_v> manifold(
left_v, right_v);
triangulation_v->set_all_manifold_ids(1);
triangulation_v->set_manifold(1, manifold);
}
triangulation_x->refine_global(n_refinements_x);
triangulation_v->refine_global(n_refinements_v);
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
else if (auto triangulation_x = dynamic_cast<
dealii::parallel::fullydistributed::Triangulation<dim_x> *>(
&*tria_x))
{
if (auto triangulation_v = dynamic_cast<
dealii::parallel::fullydistributed::Triangulation<dim_v> *>(
&*tria_v))
{
{
auto comm = tria_x->get_communicator();
dealii::Triangulation<dim_x> tria(
dealii::Triangulation<
dim_x>::limit_level_difference_at_vertices);
dealii::GridGenerator::subdivided_hyper_rectangle(tria,
repetitions_x,
left_x,
right_x);
if (do_periodic_x)
internal::apply_periodicity(&tria, left_x, right_x);
static internal::DeformedCubeManifold<dim_x> manifold(left_x,
right_x);
if (with_internal_deformation)
{
tria.set_all_manifold_ids(1);
tria.set_manifold(1, manifold);
}
tria.refine_global(n_refinements_x);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria, false);
dealii::GridTools::partition_multigrid_levels(tria);
if (with_internal_deformation)
tria_x->set_manifold(1, manifold);
const auto construction_data =
dealii::TriangulationDescription::Utilities::
create_description_from_triangulation(
tria,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
triangulation_x->create_triangulation(construction_data);
}
if (do_periodic_x)
internal::apply_periodicity(
dynamic_cast<dealii::Triangulation<dim_x> *>(&*tria_x),
left_x,
right_x,
20);
{
auto comm = tria_v->get_communicator();
dealii::Triangulation<dim_v> tria(
dealii::Triangulation<
dim_v>::limit_level_difference_at_vertices);
dealii::GridGenerator::subdivided_hyper_rectangle(tria,
repetitions_v,
left_v,
right_v);
if (do_periodic_v)
internal::apply_periodicity(&tria,
left_v,
right_v,
2 * dim_x);
static internal::DeformedCubeManifold<dim_v> manifold(left_v,
right_v);
if (with_internal_deformation)
{
tria.set_all_manifold_ids(1);
tria.set_manifold(1, manifold);
}
tria.refine_global(n_refinements_v);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria, false);
dealii::GridTools::partition_multigrid_levels(tria);
if (with_internal_deformation)
tria_v->set_manifold(1, manifold);
const auto construction_data =
dealii::TriangulationDescription::Utilities::
create_description_from_triangulation(
tria,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
triangulation_v->create_triangulation(construction_data);
}
if (do_periodic_v)
internal::apply_periodicity(
dynamic_cast<dealii::Triangulation<dim_v> *>(&*tria_v),
left_v,
right_v,
20 + 2 * dim_x);
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
template <int dim_x, int dim_v>
void
hyper_cube(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int &n_refinements_x,
const double left_x,
const double right_x,
const bool do_periodic_x,
const unsigned int &n_refinements_v,
const double left_v,
const double right_v,
const bool do_periodic_v)
{
// clang-format off
const dealii::Point< dim_x > p_left_x = dim_x == 1 ? dealii::Point< dim_x >(left_x) : (dim_x == 2 ? dealii::Point< dim_x >(left_x, left_x) : dealii::Point< dim_x >(left_x, left_x, left_x));
const dealii::Point< dim_x > p_right_x = dim_x == 1 ? dealii::Point< dim_x >(right_x) : (dim_x == 2 ? dealii::Point< dim_x >(right_x, right_x) : dealii::Point< dim_x >(right_x, right_x, right_x));
const dealii::Point< dim_v > p_left_v = dim_v == 1 ? dealii::Point< dim_v >(left_v) : (dim_v == 2 ? dealii::Point< dim_v >(left_v, left_v) : dealii::Point< dim_v >(left_v, left_v, left_v));
const dealii::Point< dim_v > p_right_v = dim_v == 1 ? dealii::Point< dim_v >(right_v) : (dim_v == 2 ? dealii::Point< dim_v >(right_v, right_v) : dealii::Point< dim_v >(right_v, right_v, right_v));
std::vector<unsigned int> repetitions_x(dim_x, 1);
std::vector<unsigned int> repetitions_v(dim_v, 1);
subdivided_hyper_rectangle(tria_x, tria_v,
n_refinements_x, repetitions_x, p_left_x, p_right_x, do_periodic_x,
n_refinements_v, repetitions_v, p_left_v, p_right_v, do_periodic_v);
// clang-format on
}
template <int dim_x, int dim_v>
void
hyper_cube(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const bool do_periodic,
const unsigned int &n_refinements,
const double left,
const double right)
{
// clang-format off
hyper_cube(tria_x, tria_v,
n_refinements, left, right, do_periodic,
n_refinements, left, right, do_periodic);
// clang-format on
}
template <int dim_x, int dim_v>
void
subdivided_hyper_ball(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int & n_refinements_x,
const dealii::Point<dim_x> &left_x,
const dealii::Point<dim_x> &right_x,
const bool do_periodic_x,
const unsigned int & n_refinements_v,
const dealii::Point<dim_v> &left_v,
const dealii::Point<dim_v> &right_v,
const bool do_periodic_v)
{
if (auto triangulation_x =
dynamic_cast<dealii::parallel::distributed::Triangulation<dim_x> *>(
&*tria_x))
{
if (auto triangulation_v = dynamic_cast<
dealii::parallel::distributed::Triangulation<dim_v> *>(
&*tria_v))
{
dealii::GridGenerator::hyper_ball(
*triangulation_x,
dim_x == 2 ? dealii::Point<dim_x>(0.0, 0.0) :
dealii::Point<dim_x>(0.0, 0.0, 0.0),
2.0 * (dim_x == 2 ? std::sqrt(0.5) : std::sqrt(0.75)));
for (auto &cell : triangulation_x->cell_iterators())
cell->set_all_manifold_ids(dealii::numbers::flat_manifold_id);
;
dealii::GridGenerator::hyper_ball(
*triangulation_v,
dim_v == 2 ? dealii::Point<dim_v>(0.0, 0.0) :
dealii::Point<dim_v>(0.0, 0.0, 0.0),
2.0 * (dim_v == 2 ? std::sqrt(0.5) : std::sqrt(0.75)));
for (auto &cell : triangulation_v->cell_iterators())
cell->set_all_manifold_ids(dealii::numbers::flat_manifold_id);
if (do_periodic_x)
internal::apply_periodicity(triangulation_x, left_x, right_x);
if (do_periodic_v)
internal::apply_periodicity(triangulation_v,
left_v,
right_v,
2 * dim_x);
triangulation_x->refine_global(n_refinements_x);
triangulation_v->refine_global(n_refinements_v);
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
else if (auto triangulation_x = dynamic_cast<
dealii::parallel::fullydistributed::Triangulation<dim_x> *>(
&*tria_x))
{
if (auto triangulation_v = dynamic_cast<
dealii::parallel::fullydistributed::Triangulation<dim_v> *>(
&*tria_v))
{
{
auto comm = tria_x->get_communicator();
dealii::Triangulation<dim_x> tria(
dealii::Triangulation<
dim_x>::limit_level_difference_at_vertices);
dealii::GridGenerator::hyper_ball(
tria,
dim_x == 2 ? dealii::Point<dim_x>(0.0, 0.0) :
dealii::Point<dim_x>(0.0, 0.0, 0.0),
2.0 * (dim_x == 2 ? std::sqrt(0.5) : std::sqrt(0.75)));
for (auto &cell : tria.cell_iterators())
cell->set_all_manifold_ids(dealii::numbers::flat_manifold_id);
if (do_periodic_x)
internal::apply_periodicity(&tria, left_x, right_x);
tria.refine_global(n_refinements_x);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria, false);
dealii::GridTools::partition_multigrid_levels(tria);
const auto construction_data =
dealii::TriangulationDescription::Utilities::
create_description_from_triangulation(
tria,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
triangulation_x->create_triangulation(construction_data);
}
if (do_periodic_x)
internal::apply_periodicity(
dynamic_cast<dealii::Triangulation<dim_x> *>(&*tria_x),
left_x,
right_x,
20);
{
auto comm = tria_v->get_communicator();
dealii::Triangulation<dim_v> tria(
dealii::Triangulation<
dim_v>::limit_level_difference_at_vertices);
;
dealii::GridGenerator::hyper_ball(
tria,
dim_v == 2 ? dealii::Point<dim_v>(0.0, 0.0) :
dealii::Point<dim_v>(0.0, 0.0, 0.0),
2.0 * (dim_v == 2 ? std::sqrt(0.5) : std::sqrt(0.75)));
for (auto &cell : tria.cell_iterators())
cell->set_all_manifold_ids(dealii::numbers::flat_manifold_id);
if (do_periodic_v)
internal::apply_periodicity(&tria,
left_v,
right_v,
2 * dim_x);
tria.refine_global(n_refinements_v);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria, false);
dealii::GridTools::partition_multigrid_levels(tria);
const auto construction_data =
dealii::TriangulationDescription::Utilities::
create_description_from_triangulation(
tria,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
triangulation_v->create_triangulation(construction_data);
}
if (do_periodic_v)
internal::apply_periodicity(
dynamic_cast<dealii::Triangulation<dim_v> *>(&*tria_v),
left_v,
right_v,
20 + 2 * dim_x);
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
template <int dim>
void
orientated_hyper_cube_impl(dealii::Triangulation<dim> &, int)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
template <>
void orientated_hyper_cube_impl(dealii::Triangulation<3> &triangulation,
int orientation)
{
AssertIndexRange(orientation, 16);
dealii::Point<3> vertices_1[] = {dealii::Point<3>(-1., -1., -1.),
dealii::Point<3>(+1., -1., -1.),
dealii::Point<3>(-1., +1., -1.),
dealii::Point<3>(+1., +1., -1.),
dealii::Point<3>(-1., -1., +0.),
dealii::Point<3>(+1., -1., +0.),
dealii::Point<3>(-1., +1., +0.),
dealii::Point<3>(+1., +1., +0.),
dealii::Point<3>(-1., -1., +1.),
dealii::Point<3>(+1., -1., +1.),
dealii::Point<3>(-1., +1., +1.),
dealii::Point<3>(+1., +1., +1.)};
std::vector<dealii::Point<3>> vertices(&vertices_1[0], &vertices_1[12]);
std::vector<dealii::CellData<3>> cells(2, dealii::CellData<3>());
/* cell 0 */
int cell_vertices_0[dealii::GeometryInfo<3>::vertices_per_cell] = {
0, 1, 2, 3, 4, 5, 6, 7};
/* cell 1 */
int cell_vertices_1[8][dealii::GeometryInfo<3>::vertices_per_cell] = {
{4, 5, 6, 7, 8, 9, 10, 11},
{5, 7, 4, 6, 9, 11, 8, 10},
{7, 6, 5, 4, 11, 10, 9, 8},
{6, 4, 7, 5, 10, 8, 11, 9},
{9, 8, 11, 10, 5, 4, 7, 6},
{8, 10, 9, 11, 4, 6, 5, 7},
{10, 11, 8, 9, 6, 7, 4, 5},
{11, 9, 10, 8, 7, 5, 6, 4}};
for (const unsigned int j : dealii::GeometryInfo<3>::vertex_indices())
{
cells[orientation < 8 ? 0 : 1].vertices[j] = cell_vertices_0[j];
cells[orientation < 8 ? 1 : 0].vertices[j] =
cell_vertices_1[orientation % 8][j];
}
triangulation.create_triangulation(vertices,
cells,
dealii::SubCellData());
}
template <int dim_x, int dim_v>
void
orientated_hyper_cube(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int & n_refinements_x,
const dealii::Point<dim_x> &left_x,
const dealii::Point<dim_x> &right_x,
const bool do_periodic_x,
const unsigned int & orientation_x,
const unsigned int & n_refinements_v,
const dealii::Point<dim_v> &left_v,
const dealii::Point<dim_v> &right_v,
const bool do_periodic_v,
const unsigned int & orientation_v)
{
if (auto triangulation_x =
dynamic_cast<dealii::parallel::distributed::Triangulation<dim_x> *>(
&*tria_x))
{
if (auto triangulation_v = dynamic_cast<
dealii::parallel::distributed::Triangulation<dim_v> *>(
&*tria_v))
{
orientated_hyper_cube_impl(*triangulation_x, orientation_x);
orientated_hyper_cube_impl(*triangulation_v, orientation_v);
if (do_periodic_x)
internal::apply_periodicity(triangulation_x, left_x, right_x);
if (do_periodic_v)
internal::apply_periodicity(triangulation_v,
left_v,
right_v,
2 * dim_x);
triangulation_x->refine_global(n_refinements_x);
triangulation_v->refine_global(n_refinements_v);
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
else if (auto triangulation_x = dynamic_cast<
dealii::parallel::fullydistributed::Triangulation<dim_x> *>(
&*tria_x))
{
if (auto triangulation_v = dynamic_cast<
dealii::parallel::fullydistributed::Triangulation<dim_v> *>(
&*tria_v))
{
{
auto comm = tria_x->get_communicator();
dealii::Triangulation<dim_x> tria(
dealii::Triangulation<
dim_x>::limit_level_difference_at_vertices);
orientated_hyper_cube_impl(tria, orientation_x);
if (do_periodic_x)
internal::apply_periodicity(&tria, left_x, right_x);
tria.refine_global(n_refinements_x);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria, false);
dealii::GridTools::partition_multigrid_levels(tria);
const auto construction_data =
dealii::TriangulationDescription::Utilities::
create_description_from_triangulation(
tria,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
triangulation_x->create_triangulation(construction_data);
}
if (do_periodic_x)
internal::apply_periodicity(
dynamic_cast<dealii::Triangulation<dim_x> *>(&*tria_x),
left_x,
right_x,
20);
{
auto comm = tria_v->get_communicator();
dealii::Triangulation<dim_v> tria(
dealii::Triangulation<
dim_v>::limit_level_difference_at_vertices);
orientated_hyper_cube_impl(tria, orientation_v);
for (auto &cell : tria.cell_iterators())
cell->set_all_manifold_ids(dealii::numbers::flat_manifold_id);
if (do_periodic_v)
internal::apply_periodicity(&tria,
left_v,
right_v,
2 * dim_x);
tria.refine_global(n_refinements_v);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria, false);
dealii::GridTools::partition_multigrid_levels(tria);
const auto construction_data =
dealii::TriangulationDescription::Utilities::
create_description_from_triangulation(
tria,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
triangulation_v->create_triangulation(construction_data);
}
if (do_periodic_v)
internal::apply_periodicity(
dynamic_cast<dealii::Triangulation<dim_v> *>(&*tria_v),
left_v,
right_v,
20 + 2 * dim_x);
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
template <int dim>
void
construct(std::shared_ptr<dealii::parallel::TriangulationBase<dim>> &tria,
const std::function<void(dealii::Triangulation<dim> &)> fu)
{
if (auto triangulation = dynamic_cast<
dealii::parallel::fullydistributed::Triangulation<dim> *>(&*tria))
{
const auto comm = tria->get_communicator();
dealii::Triangulation<dim> tria(
dealii::Triangulation<dim>::limit_level_difference_at_vertices);
fu(tria);
dealii::GridTools::partition_triangulation_zorder(
dealii::Utilities::MPI::n_mpi_processes(comm), tria, false);
dealii::GridTools::partition_multigrid_levels(tria);
const auto manifold_ids = tria.get_manifold_ids();
for (const auto manifold_id : manifold_ids)
if (manifold_id != dealii::numbers::flat_manifold_id)
{
auto manifold = tria.get_manifold(manifold_id).clone();
triangulation->set_manifold(manifold_id, *manifold);
}
const auto construction_data = dealii::TriangulationDescription::
Utilities::create_description_from_triangulation(
tria,
comm,
dealii::TriangulationDescription::Settings::
construct_multigrid_hierarchy);
triangulation->create_triangulation(construction_data);
}
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
}
template <int dim_x, int dim_v>
void
construct_tensor_product(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const std::function<void(dealii::Triangulation<dim_x> &)> fu_x,
const std::function<void(dealii::Triangulation<dim_v> &)> fu_v)
{
construct<dim_x>(tria_x, fu_x);
construct<dim_v>(tria_v, fu_v);
}
#include "grid_generator.inst"
} // namespace GridGenerator
} // namespace hyperdeal
| 35,352
|
C++
|
.cc
| 745
| 31.656376
| 202
| 0.486631
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,116
|
time_loop.cc
|
hyperdeal_hyperdeal/source/base/time_loop.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/lac/la_parallel_vector.h>
#include <hyper.deal/base/time_loop.h>
namespace hyperdeal
{
template <typename Number, typename VectorType>
void
TimeLoop<Number, VectorType>::reinit(
const TimeLoopParamters<Number> ¶meters)
{
this->time_step = parameters.time_step;
this->start_time = parameters.start_time;
this->final_time = parameters.final_time;
this->max_time_step_number = parameters.max_time_step_number;
}
template <typename Number, typename VectorType>
int
TimeLoop<Number, VectorType>::loop(
VectorType &solution,
const std::function<void(
VectorType &,
const Number,
const Number,
const std::function<void(const VectorType &, VectorType &, const Number)>
&)> & time_integrator,
const std::function<void(const VectorType &, VectorType &, const Number)>
& runnable,
const std::function<void(const Number)> &diagnostics)
{
unsigned int time_step_number = 1; // time step number
// perform diagnostics of the initial condition
diagnostics(start_time);
// perform sequence of time steps (We multiply final_time by 1+1E-13 to
// take care of roundoff errors)
for (Number time = start_time + time_step;
time <= final_time * (1.0000000000001) &&
time_step_number <= max_time_step_number;
time += time_step, ++time_step_number)
{
// perform time step
time_integrator(solution, time - time_step, time_step, runnable);
// perform post-processing (diagnostic, vtk output, ...)
diagnostics(time);
}
return time_step_number - 1;
}
template class TimeLoop<double,
dealii::LinearAlgebra::distributed::Vector<double>>;
} // namespace hyperdeal
| 2,502
|
C++
|
.cc
| 62
| 35.645161
| 79
| 0.631839
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,117
|
time_integrators.cc
|
hyperdeal_hyperdeal/source/base/time_integrators.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/lac/la_parallel_block_vector.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <hyper.deal/base/time_integrators.h>
#include <hyper.deal/base/time_integrators.templates.h>
namespace hyperdeal
{
template class LowStorageRungeKuttaIntegrator<
double,
dealii::LinearAlgebra::distributed::Vector<double>>;
template class LowStorageRungeKuttaIntegrator<
double,
dealii::LinearAlgebra::distributed::BlockVector<double>>;
} // namespace hyperdeal
| 1,135
|
C++
|
.cc
| 27
| 40.148148
| 72
| 0.671196
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,118
|
utilities.cc
|
hyperdeal_hyperdeal/source/base/utilities.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/base/conditional_ostream.h>
#include <deal.II/base/mpi.templates.h>
#include <deal.II/base/revision.h>
#include <hyper.deal/base/revision.h>
#include <hyper.deal/base/utilities.h>
#include <immintrin.h>
#include <algorithm>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <vector>
namespace hyperdeal
{
namespace Utilities
{
std::pair<unsigned int, unsigned int>
lex_to_pair(const unsigned int rank,
const unsigned int size1,
const unsigned int size2)
{
AssertThrow(rank < size1 * size2, dealii::ExcMessage("Invalid rank."));
return {rank % size1, rank / size1};
}
std::pair<unsigned int, unsigned int>
decompose(const unsigned int &number)
{
std::vector<std::pair<unsigned int, unsigned int>> possible_solutions;
// TODO: not optimal since N^2
for (unsigned int i = 1; i <= number; i++)
for (unsigned int j = 1; j <= i; j++)
if (i * j == number)
possible_solutions.emplace_back(i, j);
AssertThrow(possible_solutions.size() > 0,
dealii::ExcMessage("No possible decomposition found!"));
std::sort(possible_solutions.begin(),
possible_solutions.end(),
[](const auto &a, const auto &b) {
return std::abs((int)a.first - (int)a.second) <
std::abs((int)b.first - (int)b.second);
});
return possible_solutions.front();
}
template <typename StreamType>
void
print_version(const StreamType &stream)
{
stream << "-- hyper.deal-version " << std::endl;
stream << "-- hyper.deal-branch: " << HYPER_DEAL_GIT_BRANCH << std::endl;
stream << "-- hyper.deal-hash: " << HYPER_DEAL_GIT_REVISION
<< std::endl;
stream << "-- " << std::endl;
stream << "-- deal.II-version " << std::endl;
stream << "-- deal.II-branch: " << DEAL_II_GIT_BRANCH << std::endl;
stream << "-- deal.II-hash: " << DEAL_II_GIT_REVISION << std::endl;
stream << "-- " << std::endl;
}
// template instantiations
template void
print_version(const dealii::ConditionalOStream &stream);
} // namespace Utilities
} // namespace hyperdeal
| 2,981
|
C++
|
.cc
| 75
| 33.866667
| 79
| 0.587889
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,119
|
function.cc
|
hyperdeal_hyperdeal/source/base/function.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// instantiate functions for higher dimensions since in
// dealii/source/base/function.inst.in it is done only for 1-3
#include <deal.II/base/function.templates.h>
DEAL_II_NAMESPACE_OPEN
template class Function<4, double>;
template class Function<5, double>;
template class Function<6, double>;
namespace Functions
{
template class ZeroFunction<4, double>;
template class ZeroFunction<5, double>;
template class ZeroFunction<6, double>;
} // namespace Functions
DEAL_II_NAMESPACE_CLOSE
| 1,145
|
C++
|
.cc
| 28
| 39.464286
| 72
| 0.674167
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,120
|
mpi.cc
|
hyperdeal_hyperdeal/source/base/mpi.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/base/mpi.templates.h>
#include <hyper.deal/base/mpi.h>
#include <hyper.deal/base/utilities.h>
#include <immintrin.h>
#include <algorithm>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <vector>
namespace hyperdeal
{
namespace mpi
{
MPI_Comm
create_sm(const MPI_Comm &comm)
{
int rank;
MPI_Comm_rank(comm, &rank);
MPI_Comm comm_shared;
MPI_Comm_split_type(
comm, MPI_COMM_TYPE_SHARED, rank, MPI_INFO_NULL, &comm_shared);
return comm_shared;
}
unsigned int
n_procs_of_sm(const MPI_Comm &comm, const MPI_Comm &comm_sm)
{
// determine size of current shared memory communicator
int size_shared;
MPI_Comm_size(comm_sm, &size_shared);
// determine maximum, since some shared memory communicators might not be
// filed completely
int size_shared_max;
MPI_Allreduce(&size_shared, &size_shared_max, 1, MPI_INT, MPI_MAX, comm);
return size_shared_max;
}
std::vector<unsigned int>
procs_of_sm(const MPI_Comm &comm, const MPI_Comm &comm_shared)
{
// extract information from comm
int rank_;
MPI_Comm_rank(comm, &rank_);
const unsigned int rank = rank_;
// extract information from sm-comm
int size_shared;
MPI_Comm_size(comm_shared, &size_shared);
// gather ranks
std::vector<unsigned int> ranks_shared(size_shared);
MPI_Allgather(
&rank, 1, MPI_UNSIGNED, ranks_shared.data(), 1, MPI_INT, comm_shared);
return ranks_shared;
}
template <typename T>
std::vector<std::vector<T>>
allgatherv(const std::vector<T> data_in, const MPI_Comm &comm)
{
int size;
MPI_Comm_size(comm, &size);
std::vector<int> recvcounts(size);
int data_size = data_in.size();
MPI_Allgather(
&data_size, 1, MPI_INT, recvcounts.data(), 1, MPI_INT, comm);
std::vector<int> displs(size + 1);
displs[0] = 0;
for (int i = 0; i < size; i++)
displs[i + 1] = displs[i] + recvcounts[i];
std::vector<T> temp(displs.back());
MPI_Allgatherv(data_in.data(),
data_in.size(),
dealii::Utilities::MPI::mpi_type_id_for_type<T>,
temp.data(),
recvcounts.data(),
displs.data(),
dealii::Utilities::MPI::mpi_type_id_for_type<T>,
comm);
std::vector<std::vector<T>> result(size);
for (int i = 0; i < size; i++)
result[i] = std::vector<T>(temp.begin() + displs[i],
temp.begin() + displs[i + 1]);
return result;
}
void
print_sm(const MPI_Comm &comm, const MPI_Comm &comm_sm)
{
int rank, rank_sm;
MPI_Comm_rank(comm, &rank);
MPI_Comm_rank(comm_sm, &rank_sm);
const auto procs_of_sm_ = procs_of_sm(comm, comm_sm);
MPI_Comm comm_sm_index;
MPI_Comm_split(comm, rank_sm == 0, rank, &comm_sm_index);
if (rank_sm == 0)
{
const auto list = allgatherv(procs_of_sm_, comm_sm_index);
if (rank == 0)
for (unsigned int i = 0; i < list.size(); i++)
{
for (unsigned int j = 0; j < list[i].size(); j++)
printf("%5d ", list[i][j]);
printf("\n");
}
}
MPI_Comm_free(&comm_sm_index);
}
void
print_new_order(const MPI_Comm &comm_old, const MPI_Comm &comm_new)
{
int size, rank, new_number;
MPI_Comm_rank(comm_old, &rank);
MPI_Comm_size(comm_old, &size);
if (comm_new == MPI_COMM_NULL)
new_number = -1;
else
MPI_Comm_rank(comm_new, &new_number);
std::vector<int> recv_data(size);
MPI_Gather(
&new_number, 1, MPI_INT, recv_data.data(), 1, MPI_INT, 0, comm_old);
if (rank == 0)
for (unsigned int i = 0; i < recv_data.size(); i++)
printf("(%5d,%5d)\n", i, recv_data[i]);
}
MPI_Comm
create_row_comm(const MPI_Comm & comm,
const unsigned int size1,
const unsigned int size2)
{
int size, rank;
MPI_Comm_size(comm, &size);
AssertThrow(static_cast<unsigned int>(size) == size1 * size2,
dealii::ExcMessage("Invalid communicator size."));
MPI_Comm_rank(comm, &rank);
MPI_Comm row_comm;
MPI_Comm_split(comm,
Utilities::lex_to_pair(rank, size1, size2).second,
rank,
&row_comm);
return row_comm;
}
MPI_Comm
create_column_comm(const MPI_Comm & comm,
const unsigned int size1,
const unsigned int size2)
{
int size, rank;
MPI_Comm_size(comm, &size);
AssertThrow(static_cast<unsigned int>(size) == size1 * size2,
dealii::ExcMessage("Invalid communicator size."));
MPI_Comm_rank(comm, &rank);
MPI_Comm col_comm;
MPI_Comm_split(comm,
Utilities::lex_to_pair(rank, size1, size2).first,
rank,
&col_comm);
return col_comm;
}
MPI_Comm
create_rectangular_comm(const MPI_Comm & comm,
const unsigned int size_x,
const unsigned int size_v)
{
int rank, size;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &size);
AssertThrow((size_x * size_v) <= static_cast<unsigned int>(size),
dealii::ExcMessage("Not enough ranks."));
MPI_Comm sub_comm;
MPI_Comm_split(comm,
(static_cast<unsigned int>(rank) < (size_x * size_v)),
rank,
&sub_comm);
if (static_cast<unsigned int>(rank) < (size_x * size_v))
return sub_comm;
else
{
MPI_Comm_free(&sub_comm);
return MPI_COMM_NULL;
}
}
#ifndef __AVX2__
unsigned int
_pdep_u32(unsigned int a, unsigned int mask)
{
// Intrinsics command only available from AVX2 upwards. This is a
// workaround for older processor architectures - according to:
// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_pdep_u32&expand=4151
unsigned int dst = 0;
unsigned int tmp = a;
unsigned int k = 0;
for (unsigned int m = 0; m < 32; m++)
if ((mask >> m & 1) == 1)
dst += ((tmp >> k++) & 1) << m;
return dst;
}
#endif
MPI_Comm
create_z_order_comm(const MPI_Comm & comm,
const std::pair<unsigned int, unsigned int> procs,
const std::pair<unsigned int, unsigned int> group_size)
{
const unsigned int size_x = procs.first;
const unsigned int size_v = procs.second;
const unsigned int group_size_x = group_size.first;
const unsigned int group_size_v = group_size.second;
int size, rank;
MPI_Comm_size(comm, &size);
MPI_Comm_rank(comm, &rank);
AssertThrow(static_cast<unsigned int>(size) == size_x * size_v,
dealii::ExcMessage("Invalid communicator size."));
auto new_number = [&](const int i) {
auto xy_to_morton = [](uint32_t x, uint32_t y) {
return _pdep_u32(x, 0x55555555) | _pdep_u32(y, 0xaaaaaaaa);
};
const unsigned int x = i % size_x;
const unsigned int v = i / size_x;
const unsigned int new_number =
xy_to_morton(x / group_size_x, v / group_size_v) * group_size_x *
group_size_v +
(v % group_size_v) * group_size_x + (x % group_size_x);
return new_number + ((x >= (size_x / group_size_x) * group_size_x ||
v >= (size_v / group_size_v) * group_size_v) ?
size_x * size_v :
0);
};
MPI_Comm new_comm;
std::vector<std::pair<unsigned int, unsigned int>> pairs;
for (unsigned int v = 0; v < size_v; v++)
for (unsigned int x = 0; x < size_x; x++)
pairs.emplace_back(x + v * size_x, new_number(x + v * size_x));
std::sort(pairs.begin(), pairs.end(), [](const auto &a, const auto &b) {
return a.second < b.second;
});
MPI_Comm_split(comm, 0, pairs[rank].first, &new_comm);
return new_comm;
}
} // namespace mpi
} // namespace hyperdeal
| 9,239
|
C++
|
.cc
| 248
| 28.274194
| 97
| 0.55023
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,121
|
operators_advection_02.likwid.cc
|
hyperdeal_hyperdeal/performance/operators_advection_02.likwid.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test performance of components of advection operator run as a stand alone.
#define NUMBER_TYPE double
#define MIN_DEGREE 3
#define MAX_DEGREE 5
#define MIN_DIM 2
#define MAX_DIM 6
#define MIN_SIMD_LENGTH 0
#define MAX_SIMD_LENGTH 0
#include <deal.II/matrix_free/evaluation_kernels.h>
#include <hyper.deal/base/dynamic_convergence_table.h>
#include <hyper.deal/grid/grid_generator.h>
#include <hyper.deal/matrix_free/fe_evaluation_cell.h>
#include <hyper.deal/matrix_free/fe_evaluation_cell_inverse.h>
#include <hyper.deal/matrix_free/fe_evaluation_face.h>
#include <hyper.deal/matrix_free/matrix_free.h>
#include <hyper.deal/matrix_free/tools.h>
#include <hyper.deal/operators/advection/advection_operation_parameters.h>
#include <hyper.deal/operators/advection/boundary_descriptor.h>
#include <hyper.deal/operators/advection/cfl.h>
#include <hyper.deal/operators/advection/velocity_field_view.h>
#include "../tests/tests_mf.h"
#include "util/driver.h"
namespace hyperdeal
{
namespace advection
{
enum class AdvectionOperationEvaluationLevel
{
cell,
all_without_neighbor_load,
all
};
/**
* Advection operator. It is defined by a velocity field and by boundary
* conditions.
*/
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorType,
typename VelocityField,
typename VectorizedArrayType>
class AdvectionOperation1
{
public:
using This = AdvectionOperation1<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityField,
VectorizedArrayType>;
using VNumber = VectorizedArrayType;
static const int dim = dim_x + dim_v;
static const dealii::internal::EvaluatorVariant tensorproduct =
dealii::internal::EvaluatorVariant::evaluate_evenodd;
using FECellEval =
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>;
using FEFaceEval =
FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>;
using FECellEval_inv =
FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>;
/**
* Constructor
*/
AdvectionOperation1(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
DynamicConvergenceTable & table)
: data(data)
, table(table)
, do_collocation(false)
{}
/**
* Set boundary condition and velocity field as well as set up internal
* data structures.
*/
void
reinit(
std::shared_ptr<BoundaryDescriptor<dim, Number>> boundary_descriptor,
std::shared_ptr<VelocityField> velocity_field,
const AdvectionOperationParamters additional_data)
{
this->factor_skew = additional_data.factor_skew;
this->boundary_descriptor = boundary_descriptor;
(void)velocity_field;
AssertDimension(
(data.get_matrix_free_x().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation),
(data.get_matrix_free_v().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation));
const bool do_collocation =
data.get_matrix_free_x().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation;
this->do_collocation = do_collocation;
// clang-format off
phi_cell.reset(new FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, 0, 0, 0, 0));
phi_cell_inv.reset(new FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>(data, 0, 0, 0, 0));
phi_cell_inv_co.reset(new FEEvaluationInverse<dim_x, dim_v, degree, degree + 1, Number, VNumber>(data, 0, 0, do_collocation ? 0 : 1, do_collocation ? 0 : 1));
phi_face_m.reset(new FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, true, 0, 0, 0, 0));
phi_face_p.reset(new FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, false, 0, 0, 0, 0));
// clang-format on
const unsigned int n_cells = data.get_matrix_free_x().n_cell_batches() *
data.get_matrix_free_v().n_cell_batches();
const unsigned int n_q_cells =
n_cells * dealii::Utilities::pow(n_points, dim);
const unsigned int n_q_faces =
2 * n_cells * dim * dealii::Utilities::pow(n_points, dim - 1);
JxW_values.resize(n_q_cells, 0);
JxW_inv_values.resize(n_q_cells, 0);
inverse_jacobian_values.resize(
n_q_cells,
Tensor<
2,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>());
JxW_face_values.resize(n_q_faces, 0);
normal_values.resize(
n_q_faces,
Tensor<
1,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>());
}
/**
* Apply operator. Depending on configuration ECL or FCL.
*/
template <AdvectionOperationEvaluationLevel eval_level =
AdvectionOperationEvaluationLevel::all>
void
apply(VectorType & dst,
const VectorType &src,
const Number time,
Timers * timers = nullptr)
{
// set time of boundary functions
boundary_descriptor->set_time(time);
// TODO: also for velocity field
// loop over all cells/faces in phase-space
if (!data.is_ecl_supported()) // FCL
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented());
}
else // ECL
{
if (timers != nullptr)
timers->enter("ECL");
// advection and inverse-mass matrix operator in one go
data.loop_cell_centric(
&This::local_apply_advect_and_inverse_mass_matrix<eval_level>,
this,
dst,
src,
eval_level == AdvectionOperationEvaluationLevel::all ?
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values :
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::none,
timers);
if (timers != nullptr)
timers->leave();
}
}
private:
using ID =
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID;
/**
* Advection + inverse mass-matrix cell operation -> ECL.
*/
template <AdvectionOperationEvaluationLevel eval_level =
AdvectionOperationEvaluationLevel::all>
void
local_apply_advect_and_inverse_mass_matrix(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
VectorType & dst,
const VectorType & src,
const ID cell)
{
(void)data;
auto &phi = *this->phi_cell;
auto &phi_m = *this->phi_face_m;
auto &phi_p = *this->phi_face_p;
auto &phi_inv = *this->phi_cell_inv;
// get data and scratch
VNumber *data_ptr = phi.get_data_ptr();
VNumber *data_ptr1 = phi_m.get_data_ptr();
VNumber *data_ptr2 = phi_p.get_data_ptr();
VNumber *data_ptr_inv = phi_inv.get_data_ptr();
// initialize tensor product kernels
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
n_points,
VNumber,
Number>
eval(*phi.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim - 1,
degree + 1,
n_points,
VNumber,
Number>
eval_face(*phi.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
n_points,
n_points,
VNumber,
Number>
eval_(dealii::AlignedVector<Number>(),
*phi.get_shape_gradients(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
n_points,
VNumber,
Number>
eval_inv(dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>(),
data.get_matrix_free_x()
.get_shape_info()
.data[0]
.inverse_shape_values_eo);
dealii::Tensor<1, dim, VectorizedArrayType> vel; // constant velocity
{
const unsigned int offset =
cell.macro * dealii::Utilities::pow(n_points, dim_x + dim_v);
JxW = &JxW_values[offset];
JxW_inv = &JxW_inv_values[offset];
inverse_jacobian = &inverse_jacobian_values[offset];
}
// clang-format off
// 1) advection: cell contribution
{
// load from global structure
phi.reinit(cell);
phi.read_dof_values(src);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 1) eval.template values<0, true, false>(data_ptr, data_ptr);
if (dim >= 2) eval.template values<1, true, false>(data_ptr, data_ptr);
if (dim >= 3) eval.template values<2, true, false>(data_ptr, data_ptr);
if (dim >= 4) eval.template values<3, true, false>(data_ptr, data_ptr);
if (dim >= 5) eval.template values<4, true, false>(data_ptr, data_ptr);
if (dim >= 6) eval.template values<5, true, false>(data_ptr, data_ptr);
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
// copy quadrature values into buffer
VNumber *buffer = phi_cell_inv->get_data_ptr();
if(eval_level != AdvectionOperationEvaluationLevel::cell)
for (auto i = 0u; i < dealii::Utilities::pow<unsigned int>(n_points, dim); i++)
buffer[i] = data_ptr[i];
// xv-space
{
dealii::AlignedVector<VNumber> scratch_data_array;
scratch_data_array.resize_fast(dealii::Utilities::pow(n_points, dim) * dim);
VNumber *tempp = scratch_data_array.begin();
if(factor_skew != 0.0)
{
if (dim >= 1) eval_.template gradients<0, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 0);
if (dim >= 2) eval_.template gradients<1, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 1);
if (dim >= 3) eval_.template gradients<2, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 2);
if (dim >= 4) eval_.template gradients<3, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 3);
if (dim >= 5) eval_.template gradients<4, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 4);
if (dim >= 6) eval_.template gradients<5, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 5);
}
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
VNumber grad_in[dim];
if(factor_skew != 0.0)
submit_value_cell<false>(data_ptr, - factor_skew * (get_gradient_cell(tempp, q, qx, qv) * vel), q, qx, qv);
if (factor_skew != 1.0)
{
for (int d = 0; d < dim; d++)
grad_in[d] = (1.0-factor_skew) * buffer[q] * vel[d];
submit_gradient_cell(tempp, grad_in, q, qx, qv);
}
}
if(factor_skew != 1.0)
{
if (dim >= 1 && (factor_skew != 0.0))
eval_.template gradients<0, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
else if (dim >= 1)
eval_.template gradients<0, false, false>(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
if (dim >= 2) eval_.template gradients<1, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 1, data_ptr);
if (dim >= 3) eval_.template gradients<2, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 2, data_ptr);
if (dim >= 4) eval_.template gradients<2, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 3, data_ptr);
if (dim >= 5) eval_.template gradients<2, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 4, data_ptr);
if (dim >= 6) eval_.template gradients<2, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 5, data_ptr);
}
}
}
// 2) advection: faces
if(eval_level != AdvectionOperationEvaluationLevel::cell)
for (auto face = 0u; face < dim * 2; face++)
{
// load negative side from buffer
phi_m.reinit(cell, face);
{
const unsigned int offset_face = (cell.macro * 2 * dim + face) * dealii::Utilities::pow(n_points, dim_x + dim_v - 1);
JxW_face = &JxW_face_values[offset_face];
normal = &normal_values[offset_face];
}
const auto bid = data.get_faces_by_cells_boundary_id(cell, face);
// load positive side from global structure
if(bid == dealii::numbers::internal_face_boundary_id)
{
phi_p.reinit(cell, face);
if(eval_level == AdvectionOperationEvaluationLevel::all)
phi_p.read_dof_values(src);
}
if(do_collocation == false)
{
dealii::internal::FEFaceNormalEvaluationImpl<dim, n_points - 1, VectorizedArrayType>::template interpolate_quadrature<true, false>(1, dealii::EvaluationFlags::values, data.get_matrix_free_x().get_shape_info(), /*out=*/data_ptr_inv, /*in=*/data_ptr1, face);
if(degree + 1 == n_points)
{
if (dim >= 2) eval_face.template values<0, true, false>(data_ptr2, data_ptr2);
if (dim >= 3) eval_face.template values<1, true, false>(data_ptr2, data_ptr2);
if (dim >= 4) eval_face.template values<2, true, false>(data_ptr2, data_ptr2);
if (dim >= 5) eval_face.template values<3, true, false>(data_ptr2, data_ptr2);
if (dim >= 6) eval_face.template values<4, true, false>(data_ptr2, data_ptr2);
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
if(bid == dealii::numbers::internal_face_boundary_id)
{
if (face < dim_x * 2)
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x - 1); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = vel * get_normal_vector_face(q);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
submit_value_face<ID::SpaceType::X>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
else
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v - 1); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = vel * get_normal_vector_face(q);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
submit_value_face<ID::SpaceType::V>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
if(do_collocation == false)
dealii::internal::FEFaceNormalEvaluationImpl<dim, n_points - 1, VectorizedArrayType>::template interpolate_quadrature<false, true>(1, dealii::EvaluationFlags::values, data.get_matrix_free_x().get_shape_info(), /*out=*/data_ptr1, /*in=*/data_ptr, face);
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
// 3) inverse mass matrix
{
phi_inv.reinit(cell);
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
submit_inv(data_ptr, q, qx, qv);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 6) eval_inv.template hessians<5, false, false>(data_ptr, data_ptr);
if (dim >= 5) eval_inv.template hessians<4, false, false>(data_ptr, data_ptr);
if (dim >= 4) eval_inv.template hessians<3, false, false>(data_ptr, data_ptr);
if (dim >= 3) eval_inv.template hessians<2, false, false>(data_ptr, data_ptr);
if (dim >= 2) eval_inv.template hessians<1, false, false>(data_ptr, data_ptr);
if (dim >= 1) eval_inv.template hessians<0, false, false>(data_ptr, data_ptr);
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
// write into global structure back
phi.set_dof_values(dst);
}
// clang-format on
}
template <bool do_add>
void
submit_value_cell(VectorizedArrayType *__restrict data_ptr_out,
const VectorizedArrayType values_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
(void)qx;
(void)qv;
const auto jxw = JxW_inv[q];
if (do_add)
data_ptr_out[q] += values_in * jxw;
else
data_ptr_out[q] = values_in * jxw;
}
void
submit_inv(VectorizedArrayType *__restrict data_ptr_out,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
(void)qx;
(void)qv;
data_ptr_out[q] *= JxW_inv[q];
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim, VectorizedArrayType>
get_gradient_cell(const VectorizedArrayType *__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
(void)qx;
(void)qv;
const auto jxw = JxW[q];
const auto &jacobian = inverse_jacobian[qx];
dealii::Tensor<1, dim, VectorizedArrayType> result;
for (auto d = 0u; d < dim; d++)
{
result[d] = jacobian[d][0] * grad_in[q];
for (auto e = 1u; e < dim; ++e)
result[d] +=
(jacobian[d][e] *
grad_in[q + e *
dealii::Utilities::pow<unsigned int>(n_points,
dim_x) *
dealii::Utilities::pow<unsigned int>(n_points,
dim_v)]);
}
return result;
}
inline DEAL_II_ALWAYS_INLINE //
void
submit_gradient_cell(VectorizedArrayType *__restrict data_ptr_out,
const VectorizedArrayType *__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
(void)qx;
(void)qv;
const auto jxw = JxW[q];
const auto &jacobian = inverse_jacobian[qx];
for (auto d = 0u; d < dim; d++)
{
auto new_val = jacobian[0][d] * grad_in[0];
for (auto e = 1u; e < dim; ++e)
new_val += (jacobian[e][d] * grad_in[e]);
data_ptr_out
[q + d * dealii::Utilities::pow<unsigned int>(n_points, dim_x) *
dealii::Utilities::pow<unsigned int>(n_points, dim_v)] =
new_val * jxw;
}
}
template <TensorID::SpaceType stype>
inline DEAL_II_ALWAYS_INLINE //
void
submit_value_face(VectorizedArrayType *__restrict data_ptr,
const VectorizedArrayType &value,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
(void)qx;
(void)qv;
data_ptr[q] = -value * JxW_face[q];
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim, VectorizedArrayType>
get_normal_vector_face(const unsigned int q) const
{
return normal[q];
}
AlignedVector<
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>
JxW_values;
AlignedVector<
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>
JxW_inv_values;
AlignedVector<
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>
JxW_face_values;
AlignedVector<
Tensor<2,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>>
inverse_jacobian_values;
AlignedVector<
Tensor<1,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>>
normal_values;
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX *JxW;
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX *JxW_inv;
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX * JxW_face;
Tensor<2,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX> *inverse_jacobian;
Tensor<1,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX> *normal;
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data;
DynamicConvergenceTable & table;
// clang-format off
std::shared_ptr<FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_cell;
std::shared_ptr<FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_cell_inv;
std::shared_ptr<FEEvaluationInverse<dim_x, dim_v, degree, degree + 1, Number, VNumber>> phi_cell_inv_co;
std::shared_ptr<FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_face_m;
std::shared_ptr<FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_face_p;
// clang-format on
std::shared_ptr<BoundaryDescriptor<dim, Number>> boundary_descriptor;
bool do_collocation;
const double alpha = 1.0;
// skew factor: conservative (skew=0) and convective (skew=1)
double factor_skew = 0.0;
};
/**
* Advection operator. It is defined by a velocity field and by boundary
* conditions.
*/
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorType,
typename VelocityField,
typename VectorizedArrayType>
class AdvectionOperation2
{
public:
using This = AdvectionOperation2<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityField,
VectorizedArrayType>;
using VNumber = VectorizedArrayType;
static const int dim = dim_x + dim_v;
static const dealii::internal::EvaluatorVariant tensorproduct =
dealii::internal::EvaluatorVariant::evaluate_evenodd;
using FECellEval =
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>;
using FEFaceEval =
FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>;
using FECellEval_inv =
FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>;
/**
* Constructor
*/
AdvectionOperation2(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
DynamicConvergenceTable & table)
: data(data)
, table(table)
, do_collocation(false)
{}
/**
* Set boundary condition and velocity field as well as set up internal
* data structures.
*/
void
reinit(
std::shared_ptr<BoundaryDescriptor<dim, Number>> boundary_descriptor,
std::shared_ptr<VelocityField> velocity_field,
const AdvectionOperationParamters additional_data)
{
(void)velocity_field;
this->factor_skew = additional_data.factor_skew;
this->boundary_descriptor = boundary_descriptor;
AssertDimension(
(data.get_matrix_free_x().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation),
(data.get_matrix_free_v().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation));
const bool do_collocation =
data.get_matrix_free_x().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation;
this->do_collocation = do_collocation;
// clang-format off
phi_cell.reset(new FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, 0, 0, 0, 0));
phi_cell_inv.reset(new FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>(data, 0, 0, 0, 0));
phi_cell_inv_co.reset(new FEEvaluationInverse<dim_x, dim_v, degree, degree + 1, Number, VNumber>(data, 0, 0, do_collocation ? 0 : 1, do_collocation ? 0 : 1));
phi_face_m.reset(new FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, true, 0, 0, 0, 0));
phi_face_p.reset(new FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, false, 0, 0, 0, 0));
// clang-format on
const unsigned int n_cells = 1;
const unsigned int n_q_cells =
n_cells * dealii::Utilities::pow(n_points, dim);
const unsigned int n_q_faces =
2 * n_cells * dim * dealii::Utilities::pow(n_points, dim - 1);
JxW_values.resize(n_q_cells, 0);
JxW_inv_values.resize(n_q_cells, 0);
inverse_jacobian_values.resize(
n_q_cells,
Tensor<
2,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>());
JxW_face_values.resize(n_q_faces, 0);
}
/**
* Apply operator. Depending on configuration ECL or FCL.
*/
template <AdvectionOperationEvaluationLevel eval_level =
AdvectionOperationEvaluationLevel::all>
void
apply(VectorType & dst,
const VectorType &src,
const Number time,
Timers * timers = nullptr)
{
// set time of boundary functions
boundary_descriptor->set_time(time);
// TODO: also for velocity field
// loop over all cells/faces in phase-space
if (!data.is_ecl_supported()) // FCL
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented());
}
else // ECL
{
if (timers != nullptr)
timers->enter("ECL");
// advection and inverse-mass matrix operator in one go
data.loop_cell_centric(
&This::local_apply_advect_and_inverse_mass_matrix<eval_level>,
this,
dst,
src,
eval_level == AdvectionOperationEvaluationLevel::all ?
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values :
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::none,
timers);
if (timers != nullptr)
timers->leave();
}
}
private:
using ID =
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID;
/**
* Advection + inverse mass-matrix cell operation -> ECL.
*/
template <AdvectionOperationEvaluationLevel eval_level =
AdvectionOperationEvaluationLevel::all>
void
local_apply_advect_and_inverse_mass_matrix(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
VectorType & dst,
const VectorType & src,
const ID cell)
{
(void)data;
auto &phi = *this->phi_cell;
auto &phi_m = *this->phi_face_m;
auto &phi_p = *this->phi_face_p;
auto &phi_inv = *this->phi_cell_inv;
// get data and scratch
VNumber *data_ptr = phi.get_data_ptr();
VNumber *data_ptr1 = phi_m.get_data_ptr();
VNumber *data_ptr2 = phi_p.get_data_ptr();
VNumber *data_ptr_inv = phi_inv.get_data_ptr();
// initialize tensor product kernels
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
n_points,
VNumber,
Number>
eval(*phi.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim - 1,
degree + 1,
n_points,
VNumber,
Number>
eval_face(*phi.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
n_points,
n_points,
VNumber,
Number>
eval_(dealii::AlignedVector<Number>(),
*phi.get_shape_gradients(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
n_points,
VNumber,
Number>
eval_inv(dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>(),
data.get_matrix_free_x()
.get_shape_info()
.data[0]
.inverse_shape_values_eo);
dealii::Tensor<1, dim, VectorizedArrayType> vel; // constant velocity
{
const unsigned int offset = 0;
JxW = &JxW_values[offset];
JxW_inv = &JxW_inv_values[offset];
inverse_jacobian = &inverse_jacobian_values[offset];
}
// clang-format off
// 1) advection: cell contribution
{
// load from global structure
phi.reinit(cell);
phi.read_dof_values(src);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 1) eval.template values<0, true, false>(data_ptr, data_ptr);
if (dim >= 2) eval.template values<1, true, false>(data_ptr, data_ptr);
if (dim >= 3) eval.template values<2, true, false>(data_ptr, data_ptr);
if (dim >= 4) eval.template values<3, true, false>(data_ptr, data_ptr);
if (dim >= 5) eval.template values<4, true, false>(data_ptr, data_ptr);
if (dim >= 6) eval.template values<5, true, false>(data_ptr, data_ptr);
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
// copy quadrature values into buffer
VNumber *buffer = phi_cell_inv->get_data_ptr();
if(eval_level != AdvectionOperationEvaluationLevel::cell)
for (auto i = 0u; i < dealii::Utilities::pow<unsigned int>(n_points, dim); i++)
buffer[i] = data_ptr[i];
for(unsigned int d = 0; d < dim; ++d)
{
dealii::AlignedVector<VNumber> scratch_data_array;
scratch_data_array.resize_fast(dealii::Utilities::pow(n_points, dim) );
VNumber *tempp = scratch_data_array.begin();
if(factor_skew != 0.0)
{
if (d == 0 && dim_x >= 1) eval_.template gradients<0, true, false>(buffer, tempp);
if (d == 1 && dim_x >= 2) eval_.template gradients<1, true, false>(buffer, tempp);
if (d == 2 && dim_x >= 3) eval_.template gradients<2, true, false>(buffer, tempp);
if (d == 3 && dim_x >= 4) eval_.template gradients<3, true, false>(buffer, tempp);
if (d == 4 && dim_x >= 5) eval_.template gradients<4, true, false>(buffer, tempp);
if (d == 5 && dim_x >= 6) eval_.template gradients<5, true, false>(buffer, tempp);
}
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
if(factor_skew != 0.0)
submit_value_cell<false>(data_ptr, - factor_skew * (get_gradient_cell(tempp, q, qx, qv, d) * vel[d]), q, qx, qv);
if (factor_skew != 1.0)
submit_gradient_cell(tempp, (1.0-factor_skew) * buffer[q] * vel[d], q, qx, qv, d);
}
if(factor_skew != 1.0)
{
if (d == 0 && dim_x >= 1 && (factor_skew != 0.0))
eval_.template gradients<0, false, true >(tempp, data_ptr);
else if (d == 0 && dim_x >= 1)
eval_.template gradients<0, false, false>(tempp, data_ptr);
if (d == 1 && dim_x >= 2) eval_.template gradients<1, false, true >(tempp, data_ptr);
if (d == 2 && dim_x >= 3) eval_.template gradients<2, false, true >(tempp, data_ptr);
if (d == 3 && dim_x >= 4) eval_.template gradients<3, false, true >(tempp, data_ptr);
if (d == 4 && dim_x >= 5) eval_.template gradients<4, false, true >(tempp, data_ptr);
if (d == 5 && dim_x >= 6) eval_.template gradients<5, false, true >(tempp, data_ptr);
}
}
}
// 2) advection: faces
if(eval_level != AdvectionOperationEvaluationLevel::cell)
for (auto face = 0u; face < dim * 2; face++)
{
// load negative side from buffer
phi_m.reinit(cell, face);
{
const unsigned int offset_face = (face) * dealii::Utilities::pow(n_points, dim_x + dim_v - 1);
JxW_face = &JxW_face_values[offset_face];
}
const auto bid = data.get_faces_by_cells_boundary_id(cell, face);
// load positive side from global structure
if(bid == dealii::numbers::internal_face_boundary_id)
{
phi_p.reinit(cell, face);
if(eval_level == AdvectionOperationEvaluationLevel::all)
phi_p.read_dof_values(src);
}
if(do_collocation == false)
{
dealii::internal::FEFaceNormalEvaluationImpl<dim, n_points - 1, VectorizedArrayType>::template interpolate_quadrature<true, false>(1, dealii::EvaluationFlags::values, data.get_matrix_free_x().get_shape_info(), /*out=*/data_ptr_inv, /*in=*/data_ptr1, face);
if(degree + 1 == n_points)
{
if (dim >= 2) eval_face.template values<0, true, false>(data_ptr2, data_ptr2);
if (dim >= 3) eval_face.template values<1, true, false>(data_ptr2, data_ptr2);
if (dim >= 4) eval_face.template values<2, true, false>(data_ptr2, data_ptr2);
if (dim >= 5) eval_face.template values<3, true, false>(data_ptr2, data_ptr2);
if (dim >= 6) eval_face.template values<4, true, false>(data_ptr2, data_ptr2);
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
if(bid == dealii::numbers::internal_face_boundary_id)
{
if (face < dim_x * 2)
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x - 1); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = vel[face/2] * ((face%2==0) ? -1.0 : 1.0 );
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
submit_value_face<ID::SpaceType::X>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
else
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v - 1); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = vel[face/2] * ((face%2==0) ? -1.0 : 1.0 );
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
submit_value_face<ID::SpaceType::V>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
if(do_collocation == false)
{
dealii::internal::FEFaceNormalEvaluationImpl<dim, n_points - 1, VectorizedArrayType>::template interpolate_quadrature<false, true>(1, dealii::EvaluationFlags::values, data.get_matrix_free_x().get_shape_info(), /*out=*/data_ptr1, /*in=*/data_ptr, face);
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
// 3) inverse mass matrix
{
phi_inv.reinit(cell);
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
submit_inv(data_ptr, q, qx, qv);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 6) eval_inv.template hessians<5, false, false>(data_ptr, data_ptr);
if (dim >= 5) eval_inv.template hessians<4, false, false>(data_ptr, data_ptr);
if (dim >= 4) eval_inv.template hessians<3, false, false>(data_ptr, data_ptr);
if (dim >= 3) eval_inv.template hessians<2, false, false>(data_ptr, data_ptr);
if (dim >= 2) eval_inv.template hessians<1, false, false>(data_ptr, data_ptr);
if (dim >= 1) eval_inv.template hessians<0, false, false>(data_ptr, data_ptr);
}
else
{
Assert(false, dealii::StandardExceptions::ExcNotImplemented ());
}
}
// write into global structure back
phi.set_dof_values(dst);
}
// clang-format on
}
template <bool do_add>
void
submit_value_cell(VectorizedArrayType *__restrict data_ptr_out,
const VectorizedArrayType values_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv)
{
(void)qx;
(void)qv;
const auto jxw = JxW_inv[q];
if (do_add)
data_ptr_out[q] += values_in * jxw;
else
data_ptr_out[q] = values_in * jxw;
}
void
submit_inv(VectorizedArrayType *__restrict data_ptr_out,
const unsigned int q,
const unsigned int qx,
const unsigned int qv)
{
(void)qx;
(void)qv;
data_ptr_out[q] *= JxW_inv[q];
}
inline DEAL_II_ALWAYS_INLINE //
VectorizedArrayType
get_gradient_cell(const VectorizedArrayType *__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv,
const unsigned int d)
{
(void)qx;
(void)qv;
return inverse_jacobian[0][d][d] * grad_in[q];
}
inline DEAL_II_ALWAYS_INLINE //
void
submit_gradient_cell(VectorizedArrayType *__restrict data_ptr_out,
const VectorizedArrayType &__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv,
const unsigned int d)
{
(void)qx;
(void)qv;
data_ptr_out[q] = grad_in * JxW[q] * inverse_jacobian[0][d][d];
}
template <TensorID::SpaceType stype>
inline DEAL_II_ALWAYS_INLINE //
void
submit_value_face(VectorizedArrayType *__restrict data_ptr,
const VectorizedArrayType &value,
const unsigned int q,
const unsigned int qx,
const unsigned int qv)
{
(void)qx;
(void)qv;
data_ptr[q] = -value * JxW_face[q];
}
AlignedVector<
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>
JxW_values;
AlignedVector<
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>
JxW_inv_values;
AlignedVector<
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>
JxW_face_values;
AlignedVector<
Tensor<2,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX>>
inverse_jacobian_values;
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX *JxW;
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX *JxW_inv;
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX * JxW_face;
Tensor<2,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX> *inverse_jacobian;
Tensor<1,
dim,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX> *normal;
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data;
DynamicConvergenceTable & table;
// clang-format off
std::shared_ptr<FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_cell;
std::shared_ptr<FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_cell_inv;
std::shared_ptr<FEEvaluationInverse<dim_x, dim_v, degree, degree + 1, Number, VNumber>> phi_cell_inv_co;
std::shared_ptr<FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_face_m;
std::shared_ptr<FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_face_p;
// clang-format on
std::shared_ptr<BoundaryDescriptor<dim, Number>> boundary_descriptor;
bool do_collocation;
const double alpha = 1.0;
// skew factor: conservative (skew=0) and convective (skew=1)
double factor_skew = 0.0;
};
} // namespace advection
} // namespace hyperdeal
template <int dim_x, int dim_v>
struct Parameters
{
Parameters(const std::string & file_name,
const dealii::ConditionalOStream &pcout)
: n_subdivisions_x(dim_x, 0)
, n_subdivisions_v(dim_v, 0)
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
add_parameters(prm);
prm.parse_input_from_json(file, true);
if (print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("General");
prm.add_parameter("Verbose", print_parameter);
prm.add_parameter("Details", details);
prm.add_parameter("Mapping", mapping);
prm.leave_subsection();
prm.enter_subsection("Performance");
prm.add_parameter("Iterations", n_iterations);
prm.add_parameter("IterationsWarmup", n_iterations_warmup);
prm.leave_subsection();
prm.enter_subsection("Case");
prm.add_parameter("NRefinementsX", n_refinements_x);
prm.add_parameter("NRefinementsV", n_refinements_v);
prm.enter_subsection("NSubdivisionsX");
if (dim_x >= 1)
prm.add_parameter("X", n_subdivisions_x[0]);
if (dim_x >= 2)
prm.add_parameter("Y", n_subdivisions_x[1]);
if (dim_x >= 3)
prm.add_parameter("Z", n_subdivisions_x[2]);
prm.leave_subsection();
prm.enter_subsection("NSubdivisionsV");
if (dim_v >= 1)
prm.add_parameter("X", n_subdivisions_v[0]);
if (dim_v >= 2)
prm.add_parameter("Y", n_subdivisions_v[1]);
if (dim_v >= 3)
prm.add_parameter("Z", n_subdivisions_v[2]);
prm.leave_subsection();
prm.leave_subsection();
prm.enter_subsection("AdvectionOperation");
advection_operation_parameters.add_parameters(prm);
prm.leave_subsection();
}
bool print_parameter = false;
bool details = false;
unsigned int n_iterations_warmup = 0;
unsigned int n_iterations = 10;
unsigned int n_refinements_x = 0;
unsigned int n_refinements_v = 0;
std::vector<unsigned int> n_subdivisions_x;
std::vector<unsigned int> n_subdivisions_v;
hyperdeal::advection::AdvectionOperationParamters
advection_operation_parameters;
std::string mapping;
};
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
void
test(const MPI_Comm & comm_global,
const MPI_Comm & comm_sm,
const unsigned int size_x,
const unsigned int size_v,
hyperdeal::DynamicConvergenceTable &table,
const std::string file_name)
{
auto pcout = dealii::ConditionalOStream(
std::cout, dealii::Utilities::MPI::this_mpi_process(comm_global) == 0);
hyperdeal::MatrixFreeWrapper<dim_x, dim_v, Number, VectorizedArrayType>
matrixfree_wrapper(comm_global, comm_sm, size_x, size_v);
const Parameters<dim_x, dim_v> param(file_name, pcout);
// clang-format off
const dealii::Point< dim_x > px_1 = dim_x == 1 ? dealii::Point< dim_x >(0.0) : (dim_x == 2 ? dealii::Point< dim_x >(0.0, 0.0) : dealii::Point< dim_x >(0.0, 0.0, 0.0));
const dealii::Point< dim_x > px_2 = dim_x == 1 ? dealii::Point< dim_x >(1.0) : (dim_x == 2 ? dealii::Point< dim_x >(1.0, 1.0) : dealii::Point< dim_x >(1.0, 1.0, 1.0));
const dealii::Point< dim_v > pv_1 = dim_v == 1 ? dealii::Point< dim_v >(0.0) : (dim_v == 2 ? dealii::Point< dim_v >(0.0, 0.0) : dealii::Point< dim_v >(0.0, 0.0, 0.0));
const dealii::Point< dim_v > pv_2 = dim_v == 1 ? dealii::Point< dim_v >(1.0) : (dim_v == 2 ? dealii::Point< dim_v >(1.0, 1.0) : dealii::Point< dim_v >(1.0, 1.0, 1.0));
// clang-format on
const bool do_periodic_x = true;
const bool do_periodic_v = true;
const hyperdeal::Parameters p(file_name, pcout);
AssertThrow(p.degree == degree,
dealii::StandardExceptions::ExcMessage(
"Degrees " + std::to_string(p.degree) + " and " +
std::to_string(degree) + " do not match!"));
// clang-format off
matrixfree_wrapper.init(p, [&](auto & tria_x, auto & tria_v){hyperdeal::GridGenerator::subdivided_hyper_rectangle(
tria_x, tria_v,
param.n_refinements_x, param.n_subdivisions_x, px_1, px_2, do_periodic_x,
param.n_refinements_v, param.n_subdivisions_v, pv_1, pv_2, do_periodic_v, /*deformation not needed:*/ false);});
// clang-format on
const auto &matrix_free = matrixfree_wrapper.get_matrix_free();
using VectorType = dealii::LinearAlgebra::distributed::Vector<Number>;
using VelocityFieldView =
hyperdeal::advection::ConstantVelocityFieldView<dim_x + dim_v,
Number,
VectorizedArrayType,
dim_x,
dim_v>;
auto boundary_descriptor = std::make_shared<
hyperdeal::advection::BoundaryDescriptor<dim_x + dim_v, Number>>();
auto velocity_field =
std::make_shared<VelocityFieldView>(dealii::Tensor<1, dim_x + dim_v>());
VectorType vec_src, vec_dst;
matrix_free.initialize_dof_vector(vec_src, 0, true, true);
matrix_free.initialize_dof_vector(vec_dst, 0, !p.use_ecl, true);
hyperdeal::Timers timers(false);
if (param.mapping == "full")
{
hyperdeal::advection::AdvectionOperation1<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityFieldView,
VectorizedArrayType>
advection_operation(matrix_free, table);
advection_operation.reinit(boundary_descriptor,
velocity_field,
param.advection_operation_parameters);
timers.enter("apply");
{
hyperdeal::ScopedLikwidTimerWrapper likwid(
std::string("apply") + "_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_global)) +
"_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_sm)) +
"_" + std::to_string(p.use_ecl) + "_" +
std::to_string(VectorizedArrayType::size()) + "_" +
std::to_string(degree) + "_" + std::to_string(dim_x + dim_v));
timers.enter("withtimers");
// run with timers
hyperdeal::ScopedTimerWrapper timer(timers, "total");
for (unsigned int i = 0; i < param.n_iterations; i++)
advection_operation.apply(vec_dst, vec_src, 0.0, &timers);
timers.leave();
}
timers.leave();
}
if (param.mapping == "cartesian")
{
hyperdeal::advection::AdvectionOperation2<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityFieldView,
VectorizedArrayType>
advection_operation(matrix_free, table);
advection_operation.reinit(boundary_descriptor,
velocity_field,
param.advection_operation_parameters);
timers.enter("apply");
{
hyperdeal::ScopedLikwidTimerWrapper likwid(
std::string("apply") + "_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_global)) +
"_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_sm)) +
"_" + std::to_string(p.use_ecl) + "_" +
std::to_string(VectorizedArrayType::size()) + "_" +
std::to_string(degree) + "_" + std::to_string(dim_x + dim_v));
timers.enter("withtimers");
// run with timers
hyperdeal::ScopedTimerWrapper timer(timers, "total");
for (unsigned int i = 0; i < param.n_iterations; i++)
advection_operation.apply(vec_dst, vec_src, 0.0, &timers);
timers.leave();
}
timers.leave();
}
table.set("info->size [DoFs]", matrixfree_wrapper.n_dofs());
table.set(
"info->ghost_size [DoFs]",
Utilities::MPI::sum(matrix_free.get_vector_partitioner()->n_ghost_indices(),
comm_global));
table.set("info->dim_x", dim_x);
table.set("info->dim_v", dim_v);
table.set("info->degree", degree);
table.set("info->v_len", VectorizedArrayType::size());
table.set("info->procs",
dealii::Utilities::MPI::n_mpi_processes(comm_global));
table.set("info->procs_x",
dealii::Utilities::MPI::n_mpi_processes(
matrixfree_wrapper.get_comm_row()));
table.set("info->procs_v",
dealii::Utilities::MPI::n_mpi_processes(
matrixfree_wrapper.get_comm_column()));
table.set("info->procs_sm", dealii::Utilities::MPI::n_mpi_processes(comm_sm));
table.set("apply:total [s]",
timers["apply:withtimers:total"].get_accumulated_time() / 1e6 /
param.n_iterations);
table.set("throughput - all1 [GDoFs/s]",
matrixfree_wrapper.n_dofs() * param.n_iterations /
timers["apply:withtimers:total"].get_accumulated_time() / 1000);
std::vector<std::pair<std::string, std::string>> timer_labels;
// clang-format off
if(p.use_ecl)
{
timer_labels.emplace_back("apply:ECL:update_ghost_values_0", "apply:withtimers:ECL:update_ghost_values_0");
timer_labels.emplace_back("apply:ECL:update_ghost_values_1", "apply:withtimers:ECL:update_ghost_values_1");
timer_labels.emplace_back("apply:ECL:loop" , "apply:withtimers:ECL:loop");
timer_labels.emplace_back("apply:ECL:barrier" , "apply:withtimers:ECL:barrier");
}
else
{
timer_labels.emplace_back("apply:FCL:advection" , "apply:withtimers:FCL:advection");
timer_labels.emplace_back("apply:FCL:advection:update_ghost_values" , "apply:withtimers:FCL:advection:update_ghost_values");
timer_labels.emplace_back("apply:FCL:advection:zero_out_ghosts" , "apply:withtimers:FCL:advection:zero_out_ghosts");
timer_labels.emplace_back("apply:FCL:advection:cell_loop" , "apply:withtimers:FCL:advection:cell_loop");
timer_labels.emplace_back("apply:FCL:advection:face_loop_x" , "apply:withtimers:FCL:advection:face_loop_x");
timer_labels.emplace_back("apply:FCL:advection:face_loop_v" , "apply:withtimers:FCL:advection:face_loop_v");
timer_labels.emplace_back("apply:FCL:advection:boundary_loop_x" , "apply:withtimers:FCL:advection:boundary_loop_x");
timer_labels.emplace_back("apply:FCL:advection:boundary_loop_v" , "apply:withtimers:FCL:advection:boundary_loop_v");
timer_labels.emplace_back("apply:FCL:advection:compress" , "apply:withtimers:FCL:advection:compress");
timer_labels.emplace_back("apply:FCL:mass" , "apply:withtimers:FCL:mass");
}
{
std::vector<double> timing_values(timer_labels.size());
for(unsigned int i = 0; i < timer_labels.size(); i++)
timing_values[i] = timers[timer_labels[i].second].get_accumulated_time() / 1e6 / param.n_iterations;
const auto timing_values_min_max_avg = Utilities::MPI::min_max_avg (timing_values, comm_global);
for(unsigned int i = 0; i < timer_labels.size(); i++)
{
const auto min_max_avg = timing_values_min_max_avg[i];
table.set(timer_labels[i].first + ":avg [s]", min_max_avg.avg);
table.set(timer_labels[i].first + ":min [s]", min_max_avg.min);
table.set(timer_labels[i].first + ":max [s]", min_max_avg.max);
}
}
// clang-format on
}
| 64,591
|
C++
|
.cc
| 1,314
| 35.075342
| 272
| 0.528807
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,122
|
operators_advection_01.likwid.cc
|
hyperdeal_hyperdeal/performance/operators_advection_01.likwid.cc
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
// Test performance of components of advection operator run as a stand alone.
#define NUMBER_TYPE double
#define MIN_DEGREE 3
#define MAX_DEGREE 3
#define MIN_DIM 6
#define MAX_DIM 6
#define MIN_SIMD_LENGTH 0
#define MAX_SIMD_LENGTH 0
#include <hyper.deal/grid/grid_generator.h>
#include <hyper.deal/operators/advection/advection_operation.h>
#include <hyper.deal/operators/advection/cfl.h>
#include <hyper.deal/operators/advection/velocity_field_view.h>
#include "../tests/tests_mf.h"
#include "util/driver.h"
template <int dim_x, int dim_v>
struct Parameters
{
Parameters(const std::string & file_name,
const dealii::ConditionalOStream &pcout)
: n_subdivisions_x(dim_x, 0)
, n_subdivisions_v(dim_v, 0)
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
add_parameters(prm);
prm.parse_input_from_json(file, true);
if (print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("General");
prm.add_parameter("Verbose", print_parameter);
prm.add_parameter("Details", details);
prm.leave_subsection();
prm.enter_subsection("Performance");
prm.add_parameter("Iterations", n_iterations);
prm.add_parameter("IterationsWarmup", n_iterations_warmup);
prm.leave_subsection();
prm.enter_subsection("Case");
prm.add_parameter("NRefinementsX", n_refinements_x);
prm.add_parameter("NRefinementsV", n_refinements_v);
prm.enter_subsection("NSubdivisionsX");
if (dim_x >= 1)
prm.add_parameter("X", n_subdivisions_x[0]);
if (dim_x >= 2)
prm.add_parameter("Y", n_subdivisions_x[1]);
if (dim_x >= 3)
prm.add_parameter("Z", n_subdivisions_x[2]);
prm.leave_subsection();
prm.enter_subsection("NSubdivisionsV");
if (dim_v >= 1)
prm.add_parameter("X", n_subdivisions_v[0]);
if (dim_v >= 2)
prm.add_parameter("Y", n_subdivisions_v[1]);
if (dim_v >= 3)
prm.add_parameter("Z", n_subdivisions_v[2]);
prm.leave_subsection();
prm.leave_subsection();
prm.enter_subsection("AdvectionOperation");
advection_operation_parameters.add_parameters(prm);
prm.leave_subsection();
}
bool print_parameter = false;
bool details = false;
unsigned int n_iterations_warmup = 0;
unsigned int n_iterations = 10;
unsigned int n_refinements_x = 0;
unsigned int n_refinements_v = 0;
std::vector<unsigned int> n_subdivisions_x;
std::vector<unsigned int> n_subdivisions_v;
hyperdeal::advection::AdvectionOperationParamters
advection_operation_parameters;
};
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
void
test(const MPI_Comm & comm_global,
const MPI_Comm & comm_sm,
const unsigned int size_x,
const unsigned int size_v,
hyperdeal::DynamicConvergenceTable &table,
const std::string file_name)
{
auto pcout = dealii::ConditionalOStream(
std::cout, dealii::Utilities::MPI::this_mpi_process(comm_global) == 0);
hyperdeal::MatrixFreeWrapper<dim_x, dim_v, Number, VectorizedArrayType>
matrixfree_wrapper(comm_global, comm_sm, size_x, size_v);
const Parameters<dim_x, dim_v> param(file_name, pcout);
// clang-format off
const dealii::Point< dim_x > px_1 = dim_x == 1 ? dealii::Point< dim_x >(0.0) : (dim_x == 2 ? dealii::Point< dim_x >(0.0, 0.0) : dealii::Point< dim_x >(0.0, 0.0, 0.0));
const dealii::Point< dim_x > px_2 = dim_x == 1 ? dealii::Point< dim_x >(1.0) : (dim_x == 2 ? dealii::Point< dim_x >(1.0, 1.0) : dealii::Point< dim_x >(1.0, 1.0, 1.0));
const dealii::Point< dim_v > pv_1 = dim_v == 1 ? dealii::Point< dim_v >(0.0) : (dim_v == 2 ? dealii::Point< dim_v >(0.0, 0.0) : dealii::Point< dim_v >(0.0, 0.0, 0.0));
const dealii::Point< dim_v > pv_2 = dim_v == 1 ? dealii::Point< dim_v >(1.0) : (dim_v == 2 ? dealii::Point< dim_v >(1.0, 1.0) : dealii::Point< dim_v >(1.0, 1.0, 1.0));
// clang-format on
const bool do_periodic_x = true;
const bool do_periodic_v = true;
const hyperdeal::Parameters p(file_name, pcout);
AssertThrow(p.degree == degree,
dealii::StandardExceptions::ExcMessage(
"Degrees " + std::to_string(p.degree) + " and " +
std::to_string(degree) + " do not match!"));
// clang-format off
matrixfree_wrapper.init(p, [&](auto & tria_x, auto & tria_v){hyperdeal::GridGenerator::subdivided_hyper_rectangle(
tria_x, tria_v,
param.n_refinements_x, param.n_subdivisions_x, px_1, px_2, do_periodic_x,
param.n_refinements_v, param.n_subdivisions_v, pv_1, pv_2, do_periodic_v, /*deformation:*/ true);});
// clang-format on
const auto &matrix_free = matrixfree_wrapper.get_matrix_free();
using VectorType = dealii::LinearAlgebra::distributed::Vector<Number>;
using VelocityFieldView =
hyperdeal::advection::ConstantVelocityFieldView<dim_x + dim_v,
Number,
VectorizedArrayType,
dim_x,
dim_v>;
hyperdeal::advection::AdvectionOperation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityFieldView,
VectorizedArrayType>
advection_operation(matrix_free, table);
auto boundary_descriptor = std::make_shared<
hyperdeal::advection::BoundaryDescriptor<dim_x + dim_v, Number>>();
auto velocity_field =
std::make_shared<VelocityFieldView>(dealii::Tensor<1, dim_x + dim_v>());
advection_operation.reinit(boundary_descriptor,
velocity_field,
param.advection_operation_parameters);
VectorType vec_src, vec_dst;
matrix_free.initialize_dof_vector(vec_src, 0, true, true);
matrix_free.initialize_dof_vector(vec_dst, 0, !p.use_ecl, true);
hyperdeal::Timers timers(false);
{
timers.enter("apply");
{
// run for warm up
for (unsigned int i = 0; i < param.n_iterations_warmup; i++)
advection_operation.template apply<
hyperdeal::advection::AdvectionOperationEvaluationLevel::all>(vec_dst,
vec_src,
0.0);
}
{
timers.enter("withouttimers");
// run without timers
hyperdeal::ScopedTimerWrapper timer(timers, "total");
for (unsigned int i = 0; i < param.n_iterations; i++)
advection_operation.template apply<
hyperdeal::advection::AdvectionOperationEvaluationLevel::all>(vec_dst,
vec_src,
0.0);
timers.leave();
}
{
hyperdeal::ScopedLikwidTimerWrapper likwid(
std::string("apply") + "_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_global)) +
"_" + std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_sm)) +
"_" + std::to_string(p.use_ecl) + "_" +
std::to_string(VectorizedArrayType::size()) + "_" +
std::to_string(degree) + "_" + std::to_string(dim_x + dim_v));
timers.enter("withtimers");
// run with timers
hyperdeal::ScopedTimerWrapper timer(timers, "total");
for (unsigned int i = 0; i < param.n_iterations; i++)
advection_operation.apply(vec_dst, vec_src, 0.0, &timers);
timers.leave();
}
timers.leave();
}
if (param.details)
{
timers.enter("all1");
{
hyperdeal::ScopedLikwidTimerWrapper likwid(
std::string("all1") + "_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_global)) +
"_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_sm)) +
"_" + std::to_string(p.use_ecl) + "_" +
std::to_string(VectorizedArrayType::size()) + "_" +
std::to_string(degree) + "_" + std::to_string(dim_x + dim_v));
timers.enter("withtimers");
// run with timers
hyperdeal::ScopedTimerWrapper timer(timers, "total");
for (unsigned int i = 0; i < param.n_iterations; i++)
advection_operation.template apply<
hyperdeal::advection::AdvectionOperationEvaluationLevel::cell>(
vec_dst, vec_src, 0.0, &timers);
timers.leave();
}
timers.leave();
}
if (param.details)
{
timers.enter("all2");
{
hyperdeal::ScopedLikwidTimerWrapper likwid(
std::string("all2") + "_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_global)) +
"_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_sm)) +
"_" + std::to_string(p.use_ecl) + "_" +
std::to_string(VectorizedArrayType::size()) + "_" +
std::to_string(degree) + "_" + std::to_string(dim_x + dim_v));
timers.enter("withtimers");
// run with timers
hyperdeal::ScopedTimerWrapper timer(timers, "total");
for (unsigned int i = 0; i < param.n_iterations; i++)
advection_operation.template apply<
hyperdeal::advection::AdvectionOperationEvaluationLevel::
all_without_neighbor_load>(vec_dst, vec_src, 0.0, &timers);
timers.leave();
}
timers.leave();
}
if (param.details)
{
timers.enter("all3");
{
hyperdeal::ScopedLikwidTimerWrapper likwid(
std::string("all3") + "_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_global)) +
"_" +
std::to_string(dealii::Utilities::MPI::n_mpi_processes(comm_sm)) +
"_" + std::to_string(p.use_ecl) + "_" +
std::to_string(VectorizedArrayType::size()) + "_" +
std::to_string(degree) + "_" + std::to_string(dim_x + dim_v));
timers.enter("withtimers");
// run with timers
hyperdeal::ScopedTimerWrapper timer(timers, "total");
for (unsigned int i = 0; i < param.n_iterations; i++)
advection_operation.template apply<
hyperdeal::advection::AdvectionOperationEvaluationLevel::all>(
vec_dst, vec_src, 0.0, &timers);
timers.leave();
}
timers.leave();
}
table.set("info->size [DoFs]", matrixfree_wrapper.n_dofs());
table.set("info->size_x [DoFs]", matrixfree_wrapper.n_dofs_x());
table.set("info->size_v [DoFs]", matrixfree_wrapper.n_dofs_v());
table.set(
"info->ghost_size [DoFs]",
Utilities::MPI::sum(matrix_free.get_vector_partitioner()->n_ghost_indices(),
comm_global));
table.set("info->dim_x", dim_x);
table.set("info->dim_v", dim_v);
table.set("info->degree", degree);
table.set("info->v_len", VectorizedArrayType::size());
table.set("info->procs",
dealii::Utilities::MPI::n_mpi_processes(comm_global));
table.set("info->procs_x",
dealii::Utilities::MPI::n_mpi_processes(
matrixfree_wrapper.get_comm_row()));
table.set("info->procs_v",
dealii::Utilities::MPI::n_mpi_processes(
matrixfree_wrapper.get_comm_column()));
table.set("info->procs_sm", dealii::Utilities::MPI::n_mpi_processes(comm_sm));
table.set("throughput without timers [GDoFs/s]",
matrixfree_wrapper.n_dofs() * param.n_iterations /
timers["apply:withouttimers:total"].get_accumulated_time() /
1000);
table.set("throughput [GDoFs/s]",
matrixfree_wrapper.n_dofs() * param.n_iterations /
timers["apply:withtimers:total"].get_accumulated_time() / 1000);
if (param.details)
table.set("throughput - all1 [GDoFs/s]",
matrixfree_wrapper.n_dofs() * param.n_iterations /
timers["all1:withtimers:total"].get_accumulated_time() / 1000);
if (param.details)
table.set("throughput - all2 [GDoFs/s]",
matrixfree_wrapper.n_dofs() * param.n_iterations /
timers["all2:withtimers:total"].get_accumulated_time() / 1000);
if (param.details)
table.set("throughput - all3 [GDoFs/s]",
matrixfree_wrapper.n_dofs() * param.n_iterations /
timers["all3:withtimers:total"].get_accumulated_time() / 1000);
table.set("apply:total [s]",
timers["apply:withtimers:total"].get_accumulated_time() / 1e6 /
param.n_iterations);
std::vector<std::pair<std::string, std::string>> timer_labels;
// clang-format off
if(p.use_ecl)
{
timer_labels.emplace_back("apply:ECL:update_ghost_values_0", "apply:withtimers:ECL:update_ghost_values_0");
timer_labels.emplace_back("apply:ECL:update_ghost_values_1", "apply:withtimers:ECL:update_ghost_values_1");
timer_labels.emplace_back("apply:ECL:loop" , "apply:withtimers:ECL:loop");
timer_labels.emplace_back("apply:ECL:barrier" , "apply:withtimers:ECL:barrier");
}
else
{
timer_labels.emplace_back("apply:FCL:advection" , "apply:withtimers:FCL:advection");
timer_labels.emplace_back("apply:FCL:advection:update_ghost_values" , "apply:withtimers:FCL:advection:update_ghost_values");
timer_labels.emplace_back("apply:FCL:advection:zero_out_ghosts" , "apply:withtimers:FCL:advection:zero_out_ghosts");
timer_labels.emplace_back("apply:FCL:advection:cell_loop" , "apply:withtimers:FCL:advection:cell_loop");
timer_labels.emplace_back("apply:FCL:advection:face_loop_x" , "apply:withtimers:FCL:advection:face_loop_x");
timer_labels.emplace_back("apply:FCL:advection:face_loop_v" , "apply:withtimers:FCL:advection:face_loop_v");
timer_labels.emplace_back("apply:FCL:advection:boundary_loop_x" , "apply:withtimers:FCL:advection:boundary_loop_x");
timer_labels.emplace_back("apply:FCL:advection:boundary_loop_v" , "apply:withtimers:FCL:advection:boundary_loop_v");
timer_labels.emplace_back("apply:FCL:advection:compress" , "apply:withtimers:FCL:advection:compress");
timer_labels.emplace_back("apply:FCL:mass" , "apply:withtimers:FCL:mass");
}
{
std::vector<double> timing_values(timer_labels.size());
for(unsigned int i = 0; i < timer_labels.size(); i++)
timing_values[i] = timers[timer_labels[i].second].get_accumulated_time() / 1e6 / param.n_iterations;
const auto timing_values_min_max_avg = Utilities::MPI::min_max_avg (timing_values, comm_global);
for(unsigned int i = 0; i < timer_labels.size(); i++)
{
const auto min_max_avg = timing_values_min_max_avg[i];
table.set(timer_labels[i].first + ":avg [s]", min_max_avg.avg);
table.set(timer_labels[i].first + ":min [s]", min_max_avg.min);
table.set(timer_labels[i].first + ":max [s]", min_max_avg.max);
}
}
// clang-format on
}
| 16,267
|
C++
|
.cc
| 344
| 38.625
| 170
| 0.600391
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,124
|
hyperrectangle.h
|
hyperdeal_hyperdeal/examples/advection/cases/hyperrectangle.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_ADVECTION_CASES_HYPERRECTANGLE
#define HYPERDEAL_ADVECTION_CASES_HYPERRECTANGLE
#include <hyper.deal/grid/grid_generator.h>
#include "../include/parameters.h"
namespace hyperdeal
{
namespace advection
{
namespace hyperrectangle
{
template <int DIM, typename Number = double>
class ExactSolution : public dealii::Function<DIM, Number>
{
public:
ExactSolution(const double time = 0.)
: dealii::Function<DIM, Number>(1, time)
, wave_number(2.)
{
advection[0] = 1.;
if (DIM > 1)
advection[1] = 0.15;
if (DIM > 2)
advection[2] = -0.05;
}
virtual double
value(const dealii::Point<DIM> &p,
const unsigned int = 1) const override
{
double t = this->get_time();
const dealii::Tensor<1, DIM> position = p - t * advection;
double result =
std::sin(wave_number * position[0] * dealii::numbers::PI);
for (unsigned int d = 1; d < DIM; ++d)
result *= std::cos(wave_number * position[d] * dealii::numbers::PI);
return result;
}
dealii::Tensor<1, DIM>
get_transport_direction() const
{
return advection;
}
private:
dealii::Tensor<1, DIM> advection;
const double wave_number;
};
template <int dim_x, int dim_v, int degree, typename Number>
class Initializer
: public hyperdeal::advection::Initializer<dim_x, dim_v, degree, Number>
{
public:
Initializer()
: n_subdivisions_x(dim_x, 4)
, n_subdivisions_v(dim_v, 4)
{}
void
add_parameters(dealii::ParameterHandler &prm) override
{
prm.enter_subsection("Case");
prm.add_parameter("NRefinementsX",
n_refinements_x,
"x-space: number of global refinements.");
prm.add_parameter("NRefinementsV",
n_refinements_v,
"v-space: number of global refinements.");
prm.add_parameter("PeriodicX",
do_periodic_x,
"x-space: apply periodicity.");
prm.add_parameter("PeriodicV",
do_periodic_v,
"v-space: apply periodicity.");
prm.enter_subsection("NSubdivisionsX");
if (dim_x >= 1)
prm.add_parameter(
"X",
n_subdivisions_x[0],
"x-space: number of subdivisions in x-direction.");
if (dim_x >= 2)
prm.add_parameter(
"Y",
n_subdivisions_x[1],
"x-space: number of subdivisions in y-direction.");
if (dim_x >= 3)
prm.add_parameter(
"Z",
n_subdivisions_x[2],
"x-space: number of subdivisions in z-direction.");
prm.leave_subsection();
prm.enter_subsection("NSubdivisionsV");
if (dim_v >= 1)
prm.add_parameter(
"X",
n_subdivisions_v[0],
"v-space: number of subdivisions in x-direction.");
if (dim_v >= 2)
prm.add_parameter(
"Y",
n_subdivisions_v[1],
"v-space: number of subdivisions in y-direction.");
if (dim_v >= 3)
prm.add_parameter(
"Z",
n_subdivisions_v[2],
"v-space: number of subdivisions in z-direction.");
prm.leave_subsection();
prm.add_parameter("OrientationX",
orientation_x,
"x-space: number of global refinements.");
prm.add_parameter("OrientationV",
orientation_v,
"v-space: number of global refinements.");
prm.add_parameter(
"DeformMesh",
deform_mesh,
"Deform Cartesian mesh with an arbitrary non-linear manifold.");
prm.leave_subsection();
}
void
create_grid(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v)
override
{
dealii::Point<dim_x> p1_x;
for (unsigned int i = 0; i < dim_x; i++)
p1_x[i] = left;
dealii::Point<dim_x> p2_x;
for (unsigned int i = 0; i < dim_x; i++)
p2_x[i] = right;
dealii::Point<dim_v> p1_v;
for (unsigned int i = 0; i < dim_v; i++)
p1_v[i] = left;
dealii::Point<dim_v> p2_v;
for (unsigned int i = 0; i < dim_v; i++)
p2_v[i] = right;
// clang-format off
#if true
hyperdeal::GridGenerator::subdivided_hyper_rectangle(tria_x, tria_v,
n_refinements_x, n_subdivisions_x, p1_x, p2_x, do_periodic_x,
n_refinements_v, n_subdivisions_v, p1_v, p2_v, do_periodic_v, deform_mesh);
#elif false
hyperdeal::GridGenerator::orientated_hyper_cube(tria_x, tria_v,
n_refinements_x, p1_x, p2_x, do_periodic_x, orientation_x,
n_refinements_v, p1_v, p2_v, do_periodic_v, orientation_v);
#else
hyperdeal::GridGenerator::subdivided_hyper_ball(tria_x, tria_v,
n_refinements_x, p1_x, p2_x, do_periodic_x,
n_refinements_v, p1_v, p2_v, do_periodic_v);
#endif
// clang-format on
}
void
set_boundary_conditions(
std::shared_ptr<BoundaryDescriptor<dim_x + dim_v, Number>>
boundary_descriptor) override
{
#if true
boundary_descriptor->dirichlet_bc[0] =
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>(
new ExactSolution<dim_x + dim_v, Number>());
// TODO: hack for 1D
boundary_descriptor->dirichlet_bc[1] =
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>(
new ExactSolution<dim_x + dim_v, Number>());
#else
boundary_descriptor->homogeneous_dirichlet_bc.insert(0);
boundary_descriptor->homogeneous_dirichlet_bc.insert(1);
#endif
}
void
set_analytical_solution(
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
&analytical_solution) override
{
analytical_solution.reset(new ExactSolution<dim_x + dim_v, Number>());
}
dealii::Tensor<1, dim_x + dim_v>
get_transport_direction() override
{
return ExactSolution<dim_x + dim_v, Number>()
.get_transport_direction();
}
private:
const double left = -1.0;
const double right = +1.0;
unsigned int n_refinements_x = 0;
unsigned int n_refinements_v = 0;
bool do_periodic_x = true;
bool do_periodic_v = true;
std::vector<unsigned int> n_subdivisions_x;
std::vector<unsigned int> n_subdivisions_v;
unsigned int orientation_x = 0;
unsigned int orientation_v = 0;
bool deform_mesh = false;
};
} // namespace hyperrectangle
} // namespace advection
} // namespace hyperdeal
#endif
| 8,137
|
C++
|
.h
| 212
| 27.726415
| 89
| 0.532734
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,125
|
torus_hyperball.h
|
hyperdeal_hyperdeal/examples/advection/cases/torus_hyperball.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_ADVECTION_CASES_TORUS_HYPERBALL
#define HYPERDEAL_ADVECTION_CASES_TORUS_HYPERBALL
#include <deal.II/grid/manifold_lib.h>
#include <hyper.deal/grid/grid_generator.h>
#include "../include/parameters.h"
namespace hyperdeal
{
namespace advection
{
namespace torus_hyperball
{
template <int DIM, typename Number = double>
class ExactSolution : public dealii::Function<DIM, Number>
{
public:
ExactSolution(const double time = 0.)
: dealii::Function<DIM, Number>(1, time)
, wave_number(2.)
{
std::array<Number, 6> temp = {{1., 0.15, -0.05, -0.10, -0.15, 0.5}};
for (int i = 0; i < DIM; ++i)
advection[i] = temp[i];
}
virtual double
value(const dealii::Point<DIM> &p,
const unsigned int = 1) const override
{
double t = this->get_time();
const dealii::Tensor<1, DIM> position = p - t * advection;
double result =
std::sin(wave_number * position[0] * dealii::numbers::PI);
for (unsigned int d = 1; d < DIM; ++d)
result *= std::cos(wave_number * position[d] * dealii::numbers::PI);
return result;
}
dealii::Tensor<1, DIM>
get_transport_direction() const
{
return advection;
}
private:
dealii::Tensor<1, DIM> advection;
const double wave_number;
};
template <int dim_x, int dim_v, int degree, typename Number>
class Initializer
: public hyperdeal::advection::Initializer<dim_x, dim_v, degree, Number>
{
public:
void
add_parameters(dealii::ParameterHandler &prm) override
{
prm.enter_subsection("Case");
prm.add_parameter("NRefinementsX",
n_refinements_x,
"x-space: number of global refinements.");
prm.add_parameter("NRefinementsV",
n_refinements_v,
"v-space: number of global refinements.");
prm.leave_subsection();
}
void
create_grid(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v)
override
{
const auto fu_x = [&](auto &tria) {
if constexpr (dim_x == 3)
{
const double torus_R = 6.2; // ITER
const double torus_r = 2.0;
dealii::GridGenerator::torus(tria, torus_R, torus_r);
tria.reset_all_manifolds();
tria.set_manifold(1,
dealii::TorusManifold<3>(torus_R, torus_r));
tria.set_manifold(0,
dealii::CylindricalManifold<3>(
dealii::Tensor<1, 3>({0., 1., 0.}),
dealii::Point<3>()));
tria.set_manifold(2,
dealii::CylindricalManifold<3>(
dealii::Tensor<1, 3>({0., 1., 0.}),
dealii::Point<3>()));
}
else
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
tria.refine_global(n_refinements_x);
};
const auto fu_v = [&](auto &tria) {
if constexpr (dim_v == 3)
{
const double ball_R = 5.0;
dealii::GridGenerator::hyper_ball_balanced(
tria, dealii::Point<dim_v>(), ball_R);
}
else
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
tria.refine_global(n_refinements_v);
};
hyperdeal::GridGenerator::construct_tensor_product<dim_x, dim_v>(
tria_x, tria_v, fu_x, fu_v);
}
void
set_boundary_conditions(
std::shared_ptr<BoundaryDescriptor<dim_x + dim_v, Number>>
boundary_descriptor) override
{
boundary_descriptor->homogeneous_dirichlet_bc.insert(0);
}
void
set_analytical_solution(
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
&analytical_solution) override
{
analytical_solution.reset(new ExactSolution<dim_x + dim_v, Number>());
}
dealii::Tensor<1, dim_x + dim_v>
get_transport_direction() override
{
return ExactSolution<dim_x + dim_v, Number>()
.get_transport_direction();
}
private:
unsigned int n_refinements_x = 0;
unsigned int n_refinements_v = 0;
};
} // namespace torus_hyperball
} // namespace advection
} // namespace hyperdeal
#endif
| 5,686
|
C++
|
.h
| 147
| 27.510204
| 80
| 0.519572
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,126
|
application.h
|
hyperdeal_hyperdeal/examples/advection/include/application.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <hyper.deal/base/config.h>
#include <deal.II/base/conditional_ostream.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <deal.II/matrix_free/tools.h>
#include <hyper.deal/base/memory_consumption.h>
#include <hyper.deal/base/time_integrators.h>
#include <hyper.deal/base/time_loop.h>
#include <hyper.deal/base/timers.h>
#include <hyper.deal/matrix_free/matrix_free.h>
#include <hyper.deal/numerics/vector_tools.h>
#include <hyper.deal/operators/advection/advection_operation.h>
#include <hyper.deal/operators/advection/cfl.h>
#include <hyper.deal/operators/advection/velocity_field_view.h>
#include <stdio.h>
#include "parameters.h"
namespace hyperdeal
{
namespace advection
{
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class Application
{
public:
static const int dim = dim_x + dim_v;
using MF =
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>;
using VectorizedArrayTypeX = typename MF::VectorizedArrayTypeX;
using VectorizedArrayTypeV = typename MF::VectorizedArrayTypeV;
using VelocityFieldView =
advection::ConstantVelocityFieldView<dim,
Number,
VectorizedArrayTypeX,
dim_x,
dim_v>;
using VectorType = dealii::LinearAlgebra::distributed::Vector<Number>;
Application(const MPI_Comm comm_global,
const MPI_Comm comm_sm,
const unsigned int size_x,
const unsigned int size_v,
DynamicConvergenceTable &table)
: comm_global(comm_global)
, comm_sm(comm_sm)
, comm_row(mpi::create_row_comm(comm_global, size_x, size_v))
, comm_column(mpi::create_column_comm(comm_global, size_x, size_v))
, matrix_free(comm_global, comm_sm, matrix_free_x, matrix_free_v)
, advection_operation(matrix_free, table)
, pcout(std::cout,
dealii::Utilities::MPI::this_mpi_process(comm_global) == 0)
, table(table)
{}
~Application()
{
MPI_Comm_free(&comm_row);
MPI_Comm_free(&comm_column);
}
void
reinit(const std::string file_name)
{
// clang-format off
pcout << "--------------------------------------------------------------------------------" << std::endl;
pcout << "Setup:" << std::endl;
// clang-format on
table.set("info->procs",
dealii::Utilities::MPI::n_mpi_processes(comm_global));
table.set("info->procs_x",
dealii::Utilities::MPI::n_mpi_processes(comm_row));
table.set("info->procs_v",
dealii::Utilities::MPI::n_mpi_processes(comm_column));
table.set("info->procs_sm",
dealii::Utilities::MPI::n_mpi_processes(comm_sm));
const unsigned int degree_x = degree;
const unsigned int degree_v = degree;
const unsigned int n_points_x = n_points;
const unsigned int n_points_v = n_points;
table.set("info->dim_x", dim_x);
table.set("info->dim_v", dim_v);
table.set("info->degree_x", degree_x);
table.set("info->degree_v", degree_v);
const auto initializer =
cases::get<dim_x, dim_v, degree, Number>(file_name, pcout);
initializer->set_input_parameters(param, file_name, pcout);
MemoryStatMonitor memory_stat_monitor(comm_global);
// step 1: create two low-dimensional triangulations
{
pcout << " - dealii::Triangulation (x/v)" << std::endl;
memory_stat_monitor.monitor("triangulation");
// clang-format off
if(param.triangulation_type == "fullydistributed")
{
triangulation_x.reset(new dealii::parallel::fullydistributed::Triangulation<dim_x>(comm_row));
triangulation_v.reset(new dealii::parallel::fullydistributed::Triangulation<dim_v>(comm_column));
}
#ifdef DEAL_II_WITH_P4EST
else if(param.triangulation_type == "distributed")
{
triangulation_x.reset(new dealii::parallel::distributed::Triangulation<dim_x>(comm_row));
triangulation_v.reset(new dealii::parallel::distributed::Triangulation<dim_v>(comm_column));
}
#endif
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
// clang-format on
initializer->create_grid(triangulation_x, triangulation_v);
// output low-dimensional meshes (optional)
if (param.output_grid)
{
dealii::GridOut grid_out;
if (dealii::Utilities::MPI::this_mpi_process(comm_column) == 0)
grid_out.write_mesh_per_processor_as_vtu(*this->triangulation_x,
"grid_x");
if (dealii::Utilities::MPI::this_mpi_process(comm_row) == 0)
grid_out.write_mesh_per_processor_as_vtu(*this->triangulation_v,
"grid_v");
}
}
// step 2: create two low-dimensional dof-handler
{
pcout << " - dealii::DoFHandler (x/v)" << std::endl;
memory_stat_monitor.monitor("dofhandler");
dof_handler_x.reset(new dealii::DoFHandler<dim_x>(*triangulation_x));
dof_handler_v.reset(new dealii::DoFHandler<dim_v>(*triangulation_v));
dealii::FE_DGQ<dim_x> fe_x(degree_x);
dealii::FE_DGQ<dim_v> fe_v(degree_v);
dof_handler_x->distribute_dofs(fe_x);
dof_handler_v->distribute_dofs(fe_v);
table.set("info->size_x", dof_handler_x->n_dofs());
table.set("info->size_v", dof_handler_v->n_dofs());
table.set("info->size",
dof_handler_x->n_dofs() * dof_handler_v->n_dofs());
}
// step 3: setup two low-dimensional matrix-frees
{
memory_stat_monitor.monitor("dealii::matrixfree");
dealii::AffineConstraints<Number> constraint;
constraint.close();
{
pcout << " - dealii::MatrixFree (x)" << std::endl;
typename dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>::
AdditionalData additional_data;
additional_data.mapping_update_flags =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.mapping_update_flags_inner_faces =
dealii::update_gradients | dealii::update_JxW_values;
additional_data.mapping_update_flags_boundary_faces =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.hold_all_faces_to_owned_cells = true;
additional_data.mapping_update_flags_faces_by_cells =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
dealii::MappingQGeneric<dim_x> mapping_x(param.mapping_degree_x);
std::vector<const dealii::DoFHandler<dim_x> *> dof_handlers{
&*dof_handler_x};
std::vector<const dealii::AffineConstraints<Number> *> constraints{
&constraint};
std::vector<dealii::Quadrature<1>> quads;
if (param.do_collocation)
quads.push_back(dealii::QGaussLobatto<1>(n_points_x));
else
quads.push_back(dealii::QGauss<1>(n_points_x));
quads.push_back(dealii::QGauss<1>(degree_x + 1));
quads.push_back(dealii::QGaussLobatto<1>(degree_x + 1));
// ensure that inner and boundary faces are not mixed in the
// same macro cell
dealii::MatrixFreeTools::categorize_by_boundary_ids(
*triangulation_x, additional_data);
matrix_free_x.reinit(
mapping_x, dof_handlers, constraints, quads, additional_data);
}
{
pcout << " - dealii::MatrixFree (v)" << std::endl;
typename dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV>::
AdditionalData additional_data;
additional_data.mapping_update_flags =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.mapping_update_flags_inner_faces =
dealii::update_gradients | dealii::update_JxW_values;
additional_data.mapping_update_flags_boundary_faces =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.hold_all_faces_to_owned_cells = true;
additional_data.mapping_update_flags_faces_by_cells =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
dealii::MappingQGeneric<dim_v> mapping_v(param.mapping_degree_v);
std::vector<const dealii::DoFHandler<dim_v> *> dof_handlers{
&*dof_handler_v};
std::vector<const dealii::AffineConstraints<Number> *> constraints{
&constraint};
std::vector<dealii::Quadrature<1>> quads;
if (param.do_collocation)
quads.push_back(dealii::QGaussLobatto<1>(n_points_v));
else
quads.push_back(dealii::QGauss<1>(n_points_v));
quads.push_back(dealii::QGauss<1>(degree_v + 1));
quads.push_back(dealii::QGaussLobatto<1>(degree_v + 1));
// ensure that inner and boundary faces are not mixed in the
// same macro cell
dealii::MatrixFreeTools::categorize_by_boundary_ids(
*triangulation_v, additional_data);
matrix_free_v.reinit(
mapping_v, dof_handlers, constraints, quads, additional_data);
}
}
// step 4: setup tensor-product matrixfree
{
memory_stat_monitor.monitor("hyperdeal_matrixfree");
pcout << " - hyperdeal::MatrixFree" << std::endl;
typename MF::AdditionalData ad;
ad.do_ghost_faces = param.do_ghost_faces;
ad.do_buffering = param.do_buffering;
ad.use_ecl = param.use_ecl;
ad.overlapping_level = param.overlapping_level;
matrix_free.reinit(ad);
}
// step 5: allocate memory for vectors (with only vct_Ti having ghost
// value)
{
// clang-format off
memory_stat_monitor.monitor("vector_solution");
matrix_free.initialize_dof_vector(vct_solution, 0, false || !param.use_ecl, true);
memory_stat_monitor.monitor("vector_Ki");
matrix_free.initialize_dof_vector(vct_Ki, 0, false || !param.use_ecl, true);
memory_stat_monitor.monitor("vector_Ti");
matrix_free.initialize_dof_vector(vct_Ti, 0, true, true);
// clang-format on
const auto add_min_max_avg_table_entry = [](const auto & table,
const std::string label,
const auto val,
const auto & comm) {
const auto min_max_avg =
dealii::Utilities::MPI::min_max_avg(static_cast<double>(val),
comm);
table.set(label + ":sum", min_max_avg.sum);
table.set(label + ":min", min_max_avg.min);
table.set(label + ":max", min_max_avg.max);
table.set(label + ":avg", min_max_avg.avg);
};
add_min_max_avg_table_entry(
table,
"info->partitioner->local_size",
matrix_free.get_vector_partitioner()->locally_owned_size(),
comm_global);
add_min_max_avg_table_entry(
table,
"info->partitioner->n_ghost_indices",
matrix_free.get_vector_partitioner()->n_ghost_indices(),
comm_global);
}
// step 6: set initial condition in Gauss-Lobatto points (quad_no_x=2,
// quad_no_v=2)
{
pcout << " - advection::initial_condition" << std::endl;
initializer->set_analytical_solution(analytical_solution);
VectorTools::interpolate<degree, degree + 1>(analytical_solution,
matrix_free,
vct_solution,
0 /* dof_no_x*/,
0 /* dof_no_v */,
2 /* quad_no_x */,
2 /* quad_no_v */);
}
// step 7: set boundary conditions
{
pcout << " - advection::boundary_condition" << std::endl;
boundary_descriptor.reset(
new advection::BoundaryDescriptor<dim, Number>());
initializer->set_boundary_conditions(boundary_descriptor);
}
// step 8: set (constant) velocity field
{
pcout << " - advection::velocity_field_view" << std::endl;
velocity_field = std::make_shared<VelocityFieldView>(
initializer->get_transport_direction());
}
// step 9: initialize advection operator
{
pcout << " - advection::operator" << std::endl;
advection_operation.reinit(boundary_descriptor,
velocity_field,
param.advection_operation_parameters);
}
// step 10: time loop
{
pcout << " - advection::time_loop" << std::endl;
auto &time_loop_parameters = param.time_loop_parameters;
// determine critical time step (CFL condition)
const Number critical_time_step =
hyperdeal::advection::compute_critical_time_step(
*dof_handler_x.get(),
*dof_handler_v.get(),
initializer->get_transport_direction(),
degree_x,
n_points_x,
comm_row,
degree_v,
n_points_v,
comm_column);
// determine minimal time step (parameter file vs. CFL)
const Number dt = std::min(time_loop_parameters.time_step,
param.cfl_number * critical_time_step /
std::pow(degree, 1.5));
// set time step s.t. final time step ends at final time
time_loop_parameters.time_step =
(time_loop_parameters.final_time -
time_loop_parameters.start_time) /
std::ceil((time_loop_parameters.final_time -
time_loop_parameters.start_time) /
dt);
// setup time loop
time_loop.reinit(time_loop_parameters);
}
// clang-format off
pcout << " ... done!" << std::endl;
pcout << "--------------------------------------------------------------------------------" << std::endl << std::endl;
// clang-format on
{
memory_stat_monitor.print(pcout);
const auto &mem = memory_consumption();
mem.print(comm_global, pcout);
}
}
void
solve()
{
LowStorageRungeKuttaIntegrator<Number, VectorType> time_integrator(
vct_Ki, vct_Ti, param.rk_parameters.type, param.use_ecl);
unsigned int time_step_counter = 0;
#ifdef PERFORMANCE_TIMING
bool performance_timing = true;
#else
bool performance_timing = false;
#endif
Timers timers(param.performance_log_all_calls);
std::array<Number, 2> error;
const unsigned int time_steps = time_loop.loop(
vct_solution,
[&](auto & solution,
const auto cur_time,
const auto time_step,
const auto &runnable) {
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
if (time_step_counter == param.performance_warm_up_iterations)
{
if (time_step_counter != 0)
timers.reset();
MPI_Barrier(comm_global);
timers["id_total"].start();
}
time_step_counter++;
}
#endif
ScopedTimerWrapper timer(timers, "id_stage");
time_integrator.perform_time_step(solution,
cur_time,
time_step,
runnable);
},
[&](const VectorType &src, VectorType &dst, const Number cur_time) {
ScopedTimerWrapper timer(timers, "id_advection");
if (performance_timing || param.performance_log_all_calls)
advection_operation.apply(dst, src, cur_time, &timers);
else
advection_operation.apply(dst, src, cur_time);
},
[&](const Number cur_time) {
if (!param.dignostics_enabled ||
(cur_time != param.time_loop_parameters.start_time &&
static_cast<int>((cur_time + 0.00000000001 -
param.time_loop_parameters.start_time) /
param.dignostics_tick) ==
static_cast<int>((cur_time + 0.00000000001 -
param.time_loop_parameters.start_time -
param.time_loop_parameters.time_step) /
param.dignostics_tick)))
return; // nothing to do
ScopedTimerWrapper timer(timers, "id_diagnostics");
// Compute norm and error in Gauss-Legendre points (quad_no_x=0,
// quad_no_v=0)
analytical_solution->set_time(cur_time);
error = VectorTools::norm_and_error<degree, n_points>(
analytical_solution, matrix_free, vct_solution, 0, 0, 0, 0);
if (pcout.is_active())
{
const auto print_result_to_stream = [&](auto fp) {
fprintf(fp,
" Time:%10.3e, norm: %17.10e, error: %17.10e\n",
cur_time,
error[0],
error[1]);
};
// print to screen
print_result_to_stream(stdout);
// print result to file
FILE *fp;
fp = fopen("time_history_diagnostic.out",
cur_time == param.time_loop_parameters.start_time ?
"w" :
"a");
print_result_to_stream(fp);
fclose(fp);
}
});
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
MPI_Barrier(comm_global);
timers["id_total"].stop();
timers.print(comm_global, pcout);
}
#endif
{
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
auto &timer = timers["id_stage"];
AssertThrow(time_steps == time_step_counter,
dealii::StandardExceptions::ExcMessage(
"Mismatch in time step counter!"));
AssertThrow((time_steps - param.performance_warm_up_iterations) ==
timer.get_counter(),
dealii::StandardExceptions::ExcMessage(
"Mismatch in time step counter!"));
}
#endif
table.set("info->time_steps",
time_steps - param.performance_warm_up_iterations);
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
auto &timer = timers["id_stage"];
table.set("throughput [MDoFs/s]",
dof_handler_x->n_dofs() * dof_handler_v->n_dofs() *
timer.get_counter() * time_integrator.n_stages() /
timer.get_accumulated_time());
table.set("throughput [MDoFs/s/core]",
dof_handler_x->n_dofs() * dof_handler_v->n_dofs() *
timer.get_counter() * time_integrator.n_stages() /
timer.get_accumulated_time() /
dealii::Utilities::MPI::n_mpi_processes(comm_row) /
dealii::Utilities::MPI::n_mpi_processes(comm_column));
}
#endif
}
if (performance_timing && param.performance_log_all_calls)
{
#ifdef PERFORMANCE_TIMING
timers.print_log(comm_global,
param.performance_log_all_calls_prefix);
#endif
}
if (param.dignostics_enabled)
{
table.set("numerics->solution_l2", error[0]);
table.set("numerics->error_l2", error[1]);
}
}
MemoryConsumption
memory_consumption() const
{
MemoryConsumption mem("application");
mem.insert("triangulation_x", triangulation_x->memory_consumption());
mem.insert("triangulation_v", triangulation_v->memory_consumption());
mem.insert("dof_handler_x", dof_handler_x->memory_consumption());
mem.insert("dof_handler_v", dof_handler_v->memory_consumption());
mem.insert("matrix_free_x", matrix_free_x.memory_consumption());
mem.insert("matrix_free_v", matrix_free_v.memory_consumption());
mem.insert(matrix_free.memory_consumption());
MemoryConsumption mem_vec("vct");
mem_vec.insert("solution", vct_solution.memory_consumption());
mem_vec.insert("Ki", vct_Ki.memory_consumption());
mem_vec.insert("Ti", vct_Ti.memory_consumption());
mem.insert(mem_vec);
return mem;
}
private:
// communicators
const MPI_Comm comm_global;
const MPI_Comm comm_sm;
MPI_Comm comm_row; // should be const. but has to be freed at the end
MPI_Comm comm_column; // the same here
// x- and v-space objects
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>>
triangulation_x;
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>>
triangulation_v;
std::shared_ptr<dealii::DoFHandler<dim_x>> dof_handler_x;
std::shared_ptr<dealii::DoFHandler<dim_v>> dof_handler_v;
dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX> matrix_free_x;
dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV> matrix_free_v;
MF matrix_free;
advection::AdvectionOperation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityFieldView,
VectorizedArrayTypeX>
advection_operation;
dealii::ConditionalOStream pcout;
DynamicConvergenceTable & table;
std::shared_ptr<dealii::Function<dim, Number>> analytical_solution;
std::shared_ptr<hyperdeal::advection::BoundaryDescriptor<dim, Number>>
boundary_descriptor;
std::shared_ptr<VelocityFieldView> velocity_field;
VectorType vct_solution, vct_Ki, vct_Ti;
TimeLoop<Number, VectorType> time_loop;
Parameters<Number> param;
};
} // namespace advection
} // namespace hyperdeal
| 25,336
|
C++
|
.h
| 540
| 33.127778
| 126
| 0.536586
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,127
|
parameters.h
|
hyperdeal_hyperdeal/examples/advection/include/parameters.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_ADVECTION_PARAMETERS
#define HYPERDEAL_ADVECTION_PARAMETERS
#include <hyper.deal/base/time_integrators_parameters.h>
#include <hyper.deal/base/time_loop_parameters.h>
#include <hyper.deal/operators/advection/advection_operation_parameters.h>
#include <fstream>
namespace hyperdeal
{
namespace advection
{
template <typename Number>
struct Parameters
{
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("SpatialDiscretization");
prm.add_parameter("MappingX",
mapping_degree_x,
"Degree of the mapping in x-space.");
prm.add_parameter("MappingV",
mapping_degree_v,
"Degree of the mapping in v-space.");
prm.add_parameter(
"DoCollocation",
do_collocation,
"Perform numerical integration directly in Gauss-Lobatto points (collocation setup - no basis change needed).");
prm.leave_subsection();
prm.enter_subsection("Triangulation");
prm.add_parameter("Type",
triangulation_type,
"Type of the triangulation.");
prm.add_parameter(
"OutputGrid",
output_grid,
"Output x- and v-triangulation to file so that it can be viewed in Paraview.");
prm.leave_subsection();
prm.enter_subsection("TemporalDiscretization");
time_loop_parameters.add_parameters(prm);
rk_parameters.add_parameters(prm);
prm.add_parameter("CFLNumber",
cfl_number,
"The CFL number limiting the time steps.");
prm.add_parameter("DiagnosticsEnabled",
dignostics_enabled,
"Perform diagnostics (post-processing).");
prm.add_parameter("DiagnosticsTick",
dignostics_tick,
"Perform diagnostics after this interveral.");
prm.add_parameter(
"PerformanceLogAllCalls",
performance_log_all_calls,
"Save all measured timings (extra memory consumption) or only store min/max/avg.");
prm.add_parameter(
"PerformanceLogAllCallsPrefix",
performance_log_all_calls_prefix,
"Save all measured timings (extra memory consumption) or only store min/max/avg.");
prm.add_parameter(
"DiagnosticsWarmUpIterations",
performance_warm_up_iterations,
"Number of warm-up iterations (these iterations are ignored for the timings).");
prm.leave_subsection();
prm.enter_subsection("AdvectionOperation");
advection_operation_parameters.add_parameters(prm);
prm.leave_subsection();
prm.enter_subsection("Matrixfree");
prm.add_parameter(
"GhostFaces",
do_ghost_faces,
"Use ghost faces (advection) or ghost cells (Laplace).");
prm.add_parameter("DoBuffering",
do_buffering,
"Use buffering-mode of shared memory vector.");
prm.add_parameter(
"UseECL",
use_ecl,
"Use element-centric loops (ECL) or face-centric loops (FCL).");
prm.add_parameter(
"OverlappingLevel",
overlapping_level,
"Level of overlapping of communication and computation.");
prm.leave_subsection();
prm.enter_subsection("General");
prm.add_parameter("Verbose",
print_parameter,
"Print the parameter after parsing.");
prm.leave_subsection();
}
// discretization
unsigned int mapping_degree_x = 1;
unsigned int mapping_degree_v = 1;
bool do_collocation = false;
// triangulation
std::string triangulation_type = "fullydistributed";
bool output_grid = false;
// time-loop
TimeLoopParamters<Number> time_loop_parameters;
LowStorageRungeKuttaIntegratorParamters rk_parameters;
// ... CFL-condition
Number cfl_number = 0.3;
// ... advection operation
AdvectionOperationParamters advection_operation_parameters;
// ... diagnostic
bool dignostics_enabled = true;
Number dignostics_tick = 0.1;
// ... performance
bool performance_log_all_calls = false;
std::string performance_log_all_calls_prefix = "test";
unsigned int performance_warm_up_iterations = 0;
// matrix-free
bool do_ghost_faces = true;
bool do_buffering = false;
bool use_ecl = true;
unsigned int overlapping_level = 0;
bool print_parameter = true;
};
template <int dim_x, int dim_v, int degree, typename Number>
class Initializer
{
public:
virtual ~Initializer() = default;
void
set_input_parameters(Parameters<Number> & param,
const std::string file_name,
const dealii::ConditionalOStream &pcout)
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
// add general parameters
param.add_parameters(prm);
// add case-specific parameters
this->add_parameters(prm);
prm.parse_input_from_json(file, true);
if (param.print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
virtual void
add_parameters(dealii::ParameterHandler &prm)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)prm;
}
virtual void
create_grid(std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>>
&triangulation_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>>
&triangulation_v)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)triangulation_x;
(void)triangulation_v;
}
virtual void
set_boundary_conditions(
std::shared_ptr<
hyperdeal::advection::BoundaryDescriptor<dim_x + dim_v, Number>>
boundary_descriptor)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)boundary_descriptor;
}
virtual void
set_analytical_solution(
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
&analytical_solution)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)analytical_solution;
}
virtual dealii::Tensor<1, dim_x + dim_v>
get_transport_direction()
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
return dealii::Tensor<1, dim_x + dim_v>();
}
};
} // namespace advection
} // namespace hyperdeal
#include "../cases/hyperrectangle.h"
#include "../cases/torus_hyperball.h"
namespace hyperdeal
{
namespace advection
{
namespace cases
{
struct Parameters
{
Parameters(std::string case_name)
: case_name(case_name)
{}
Parameters(const std::string & file_name,
const dealii::ConditionalOStream &pcout)
: case_name("dummy")
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
add_parameters(prm);
prm.parse_input_from_json(file, true);
if (print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("General");
prm.add_parameter(
"Case",
case_name,
"Name of the case to be run (the section Case contains the parameters of this case).");
prm.add_parameter("Verbose",
print_parameter,
"Print the parameter after parsing.");
prm.leave_subsection();
}
std::string case_name;
bool print_parameter = true;
};
template <int dim_x, int dim_v, int degree, typename Number>
std::shared_ptr<
hyperdeal::advection::Initializer<dim_x, dim_v, degree, Number>>
get(const std::string &case_name)
{
// clang-format off
std::shared_ptr<hyperdeal::advection::Initializer<dim_x, dim_v, degree, Number>> initializer;
if(case_name == "hyperrectangle")
initializer.reset(new hyperdeal::advection::hyperrectangle::Initializer<dim_x, dim_v, degree, Number>);
else if(case_name == "torus")
initializer.reset(new hyperdeal::advection::torus_hyperball::Initializer<dim_x, dim_v, degree, Number>);
else
AssertThrow(false, dealii::ExcMessage("This case does not exist!"));
// clang-format on
return initializer;
}
template <int dim_x, int dim_v, int degree, typename Number>
std::shared_ptr<
hyperdeal::advection::Initializer<dim_x, dim_v, degree, Number>>
get(const std::string &file_name, const dealii::ConditionalOStream &pcout)
{
Parameters params(file_name, pcout);
return get<dim_x, dim_v, degree, Number>(params.case_name);
}
} // namespace cases
} // namespace advection
} // namespace hyperdeal
#endif
| 10,537
|
C++
|
.h
| 266
| 30.018797
| 122
| 0.594209
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,128
|
hyperrectangle.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/cases/hyperrectangle.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_ADVECTION_CASES_HYPERRECTANGLE
#define HYPERDEAL_ADVECTION_CASES_HYPERRECTANGLE
#include <hyper.deal/grid/grid_generator.h>
#include "../include/parameters.h"
namespace hyperdeal
{
namespace vp
{
namespace hyperrectangle
{
template <int dim_x, int dim_v, typename Number = double>
class ExactSolution : public dealii::Function<dim_x + dim_v, Number>
{
public:
static const unsigned int DIM = dim_x + dim_v;
ExactSolution(const double time = 0.)
: dealii::Function<DIM, Number>(1, time)
, wave_number(0.5)
{
for (unsigned int d = 0; d < dim_x; ++d)
advection[d] = 1.0;
for (unsigned int d = 0; d < dim_v; ++d)
advection[d + dim_v] = 6.0;
}
virtual double
value(const dealii::Point<DIM> &p,
const unsigned int = 1) const override
{
const dealii::Tensor<1, DIM> position = p;
double result =
1.0; // std::sin(wave_number * position[0] * numbers::PI);
for (unsigned int d = 0; d < 1; ++d)
result = result + 0.01 * std::cos(wave_number * position[d]);
for (unsigned int d = dim_x; d < dim_x + dim_v; ++d)
result = result * std::exp(-0.5 * pow(position[d], 2)) /
std::sqrt(2.0 * dealii::numbers::PI);
return result;
}
dealii::Tensor<1, DIM>
get_transport_direction() const
{
return advection;
}
private:
dealii::Tensor<1, DIM> advection;
const double wave_number;
};
template <int dim_x, int dim_v, int degree, typename Number>
class Initializer
: public hyperdeal::vp::Initializer<dim_x, dim_v, degree, Number>
{
public:
Initializer()
: n_subdivisions_x(dim_x, 4)
, n_subdivisions_v(dim_v, 4)
{}
void
add_parameters(dealii::ParameterHandler &prm) override
{
prm.enter_subsection("Case");
prm.add_parameter("NRefinementsX",
n_refinements_x,
"x-space: number of global refinements.");
prm.add_parameter("NRefinementsV",
n_refinements_v,
"v-space: number of global refinements.");
prm.add_parameter("PeriodicX",
do_periodic_x,
"x-space: apply periodicity.");
prm.add_parameter("PeriodicV",
do_periodic_v,
"v-space: apply periodicity.");
prm.enter_subsection("NSubdivisionsX");
if (dim_x >= 1)
prm.add_parameter(
"X",
n_subdivisions_x[0],
"x-space: number of subdivisions in x-direction.");
if (dim_x >= 2)
prm.add_parameter(
"Y",
n_subdivisions_x[1],
"x-space: number of subdivisions in y-direction.");
if (dim_x >= 3)
prm.add_parameter(
"Z",
n_subdivisions_x[2],
"x-space: number of subdivisions in z-direction.");
prm.leave_subsection();
prm.enter_subsection("NSubdivisionsV");
if (dim_v >= 1)
prm.add_parameter(
"X",
n_subdivisions_v[0],
"v-space: number of subdivisions in x-direction.");
if (dim_v >= 2)
prm.add_parameter(
"Y",
n_subdivisions_v[1],
"v-space: number of subdivisions in y-direction.");
if (dim_v >= 3)
prm.add_parameter(
"Z",
n_subdivisions_v[2],
"v-space: number of subdivisions in z-direction.");
prm.leave_subsection();
prm.add_parameter(
"DeformMesh",
deform_mesh,
"Deform Cartesian mesh with an arbitrary non-linear manifold.");
prm.leave_subsection();
}
void
create_grid(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v)
override
{
dealii::Point<dim_x> p1_x;
for (unsigned int d = 0; d < dim_x; ++d)
p1_x(d) = 0.0;
dealii::Point<dim_x> p2_x;
for (unsigned int d = 0; d < dim_x; ++d)
p2_x(d) = 4.0 * dealii::numbers::PI;
dealii::Point<dim_v> p1_v;
for (unsigned int d = 0; d < dim_v; ++d)
p1_v(d) = -6.0;
dealii::Point<dim_v> p2_v;
for (unsigned int d = 0; d < dim_v; ++d)
p2_v(d) = 6.0;
// clang-format off
hyperdeal::GridGenerator::subdivided_hyper_rectangle(tria_x, tria_v,
n_refinements_x, n_subdivisions_x, p1_x, p2_x, do_periodic_x,
n_refinements_v, n_subdivisions_v, p1_v, p2_v, do_periodic_v, deform_mesh);
// clang-format on
}
void
set_boundary_conditions(
std::shared_ptr<
hyperdeal::advection::BoundaryDescriptor<dim_x + dim_v, Number>>
boundary_descriptor) override
{
boundary_descriptor->dirichlet_bc[0] =
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>(
new ExactSolution<dim_x, dim_v, Number>());
// TODO: hack for 1D
boundary_descriptor->dirichlet_bc[1] =
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>(
new ExactSolution<dim_x, dim_v, Number>());
}
void
set_analytical_solution(
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
&analytical_solution) override
{
analytical_solution.reset(new ExactSolution<dim_x, dim_v, Number>());
}
dealii::Tensor<1, dim_x + dim_v>
get_transport_direction() override
{
return ExactSolution<dim_x, dim_v, Number>()
.get_transport_direction();
}
LaplaceOperatorBCType
get_poisson_problem_bc_type() const override
{
return LaplaceOperatorBCType::PBC;
}
private:
unsigned int n_refinements_x = 0;
unsigned int n_refinements_v = 0;
bool do_periodic_x = true;
bool do_periodic_v = true;
std::vector<unsigned int> n_subdivisions_x;
std::vector<unsigned int> n_subdivisions_v;
bool deform_mesh = false;
};
} // namespace hyperrectangle
} // namespace vp
} // namespace hyperdeal
#endif
| 7,449
|
C++
|
.h
| 195
| 27.620513
| 89
| 0.527263
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,129
|
torus_hyperball.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/cases/torus_hyperball.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_ADVECTION_CASES_TORUS_HYPERBALL
#define HYPERDEAL_ADVECTION_CASES_TORUS_HYPERBALL
#include <deal.II/grid/manifold_lib.h>
#include <hyper.deal/grid/grid_generator.h>
#include "../include/parameters.h"
namespace hyperdeal
{
namespace vp
{
namespace torus_hyperball
{
static const double torus_R = 6.2; // ITER
static const double torus_r = 2.0;
static const double ball_R = 5.0;
template <int dim_x, int dim_v, typename Number = double>
class ExactSolution : public dealii::Function<dim_x + dim_v, Number>
{
public:
ExactSolution(const double time = 0.)
: dealii::Function<dim_x + dim_v, Number>(1, time)
, wave_number(0.5)
{
for (unsigned int d = 0; d < dim_x; ++d)
advection[d] = 1.0;
for (unsigned int d = 0; d < dim_v; ++d)
advection[d + dim_v] = 6.0;
}
virtual double
value(const dealii::Point<dim_x + dim_v> &p,
const unsigned int = 1) const override
{
// project p on x-z plane -> direction vector
const dealii::Point<dim_x> pp(p[0], 0.0, p[2]);
// normalized and scale direction vector, s.t, its length equals to R
// and subtract from point -> distance from the center of the tube
const double distance = (torus_R * (pp / pp.norm()) -
dealii::Point<dim_x>(p[0], p[1], p[2]))
.norm();
double result = std::exp(-1.0 * pow(distance, 2));
for (unsigned int d = dim_x; d < dim_x + dim_v; ++d)
result = result * std::exp(-0.5 * pow(p[d], 2)) /
std::sqrt(2.0 * dealii::numbers::PI);
return result;
}
dealii::Tensor<1, dim_x + dim_v>
get_transport_direction() const
{
return advection;
}
private:
dealii::Tensor<1, dim_x + dim_v> advection;
const double wave_number;
};
template <int dim_x, int dim_v, int degree, typename Number>
class Initializer
: public hyperdeal::vp::Initializer<dim_x, dim_v, degree, Number>
{
public:
void
add_parameters(dealii::ParameterHandler &prm) override
{
prm.enter_subsection("Case");
prm.add_parameter("NRefinementsX",
n_refinements_x,
"x-space: number of global refinements.");
prm.add_parameter("NRefinementsV",
n_refinements_v,
"v-space: number of global refinements.");
prm.leave_subsection();
}
void
create_grid(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v)
override
{
const auto fu_x = [&](auto &tria) {
if constexpr (dim_x == 3)
{
dealii::GridGenerator::torus(tria, torus_R, torus_r);
tria.reset_all_manifolds();
tria.set_manifold(1,
dealii::TorusManifold<3>(torus_R, torus_r));
tria.set_manifold(0,
dealii::CylindricalManifold<3>(
dealii::Tensor<1, 3>({0., 1., 0.}),
dealii::Point<3>()));
tria.set_manifold(2,
dealii::CylindricalManifold<3>(
dealii::Tensor<1, 3>({0., 1., 0.}),
dealii::Point<3>()));
}
else
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
tria.refine_global(n_refinements_x);
};
const auto fu_v = [&](auto &tria) {
if constexpr (dim_v == 3)
dealii::GridGenerator::hyper_ball_balanced(tria,
dealii::Point<dim_v>(),
ball_R);
else
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
tria.refine_global(n_refinements_v);
};
hyperdeal::GridGenerator::construct_tensor_product<dim_x, dim_v>(
tria_x, tria_v, fu_x, fu_v);
}
void
set_boundary_conditions(
std::shared_ptr<
hyperdeal::advection::BoundaryDescriptor<dim_x + dim_v, Number>>
boundary_descriptor) override
{
boundary_descriptor->homogeneous_dirichlet_bc.insert(0);
}
void
set_analytical_solution(
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
&analytical_solution) override
{
analytical_solution.reset(new ExactSolution<dim_x, dim_v, Number>());
}
dealii::Tensor<1, dim_x + dim_v>
get_transport_direction() override
{
return ExactSolution<dim_x, dim_v, Number>()
.get_transport_direction();
}
LaplaceOperatorBCType
get_poisson_problem_bc_type() const override
{
return LaplaceOperatorBCType::NBC;
}
private:
unsigned int n_refinements_x = 0;
unsigned int n_refinements_v = 0;
};
} // namespace torus_hyperball
} // namespace vp
} // namespace hyperdeal
#endif
| 6,311
|
C++
|
.h
| 158
| 28.107595
| 80
| 0.517056
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,130
|
derivative_container.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/include/derivative_container.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_DERIVATIVE_CONTAINER
#define HYPERDEAL_DERIVATIVE_CONTAINER
#include <deal.II/base/aligned_vector.h>
#include <deal.II/base/tensor.h>
#include <deal.II/base/utilities.h>
#include <deal.II/matrix_free/fe_evaluation.h>
#include <deal.II/matrix_free/matrix_free.h>
namespace hyperdeal
{
namespace vp
{
/**
* Data structure storing some information at cell/face quadrature points
* (stored such a way as matrix-free needs it).
*
* TODO: add support for ECL for faces. Currently not needed for VP.
*/
template <int dim, int n_points, typename UnitType>
class QuadraturePointContainer
{
static const unsigned int n_points_cell =
dealii::Utilities::pow(n_points, dim - 0);
static const unsigned int n_points_face =
dealii::Utilities::pow(n_points, dim - 1);
public:
/**
* Return the value at a cell quadrature point.
*/
inline DEAL_II_ALWAYS_INLINE //
UnitType
get_value_cell(const unsigned int cell_index,
const unsigned int q_index) const
{
return values_cells[cell_index * n_points_cell + q_index];
}
/**
* Return the value at a interior finner face quadrature point (FCL).
*/
inline DEAL_II_ALWAYS_INLINE //
UnitType
get_value_face_interior(const unsigned int face_index,
const unsigned int q_index) const
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
return values_faces_int[face_index * n_points_face + q_index];
}
/**
* Return the value at a exterior finner ace quadrature point (FCL).
*/
inline DEAL_II_ALWAYS_INLINE //
UnitType
get_value_face_exterior(const unsigned int face_index,
const unsigned int q_index) const
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
return values_faces_ext[face_index * n_points_face + q_index];
}
virtual std::size_t
memory_consumption() const
{
return values_cells.memory_consumption() +
values_faces_int.memory_consumption() +
values_faces_ext.memory_consumption();
}
/**
* Allocate memory
*/
template <typename MF>
void
reinit(const MF &data)
{
if (values_cells.size() != data.n_cell_batches() * n_points_cell)
values_cells.resize(data.n_cell_batches() * n_points_cell);
#ifdef false
if (values_faces_int.size() !=
(data.n_inner_face_batches() + data.n_boundary_face_batches()) *
n_points_face)
values_faces_int.resize(
(data.n_inner_face_batches() + data.n_boundary_face_batches()) *
n_points_face);
if (values_faces_ext.size() !=
data.n_inner_face_batches() * n_points_face)
values_faces_ext.resize(data.n_inner_face_batches() * n_points_face);
#endif
}
protected:
/**
* Values at cell quadrature points.
*/
dealii::AlignedVector<UnitType> values_cells;
/**
* Values at interior internal face quadrature points.
*/
dealii::AlignedVector<UnitType> values_faces_int;
/**
* Values at exterior internal face quadrature points.
*/
dealii::AlignedVector<UnitType> values_faces_ext;
};
/**
* Data structure storing the precomputed derivative of a solution field
* at the quadrature points.
*
* @note This class does nothing else than computing the derivatives. The
* actual storage of the values and the access to them is handled by
* the class QuadraturePointContainer.
*/
template <int dim,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class DerivativeContainer : public QuadraturePointContainer<
dim,
n_points,
dealii::Tensor<1, dim, VectorizedArrayType>>
{
static const unsigned int n_points_cell =
dealii::Utilities::pow(n_points, dim - 0);
static const unsigned int n_points_face =
dealii::Utilities::pow(n_points, dim - 1);
public:
/*
* Recompute derivatives.
*/
template <typename VectorType>
void
update(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free,
const VectorType & src)
{
this->reinit(matrix_free);
dealii::
FEEvaluation<dim, degree, n_points, 1, Number, VectorizedArrayType>
phi_rho(matrix_free);
dealii::FEFaceEvaluation<dim,
degree,
n_points,
1,
Number,
VectorizedArrayType>
phi_rho_i(matrix_free, true);
dealii::FEFaceEvaluation<dim,
degree,
n_points,
1,
Number,
VectorizedArrayType>
phi_rho_e(matrix_free, false);
int dummy;
matrix_free.template loop<int, VectorType>(
[&](const auto &, auto &, const auto &src, const auto range) {
// cells
for (auto cell = range.first; cell < range.second; ++cell)
{
phi_rho.reinit(cell);
phi_rho.gather_evaluate(src,
dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < n_points_cell; ++q)
this->values_cells[cell * n_points_cell + q] =
phi_rho.get_gradient(q);
}
},
[&](const auto &, auto &, const auto &src, const auto range) {
// inner faces
#if true
(void)src;
(void)range;
#else
for (auto face = range.first; face < range.second; ++face)
{
// ... interior face
phi_rho_i.reinit(face);
phi_rho_i.gather_evaluate(src,
dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < n_points_face; ++q)
this->values_faces_int[face * n_points_face + q] =
phi_rho_i.get_gradient(q);
// ... exterior face
phi_rho_e.reinit(face);
phi_rho_e.gather_evaluate(src,
dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < n_points_face; ++q)
this->values_faces_ext[face * n_points_face + q] =
phi_rho_e.get_gradient(q);
}
#endif
},
[&](const auto &, auto &, const auto &src, const auto range) {
// boundary faces
#if true
(void)src;
(void)range;
#else
for (auto face = range.first; face < range.second; ++face)
{
phi_rho_i.reinit(face);
phi_rho_i.gather_evaluate(src,
dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < n_points_face; ++q)
this->values_faces_int[face * n_points_face + q] =
phi_rho_i.get_gradient(q);
}
#endif
},
dummy,
src,
false,
dealii::MatrixFree<dim, Number, VectorizedArrayType>::
DataAccessOnFaces::none,
dealii::MatrixFree<dim, Number, VectorizedArrayType>::
DataAccessOnFaces::gradients);
}
};
} // namespace vp
} // namespace hyperdeal
#endif
| 8,714
|
C++
|
.h
| 231
| 26.718615
| 80
| 0.538252
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,131
|
velocity_field_view.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/include/velocity_field_view.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_PHASESPACEVELOCITYFIELDVIEW
#define HYPERDEAL_PHASESPACEVELOCITYFIELDVIEW
#include <hyper.deal/matrix_free/id.h>
#include <hyper.deal/operators/advection/velocity_field_view.h>
#include "./derivative_container.h"
namespace hyperdeal
{
namespace vp
{
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class PhaseSpaceVelocityFieldView
: public hyperdeal::advection::VelocityFieldView<dim_x + dim_v,
Number,
TensorID,
VectorizedArrayType,
dim_x,
dim_v>
{
public:
static_assert(dim_x == dim_v,
"Vlasov-Poisson only implemented for dim_x == dim_v");
static const int dim = dim_x + dim_v;
using MF =
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>;
using VectorizedArrayTypeX = typename MF::VectorizedArrayTypeX;
using VectorizedArrayTypeV = typename MF::VectorizedArrayTypeV;
PhaseSpaceVelocityFieldView(
const hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>
&matrix_free,
const DerivativeContainer<dim_x,
degree,
n_points,
Number,
VectorizedArrayTypeX>
&negative_electric_field)
: evaluator_v(matrix_free.get_matrix_free_v(), 0, /*q-index*/ 0)
, negative_electric_field(negative_electric_field)
{}
void
reinit(TensorID cell_index) override
{
this->index_x = cell_index.x;
this->index_v = cell_index.v / VectorizedArrayTypeV::size();
this->lane_v = cell_index.v % VectorizedArrayTypeV::size();
this->face_type = TensorID::SpaceType::XV;
evaluator_v.reinit(index_v);
}
void
reinit_face(TensorID face_index) override
{
this->index_x = face_index.x;
this->index_v = face_index.v / VectorizedArrayTypeV::size();
this->lane_v = face_index.v % VectorizedArrayTypeV::size();
this->face_type = face_index.type;
if (face_type == TensorID::SpaceType::X)
evaluator_v.reinit(index_v);
}
void
reinit_face(TensorID id, unsigned int face) override
{
this->reinit(id);
AssertIndexRange(face, 2 * (dim_x + dim_v));
if (face < 2 * dim_x)
this->face_type = TensorID::SpaceType::X;
else
this->face_type = TensorID::SpaceType::V;
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_x, VectorizedArrayType>
evaluate_x(unsigned int /*q*/,
unsigned int /*q_x*/,
unsigned int q_v) const override
{
Assert(face_type == TensorID::SpaceType::XV,
dealii::StandardExceptions::ExcMessage("No cell given!"));
AssertIndexRange(q_v, dealii::Utilities::pow(n_points, dim_v));
return bcast(evaluator_v.quadrature_point(q_v), this->lane_v);
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_v, VectorizedArrayType>
evaluate_v(unsigned int /*q*/,
unsigned int q_x,
unsigned int /*q_v*/) const override
{
Assert(index_x != dealii::numbers::invalid_unsigned_int,
dealii::StandardExceptions::ExcMessage(
"The function reinit has not been called!"));
Assert(face_type == TensorID::SpaceType::XV,
dealii::StandardExceptions::ExcMessage("No cell given!"));
AssertIndexRange(q_x, dealii::Utilities::pow(n_points, dim_x));
// TODO: add magnetic field
return negative_electric_field.get_value_cell(index_x, q_x);
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_x, VectorizedArrayType>
evaluate_face_x(unsigned int /*q*/,
unsigned int /*q_x*/,
unsigned int q_v) const override
{
Assert(face_type == TensorID::SpaceType::X,
dealii::StandardExceptions::ExcMessage("No x-face given!"));
AssertIndexRange(q_v, dealii::Utilities::pow(n_points, dim_v));
return bcast(evaluator_v.quadrature_point(q_v), this->lane_v);
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_v, VectorizedArrayType>
evaluate_face_v(unsigned int /*q*/,
unsigned int q_x,
unsigned int /*q_v*/) const override
{
Assert(index_x != dealii::numbers::invalid_unsigned_int,
dealii::StandardExceptions::ExcMessage(
"The function reinit has not been called!"));
Assert(face_type == TensorID::SpaceType::V,
dealii::StandardExceptions::ExcMessage("No v-face given!"));
AssertIndexRange(q_x, dealii::Utilities::pow(n_points, dim_x));
// TODO: add magnetic field
return negative_electric_field.get_value_cell(index_x, q_x);
}
private:
static inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_x, VectorizedArrayTypeX>
bcast(const dealii::Tensor<1, dim_v, VectorizedArrayTypeV> vector_in,
const unsigned int lane_v)
{
dealii::Tensor<1, dim_x, VectorizedArrayTypeX> vector_out;
for (unsigned int d = 0; d < dim_x;
++d) // if-statment is evaluated at compile time
vector_out[d] =
vector_in[d][VectorizedArrayTypeV::size() == 0 ? 0 : lane_v];
return vector_out;
}
// current macro cell/face
unsigned int index_x = dealii::numbers::invalid_unsigned_int;
unsigned int index_v = dealii::numbers::invalid_unsigned_int;
unsigned int lane_v = dealii::numbers::invalid_unsigned_int;
typename TensorID::SpaceType face_type = TensorID::SpaceType::XV;
dealii::
FEEvaluation<dim_v, degree, n_points, 1, Number, VectorizedArrayTypeV>
evaluator_v;
const DerivativeContainer<dim_x,
degree,
n_points,
Number,
VectorizedArrayTypeX> &negative_electric_field;
};
} // namespace vp
} // namespace hyperdeal
#endif
| 7,422
|
C++
|
.h
| 168
| 32.47619
| 79
| 0.562769
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,132
|
diagnostics.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/include/diagnostics.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef NDIM_PHASE_SPACE_DIAGNOSTICS
#define NDIM_PHASE_SPACE_DIAGNOSTICS
#include <hyper.deal/matrix_free/fe_evaluation_cell.h>
#include <hyper.deal/matrix_free/matrix_free.h>
#include <hyper.deal/numerics/vector_tools.h>
namespace hyperdeal
{
/**
* [TODO]
*/
template <int degree,
int n_points,
int dim_x,
int dim_v,
typename Number,
typename VectorType,
typename VectorizedArrayType>
dealii::Tensor<1, 6, Number>
phase_space_diagnostics(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free,
const VectorType & src)
{
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VectorizedArrayType>
phi(matrix_free, 0, 0, 0, 0);
dealii::Tensor<1, 6, Number> result;
int dummy;
matrix_free.template cell_loop<int, VectorType>(
[&](const auto &, int &, const VectorType &src, const auto cell) mutable {
const VectorizedArrayType *f_ptr =
VectorTools::internal::interpolate(phi, src, cell);
dealii::Tensor<1, 6, VectorizedArrayType> temp;
for (unsigned int qv = 0, q = 0; qv < phi.n_q_points_v; qv++)
{
const auto v = phi.get_quadrature_point_v(qv);
const auto vxv = v * v;
for (unsigned int qx = 0; qx < phi.n_q_points_x; qx++, q++)
{
const auto f = f_ptr[q];
const auto JxW = phi.JxW(qx, qv);
temp[0] += f * JxW; // mass
temp[1] += f * f * JxW; // l2 norm
temp[2] += vxv * f * JxW; // kinetic energy
// components of the momentum
for (unsigned int d = 0; d < dim_v; ++d)
temp[3 + d] += v[d] * f * JxW;
}
}
// gather results (VectorizedArray<Number> -> Number)
for (unsigned int v = 0; v < phi.n_vectorization_lanes_filled(); v++)
for (unsigned int i = 0; i < 6; i++)
result[i] += temp[i][v];
},
dummy,
src);
result =
dealii::Utilities::MPI::sum(result, matrix_free.get_communicator());
result[1] = std::sqrt(result[1]);
return result;
}
/**
* [TODO]
*/
template <int degree,
int n_points,
int dim_x,
typename Number,
typename VectorType,
typename VectorizedArrayType>
dealii::Tensor<1, dim_x, Number>
compute_electric_energy(
const dealii::MatrixFree<dim_x, Number, VectorizedArrayType> &data,
const VectorType & src)
{
dealii::Tensor<1, dim_x, Number> accumulated_electric_energy;
dealii::
FEEvaluation<dim_x, degree, n_points, 1, Number, VectorizedArrayType>
phi_rho(data);
int dummy;
data.template cell_loop<int, VectorType>(
[&](
const auto &, int &, const VectorType &src, const auto range) mutable {
for (unsigned int cell = range.first; cell < range.second; ++cell)
{
dealii::Tensor<1, dim_x, VectorizedArrayType> local_sum;
phi_rho.reinit(cell);
phi_rho.gather_evaluate(src, dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < phi_rho.n_q_points; ++q)
for (unsigned int d = 0; d < dim_x; ++d)
local_sum[d] += phi_rho.get_gradient(q)[d] *
phi_rho.get_gradient(q)[d] * phi_rho.JxW(q);
for (unsigned int v = 0;
v < data.n_active_entries_per_cell_batch(cell);
++v)
for (unsigned int d = 0; d < dim_x; ++d)
accumulated_electric_energy[d] += local_sum[d][v];
}
},
dummy,
src);
const auto tria =
dynamic_cast<const dealii::parallel::TriangulationBase<dim_x> *>(
&data.get_dof_handler().get_triangulation());
const MPI_Comm comm = tria ? tria->get_communicator() : MPI_COMM_SELF;
return dealii::Utilities::MPI::sum(accumulated_electric_energy, comm);
}
} // namespace hyperdeal
#endif
| 4,818
|
C++
|
.h
| 121
| 31.710744
| 80
| 0.557886
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,133
|
application.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/include/application.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <hyper.deal/base/config.h>
#include <deal.II/base/conditional_ostream.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <deal.II/matrix_free/tools.h>
#include <deal.II/numerics/data_out.h>
#include <hyper.deal/base/memory_consumption.h>
#include <hyper.deal/base/time_integrators.h>
#include <hyper.deal/base/time_loop.h>
#include <hyper.deal/base/timers.h>
#include <hyper.deal/matrix_free/matrix_free.h>
#include <hyper.deal/numerics/vector_tools.h>
#include <hyper.deal/operators/advection/advection_operation.h>
#include <hyper.deal/operators/advection/cfl.h>
#include <hyper.deal/operators/advection/velocity_field_view.h>
#include "derivative_container.h"
#include "diagnostics.h"
#include "parameters.h"
#include "poisson.h"
#include "velocity_field_view.h"
namespace hyperdeal
{
namespace vp
{
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class Application
{
public:
static const int dim = dim_x + dim_v;
using MF =
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>;
using VectorizedArrayTypeX = typename MF::VectorizedArrayTypeX;
using VectorizedArrayTypeV = typename MF::VectorizedArrayTypeV;
using VelocityFieldView =
vp::PhaseSpaceVelocityFieldView<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayTypeX>;
using PoissonMatrixType =
LaplaceOperator<dim_x, degree, n_points, Number, VectorizedArrayType>;
using VectorType = dealii::LinearAlgebra::distributed::Vector<Number>;
using VectorType2 = dealii::LinearAlgebra::distributed::Vector<Number>;
Application(const MPI_Comm comm_global,
const MPI_Comm comm_sm,
const unsigned int size_x,
const unsigned int size_v,
DynamicConvergenceTable &table)
: comm_global(comm_global)
, comm_sm(comm_sm)
, comm_row(mpi::create_row_comm(comm_global, size_x, size_v))
, comm_column(mpi::create_column_comm(comm_global, size_x, size_v))
, matrix_free(comm_global, comm_sm, matrix_free_x, matrix_free_v)
, advection_operation(matrix_free, table)
, pcout(std::cout,
dealii::Utilities::MPI::this_mpi_process(comm_global) == 0)
, table(table)
{}
~Application()
{
MPI_Comm_free(&comm_row);
MPI_Comm_free(&comm_column);
}
void
reinit(const std::string file_name)
{
// clang-format off
pcout << "--------------------------------------------------------------------------------" << std::endl;
pcout << "Setup:" << std::endl;
// clang-format on
table.set("info->procs",
dealii::Utilities::MPI::n_mpi_processes(comm_global));
table.set("info->procs_x",
dealii::Utilities::MPI::n_mpi_processes(comm_row));
table.set("info->procs_v",
dealii::Utilities::MPI::n_mpi_processes(comm_column));
table.set("info->procs_sm",
dealii::Utilities::MPI::n_mpi_processes(comm_sm));
const unsigned int degree_x = degree;
const unsigned int degree_v = degree;
const unsigned int n_points_x = n_points;
const unsigned int n_points_v = n_points;
table.set("info->dim_x", dim_x);
table.set("info->dim_v", dim_v);
table.set("info->degree_x", degree_x);
table.set("info->degree_v", degree_v);
const auto initializer =
cases::get<dim_x, dim_v, degree, Number>(file_name, pcout);
initializer->set_input_parameters(param, file_name, pcout);
MemoryStatMonitor memory_stat_monitor(comm_global);
// step 1: create two low-dimensional triangulations
{
pcout << " - dealii::Triangulation (x/v)" << std::endl;
memory_stat_monitor.monitor("triangulation");
// clang-format off
if(param.triangulation_type == "fullydistributed")
{
triangulation_x.reset(new dealii::parallel::fullydistributed::Triangulation<dim_x>(comm_row));
triangulation_v.reset(new dealii::parallel::fullydistributed::Triangulation<dim_v>(comm_column));
}
#ifdef DEAL_II_WITH_P4EST
else if(param.triangulation_type == "distributed")
{
triangulation_x.reset(new dealii::parallel::distributed::Triangulation<dim_x>(comm_row,
dealii::Triangulation<dim_x>::none,
dealii::parallel::distributed::Triangulation<dim_x>::construct_multigrid_hierarchy));
triangulation_v.reset(new dealii::parallel::distributed::Triangulation<dim_v>(comm_column,
dealii::Triangulation<dim_v>::none,
dealii::parallel::distributed::Triangulation<dim_v>::construct_multigrid_hierarchy));
}
#endif
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
// clang-format on
initializer->create_grid(triangulation_x, triangulation_v);
// output low-dimensional meshes (optional)
if (param.output_grid)
{
dealii::GridOut grid_out;
if (dealii::Utilities::MPI::this_mpi_process(comm_column) == 0)
grid_out.write_mesh_per_processor_as_vtu(*this->triangulation_x,
"grid_x");
if (dealii::Utilities::MPI::this_mpi_process(comm_row) == 0)
grid_out.write_mesh_per_processor_as_vtu(*this->triangulation_v,
"grid_v");
}
}
// step 2: create two low-dimensional dof-handler
{
pcout << " - dealii::DoFHandler (x/v)" << std::endl;
memory_stat_monitor.monitor("dofhandler");
dof_handler_x.reset(new dealii::DoFHandler<dim_x>(*triangulation_x));
dof_handler_v.reset(new dealii::DoFHandler<dim_v>(*triangulation_v));
dealii::FE_DGQ<dim_x> fe_x(degree_x);
dealii::FE_DGQ<dim_v> fe_v(degree_v);
dof_handler_x->distribute_dofs(fe_x);
dof_handler_x->distribute_mg_dofs();
dof_handler_v->distribute_dofs(fe_v);
table.set("info->size_x", dof_handler_x->n_dofs());
table.set("info->size_v", dof_handler_v->n_dofs());
table.set("info->size",
dof_handler_x->n_dofs() * dof_handler_v->n_dofs());
}
// step 3: setup two low-dimensional matrix-frees
{
memory_stat_monitor.monitor("dealii::matrixfree");
dealii::AffineConstraints<Number> constraint;
constraint.close();
{
pcout << " - dealii::MatrixFree (x)" << std::endl;
typename dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>::
AdditionalData additional_data;
additional_data.mapping_update_flags =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.mapping_update_flags_inner_faces =
dealii::update_gradients | dealii::update_JxW_values;
additional_data.mapping_update_flags_boundary_faces =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.hold_all_faces_to_owned_cells = true;
additional_data.mapping_update_flags_faces_by_cells =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
dealii::MappingQGeneric<dim_x> mapping_x(param.mapping_degree_x);
std::vector<const dealii::DoFHandler<dim_x> *> dof_handlers{
&*dof_handler_x};
std::vector<const dealii::AffineConstraints<Number> *> constraints{
&constraint};
std::vector<dealii::Quadrature<1>> quads;
if (param.do_collocation)
quads.push_back(dealii::QGaussLobatto<1>(n_points_x));
else
quads.push_back(dealii::QGauss<1>(n_points_x));
quads.push_back(dealii::QGauss<1>(degree_x + 1));
quads.push_back(dealii::QGaussLobatto<1>(degree_x + 1));
// ensure that inner and boundary faces are not mixed in the
// same macro cell
if (param.use_ecl)
dealii::MatrixFreeTools::categorize_by_boundary_ids(
*triangulation_x, additional_data);
matrix_free_x.reinit(
mapping_x, dof_handlers, constraints, quads, additional_data);
// Poisson solver: [TODO] not a great place here...
{
const bool use_multigrid = true; // [TODO]: parameter file
poisson_matrix.initialize(
matrix_free_x, initializer->get_poisson_problem_bc_type());
if (!use_multigrid) // solve with PCG + Chebychev preconditioner
{
poisson_solver.reset(
new PoissonSolver<PoissonMatrixType>(poisson_matrix));
}
else // solve with PCG + multigrid preconditioner
{
const unsigned int min_level = 0;
const unsigned int max_level =
triangulation_x->n_global_levels() - 1;
auto level_matrix_free =
std::make_shared<dealii::MGLevelObject<
dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>>>(
min_level, max_level);
auto mg_matrices =
std::make_shared<dealii::MGLevelObject<PoissonMatrixType>>(
min_level, max_level);
// initialize levels
for (unsigned int level = min_level; level <= max_level;
level++)
{
// ... initialize matrix_free
additional_data.mg_level = level;
if (param.use_ecl)
dealii::MatrixFreeTools::categorize_by_boundary_ids(
*triangulation_x, additional_data);
(*level_matrix_free)[level].reinit(mapping_x,
dof_handlers,
constraints,
quads,
additional_data);
// ... initialize level operator
(*mg_matrices)[level].initialize(
(*level_matrix_free)[level],
initializer->get_poisson_problem_bc_type());
}
poisson_solver.reset(new PoissonSolverMG<PoissonMatrixType>(
poisson_matrix, level_matrix_free, mg_matrices));
}
}
}
{
pcout << " - dealii::MatrixFree (v)" << std::endl;
typename dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV>::
AdditionalData additional_data;
additional_data.mapping_update_flags =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.mapping_update_flags_inner_faces =
dealii::update_gradients | dealii::update_JxW_values;
additional_data.mapping_update_flags_boundary_faces =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.hold_all_faces_to_owned_cells = true;
additional_data.mapping_update_flags_faces_by_cells =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
dealii::MappingQGeneric<dim_v> mapping_v(param.mapping_degree_v);
std::vector<const dealii::DoFHandler<dim_v> *> dof_handlers{
&*dof_handler_v};
std::vector<const dealii::AffineConstraints<Number> *> constraints{
&constraint};
std::vector<dealii::Quadrature<1>> quads;
if (param.do_collocation)
quads.push_back(dealii::QGaussLobatto<1>(n_points_v));
else
quads.push_back(dealii::QGauss<1>(n_points_v));
quads.push_back(dealii::QGauss<1>(degree_v + 1));
quads.push_back(dealii::QGaussLobatto<1>(degree_v + 1));
// ensure that inner and boundary faces are not mixed in the
// same macro cell
if (param.use_ecl)
dealii::MatrixFreeTools::categorize_by_boundary_ids(
*triangulation_v, additional_data);
matrix_free_v.reinit(
mapping_v, dof_handlers, constraints, quads, additional_data);
}
}
// step 4: setup tensor-product matrixfree
{
memory_stat_monitor.monitor("hyperdeal_matrixfree");
pcout << " - hyperdeal::MatrixFree" << std::endl;
typename MF::AdditionalData ad;
ad.do_ghost_faces = param.do_ghost_faces;
ad.do_buffering = param.do_buffering;
ad.use_ecl = param.use_ecl;
ad.overlapping_level = param.overlapping_level;
matrix_free.reinit(ad);
}
// step 5: allocate memory for vectors (with only vct_Ti having ghost
// value)
{
// clang-format off
memory_stat_monitor.monitor("vector_solution");
matrix_free.initialize_dof_vector(vct_solution, 0, false || !param.use_ecl, true);
memory_stat_monitor.monitor("vector_Ki");
matrix_free.initialize_dof_vector(vct_Ki, 0, false || !param.use_ecl, true);
memory_stat_monitor.monitor("vector_Ti");
matrix_free.initialize_dof_vector(vct_Ti, 0, true, true);
// clang-format on
// initialize vectors in x-space
memory_stat_monitor.monitor("vector_particle_density");
matrix_free_x.initialize_dof_vector(particle_density);
particle_density = 0.0;
particle_density.zero_out_ghost_values();
memory_stat_monitor.monitor("vector_potential");
matrix_free_x.initialize_dof_vector(potential);
potential = 0.0;
potential.zero_out_ghost_values();
}
// step 6: set initial condition in Gauss-Lobatto points (quad_no_x = 2,
// quad_no_v = 2)
{
pcout << " - advection::initial_condition" << std::endl;
initializer->set_analytical_solution(analytical_solution);
VectorTools::interpolate<degree, n_points>(
analytical_solution, matrix_free, vct_solution, 0, 0, 2, 2);
}
// step 7: set boundary conditions
{
pcout << " - advection::boundary_condition" << std::endl;
boundary_descriptor.reset(
new advection::BoundaryDescriptor<dim, Number>());
initializer->set_boundary_conditions(boundary_descriptor);
}
// step 8: set (constant) velocity field
{
pcout << " - advection::velocity_field_view" << std::endl;
velocity_field =
std::make_shared<VelocityFieldView>(matrix_free,
negative_electric_field);
}
// step 9: initialize advection operator
{
pcout << " - advection::operator" << std::endl;
advection_operation.reinit(boundary_descriptor,
velocity_field,
param.advection_operation_parameters);
}
// step 10: time loop
{
pcout << " - advection::time_loop" << std::endl;
auto &time_loop_parameters = param.time_loop_parameters;
// determine critical time step (CFL condition)
const Number critical_time_step =
hyperdeal::advection::compute_critical_time_step(
*dof_handler_x.get(),
*dof_handler_v.get(),
initializer->get_transport_direction(),
degree_x,
n_points_x,
comm_row,
degree_v,
n_points_v,
comm_column);
// determine minimal time step (parameter file vs. CFL)
const Number dt = std::min(time_loop_parameters.time_step,
param.cfl_number * critical_time_step /
std::pow(degree, 1.5));
// set time step s.t. final time step ends at final time
time_loop_parameters.time_step =
(time_loop_parameters.final_time -
time_loop_parameters.start_time) /
std::ceil((time_loop_parameters.final_time -
time_loop_parameters.start_time) /
dt);
// setup time loop
time_loop.reinit(time_loop_parameters);
}
{
memory_stat_monitor.monitor("negative_electric_field");
negative_electric_field.reinit(matrix_free_x);
}
// clang-format off
pcout << " ... done!" << std::endl;
pcout << "--------------------------------------------------------------------------------" << std::endl << std::endl;
// clang-format on
{
memory_stat_monitor.print(pcout);
const auto &mem = memory_consumption();
mem.print(comm_global, pcout);
}
}
void
solve()
{
LowStorageRungeKuttaIntegrator<Number, VectorType> time_integrator(
vct_Ki, vct_Ti, param.rk_parameters.type, param.use_ecl);
bool clear_diag_file = true;
unsigned int time_step_counter = 0;
unsigned int n_total_poisson_iterations = 0;
#ifdef PERFORMANCE_TIMING
bool performance_timing = true;
#else
bool performance_timing = false;
#endif
Timers timers(param.performance_log_all_calls);
const unsigned int time_steps = time_loop.loop(
vct_solution,
[&](auto & solution,
const auto cur_time,
const auto time_step,
const auto &runnable) {
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
if (time_step_counter == param.performance_warm_up_iterations)
{
if (time_step_counter != 0)
timers.reset();
n_total_poisson_iterations = 0;
MPI_Barrier(comm_global);
timers["id_total"].start();
}
time_step_counter++;
}
#endif
ScopedTimerWrapper timer(timers, "id_stage");
time_integrator.perform_time_step(solution,
cur_time,
time_step,
runnable);
},
[&](const VectorType &src, VectorType &dst, const Number cur_time) {
{
// step 1: determine particle density ρ via integral over v-space
ScopedTimerWrapper timer(timers, "id_step1");
//...use Gauss-Lobatto points (quad_no_v = 2)
VectorTools::velocity_space_integration<degree, n_points>(
matrix_free,
particle_density,
src,
0 /* dof_no_x*/,
0 /*dof_no_v*/,
2 /* quad_no_v */);
}
{
// step 2: Take 1-particle_density (where we use the approximated
// one by the mean)
ScopedTimerWrapper timer(timers, "id_step2");
// subtract mean (why is this necessary?)
if (poisson_matrix.is_singular())
particle_density.add(-particle_density.mean_value());
// test the particle density to obtain the right-hand-side
// for the Poisson problem
dealii::FEEvaluation<dim_x, degree, n_points, 1, Number> phi_x(
matrix_free_x);
matrix_free_x.template cell_loop<VectorType2, VectorType2>(
[&](const auto &,
auto & dst,
const auto &src,
const auto range) mutable {
for (unsigned int cell = range.first; cell < range.second;
++cell)
{
phi_x.reinit(cell);
phi_x.gather_evaluate(src,
dealii::EvaluationFlags::values);
for (unsigned int q = 0; q < phi_x.n_q_points; ++q)
phi_x.submit_value(-phi_x.get_value(q), q);
phi_x.integrate(dealii::EvaluationFlags::values);
phi_x.set_dof_values(dst);
}
},
particle_density,
particle_density);
// subtract mean needed by Poisson solver
if (poisson_matrix.is_singular())
particle_density.add(-particle_density.mean_value());
}
{
// step 3: solution of Poisson problem with inverted partial
// density
ScopedTimerWrapper timer(timers, "id_step3");
n_total_poisson_iterations +=
poisson_solver->solve(potential, particle_density);
}
{
// step 4: derivative of potential gives the negative electric
// field
ScopedTimerWrapper timer(timers, "id_step4");
negative_electric_field.update(matrix_free_x, potential);
}
{
// step 5: advect in phase space
ScopedTimerWrapper timer(timers, "id_step5");
timers.enter("id_step5");
{
ScopedTimerWrapper timer(timers, "id_advection");
if (performance_timing || param.performance_log_all_calls)
advection_operation.apply(dst, src, cur_time, &timers);
else
advection_operation.apply(dst, src, cur_time);
}
timers.leave();
}
},
[&](const Number cur_time) {
if (!param.dignostics_enabled ||
(cur_time != param.time_loop_parameters.start_time &&
static_cast<int>((cur_time + 0.00000000001 -
param.time_loop_parameters.start_time) /
param.dignostics_tick) ==
static_cast<int>((cur_time + 0.00000000001 -
param.time_loop_parameters.start_time -
param.time_loop_parameters.time_step) /
param.dignostics_tick)))
return; // nothing to do
ScopedTimerWrapper timer(timers, "id_diagnostics");
// compute electric energy [TODO] recompute potential!
const auto en =
compute_electric_energy<degree, n_points>(matrix_free_x,
potential);
// run phase-space diagnostics
const auto diag_val =
phase_space_diagnostics<degree, n_points>(matrix_free,
vct_solution);
if (pcout.is_active())
fprintf(stdout, " Time:%10.3e \n", cur_time);
if (dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)
{
std::ofstream diag_file;
if (clear_diag_file == true)
{
diag_file.open(param.diag_file, std::ios::trunc);
diag_file
<< "# time energy components mass l2norm kinetic energy momentum "
<< std::endl;
diag_file << std::setw(8) << std::fixed
<< std::setprecision(3) << cur_time << " "
<< std::setprecision(16) << std::scientific << en
<< " " << diag_val[0] << " " << diag_val[1] << " "
<< diag_val[2] << " " << diag_val[3] << " "
<< diag_val[4] << " " << diag_val[5] << std::endl;
clear_diag_file = false;
}
else
{
diag_file.open(param.diag_file, std::ios::app);
diag_file << std::setw(8) << std::fixed
<< std::setprecision(3) << cur_time << " "
<< std::setprecision(16) << std::scientific << en
<< " " << diag_val[0] << " " << diag_val[1] << " "
<< diag_val[2] << " " << diag_val[3] << " "
<< diag_val[4] << " " << diag_val[5] << std::endl;
}
}
// temporal particle density vector since the actual particle
// vector is overwritten in the Poisson solver
VectorType2 particle_density_temp;
matrix_free_x.initialize_dof_vector(particle_density_temp);
// compute particle density and potiential again
if (param.dignostics_vtk)
{
VectorTools::velocity_space_integration<degree, n_points>(
matrix_free,
particle_density,
vct_solution,
0 /* dof_no_x*/,
0 /*dof_no_v*/,
2 /* quad_no_v */);
if (poisson_matrix.is_singular())
particle_density.add(-particle_density.mean_value());
particle_density_temp.copy_locally_owned_data_from(
particle_density);
dealii::FEEvaluation<dim_x, degree, n_points, 1, Number> phi_x(
matrix_free_x);
matrix_free_x.template cell_loop<VectorType2, VectorType2>(
[&](const auto &,
auto & dst,
const auto &src,
const auto range) mutable {
for (unsigned int cell = range.first; cell < range.second;
++cell)
{
phi_x.reinit(cell);
phi_x.gather_evaluate(src,
dealii::EvaluationFlags::values);
for (unsigned int q = 0; q < phi_x.n_q_points; ++q)
phi_x.submit_value(-phi_x.get_value(q), q);
phi_x.integrate(dealii::EvaluationFlags::values);
phi_x.set_dof_values(dst);
}
},
particle_density,
particle_density);
// subtract mean needed by Poisson solver
if (poisson_matrix.is_singular())
particle_density.add(-particle_density.mean_value());
potential = 0.0;
poisson_solver->solve(potential, particle_density);
}
// output VTK files once
if (dealii::Utilities::MPI::this_mpi_process(comm_column) == 0)
{
dealii::DataOutBase::VtkFlags flags;
flags.write_higher_order_cells = true;
dealii::DataOut<dim_x> data_out;
data_out.set_flags(flags);
data_out.attach_dof_handler(*dof_handler_x);
data_out.add_data_vector(particle_density_temp,
"particle_density");
data_out.add_data_vector(potential, "potential");
data_out.build_patches(
dealii::MappingQGeneric<dim_x>(3),
3,
dealii::DataOut<dim_x>::CurvedCellRegion::curved_inner_cells);
const std::string filename =
"solution_" + std::to_string(time_step_counter) + ".vtu";
data_out.write_vtu_in_parallel(filename, comm_row);
}
});
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
MPI_Barrier(comm_global);
timers["id_total"].stop();
timers.print(comm_global, pcout);
}
#endif
{
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
auto &timer = timers["id_stage"];
AssertThrow(time_steps == time_step_counter,
dealii::StandardExceptions::ExcMessage(
"Mismatch in time step counter!"));
AssertThrow((time_steps - param.performance_warm_up_iterations) ==
timer.get_counter(),
dealii::StandardExceptions::ExcMessage(
"Mismatch in time step counter!"));
}
#endif
table.set("info->time_steps",
time_steps - param.performance_warm_up_iterations);
#ifdef PERFORMANCE_TIMING
if (performance_timing)
{
auto &timer = timers["id_stage"];
table.set("throughput [MDoFs/s]",
dof_handler_x->n_dofs() * dof_handler_v->n_dofs() *
timer.get_counter() * time_integrator.n_stages() /
timer.get_accumulated_time());
table.set("throughput [MDoFs/s/core]",
dof_handler_x->n_dofs() * dof_handler_v->n_dofs() *
timer.get_counter() * time_integrator.n_stages() /
timer.get_accumulated_time() /
dealii::Utilities::MPI::n_mpi_processes(comm_row) /
dealii::Utilities::MPI::n_mpi_processes(comm_column));
table.set("avg. Poisson iterations",
static_cast<double>(n_total_poisson_iterations) /
timers["id_step3"].get_counter());
}
#endif
}
}
MemoryConsumption
memory_consumption() const
{
MemoryConsumption mem("application");
mem.insert("triangulation_x", triangulation_x->memory_consumption());
mem.insert("triangulation_v", triangulation_v->memory_consumption());
mem.insert("dof_handler_x", dof_handler_x->memory_consumption());
mem.insert("dof_handler_v", dof_handler_v->memory_consumption());
mem.insert("matrix_free_x", matrix_free_x.memory_consumption());
mem.insert("matrix_free_v", matrix_free_v.memory_consumption());
mem.insert(matrix_free.memory_consumption());
MemoryConsumption mem_vec("vct");
mem_vec.insert("solution", vct_solution.memory_consumption());
mem_vec.insert("Ki", vct_Ki.memory_consumption());
mem_vec.insert("Ti", vct_Ti.memory_consumption());
mem_vec.insert("particle_density",
particle_density.memory_consumption());
mem_vec.insert("potential", potential.memory_consumption());
mem.insert(mem_vec);
// [TODO]: poisson_matrix
// [TODO]: poisson_solver
mem.insert("negative_electric_field",
negative_electric_field.memory_consumption());
return mem;
}
private:
// communicators
const MPI_Comm comm_global;
const MPI_Comm comm_sm;
MPI_Comm comm_row; // should be const. but has to be freed at the end
MPI_Comm comm_column; // the same here
// x- and v-space objects
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>>
triangulation_x;
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>>
triangulation_v;
std::shared_ptr<dealii::DoFHandler<dim_x>> dof_handler_x;
std::shared_ptr<dealii::DoFHandler<dim_v>> dof_handler_v;
dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX> matrix_free_x;
dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV> matrix_free_v;
MF matrix_free;
advection::AdvectionOperation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityFieldView,
VectorizedArrayTypeX>
advection_operation;
dealii::ConditionalOStream pcout;
DynamicConvergenceTable & table;
std::shared_ptr<dealii::Function<dim, Number>> analytical_solution;
std::shared_ptr<hyperdeal::advection::BoundaryDescriptor<dim, Number>>
boundary_descriptor;
std::shared_ptr<VelocityFieldView> velocity_field;
VectorType vct_solution, vct_Ki, vct_Ti;
TimeLoop<Number, VectorType> time_loop;
Parameters<Number> param;
PoissonMatrixType poisson_matrix;
// TODO: document
VectorType2 particle_density, potential;
std::shared_ptr<PoissonSolverBase<VectorType2>> poisson_solver;
// negative electric field
hyperdeal::vp::DerivativeContainer<dim_x,
degree,
n_points,
Number,
VectorizedArrayTypeX>
negative_electric_field;
};
} // namespace vp
} // namespace hyperdeal
| 35,581
|
C++
|
.h
| 742
| 32.909704
| 126
| 0.524341
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,134
|
poisson.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/include/poisson.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_OPERATORS_POISSON
#define HYPERDEAL_NDIM_OPERATORS_POISSON
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/subscriptor.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/matrix_free/fe_evaluation.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <deal.II/multigrid/mg_coarse.h>
#include <deal.II/multigrid/mg_matrix.h>
#include <deal.II/multigrid/mg_smoother.h>
#include <deal.II/multigrid/mg_transfer_matrix_free.h>
#include <deal.II/multigrid/multigrid.h>
enum class LaplaceOperatorBCType
{
DBC,
NBC,
PBC
};
template <int dim_,
int fe_degree,
int n_q_points_1d,
typename Number,
typename VectorizedArrayType_>
class LaplaceOperator : public dealii::Subscriptor
{
public:
static const int dim = dim_;
using value_type = Number;
using VectorizedArrayType = VectorizedArrayType_;
using VectorType = dealii::LinearAlgebra::distributed::Vector<Number>;
void
initialize(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free,
const LaplaceOperatorBCType bc_type)
{
this->matrix_free = &matrix_free;
this->bc_type = bc_type;
if ((bc_type == LaplaceOperatorBCType::NBC ||
bc_type == LaplaceOperatorBCType::PBC) &&
(matrix_free.get_mg_level() == dealii::numbers::invalid_unsigned_int))
this->do_zero_mean = true;
else
this->do_zero_mean = false;
}
bool
is_singular() const
{
return this->do_zero_mean;
}
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &
get_matrix_free() const
{
return *this->matrix_free;
}
void
initialize_dof_vector(VectorType &vector) const
{
matrix_free->initialize_dof_vector(vector);
}
void
vmult(VectorType &dst, const VectorType &src) const
{
VectorType src_;
const VectorType *src_ptr = &src;
if (do_zero_mean)
{
src_.reinit(src, true);
src_.copy_locally_owned_data_from(src);
src_.add(-src_.mean_value());
src_ptr = &src_;
}
matrix_free->loop(&LaplaceOperator::local_apply,
&LaplaceOperator::local_apply_face,
&LaplaceOperator::local_apply_boundary,
this,
dst,
*src_ptr);
}
void
Tvmult(VectorType &dst, const VectorType &src) const
{
this->vmult(dst, src);
}
void
compute_inverse_diagonal(VectorType &inverse_diagonal_entries) const
{
matrix_free->initialize_dof_vector(inverse_diagonal_entries);
inverse_diagonal_entries = 0.0;
unsigned int dummy;
matrix_free->loop(&LaplaceOperator::local_diagonal_cell,
&LaplaceOperator::local_diagonal_face,
&LaplaceOperator::local_diagonal_boundary,
this,
inverse_diagonal_entries,
dummy);
for (unsigned int i = 0; i < inverse_diagonal_entries.locally_owned_size();
++i)
if (std::abs(inverse_diagonal_entries.local_element(i)) > 1e-10)
inverse_diagonal_entries.local_element(i) =
1. / inverse_diagonal_entries.local_element(i);
}
Number
el(const dealii::types::global_dof_index,
const dealii::types::global_dof_index) const
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
return 0;
}
dealii::types::global_dof_index
m() const
{
return matrix_free->get_vector_partitioner()->size();
}
private:
void
local_apply(const dealii::MatrixFree<dim, Number, VectorizedArrayType> &data,
dealii::LinearAlgebra::distributed::Vector<Number> & dst,
const dealii::LinearAlgebra::distributed::Vector<Number> & src,
const std::pair<unsigned int, unsigned int> &cell_range) const
{
dealii::FEEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
phi(data);
for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell)
{
phi.reinit(cell);
phi.read_dof_values(src);
phi.evaluate(dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < phi.n_q_points; ++q)
phi.submit_gradient(phi.get_gradient(q), q);
phi.integrate(dealii::EvaluationFlags::gradients);
phi.set_dof_values(dst);
}
}
void
local_apply_face(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &data,
dealii::LinearAlgebra::distributed::Vector<Number> & dst,
const dealii::LinearAlgebra::distributed::Vector<Number> & src,
const std::pair<unsigned int, unsigned int> &face_range) const
{
dealii::FEFaceEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
fe_eval(data, true);
dealii::FEFaceEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
fe_eval_neighbor(data, false);
for (unsigned int face = face_range.first; face < face_range.second; face++)
{
fe_eval.reinit(face);
fe_eval_neighbor.reinit(face);
fe_eval.read_dof_values(src);
fe_eval.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
fe_eval_neighbor.read_dof_values(src);
fe_eval_neighbor.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
VectorizedArrayType sigmaF =
(std::abs((fe_eval.get_normal_vector(0) *
fe_eval.inverse_jacobian(0))[dim - 1]) +
std::abs((fe_eval.get_normal_vector(0) *
fe_eval_neighbor.inverse_jacobian(0))[dim - 1])) *
(Number)(std::max(fe_degree, 1) * (fe_degree + 1.0));
for (unsigned int q = 0; q < fe_eval.n_q_points; ++q)
{
VectorizedArrayType average_value =
(fe_eval.get_value(q) - fe_eval_neighbor.get_value(q)) * 0.5;
VectorizedArrayType average_valgrad =
fe_eval.get_normal_derivative(q) +
fe_eval_neighbor.get_normal_derivative(q);
average_valgrad =
average_value * 2. * sigmaF - average_valgrad * 0.5;
fe_eval.submit_normal_derivative(-average_value, q);
fe_eval_neighbor.submit_normal_derivative(-average_value, q);
fe_eval.submit_value(average_valgrad, q);
fe_eval_neighbor.submit_value(-average_valgrad, q);
}
fe_eval.integrate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
fe_eval.distribute_local_to_global(dst);
fe_eval_neighbor.integrate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
fe_eval_neighbor.distribute_local_to_global(dst);
}
}
void
local_apply_boundary(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &data,
dealii::LinearAlgebra::distributed::Vector<Number> & dst,
const dealii::LinearAlgebra::distributed::Vector<Number> & src,
const std::pair<unsigned int, unsigned int> &face_range) const
{
dealii::FEFaceEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
fe_eval(data, true);
for (unsigned int face = face_range.first; face < face_range.second; face++)
{
fe_eval.reinit(face);
fe_eval.read_dof_values(src);
fe_eval.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
VectorizedArrayType sigmaF =
std::abs((fe_eval.get_normal_vector(0) *
fe_eval.inverse_jacobian(0))[dim - 1]) *
Number(std::max(fe_degree, 1) * (fe_degree + 1.0)) * 2.0;
for (unsigned int q = 0; q < fe_eval.n_q_points; ++q)
{
if (bc_type == LaplaceOperatorBCType::NBC)
{
VectorizedArrayType jump_value = 0.0;
VectorizedArrayType average_gradient = 0.0;
average_gradient = average_gradient - jump_value * sigmaF;
fe_eval.submit_normal_derivative(-0.5 * jump_value, q);
fe_eval.submit_value(-average_gradient, q);
}
else if (bc_type == LaplaceOperatorBCType::DBC)
{
VectorizedArrayType average_value = fe_eval.get_value(q);
VectorizedArrayType average_valgrad =
-fe_eval.get_normal_derivative(q);
average_valgrad += average_value * sigmaF * 2.0;
fe_eval.submit_normal_derivative(-average_value, q);
fe_eval.submit_value(average_valgrad, q);
}
else
{
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
}
}
fe_eval.integrate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
fe_eval.distribute_local_to_global(dst);
}
}
void
local_diagonal_cell(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &data,
dealii::LinearAlgebra::distributed::Vector<Number> & dst,
const unsigned int &,
const std::pair<unsigned int, unsigned int> &cell_range) const
{
dealii::FEEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
phi(data);
for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell)
{
phi.reinit(cell);
VectorizedArrayType local_diagonal_vector[phi.static_dofs_per_cell];
for (unsigned int i = 0; i < phi.dofs_per_cell; ++i)
{
for (unsigned int j = 0; j < phi.dofs_per_cell; ++j)
phi.begin_dof_values()[j] = VectorizedArrayType();
phi.begin_dof_values()[i] = 1.;
phi.evaluate(dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < phi.n_q_points; ++q)
phi.submit_gradient(phi.get_gradient(q), q);
phi.integrate(dealii::EvaluationFlags::gradients);
local_diagonal_vector[i] = phi.begin_dof_values()[i];
}
for (unsigned int i = 0; i < phi.static_dofs_per_cell; ++i)
phi.begin_dof_values()[i] = local_diagonal_vector[i];
phi.set_dof_values(dst);
}
}
void
local_diagonal_face(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &data,
dealii::LinearAlgebra::distributed::Vector<Number> & dst,
const unsigned int &,
const std::pair<unsigned int, unsigned int> &face_range) const
{
dealii::FEFaceEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
phi(data, true);
dealii::FEFaceEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
phi_outer(data, false);
for (unsigned int face = face_range.first; face < face_range.second; face++)
{
phi.reinit(face);
phi_outer.reinit(face);
VectorizedArrayType local_diagonal_vector[phi.static_dofs_per_cell];
VectorizedArrayType sigmaF =
(std::abs(
(phi.get_normal_vector(0) * phi.inverse_jacobian(0))[dim - 1]) +
std::abs((phi.get_normal_vector(0) *
phi_outer.inverse_jacobian(0))[dim - 1])) *
(Number)(std::max(fe_degree, 1) * (fe_degree + 1.0));
// Compute phi part
for (unsigned int j = 0; j < phi.dofs_per_cell; ++j)
phi_outer.begin_dof_values()[j] = VectorizedArrayType();
phi_outer.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
for (unsigned int i = 0; i < phi.dofs_per_cell; ++i)
{
for (unsigned int j = 0; j < phi.dofs_per_cell; ++j)
phi.begin_dof_values()[j] = VectorizedArrayType();
phi.begin_dof_values()[i] = 1.;
phi.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < phi.n_q_points; ++q)
{
VectorizedArrayType average_value =
(phi.get_value(q) - phi_outer.get_value(q)) * 0.5;
VectorizedArrayType average_valgrad =
phi.get_normal_derivative(q) +
phi_outer.get_normal_derivative(q);
average_valgrad =
average_value * 2. * sigmaF - average_valgrad * 0.5;
phi.submit_normal_derivative(-average_value, q);
phi.submit_value(average_valgrad, q);
}
phi.integrate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
local_diagonal_vector[i] = phi.begin_dof_values()[i];
}
for (unsigned int i = 0; i < phi.dofs_per_cell; ++i)
phi.begin_dof_values()[i] = local_diagonal_vector[i];
phi.distribute_local_to_global(dst);
// Compute phi_outer part
for (unsigned int j = 0; j < phi.dofs_per_cell; ++j)
phi.begin_dof_values()[j] = VectorizedArrayType();
phi.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
for (unsigned int i = 0; i < phi.dofs_per_cell; ++i)
{
for (unsigned int j = 0; j < phi.dofs_per_cell; ++j)
phi_outer.begin_dof_values()[j] = VectorizedArrayType();
phi_outer.begin_dof_values()[i] = 1.;
phi_outer.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < phi.n_q_points; ++q)
{
VectorizedArrayType average_value =
(phi.get_value(q) - phi_outer.get_value(q)) * 0.5;
VectorizedArrayType average_valgrad =
phi.get_normal_derivative(q) +
phi_outer.get_normal_derivative(q);
average_valgrad =
average_value * 2. * sigmaF - average_valgrad * 0.5;
phi_outer.submit_normal_derivative(-average_value, q);
phi_outer.submit_value(-average_valgrad, q);
}
phi_outer.integrate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
local_diagonal_vector[i] = phi_outer.begin_dof_values()[i];
}
for (unsigned int i = 0; i < phi.dofs_per_cell; ++i)
phi_outer.begin_dof_values()[i] = local_diagonal_vector[i];
phi_outer.distribute_local_to_global(dst);
}
}
void
local_diagonal_boundary(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &data,
dealii::LinearAlgebra::distributed::Vector<Number> & dst,
const unsigned int &,
const std::pair<unsigned int, unsigned int> &face_range) const
{
dealii::FEFaceEvaluation<dim,
fe_degree,
n_q_points_1d,
1,
Number,
VectorizedArrayType>
phi(data);
for (unsigned int face = face_range.first; face < face_range.second; face++)
{
phi.reinit(face);
VectorizedArrayType local_diagonal_vector[phi.static_dofs_per_cell];
VectorizedArrayType sigmaF =
std::abs(
(phi.get_normal_vector(0) * phi.inverse_jacobian(0))[dim - 1]) *
Number(std::max(fe_degree, 1) * (fe_degree + 1.0)) * 2.0;
for (unsigned int i = 0; i < phi.dofs_per_cell; ++i)
{
for (unsigned int j = 0; j < phi.dofs_per_cell; ++j)
phi.begin_dof_values()[j] = VectorizedArrayType();
phi.begin_dof_values()[i] = 1.;
phi.evaluate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
for (unsigned int q = 0; q < phi.n_q_points; ++q)
{
if (bc_type == LaplaceOperatorBCType::NBC)
{
VectorizedArrayType jump_value = 0.0;
VectorizedArrayType average_gradient = 0.0;
average_gradient = average_gradient - jump_value * sigmaF;
phi.submit_normal_derivative(-0.5 * jump_value, q);
phi.submit_value(-average_gradient, q);
}
else if (bc_type == LaplaceOperatorBCType::DBC)
{
VectorizedArrayType average_value = phi.get_value(q);
VectorizedArrayType average_valgrad =
-phi.get_normal_derivative(q);
average_valgrad += average_value * sigmaF * 2.0;
phi.submit_normal_derivative(-average_value, q);
phi.submit_value(average_valgrad, q);
}
else
{
AssertThrow(
false, dealii::StandardExceptions::ExcNotImplemented());
}
}
phi.integrate(dealii::EvaluationFlags::values |
dealii::EvaluationFlags::gradients);
local_diagonal_vector[i] = phi.begin_dof_values()[i];
}
for (unsigned int i = 0; i < phi.dofs_per_cell; ++i)
phi.begin_dof_values()[i] = local_diagonal_vector[i];
phi.distribute_local_to_global(dst);
}
}
const dealii::MatrixFree<dim, Number, VectorizedArrayType> *matrix_free;
bool do_zero_mean = false;
LaplaceOperatorBCType bc_type;
};
template <int dim, typename LAPLACEOPERATOR>
class MGTransferMF
: public dealii::MGTransferMatrixFree<dim,
typename LAPLACEOPERATOR::value_type>
{
public:
MGTransferMF(const dealii::MGLevelObject<LAPLACEOPERATOR> &laplace,
const dealii::MGConstrainedDoFs &mg_constrained_dofs)
: dealii::MGTransferMatrixFree<dim, typename LAPLACEOPERATOR::value_type>(
mg_constrained_dofs)
, laplace_operator(laplace){};
/**
* Overload copy_to_mg from MGTransferPrebuilt
*/
template <class InVector, int spacedim>
void
copy_to_mg(const dealii::DoFHandler<dim, spacedim> & mg_dof_handler,
dealii::MGLevelObject<dealii::LinearAlgebra::distributed::Vector<
typename LAPLACEOPERATOR::value_type>> &dst,
const InVector & src) const
{
for (unsigned int level = dst.min_level(); level <= dst.max_level();
++level)
laplace_operator[level].initialize_dof_vector(dst[level]);
dealii::MGTransferMatrixFree<dim, typename LAPLACEOPERATOR::value_type>::
copy_to_mg(mg_dof_handler, dst, src);
}
private:
const dealii::MGLevelObject<LAPLACEOPERATOR> &laplace_operator;
};
template <typename VectorType>
class PoissonSolverBase
{
public:
virtual ~PoissonSolverBase() = default;
virtual unsigned int
solve(VectorType &dst, const VectorType &src) = 0;
};
template <typename MatrixType>
class PoissonSolver : public PoissonSolverBase<typename MatrixType::VectorType>
{
public:
using VectorType = typename MatrixType::VectorType;
using SmootherPreconditionerType = dealii::DiagonalMatrix<VectorType>;
using SmootherType = dealii::
PreconditionChebyshev<MatrixType, VectorType, SmootherPreconditionerType>;
PoissonSolver(const MatrixType &fine_matrix)
: fine_matrix(fine_matrix)
{
typename SmootherType::AdditionalData ad;
ad.preconditioner = std::make_shared<SmootherPreconditionerType>();
fine_matrix.compute_inverse_diagonal(ad.preconditioner->get_vector());
preconditioner.initialize(fine_matrix, ad);
}
unsigned int
solve(VectorType &dst, const VectorType &src) override
{
dealii::ReductionControl solver_control(src.size() * 2,
1e-20,
1e-7); // [TODO]
dealii::SolverCG<VectorType> solver(solver_control);
solver.solve(fine_matrix, dst, src, preconditioner);
return solver_control.last_step();
}
private:
const MatrixType &fine_matrix;
SmootherType preconditioner;
};
template <typename MatrixType>
class PoissonSolverMG
: public PoissonSolverBase<typename MatrixType::VectorType>
{
public:
static const int dim = MatrixType::dim;
using Number = typename MatrixType::value_type;
using VectorizedArrayType = typename MatrixType::VectorizedArrayType;
using MatrixFreeType = dealii::MatrixFree<dim, Number, VectorizedArrayType>;
using VectorType = typename MatrixType::VectorType;
using SmootherPreconditionerType = dealii::DiagonalMatrix<VectorType>;
using SmootherType = dealii::
PreconditionChebyshev<MatrixType, VectorType, SmootherPreconditionerType>;
using MGTransferType = MGTransferMF<dim, MatrixType>;
using PreconditionerType =
dealii::PreconditionMG<dim, VectorType, MGTransferType>;
PoissonSolverMG(
const MatrixType &fine_matrix,
const std::shared_ptr<dealii::MGLevelObject<MatrixFreeType>>
level_matrix_free,
const std::shared_ptr<dealii::MGLevelObject<MatrixType>> mg_matrices_)
: fine_matrix(fine_matrix)
, level_matrix_free(level_matrix_free)
, mg_matrices_(mg_matrices_)
, min_level(mg_matrices_->min_level())
, max_level(mg_matrices_->max_level())
{
const auto &dof = fine_matrix.get_matrix_free().get_dof_handler();
dealii::MGLevelObject<typename SmootherType::AdditionalData> smoother_data(
min_level, max_level);
const auto &mg_matrices = *mg_matrices_;
// initialize levels
for (unsigned int level = min_level; level <= max_level; level++)
{
// ... initialize smoother
smoother_data[level].preconditioner =
std::make_shared<SmootherPreconditionerType>();
mg_matrices[level].compute_inverse_diagonal(
smoother_data[level].preconditioner->get_vector());
smoother_data[level].smoothing_range = 20.; // [TODO]
smoother_data[level].degree = 5; // [TODO]
smoother_data[level].eig_cg_n_iterations = 15; // [TODO]
// ... use coarse smoother as preconditioner on coarsest level
if (level == min_level)
mg_coarse_grid_smoother.initialize(mg_matrices[level],
smoother_data[level]);
}
// ... initialize level mg_matrices
mg_matrix.initialize(mg_matrices);
// ... initialize level smoothers
mg_smoother.initialize(mg_matrices, smoother_data);
// initialize coarse-grid solver
coarse_grid_solver_control = std::make_shared<dealii::ReductionControl>(
1e4, 1e-12, 1e-3, false, false); // [TODO]
coarse_grid_solver = std::make_shared<dealii::SolverCG<VectorType>>(
*coarse_grid_solver_control);
mg_coarse.initialize(*coarse_grid_solver,
mg_matrices[min_level],
mg_coarse_grid_smoother);
// initialize transfer operator
mg_constrained_dofs.initialize(dof);
mg_transfer =
std::make_shared<MGTransferType>(mg_matrices, mg_constrained_dofs);
mg_transfer->build(dof);
// create multigrid object
mg = std::make_shared<dealii::Multigrid<VectorType>>(
mg_matrix, mg_coarse, *mg_transfer, mg_smoother, mg_smoother);
// convert it to a precondtioner
preconditioner =
std::make_shared<PreconditionerType>(dof, *mg, *mg_transfer);
}
unsigned int
solve(VectorType &dst, const VectorType &src) override
{
dealii::ReductionControl solver_control(src.size() * 2,
1e-20,
1e-4); // [TODO]
dealii::SolverCG<VectorType> solver(solver_control);
solver.solve(fine_matrix, dst, src, *preconditioner);
return solver_control.last_step();
}
private:
const MatrixType &fine_matrix;
const std::shared_ptr<dealii::MGLevelObject<MatrixFreeType>>
level_matrix_free;
const std::shared_ptr<dealii::MGLevelObject<MatrixType>> mg_matrices_;
const unsigned int min_level;
const unsigned int max_level;
SmootherType mg_coarse_grid_smoother;
dealii::MGSmootherPrecondition<MatrixType, SmootherType, VectorType>
mg_smoother;
dealii::mg::Matrix<VectorType> mg_matrix;
std::shared_ptr<dealii::ReductionControl> coarse_grid_solver_control;
std::shared_ptr<dealii::SolverCG<VectorType>> coarse_grid_solver;
dealii::MGCoarseGridIterativeSolver<VectorType,
dealii::SolverCG<VectorType>,
MatrixType,
SmootherType>
mg_coarse;
dealii::MGConstrainedDoFs mg_constrained_dofs;
std::shared_ptr<MGTransferType> mg_transfer;
std::shared_ptr<dealii::Multigrid<VectorType>> mg;
std::shared_ptr<PreconditionerType> preconditioner;
};
#endif
| 27,353
|
C++
|
.h
| 643
| 32.069984
| 80
| 0.589613
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,135
|
parameters.h
|
hyperdeal_hyperdeal/examples/vlasov_poisson/include/parameters.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_ADVECTION_PARAMETERS
#define HYPERDEAL_ADVECTION_PARAMETERS
#include <hyper.deal/base/time_integrators_parameters.h>
#include <hyper.deal/base/time_loop_parameters.h>
#include <hyper.deal/operators/advection/advection_operation_parameters.h>
#include <fstream>
#include "poisson.h"
namespace hyperdeal
{
namespace vp
{
template <typename Number>
struct Parameters
{
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("SpatialDiscretization");
prm.add_parameter("MappingX", mapping_degree_x);
prm.add_parameter("MappingV", mapping_degree_v);
prm.add_parameter("DoCollocation", do_collocation);
prm.leave_subsection();
prm.enter_subsection("Triangulation");
prm.add_parameter("Type", triangulation_type);
prm.add_parameter("OutputGrid", output_grid);
prm.leave_subsection();
prm.enter_subsection("TemporalDiscretization");
time_loop_parameters.add_parameters(prm);
rk_parameters.add_parameters(prm);
prm.add_parameter("CFLNumber", cfl_number);
prm.add_parameter("DiagnosticsVTK", dignostics_vtk);
prm.add_parameter("DiagnosticsEnabled", dignostics_enabled);
prm.add_parameter("DiagnosticsTick", dignostics_tick);
prm.add_parameter("DiagnosticsFileName", diag_file);
prm.add_parameter("PerformanceLogAllCalls", performance_log_all_calls);
prm.add_parameter("PerformanceLogAllCallsPrefix",
performance_log_all_calls_prefix);
prm.add_parameter("DiagnosticsWarmUpIterations",
performance_warm_up_iterations);
prm.leave_subsection();
prm.enter_subsection("AdvectionOperation");
advection_operation_parameters.add_parameters(prm);
prm.leave_subsection();
prm.enter_subsection("Matrixfree");
prm.add_parameter("GhostFaces", do_ghost_faces);
prm.add_parameter("DoBuffering", do_buffering);
prm.add_parameter("UseECL", use_ecl);
prm.add_parameter("OverlappingLevel", overlapping_level);
prm.leave_subsection();
prm.enter_subsection("General");
prm.add_parameter("Verbose", print_parameter);
prm.leave_subsection();
}
// discretization
unsigned int mapping_degree_x = 1;
unsigned int mapping_degree_v = 1;
bool do_collocation = false;
// triangulation
std::string triangulation_type = "fullydistributed";
bool output_grid = false;
// time-loop
TimeLoopParamters<Number> time_loop_parameters;
LowStorageRungeKuttaIntegratorParamters rk_parameters;
// ... CFL-condition
Number cfl_number = 0.3;
// ... advection operation
advection::AdvectionOperationParamters advection_operation_parameters;
// ... diagnostic
bool dignostics_enabled = true;
bool dignostics_vtk = false;
Number dignostics_tick = 0.1;
std::string diag_file = "time_history_diagnostics.out";
// ... performance
bool performance_log_all_calls = false;
std::string performance_log_all_calls_prefix = "test";
unsigned int performance_warm_up_iterations = 0;
// matrix-free
bool do_ghost_faces = true;
bool do_buffering = false;
bool use_ecl = true;
unsigned int overlapping_level = 0;
bool print_parameter = true;
};
template <int dim_x, int dim_v, int degree, typename Number>
class Initializer
{
public:
virtual ~Initializer() = default;
void
set_input_parameters(Parameters<Number> & param,
const std::string file_name,
const dealii::ConditionalOStream &pcout)
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
// add general parameters
param.add_parameters(prm);
// add case-specific parameters
this->add_parameters(prm);
prm.parse_input_from_json(file, true);
if (param.print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
virtual void
add_parameters(dealii::ParameterHandler &prm)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)prm;
}
virtual void
create_grid(std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>>
&triangulation_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>>
&triangulation_v)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)triangulation_x;
(void)triangulation_v;
}
virtual void
set_boundary_conditions(
std::shared_ptr<
hyperdeal::advection::BoundaryDescriptor<dim_x + dim_v, Number>>
boundary_descriptor)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)boundary_descriptor;
}
virtual void
set_analytical_solution(
std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
&analytical_solution)
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
(void)analytical_solution;
}
virtual dealii::Tensor<1, dim_x + dim_v>
get_transport_direction()
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
return dealii::Tensor<1, dim_x + dim_v>();
}
virtual LaplaceOperatorBCType
get_poisson_problem_bc_type() const
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
return LaplaceOperatorBCType::NBC;
}
};
} // namespace vp
} // namespace hyperdeal
#include "../cases/hyperrectangle.h"
#include "../cases/torus_hyperball.h"
namespace hyperdeal
{
namespace vp
{
namespace cases
{
struct Parameters
{
Parameters(std::string case_name)
: case_name(case_name)
{}
Parameters(const std::string & file_name,
const dealii::ConditionalOStream &pcout)
: case_name("dummy")
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
add_parameters(prm);
prm.parse_input_from_json(file, true);
if (print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("General");
prm.add_parameter(
"Case",
case_name,
"Name of the case to be run (the section Case contains the parameters of this case).");
prm.add_parameter("Verbose",
print_parameter,
"Print the parameter after parsing.");
prm.leave_subsection();
}
std::string case_name;
bool print_parameter = true;
};
template <int dim_x, int dim_v, int degree, typename Number>
std::shared_ptr<hyperdeal::vp::Initializer<dim_x, dim_v, degree, Number>>
get(const std::string &case_name)
{
// clang-format off
std::shared_ptr<hyperdeal::vp::Initializer<dim_x, dim_v, degree, Number>> initializer;
if(case_name == "hyperrectangle")
initializer.reset(new hyperdeal::vp::hyperrectangle::Initializer<dim_x, dim_v, degree, Number>);
else if(case_name == "torus")
initializer.reset(new hyperdeal::vp::torus_hyperball::Initializer<dim_x, dim_v, degree, Number>);
else
AssertThrow(false, dealii::ExcMessage("This case does not exist!"));
// clang-format on
return initializer;
}
template <int dim_x, int dim_v, int degree, typename Number>
std::shared_ptr<hyperdeal::vp::Initializer<dim_x, dim_v, degree, Number>>
get(const std::string &file_name, const dealii::ConditionalOStream &pcout)
{
Parameters params(file_name, pcout);
return get<dim_x, dim_v, degree, Number>(params.case_name);
}
} // namespace cases
} // namespace vp
} // namespace hyperdeal
#endif
| 9,405
|
C++
|
.h
| 237
| 31.35865
| 107
| 0.615663
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,136
|
vector_tools.h
|
hyperdeal_hyperdeal/include/hyper.deal/numerics/vector_tools.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef NDIM_INTERPOLATION
#define NDIM_INTERPOLATION
#include <hyper.deal/base/config.h>
#include <deal.II/base/function.h>
#include <hyper.deal/matrix_free/fe_evaluation_cell.h>
#include <hyper.deal/matrix_free/matrix_free.h>
namespace hyperdeal
{
namespace VectorTools
{
namespace internal
{
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType,
typename VectorType,
typename ID>
VectorizedArrayType *
interpolate(FEEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType> &phi,
const VectorType & src,
const ID cell)
{
static const int dim = dim_x + dim_v;
static const dealii::internal::EvaluatorVariant tensorproduct =
dealii::internal::EvaluatorVariant::evaluate_evenodd;
// get data and scratch
VectorizedArrayType *data_ptr = phi.get_data_ptr();
// get cell values
phi.reinit(cell);
phi.read_dof_values(src);
dealii::internal::FEEvaluationImplBasisChange<
tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim,
degree + 1,
n_points>::do_forward(1, *phi.get_shape_values(), data_ptr, data_ptr);
return data_ptr;
}
} // namespace internal
/**
* Compute the interpolation of the function @p analytical_solution at the
* support points to the finite element space described by the DoFHandlers
* (@p dof_no_x and @p dof_no_v) and the quadrature rule (@p quad_no_x and
* @p quad_no_v), which should correspond to the FiniteElement object in
* use.
*/
template <int degree,
int n_points,
int dim_x,
int dim_v,
typename Number,
typename VectorType,
typename VectorizedArrayType>
void
interpolate(
const std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
analytical_solution,
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free,
VectorType & dst,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_x,
const unsigned int quad_no_v)
{
const static int dim = dim_x + dim_v;
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VectorizedArrayType>
phi(matrix_free, dof_no_x, dof_no_v, quad_no_x, quad_no_v);
const int dummy = 0;
matrix_free.template cell_loop<VectorType, int>(
[&](const auto &, auto &dst, const auto &, const auto cell) mutable {
VectorizedArrayType *data_ptr = phi.get_data_ptr();
phi.reinit(cell);
// loop over quadrature points
for (unsigned int qv = 0, q = 0; qv < phi.n_q_points_v; qv++)
for (unsigned int qx = 0; qx < phi.n_q_points_x; qx++, q++)
{
// get reference to quadrature points
const auto q_point = phi.get_quadrature_point(qx, qv);
// loop over all lanes
for (unsigned int v = 0; v < phi.n_vectorization_lanes_filled();
v++)
{
// setup point ...
dealii::Point<dim, Number> p;
for (unsigned int d = 0; d < dim; ++d)
p[d] = q_point[d][v];
// ... evaluate function at point
data_ptr[q][v] = analytical_solution->value(p);
}
}
phi.set_dof_values(dst);
},
dst,
dummy);
}
/**
* Compute L2-norm and L2-norm of error for a given vector @p src and
* solution @p analytical_solution. The DoFHandlers to be used can be
* specified by @p dof_no_x and @p dof_no_v and the point in which the
* error is evaluated (coinciding with quadrature points) by @p quad_no_x
* and @p quad_no_v.
*/
template <int degree,
int n_points,
int dim_x,
int dim_v,
typename Number,
typename VectorType,
typename VectorizedArrayType>
std::array<Number, 2>
norm_and_error(
const std::shared_ptr<dealii::Function<dim_x + dim_v, Number>>
analytical_solution,
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free,
const VectorType & src,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_x,
const unsigned int quad_no_v)
{
const static int dim = dim_x + dim_v;
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VectorizedArrayType>
phi(matrix_free, dof_no_x, dof_no_v, quad_no_x, quad_no_v);
std::array<Number, 2> result{{0.0, 0.0}};
int dummy;
matrix_free.template cell_loop<int, VectorType>(
[&](
const auto &, int &, const VectorType &src, const auto cell) mutable {
const VectorizedArrayType *f_ptr =
VectorTools::internal::interpolate(phi, src, cell);
std::array<VectorizedArrayType, 2> temp;
std::fill(temp.begin(), temp.end(), 0.);
for (unsigned int qv = 0, q = 0; qv < phi.n_q_points_v; qv++)
for (unsigned int qx = 0; qx < phi.n_q_points_x; qx++, q++)
{
// determine exact solution at quadrature point
VectorizedArrayType solution_q;
const auto q_point = phi.get_quadrature_point(qx, qv);
for (unsigned int v = 0; v < phi.n_vectorization_lanes_filled();
v++)
{
dealii::Point<dim> p;
for (unsigned int d = 0; d < dim; ++d)
p[d] = q_point[d][v];
solution_q[v] = analytical_solution->value(p);
}
const auto f = f_ptr[q]; // value at quadrature point
const auto e = f - solution_q; // error
const auto JxW = phi.JxW(qx, qv);
temp[0] += f * f * JxW; // L2: norm
temp[1] += e * e * JxW; // L2: error
}
// gather results
for (unsigned int v = 0; v < phi.n_vectorization_lanes_filled(); v++)
for (unsigned int i = 0; i < temp.size(); i++)
result[i] += temp[i][v];
},
dummy,
src);
MPI_Allreduce(MPI_IN_PLACE,
result.data(),
result.size(),
MPI_DOUBLE, // [TODO]: mpi_type_id
MPI_SUM,
matrix_free.get_communicator());
result[0] = std::sqrt(result[0]);
result[1] = std::sqrt(result[1]);
return result;
}
/**
* Perform integration along the v-space using the v-space quadrature rule
* specified by @p quad_no_v and the DoFHandlers specified by @p dof_no_x
* and @dof_no_v.
*/
template <int degree,
int n_points,
int dim_x,
int dim_v,
typename Number,
typename VectorizedArrayType,
typename Vector_Out,
typename Vector_In>
void
velocity_space_integration(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
Vector_Out & dst,
const Vector_In & src,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_v)
{
using MF =
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>;
using VectorizedArrayTypeX = typename MF::VectorizedArrayTypeX;
using VectorizedArrayTypeV = typename MF::VectorizedArrayTypeV;
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VectorizedArrayType>
phi(const_cast<MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &>(
data),
dof_no_x,
dof_no_v,
0 /*dummy*/,
0 /*dummy*/);
dealii::
FEEvaluation<dim_x, degree, n_points, 1, Number, VectorizedArrayTypeX>
phi_x(data.get_matrix_free_x(), dof_no_x, 0 /*dummy*/);
dealii::
FEEvaluation<dim_v, degree, n_points, 1, Number, VectorizedArrayTypeV>
phi_v(data.get_matrix_free_v(), dof_no_v, quad_no_v);
dst = 0.0; // clear destination vector
data.template cell_loop<Vector_Out, Vector_In>(
[&](const auto &,
Vector_Out & dst,
const Vector_In &src,
const auto cell) mutable {
phi.reinit(cell);
phi.read_dof_values(src);
phi_x.reinit(cell.x);
unsigned int index_v = cell.v / VectorizedArrayTypeV::size();
unsigned int lane_v = cell.v % VectorizedArrayTypeV::size();
phi_v.reinit(index_v);
// get data and scratch
const VectorizedArrayType *data_ptr_src = phi.get_data_ptr();
VectorizedArrayTypeX * data_ptr_dst = phi_x.begin_dof_values();
// loop over all x points and integrate over all v points
for (unsigned int qx = 0; qx < phi_x.n_q_points; ++qx)
{
VectorizedArrayType sum_v = VectorizedArrayType();
for (unsigned int qv = 0;
qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v);
++qv)
sum_v +=
data_ptr_src[qx +
dealii::Utilities::pow(n_points, dim_v) * qv] *
phi_v.JxW(qv)[lane_v];
data_ptr_dst[qx] = sum_v;
}
phi_x.distribute_local_to_global(dst);
},
dst,
src);
// collect global contributions
MPI_Allreduce(
MPI_IN_PLACE,
dst.get_values(),
dst.locally_owned_size(),
MPI_DOUBLE,
MPI_SUM,
data.get_matrix_free_v().get_dof_handler().get_communicator());
}
/**
* Perform integration along the x-space using the x-space quadrature rule
* specified by @p quad_no_x and DoFHandlers specified by @p dof_no_x and
* @p dof_no_v.
*/
template <int degree,
int n_points,
int dim_x,
int dim_v,
typename Number,
typename VectorizedArrayType,
typename Vector_Out,
typename Vector_In>
void
coordinate_space_integration(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
Vector_Out & dst,
const Vector_In & src,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_x)
{
using MF =
hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>;
using VectorizedArrayTypeX = typename MF::VectorizedArrayTypeX;
using VectorizedArrayTypeV = typename MF::VectorizedArrayTypeV;
static_assert(VectorizedArrayTypeV::size() == 1);
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VectorizedArrayType>
phi(data, dof_no_x, dof_no_v, 0 /*dummy*/, 0 /*dummy*/);
dealii::
FEEvaluation<dim_x, degree, n_points, 1, Number, VectorizedArrayTypeX>
phi_x(data.get_matrix_free_x(), dof_no_x, quad_no_x);
dealii::
FEEvaluation<dim_v, degree, n_points, 1, Number, VectorizedArrayTypeV>
phi_v(data.get_matrix_free_v(), dof_no_v, 0 /*dummy*/);
// Clear destination vector
dst = 0.0;
constexpr auto N_v_points = dealii::Utilities::pow(n_points, dim_v);
dealii::AlignedVector<VectorizedArrayTypeX> scratch(N_v_points);
data.template cell_loop<Vector_Out, Vector_In>(
[&](const auto &,
Vector_Out & dst,
const Vector_In &src,
const auto cell) mutable {
phi.reinit(cell);
phi.read_dof_values(src);
phi_x.reinit(cell.x);
phi_v.reinit(cell.v);
const VectorizedArrayType *data_ptr_src = phi.get_data_ptr();
VectorizedArrayTypeV * data_ptr_dst = phi_v.begin_dof_values();
const auto N_lanes_x = phi.n_vectorization_lanes_filled();
// reduce in x-direction in a vectorized fashion
for (unsigned int qv = 0; qv < phi_v.n_q_points; ++qv)
{
scratch[qv] = 0.0;
for (unsigned int qx = 0; qx < phi_x.n_q_points; ++qx)
scratch[qv] +=
data_ptr_src[qx + qv * N_v_points] * phi_x.JxW(qx);
}
// perform cross-lane reduction
for (unsigned int qv = 0; qv < phi_v.n_q_points; ++qv)
{
data_ptr_dst[qv] = 0.0;
for (unsigned int lane = 0; lane < N_lanes_x; ++lane)
data_ptr_dst[qv] += scratch[qv][lane];
}
phi_v.distribute_local_to_global(dst);
},
dst,
src);
// Collect global contribution
const auto comm =
data.get_matrix_free_x().get_dof_handler().get_communicator();
MPI_Allreduce(MPI_IN_PLACE,
&*dst.begin(),
dst.locally_owned_size(),
MPI_DOUBLE,
MPI_SUM,
comm);
}
} // namespace VectorTools
} // namespace hyperdeal
#endif
| 15,328
|
C++
|
.h
| 354
| 32.149718
| 87
| 0.512238
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,137
|
grid_generator.h
|
hyperdeal_hyperdeal/include/hyper.deal/grid/grid_generator.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_GRID_GRIDGENERATOR
#define HYPERDEAL_GRID_GRIDGENERATOR
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/manifold.h>
namespace hyperdeal
{
/**
* This namespace provides a collection of functions for generating
* triangulations for some basic tensor-product geometries.
*
* TODO: replace shared_ptr!
*/
namespace GridGenerator
{
/**
* Create two dealii::GridGenerator::subdivided_hyper_rectangle().
*/
template <int dim_x, int dim_v>
void
subdivided_hyper_rectangle(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int & n_refinements_x,
const std::vector<unsigned int> &repetitions_x,
const dealii::Point<dim_x> & left_x,
const dealii::Point<dim_x> & right_x,
const bool do_periodic_x,
const unsigned int & n_refinements_v,
const std::vector<unsigned int> &repetitions_v,
const dealii::Point<dim_v> & left_v,
const dealii::Point<dim_v> & right_v,
const bool do_periodic_v,
const bool with_internal_deformation = false);
/**
* Create two dealii::GridGenerator::hyper_cube().
*/
template <int dim_x, int dim_v>
void
hyper_cube(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int &n_refinements_x,
const double left_x,
const double right_x,
const bool do_periodic_x,
const unsigned int &n_refinements_v,
const double left_v,
const double right_v,
const bool do_periodic_v);
/**
* Same as above but that the parameters of x- and v-space triangulation are
* chosen the same way.
*/
template <int dim_x, int dim_v>
void
hyper_cube(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const bool do_periodic,
const unsigned int &n_refinements,
const double left = 0.0,
const double right = 1.0);
/**
* Same as above but that each coarse cell is subdivided in z-direction.
* In contrast to hyperdeal::GridGenerator::subdivided_hyper_rectangle,
* one can give the coarse cells different orientations
* (0 ≥ orientation_x, orientation_v < 16). This function is
* particular useful, since it is the most simple prototype of an
* unstrucured grid and enables straight-forward debugging.
*
* @note Only implemented for dim_x==dim_v==3.
*/
template <int dim_x, int dim_v>
void
orientated_hyper_cube(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int & n_refinements_x,
const dealii::Point<dim_x> &left_x,
const dealii::Point<dim_x> &right_x,
const bool do_periodic_x,
const unsigned int & orientation_x,
const unsigned int & n_refinements_v,
const dealii::Point<dim_v> &left_v,
const dealii::Point<dim_v> &right_v,
const bool do_periodic_v,
const unsigned int & orientation_v);
/**
* Create two dealii::GridGenerator::hyper_ball().
*
* @note Before refinement, we remove the manifolds from geometric entities
* of the triangluations so that the final bounding faces look exactly
* like in the case of hyperdeal::GridGenerator::hyper_cube().
*/
template <int dim_x, int dim_v>
void
subdivided_hyper_ball(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const unsigned int & n_refinements_x,
const dealii::Point<dim_x> &left_x,
const dealii::Point<dim_x> &right_x,
const bool do_periodic_x,
const unsigned int & n_refinements_v,
const dealii::Point<dim_v> &left_v,
const dealii::Point<dim_v> &right_v,
const bool do_periodic_v);
template <int dim_x, int dim_v>
void
construct_tensor_product(
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> &tria_x,
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> &tria_v,
const std::function<void(dealii::Triangulation<dim_x> &)> fu_x,
const std::function<void(dealii::Triangulation<dim_v> &)> fu_v);
} // namespace GridGenerator
} // namespace hyperdeal
#endif
| 5,719
|
C++
|
.h
| 134
| 37.447761
| 80
| 0.625336
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,138
|
fe_evaluation_base.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/fe_evaluation_base.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_FEEVALUATION_BASE
#define HYPERDEAL_NDIM_FEEVALUATION_BASE
#include <hyper.deal/base/config.h>
#include <hyper.deal/matrix_free/matrix_free.h>
namespace hyperdeal
{
/**
* Base class of FEEvaluation and FEFaceEvaluation.
*/
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class FEEvaluationBase
{
public:
static const int dim = dim_x + dim_v;
using NUMBER_ = Number;
using VEC_NUMBER_ = VectorizedArrayType;
using MF = MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>;
static const unsigned int n_vectors = MF::VectorizedArrayTypeX::size();
static const unsigned int n_vectors_v = MF::VectorizedArrayTypeV::size();
static const int static_dofs =
dealii::Utilities::pow((degree + 1 > n_points) ? (degree + 1) : n_points,
dim);
using VectorizedArrayTypeX = typename MF::VectorizedArrayTypeX;
using VectorizedArrayTypeV = typename MF::VectorizedArrayTypeV;
/**
* Constructor.
*/
FEEvaluationBase(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free);
/**
* Destructor.
*/
virtual ~FEEvaluationBase() = default;
/**
* Set the view to the current cell.
*/
virtual void
reinit(typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID
cell_index);
/**
* Return pointer to the internal buffer.
*/
VectorizedArrayType *
get_data_ptr();
/**
* Return shape values.
*/
const dealii::AlignedVector<Number> *
get_shape_values() const;
/**
* Return gradient of the shape values.
*/
const dealii::AlignedVector<Number> *
get_shape_gradients() const;
protected:
/**
* Local storage for values and derivatives.
*/
dealii::AlignedVector<VectorizedArrayType> data;
/**
* Reference to the phase-space matrix-free instance.
*/
const MF &matrix_free;
/**
* Reference to the x-space matrix-free instance.
*/
const dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>
&matrix_free_x;
/**
* Reference to the v-space matrix-free instance.
*/
const dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV>
&matrix_free_v;
// information about the current cell/face (interpretation depends on
// FEEvaluation/FEFaceEvaluation)
unsigned int macro_cell_x;
unsigned int macro_cell_v;
unsigned int lane_y;
unsigned int macro;
/**
* Pointer to the shape functions.
*/
const dealii::AlignedVector<Number> *shape_values;
/**
* Pointer to the gradient of the shape functions.
*/
const dealii::AlignedVector<Number> *shape_gradients;
};
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>::
FEEvaluationBase(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free)
: matrix_free(matrix_free)
, matrix_free_x(matrix_free.get_matrix_free_x())
, matrix_free_v(matrix_free.get_matrix_free_v())
{
this->data.resize(static_dofs);
}
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
void
FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>::
reinit(typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID
cell_index)
{
this->macro_cell_x = cell_index.x;
this->macro_cell_v = cell_index.v / n_vectors_v;
this->lane_y = cell_index.v % n_vectors_v;
this->macro = cell_index.macro;
Assert(this->lane_y < this->n_vectors_v,
dealii::ExcIndexRange(this->lane_y, 0, n_vectors_v));
}
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
VectorizedArrayType *
FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>::get_data_ptr()
{
return &data[0];
}
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
const dealii::AlignedVector<Number> *
FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>::get_shape_values() const
{
return shape_values;
}
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
const dealii::AlignedVector<Number> *
FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>::get_shape_gradients() const
{
return shape_gradients;
}
} // namespace hyperdeal
#endif
| 6,273
|
C++
|
.h
| 200
| 23.435
| 80
| 0.586344
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,139
|
fe_evaluation_cell_inverse.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/fe_evaluation_cell_inverse.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_FEEVALUATION_CELL_INVERSE
#define HYPERDEAL_NDIM_FEEVALUATION_CELL_INVERSE
#include <hyper.deal/base/config.h>
#include <hyper.deal/matrix_free/fe_evaluation_cell.h>
namespace hyperdeal
{
/**
* The same as FEEvaluation but specialized for inverse mass matrix.
*
* TODO: rename?
*/
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class FEEvaluationInverse : public FEEvaluation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
{
public:
using PARENT =
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VectorizedArrayType>;
/**
* Constructor.
*/
FEEvaluationInverse(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_x,
const unsigned int quad_no_v);
/**
* Return inverse shape function.
*/
const dealii::AlignedVector<Number> *
get_inverse_shape() const;
/**
* Return product of @p data and 1/(|J|xw).
*/
inline DEAL_II_ALWAYS_INLINE //
void
submit_inv(VectorizedArrayType *__restrict data_ptr,
const unsigned int q,
const unsigned int q1,
const unsigned int q2);
private:
/**
* Reference to the inverse shape function.
*/
const dealii::AlignedVector<Number> &inverse_shape;
};
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VNumber>
FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>::
FEEvaluationInverse(
const MatrixFree<dim_x, dim_v, Number, VNumber> &matrix_free,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_x,
const unsigned int quad_no_v)
: PARENT(matrix_free, dof_no_x, dof_no_v, quad_no_x, quad_no_v)
, inverse_shape(
this->phi_x.get_shape_info().data[0].inverse_shape_values_eo)
{}
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VNumber>
const dealii::AlignedVector<Number> *
FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>::
get_inverse_shape() const
{
return &inverse_shape;
}
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VNumber>
inline DEAL_II_ALWAYS_INLINE //
void
FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>::
submit_inv(VNumber *__restrict data_ptr,
const unsigned int q,
const unsigned int q1,
const unsigned int q2)
{
data_ptr[q] /=
this->phi_x.JxW(q1) *
this->phi_v.JxW(q2)[PARENT::n_vectors_v == 1 ? 0 : this->lane_y];
}
} // namespace hyperdeal
#endif
| 4,309
|
C++
|
.h
| 119
| 27.840336
| 80
| 0.532726
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,140
|
shape_info.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/shape_info.h
|
#ifndef HYPERDEAL_NDIM_MATRIXFREE_SHAPE_INFO
#define HYPERDEAL_NDIM_MATRIXFREE_SHAPE_INFO
#include <hyper.deal/base/config.h>
#include <deal.II/base/geometry_info.h>
namespace hyperdeal
{
namespace internal
{
namespace MatrixFreeFunctions
{
/**
* Utility functions for shape functions.
*/
template <typename Number>
struct ShapeInfo
{
/**
* Setup internal data structures for a given @p degree.
*
* TODO: take a dealii::FiniteElement?
*/
template <int dim_x, int dim_v>
void
reinit(const unsigned int degree);
std::size_t
memory_consumption() const
{
return dealii::MemoryConsumption::memory_consumption(
face_to_cell_index_nodal);
}
/**
* Degrees of freedom per cell.
*/
dealii::types::global_dof_index dofs_per_cell;
/**
* Degrees of freedom per face.
*/
dealii::types::global_dof_index dofs_per_face;
/**
* Indices of degrees of freedom of the 2*dim faces.
*
* @note This is similar to
* dealii::internal::MatrixFreeFunctions::ShapeInfo without
* the annoying orientation switch in 3D.
*/
std::vector<std::vector<unsigned int>> face_to_cell_index_nodal;
/**
* TODO
*/
std::vector<std::vector<unsigned int>> face_orientations;
};
namespace
{
template <int dim>
void
fill_face_to_cell_index_nodal(
const unsigned int points,
dealii::Table<2, unsigned int> &face_to_cell_index_nodal)
{
// adopted from dealii::internal::ShapeInfo::reinit()
#ifdef DEBUG
const unsigned int dofs_per_component_on_cell =
dealii::Utilities::pow(points, dim);
#endif
const unsigned int dofs_per_component_on_face =
dealii::Utilities::pow(points, dim - 1);
face_to_cell_index_nodal.reinit(
dealii::GeometryInfo<dim>::faces_per_cell,
dofs_per_component_on_face);
for (const auto f : dealii::GeometryInfo<dim>::face_indices())
{
const unsigned int direction = f / 2;
const unsigned int stride = direction < dim - 1 ? points : 1;
int shift = 1;
for (unsigned int d = 0; d < direction; ++d)
shift *= points;
const unsigned int offset = (f % 2) * (points - 1) * shift;
if (direction == 0 || direction == dim - 1)
for (unsigned int i = 0; i < dofs_per_component_on_face; ++i)
face_to_cell_index_nodal(f, i) = offset + i * stride;
else
// local coordinate system on faces 2 and 3 is zx in
// deal.II, not xz as expected for tensor products -> adjust
// that here
for (unsigned int j = 0; j < points; ++j)
for (unsigned int i = 0; i < points; ++i)
{
const unsigned int ind =
offset + j * dofs_per_component_on_face + i;
AssertIndexRange(ind, dofs_per_component_on_cell);
const unsigned int l = i * points + j;
face_to_cell_index_nodal(f, l) = ind;
}
}
}
} // namespace
template <typename Number>
template <int dim_x, int dim_v>
void
ShapeInfo<Number>::reinit(const unsigned int degree)
{
const unsigned int dim = dim_x + dim_v;
const unsigned int points = degree + 1;
this->dofs_per_cell = dealii::Utilities::pow(points, dim);
this->dofs_per_face = dealii::Utilities::pow(points, dim - 1);
const unsigned int dofs_per_component_on_face =
dealii::Utilities::pow(points, dim - 1);
face_to_cell_index_nodal.resize(
dealii::GeometryInfo<dim>::faces_per_cell);
dealii::Table<2, unsigned int> face_to_cell_index_nodal_x;
dealii::Table<2, unsigned int> face_to_cell_index_nodal_v;
fill_face_to_cell_index_nodal<dim_x>(points,
face_to_cell_index_nodal_x);
fill_face_to_cell_index_nodal<dim_v>(points,
face_to_cell_index_nodal_v);
for (unsigned int surface = 0;
surface < dealii::GeometryInfo<dim>::faces_per_cell;
surface++)
{
face_to_cell_index_nodal[surface].resize(
dofs_per_component_on_face);
if (surface < dim_x * 2)
for (unsigned int i = 0, k = 0;
i < dealii::Utilities::pow(points, dim_v);
i++)
for (unsigned int j = 0;
j < dealii::Utilities::pow(points, dim_x - 1);
j++)
face_to_cell_index_nodal[surface][k++] =
face_to_cell_index_nodal_x(surface, j) +
dealii::Utilities::pow(points, dim_x) * i;
else
for (unsigned int i = 0, k = 0;
i < dealii::Utilities::pow(points, dim_v - 1);
i++)
for (unsigned int j = 0;
j < dealii::Utilities::pow(points, dim_x);
j++)
face_to_cell_index_nodal[surface][k++] =
j + dealii::Utilities::pow(points, dim_x) *
face_to_cell_index_nodal_v(surface - 2 * dim_x, i);
}
// clang-format off
if (dim_x == 3 || dim_v == 3)
{
const unsigned int n = degree + 1;
face_orientations.resize( 16, std::vector<unsigned int>(this->dofs_per_face));
// x-space face
if (dim_x == 3)
for (unsigned int i = 0, c = 0; i < dealii::Utilities::pow(points, dim_v); ++i)
for (unsigned int j = 0; j < n; ++j)
for (unsigned int k = 0; k < n; ++k, ++c)
{
// face_orientation=true, face_flip=false, face_rotation=false
face_orientations[0][c] = c;
// face_orientation=false, face_flip=false, face_rotation=false
face_orientations[1][c] = j + k * n + i * dealii::Utilities::pow(points, 2);
// face_orientation=true, face_flip=true, face_rotation=false
face_orientations[2][c] = (n - 1 - k) + (n - 1 - j) * n + i * dealii::Utilities::pow(points, 2);
// face_orientation=false, face_flip=true, face_rotation=false
face_orientations[3][c] = (n - 1 - j) + (n - 1 - k) * n + i * dealii::Utilities::pow(points, 2);
// face_orientation=true, face_flip=false, face_rotation=true
face_orientations[4][c] = j + (n - 1 - k) * n + i * dealii::Utilities::pow(points, 2);
// face_orientation=false, face_flip=false, face_rotation=true
face_orientations[5][c] = k + (n - 1 - j) * n + i * dealii::Utilities::pow(points, 2);
// face_orientation=true, face_flip=true, face_rotation=true
face_orientations[6][c] = (n - 1 - j) + k * n + i * dealii::Utilities::pow(points, 2);
// face_orientation=false, face_flip=true, face_rotation=true
face_orientations[7][c] = (n - 1 - k) + j * n + i * dealii::Utilities::pow(points, 2);
}
else
for (unsigned int c = 0; c < dealii::Utilities::pow(points, dim - 1); ++c)
for (unsigned int i = 0; i < 8; ++i)
face_orientations[i][c] = c;
// v-space face
if (dim_v == 3)
for (unsigned int j = 0, c = 0; j < n; ++j)
for (unsigned int k = 0; k < n; ++k)
for (unsigned int i = 0; i < dealii::Utilities::pow(points, dim_x); ++i, ++c)
{
// face_orientation=true, face_flip=false, face_rotation=false
face_orientations[8][c] = c;
// face_orientation=false, face_flip=false, face_rotation=false
face_orientations[9][c] = (j + k * n) * dealii::Utilities::pow(points, dim_x) + i;
// face_orientation=true, face_flip=true, face_rotation=false
face_orientations[10][c] = ((n - 1 - k) + (n - 1 - j) * n) * dealii::Utilities::pow(points, dim_x) + i;
// face_orientation=false, face_flip=true, face_rotation=false
face_orientations[11][c] = ((n - 1 - j) + (n - 1 - k) * n) * dealii::Utilities::pow(points, dim_x) + i;
// face_orientation=true, face_flip=false, face_rotation=true
face_orientations[12][c] = (j + (n - 1 - k) * n) * dealii::Utilities::pow(points, dim_x) + i;
// face_orientation=false, face_flip=false, face_rotation=true
face_orientations[13][c] = (k + (n - 1 - j) * n) * dealii::Utilities::pow(points, dim_x) + i;
// face_orientation=true, face_flip=true, face_rotation=true
face_orientations[14][c] = ((n - 1 - j) + k * n) * dealii::Utilities::pow(points, dim_x) + i;
// face_orientation=false, face_flip=true, face_rotation=true
face_orientations[15][c] = ((n - 1 - k) + j * n) * dealii::Utilities::pow(points, dim_x) + i;
}
else
for (unsigned int c = 0; c < dealii::Utilities::pow(points, dim - 1); ++c)
for (unsigned int i = 8; i < 16; ++i)
face_orientations[i][c] = c;
}
else
{
face_to_cell_index_nodal.resize(16, std::vector<unsigned int>(1));
}
// clang-format on
}
} // namespace MatrixFreeFunctions
} // namespace internal
} // namespace hyperdeal
#endif
| 10,426
|
C++
|
.h
| 212
| 35.009434
| 125
| 0.494405
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,141
|
matrix_free.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/matrix_free.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_MATRIXFREE
#define HYPERDEAL_NDIM_MATRIXFREE
#include <hyper.deal/base/config.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <hyper.deal/base/memory_consumption.h>
#include <hyper.deal/base/timers.h>
#include <hyper.deal/matrix_free/dof_info.h>
#include <hyper.deal/matrix_free/face_info.h>
#include <hyper.deal/matrix_free/id.h>
#include <hyper.deal/matrix_free/shape_info.h>
#include <hyper.deal/matrix_free/vector_partitioner.h>
namespace hyperdeal
{
/**
* A matrix-free class for phase-space.
*/
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
class MatrixFree
{
public:
using ID = TensorID;
using VectorizedArrayTypeX = VectorizedArrayType;
using VectorizedArrayTypeV = dealii::VectorizedArray<Number, 1>;
/**
* Type of access on faces.
*
* @note Currently only none and values (ghost-face access) are supported.
*/
enum class DataAccessOnFaces
{
none,
values,
gradients,
unspecified
};
/**
* Struct to configure MatrixFree.
*/
struct AdditionalData
{
/**
* Constructor.
*/
AdditionalData()
: do_ghost_faces(true)
, do_buffering(false)
, use_ecl(true)
, overlapping_level(0 /*no overlapping communication-computation*/)
{}
/**
* Work on ghost faces or ghost cells.
*
* @note Currently only ghost faces are supported.
*/
bool do_ghost_faces;
/**
* Do buffering of values on shared memory domain.
*
* TODO: extend partitioner so that it can work in buffering and
* non-buffering at the same time (maybe connected to ECL).
*/
bool do_buffering;
/**
* Use element centric loops.
*
* TODO: extend partitioner so that it can work for ECL and FCL the same
* time.
*/
bool use_ecl;
/**
* TODO
*/
unsigned int overlapping_level;
};
/**
* Constructor (does nothing - see reinit()).
*/
MatrixFree(const MPI_Comm comm,
const MPI_Comm comm_sm,
const dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>
&matrix_free_x,
const dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV>
&matrix_free_v);
/**
* Actually setup internal data structures (except partitioner).
*/
void
reinit(const AdditionalData &ad = AdditionalData());
/**
* Loop over all cell pairs. No communication performed.
*/
template <typename OutVector, typename InVector>
void
cell_loop(
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
& cell_operation,
OutVector & dst,
const InVector &src) const;
/**
* The same as above, but without std::function.
*/
template <typename CLASS, typename OutVector, typename InVector>
void
cell_loop(void (CLASS::*cell_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
CLASS * owning_class,
OutVector & dst,
const InVector &src) const;
/**
* Loop over all cell pairs in an element-centric fashion (ECL). It
* includes a ghost value update of the source vector.
*/
template <typename OutVector, typename InVector>
void
loop_cell_centric(
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
& cell_operation,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces src_vector_face_access =
DataAccessOnFaces::unspecified,
Timers *timers = nullptr) const;
/**
* The same as above, but without std::function.
*/
template <typename CLASS, typename OutVector, typename InVector>
void
loop_cell_centric(void (CLASS::*cell_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
CLASS * owning_class,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces src_vector_face_access =
DataAccessOnFaces::unspecified,
Timers *timers = nullptr) const;
/**
* Loop over all cell pairs in an face-centric fashion (FCL). It
* includes a ghost value update of the source vector and a compression
* of the destination vector.
*/
template <typename OutVector, typename InVector>
void
loop(const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
&cell_operation,
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
&face_operation,
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
& boundary_operation,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces dst_vector_face_access =
DataAccessOnFaces::unspecified,
const DataAccessOnFaces src_vector_face_access =
DataAccessOnFaces::unspecified,
Timers *timers = nullptr) const;
/**
* Loop over all cell pairs in an face-centric fashion (FCL). It
* includes a ghost value update of the source vector and a compression
* of the destination vector.
*/
template <typename CLASS, typename OutVector, typename InVector>
void
loop(void (CLASS::*cell_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
void (CLASS::*face_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
void (CLASS::*boundary_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
CLASS * owning_class,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces dst_vector_face_access =
DataAccessOnFaces::unspecified,
const DataAccessOnFaces src_vector_face_access =
DataAccessOnFaces::unspecified,
Timers *timers = nullptr) const;
/**
* Return global communicator.
*/
const MPI_Comm &
get_communicator() const;
/**
* Allocate shared-memory vector. Additionally, all values are zeroed out
* so that out-of-memory errors are back-trackable.
*
* @note If this function has been called the first time, also the
* partitioner is set up.
*/
void
initialize_dof_vector(
dealii::LinearAlgebra::distributed::Vector<Number> &vec,
const unsigned int dof_handler_index = 0,
const bool do_ghosts = true,
const bool zero_out_values = true) const;
/**
* Return boundary id of face.
*/
dealii::types::boundary_id
get_boundary_id(const ID macro_face) const;
/**
* Return boundary id of face of cell.
*
* @note In constrast to dealii::MatrixFree::get_faces_by_cells_boundary_id()
* we only return a single number since we require that the cells
* of a macro cell all have the same type of boundary faces.
*/
dealii::types::boundary_id
get_faces_by_cells_boundary_id(const TensorID & macro_cell,
const unsigned int face_number) const;
/**
* Is ECL supported?
*/
bool
is_ecl_supported() const;
/**
* Return if ghost faces or ghost cells are supported.
*/
bool
are_ghost_faces_supported() const;
/**
* Return dealii::MatrixFree for x-space.
*/
const dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX> &
get_matrix_free_x() const;
/**
* Return dealii::MatrixFree for v-space.
*/
const dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV> &
get_matrix_free_v() const;
/**
* Return dof info.
*/
const internal::MatrixFreeFunctions::DoFInfo &
get_dof_info() const;
/**
* Return face info.
*/
const internal::MatrixFreeFunctions::FaceInfo &
get_face_info() const;
/**
* Return shape info.
*/
const internal::MatrixFreeFunctions::ShapeInfo<Number> &
get_shape_info() const;
/**
* Return an estimate for the memory consumption, in bytes, of this object.
*/
MemoryConsumption
memory_consumption() const;
/**
* Return partitioner of the vectors.
*/
const std::shared_ptr<
const dealii::internal::MatrixFreeFunctions::VectorDataExchange::Base> &
get_vector_partitioner() const;
private:
/**
* Global communicator.
*/
const MPI_Comm comm;
/**
* Shared-memory communicator.
*/
const MPI_Comm comm_sm;
/**
* dealii::MatrixFree for x-space.
*/
const dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>
&matrix_free_x;
/**
* dealii::MatrixFree for v-space.
*/
const dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV>
&matrix_free_v;
/**
* Configuration: buffer shared-memory ghost values.
*/
bool do_buffering;
/**
* Configuration: work with ghost faces (advection) or ghost cell (Laplace).
*/
bool do_ghost_faces;
/**
* Perform ECL or FCL.
*/
bool use_ecl;
/**
* Partitioner for ghost_value_update() and compress().
*/
std::shared_ptr<
const dealii::internal::MatrixFreeFunctions::VectorDataExchange::Base>
partitioner;
/**
* Cell info.
*/
internal::MatrixFreeFunctions::DoFInfo dof_info;
/**
* Face info.
*/
internal::MatrixFreeFunctions::FaceInfo face_info;
/**
* Shape info.
*/
internal::MatrixFreeFunctions::ShapeInfo<Number> shape_info;
/**
* Partitions for ECL.
*
* TODO: more details
*/
std::array<std::vector<ID>, 3> partitions;
};
} // namespace hyperdeal
#include <hyper.deal/matrix_free/matrix_free.templates.h>
#endif
| 11,723
|
C++
|
.h
| 344
| 25.828488
| 81
| 0.578037
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,142
|
dof_info.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/dof_info.h
|
#ifndef HYPERDEAL_NDIM_MATRIXFREE_DOF_INFO
#define HYPERDEAL_NDIM_MATRIXFREE_DOF_INFO
#include <hyper.deal/base/config.h>
namespace hyperdeal
{
namespace internal
{
namespace MatrixFreeFunctions
{
/**
* The class that stores the indices of the degrees of freedom for all the
* cells and faces within the shared-memory domain. As a consequence
* the index is a pair consisting of:
* - the rank of the process owning the cell (with the shared memory)
* - the offset from the beginning of the array of that rank.
*/
struct DoFInfo
{
/**
* Caches the number of indices filled when vectorizing.
*
* @note (0) FCL (interior); (1) FCL (exterior);
* (2) cell; (3) ECL (exterior - TODO remove should be the same
* as (2))
*/
std::array<std::vector<unsigned char>, 4> n_vectorization_lanes_filled;
/**
* Stores the indices of the degrees of freedom for each face/cell
* in the shared-memory domain. The first number of the pair
* is the rank within the shared-memory communicator and the
* second number is the offset with the corresponding local array.
*
* @note Faces might be stand alone or might be embedded into
* cells: ghost faces vs. faces of cells owned by a process in
* the same shared memory domain. The number here gives the
* starting point of the corresponding primitive. If a face
* is embedded into a cell additional info is needed from
* FaceInfo for reading/writing.
*
* @note (0) FCL (interior); (1) FCL (exterior);
* (2) cell; (3) ECL (exterior)
*/
std::array<std::vector<std::pair<unsigned int, unsigned int>>, 4>
dof_indices_contiguous_ptr;
std::size_t
memory_consumption() const
{
return dealii::MemoryConsumption::memory_consumption(
n_vectorization_lanes_filled) +
dealii::MemoryConsumption::memory_consumption(
dof_indices_contiguous_ptr);
}
};
} // namespace MatrixFreeFunctions
} // namespace internal
} // namespace hyperdeal
#endif
| 2,305
|
C++
|
.h
| 57
| 32.105263
| 80
| 0.617752
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,143
|
evaluation_kernels.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/evaluation_kernels.h
|
#ifndef HYPERDEAL_NDIM_MATRIXFREE_EVALUTION_KERNELS
#define HYPERDEAL_NDIM_MATRIXFREE_EVALUTION_KERNELS
#include <hyper.deal/base/config.h>
#include <deal.II/matrix_free/evaluation_flags.h>
#include <deal.II/matrix_free/shape_info.h>
namespace hyperdeal
{
namespace internal
{
template <int dim_x,
int dim_v,
int n_rows,
int n_columns,
typename Number,
typename Number2 = Number>
struct EvaluatorTensorProduct
{
static constexpr int dim = dim_x + dim_v;
static constexpr unsigned int n_rows_of_product =
dealii::Utilities::pow(n_rows, dim);
static constexpr unsigned int n_columns_of_product =
dealii::Utilities::pow(n_columns, dim);
EvaluatorTensorProduct()
: shape_values(nullptr)
, shape_gradients(nullptr)
, shape_hessians(nullptr)
{}
EvaluatorTensorProduct(
const dealii::AlignedVector<Number2> &shape_values,
const dealii::AlignedVector<Number2> &shape_gradients,
const dealii::AlignedVector<Number2> &shape_hessians,
const unsigned int dummy1 = 0,
const unsigned int dummy2 = 0)
: shape_values(shape_values.begin())
, shape_gradients(shape_gradients.begin())
, shape_hessians(shape_hessians.begin())
{
// We can enter this function either for the apply() path that has
// n_rows * n_columns entries or for the apply_face() path that only has
// n_rows * 3 entries in the array. Since we cannot decide about the use
// we must allow for both here.
Assert(shape_values.size() == 0 ||
shape_values.size() == n_rows * n_columns ||
shape_values.size() == 3 * n_rows,
dealii::ExcDimensionMismatch(shape_values.size(),
n_rows * n_columns));
Assert(shape_gradients.size() == 0 ||
shape_gradients.size() == n_rows * n_columns,
dealii::ExcDimensionMismatch(shape_gradients.size(),
n_rows * n_columns));
Assert(shape_hessians.size() == 0 ||
shape_hessians.size() == n_rows * n_columns,
dealii::ExcDimensionMismatch(shape_hessians.size(),
n_rows * n_columns));
(void)dummy1;
(void)dummy2;
}
template <int face_direction,
bool contract_onto_face,
bool add,
int max_derivative>
void
apply_face_1D(const Number *DEAL_II_RESTRICT in,
Number *DEAL_II_RESTRICT out,
const unsigned int in_index,
const unsigned int out_index) const
{
constexpr int in_stride =
dealii::Utilities::pow(n_rows, face_direction);
constexpr int out_stride = dealii::Utilities::pow(n_rows, dim - 1);
const Number2 *DEAL_II_RESTRICT shape_values = this->shape_values;
if (contract_onto_face == true)
{
Number res0 = shape_values[0] * in[in_index + 0];
Number res1, res2;
if (max_derivative > 0)
res1 = shape_values[n_rows] * in[in_index + 0];
if (max_derivative > 1)
res2 = shape_values[2 * n_rows] * in[in_index + 0];
for (int ind = 1; ind < n_rows; ++ind)
{
res0 += shape_values[ind] * in[in_index + in_stride * ind];
if (max_derivative > 0)
res1 +=
shape_values[ind + n_rows] * in[in_index + in_stride * ind];
if (max_derivative > 1)
res2 += shape_values[ind + 2 * n_rows] *
in[in_index + in_stride * ind];
}
if (add)
{
out[out_index + 0] += res0;
if (max_derivative > 0)
out[out_index + out_stride] += res1;
if (max_derivative > 1)
out[out_index + 2 * out_stride] += res2;
}
else
{
out[out_index + 0] = res0;
if (max_derivative > 0)
out[out_index + out_stride] = res1;
if (max_derivative > 1)
out[out_index + 2 * out_stride] = res2;
}
}
else
{
for (int col = 0; col < n_rows; ++col)
{
if (add)
out[in_index + col * in_stride] +=
shape_values[col] * in[out_index + 0];
else
out[in_index + col * in_stride] =
shape_values[col] * in[out_index + 0];
if (max_derivative > 0)
out[in_index + col * in_stride] +=
shape_values[col + n_rows] * in[out_index + out_stride];
if (max_derivative > 1)
out[in_index + col * in_stride] +=
shape_values[col + 2 * n_rows] *
in[out_index + 2 * out_stride];
}
}
}
template <int face_direction,
bool contract_onto_face,
bool add,
int max_derivative>
void
apply_face(const Number *DEAL_II_RESTRICT in,
Number *DEAL_II_RESTRICT out) const
{
static_assert(max_derivative >= 0 && max_derivative < 3,
"Only derivative orders 0-2 implemented");
Assert(shape_values != nullptr,
dealii::ExcMessage(
"The given array shape_values must not be the null pointer."));
AssertIndexRange(face_direction, dim);
using namespace dealii::Utilities;
if ((dim_x == 3) && (face_direction == 1)) // swap x face
{
for (int i3 = 0; i3 < pow(n_rows, dim_v); ++i3)
for (int i2 = 0; i2 < n_rows; ++i2)
for (int i1 = 0; i1 < n_rows; ++i1)
{
const unsigned in_index =
i1 + i2 * pow(n_rows, 2) + i3 * pow(n_rows, 3);
// swap i1 and i2
const unsigned out_index =
i2 + i1 * n_rows + i3 * pow(n_rows, 2);
apply_face_1D<face_direction,
contract_onto_face,
add,
max_derivative>(in, out, in_index, out_index);
}
}
else if ((dim_v == 3) && (face_direction == (1 + dim_x))) // swap v face
{
for (int i3 = 0; i3 < n_rows; ++i3)
for (int i2 = 0; i2 < n_rows; ++i2)
for (int i1 = 0; i1 < pow(n_rows, dim_x); ++i1)
{
const unsigned in_index = i1 + i2 * pow(n_rows, dim_x) +
i3 * pow(n_rows, dim_x + 2);
// swap i2 and i3
const unsigned out_index = i1 + i3 * pow(n_rows, dim_x) +
i2 * pow(n_rows, dim_x + 1);
apply_face_1D<face_direction,
contract_onto_face,
add,
max_derivative>(in, out, in_index, out_index);
}
}
else // lex
{
constexpr int n_blocks1 = pow(n_rows, face_direction);
constexpr int n_blocks2 =
pow(n_rows, std::max(dim - face_direction - 1, 0));
for (int i2 = 0; i2 < n_blocks2; ++i2)
for (int i1 = 0; i1 < n_blocks1; ++i1)
{
const unsigned in_index =
i1 + i2 * pow(n_rows, face_direction + 1);
const unsigned out_index =
i1 + i2 * pow(n_rows, face_direction);
apply_face_1D<face_direction,
contract_onto_face,
add,
max_derivative>(in, out, in_index, out_index);
}
}
}
private:
const Number2 *shape_values;
const Number2 *shape_gradients;
const Number2 *shape_hessians;
};
template <int dim_x, int dim_v, int fe_degree, typename Number>
struct FEFaceNormalEvaluationImpl
{
static const int dim = dim_x + dim_v;
/**
* Interpolate the values on the cell quadrature points onto a face.
*/
template <bool do_evaluate, bool add_into_output, typename Number2>
static void
interpolate_quadrature(
const unsigned int n_components,
const dealii::EvaluationFlags::EvaluationFlags flags,
const dealii::internal::MatrixFreeFunctions::ShapeInfo<Number>
& shape_info,
const Number2 * input,
Number2 * output,
const unsigned int face_no)
{
Assert(static_cast<unsigned int>(fe_degree + 1) ==
shape_info.data.front().n_q_points_1d ||
fe_degree == -1,
dealii::ExcInternalError());
interpolate_generic<do_evaluate, add_into_output>(
n_components,
input,
output,
flags,
face_no,
shape_info.data.front().quadrature.size(),
shape_info.data.front().quadrature_data_on_face,
shape_info.n_q_points,
shape_info.n_q_points_face);
}
private:
template <bool do_evaluate,
bool add_into_output,
int face_direction = 0,
typename Number2>
static void
interpolate_generic(
const unsigned int n_components,
const Number2 * input,
Number2 * output,
const dealii::EvaluationFlags::EvaluationFlags flag,
const unsigned int face_no,
const unsigned int n_points_1d,
const std::array<dealii::AlignedVector<Number>, 2> &shape_data,
const unsigned int dofs_per_component_on_cell,
const unsigned int dofs_per_component_on_face)
{
if (face_direction == face_no / 2)
{
EvaluatorTensorProduct<dim_x,
dim_v,
fe_degree + 1,
0,
Number2,
Number>
evalf(shape_data[face_no % 2],
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>(),
n_points_1d,
0);
const unsigned int in_stride = do_evaluate ?
dofs_per_component_on_cell :
dofs_per_component_on_face;
const unsigned int out_stride = do_evaluate ?
dofs_per_component_on_face :
dofs_per_component_on_cell;
for (unsigned int c = 0; c < n_components; ++c)
{
if (flag & dealii::EvaluationFlags::hessians)
evalf.template apply_face<face_direction,
do_evaluate,
add_into_output,
2>(input, output);
else if (flag & dealii::EvaluationFlags::gradients)
evalf.template apply_face<face_direction,
do_evaluate,
add_into_output,
1>(input, output);
else
evalf.template apply_face<face_direction,
do_evaluate,
add_into_output,
0>(input, output);
input += in_stride;
output += out_stride;
}
}
else if (face_direction < dim)
{
interpolate_generic<do_evaluate,
add_into_output,
std::min(face_direction + 1, dim - 1)>(
n_components,
input,
output,
flag,
face_no,
n_points_1d,
shape_data,
dofs_per_component_on_cell,
dofs_per_component_on_face);
}
}
};
} // namespace internal
} // namespace hyperdeal
#endif
| 13,135
|
C++
|
.h
| 309
| 26.71521
| 80
| 0.455938
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,144
|
read_write_operation.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/read_write_operation.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_MATRIX_FREE_READ_WRITE_OPERATION
#define HYPERDEAL_MATRIX_FREE_READ_WRITE_OPERATION
#include <hyper.deal/base/config.h>
#include <hyper.deal/matrix_free/dof_info.h>
#include <hyper.deal/matrix_free/face_info.h>
#include <hyper.deal/matrix_free/shape_info.h>
namespace hyperdeal
{
namespace internal
{
namespace MatrixFreeFunctions
{
/**
* Helper class for transferring data from global to cell-local vectors
* and vice versa.
*/
template <typename Number>
class ReadWriteOperation
{
public:
/**
* Constructor.
*/
ReadWriteOperation(
const hyperdeal::internal::MatrixFreeFunctions::DoFInfo & dof_info,
const hyperdeal::internal::MatrixFreeFunctions::FaceInfo &face_info,
const hyperdeal::internal::MatrixFreeFunctions::ShapeInfo<Number>
&shape_info);
/**
* Transfer data for a (macro-)cell. If dofs are read, write, or
* distributed is determined by @p operation.
*/
template <int dim,
int degree,
typename VectorOperation,
typename VectorizedArrayType>
void
process_cell(
const VectorOperation & operation,
const std::vector<dealii::ArrayView<const Number>> &data_others,
VectorizedArrayType * dst,
const unsigned int cell_batch_number) const;
/**
* Transfer data for a (macro-)face. If dofs are read, write, or
* distributed is determined by @p operation.
*
* The complexity compared to process_cell (additional arguments) rises
* due to the fact:
* - faces are relevant in different context: ECL/FCL interior/exterior
* - that faces might be embedded within cells (e.g., interior faces)
* or might be stored on their own (ghost faces). In the first case,
* the dofs from @p face_no have to be extracted.
* - faces might be not orientated in relation to the neighbor, which
* requires a re-orientation here.
* - In comparison to FCL and ECL interior faces, each faces
* of a ECL exterior macro face might have a different orientation
* and face number.
*
* @note For a detailed discussion, see the documentation of deal.II.
*/
template <int dim_x,
int dim_v,
int degree,
typename VectorOperation,
typename VectorizedArrayType>
void
process_face(
const VectorOperation & operation,
const std::vector<dealii::ArrayView<const Number>> &data_others,
VectorizedArrayType * dst,
const unsigned int * face_no,
const unsigned int * face_orientation,
const unsigned int face_orientation_offset,
const unsigned int cell_batch_number,
const unsigned int cell_side,
const unsigned int face_batch_number,
const unsigned int face_side) const;
private:
const std::array<std::vector<unsigned char>, 4>
&n_vectorization_lanes_filled;
const std::array<std::vector<std::pair<unsigned int, unsigned int>>, 4>
& dof_indices_contiguous_ptr;
const std::array<std::vector<bool>, 4> &face_type;
const std::array<std::vector<bool>, 4> &face_all;
const std::vector<std::vector<unsigned int>> &face_to_cell_index_nodal;
const std::vector<std::vector<unsigned int>> &face_orientations;
};
template <typename Number>
ReadWriteOperation<Number>::ReadWriteOperation(
const hyperdeal::internal::MatrixFreeFunctions::DoFInfo & dof_info,
const hyperdeal::internal::MatrixFreeFunctions::FaceInfo &face_info,
const hyperdeal::internal::MatrixFreeFunctions::ShapeInfo<Number>
&shape_info)
: n_vectorization_lanes_filled(dof_info.n_vectorization_lanes_filled)
, dof_indices_contiguous_ptr(dof_info.dof_indices_contiguous_ptr)
, face_type(face_info.face_type)
, face_all(face_info.face_all)
, face_to_cell_index_nodal(shape_info.face_to_cell_index_nodal)
, face_orientations(shape_info.face_orientations)
{}
template <typename Number>
template <int dim,
int degree,
typename VectorOperation,
typename VectorizedArrayType>
void
ReadWriteOperation<Number>::process_cell(
const VectorOperation & operation,
const std::vector<dealii::ArrayView<const Number>> &global,
VectorizedArrayType * local,
const unsigned int cell_batch_number) const
{
static const unsigned int v_len = VectorizedArrayType::size();
static const unsigned int n_dofs_per_cell =
dealii::Utilities::pow<unsigned int>(degree + 1, dim);
// step 1: get pointer to the first dof of the cell in the sm-domain
std::array<Number *, v_len> global_ptr;
std::fill(global_ptr.begin(), global_ptr.end(), nullptr);
for (unsigned int v = 0;
v < n_vectorization_lanes_filled[2][cell_batch_number] &&
v < v_len;
v++)
{
const auto sm_ptr =
dof_indices_contiguous_ptr[2][v_len * cell_batch_number + v];
global_ptr[v] =
const_cast<Number *>(global[sm_ptr.first].data()) + sm_ptr.second;
}
// step 2: process dofs
if (n_vectorization_lanes_filled[2][cell_batch_number] == v_len)
// case 1: all lanes are filled -> use optimized function
operation.process_dofs_vectorized_transpose(n_dofs_per_cell,
global_ptr,
local);
else
// case 2: some lanes are empty
for (unsigned int i = 0; i < n_dofs_per_cell; ++i)
for (unsigned int v = 0;
v < n_vectorization_lanes_filled[2][cell_batch_number] &&
v < v_len;
v++)
operation.process_dof(global_ptr[v][i], local[i][v]);
}
template <typename Number>
template <int dim_x,
int dim_v,
int degree,
typename VectorOperation,
typename VectorizedArrayType>
void
ReadWriteOperation<Number>::process_face(
const VectorOperation & operation,
const std::vector<dealii::ArrayView<const Number>> &global,
VectorizedArrayType * local,
const unsigned int * face_no,
const unsigned int * face_orientation,
const unsigned int face_orientation_offset,
const unsigned int cell_batch_number,
const unsigned int cell_side,
const unsigned int face_batch_number,
const unsigned int face_side) const
{
static const unsigned int dim = dim_x + dim_v;
static const unsigned int v_len = VectorizedArrayType::size();
static const unsigned int n_dofs_per_face =
dealii::Utilities::pow<unsigned int>(degree + 1, dim - 1);
std::array<Number *, v_len> global_ptr;
std::fill(global_ptr.begin(), global_ptr.end(), nullptr);
for (unsigned int v = 0;
v < n_vectorization_lanes_filled[cell_side][cell_batch_number] &&
v < v_len;
v++)
{
AssertIndexRange(v_len * face_batch_number + v,
dof_indices_contiguous_ptr[face_side].size());
const auto sm_ptr =
dof_indices_contiguous_ptr[face_side]
[v_len * face_batch_number + v];
global_ptr[v] =
const_cast<Number *>(global[sm_ptr.first].data()) + sm_ptr.second;
}
if (n_vectorization_lanes_filled[cell_side][cell_batch_number] ==
v_len &&
(face_side == 2 || face_all[face_side][face_batch_number]))
{
if ((dim_x <= 2 && dim_v <= 2) || face_orientation[0] == 0)
{
if (face_side != 2 &&
face_type[face_side][v_len * face_batch_number])
{
// case 1: read from buffers
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
for (unsigned int v = 0; v < v_len; ++v)
operation.process_dof(global_ptr[v][i], local[i][v]);
}
else
{
// case 2: read from shared memory
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
for (unsigned int v = 0; v < v_len; ++v)
operation.process_dof(
global_ptr[v]
[face_to_cell_index_nodal[face_no[0]][i]],
local[i][v]);
}
}
else
{
const auto &face_orientations_ =
face_orientations[face_orientation[0] +
face_orientation_offset];
if (face_side != 2 &&
face_type[face_side][v_len * face_batch_number])
{
// case 1: read from buffers
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
{
const unsigned int i_ = face_orientations_[i];
for (unsigned int v = 0; v < v_len; ++v)
operation.process_dof(global_ptr[v][i], local[i_][v]);
}
}
else
{
// case 2: read from shared memory
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
{
const unsigned int i_ = face_orientations_[i];
for (unsigned int v = 0; v < v_len; ++v)
operation.process_dof(
global_ptr[v]
[face_to_cell_index_nodal[face_no[0]][i]],
local[i_][v]);
}
}
}
}
else
for (unsigned int v = 0;
v < n_vectorization_lanes_filled[cell_side][cell_batch_number] &&
v < v_len;
v++)
{
if (((dim_x <= 2) && (dim_v <= 2)) ||
face_orientation[face_side == 3 ? v : 0] == 0)
{
if (face_side != 2 &&
face_type[face_side][v_len * face_batch_number + v])
{
// case 1: read from buffers
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
operation.process_dof(global_ptr[v][i], local[i][v]);
}
else
{
// case 2: read from shared memory
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
operation.process_dof(
global_ptr[v][face_to_cell_index_nodal
[face_no[face_side == 3 ? v : 0]][i]],
local[i][v]);
}
}
else
{
const auto &face_orientations_ =
face_orientations[face_orientation[face_side == 3 ? v : 0] +
face_orientation_offset];
if (face_side != 2 &&
face_type[face_side][v_len * face_batch_number + v])
{
// case 1: read from buffers
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
{
const unsigned int i_ = face_orientations_[i];
operation.process_dof(global_ptr[v][i], local[i_][v]);
}
}
else
{
// case 2: read from shared memory
for (unsigned int i = 0; i < n_dofs_per_face; ++i)
{
const unsigned int i_ = face_orientations_[i];
operation.process_dof(
global_ptr[v]
[face_to_cell_index_nodal
[face_no[face_side == 3 ? v : 0]][i]],
local[i_][v]);
}
}
}
}
}
} // namespace MatrixFreeFunctions
} // namespace internal
} // namespace hyperdeal
#endif
| 14,089
|
C++
|
.h
| 312
| 30.852564
| 80
| 0.491599
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,145
|
vector_access_internal.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/vector_access_internal.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_MATRIX_FREE_VECTOR_ACCESS_INTERNAL
#define HYPERDEAL_MATRIX_FREE_VECTOR_ACCESS_INTERNAL
#include <hyper.deal/base/config.h>
namespace hyperdeal
{
namespace internal
{
namespace MatrixFreeFunctions
{
template <typename Number, typename VectorizedArrayType>
struct VectorReader
{
void
process_dof(const Number &global, Number &local) const
{
local = global;
}
void
process_dofs_vectorized_transpose(
const unsigned int dofs_per_cell,
const std::array<Number *, VectorizedArrayType::size()> &global_ptr,
VectorizedArrayType * local) const
{
vectorized_load_and_transpose(dofs_per_cell, global_ptr, local);
}
};
template <typename Number, typename VectorizedArrayType>
struct VectorDistributorLocalToGlobal
{
void
process_dof(Number &global, const Number &local) const
{
global += local;
}
void
process_dofs_vectorized_transpose(
const unsigned int dofs_per_cell,
std::array<Number *, VectorizedArrayType::size()> &global_ptr,
const VectorizedArrayType * local) const
{
vectorized_transpose_and_store(true,
dofs_per_cell,
local,
global_ptr);
}
};
template <typename Number, typename VectorizedArrayType>
struct VectorSetter
{
void
process_dof(Number &global, const Number &local) const
{
global = local;
}
void
process_dofs_vectorized_transpose(
const unsigned int dofs_per_cell,
std::array<Number *, VectorizedArrayType::size()> &global_ptr,
const VectorizedArrayType * local) const
{
vectorized_transpose_and_store(false,
dofs_per_cell,
local,
global_ptr);
}
};
} // namespace MatrixFreeFunctions
} // namespace internal
} // namespace hyperdeal
#endif
| 3,055
|
C++
|
.h
| 84
| 27.130952
| 79
| 0.53906
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,146
|
id.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/id.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_MATRIXFREE_ID
#define HYPERDEAL_NDIM_MATRIXFREE_ID
#include <hyper.deal/base/config.h>
namespace hyperdeal
{
/**
* ID describing cells and faces uniquely in phase space.
*/
struct TensorID
{
/**
* Type of face in phase space.
*/
enum class SpaceType
{
XV,
X,
V
};
/**
* Constructor.
*/
TensorID(const unsigned int x,
const unsigned int v,
const unsigned int macro,
const SpaceType type = SpaceType::XV)
: x(x)
, v(v)
, macro(macro)
, type(type)
{}
/**
* Macro-cell/face ID in x-space.
*/
const unsigned int x;
/**
* Macro-cell/face ID in v-space.
*/
const unsigned int v;
/**
* Macro-cell/face ID in phase-space.
*/
const unsigned int macro;
/**
* Type of face in phase space.
*/
const SpaceType type;
};
} // namespace hyperdeal
#endif
| 1,634
|
C++
|
.h
| 64
| 21.03125
| 72
| 0.571429
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,147
|
tools.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/tools.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef hyperdeal_matrix_free_tools_h
#define hyperdeal_matrix_free_tools_h
#include <deal.II/base/config.h>
#include <deal.II/matrix_free/matrix_free.h>
namespace hyperdeal
{
/**
* A namespace for utility functions in the context of matrix-free operator
* evaluation.
*/
namespace MatrixFreeTools
{
template <int dim, typename VectorizedArrayType>
VectorizedArrayType
evaluate_scalar_function(
const dealii::Point<dim, VectorizedArrayType> &point,
const dealii::Function<dim, typename VectorizedArrayType::value_type>
& function,
const unsigned int n_lanes)
{
VectorizedArrayType result = 0;
for (unsigned int v = 0; v < n_lanes; ++v)
{
dealii::Point<dim> p;
for (unsigned int d = 0; d < dim; ++d)
p[d] = point[d][v];
result[v] = function.value(p);
}
return result;
}
} // namespace MatrixFreeTools
} // namespace hyperdeal
#endif
| 1,645
|
C++
|
.h
| 47
| 30.787234
| 77
| 0.62232
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,148
|
fe_evaluation_face.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/fe_evaluation_face.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_FEEVALUATION_FACE
#define HYPERDEAL_NDIM_FEEVALUATION_FACE
#include <hyper.deal/base/config.h>
#include <deal.II/matrix_free/fe_evaluation.h>
#include <hyper.deal/matrix_free/fe_evaluation_base.h>
#include <hyper.deal/matrix_free/read_write_operation.h>
#include <hyper.deal/matrix_free/vector_access_internal.h>
namespace hyperdeal
{
/**
* The class that provides all functions necessary to evaluate functions at
* quadrature points and face integrations in phase space. It delegates the
* the actual evaluation task to two dealii::FEEvaluation and two
* dealii::FEFaceEvaluation objects and combines the result on-the-fly.
*/
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class FEFaceEvaluation : public FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
{
public:
static const unsigned int DIM = dim_x + dim_v;
static const unsigned int DIM_ = DIM;
static const unsigned int N_Q_POINTS =
dealii::Utilities::pow(n_points, DIM - 1);
static const unsigned int N_Q_POINTS_1_CELL =
dealii::Utilities::pow(n_points, dim_x - 0);
static const unsigned int N_Q_POINTS_2_CELL =
dealii::Utilities::pow(n_points, dim_v - 0);
static const unsigned int N_Q_POINTS_1_FACE =
dealii::Utilities::pow(n_points, dim_x - 1);
static const unsigned int N_Q_POINTS_2_FACE =
dealii::Utilities::pow(n_points, dim_v - 1);
using PARENT = FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>;
static const unsigned int n_vectors = PARENT::n_vectors;
static const unsigned int n_vectors_v = PARENT::n_vectors_v;
// clang-format off
static const unsigned int dim = dim_x + dim_v;
static const unsigned int static_dofs_per_cell = dealii::Utilities::pow(degree + 1, dim);
static const unsigned int static_dofs_per_cell_x = dealii::Utilities::pow(degree + 1, dim_x);
static const unsigned int static_dofs_per_cell_v = dealii::Utilities::pow(degree + 1, dim_v);
static const unsigned int static_dofs_per_face = dealii::Utilities::pow(degree + 1, dim_x + dim_v - 1);
// clang-format on
using SpaceType =
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID::
SpaceType;
/**
* Constructor.
*
* @param matrix_free Data object that contains all data.
* @param is_minus_face This selects which of the two cells of an internal
* face the current evaluator will be based upon.
* The interior face is the main face along which the
* normal vectors are oriented. The exterior face
* coming from the other side provides the same normal
* vector as the interior side, so if the outer normal
* vector to that side is desired, it must be
* multiplied by -1..
* @param dof_no_x If x-space matrix_free of matrix_free was set up
* with multiple DoFHandler objects, this parameter
* selects to which DoFHandler/AffineConstraints pair
* the given evaluator should be attached to.
* @param dof_no_v Same as above but for v-space.
* @param quad_no_x If x-space matrix_free of matrix_free was set up
* with multiple Quadrature objects, this parameter
* selects the appropriate number of the quadrature
* formula.
* @param quad_no_v Same as above but for v-space.
*/
FEFaceEvaluation(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free,
const bool is_minus_face,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_x,
const unsigned int quad_no_v)
: PARENT(matrix_free)
, is_minus_face(is_minus_face)
, phi_x(this->matrix_free_x, dof_no_x, quad_no_x)
, phi_v(this->matrix_free_v, dof_no_v, quad_no_v)
, phi_face_x(this->matrix_free_x, is_minus_face, dof_no_x, quad_no_x)
, phi_face_v(this->matrix_free_v, is_minus_face, dof_no_v, quad_no_v)
{
this->shape_values = &phi_x.get_shape_info().data[0].shape_values_eo;
this->shape_gradients =
&phi_x.get_shape_info().data[0].shape_gradients_collocation_eo;
}
/**
* Set the view the current face in the context of FCL.
*/
void
reinit(typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID
face_index) override
{
PARENT::reinit(face_index);
this->type = face_index.type;
this->is_ecl = false;
if (this->type == SpaceType::X)
{
phi_face_x.reinit(this->macro_cell_x);
phi_v.reinit(this->macro_cell_v);
}
else
{
phi_x.reinit(this->macro_cell_x);
phi_face_v.reinit(this->macro_cell_v);
}
if (this->type == SpaceType::X)
{
this->n_filled_lanes =
this->matrix_free_x.n_active_entries_per_face_batch(
this->macro_cell_x);
}
else
{
this->n_filled_lanes =
this->matrix_free_x.n_active_entries_per_cell_batch(
this->macro_cell_x);
}
// get direction of face
if (type == SpaceType::X)
{
const dealii::internal::MatrixFreeFunctions::FaceToCellTopology<
n_vectors> &faces =
this->matrix_free_x.get_face_info(this->macro_cell_x);
this->face_no = this->is_minus_face ? faces.interior_face_no :
faces.exterior_face_no;
}
else
{
const dealii::internal::MatrixFreeFunctions::FaceToCellTopology<
n_vectors_v> &faces =
this->matrix_free_v.get_face_info(this->macro_cell_v);
this->face_no = this->is_minus_face ? faces.interior_face_no :
faces.exterior_face_no;
this->face_no += dim_x * 2;
}
}
/**
* Set the view the current face in the context of ECL.
*/
void
reinit(typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID
cell_index,
unsigned int face)
{
PARENT::reinit(cell_index);
this->type = (face >= 2 * dim_x) ? SpaceType::V : SpaceType::X;
this->is_ecl = true;
// delegate reinit to deal.II data structures
if (this->type == SpaceType::X)
{
phi_face_x.reinit(this->macro_cell_x, face);
phi_v.reinit(this->macro_cell_v);
}
else
{
phi_x.reinit(this->macro_cell_x);
phi_face_v.reinit(this->macro_cell_v, face - 2 * dim_x);
}
// how many lanes are filled?
{
this->n_filled_lanes =
this->matrix_free_x.n_active_entries_per_cell_batch(
this->macro_cell_x);
}
// get direction of face
{
this->face_no = face;
}
}
/**
* Read data from a global vector into the internal buffer.
*/
void
read_dof_values(
const dealii::LinearAlgebra::distributed::Vector<Number> &src)
{
read_dof_values(src, &this->data[0]);
}
/**
* Read data from a global vector into a given buffer.
*/
void
read_dof_values(
const dealii::LinearAlgebra::distributed::Vector<Number> &src,
VectorizedArrayType * data) const
{
if (this->matrix_free.are_ghost_faces_supported())
{
// for comments see dealii::FEEvaluation::reinit
const unsigned int face_orientation =
is_ecl ? 0 :
((this->is_minus_face ==
(this->matrix_free.get_face_info()
.face_orientations[0][this->macro] >= 8)) ?
(this->matrix_free.get_face_info()
.face_orientations[0][this->macro] %
8) :
0);
internal::MatrixFreeFunctions::ReadWriteOperation<Number>(
this->matrix_free.get_dof_info(),
this->matrix_free.get_face_info(),
this->matrix_free.get_shape_info())
.template process_face<dim_x, dim_v, degree>(
internal::MatrixFreeFunctions::
VectorReader<Number, VectorizedArrayType>(),
src.shared_vector_data(),
data,
(is_ecl == false || this->is_minus_face) ?
&this->face_no :
this->matrix_free.get_face_info().no_faces[3].data() +
(2 * dim * this->macro + this->face_no) * n_vectors,
(is_ecl == false || this->is_minus_face) ?
&face_orientation :
this->matrix_free.get_face_info().face_orientations[3].data() +
(2 * dim * this->macro + this->face_no) * n_vectors,
this->type == SpaceType::X ? 0 : 8,
this->macro,
is_ecl ? 2 : !is_minus_face,
(is_ecl == false || this->is_minus_face) ?
this->macro :
2 * dim * this->macro + this->face_no,
!is_minus_face + (is_ecl ? 2 : 0));
}
else
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
}
/*
* Read the face data from a cell buffer held e.g. by FEEvaluation.
*/
void
read_dof_values_from_buffer(const VectorizedArrayType *src)
{
const auto &index_array = this->matrix_free.get_shape_info()
.face_to_cell_index_nodal[this->face_no];
for (unsigned int i = 0; i < static_dofs_per_face; ++i)
this->data[i] = src[index_array[i]];
}
/**
* Add the face data into a cell buffer held e.g. by FEEvaluation.
*/
void
distribute_to_buffer(VectorizedArrayType *dst) const
{
const auto &index_array = this->matrix_free.get_shape_info()
.face_to_cell_index_nodal[this->face_no];
for (unsigned int i = 0; i < static_dofs_per_face; ++i)
dst[index_array[i]] += this->data[i];
}
/**
* Add the face data into a global vector.
*/
void
distribute_local_to_global(
dealii::LinearAlgebra::distributed::Vector<Number> &dst) const
{
Assert(is_ecl == false, dealii::StandardExceptions::ExcNotImplemented());
if (this->matrix_free.are_ghost_faces_supported())
{
// for comments see dealii::FEEvaluation::reinit
const unsigned int face_orientation =
is_ecl ? 0 :
((this->is_minus_face ==
(this->matrix_free.get_face_info()
.face_orientations[0][this->macro] >= 8)) ?
(this->matrix_free.get_face_info()
.face_orientations[0][this->macro] %
8) :
0);
internal::MatrixFreeFunctions::ReadWriteOperation<Number>(
this->matrix_free.get_dof_info(),
this->matrix_free.get_face_info(),
this->matrix_free.get_shape_info())
.template process_face<dim_x, dim_v, degree>(
internal::MatrixFreeFunctions::
VectorDistributorLocalToGlobal<Number, VectorizedArrayType>(),
dst.shared_vector_data(),
&this->data[0],
&this->face_no,
&face_orientation,
this->type == SpaceType::X ? 0 : 8,
this->macro,
!is_minus_face,
this->macro,
!is_minus_face);
}
else
{
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
}
/**
* Return number of filled lanes.
*/
inline unsigned int
n_vectorization_lanes_filled() const
{
return n_filled_lanes;
}
/**
* Submit value (i.e. multiply by JxW).
*/
template <SpaceType stype>
inline DEAL_II_ALWAYS_INLINE //
void
submit_value(VectorizedArrayType *__restrict data_ptr,
const VectorizedArrayType &value,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
Assert(stype == this->type, dealii::ExcMessage("Types do not match!"));
// note: this if-statement is evaluated at compile time
if (stype == SpaceType::X)
data_ptr[q] = -value * phi_face_x.JxW(qx) *
phi_v.JxW(qv)[n_vectors_v == 1 ? 0 : this->lane_y];
else if (stype == SpaceType::V)
data_ptr[q] = -value * phi_x.JxW(qx) *
phi_face_v.JxW(qv)[n_vectors_v == 1 ? 0 : this->lane_y];
}
/**
* The same as above but tested from both sides -> FCL.
*/
template <SpaceType stype>
inline DEAL_II_ALWAYS_INLINE //
void
submit_value(VectorizedArrayType *__restrict data_ptr_1,
VectorizedArrayType *__restrict data_ptr_2,
const VectorizedArrayType &value,
const unsigned int q,
const unsigned int q1,
const unsigned int q2) const
{
Assert(stype == this->type, dealii::ExcMessage("Types do not match!"));
// note: this if-statement is evaluated at compile time
const auto temp =
(stype == SpaceType::X) ?
(value * phi_face_x.JxW(q1) *
phi_v.JxW(q2)[n_vectors_v == 1 ? 0 : this->lane_y]) :
(value * phi_x.JxW(q1) *
phi_face_v.JxW(q2)[n_vectors_v == 1 ? 0 : this->lane_y]);
data_ptr_1[q] = -temp;
data_ptr_2[q] = +temp;
}
/**
* Get normal for an x-face
*/
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_x, VectorizedArrayType>
get_normal_vector_x(const unsigned int qx) const
{
// TODO: assert that we have (face x cell)
return phi_face_x.get_normal_vector(qx);
}
/**
* Get normal for a y-face
*/
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_v, VectorizedArrayType>
get_normal_vector_v(const unsigned int qv) const
{
// TODO: assert that we have (cell x face)
// here we unfortunately have to copy the content due to different data
// types!
// TODO: implement constructor VectorizedArray<Number,
// N>::VectorizedArray(VectorizedArray<Number, 1>)
dealii::Tensor<1, dim_v, VectorizedArrayType> result;
const auto temp = phi_face_v.get_normal_vector(qv);
for (auto i = 0u; i < dim_v; i++)
result[i] = temp[i][0];
return result;
}
/**
* Return position of quadrature point.
*
* TODO: specialize for x-space and v-space.
*/
inline dealii::Point<DIM, VectorizedArrayType>
get_quadrature_point(const unsigned int q) const
{
dealii::Point<DIM, VectorizedArrayType> temp;
if (type == SpaceType::X)
{
const auto t1 =
this->phi_face_x.quadrature_point(q % N_Q_POINTS_1_FACE);
for (int i = 0; i < dim_x; i++)
temp[i] = t1[i];
const auto t2 = this->phi_v.quadrature_point(q / N_Q_POINTS_1_FACE);
for (int i = 0; i < dim_v; i++)
temp[i + dim_x] = t2[i][n_vectors_v == 1 ? 0 : this->lane_y];
}
else
{
const auto t1 = this->phi_x.quadrature_point(q % N_Q_POINTS_1_CELL);
for (int i = 0; i < dim_x; i++)
temp[i] = t1[i];
const auto t2 =
this->phi_face_v.quadrature_point(q / N_Q_POINTS_1_CELL);
for (int i = 0; i < dim_v; i++)
temp[i + dim_x] = t2[i][n_vectors_v == 1 ? 0 : this->lane_y];
}
return temp;
}
/**
* Return coordinate of quadrature point (@p qx, @p qv).
*/
template <SpaceType stype>
inline dealii::Point<dim, VectorizedArrayType>
get_quadrature_point(const unsigned int qx, const unsigned int qv) const
{
Assert(stype == this->type, dealii::ExcMessage("Types do not match!"));
dealii::Point<dim, VectorizedArrayType> temp;
if (stype == SpaceType::X)
{
const auto t1 = this->phi_face_x.quadrature_point(qx);
for (int i = 0; i < dim_x; i++)
temp[i] = t1[i];
const auto t2 = this->phi_v.quadrature_point(qv);
for (int i = 0; i < dim_v; i++)
temp[i + dim_x] = t2[i][n_vectors_v == 1 ? 0 : this->lane_y];
}
else
{
const auto t1 = this->phi_x.quadrature_point(qx);
for (int i = 0; i < dim_x; i++)
temp[i] = t1[i];
const auto t2 = this->phi_face_v.quadrature_point(qv);
for (int i = 0; i < dim_v; i++)
temp[i + dim_x] = t2[i][n_vectors_v == 1 ? 0 : this->lane_y];
}
return temp;
}
private:
/**
* Interior or exterior face.
*/
const bool is_minus_face;
/**
* Number of filled lanes.
*/
unsigned int n_filled_lanes;
/**
* Has reinit() been called within an ECL or FCL context.
*/
bool is_ecl;
/**
* x- or v-space face.
*/
SpaceType type;
/**
* Face number < dim * 2.
*/
unsigned int face_no;
// clang-format off
dealii::FEEvaluation<dim_x, degree, n_points, 1, Number, typename PARENT::VectorizedArrayTypeX> phi_x;
dealii::FEEvaluation<dim_v, degree, n_points, 1, Number, typename PARENT::VectorizedArrayTypeV> phi_v;
dealii::FEFaceEvaluation<dim_x, degree, n_points, 1, Number, typename PARENT::VectorizedArrayTypeX> phi_face_x;
dealii::FEFaceEvaluation<dim_v, degree, n_points, 1, Number, typename PARENT::VectorizedArrayTypeV> phi_face_v;
// clang-format on
};
} // namespace hyperdeal
#endif
| 19,462
|
C++
|
.h
| 492
| 29.924797
| 115
| 0.54955
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,149
|
fe_evaluation_cell.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/fe_evaluation_cell.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_FEEVALUATION_CELL
#define HYPERDEAL_NDIM_FEEVALUATION_CELL
#include <hyper.deal/base/config.h>
#include <deal.II/matrix_free/fe_evaluation.h>
#include <hyper.deal/matrix_free/fe_evaluation_base.h>
#include <hyper.deal/matrix_free/read_write_operation.h>
#include <hyper.deal/matrix_free/vector_access_internal.h>
namespace hyperdeal
{
/**
* The class that provides all functions necessary to evaluate functions at
* quadrature points and cell integrations in phase space. It delegates the
* the actual evaluation task to two dealii::FEEvaluation objects and combines
* the result on-the-fly.
*/
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
class FEEvaluation : public FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>
{
public:
// clang-format off
static const unsigned int dim = dim_x + dim_v;
static const unsigned int static_dofs_per_cell_x = dealii::Utilities::pow(degree + 1, dim_x);
static const unsigned int static_dofs_per_cell_v = dealii::Utilities::pow(degree + 1, dim_v);
static const unsigned int static_dofs_per_cell = static_dofs_per_cell_x * static_dofs_per_cell_v;
static const unsigned int n_q_points_x = dealii::Utilities::pow(n_points, dim_x);
static const unsigned int n_q_points_v = dealii::Utilities::pow(n_points, dim_v);
static const unsigned int n_q_points = n_q_points_x * n_q_points_v;
// clang-format on
using PARENT = FEEvaluationBase<dim_x,
dim_v,
degree,
n_points,
Number,
VectorizedArrayType>;
static const unsigned int n_vectors = PARENT::n_vectors;
static const unsigned int n_vectors_v = PARENT::n_vectors_v;
/**
* Constructor.
*
* @param matrix_free Data object that contains all data.
* @param dof_no_x If x-space matrix_free of matrix_free was set up with
* multiple DoFHandler objects, this parameter selects to
* which DoFHandler/AffineConstraints pair the given
* evaluator should be attached to.
* @param dof_no_v Same as above but for v-space.
* @param quad_no_x If x-space matrix_free of matrix_free was set up with
* multiple Quadrature objects, this parameter selects
* the appropriate number of the quadrature formula.
* @param quad_no_v Same as above but for v-space.
*/
FEEvaluation(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &matrix_free,
const unsigned int dof_no_x,
const unsigned int dof_no_v,
const unsigned int quad_no_x,
const unsigned int quad_no_v)
: PARENT(matrix_free)
, phi_x(this->matrix_free_x, dof_no_x, quad_no_x)
, phi_v(this->matrix_free_v, dof_no_v, quad_no_v)
{
this->shape_values = &phi_x.get_shape_info().data[0].shape_values_eo;
this->shape_gradients =
&phi_x.get_shape_info().data[0].shape_gradients_collocation_eo;
}
/**
* Set the view to the current cell.
*/
void
reinit(typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID
cell_index) override
{
PARENT::reinit(cell_index);
phi_x.reinit(this->macro_cell_x);
phi_v.reinit(this->macro_cell_v);
}
/**
* Read values from @p src vector and write it into the buffer @p data.
*/
void
read_dof_values(
const dealii::LinearAlgebra::distributed::Vector<Number> &src,
VectorizedArrayType * data) const
{
internal::MatrixFreeFunctions::ReadWriteOperation<Number>(
this->matrix_free.get_dof_info(),
this->matrix_free.get_face_info(),
this->matrix_free.get_shape_info())
.template process_cell<dim, degree>(
internal::MatrixFreeFunctions::VectorReader<Number,
VectorizedArrayType>(),
src.shared_vector_data(),
data,
this->macro);
}
/**
* Read values from @p src vector and write them into the internal buffer.
*/
void
read_dof_values(
const dealii::LinearAlgebra::distributed::Vector<Number> &src)
{
read_dof_values(src, &this->data[0]);
}
/**
* Sum values from the internal buffer into the vector @p dst.
*/
void
set_dof_values(
dealii::LinearAlgebra::distributed::Vector<Number> &dst) const
{
internal::MatrixFreeFunctions::ReadWriteOperation<Number>(
this->matrix_free.get_dof_info(),
this->matrix_free.get_face_info(),
this->matrix_free.get_shape_info())
.template process_cell<dim, degree>(
internal::MatrixFreeFunctions::VectorSetter<Number,
VectorizedArrayType>(),
dst.shared_vector_data(),
&this->data[0],
this->macro);
}
/**
* Return number of filled lanes.
*/
inline unsigned int
n_vectorization_lanes_filled() const
{
return this->matrix_free_x.n_active_entries_per_cell_batch(
this->macro_cell_x);
}
/**
* Return product of @p data and |J|xw.
*
* TODO: remove.
*/
inline VectorizedArrayType
submit_inplace(const VectorizedArrayType data, const unsigned int q) const
{
return submit_inplace(data, q, q % n_q_points_x, q / n_q_points_x);
}
/**
* Return product of @p data and |J|xw.
*
* TODO: remove.
*/
inline VectorizedArrayType
submit_inplace(const VectorizedArrayType data,
unsigned int /*q*/,
unsigned int qx,
unsigned int qv) const
{
return data * phi_x.JxW(qx) *
phi_v.JxW(qv)[n_vectors_v == 1 ? 0 : this->lane_y];
}
inline DEAL_II_ALWAYS_INLINE //
VectorizedArrayType
JxW(unsigned int qx, unsigned int qv) const
{
return phi_x.JxW(qx) * phi_v.JxW(qv)[n_vectors_v == 1 ? 0 : this->lane_y];
}
/**
* Get gradient in x-space
*/
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_x, VectorizedArrayType>
get_gradient_x(const VectorizedArrayType *__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
(void)qv;
dealii::Tensor<1, dim_x, VectorizedArrayType> result;
const auto jacobian = phi_x.inverse_jacobian(qx);
for (auto d = 0u; d < dim_x; d++)
{
result[d] = jacobian[d][0] * grad_in[q];
for (auto e = 1u; e < dim_x; ++e)
result[d] +=
(jacobian[d][e] * grad_in[q + e * n_q_points_x * n_q_points_v]);
}
return result;
}
/**
* Get gradient in v-space
*/
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_v, VectorizedArrayType>
get_gradient_v(const VectorizedArrayType *__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
(void)qx;
dealii::Tensor<1, dim_v, VectorizedArrayType> result;
const auto jacobian = phi_v.inverse_jacobian(qv);
for (auto d = 0u; d < dim_v; d++)
{
result[d] =
jacobian[d][0][n_vectors_v == 1 ? 0 : this->lane_y] * grad_in[q];
for (auto e = 1u; e < dim_v; ++e)
result[d] += (jacobian[d][e][n_vectors_v == 1 ? 0 : this->lane_y] *
grad_in[q + e * n_q_points_x * n_q_points_v]);
}
return result;
}
/**
* Submit value for integration along x-v coordinates
*/
template <bool do_add>
inline DEAL_II_ALWAYS_INLINE //
void
submit_value(VectorizedArrayType *__restrict data_ptr_out,
const VectorizedArrayType values_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
const auto jxw =
phi_x.JxW(qx) * phi_v.JxW(qv)[n_vectors_v == 1 ? 0 : this->lane_y];
if (do_add)
data_ptr_out[q] += values_in * jxw;
else
data_ptr_out[q] = values_in * jxw;
}
/**
* Submit gradient in x-space
*/
inline DEAL_II_ALWAYS_INLINE //
void
submit_gradient_x(VectorizedArrayType *__restrict data_ptr_out,
const VectorizedArrayType *__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
const auto jxw =
phi_x.JxW(qx) * phi_v.JxW(qv)[n_vectors_v == 1 ? 0 : this->lane_y];
const auto jacobian = phi_x.inverse_jacobian(qx);
for (auto d = 0u; d < dim_x; d++)
{
auto new_val = jacobian[0][d] * grad_in[0];
for (auto e = 1u; e < dim_x; ++e)
new_val += (jacobian[e][d] * grad_in[e]);
data_ptr_out[q + d * n_q_points_x * n_q_points_v] = new_val * jxw;
}
}
/**
* Submit gradient in v-space
*/
inline DEAL_II_ALWAYS_INLINE //
void
submit_gradient_v(VectorizedArrayType *__restrict data_ptr_out,
const VectorizedArrayType *__restrict grad_in,
const unsigned int q,
const unsigned int qx,
const unsigned int qv) const
{
const auto jxw =
phi_x.JxW(qx) * phi_v.JxW(qv)[n_vectors_v == 1 ? 0 : this->lane_y];
const auto jacobian = phi_v.inverse_jacobian(qv);
for (auto d = 0u; d < dim_v; d++)
{
auto new_val =
jacobian[0][d][n_vectors_v == 1 ? 0 : this->lane_y] * grad_in[0];
for (auto e = 1u; e < dim_v; ++e)
new_val += (jacobian[e][d][n_vectors_v == 1 ? 0 : this->lane_y] *
grad_in[e]);
data_ptr_out[q + d * n_q_points_x * n_q_points_v] = new_val * jxw;
}
}
/**
* Return location of quadrature point.
*
* TODO: split up in x- and v-space.
*/
inline dealii::Point<dim, VectorizedArrayType>
get_quadrature_point(const unsigned int q) const
{
dealii::Point<dim, VectorizedArrayType> temp;
auto t1 = this->phi_x.quadrature_point(q % n_q_points_x);
for (int i = 0; i < dim_x; i++)
temp[i] = t1[i];
auto t2 = this->phi_v.quadrature_point(q / n_q_points_x);
for (int i = 0; i < dim_v; i++)
temp[i + dim_x] = t2[i][n_vectors_v == 1 ? 0 : this->lane_y];
return temp;
}
inline dealii::Point<dim, VectorizedArrayType>
get_quadrature_point(const unsigned int qx, const unsigned int qv) const
{
dealii::Point<dim, VectorizedArrayType> temp;
auto t1 = this->phi_x.quadrature_point(qx);
for (int i = 0; i < dim_x; i++)
temp[i] = t1[i];
auto t2 = this->phi_v.quadrature_point(qv);
for (int i = 0; i < dim_v; i++)
temp[i + dim_x] = t2[i][n_vectors_v == 1 ? 0 : this->lane_y];
return temp;
}
inline dealii::Point<dim_v, VectorizedArrayType>
get_quadrature_point_v(const unsigned int qv) const
{
dealii::Point<dim_v, VectorizedArrayType> temp;
auto t2 = this->phi_v.quadrature_point(qv);
for (int i = 0; i < dim_v; i++)
temp[i] = t2[i][n_vectors_v == 1 ? 0 : this->lane_y];
return temp;
}
protected:
// clang-format off
dealii::FEEvaluation<dim_x, degree, n_points, 1, Number, typename PARENT::VectorizedArrayTypeX> phi_x;
dealii::FEEvaluation<dim_v, degree, n_points, 1, Number, typename PARENT::VectorizedArrayTypeV> phi_v;
// clang-format on
};
} // namespace hyperdeal
#endif
| 13,316
|
C++
|
.h
| 340
| 30.176471
| 106
| 0.553455
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,150
|
face_info.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/face_info.h
|
#ifndef HYPERDEAL_NDIM_MATRIXFREE_FACE_INFO
#define HYPERDEAL_NDIM_MATRIXFREE_FACE_INFO
#include <hyper.deal/base/config.h>
namespace hyperdeal
{
namespace internal
{
namespace MatrixFreeFunctions
{
/**
* A data structure that holds the connectivity between the faces and the
* cells.
*/
struct FaceInfo
{
/**
* Caches the face number of a macro face.
*
* @note (0) FCL (interior); (1) FCL (exterior);
* (2) empty (ECL - interior); (3) ECL (exterior)
*/
std::array<std::vector<unsigned int>, 4> no_faces;
/**
* Caches the face orientations of a macro faces.
*
* The values is copied directly from the faces of the low-dimensional
* faces. At this place, no distinguish is done if a face is x- or
* v-face since this can be done directly in
* hyperdeal::FEFaceEvaluation.
*
* @note (0) FCL (interior); (1) empty (FCL - exterior);
* (2) empty (ECL - interior); (3) ECL (exterior)
*/
std::array<std::vector<unsigned int>, 4> face_orientations;
/**
* Stores for each face the type.Type
* means in this context if their dofs are stored in faces or
* are embedded in a cell. Example: ghost faces vs. faces of
* cells owned by a process in the same shared memory domain.
*
* @note (0) FCL (interior); (1) FCL (exterior);
* (2) empty (ECL - interior); (3) ECL (exterior)
*/
std::array<std::vector<bool>, 4> face_type;
/**
* Caches if all faces have the same type, face number, and face
* orientation when vectorizing.
*
* @note (0) FCL (interior); (1) FCL (exterior);
* (2) empty (ECL - interior); (3) ECL (exterior)
*/
std::array<std::vector<bool>, 4> face_all;
std::size_t
memory_consumption() const
{
return dealii::MemoryConsumption::memory_consumption(no_faces) +
dealii::MemoryConsumption::memory_consumption(
face_orientations) +
dealii::MemoryConsumption::memory_consumption(face_type) +
dealii::MemoryConsumption::memory_consumption(face_all);
}
};
} // namespace MatrixFreeFunctions
} // namespace internal
} // namespace hyperdeal
#endif
| 2,475
|
C++
|
.h
| 66
| 28.80303
| 79
| 0.577676
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,151
|
matrix_free.templates.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/matrix_free.templates.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/fe/fe_dgq.h>
#include <hyper.deal/base/mpi_tags.h>
#include <hyper.deal/matrix_free/matrix_free.h>
namespace hyperdeal
{
namespace internal
{
struct CellInfo
{
/**
* Constructor.
*/
CellInfo()
: gid(0)
, rank(0)
{}
/**
* Constructor.
*/
CellInfo(dealii::types::global_dof_index gid, unsigned int rank)
: gid(gid)
, rank(rank)
{}
/**
* Global id of cell.
*/
dealii::types::global_dof_index gid;
/**
* Rank of cell.
*/
unsigned int rank;
};
struct FaceInfo
{
FaceInfo()
: gid(0)
, rank(0)
, no(0)
{}
FaceInfo(unsigned int gid, unsigned int rank, unsigned char no)
: gid(gid)
, rank(rank)
, no(no)
{}
unsigned int gid;
unsigned int rank;
unsigned char no;
};
struct GlobalCellInfo
{
// general (cached) info
unsigned int max_batch_size;
unsigned int n_cell_batches;
// cell information
std::vector<unsigned char> cells_fill; // for each macro cell
std::vector<CellInfo> cells; // for each lane
std::vector<unsigned int> cells_lid; //
// face information in context of FCL
std::vector<unsigned char> faces_fill; // for each macro face
std::vector<unsigned int> interior_face_no; //
std::vector<unsigned int> exterior_face_no; //
std::vector<unsigned int> face_orientation; //
std::vector<CellInfo> cells_interior; // for each lane
std::vector<CellInfo> cells_exterior; //
// face information in context of ECL
std::vector<CellInfo> cells_exterior_ecl; // for each lane
std::vector<unsigned int> exterior_face_no_ecl; //
std::vector<unsigned int> face_orientation_ecl; //
unsigned int
compute_n_cell_batches() const
{
return n_cell_batches;
}
unsigned int
compute_n_cell_and_ghost_batches() const
{
return this->cells_fill.size();
}
unsigned int
compute_n_cells() const
{
if (max_batch_size == 1)
return n_cell_batches;
unsigned int n_cells = 0;
for (unsigned int i = 0; i < this->n_cell_batches; i++)
for (unsigned int v = 0; v < this->cells_fill[i]; v++)
n_cells++;
return n_cells;
}
unsigned int
compute_n_cells_and_ghost() const
{
if (max_batch_size == 1)
return cells.size();
unsigned int n_cells = 0;
for (unsigned int i = 0; i < this->cells_fill.size(); i++)
for (unsigned int v = 0; v < this->cells_fill[i]; v++)
n_cells++;
return n_cells;
}
};
/**
* Helper class to create a list of ghost faces.
*/
struct GlobalCellInfoProcessor
{
/**
* Constructor.
*/
GlobalCellInfoProcessor(const GlobalCellInfo &info)
: info(info)
{}
/**
* Compute ghost faces.
*/
std::vector<FaceInfo>
get_ghost_faces(const int dim, const bool ecl = false) const
{
return get_ghost_faces(get_local_range(), dim, ecl);
}
private:
std::pair<unsigned int, unsigned int>
get_local_range() const
{
// 1) determine local range
unsigned int i_min = std::numeric_limits<unsigned int>::max();
unsigned int i_max = std::numeric_limits<unsigned int>::min();
for (unsigned int i = 0; i < info.n_cell_batches; i++)
for (unsigned int v = 0; v < info.cells_fill[i]; v++)
{
unsigned int gid = info.cells[i * info.max_batch_size + v].gid;
i_min = std::min(i_min, gid);
i_max = std::max(i_max, gid);
}
return {i_min, i_max};
}
std::vector<FaceInfo>
get_ghost_faces(const std::pair<unsigned int, unsigned int> local_range,
const int dim,
const bool ecl = false) const
{
const auto i_min = local_range.first;
const auto i_max = local_range.second;
std::vector<FaceInfo> ghosts_faces;
if (ecl)
{
for (unsigned int i = 0; i < info.n_cell_batches; i++)
for (int d = 0; d < 2 * dim; d++)
for (unsigned int v = 0; v < info.max_batch_size; v++)
{
Assert(i * info.max_batch_size * 2 * dim +
d * info.max_batch_size + v <
info.cells_exterior_ecl.size(),
dealii::ExcMessage("Out of range!"));
const unsigned int index =
i * info.max_batch_size * 2 * dim +
d * info.max_batch_size + v;
const auto cell_info = info.cells_exterior_ecl[index];
const unsigned int gid = cell_info.gid;
if (gid == dealii::numbers::invalid_unsigned_int)
continue;
if (gid < i_min || i_max < gid)
ghosts_faces.emplace_back(
gid, cell_info.rank, info.exterior_face_no_ecl[index]);
}
}
else
{
for (unsigned int i = 0; i < info.interior_face_no.size(); i++)
for (unsigned int v = 0; v < info.faces_fill[i]; v++)
{
const auto cell_info =
info.cells_interior[i * info.max_batch_size + v];
const auto gid = cell_info.gid;
Assert(gid != dealii::numbers::invalid_dof_index,
dealii::StandardExceptions::ExcInternalError());
if (gid < i_min || i_max < gid)
ghosts_faces.emplace_back(gid,
cell_info.rank,
info.interior_face_no[i]);
}
for (unsigned int i = 0; i < info.exterior_face_no.size(); i++)
for (unsigned int v = 0; v < info.faces_fill[i]; v++)
{
const auto cell_info =
info.cells_exterior[i * info.max_batch_size + v];
const auto gid = cell_info.gid;
Assert(gid != dealii::numbers::invalid_dof_index,
dealii::StandardExceptions::ExcInternalError());
if (gid < i_min || i_max < gid)
ghosts_faces.emplace_back(gid,
cell_info.rank,
info.exterior_face_no[i]);
}
}
return ghosts_faces;
}
const GlobalCellInfo &info;
};
template <int dim, typename Number, typename VectorizedArrayType>
void
collect_global_cell_info(
const dealii::MatrixFree<dim, Number, VectorizedArrayType> &data,
GlobalCellInfo & info)
{
// 1) create function to be able translate local cell ids to global ones
// and get the rank of the owning process
//
// TODO: replace by global_active_cell_index once
// https://github.com/dealii/dealii/pull/10490 is merged
dealii::FE_DGQ<dim> fe(0);
// ... distribute degrees of freedoms
dealii::DoFHandler<dim> dof_handler(
data.get_dof_handler().get_triangulation());
dof_handler.distribute_dofs(fe);
const auto cell_to_gid = [&](const auto &cell) {
typename dealii::DoFHandler<dim>::level_cell_accessor dof_cell(
&data.get_dof_handler().get_triangulation(),
cell->level(),
cell->index(),
&dof_handler);
std::vector<dealii::types::global_dof_index> indices(1);
dof_cell.get_dof_indices(indices);
return CellInfo(indices[0], dof_cell.subdomain_id());
};
// 2) allocate memory
const unsigned int v_len = VectorizedArrayType::size();
// ... general info
info.max_batch_size = v_len;
info.n_cell_batches = data.n_cell_batches();
// ... cells
info.cells.resize(v_len *
(data.n_cell_batches() + data.n_ghost_cell_batches()));
info.cells_exterior_ecl.resize(dealii::GeometryInfo<dim>::faces_per_cell *
v_len * data.n_cell_batches(),
{dealii::numbers::invalid_unsigned_int,
dealii::numbers::invalid_unsigned_int});
info.cells_lid.resize(
v_len * (data.n_cell_batches() + data.n_ghost_cell_batches()));
info.cells_interior.resize(
v_len * (data.n_inner_face_batches() + data.n_boundary_face_batches()));
info.cells_exterior.resize(v_len * data.n_inner_face_batches());
// ... fill
info.cells_fill.resize(data.n_cell_batches() +
data.n_ghost_cell_batches());
info.faces_fill.resize(data.n_inner_face_batches() +
data.n_boundary_face_batches());
// ... face_no
info.interior_face_no.resize(data.n_inner_face_batches() +
data.n_boundary_face_batches());
info.exterior_face_no.resize(data.n_inner_face_batches());
info.exterior_face_no_ecl.resize(
dealii::GeometryInfo<dim>::faces_per_cell * v_len *
data.n_cell_batches());
// ... face_orientation
info.face_orientation.resize(data.n_inner_face_batches() +
data.n_boundary_face_batches());
info.face_orientation_ecl.resize(
dealii::GeometryInfo<dim>::faces_per_cell * v_len *
data.n_cell_batches());
// 3) collect info by looping over local cells and ...
for (unsigned int cell = 0;
cell < data.n_cell_batches() + data.n_ghost_cell_batches();
cell++)
{
info.cells_fill[cell] = data.n_active_entries_per_cell_batch(cell);
// loop over all cells in macro cells and fill data structures
unsigned int v = 0;
for (; v < data.n_active_entries_per_cell_batch(cell); v++)
{
const auto c_it = data.get_cell_iterator(cell, v);
// global id
info.cells[cell * v_len + v] = cell_to_gid(c_it);
// local id -> for data access
//
// warning: we assume that ghost cells have the same number
// of unknowns as interior cells
info.cells_lid[cell * v_len + v] =
data.get_dof_info(/*TODO*/)
.dof_indices_contiguous[2][cell * v_len + v] /
data.get_dofs_per_cell();
// for interior cells ...
if (cell < data.n_cell_batches())
// ... loop over all its faces
for (unsigned int face_no = 0;
face_no < dealii::GeometryInfo<dim>::faces_per_cell;
face_no++)
{
const unsigned int n_index =
cell * v_len * dealii::GeometryInfo<dim>::faces_per_cell +
v_len * face_no + v;
// on boundary faces: nothing to do so fill with invalid
// values
if (!c_it->has_periodic_neighbor(face_no) &&
c_it->at_boundary(face_no))
{
info.cells_exterior_ecl[n_index].gid = -1;
info.cells_exterior_ecl[n_index].rank = -1;
info.exterior_face_no_ecl[n_index] = -1;
info.face_orientation_ecl[n_index] = -1;
continue;
}
// .. and collect the neighbors for ECL with the following
// information: 1) global id
info.cells_exterior_ecl[n_index] =
cell_to_gid(c_it->neighbor_or_periodic_neighbor(face_no));
// 2) face number and face orientation
//
// note: this is a modified copy and merged version of the
// methods dealii::FEFaceEvaluation::compute_face_no_data()
// and dealii::FEFaceEvaluation::compute_face_orientations()
// so that we don't have to use here FEEFaceEvaluation
{
const unsigned int cell_this =
cell * VectorizedArrayType::size() + v;
const unsigned int face_index =
data.get_cell_and_face_to_plain_faces()(cell,
face_no,
v);
Assert(face_index !=
dealii::numbers::invalid_unsigned_int,
dealii::StandardExceptions::ExcNotInitialized());
const auto &faces = data.get_face_info(
face_index / VectorizedArrayType::size());
const auto cell_m =
faces.cells_interior[face_index %
VectorizedArrayType::size()];
const bool is_interior_face =
(cell_m != cell_this) ||
((cell_m == cell_this) &&
(face_no !=
data
.get_face_info(face_index /
VectorizedArrayType::size())
.interior_face_no));
info.exterior_face_no_ecl[n_index] =
is_interior_face ? faces.interior_face_no :
faces.exterior_face_no;
if (dim == 3)
{
const bool fo_interior_face =
faces.face_orientation >= 8;
const unsigned int face_orientation =
faces.face_orientation % 8;
static const std::array<unsigned int, 8> table{
{0, 1, 2, 3, 6, 5, 4, 7}};
info.face_orientation_ecl[n_index] =
(is_interior_face != fo_interior_face) ?
table[face_orientation] :
face_orientation;
}
else
info.face_orientation_ecl[n_index] = -1;
}
}
}
}
// ... interior faces (filled lanes, face_no_m/_p, gid_m/_p)
for (unsigned int face = 0; face < data.n_inner_face_batches(); ++face)
{
// number of filled lanes
info.faces_fill[face] = data.n_active_entries_per_face_batch(face);
// face number
info.interior_face_no[face] =
data.get_face_info(face).interior_face_no;
info.exterior_face_no[face] =
data.get_face_info(face).exterior_face_no;
// face orientation
info.face_orientation[face] =
data.get_face_info(face).face_orientation;
// process cells in batch
for (unsigned int v = 0;
v < data.n_active_entries_per_face_batch(face);
++v)
{
const auto cell_m = data.get_face_info(face).cells_interior[v];
info.cells_interior[face * v_len + v] = cell_to_gid(
data.get_cell_iterator(cell_m / v_len, cell_m % v_len));
const auto cell_p = data.get_face_info(face).cells_exterior[v];
info.cells_exterior[face * v_len + v] = cell_to_gid(
data.get_cell_iterator(cell_p / v_len, cell_p % v_len));
}
}
// ... boundary faces (filled lanes, face_no_m, gid_m)
for (unsigned int face = data.n_inner_face_batches();
face < data.n_inner_face_batches() + data.n_boundary_face_batches();
++face)
{
info.faces_fill[face] = data.n_active_entries_per_face_batch(face);
info.interior_face_no[face] =
data.get_face_info(face).interior_face_no;
for (unsigned int v = 0;
v < data.n_active_entries_per_face_batch(face);
++v)
{
const auto cell_m = data.get_face_info(face).cells_interior[v];
info.cells_interior[face * v_len + v] = cell_to_gid(
data.get_cell_iterator(cell_m / v_len, cell_m % v_len));
}
}
}
/**
* A class to translate the tensor product of global cell ids to a
* single global id. Processes are enumerated lexicographically and cells
* are enumerated lexicographically and continuously within a process.
*/
class GlobaleCellIDTranslator
{
public:
/**
* Constructor.
*/
GlobaleCellIDTranslator(const GlobalCellInfo &info_x,
const GlobalCellInfo &info_v,
const MPI_Comm comm_x,
const MPI_Comm comm_v)
{
// determine the first cell of each rank in x-space
{
// allocate memory
n1.resize(dealii::Utilities::MPI::n_mpi_processes(comm_x) + 1);
// number of locally owned cells
const unsigned int n_local = info_x.compute_n_cells();
// gather the number of cells of all processes
MPI_Allgather(
&n_local, 1, MPI_UNSIGNED, n1.data() + 1, 1, MPI_UNSIGNED, comm_x);
// perform prefix sum
for (unsigned int i = 0; i < n1.size() - 1; i++)
n1[i + 1] += n1[i];
}
// the same for v-space
{
n2.resize(dealii::Utilities::MPI::n_mpi_processes(comm_v) + 1);
unsigned int local = info_v.compute_n_cells();
MPI_Allgather(
&local, 1, MPI_UNSIGNED, n2.data() + 1, 1, MPI_UNSIGNED, comm_v);
for (unsigned int i = 0; i < n2.size() - 1; i++)
n2[i + 1] += n2[i];
}
}
/**
* Translate the tensor product of global cell IDs to a single global ID.
*/
CellInfo
translate(const CellInfo &id1, const CellInfo &id2) const
{
// extract needed information
const unsigned int gid1 = id1.gid;
const unsigned int rank1 = id1.rank;
const unsigned int gid2 = id2.gid;
const unsigned int rank2 = id2.rank;
Assert(rank1 != static_cast<unsigned int>(-1),
dealii::StandardExceptions::ExcNotImplemented());
Assert(rank2 != static_cast<unsigned int>(-1),
dealii::StandardExceptions::ExcNotImplemented());
AssertIndexRange(rank1 + 1, n1.size());
AssertIndexRange(rank2 + 1, n2.size());
// 1) determine local IDs
const unsigned int lid1 = gid1 - n1[rank1];
const unsigned int lid2 = gid2 - n2[rank2];
// 2) determine local ID by taking taking tensor product
const unsigned int lid = lid1 + lid2 * (n1[rank1 + 1] - n1[rank1]);
// 3) add offset to local ID to get global ID
return {lid + n1.back() * n2[rank2] +
n1[rank1] * (n2[rank2 + 1] - n2[rank2]),
rank1 + ((unsigned int)n1.size() - 1) * rank2};
}
private:
std::vector<unsigned int> n1;
std::vector<unsigned int> n2;
};
inline void
combine_global_cell_info(const MPI_Comm comm_x,
const MPI_Comm comm_v,
const GlobalCellInfo &info_x,
const GlobalCellInfo &info_v,
GlobalCellInfo & info,
int dim_x,
int dim_v)
{
// batch size
info.max_batch_size = info_x.max_batch_size;
// number of cell batches
info.n_cell_batches =
info_x.compute_n_cell_batches() * info_v.compute_n_cells();
// helper function to create the global cell id of a tensor-product cell
GlobaleCellIDTranslator translator(info_x, info_v, comm_x, comm_v);
// helper function to create the tensor product of cells
const auto process = [&](const unsigned int i_x,
const unsigned int i_v,
const unsigned int v_v) {
unsigned int v_x = 0;
for (; v_x < info_x.cells_fill[i_x]; v_x++)
{
const auto cell_x = info_x.cells[i_x * info_x.max_batch_size + v_x];
const auto cell_y = info_v.cells[i_v * info_v.max_batch_size + v_v];
info.cells.emplace_back(translator.translate(cell_x, cell_y));
}
for (; v_x < info_x.max_batch_size; v_x++)
info.cells.emplace_back(-1, -1);
info.cells_fill.push_back(info_x.cells_fill[i_x]);
};
const unsigned int n_cell_batches_x = info_x.compute_n_cell_batches();
const unsigned int n_cell_batches_v = info_v.compute_n_cell_batches();
const unsigned int n_cell_and_ghost_batches_x =
info_x.compute_n_cell_and_ghost_batches();
const unsigned int n_cell_and_ghost_batches_v =
info_v.compute_n_cell_and_ghost_batches();
// cells: local x local
for (unsigned int i_v = 0; i_v < n_cell_batches_v; i_v++)
for (unsigned int v_v = 0; v_v < info_v.cells_fill[i_v]; v_v++)
for (unsigned int i_x = 0; i_x < n_cell_batches_x; i_x++)
process(i_x, i_v, v_v);
// ecl neighbors
for (unsigned int i_v = 0; i_v < n_cell_batches_v; i_v++)
for (unsigned int v_v = 0; v_v < info_v.cells_fill[i_v]; v_v++)
for (unsigned int i_x = 0; i_x < n_cell_batches_x; i_x++)
{
for (int d = 0; d < 2 * dim_x; d++)
{
unsigned int v_x = 0;
for (; v_x < info_x.cells_fill[i_x]; v_x++)
{
const unsigned int index =
i_x * info_x.max_batch_size * 2 * dim_x +
d * info_x.max_batch_size + v_x;
const auto cell_x = info_x.cells_exterior_ecl[index];
const auto cell_y =
info_v.cells[i_v * info_v.max_batch_size + v_v];
// on boundary faces: nothing to do so fill with invalid
// values
if (cell_x.gid == static_cast<decltype(cell_x.gid)>(-1) ||
cell_y.gid == static_cast<decltype(cell_y.gid)>(-1))
{
info.cells_exterior_ecl.emplace_back(-1, -1);
info.exterior_face_no_ecl.emplace_back(-1);
info.face_orientation_ecl.emplace_back(-1);
continue;
}
info.cells_exterior_ecl.emplace_back(
translator.translate(cell_x, cell_y));
info.exterior_face_no_ecl.emplace_back(
info_x.exterior_face_no_ecl[index]);
info.face_orientation_ecl.emplace_back(
info_x.face_orientation_ecl[index]); // TODO?
}
for (; v_x < info_x.max_batch_size; v_x++)
{
info.cells_exterior_ecl.emplace_back(-1, -1);
info.exterior_face_no_ecl.emplace_back(-1);
info.face_orientation_ecl.emplace_back(-1);
}
}
for (int d = 0; d < 2 * dim_v; d++)
{
unsigned int v_x = 0;
for (; v_x < info_x.cells_fill[i_x]; v_x++)
{
const unsigned index =
i_v * info_v.max_batch_size * 2 * dim_v +
d * info_v.max_batch_size + v_v;
const auto cell_x =
info_x.cells[i_x * info_x.max_batch_size + v_x];
const auto cell_y = info_v.cells_exterior_ecl[index];
// on boundary faces: nothing to do so fill with invalid
// values
if (cell_x.gid == static_cast<decltype(cell_x.gid)>(-1) ||
cell_y.gid == static_cast<decltype(cell_y.gid)>(-1))
{
info.cells_exterior_ecl.emplace_back(-1, -1);
info.exterior_face_no_ecl.emplace_back(-1);
info.face_orientation_ecl.emplace_back(-1);
continue;
}
info.cells_exterior_ecl.emplace_back(
translator.translate(cell_x, cell_y));
info.exterior_face_no_ecl.emplace_back(
info_v.exterior_face_no_ecl[index] + 2 * dim_x);
info.face_orientation_ecl.emplace_back(
info_v.face_orientation_ecl[index]); // TODO?
}
for (; v_x < info_x.max_batch_size; v_x++)
{
info.cells_exterior_ecl.emplace_back(-1, -1);
info.exterior_face_no_ecl.emplace_back(-1);
info.face_orientation_ecl.emplace_back(-1);
}
}
}
// cells: ghost x local
for (unsigned int i_v = 0; i_v < n_cell_batches_v; i_v++)
for (unsigned int v_v = 0; v_v < info_v.cells_fill[i_v]; v_v++)
for (unsigned int i_x = n_cell_batches_x;
i_x < n_cell_and_ghost_batches_x;
i_x++)
process(i_x, i_v, v_v);
// cells: local x ghost
for (unsigned int i_v = n_cell_batches_v;
i_v < n_cell_and_ghost_batches_v;
i_v++)
for (unsigned int v_v = 0; v_v < info_v.cells_fill[i_v]; v_v++)
for (unsigned int i_x = 0; i_x < n_cell_batches_x; i_x++)
process(i_x, i_v, v_v);
// internal faces
{
const unsigned int n_face_batches_x = info_x.exterior_face_no.size();
const unsigned int n_face_batches_v = info_v.exterior_face_no.size();
const unsigned int n_face_batches_x_all =
info_x.interior_face_no.size();
const unsigned int n_face_batches_v_all =
info_v.interior_face_no.size();
// interior faces (face x cell):
for (unsigned int i_v = 0; i_v < n_cell_batches_v; i_v++)
for (unsigned int v_v = 0; v_v < info_v.cells_fill[i_v]; v_v++)
for (unsigned int i_x = 0; i_x < n_face_batches_x; i_x++)
{
unsigned int v_x = 0;
for (; v_x < info_x.faces_fill[i_x]; v_x++)
{
const auto cell_y =
info_v.cells[i_v * info_v.max_batch_size + v_v];
info.cells_interior.emplace_back(translator.translate(
info_x.cells_interior[i_x * info_x.max_batch_size + v_x],
cell_y));
info.cells_exterior.emplace_back(translator.translate(
info_x.cells_exterior[i_x * info_x.max_batch_size + v_x],
cell_y));
}
for (; v_x < info_x.max_batch_size; v_x++)
{
info.cells_interior.emplace_back(-1, -1);
info.cells_exterior.emplace_back(-1, -1);
}
info.faces_fill.push_back(info_x.faces_fill[i_x]);
info.interior_face_no.push_back(info_x.interior_face_no[i_x]);
info.exterior_face_no.push_back(info_x.exterior_face_no[i_x]);
info.face_orientation.push_back(info_x.face_orientation[i_x]);
}
// interior faces (cell x face):
for (unsigned int i_v = 0; i_v < n_face_batches_v; i_v++)
for (unsigned int v_v = 0; v_v < info_v.faces_fill[i_v]; v_v++)
for (unsigned int i_x = 0; i_x < n_cell_batches_x; i_x++)
{
unsigned int v_x = 0;
for (; v_x < info_x.cells_fill[i_x]; v_x++)
{
const auto cell_x =
info_x.cells[i_x * info_x.max_batch_size + v_x];
info.cells_interior.emplace_back(translator.translate(
cell_x,
info_v
.cells_interior[i_v * info_v.max_batch_size + v_v]));
info.cells_exterior.emplace_back(translator.translate(
cell_x,
info_v
.cells_exterior[i_v * info_v.max_batch_size + v_v]));
}
for (; v_x < info_x.max_batch_size; v_x++)
{
info.cells_interior.emplace_back(-1, -1);
info.cells_exterior.emplace_back(-1, -1);
}
info.faces_fill.push_back(info_x.cells_fill[i_x]);
info.interior_face_no.push_back(info_v.interior_face_no[i_v] +
2 * dim_x);
info.exterior_face_no.push_back(info_v.exterior_face_no[i_v] +
2 * dim_x);
info.face_orientation.push_back(info_v.face_orientation[i_v]);
}
for (unsigned int i_v = 0; i_v < n_cell_batches_v; i_v++)
for (unsigned int v_v = 0; v_v < info_v.cells_fill[i_v]; v_v++)
for (unsigned int i_x = n_face_batches_x;
i_x < n_face_batches_x_all;
i_x++)
{
unsigned int v_x = 0;
for (; v_x < info_x.faces_fill[i_x]; v_x++)
{
const auto cell_x =
info_x.cells_interior[i_x * info_x.max_batch_size + v_x];
const auto cell_y =
info_v.cells[i_v * info_v.max_batch_size + v_v];
info.cells_interior.emplace_back(
translator.translate(cell_x, cell_y));
}
for (; v_x < info_x.max_batch_size; v_x++)
info.cells_interior.emplace_back(-1, -1);
info.faces_fill.push_back(info_x.faces_fill[i_x]);
info.interior_face_no.push_back(info_x.interior_face_no[i_x]);
info.face_orientation.push_back(info_x.face_orientation[i_x]);
}
// interior faces (cell x face):
for (unsigned int i_v = n_face_batches_v; i_v < n_face_batches_v_all;
i_v++)
for (unsigned int v_v = 0; v_v < info_v.faces_fill[i_v]; v_v++)
for (unsigned int i_x = 0; i_x < n_cell_batches_x; i_x++)
{
unsigned int v_x = 0;
for (; v_x < info_x.cells_fill[i_x]; v_x++)
{
const auto cell_x =
info_x.cells[i_x * info_x.max_batch_size + v_x];
const auto cell_y =
info_v.cells_interior[i_v * info_v.max_batch_size + v_v];
info.cells_interior.emplace_back(
translator.translate(cell_x, cell_y));
}
for (; v_x < info_x.max_batch_size; v_x++)
info.cells_interior.emplace_back(-1, -1);
info.faces_fill.push_back(info_x.cells_fill[i_x]);
info.interior_face_no.push_back(info_v.interior_face_no[i_v] +
2 * dim_x);
info.face_orientation.push_back(info_v.face_orientation[i_v]);
}
}
}
} // namespace internal
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::MatrixFree(
const MPI_Comm comm,
const MPI_Comm comm_sm,
const dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>
&matrix_free_x,
const dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV>
&matrix_free_v)
: comm(comm)
, comm_sm(comm_sm)
, matrix_free_x(matrix_free_x)
, matrix_free_v(matrix_free_v)
{}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::reinit(
const AdditionalData &additional_data)
{
// store relevant settings
this->do_buffering = additional_data.do_buffering;
this->do_ghost_faces = additional_data.do_ghost_faces;
this->use_ecl = additional_data.use_ecl;
AssertThrow(this->do_ghost_faces,
dealii::ExcMessage(
"At the moment only ghost faces are supported!"));
AssertThrow(this->use_ecl || (/*!this->use_ecl &&*/ this->do_buffering),
dealii::ExcMessage("FCL needs buffering!"));
AssertDimension(matrix_free_x.get_shape_info().n_components, 1);
AssertDimension(matrix_free_v.get_shape_info().n_components, 1);
AssertDimension(matrix_free_x.get_shape_info().data.front().fe_degree,
matrix_free_v.get_shape_info().data.front().fe_degree);
const int dim = dim_x + dim_v;
// set up shape_info
this->shape_info.template reinit<dim_x, dim_v>(
matrix_free_x.get_shape_info().data.front().fe_degree);
// collect (global) information of each macro cell in phase space
const auto info = [&]() {
internal::GlobalCellInfo info_x, info_v, info;
// collect (global) information of each macro cell in x-space
internal::collect_global_cell_info(matrix_free_x, info_x);
// collect (global) information of each macro cell in v-space
internal::collect_global_cell_info(matrix_free_v, info_v);
// create tensor product
internal::combine_global_cell_info(
matrix_free_x.get_task_info().communicator,
matrix_free_v.get_task_info().communicator,
info_x,
info_v,
info,
dim_x,
dim_v);
return info;
}();
// set up partitioner
this->partitioner = [&] {
AssertThrow(do_ghost_faces,
dealii::StandardExceptions::ExcNotImplemented());
auto partitioner = new dealii::internal::MatrixFreeFunctions::
VectorDataExchange::Contiguous(shape_info);
// create a list of inner cells and ghost faces
std::vector<dealii::types::global_dof_index> local_list;
std::vector<
std::pair<dealii::types::global_dof_index, std::vector<unsigned int>>>
ghost_list;
// 1) collect local cells
{
for (unsigned int i = 0; i < info.n_cell_batches; i++)
for (unsigned int v = 0; v < info.cells_fill[i]; v++)
local_list.emplace_back(
info.cells[i * info.max_batch_size + v].gid);
std::sort(local_list.begin(), local_list.end());
}
// 2) collect ghost faces and group them for each cell
{
// a) get ghost faces
auto ghost_faces =
internal::GlobalCellInfoProcessor(info).get_ghost_faces(
dim, this->use_ecl);
// b) sort them
std::sort(ghost_faces.begin(),
ghost_faces.end(),
[](const auto &a, const auto &b) {
// according to global id of corresponding cell ...
if (a.gid < b.gid)
return true;
// ... and face number
if (a.gid == b.gid && a.no < b.no)
return true;
return false;
});
// c) group them
if (ghost_faces.size() > 0)
{
auto ptr = ghost_faces.begin();
ghost_list.emplace_back(ptr->gid,
std::vector<unsigned int>{ptr->no});
ptr++;
for (; ptr != ghost_faces.end(); ptr++)
{
if (ghost_list.back().first == ptr->gid)
ghost_list.back().second.emplace_back(ptr->no);
else
ghost_list.emplace_back(ptr->gid,
std::vector<unsigned int>{ptr->no});
}
}
}
// actually setup partitioner
partitioner->reinit(local_list, ghost_list, comm, comm_sm, do_buffering);
return std::shared_ptr<
const dealii::internal::MatrixFreeFunctions::VectorDataExchange::Base>(
partitioner);
}();
/**
* Global ID of cell each face/cell is related to.
*
* @note (0) FCL (interior); (1) FCL (exterior);
* (2) cell; (3) ECL (exterior)
*/
std::array<std::vector<unsigned int>, 4> dof_indices_contiguous;
// set up rest of dof_info and face_info (1)
{
auto &n_vectorization_lanes_filled =
dof_info.n_vectorization_lanes_filled;
auto &no_faces = face_info.no_faces;
auto &face_orientations = face_info.face_orientations;
// 1) collect gids (dof_indices) according to vectorization
{
for (unsigned int i = 0; i < info.interior_face_no.size(); i++)
for (unsigned int v = 0; v < info.max_batch_size; v++)
dof_indices_contiguous[0].push_back(
info.cells_interior[i * info.max_batch_size + v].gid);
for (unsigned int i = 0; i < info.exterior_face_no.size(); i++)
for (unsigned int v = 0; v < info.max_batch_size; v++)
dof_indices_contiguous[1].push_back(
info.cells_exterior[i * info.max_batch_size + v].gid);
for (unsigned int i = 0; i < info.n_cell_batches; i++)
for (unsigned int v = 0; v < info.max_batch_size; v++)
dof_indices_contiguous[2].push_back(
info.cells[i * info.max_batch_size + v].gid);
for (unsigned int i = 0; i < info.n_cell_batches; i++)
for (unsigned int d = 0;
d < dealii::GeometryInfo<dim>::faces_per_cell;
d++)
for (unsigned int v = 0; v < info.max_batch_size; v++)
dof_indices_contiguous[3].push_back(
info
.cells_exterior_ecl
[i * info.max_batch_size *
dealii::GeometryInfo<dim>::faces_per_cell +
d * info.max_batch_size + v]
.gid);
}
// 2) collect filled lanes
{
for (unsigned int i = 0; i < info.interior_face_no.size(); i++)
n_vectorization_lanes_filled[0].push_back(info.faces_fill[i]);
for (unsigned int i = 0; i < info.exterior_face_no.size(); i++)
n_vectorization_lanes_filled[1].push_back(info.faces_fill[i]);
for (unsigned int i = 0; i < info.n_cell_batches; i++)
n_vectorization_lanes_filled[2].push_back(info.cells_fill[i]);
if (this->use_ecl) // filled only so that the code is more generic
// cleared later on!
for (unsigned int i = 0; i < info.n_cell_batches; i++)
for (unsigned int d = 0;
d < dealii::GeometryInfo<dim>::faces_per_cell;
d++)
n_vectorization_lanes_filled[3].push_back(info.cells_fill[i]);
}
// 3) collect face numbers
{
no_faces[0] = info.interior_face_no;
no_faces[1] = info.exterior_face_no;
no_faces[3] = info.exterior_face_no_ecl;
}
// 3) collect face orientations
{
face_orientations[0] = info.face_orientation;
face_orientations[3] = info.face_orientation_ecl;
}
}
// set up rest of dof_info and face_info (2)
{
// given information
const auto &vectorization_length = dof_info.n_vectorization_lanes_filled;
const auto &no_faces = face_info.no_faces;
const auto &face_orientations = face_info.face_orientations;
const auto &maps =
dynamic_cast<const dealii::internal::MatrixFreeFunctions::
VectorDataExchange::Contiguous *>(partitioner.get())
->get_maps();
const auto &maps_ghost =
dynamic_cast<const dealii::internal::MatrixFreeFunctions::
VectorDataExchange::Contiguous *>(partitioner.get())
->get_maps_ghost();
static const int v_len = VectorizedArrayType::size();
// to be computed
auto &cell_ptrs = dof_info.dof_indices_contiguous_ptr;
auto &face_type = face_info.face_type;
auto &face_all = face_info.face_all;
// allocate memory
for (unsigned int i = 0; i < 4; i++)
cell_ptrs[i].resize(dof_indices_contiguous[i].size());
for (unsigned int i = 0; i < 4; i++)
face_type[i].resize(i == 2 ? 0 : dof_indices_contiguous[i].size());
for (unsigned int i = 0; i < 4; i++)
face_all[i].resize(i == 2 ? 0 : vectorization_length[i].size());
// process faces: cell_ptrs and face_type
for (unsigned int i = 0; i < 4; i++)
{
if (i == 2)
continue; // nothing to do for cells - it is done later
for (unsigned int j = 0; j < vectorization_length[i].size(); j++)
for (unsigned int v = 0; v < vectorization_length[i][j]; v++)
{
const unsigned int l = j * v_len + v;
Assert(l < dof_indices_contiguous[i].size(),
dealii::StandardExceptions::ExcMessage(
"Size of gid does not match."));
const unsigned int gid_this = dof_indices_contiguous[i][l];
// for boundary faces nothing has to be done
if (gid_this == dealii::numbers::invalid_unsigned_int)
continue;
const auto ptr1 = maps_ghost.find(
{gid_this,
do_ghost_faces ? no_faces[i][i == 3 ? l : j] :
dealii::numbers::invalid_unsigned_int});
if (ptr1 != maps_ghost.end())
{
cell_ptrs[i][l] = {ptr1->second.first, ptr1->second.second};
face_type[i][l] = true; // ghost face
continue;
}
const auto ptr2 = maps.find(gid_this);
if (ptr2 != maps.end())
{
cell_ptrs[i][l] = {ptr2->second.first, ptr2->second.second};
face_type[i][l] = false; // cell is part of sm
continue;
}
AssertThrow(false,
dealii::StandardExceptions::ExcMessage(
"Cell not found!"));
}
}
// process faces: face_all
for (unsigned int i = 0; i < 4; i++)
{
if (i == 2)
continue; // nothing to do for cells - it is done later
for (unsigned int j = 0; j < vectorization_length[i].size(); j++)
{
bool temp = true;
for (unsigned int v = 0; v < vectorization_length[i][j]; v++)
temp &=
(face_type[i][j * v_len] == face_type[i][j * v_len + v]) &&
(i == 3 ?
((no_faces[i][j * v_len] == no_faces[i][j * v_len + v]) &&
(face_orientations[i][j * v_len] ==
face_orientations[i][j * v_len + v])) :
true);
face_all[i][j] = temp;
}
}
// process cells
for (unsigned int j = 0; j < vectorization_length[2].size(); j++)
for (unsigned int v = 0; v < vectorization_length[2][j]; v++)
{
const unsigned int l = j * v_len + v;
const unsigned int gid_this = dof_indices_contiguous[2][l];
const auto ptr = maps.find(gid_this);
cell_ptrs[2][l] = {ptr->second.first, ptr->second.second};
}
// clear vector since it is not needed anymore, since the values
// are the same as for cells
dof_info.n_vectorization_lanes_filled[3].clear();
}
// partitions for ECL
if (this->use_ecl)
{
for (auto &partition : partitions)
partition.clear();
const unsigned int v_len = VectorizedArrayTypeV::size();
const auto my_rank = dealii::Utilities::MPI::this_mpi_process(comm);
const auto sm_ranks_vec = mpi::procs_of_sm(comm, comm_sm);
const std::set<unsigned int> sm_ranks(sm_ranks_vec.begin(),
sm_ranks_vec.end());
const unsigned int n_cell_batches_x = matrix_free_x.n_cell_batches();
const unsigned int n_cell_batches_v = matrix_free_v.n_cell_batches();
// 0: no overlapping
const unsigned int overlapping_level =
additional_data.overlapping_level;
for (unsigned int j = 0, i0 = 0; j < n_cell_batches_v; j++)
for (unsigned int v = 0;
v < matrix_free_v.n_active_entries_per_cell_batch(j);
v++)
for (unsigned int i = 0; i < n_cell_batches_x; i++, i0++)
{
unsigned int flag = 0;
for (unsigned int d = 0;
d < dealii::GeometryInfo<dim>::faces_per_cell;
d++)
for (unsigned int v = 0;
v < dof_info.n_vectorization_lanes_filled[2][i0];
v++)
{
const auto gid =
info
.cells_exterior_ecl
[i0 * info.max_batch_size *
dealii::GeometryInfo<dim>::faces_per_cell +
d * info.max_batch_size + v]
.rank;
if (overlapping_level >= 1 && gid == my_rank)
flag = std::max(flag, 0u);
else if (overlapping_level == 2 &&
sm_ranks.find(gid) != sm_ranks.end())
flag = std::max(flag, 1u);
else
flag = std::max(flag, 2u);
}
partitions[flag].emplace_back(i, j * v_len + v, i0);
}
if (dealii::Utilities::MPI::this_mpi_process(comm) == 0)
std::cout << partitions[0].size() << " " << partitions[1].size()
<< " " << partitions[2].size() << " " << std::endl;
}
}
namespace internal
{
template <typename Number>
struct VectorDataExchange
{
VectorDataExchange(
std::shared_ptr<
const dealii::internal::MatrixFreeFunctions::VectorDataExchange::Base>
partitioner)
: partitioner(partitioner)
{}
template <typename VectorType>
void
export_to_ghosted_array_start(VectorType &vec)
{
buffer.resize_fast(this->partitioner->n_import_indices());
this->partitioner->export_to_ghosted_array_start(
0,
dealii::ArrayView<const Number>(
vec.begin(), this->partitioner->locally_owned_size()),
vec.shared_vector_data(),
dealii::ArrayView<Number>(const_cast<Number *>(vec.begin()) +
this->partitioner->locally_owned_size(),
this->partitioner->n_ghost_indices()),
dealii::ArrayView<Number>(buffer.begin(), buffer.size()),
requests);
}
template <typename VectorType>
void
export_to_ghosted_array_finish(VectorType &vec)
{
AssertDimension(buffer.size(), this->partitioner->n_import_indices());
this->partitioner->export_to_ghosted_array_finish(
dealii::ArrayView<const Number>(
vec.begin(), this->partitioner->locally_owned_size()),
vec.shared_vector_data(),
dealii::ArrayView<Number>(const_cast<Number *>(vec.begin()) +
this->partitioner->locally_owned_size(),
this->partitioner->n_ghost_indices()),
requests);
}
template <typename VectorType>
void
export_to_ghosted_array_finish_0(VectorType &vec)
{
const auto part =
dynamic_cast<const dealii::internal::MatrixFreeFunctions::
VectorDataExchange::Contiguous *>(partitioner.get());
part->export_to_ghosted_array_finish_0(
dealii::ArrayView<const Number>(
const_cast<Number *>(vec.begin()),
this->partitioner->locally_owned_size()),
vec.shared_vector_data(),
dealii::ArrayView<Number>(const_cast<Number *>(vec.begin()) +
this->partitioner->locally_owned_size(),
this->partitioner->n_ghost_indices()),
requests);
}
template <typename VectorType>
void
export_to_ghosted_array_finish_1(VectorType &vec)
{
const auto part =
dynamic_cast<const dealii::internal::MatrixFreeFunctions::
VectorDataExchange::Contiguous *>(partitioner.get());
part->export_to_ghosted_array_finish_1(
dealii::ArrayView<const Number>(
vec.begin(), this->partitioner->locally_owned_size()),
vec.shared_vector_data(),
dealii::ArrayView<Number>(const_cast<Number *>(vec.begin()) +
this->partitioner->locally_owned_size(),
this->partitioner->n_ghost_indices()),
requests);
}
template <typename VectorType>
void
import_from_ghosted_array_start(VectorType &vec)
{
buffer.resize_fast(this->partitioner->n_import_indices());
this->partitioner->import_from_ghosted_array_start(
dealii::VectorOperation::values::add,
0,
dealii::ArrayView<const Number>(
vec.begin(), this->partitioner->locally_owned_size()),
vec.shared_vector_data(),
dealii::ArrayView<Number>(vec.begin() +
this->partitioner->locally_owned_size(),
this->partitioner->n_ghost_indices()),
dealii::ArrayView<Number>(buffer.begin(), buffer.size()),
requests);
}
template <typename VectorType>
void
import_from_ghosted_array_finish(VectorType &vec)
{
AssertDimension(buffer.size(), this->partitioner->n_import_indices());
this->partitioner->import_from_ghosted_array_finish(
dealii::VectorOperation::values::add,
dealii::ArrayView<Number>(vec.begin(),
this->partitioner->locally_owned_size()),
vec.shared_vector_data(),
dealii::ArrayView<Number>(vec.begin() +
this->partitioner->locally_owned_size(),
this->partitioner->n_ghost_indices()),
dealii::ArrayView<const Number>(buffer.begin(), buffer.size()),
requests);
}
const std::shared_ptr<
const dealii::internal::MatrixFreeFunctions::VectorDataExchange::Base>
partitioner;
dealii::AlignedVector<Number> buffer;
std::vector<MPI_Request> requests;
};
} // namespace internal
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::initialize_dof_vector(
dealii::LinearAlgebra::distributed::Vector<Number> &vec,
const unsigned int dof_handler_index,
const bool do_ghosts,
const bool zero_out_values) const
{
AssertThrow(dof_handler_index == 0,
dealii::ExcMessage(
"Only one dof_handler supported at the moment!"));
AssertThrow((partitioner != nullptr),
dealii::ExcMessage("Partitioner has not been initialized!"));
// setup vector
vec.reinit(partitioner->locally_owned_size(),
do_ghosts ? partitioner->n_ghost_indices() : 0,
comm,
comm_sm);
// zero out values
if (zero_out_values)
vec = 0.0;
// perform test ghost value update (working for ECL/FCL)
if (zero_out_values && do_ghosts)
{
vec.zero_out_ghost_values();
internal::VectorDataExchange<Number> data_exchanger(partitioner);
data_exchanger.export_to_ghosted_array_start(vec);
data_exchanger.export_to_ghosted_array_finish(vec);
vec.zero_out_ghost_values();
}
// perform test compression (working for FCL)
if (zero_out_values && do_ghosts && !use_ecl)
{
internal::VectorDataExchange<Number> data_exchanger(partitioner);
data_exchanger.import_from_ghosted_array_start(vec);
data_exchanger.import_from_ghosted_array_finish(vec);
}
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
template <typename OutVector, typename InVector>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::cell_loop(
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
& cell_operation,
OutVector & dst,
const InVector &src) const
{
unsigned int v_len = VectorizedArrayTypeV::size();
const unsigned int n_cell_batches_x = matrix_free_x.n_cell_batches();
const unsigned int n_cell_batches_v = matrix_free_v.n_cell_batches();
unsigned int i0 = 0;
for (unsigned int j = 0; j < n_cell_batches_v; j++)
for (unsigned int v = 0;
v < matrix_free_v.n_active_entries_per_cell_batch(j);
v++)
for (unsigned int i = 0; i < n_cell_batches_x; i++)
cell_operation(*this, dst, src, ID(i, j * v_len + v, i0++));
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
template <typename CLASS, typename OutVector, typename InVector>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::cell_loop(
void (CLASS::*cell_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
CLASS * owning_class,
OutVector & dst,
const InVector &src) const
{
this->template cell_loop<OutVector, InVector>(
[&cell_operation, &owning_class](const MatrixFree &mf,
OutVector & dst,
const InVector & src,
const ID id) {
(owning_class->*cell_operation)(mf, dst, src, id);
},
dst,
src);
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
template <typename CLASS, typename OutVector, typename InVector>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::loop_cell_centric(
void (CLASS::*cell_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
CLASS * owning_class,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces src_vector_face_access,
Timers * timers) const
{
this->template loop_cell_centric<OutVector, InVector>(
[&cell_operation, &owning_class](const MatrixFree &mf,
OutVector & dst,
const InVector & src,
const ID id) {
(owning_class->*cell_operation)(mf, dst, src, id);
},
dst,
src,
src_vector_face_access,
timers);
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
template <typename OutVector, typename InVector>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::loop_cell_centric(
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
& cell_operation,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces src_vector_face_access,
Timers * timers) const
{
AssertThrow(src_vector_face_access == DataAccessOnFaces::values ||
src_vector_face_access == DataAccessOnFaces::none,
dealii::StandardExceptions::ExcNotImplemented());
{
ScopedTimerWrapper timer(timers, "loop");
internal::VectorDataExchange<Number> data_exchanger(partitioner);
// loop over all partitions
for (unsigned int i = 0; i < this->partitions.size(); ++i)
{
// perform pre-processing step for partition
if (src_vector_face_access == DataAccessOnFaces::values)
{
if (i == 0)
{
if (timers != nullptr)
timers->operator[]("update_ghost_values_0").start();
// perform src.update_ghost_values_start()
data_exchanger.export_to_ghosted_array_start(src);
// zero out ghost of destination vector
if (dst.has_ghost_elements())
dst.zero_out_ghost_values();
}
else if (i == 1)
{
// ... src.update_ghost_values_finish() for shared-memory
// domain:
data_exchanger.export_to_ghosted_array_finish_0(src);
if (timers != nullptr)
{
timers->operator[]("update_ghost_values_0").stop();
timers->operator[]("update_ghost_values_1").start();
}
}
else if (i == 2)
{
// ... src.update_ghost_values_finish() for remote domain:
data_exchanger.export_to_ghosted_array_finish_1(src);
if (timers != nullptr)
{
timers->operator[]("update_ghost_values_1").stop();
timers->operator[]("update_ghost_values_2").start();
}
}
else
{
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
}
}
// loop over all cells in partition
for (const auto &id : this->partitions[i])
cell_operation(*this, dst, src, id);
}
}
if (timers != nullptr)
timers->operator[]("update_ghost_values_2").stop();
if (do_buffering == false &&
src_vector_face_access == DataAccessOnFaces::values)
{
ScopedTimerWrapper timer(timers, "barrier");
dynamic_cast<const dealii::internal::MatrixFreeFunctions::
VectorDataExchange::Contiguous *>(partitioner.get())
->sync();
}
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
template <typename CLASS, typename OutVector, typename InVector>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::loop(
void (CLASS::*cell_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
void (CLASS::*face_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
void (CLASS::*boundary_operation)(const MatrixFree &,
OutVector &,
const InVector &,
const ID),
CLASS * owning_class,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces dst_vector_face_access,
const DataAccessOnFaces src_vector_face_access,
Timers * timers) const
{
this->template loop<OutVector, InVector>(
[&cell_operation, &owning_class](const MatrixFree &mf,
OutVector & dst,
const InVector & src,
const ID id) {
(owning_class->*cell_operation)(mf, dst, src, id);
},
[&face_operation, &owning_class](const MatrixFree &mf,
OutVector & dst,
const InVector & src,
const ID id) {
(owning_class->*face_operation)(mf, dst, src, id);
},
[&boundary_operation, &owning_class](const MatrixFree &mf,
OutVector & dst,
const InVector & src,
const ID id) {
(owning_class->*boundary_operation)(mf, dst, src, id);
},
dst,
src,
dst_vector_face_access,
src_vector_face_access,
timers);
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
template <typename OutVector, typename InVector>
void
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::loop(
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
&cell_operation,
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
&face_operation,
const std::function<
void(const MatrixFree &, OutVector &, const InVector &, const ID)>
& boundary_operation,
OutVector & dst,
const InVector & src,
const DataAccessOnFaces dst_vector_face_access,
const DataAccessOnFaces src_vector_face_access,
Timers * timers) const
{
if (src_vector_face_access == DataAccessOnFaces::values)
{
ScopedTimerWrapper timer(timers, "update_ghost_values");
internal::VectorDataExchange<Number> data_exchanger(partitioner);
data_exchanger.export_to_ghosted_array_start(src);
data_exchanger.export_to_ghosted_array_finish(src);
}
else
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
{
ScopedTimerWrapper timer(timers, "zero_out_ghosts");
dst.zero_out_ghost_values();
}
unsigned int v_len = VectorizedArrayTypeV::size();
const unsigned int n_cell_batches_x = matrix_free_x.n_cell_batches();
const unsigned int n_inner_face_batches_x =
matrix_free_x.n_inner_face_batches();
const unsigned int n_inner_boundary_batches_x =
matrix_free_x.n_boundary_face_batches();
const unsigned int n_inner_or_boundary_face_batches_x =
n_inner_face_batches_x + n_inner_boundary_batches_x;
const unsigned int n_cell_batches_v = matrix_free_v.n_cell_batches();
const unsigned int n_inner_face_batches_v =
matrix_free_v.n_inner_face_batches();
const unsigned int n_inner_boundary_batches_v =
matrix_free_v.n_boundary_face_batches();
const unsigned int n_inner_or_boundary_face_batches_v =
n_inner_face_batches_v + n_inner_boundary_batches_v;
unsigned int i0 = 0;
unsigned int i1 = 0;
// clang-format off
// loop over all cells
{
ScopedTimerWrapper timer(timers, "cell_loop");
for(unsigned int j = 0; j < n_cell_batches_v; j++)
for(unsigned int v = 0; v < matrix_free_v.n_active_entries_per_cell_batch(j); v++)
for(unsigned int i = 0; i < n_cell_batches_x; i++)
cell_operation(*this, dst, src, ID(i, j * v_len + v, i0++));
}
// loop over all inner faces ...
{
ScopedTimerWrapper timer(timers, "face_loop_x");
for(unsigned int j = 0; j < n_cell_batches_v; j++)
for(unsigned int v = 0; v < matrix_free_v.n_active_entries_per_cell_batch(j); v++)
for(unsigned int i = 0; i < n_inner_face_batches_x; i++)
face_operation(*this, dst, src, ID(i, j * v_len + v, i1++, ID::SpaceType::X));
}
for(unsigned int j = 0; j < n_inner_face_batches_v; j++)
{
ScopedTimerWrapper timer(timers, "face_loop_v");
for(unsigned int v = 0; v < matrix_free_v.n_active_entries_per_face_batch(j); v++)
for(unsigned int i = 0; i < n_cell_batches_x; i++)
face_operation(*this, dst, src, ID(i, j * v_len + v, i1++, ID::SpaceType::V));
}
// ... and continue to loop over all boundary faces
{
ScopedTimerWrapper timer(timers, "boundary_loop_x");
for(unsigned int j = 0; j < n_cell_batches_v; j++)
for(unsigned int v = 0; v < matrix_free_v.n_active_entries_per_cell_batch(j); v++)
for(unsigned int i = n_inner_face_batches_x; i < n_inner_or_boundary_face_batches_x; i++)
boundary_operation(*this, dst, src, ID(i, j * v_len + v, i1++, ID::SpaceType::X));
}
{
ScopedTimerWrapper timer(timers, "boundary_loop_v");
for(unsigned int j = n_inner_face_batches_v; j < n_inner_or_boundary_face_batches_v; j++)
for(unsigned int v = 0; v < matrix_free_v.n_active_entries_per_face_batch(j); v++)
for(unsigned int i = 0; i < n_cell_batches_x; i++)
boundary_operation(*this, dst, src, ID(i, j * v_len + v, i1++, ID::SpaceType::V));
}
// clang-format on
if (dst_vector_face_access == DataAccessOnFaces::values)
{
ScopedTimerWrapper timer(timers, "compress");
internal::VectorDataExchange<Number> data_exchanger(partitioner);
data_exchanger.import_from_ghosted_array_start(dst);
data_exchanger.import_from_ghosted_array_finish(dst);
}
else
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
const MPI_Comm &
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::get_communicator()
const
{
return comm;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
dealii::types::boundary_id
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::get_boundary_id(
const ID macro_face) const
{
if (macro_face.type == TensorID::SpaceType::X)
return matrix_free_x.get_boundary_id(macro_face.x);
else if (macro_face.type == TensorID::SpaceType::V)
return matrix_free_v.get_boundary_id(macro_face.v /
VectorizedArrayTypeV::size());
Assert(false, dealii::StandardExceptions::ExcInternalError());
return -1;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
dealii::types::boundary_id
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
get_faces_by_cells_boundary_id(const TensorID & macro_cell,
const unsigned int face_number) const
{
if (face_number < 2 * dim_x)
{
const auto bids =
matrix_free_x.get_faces_by_cells_boundary_id(macro_cell.x,
face_number);
#ifdef DEBUG
for (unsigned int v = 0;
v < matrix_free_x.n_active_entries_per_cell_batch(macro_cell.x);
++v)
AssertDimension(bids[0], bids[v]);
#endif
return bids[0];
}
else if (face_number < 2 * dim_x + 2 * dim_v)
{
const auto bids =
matrix_free_v.get_faces_by_cells_boundary_id(macro_cell.v,
face_number - dim_x * 2);
#ifdef DEBUG
for (unsigned int v = 0;
v < matrix_free_v.n_active_entries_per_cell_batch(macro_cell.v);
++v)
AssertDimension(bids[0], bids[v]);
#endif
return bids[0];
}
Assert(false, dealii::StandardExceptions::ExcInternalError());
return -1;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
bool
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::is_ecl_supported()
const
{
return use_ecl;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
bool
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
are_ghost_faces_supported() const
{
return do_ghost_faces;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
const dealii::MatrixFree<
dim_x,
Number,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeX> &
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::get_matrix_free_x()
const
{
return matrix_free_x;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
const dealii::MatrixFree<
dim_v,
Number,
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
VectorizedArrayTypeV> &
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::get_matrix_free_v()
const
{
return matrix_free_v;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
const internal::MatrixFreeFunctions::DoFInfo &
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::get_dof_info() const
{
return dof_info;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
const internal::MatrixFreeFunctions::FaceInfo &
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::get_face_info() const
{
return face_info;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
const internal::MatrixFreeFunctions::ShapeInfo<Number> &
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::get_shape_info() const
{
return shape_info;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
MemoryConsumption
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::memory_consumption()
const
{
MemoryConsumption mem("matrix_free");
// mem.insert("partitioner", partitioner->memory_consumption()); // TODO
mem.insert("dof_info", dof_info.memory_consumption());
mem.insert("face_info", face_info.memory_consumption());
mem.insert("shape_info", shape_info.memory_consumption());
return mem;
}
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
const std::shared_ptr<
const dealii::internal::MatrixFreeFunctions::VectorDataExchange::Base> &
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
get_vector_partitioner() const
{
return partitioner;
}
} // namespace hyperdeal
| 72,675
|
C++
|
.h
| 1,634
| 31.684823
| 99
| 0.52678
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,152
|
vector_partitioner.h
|
hyperdeal_hyperdeal/include/hyper.deal/matrix_free/vector_partitioner.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef DEALII_LINEARALGEBRA_SHAREDMPI_PARTITIONER
#define DEALII_LINEARALGEBRA_SHAREDMPI_PARTITIONER
#include <hyper.deal/base/config.h>
#include <deal.II/base/conditional_ostream.h>
#include <deal.II/base/mpi.h>
#include <deal.II/base/mpi.templates.h>
#include <deal.II/base/mpi_compute_index_owner_internal.h>
#include <deal.II/base/mpi_consensus_algorithms.h>
#include <deal.II/base/timer.h>
#ifdef DEAL_II_WITH_64BIT_INDICES
# include <deal.II/base/mpi_consensus_algorithms.templates.h>
#endif
#include <deal.II/matrix_free/vector_data_exchange.h>
#include <hyper.deal/base/mpi.h>
#include <hyper.deal/base/mpi_tags.h>
#include <hyper.deal/matrix_free/shape_info.h>
#include <map>
#include <vector>
DEAL_II_NAMESPACE_OPEN
namespace internal
{
namespace MatrixFreeFunctions
{
namespace VectorDataExchange
{
/**
* Partitioner for discontinuous Galerkin discretizations, exploiting
* shared memory.
*/
class Contiguous
: public dealii::internal::MatrixFreeFunctions::VectorDataExchange::Base
{
const dealii::types::global_dof_index dofs_per_cell;
const dealii::types::global_dof_index dofs_per_face;
const std::vector<std::vector<unsigned int>> &face_to_cell_index_nodal;
public:
using RankType = unsigned int;
using LocalDoFType = unsigned int;
using CellIdType = dealii::types::global_dof_index;
using FaceIdType = std::pair<CellIdType, unsigned int>;
/**
* Constructor.
*/
template <typename ShapeInfo>
Contiguous(const ShapeInfo &shape_info);
/**
* Initialize partitioner with a list of locally owned cells and
* a list of ghost faces (cell and face no).
*/
inline void
reinit(const std::vector<dealii::types::global_dof_index> local_cells,
const std::vector<std::pair<dealii::types::global_dof_index,
std::vector<unsigned int>>>
local_ghost_faces,
const MPI_Comm comm,
const MPI_Comm comm_sm,
const bool do_buffering);
unsigned int
locally_owned_size() const override
{
return n_local_elements;
}
unsigned int
n_ghost_indices() const override
{
return n_ghost_elements;
}
unsigned int
n_import_indices() const override
{
return send_ptr.back() * dofs_per_ghost;
}
void
reset_ghost_values(
const dealii::ArrayView<double> &ghost_array) const override
{
(void)ghost_array;
// TODO
}
void
reset_ghost_values(
const dealii::ArrayView<float> &ghost_array) const override
{
(void)ghost_array;
// TODO
}
unsigned int
n_import_sm_procs() const override
{
AssertThrow(false, ExcNotImplemented());
return 0; // TODO
}
types::global_dof_index
size() const override
{
AssertThrow(false, ExcNotImplemented());
return 0; // TODO
}
/**
* Start to export to ghost array.
*/
inline void
export_to_ghosted_array_start(
const unsigned int communication_channel,
const dealii::ArrayView<const double> &locally_owned_array,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
const dealii::ArrayView<double> & temporary_storage,
std::vector<MPI_Request> &requests) const override;
/**
* Finish to export to ghost array.
*/
inline void
export_to_ghosted_array_finish(
const dealii::ArrayView<const double> &locally_owned_array,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
std::vector<MPI_Request> &requests) const override;
/**
* Start to import from ghost array.
*/
inline void
import_from_ghosted_array_start(
const dealii::VectorOperation::values vector_operation,
const unsigned int communication_channel,
const dealii::ArrayView<const double> &locally_owned_array,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
const dealii::ArrayView<double> & temporary_storage,
std::vector<MPI_Request> &requests) const override;
/**
* Finish to import from ghost array.
*/
inline void
import_from_ghosted_array_finish(
const dealii::VectorOperation::values vector_operation,
const dealii::ArrayView<double> & locally_owned_storage,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
const dealii::ArrayView<const double> & temporary_storage,
std::vector<MPI_Request> &requests) const override;
/**
* Start to export to ghost array.
*/
inline void
export_to_ghosted_array_start(
const unsigned int communication_channel,
const dealii::ArrayView<const float> &locally_owned_array,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
const dealii::ArrayView<float> & temporary_storage,
std::vector<MPI_Request> &requests) const override;
/**
* Finish to export to ghost array.
*/
inline void
export_to_ghosted_array_finish(
const dealii::ArrayView<const float> &locally_owned_array,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
std::vector<MPI_Request> &requests) const override;
/**
* Start to import from ghost array.
*/
inline void
import_from_ghosted_array_start(
const dealii::VectorOperation::values vector_operation,
const unsigned int communication_channel,
const dealii::ArrayView<const float> &locally_owned_array,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
const dealii::ArrayView<float> & temporary_storage,
std::vector<MPI_Request> &requests) const override;
/**
* Finish to import from ghost array.
*/
inline void
import_from_ghosted_array_finish(
const dealii::VectorOperation::values vector_operation,
const dealii::ArrayView<float> & locally_owned_storage,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
const dealii::ArrayView<const float> & temporary_storage,
std::vector<MPI_Request> &requests) const override;
/**
* TODO.
*/
template <typename Number>
void
export_to_ghosted_array_finish_0(
const dealii::ArrayView<const Number> &locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
std::vector<MPI_Request> & requests) const;
/**
* TODO.
*/
template <typename Number>
void
export_to_ghosted_array_finish_1(
const dealii::ArrayView<const Number> &locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
std::vector<MPI_Request> & requests) const;
private:
/**
* Actual type-independent implementation of
* export_to_ghosted_array_start().
*/
template <typename Number>
void
export_to_ghosted_array_start_impl(
const unsigned int communication_channel,
const dealii::ArrayView<const Number> &locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
const dealii::ArrayView<Number> & temporary_storage,
std::vector<MPI_Request> & requests) const;
/**
* Actual type-independent implementation of
* export_to_ghosted_array_finish().
*/
template <typename Number>
void
export_to_ghosted_array_finish_impl(
const dealii::ArrayView<const Number> &locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
std::vector<MPI_Request> & requests) const;
/**
* Actual type-independent implementation of
* import_from_ghosted_array_start().
*/
template <typename Number>
void
import_from_ghosted_array_start_impl(
const dealii::VectorOperation::values vector_operation,
const unsigned int communication_channel,
const dealii::ArrayView<const Number> &locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
const dealii::ArrayView<Number> & temporary_storage,
std::vector<MPI_Request> & requests) const;
/**
* Actual type-independent implementation of
* import_from_ghosted_array_finish().
*/
template <typename Number>
void
import_from_ghosted_array_finish_impl(
const dealii::VectorOperation::values vector_operation,
const dealii::ArrayView<Number> & locally_owned_storage,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
const dealii::ArrayView<const Number> & temporary_storage,
std::vector<MPI_Request> & requests) const;
public:
/**
* Return position of shared cell: cell -> (owner, offset)
*/
inline const std::map<dealii::types::global_dof_index,
std::pair<unsigned int, unsigned int>> &
get_maps() const;
/**
* Return position of ghost face: (cell, no) -> (owner, offset)
*/
inline const std::map<
std::pair<dealii::types::global_dof_index, unsigned int>,
std::pair<unsigned int, unsigned int>> &
get_maps_ghost() const;
/**
* Return memory consumption.
*
* @note: Only counts the buffers [TODO].
*/
inline std::size_t
memory_consumption() const;
/**
* Synchronize.
*/
inline void
sync(const unsigned int tag = 0) const;
private:
/**
* Global communicator.
*/
MPI_Comm comm;
/**
* Shared-memory sub-communicator.
*/
MPI_Comm comm_sm;
/**
* Number of processes in comm.
*/
unsigned int n_mpi_processes_;
/**
* Number of locally-owned vector entries.
*/
unsigned int n_local_elements;
/**
* Number of ghost vector entries.
*/
unsigned int n_ghost_elements;
// I) configuration parameters
bool do_buffering; // buffering vs. non-buffering modus
unsigned int dofs_per_ghost; // ghost face or ghost cell
// II) MPI-communicator related stuff
unsigned int sm_size;
unsigned int sm_rank;
// III) access cells and ghost faces
std::map<CellIdType, std::pair<RankType, LocalDoFType>> maps;
std::map<FaceIdType, std::pair<RankType, LocalDoFType>> maps_ghost;
// III) information to pack/unpack buffers
std::vector<unsigned int> send_ranks;
std::vector<dealii::types::global_dof_index> send_ptr;
std::vector<dealii::types::global_dof_index> send_data_id;
std::vector<unsigned int> send_data_face_no;
std::vector<unsigned int> recv_ranks;
std::vector<dealii::types::global_dof_index> recv_ptr;
std::vector<dealii::types::global_dof_index> recv_size;
std::vector<unsigned int> sm_targets;
std::vector<unsigned int> sm_sources;
std::vector<dealii::types::global_dof_index> sm_send_ptr;
std::vector<unsigned int> sm_send_rank;
std::vector<unsigned int> sm_send_offset_1;
std::vector<unsigned int> sm_send_offset_2;
std::vector<unsigned int> sm_send_no;
std::vector<dealii::types::global_dof_index> sm_recv_ptr;
std::vector<unsigned int> sm_recv_rank;
std::vector<unsigned int> sm_recv_offset_1;
std::vector<unsigned int> sm_recv_offset_2;
std::vector<unsigned int> sm_recv_no;
};
inline void
Contiguous::export_to_ghosted_array_start(
const unsigned int communication_channel,
const dealii::ArrayView<const double> &locally_owned_array,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
const dealii::ArrayView<double> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
export_to_ghosted_array_start_impl(communication_channel,
locally_owned_array,
shared_arrays,
ghost_array,
temporary_storage,
requests);
}
inline void
Contiguous::export_to_ghosted_array_finish(
const dealii::ArrayView<const double> & locally_owned_array,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
std::vector<MPI_Request> & requests) const
{
export_to_ghosted_array_finish_impl(locally_owned_array,
shared_arrays,
ghost_array,
requests);
}
inline void
Contiguous::import_from_ghosted_array_start(
const dealii::VectorOperation::values vector_operation,
const unsigned int communication_channel,
const dealii::ArrayView<const double> &locally_owned_array,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
const dealii::ArrayView<double> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
import_from_ghosted_array_start_impl(vector_operation,
communication_channel,
locally_owned_array,
shared_arrays,
ghost_array,
temporary_storage,
requests);
}
inline void
Contiguous::import_from_ghosted_array_finish(
const dealii::VectorOperation::values vector_operation,
const dealii::ArrayView<double> & locally_owned_storage,
const std::vector<dealii::ArrayView<const double>> &shared_arrays,
const dealii::ArrayView<double> & ghost_array,
const dealii::ArrayView<const double> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
import_from_ghosted_array_finish_impl(vector_operation,
locally_owned_storage,
shared_arrays,
ghost_array,
temporary_storage,
requests);
}
inline void
Contiguous::export_to_ghosted_array_start(
const unsigned int communication_channel,
const dealii::ArrayView<const float> &locally_owned_array,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
const dealii::ArrayView<float> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
export_to_ghosted_array_start_impl(communication_channel,
locally_owned_array,
shared_arrays,
ghost_array,
temporary_storage,
requests);
}
inline void
Contiguous::export_to_ghosted_array_finish(
const dealii::ArrayView<const float> & locally_owned_array,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
std::vector<MPI_Request> & requests) const
{
export_to_ghosted_array_finish_impl(locally_owned_array,
shared_arrays,
ghost_array,
requests);
}
inline void
Contiguous::import_from_ghosted_array_start(
const dealii::VectorOperation::values vector_operation,
const unsigned int communication_channel,
const dealii::ArrayView<const float> &locally_owned_array,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
const dealii::ArrayView<float> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
import_from_ghosted_array_start_impl(vector_operation,
communication_channel,
locally_owned_array,
shared_arrays,
ghost_array,
temporary_storage,
requests);
}
inline void
Contiguous::import_from_ghosted_array_finish(
const dealii::VectorOperation::values vector_operation,
const dealii::ArrayView<float> & locally_owned_storage,
const std::vector<dealii::ArrayView<const float>> &shared_arrays,
const dealii::ArrayView<float> & ghost_array,
const dealii::ArrayView<const float> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
import_from_ghosted_array_finish_impl(vector_operation,
locally_owned_storage,
shared_arrays,
ghost_array,
temporary_storage,
requests);
}
inline void
Contiguous::sync(const unsigned int tag) const
{
std::vector<MPI_Request> req(sm_targets.size() + sm_sources.size());
for (unsigned int i = 0; i < sm_targets.size(); i++)
{
int dummy;
MPI_Isend(&dummy,
0,
MPI_INT,
sm_targets[i],
tag,
this->comm_sm,
req.data() + i);
}
for (unsigned int i = 0; i < sm_sources.size(); i++)
{
int dummy;
MPI_Irecv(&dummy,
0,
MPI_INT,
sm_sources[i],
tag,
this->comm_sm,
req.data() + i + sm_targets.size());
}
MPI_Waitall(req.size(), req.data(), MPI_STATUSES_IGNORE);
}
namespace internal
{
template <typename T, typename U>
std::vector<std::pair<T, U>>
MPI_Allgather_Pairs(const std::vector<std::pair<T, U>> &src,
const MPI_Comm & comm)
{
int size;
MPI_Comm_size(comm, &size);
std::vector<T> src_1;
std::vector<U> src_2;
for (auto i : src)
{
src_1.push_back(i.first);
src_2.push_back(i.second);
}
unsigned int len_local = src_1.size();
std::vector<int> len_global(
size); // actually unsigned int but MPI wants int
MPI_Allgather(
&len_local,
1,
MPI_INT,
&len_global[0],
1,
dealii::Utilities::MPI::mpi_type_id_for_type<decltype(len_local)>,
comm);
std::vector<int> displs; // actually unsigned int but MPI wants int
displs.push_back(0);
int total_size = 0;
for (auto i : len_global)
{
displs.push_back(i + displs.back());
total_size += i;
}
std::vector<T> dst_1(total_size);
std::vector<U> dst_2(total_size);
MPI_Allgatherv(
src_1.data(),
len_local,
dealii::Utilities::MPI::mpi_type_id_for_type<decltype(src_1[0])>,
dst_1.data(),
len_global.data(),
displs.data(),
dealii::Utilities::MPI::mpi_type_id_for_type<decltype(dst_1[0])>,
comm);
MPI_Allgatherv(
src_2.data(),
len_local,
dealii::Utilities::MPI::mpi_type_id_for_type<decltype(src_2[0])>,
dst_2.data(),
len_global.data(),
displs.data(),
dealii::Utilities::MPI::mpi_type_id_for_type<decltype(dst_2[0])>,
comm);
std::vector<std::pair<T, U>> dst(total_size);
for (unsigned int i = 0; i < dst_1.size(); i++)
dst[i] = {dst_1[i], dst_2[i]};
return dst;
}
} // namespace internal
template <typename ShapeInfo>
Contiguous::Contiguous(const ShapeInfo &shape_info)
: dofs_per_cell(shape_info.dofs_per_cell)
, dofs_per_face(shape_info.dofs_per_face)
, face_to_cell_index_nodal(shape_info.face_to_cell_index_nodal)
{}
inline void
Contiguous::reinit(
const std::vector<dealii::types::global_dof_index> local_cells,
const std::vector<
std::pair<dealii::types::global_dof_index, std::vector<unsigned int>>>
local_ghost_faces,
const MPI_Comm comm,
const MPI_Comm comm_sm,
const bool do_buffering)
{
// fill some information needed by PartitionerBase
this->comm = comm;
this->comm_sm = comm_sm;
this->n_mpi_processes_ = dealii::Utilities::MPI::n_mpi_processes(comm);
this->do_buffering = do_buffering;
AssertThrow(local_cells.size() > 0,
dealii::ExcMessage("No local cells!"));
this->n_local_elements = local_cells.size() * dofs_per_cell;
// 1) determine if ghost faces or ghost cells are needed
const dealii::types::global_dof_index dofs_per_ghost = [&]() {
unsigned int result = dofs_per_face;
for (const auto &ghost_faces : local_ghost_faces)
for (const auto ghost_face : ghost_faces.second)
if (ghost_face == dealii::numbers::invalid_unsigned_int)
result = dofs_per_cell;
return dealii::Utilities::MPI::max(result, comm);
}();
this->dofs_per_ghost = dofs_per_ghost;
// const auto this->comm_sm = create_sm(comm);
const auto sm_procs = hyperdeal::mpi::procs_of_sm(comm, this->comm_sm);
const auto sm_rank = [&]() {
const auto ptr =
std::find(sm_procs.begin(),
sm_procs.end(),
dealii::Utilities::MPI::this_mpi_process(comm));
AssertThrow(ptr != sm_procs.end(),
dealii::ExcMessage("Proc not found!"));
return std::distance(sm_procs.begin(), ptr);
}();
this->sm_rank = sm_rank;
this->sm_size = sm_procs.size();
for (unsigned int i = 0; i < local_cells.size(); i++)
this->maps[local_cells[i]] = {sm_rank, i * dofs_per_cell};
// 2) determine which ghost face is shared or remote
std::vector<
std::pair<dealii::types::global_dof_index, std::vector<unsigned int>>>
local_ghost_faces_remote, local_ghost_faces_shared;
{
const auto n_total_cells = dealii::Utilities::MPI::sum(
static_cast<dealii::types::global_dof_index>(local_cells.size()),
comm);
dealii::IndexSet is_local_cells(n_total_cells);
is_local_cells.add_indices(local_cells.begin(), local_cells.end());
dealii::IndexSet is_ghost_cells(n_total_cells);
for (const auto &ghost_faces : local_ghost_faces)
is_ghost_cells.add_index(ghost_faces.first);
for (unsigned int i = 0; i < local_ghost_faces.size(); i++)
AssertThrow(local_ghost_faces[i].first ==
is_ghost_cells.nth_index_in_set(i),
dealii::ExcMessage("PROBLEM!"));
AssertThrow(
local_ghost_faces.size() == is_ghost_cells.n_elements(),
dealii::ExcMessage(
"Dimensions " + std::to_string(local_ghost_faces.size()) + " " +
std::to_string(is_ghost_cells.n_elements()) + " do not match!"));
std::vector<unsigned int> owning_ranks_of_ghosts(
is_ghost_cells.n_elements());
// set up dictionary
dealii::Utilities::MPI::internal::ComputeIndexOwner::
ConsensusAlgorithmsPayload process(is_local_cells,
is_ghost_cells,
comm,
owning_ranks_of_ghosts,
false);
dealii::Utilities::MPI::ConsensusAlgorithms::Selector<
std::vector<std::pair<dealii::types::global_dof_index,
dealii::types::global_dof_index>>,
std::vector<unsigned int>>
consensus_algorithm;
consensus_algorithm.run(process, comm);
std::map<unsigned int, std::vector<dealii::types::global_dof_index>>
shared_procs_to_cells;
for (unsigned int i = 0; i < owning_ranks_of_ghosts.size(); i++)
{
AssertThrow(dealii::Utilities::MPI::this_mpi_process(comm) !=
owning_ranks_of_ghosts[i],
dealii::ExcMessage(
"Locally owned cells should be not ghosted!"));
const auto ptr = std::find(sm_procs.begin(),
sm_procs.end(),
owning_ranks_of_ghosts[i]);
if (ptr == sm_procs.end())
local_ghost_faces_remote.push_back(local_ghost_faces[i]);
else
{
local_ghost_faces_shared.push_back(local_ghost_faces[i]);
shared_procs_to_cells[std::distance(sm_procs.begin(), ptr)]
.emplace_back(local_ghost_faces[i].first);
}
}
// determine (ghost sm cell) -> (sm rank, offset)
dealii::Utilities::MPI::ConsensusAlgorithms::selector<
std::vector<dealii::types::global_dof_index>,
std::vector<unsigned int>>(
[&]() {
std::vector<unsigned int> result;
for (auto &i : shared_procs_to_cells)
result.push_back(i.first);
return result;
}(),
[&](const auto other_rank) {
return shared_procs_to_cells[other_rank];
},
[&](const auto &other_rank, const auto &buffer_recv) {
std::vector<unsigned int> request_buffer(buffer_recv.size());
for (unsigned int i = 0; i < buffer_recv.size(); i++)
{
const auto value = buffer_recv[i];
const auto ptr =
std::find(local_cells.begin(), local_cells.end(), value);
AssertThrow(ptr != local_cells.end(),
dealii::ExcMessage(
"Cell " + std::to_string(value) + " at index " +
std::to_string(i) + " on rank " +
std::to_string(
dealii::Utilities::MPI::this_mpi_process(
comm)) +
" requested by rank " +
std::to_string(other_rank) + " not found!"));
request_buffer[i] = std::distance(local_cells.begin(), ptr);
}
return request_buffer;
},
[&](const auto other_rank, const auto &recv_buffer) {
for (unsigned int i = 0; i < recv_buffer.size(); i++)
{
const dealii::types::global_dof_index cell =
shared_procs_to_cells[other_rank][i];
const unsigned int offset = recv_buffer[i];
Assert(maps.find(cell) == maps.end(),
dealii::ExcMessage("Cell " + std::to_string(cell) +
" is already in maps!"));
this->maps[cell] = {other_rank, offset * dofs_per_cell};
}
},
this->comm_sm);
}
// 3) merge local_ghost_faces_remote and sort -> ghost_faces_remote
const auto local_ghost_faces_remote_pairs_global =
[&local_ghost_faces_remote, this]() {
std::vector<
std::pair<dealii::types::global_dof_index, unsigned int>>
local_ghost_faces_remote_pairs_local;
// convert vector<pair<U, std::vector<V>>> ->.vector<std::pair<U,
// V>>>
for (const auto &ghost_faces : local_ghost_faces_remote)
for (const auto ghost_face : ghost_faces.second)
local_ghost_faces_remote_pairs_local.emplace_back(
ghost_faces.first, ghost_face);
// collect all on which are shared
std::vector<
std::pair<dealii::types::global_dof_index, unsigned int>>
local_ghost_faces_remote_pairs_global =
internal::MPI_Allgather_Pairs(
local_ghost_faces_remote_pairs_local, this->comm_sm);
// sort
std::sort(local_ghost_faces_remote_pairs_global.begin(),
local_ghost_faces_remote_pairs_global.end());
return local_ghost_faces_remote_pairs_global;
}();
// 4) distributed ghost_faces_remote,
auto distributed_local_ghost_faces_remote_pairs_global =
[&local_ghost_faces_remote_pairs_global, &sm_procs]() {
std::vector<std::vector<
std::pair<dealii::types::global_dof_index, unsigned int>>>
result(sm_procs.size());
unsigned int counter = 0;
const unsigned int faces_per_process =
(local_ghost_faces_remote_pairs_global.size() + sm_procs.size() -
1) /
sm_procs.size();
for (auto p : local_ghost_faces_remote_pairs_global)
result[(counter++) / faces_per_process].push_back(p);
return result;
}();
// revert partitioning of ghost faces (TODO)
{
std::vector<std::pair<dealii::types::global_dof_index, unsigned int>>
local_ghost_faces_remote_pairs_local;
for (const auto &ghost_faces : local_ghost_faces_remote)
for (const auto ghost_face : ghost_faces.second)
local_ghost_faces_remote_pairs_local.emplace_back(
ghost_faces.first, ghost_face);
distributed_local_ghost_faces_remote_pairs_global.clear();
distributed_local_ghost_faces_remote_pairs_global.resize(
sm_procs.size());
distributed_local_ghost_faces_remote_pairs_global[sm_rank] =
local_ghost_faces_remote_pairs_local;
}
// ... update ghost size, and
this->n_ghost_elements =
(distributed_local_ghost_faces_remote_pairs_global[sm_rank].size() +
(do_buffering ?
std::accumulate(local_ghost_faces_shared.begin(),
local_ghost_faces_shared.end(),
std::size_t(0),
[](const std::size_t &a, const auto &b) {
return a + b.second.size();
}) :
std::size_t(0))) *
dofs_per_ghost;
// ... update ghost map
this->maps_ghost = [&]() {
std::map<std::pair<dealii::types::global_dof_index, unsigned int>,
std::pair<unsigned int, unsigned int>>
maps_ghost;
// counter for offset of ghost faces
unsigned int my_offset = local_cells.size() * dofs_per_cell;
// buffering-mode: insert shared faces into maps_ghost
if (do_buffering)
for (const auto &pair : local_ghost_faces_shared)
for (const auto &face : pair.second)
{
maps_ghost[{pair.first, face}] = {sm_rank, my_offset};
my_offset += dofs_per_ghost;
}
// create map (cell, face_no) -> (sm rank, offset)
const auto maps_ghost_inverse =
[&distributed_local_ghost_faces_remote_pairs_global,
&dofs_per_ghost,
this,
&sm_procs,
&my_offset]() {
std::vector<unsigned int> offsets(sm_procs.size());
MPI_Allgather(&my_offset,
1,
dealii::Utilities::MPI::mpi_type_id_for_type<
decltype(my_offset)>,
offsets.data(),
1,
dealii::Utilities::MPI::mpi_type_id_for_type<
decltype(my_offset)>,
this->comm_sm);
std::map<std::pair<unsigned int, unsigned int>,
std::pair<dealii::types::global_dof_index, unsigned int>>
maps_ghost_inverse;
for (unsigned int i = 0; i < sm_procs.size(); i++)
for (unsigned int j = 0;
j < distributed_local_ghost_faces_remote_pairs_global[i]
.size();
j++)
maps_ghost_inverse
[distributed_local_ghost_faces_remote_pairs_global[i][j]] =
{i, offsets[i] + j * dofs_per_ghost};
return maps_ghost_inverse;
}();
// create map (cell, face_no) -> (sm rank, offset) with only
// ghost faces needed for evaluation
for (const auto &i : local_ghost_faces_remote)
for (const auto &j : i.second)
maps_ghost[{i.first, j}] = maps_ghost_inverse.at({i.first, j});
for (const auto &i :
distributed_local_ghost_faces_remote_pairs_global[sm_rank])
maps_ghost[i] = maps_ghost_inverse.at(i);
return maps_ghost;
}();
// buffering-mode: pre-compute information for memcopy of ghost faces
std::vector<std::array<LocalDoFType, 5>> ghost_list_shared_precomp;
std::vector<std::array<LocalDoFType, 5>> maps_ghost_inverse_precomp;
if (do_buffering)
{
std::map<unsigned int, std::vector<std::array<LocalDoFType, 5>>>
send_data;
for (const auto &pair : local_ghost_faces_shared)
for (const auto &face : pair.second)
{
const auto ptr1 = maps.find(pair.first);
AssertThrow(ptr1 != maps.end(),
dealii::ExcMessage("Entry not found!"));
const auto ptr2 = maps_ghost.find({pair.first, face});
AssertThrow(ptr2 != maps_ghost.end(),
dealii::ExcMessage("Entry not found!"));
std::array<LocalDoFType, 5> v{{ptr1->second.first,
ptr1->second.second,
face,
ptr2->second.first,
ptr2->second.second}};
ghost_list_shared_precomp.push_back(v);
send_data[ptr1->second.first].push_back(v);
}
dealii::Utilities::MPI::ConsensusAlgorithms::selector<
std::vector<LocalDoFType>>(
[&]() {
std::vector<unsigned int> result;
for (auto &i : send_data)
result.push_back(i.first);
return result;
}(),
[&](const auto other_rank) {
std::vector<LocalDoFType> send_buffer;
for (const auto &i : send_data[other_rank])
for (const auto &j : i)
send_buffer.push_back(j);
return send_buffer;
},
[&](const auto & /*other_rank*/, const auto &buffer_recv) {
for (unsigned int i = 0; i < buffer_recv.size(); i += 5)
maps_ghost_inverse_precomp.push_back({{buffer_recv[i],
buffer_recv[i + 1],
buffer_recv[i + 2],
buffer_recv[i + 3],
buffer_recv[i + 4]}});
},
this->comm_sm);
std::sort(maps_ghost_inverse_precomp.begin(),
maps_ghost_inverse_precomp.end());
}
// rank -> pair(offset, size)
std::map<unsigned int, std::pair<unsigned int, unsigned int>>
receive_info;
std::map<unsigned int, std::vector<std::array<unsigned int, 3>>>
requests_from_relevant_precomp;
// 5) setup communication patterns (during update_ghost_values &
// compress)
[&local_cells,
&distributed_local_ghost_faces_remote_pairs_global,
&sm_rank,
&comm,
&dofs_per_ghost](auto & requests_from_relevant_precomp,
auto & receive_info,
const auto &maps,
const auto &maps_ghost) {
// determine of the owner of cells of remote ghost faces
const auto n_total_cells = dealii::Utilities::MPI::sum(
static_cast<dealii::types::global_dof_index>(local_cells.size()),
comm);
// owned cells (TODO: generalize so that local_cells is also
// partitioned)
dealii::IndexSet is_local_cells(n_total_cells);
is_local_cells.add_indices(local_cells.begin(), local_cells.end());
// needed (ghost) cell
dealii::IndexSet is_ghost_cells(n_total_cells);
for (const auto &ghost_faces :
distributed_local_ghost_faces_remote_pairs_global[sm_rank])
is_ghost_cells.add_index(ghost_faces.first);
// determine rank of (ghost) cells
const auto owning_ranks_of_ghosts = [&]() {
std::vector<unsigned int> owning_ranks_of_ghosts(
is_ghost_cells.n_elements());
dealii::Utilities::MPI::internal::ComputeIndexOwner::
ConsensusAlgorithmsPayload process(is_local_cells,
is_ghost_cells,
comm,
owning_ranks_of_ghosts,
false);
dealii::Utilities::MPI::ConsensusAlgorithms::Selector<
std::vector<std::pair<dealii::types::global_dof_index,
dealii::types::global_dof_index>>,
std::vector<unsigned int>>
consensus_algorithm;
consensus_algorithm.run(process, comm);
return owning_ranks_of_ghosts;
}();
// determine targets
const auto send_ranks = [&]() {
std::set<unsigned int> send_ranks_set;
for (const auto &i : owning_ranks_of_ghosts)
send_ranks_set.insert(i);
const std::vector<unsigned int> send_ranks(send_ranks_set.begin(),
send_ranks_set.end());
return send_ranks;
}();
// collect ghost faces (separated for each target)
const auto send_data = [&]() {
std::vector<std::vector<std::pair<dealii::types::global_dof_index,
dealii::types::global_dof_index>>>
send_data(send_ranks.size());
unsigned int index = 0;
unsigned int index_cell = dealii::numbers::invalid_unsigned_int;
for (const auto &ghost_faces :
distributed_local_ghost_faces_remote_pairs_global[sm_rank])
{
if (index_cell != ghost_faces.first)
{
index_cell = ghost_faces.first;
const unsigned int index_rank =
owning_ranks_of_ghosts[is_ghost_cells.index_within_set(
ghost_faces.first)];
index = std::distance(send_ranks.begin(),
std::find(send_ranks.begin(),
send_ranks.end(),
index_rank));
}
send_data[index].emplace_back(ghost_faces.first,
ghost_faces.second);
}
return send_data;
}();
// send ghost faces to the owners
std::vector<MPI_Request> send_requests(send_ranks.size());
for (unsigned int i = 0; i < send_ranks.size(); i++)
{
MPI_Isend(send_data[i].data(),
2 * send_data[i].size(),
dealii::Utilities::MPI::mpi_type_id_for_type<
dealii::types::global_dof_index>,
send_ranks[i],
105,
comm,
send_requests.data() + i);
receive_info[send_ranks[i]] = {
send_data[i].size() * dofs_per_ghost,
maps_ghost.at(send_data[i][0]).second};
}
MPI_Barrier(comm);
const auto targets = dealii::Utilities::MPI::
compute_point_to_point_communication_pattern(comm, send_ranks);
// process requests
for (unsigned int i = 0; i < targets.size(); i++)
{
// wait for any request
MPI_Status status;
auto ierr = MPI_Probe(MPI_ANY_SOURCE, 105, comm, &status);
AssertThrowMPI(ierr);
// determine number of ghost faces * 2 (since we are considering
// pairs)
int len;
MPI_Get_count(&status,
dealii::Utilities::MPI::mpi_type_id_for_type<
dealii::types::global_dof_index>,
&len);
AssertThrow(len % 2 == 0,
dealii::ExcMessage("Length " + std::to_string(len) +
" is not a multiple of two!"));
// allocate memory for the incoming vector
std::vector<std::pair<dealii::types::global_dof_index,
dealii::types::global_dof_index>>
recv_data(len / 2);
// receive data
ierr = MPI_Recv(recv_data.data(),
len,
dealii::Utilities::MPI::mpi_type_id_for_type<
dealii::types::global_dof_index>,
status.MPI_SOURCE,
status.MPI_TAG,
comm,
&status);
AssertThrowMPI(ierr);
// setup pack and unpack info
requests_from_relevant_precomp[status.MPI_SOURCE] = [&]() {
std::vector<std::array<unsigned int, 3>> temp(len / 2);
for (unsigned int i = 0; i < static_cast<unsigned int>(len) / 2;
i++)
{
const CellIdType cell = recv_data[i].first;
const unsigned int face_no = recv_data[i].second;
const auto ptr = maps.find(cell);
AssertThrow(ptr != maps.end(),
dealii::ExcMessage("Entry " +
std::to_string(cell) +
" not found!"));
temp[i] = std::array<unsigned int, 3>{
{ptr->second.first,
(unsigned int)ptr->second.second,
face_no}};
}
return temp;
}();
}
// make sure requests have been sent away
MPI_Waitall(send_requests.size(),
send_requests.data(),
MPI_STATUSES_IGNORE);
}(requests_from_relevant_precomp,
receive_info,
this->maps,
this->maps_ghost);
{
recv_ptr.clear();
recv_size.clear();
recv_ranks.clear();
for (const auto &i : receive_info)
{
recv_ranks.push_back(i.first);
recv_size.push_back(i.second.first);
recv_ptr.push_back(i.second.second -
local_cells.size() * dofs_per_cell);
}
}
{
// TODO: clear
send_ptr.push_back(0);
for (const auto &i : requests_from_relevant_precomp)
{
send_ranks.push_back(i.first);
for (const auto &j : i.second)
{
AssertThrow(j[0] == sm_rank,
dealii::StandardExceptions::ExcNotImplemented());
send_data_id.push_back(j[1]);
send_data_face_no.push_back(j[2]);
}
send_ptr.push_back(send_data_id.size());
}
}
{
std::set<unsigned int> temp;
for (const auto &i : maps)
if (i.second.first != sm_rank)
temp.insert(i.second.first);
for (const auto &i : temp)
this->sm_sources.push_back(i);
this->sm_targets = dealii::Utilities::MPI::
compute_point_to_point_communication_pattern(this->comm_sm,
sm_sources);
}
if (do_buffering)
{
auto temp = ghost_list_shared_precomp;
std::sort(temp.begin(), temp.end());
std::vector<
std::vector<std::array<dealii::types::global_dof_index, 3>>>
temp_(sm_size);
for (auto t : temp)
{
AssertThrow(sm_rank == t[3],
dealii::StandardExceptions::ExcNotImplemented());
temp_[t[0]].emplace_back(
std::array<dealii::types::global_dof_index, 3>{
{t[1], t[2], t[4]}});
}
sm_send_ptr.push_back(0);
for (unsigned int i = 0; i < temp_.size(); i++)
{
if (temp_[i].size() == 0)
continue;
sm_send_rank.push_back(i);
for (const auto &v : temp_[i])
{
sm_send_offset_1.push_back(v[2] - local_cells.size() *
dofs_per_cell);
sm_send_offset_2.push_back(v[0]);
sm_send_no.push_back(v[1]);
}
sm_send_ptr.push_back(sm_send_no.size());
}
AssertThrow(sm_send_rank.size() == sm_sources.size(),
dealii::StandardExceptions::ExcNotImplemented());
}
if (do_buffering)
{
auto temp = maps_ghost_inverse_precomp;
std::sort(temp.begin(), temp.end());
std::vector<
std::vector<std::array<dealii::types::global_dof_index, 3>>>
temp_(sm_size);
for (auto t : temp)
{
AssertThrow(sm_rank == t[0],
dealii::StandardExceptions::ExcNotImplemented());
temp_[t[3]].emplace_back(
std::array<dealii::types::global_dof_index, 3>{
{t[4], t[2], t[1]}});
}
sm_recv_ptr.push_back(0);
for (unsigned int i = 0; i < temp_.size(); i++)
{
if (temp_[i].size() == 0)
continue;
sm_recv_rank.push_back(i);
for (const auto &v : temp_[i])
{
sm_recv_offset_1.push_back(v[2]);
sm_recv_offset_2.push_back(v[0]);
sm_recv_no.push_back(v[1]);
}
sm_recv_ptr.push_back(sm_recv_no.size());
}
AssertThrow(sm_recv_rank.size() == sm_targets.size(),
dealii::StandardExceptions::ExcNotImplemented());
}
}
template <typename Number>
void
Contiguous::export_to_ghosted_array_start_impl(
const unsigned int communication_channel,
const dealii::ArrayView<const Number> &locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
const dealii::ArrayView<Number> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
(void)shared_arrays;
AssertThrow(temporary_storage.size() ==
send_ptr.back() * dofs_per_ghost,
dealii::StandardExceptions::ExcDimensionMismatch(
temporary_storage.size(),
send_ptr.back() * dofs_per_ghost));
requests.resize(sm_sources.size() + sm_targets.size() +
recv_ranks.size() + send_ranks.size());
// 1) notify relevant shared processes that local data is available
if (sm_size > 1)
{
int dummy;
for (unsigned int i = 0; i < sm_targets.size(); i++)
MPI_Isend(&dummy,
0,
MPI_INT,
sm_targets[i],
communication_channel + 21,
this->comm_sm,
requests.data() + i + sm_sources.size());
for (unsigned int i = 0; i < sm_sources.size(); i++)
MPI_Irecv(&dummy,
0,
MPI_INT,
sm_sources[i],
communication_channel + 21,
this->comm_sm,
requests.data() + i);
}
// 2) start receiving form (remote) processes
{
for (unsigned int i = 0; i < recv_ranks.size(); i++)
MPI_Irecv(ghost_array.data() + recv_ptr[i],
recv_size[i],
MPI_DOUBLE,
recv_ranks[i],
communication_channel + 22,
comm,
requests.data() + i + sm_sources.size() +
sm_targets.size());
}
// 3) fill buffers and start sending to (remote) processes
for (unsigned int c = 0; c < send_ranks.size(); c++)
{
auto buffer =
temporary_storage.data() + send_ptr[c] * dofs_per_ghost;
for (unsigned int i = send_ptr[c]; i < send_ptr[c + 1];
i++, buffer += dofs_per_ghost)
if (dofs_per_ghost == dofs_per_face)
{
auto *__restrict dst = buffer;
const auto *__restrict src =
locally_owned_array.data() + send_data_id[i];
const auto *__restrict idx =
face_to_cell_index_nodal[send_data_face_no[i]].data();
for (unsigned int i = 0; i < dofs_per_face; i++)
dst[i] = src[idx[i]];
}
else if (dofs_per_ghost == dofs_per_cell)
{
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
}
MPI_Issend(temporary_storage.data() + send_ptr[c] * dofs_per_ghost,
(send_ptr[c + 1] - send_ptr[c]) * dofs_per_ghost,
MPI_DOUBLE,
send_ranks[c],
communication_channel + 22,
comm,
requests.data() + c + sm_sources.size() +
sm_targets.size() + recv_ranks.size());
}
}
template <typename Number>
void
Contiguous::export_to_ghosted_array_finish_impl(
const dealii::ArrayView<const Number> & locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
std::vector<MPI_Request> & requests) const
{
(void)locally_owned_array;
AssertDimension(requests.size(),
sm_sources.size() + sm_targets.size() +
recv_ranks.size() + send_ranks.size());
if (do_buffering) // deal with shared faces if buffering is requested
{
// update ghost values of shared cells (if requested)
for (unsigned int c = 0; c < sm_sources.size(); c++)
{
int i;
MPI_Status status;
const auto ierr =
MPI_Waitany(sm_sources.size(), requests.data(), &i, &status);
AssertThrowMPI(ierr);
for (unsigned int j = sm_send_ptr[i]; j < sm_send_ptr[i + 1];
j++)
if (dofs_per_ghost == dofs_per_face)
{
auto *__restrict dst =
ghost_array.data() + sm_send_offset_1[j];
const auto *__restrict src =
shared_arrays[sm_send_rank[i]].data() +
sm_send_offset_2[j];
const auto *__restrict idx =
face_to_cell_index_nodal[sm_send_no[j]].data();
for (unsigned int i = 0; i < dofs_per_face; i++)
dst[i] = src[idx[i]];
}
else if (dofs_per_ghost == dofs_per_cell)
{
AssertThrow(
false, dealii::StandardExceptions::ExcNotImplemented());
}
}
}
MPI_Waitall(requests.size(), requests.data(), MPI_STATUSES_IGNORE);
}
template <typename Number>
void
Contiguous::export_to_ghosted_array_finish_0(
const dealii::ArrayView<const Number> & locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
std::vector<MPI_Request> & requests) const
{
(void)locally_owned_array;
AssertDimension(requests.size(),
sm_sources.size() + sm_targets.size() +
recv_ranks.size() + send_ranks.size());
if (do_buffering) // deal with shared faces if buffering is requested
{
// update ghost values of shared cells (if requested)
for (unsigned int c = 0; c < sm_sources.size(); c++)
{
int i;
MPI_Status status;
const auto ierr =
MPI_Waitany(sm_sources.size(), requests.data(), &i, &status);
AssertThrowMPI(ierr);
for (unsigned int j = sm_send_ptr[i]; j < sm_send_ptr[i + 1];
j++)
if (dofs_per_ghost == dofs_per_face)
{
auto *__restrict dst =
ghost_array.data() + sm_send_offset_1[j];
const auto *__restrict src =
shared_arrays[sm_send_rank[i]].data() +
sm_send_offset_2[j];
const auto *__restrict idx =
face_to_cell_index_nodal[sm_send_no[j]].data();
for (unsigned int i = 0; i < dofs_per_face; i++)
dst[i] = src[idx[i]];
}
else if (dofs_per_ghost == dofs_per_cell)
{
AssertThrow(
false, dealii::StandardExceptions::ExcNotImplemented());
}
}
}
else
{
MPI_Waitall(sm_sources.size(),
requests.data(),
MPI_STATUSES_IGNORE);
}
}
template <typename Number>
void
Contiguous::export_to_ghosted_array_finish_1(
const dealii::ArrayView<const Number> & locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
std::vector<MPI_Request> & requests) const
{
(void)locally_owned_array;
(void)shared_arrays;
(void)ghost_array;
AssertDimension(requests.size(),
sm_sources.size() + sm_targets.size() +
recv_ranks.size() + send_ranks.size());
MPI_Waitall(requests.size(), requests.data(), MPI_STATUSES_IGNORE);
}
template <typename Number>
void
Contiguous::import_from_ghosted_array_start_impl(
const dealii::VectorOperation::values operation,
const unsigned int communication_channel,
const dealii::ArrayView<const Number> &locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
const dealii::ArrayView<Number> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
(void)locally_owned_array;
(void)shared_arrays;
(void)communication_channel;
(void)ghost_array;
AssertThrow(operation == dealii::VectorOperation::add,
dealii::ExcMessage("Not yet implemented."));
AssertThrow(temporary_storage.size() ==
send_ptr.back() * dofs_per_ghost,
dealii::StandardExceptions::ExcDimensionMismatch(
temporary_storage.size(),
send_ptr.back() * dofs_per_ghost));
requests.resize(sm_sources.size() + sm_targets.size() +
recv_ranks.size() + send_ranks.size());
// 1) notify relevant shared processes that data is available
if (sm_size > 1)
{
int dummy;
for (unsigned int i = 0; i < sm_sources.size(); i++)
MPI_Isend(&dummy,
0,
MPI_INT,
sm_sources[i],
communication_channel + 21,
this->comm_sm,
requests.data() + i);
for (unsigned int i = 0; i < sm_targets.size(); i++)
MPI_Irecv(&dummy,
0,
MPI_INT,
sm_targets[i],
communication_channel + 21,
this->comm_sm,
requests.data() + i + sm_sources.size());
}
// request receive
{
for (unsigned int i = 0; i < recv_ranks.size(); i++)
MPI_Isend(ghost_array.data() + recv_ptr[i],
recv_size[i],
MPI_DOUBLE,
recv_ranks[i],
0,
comm,
requests.data() + i + sm_sources.size() +
sm_targets.size());
}
// fill buffers and request send
for (unsigned int i = 0; i < send_ranks.size(); i++)
MPI_Irecv(temporary_storage.data() + send_ptr[i] * dofs_per_ghost,
(send_ptr[i + 1] - send_ptr[i]) * dofs_per_ghost,
MPI_DOUBLE,
send_ranks[i],
0,
comm,
requests.data() + i + sm_sources.size() +
sm_targets.size() + recv_ranks.size());
}
template <typename Number>
void
Contiguous::import_from_ghosted_array_finish_impl(
const dealii::VectorOperation::values operation,
const dealii::ArrayView<Number> & locally_owned_array,
const std::vector<dealii::ArrayView<const Number>> &shared_arrays,
const dealii::ArrayView<Number> & ghost_array,
const dealii::ArrayView<const Number> & temporary_storage,
std::vector<MPI_Request> & requests) const
{
(void)ghost_array;
AssertThrow(operation == dealii::VectorOperation::add,
dealii::ExcMessage("Not yet implemented."));
AssertThrow(temporary_storage.size() ==
send_ptr.back() * dofs_per_ghost,
dealii::StandardExceptions::ExcDimensionMismatch(
temporary_storage.size(),
send_ptr.back() * dofs_per_ghost));
AssertDimension(requests.size(),
sm_sources.size() + sm_targets.size() +
recv_ranks.size() + send_ranks.size());
// 1) compress for shared faces
if (do_buffering)
{
for (unsigned int c = 0; c < sm_targets.size(); c++)
{
int i;
MPI_Status status;
const auto ierr =
MPI_Waitany(sm_targets.size(),
requests.data() + sm_sources.size(),
&i,
&status);
AssertThrowMPI(ierr);
for (unsigned int j = sm_recv_ptr[i]; j < sm_recv_ptr[i + 1];
j++)
if (dofs_per_ghost == dofs_per_face)
{
auto *__restrict dst =
locally_owned_array.data() + sm_recv_offset_1[j];
const auto *__restrict src =
shared_arrays[sm_recv_rank[i]].data() +
sm_recv_offset_2[j];
const auto *__restrict idx =
face_to_cell_index_nodal[sm_recv_no[j]].data();
for (unsigned int i = 0; i < dofs_per_face; i++)
dst[idx[i]] += src[i];
}
else if (dofs_per_ghost == dofs_per_cell)
{
AssertThrow(
false, dealii::StandardExceptions::ExcNotImplemented());
}
}
}
// 2) receive data and compress for remote faces
for (unsigned int c = 0; c < send_ranks.size(); c++)
{
int r;
MPI_Status status;
const auto ierr =
MPI_Waitany(send_ranks.size(),
requests.data() + sm_sources.size() +
sm_targets.size() + recv_ranks.size(),
&r,
&status);
AssertThrowMPI(ierr);
auto buffer =
temporary_storage.data() + send_ptr[r] * dofs_per_ghost;
for (unsigned int i = send_ptr[r]; i < send_ptr[r + 1];
i++, buffer += dofs_per_ghost)
if (dofs_per_ghost == dofs_per_face)
{
auto *__restrict dst =
locally_owned_array.data() + send_data_id[i];
const auto *__restrict src = buffer;
const auto *__restrict idx =
face_to_cell_index_nodal[send_data_face_no[i]].data();
for (unsigned int i = 0; i < dofs_per_face; i++)
dst[idx[i]] += src[i];
}
else if (dofs_per_ghost == dofs_per_cell)
{
AssertThrow(false,
dealii::StandardExceptions::ExcNotImplemented());
}
}
MPI_Waitall(requests.size(), requests.data(), MPI_STATUSES_IGNORE);
}
inline const std::map<dealii::types::global_dof_index,
std::pair<unsigned int, unsigned int>> &
Contiguous::get_maps() const
{
return maps;
}
inline const std::map<
std::pair<dealii::types::global_dof_index, unsigned int>,
std::pair<unsigned int, unsigned int>> &
Contiguous::get_maps_ghost() const
{
return maps_ghost;
}
inline std::size_t
Contiguous::memory_consumption() const
{
// [TODO] not counting maps and maps_ghost
return dealii::MemoryConsumption::memory_consumption(send_ranks) +
dealii::MemoryConsumption::memory_consumption(send_ptr) +
dealii::MemoryConsumption::memory_consumption(send_data_id) +
dealii::MemoryConsumption::memory_consumption(
send_data_face_no) +
dealii::MemoryConsumption::memory_consumption(recv_ranks) +
dealii::MemoryConsumption::memory_consumption(recv_ptr) +
dealii::MemoryConsumption::memory_consumption(recv_size) +
dealii::MemoryConsumption::memory_consumption(sm_targets) +
dealii::MemoryConsumption::memory_consumption(sm_sources) +
dealii::MemoryConsumption::memory_consumption(sm_send_ptr) +
dealii::MemoryConsumption::memory_consumption(sm_send_rank) +
dealii::MemoryConsumption::memory_consumption(sm_send_offset_1) +
dealii::MemoryConsumption::memory_consumption(sm_send_offset_2) +
dealii::MemoryConsumption::memory_consumption(sm_send_no) +
dealii::MemoryConsumption::memory_consumption(sm_recv_ptr) +
dealii::MemoryConsumption::memory_consumption(sm_recv_rank) +
dealii::MemoryConsumption::memory_consumption(sm_recv_offset_1) +
dealii::MemoryConsumption::memory_consumption(sm_recv_offset_2) +
dealii::MemoryConsumption::memory_consumption(sm_recv_no);
}
} // namespace VectorDataExchange
} // namespace MatrixFreeFunctions
} // namespace internal
DEAL_II_NAMESPACE_CLOSE
#endif
| 71,644
|
C++
|
.h
| 1,542
| 31.103761
| 80
| 0.494004
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,153
|
advection_operation.h
|
hyperdeal_hyperdeal/include/hyper.deal/operators/advection/advection_operation.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_OPERATORS_ADVECTIONOPERATION
#define HYPERDEAL_NDIM_OPERATORS_ADVECTIONOPERATION
#include <hyper.deal/base/config.h>
#include <deal.II/matrix_free/evaluation_kernels.h>
#include <hyper.deal/base/dynamic_convergence_table.h>
#include <hyper.deal/matrix_free/evaluation_kernels.h>
#include <hyper.deal/matrix_free/fe_evaluation_cell.h>
#include <hyper.deal/matrix_free/fe_evaluation_cell_inverse.h>
#include <hyper.deal/matrix_free/fe_evaluation_face.h>
#include <hyper.deal/matrix_free/matrix_free.h>
#include <hyper.deal/matrix_free/tools.h>
#include <hyper.deal/operators/advection/advection_operation_parameters.h>
#include <hyper.deal/operators/advection/boundary_descriptor.h>
namespace hyperdeal
{
namespace advection
{
enum class AdvectionOperationEvaluationLevel
{
cell,
all_without_neighbor_load,
all
};
/**
* Advection operator. It is defined by a velocity field and by boundary
* conditions.
*/
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorType,
typename VelocityField,
typename VectorizedArrayType>
class AdvectionOperation
{
public:
using This = AdvectionOperation<dim_x,
dim_v,
degree,
n_points,
Number,
VectorType,
VelocityField,
VectorizedArrayType>;
using VNumber = VectorizedArrayType;
static const int dim = dim_x + dim_v;
static const dealii::internal::EvaluatorVariant tensorproduct =
dealii::internal::EvaluatorVariant::evaluate_evenodd;
using FECellEval =
FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>;
using FEFaceEval =
FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>;
using FECellEval_inv =
FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>;
/**
* Constructor
*/
AdvectionOperation(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
DynamicConvergenceTable & table)
: data(data)
, table(table)
, do_collocation(false)
{}
/**
* Set boundary condition and velocity field as well as set up internal
* data structures.
*/
void
reinit(
std::shared_ptr<BoundaryDescriptor<dim, Number>> boundary_descriptor,
std::shared_ptr<VelocityField> velocity_field,
const AdvectionOperationParamters additional_data)
{
this->factor_skew = additional_data.factor_skew;
this->boundary_descriptor = boundary_descriptor;
this->velocity_field = velocity_field;
AssertDimension(
(data.get_matrix_free_x().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation),
(data.get_matrix_free_v().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation));
const bool do_collocation =
data.get_matrix_free_x().get_shape_info(0, 0).data[0].element_type ==
dealii::internal::MatrixFreeFunctions::ElementType::
tensor_symmetric_collocation;
this->do_collocation = do_collocation;
// clang-format off
phi_cell.reset(new FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, 0, 0, 0, 0));
phi_cell_inv.reset(new FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>(data, 0, 0, 0, 0));
phi_cell_inv_co.reset(new FEEvaluationInverse<dim_x, dim_v, degree, degree + 1, Number, VNumber>(data, 0, 0, do_collocation ? 0 : 1, do_collocation ? 0 : 1));
phi_face_m.reset(new FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, true, 0, 0, 0, 0));
phi_face_p.reset(new FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>(data, false, 0, 0, 0, 0));
// clang-format on
}
/**
* Apply operator. Depending on configuration ECL or FCL.
*/
template <AdvectionOperationEvaluationLevel eval_level =
AdvectionOperationEvaluationLevel::all>
void
apply(VectorType & dst,
const VectorType &src,
const Number time,
Timers * timers = nullptr)
{
// set time of boundary functions
boundary_descriptor->set_time(time);
// TODO: also for velocity field
// loop over all cells/faces in phase-space
if (!data.is_ecl_supported()) // FCL
{
if (timers != nullptr)
timers->enter("FCL");
// advection operator
{
hyperdeal::ScopedTimerWrapper timer(timers, "advection");
if (timers != nullptr)
timers->enter("advection");
data.loop(&This::local_apply_cell,
&This::local_apply_face,
&This::local_apply_boundary,
this,
dst,
src,
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values,
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values,
timers);
if (timers != nullptr)
timers->leave();
}
// inverse-mass matrix operator
{
hyperdeal::ScopedTimerWrapper timer(timers, "mass");
data.cell_loop(&This::local_apply_inverse_mass_matrix,
this,
dst,
dst);
}
if (timers != nullptr)
timers->leave();
}
else // ECL
{
if (timers != nullptr)
timers->enter("ECL");
// advection and inverse-mass matrix operator in one go
data.loop_cell_centric(
&This::local_apply_advect_and_inverse_mass_matrix<eval_level>,
this,
dst,
src,
eval_level == AdvectionOperationEvaluationLevel::all ?
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::values :
MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::
DataAccessOnFaces::none,
timers);
if (timers != nullptr)
timers->leave();
}
}
private:
using ID =
typename MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>::ID;
/**
* Advection + inverse mass-matrix cell operation -> ECL.
*/
template <AdvectionOperationEvaluationLevel eval_level =
AdvectionOperationEvaluationLevel::all>
void
local_apply_advect_and_inverse_mass_matrix(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
VectorType & dst,
const VectorType & src,
const ID cell)
{
(void)data;
auto &phi = *this->phi_cell;
auto &phi_m = *this->phi_face_m;
auto &phi_p = *this->phi_face_p;
auto &phi_inv = *this->phi_cell_inv;
// get data and scratch
VNumber *data_ptr = phi.get_data_ptr();
VNumber *data_ptr1 = phi_m.get_data_ptr();
VNumber *data_ptr2 = phi_p.get_data_ptr();
VNumber *data_ptr_inv = phi_inv.get_data_ptr();
// initialize tensor product kernels
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
n_points,
VNumber,
Number>
eval(*phi.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim - 1,
degree + 1,
n_points,
VNumber,
Number>
eval_face(*phi.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
n_points,
n_points,
VNumber,
Number>
eval_(dealii::AlignedVector<Number>(),
*phi.get_shape_gradients(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
n_points,
VNumber,
Number>
eval_inv(dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>(),
data.get_matrix_free_x()
.get_shape_info()
.data[0]
.inverse_shape_values_eo);
// clang-format off
// 1) advection: cell contribution
{
this->velocity_field->reinit(cell);
// load from global structure
phi.reinit(cell);
phi.read_dof_values(src);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 1) eval.template values<0, true, false>(data_ptr, data_ptr);
if (dim >= 2) eval.template values<1, true, false>(data_ptr, data_ptr);
if (dim >= 3) eval.template values<2, true, false>(data_ptr, data_ptr);
if (dim >= 4) eval.template values<3, true, false>(data_ptr, data_ptr);
if (dim >= 5) eval.template values<4, true, false>(data_ptr, data_ptr);
if (dim >= 6) eval.template values<5, true, false>(data_ptr, data_ptr);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim,
degree + 1,
n_points>::
do_forward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
data_ptr,
data_ptr);
}
}
// copy quadrature values into buffer
VNumber *buffer = phi_cell_inv->get_data_ptr();
if(eval_level != AdvectionOperationEvaluationLevel::cell)
for (auto i = 0u; i < dealii::Utilities::pow<unsigned int>(n_points, dim); i++)
buffer[i] = data_ptr[i];
// x-space
{
dealii::AlignedVector<VNumber> scratch_data_array;
scratch_data_array.resize_fast(dealii::Utilities::pow(n_points, dim) * dim_x);
VNumber *tempp = scratch_data_array.begin();
if(factor_skew != 0.0)
{
if (dim_x >= 1) eval_.template gradients<0, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 0);
if (dim_x >= 2) eval_.template gradients<1, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 1);
if (dim_x >= 3) eval_.template gradients<2, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 2);
}
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
VNumber grad_in[dim_x];
const auto vel = velocity_field->evaluate_x(q, qx, qv);
if(factor_skew != 0.0)
phi.template submit_value<false>(data_ptr, - factor_skew * (phi.get_gradient_x(tempp, q, qx, qv) * vel), q, qx, qv);
if (factor_skew != 1.0)
{
for (int d = 0; d < dim_x; d++)
grad_in[d] = (1.0-factor_skew) * buffer[q] * vel[d];
phi.submit_gradient_x(tempp, grad_in, q, qx, qv);
}
}
if(factor_skew != 1.0)
{
if (dim_x >= 1 && (factor_skew != 0.0))
eval_.template gradients<0, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
else if (dim_x >= 1)
eval_.template gradients<0, false, false>(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
if (dim_x >= 2) eval_.template gradients<1, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 1, data_ptr);
if (dim_x >= 3) eval_.template gradients<2, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 2, data_ptr);
}
}
// v-space
{
dealii::AlignedVector<VNumber> scratch_data_array;
scratch_data_array.resize_fast(dealii::Utilities::pow(n_points, dim) * dim_v);
VNumber *tempp = scratch_data_array.begin();
if(factor_skew != 0.0)
{
if (dim_v >= 1) eval_.template gradients<0 + dim_x, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 0);
if (dim_v >= 2) eval_.template gradients<1 + dim_x, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 1);
if (dim_v >= 3) eval_.template gradients<2 + dim_x, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 2);
}
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
VNumber grad_in[dim_v];
const auto vel = velocity_field->evaluate_v(q, qx, qv);
if(factor_skew != 0.0)
phi.template submit_value<true>(data_ptr, - factor_skew * (phi.get_gradient_v(tempp, q, qx, qv) * vel), q, qx, qv);
if (factor_skew != 1.0)
{
for (int d = 0; d < dim_v; d++)
grad_in[d] = (1.0-factor_skew) * buffer[q] * vel[d];
phi.submit_gradient_v(tempp, grad_in, q, qx, qv);
}
}
if(factor_skew != 1.0)
{
if (dim_v >= 1) eval_.template gradients<0 + dim_x, false, true>(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
if (dim_v >= 2) eval_.template gradients<1 + dim_x, false, true>(tempp + dealii::Utilities::pow(n_points, dim) * 1, data_ptr);
if (dim_v >= 3) eval_.template gradients<2 + dim_x, false, true>(tempp + dealii::Utilities::pow(n_points, dim) * 2, data_ptr);
}
}
}
// 2) advection: faces
if(eval_level != AdvectionOperationEvaluationLevel::cell)
for (auto face = 0u; face < dim * 2; face++)
{
this->velocity_field->reinit_face(cell, face);
// load negative side from buffer
phi_m.reinit(cell, face);
const auto bid = data.get_faces_by_cells_boundary_id(cell, face);
// load positive side from global structure
if(bid == dealii::numbers::internal_face_boundary_id)
{
phi_p.reinit(cell, face);
if(eval_level == AdvectionOperationEvaluationLevel::all)
phi_p.read_dof_values(src);
}
if(do_collocation == false)
{
hyperdeal::internal::FEFaceNormalEvaluationImpl<dim_x, dim_v, n_points - 1, Number>::template interpolate_quadrature<true, false>(1, dealii::EvaluationFlags::values, data.get_matrix_free_x().get_shape_info(), /*out=*/data_ptr_inv, /*in=*/data_ptr1, face);
if(degree + 1 == n_points)
{
if (dim >= 2) eval_face.template values<0, true, false>(data_ptr2, data_ptr2);
if (dim >= 3) eval_face.template values<1, true, false>(data_ptr2, data_ptr2);
if (dim >= 4) eval_face.template values<2, true, false>(data_ptr2, data_ptr2);
if (dim >= 5) eval_face.template values<3, true, false>(data_ptr2, data_ptr2);
if (dim >= 6) eval_face.template values<4, true, false>(data_ptr2, data_ptr2);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::
do_forward(1 ,data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
data_ptr2,
data_ptr2);
}
}
else
{
phi_m.read_dof_values_from_buffer(this->phi_cell_inv->get_data_ptr());
}
if(bid == dealii::numbers::internal_face_boundary_id)
{
if (face < dim_x * 2)
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x - 1); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_x(q, qx, qv) * phi_m.get_normal_vector_x(qx);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::X>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
else
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v - 1); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_v(q, qx, qv) * phi_m.get_normal_vector_v(qv);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::V>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
}
else
{
const auto boundary_pair = boundary_descriptor->get_boundary(bid);
if (face < dim_x * 2)
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x - 1); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = boundary_pair.first == BoundaryType::DirichletHomogenous ?
(-u_minus) :
(-u_minus + 2.0 * hyperdeal::MatrixFreeTools::evaluate_scalar_function(phi_m.template get_quadrature_point<ID::SpaceType::X>(qx, qv), *boundary_pair.second, phi_m.n_vectorization_lanes_filled()));
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_x(q, qx, qv) * phi_m.get_normal_vector_x(qx);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::X>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
else
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v - 1); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = boundary_pair.first == BoundaryType::DirichletHomogenous ?
(-u_minus) :
(-u_minus + 2.0 * hyperdeal::MatrixFreeTools::evaluate_scalar_function(phi_m.template get_quadrature_point<ID::SpaceType::V>(qx, qv), *boundary_pair.second, phi_m.n_vectorization_lanes_filled()));
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_v(q, qx, qv) * phi_m.get_normal_vector_v(qv);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::V>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
}
if(do_collocation == false)
hyperdeal::internal::FEFaceNormalEvaluationImpl<dim_x, dim_v, n_points - 1, Number>::template interpolate_quadrature<false, true>(1, dealii::EvaluationFlags::values, data.get_matrix_free_x().get_shape_info(), /*out=*/data_ptr1, /*in=*/data_ptr, face);
else
phi_m.distribute_to_buffer(this->phi_cell->get_data_ptr());
}
// 3) inverse mass matrix
{
phi_inv.reinit(cell);
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
phi_inv.submit_inv(data_ptr, q, qx, qv);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 6) eval_inv.template hessians<5, false, false>(data_ptr, data_ptr);
if (dim >= 5) eval_inv.template hessians<4, false, false>(data_ptr, data_ptr);
if (dim >= 4) eval_inv.template hessians<3, false, false>(data_ptr, data_ptr);
if (dim >= 3) eval_inv.template hessians<2, false, false>(data_ptr, data_ptr);
if (dim >= 2) eval_inv.template hessians<1, false, false>(data_ptr, data_ptr);
if (dim >= 1) eval_inv.template hessians<0, false, false>(data_ptr, data_ptr);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::hessian,
dim,
degree + 1,
n_points>::
do_backward(1, data.get_matrix_free_x().get_shape_info().data.front().inverse_shape_values_eo,
false,
data_ptr,
data_ptr);
}
}
// write into global structure back
phi.set_dof_values(dst);
}
// clang-format on
}
/**
* Inverse mass-matrix cell operation -> FCL.
*/
void
local_apply_inverse_mass_matrix(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
VectorType & dst,
const VectorType & src,
const ID cell)
{
(void)data;
auto &phi_inv = *this->phi_cell_inv_co;
// get data and scratch
VectorizedArrayType *data_ptr = phi_inv.get_data_ptr();
// load from global structure
phi_inv.reinit(cell);
phi_inv.read_dof_values(src);
// initialize tensor product kernels
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
degree + 1,
VectorizedArrayType,
Number>
eval_inv(dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>(),
*phi_inv.get_inverse_shape());
// clang-format off
if(do_collocation == false)
{
if (dim >= 1) eval_inv.template hessians<0, true, false>(data_ptr, data_ptr);
if (dim >= 2) eval_inv.template hessians<1, true, false>(data_ptr, data_ptr);
if (dim >= 3) eval_inv.template hessians<2, true, false>(data_ptr, data_ptr);
if (dim >= 4) eval_inv.template hessians<3, true, false>(data_ptr, data_ptr);
if (dim >= 5) eval_inv.template hessians<4, true, false>(data_ptr, data_ptr);
if (dim >= 6) eval_inv.template hessians<5, true, false>(data_ptr, data_ptr);
}
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(degree + 1, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(degree + 1, dim_x); ++qx, ++q)
phi_inv.submit_inv(data_ptr, q, qx, qv);
if(do_collocation == false)
{
if (dim >= 6) eval_inv.template hessians<5, false, false>(data_ptr, data_ptr);
if (dim >= 5) eval_inv.template hessians<4, false, false>(data_ptr, data_ptr);
if (dim >= 4) eval_inv.template hessians<3, false, false>(data_ptr, data_ptr);
if (dim >= 3) eval_inv.template hessians<2, false, false>(data_ptr, data_ptr);
if (dim >= 2) eval_inv.template hessians<1, false, false>(data_ptr, data_ptr);
if (dim >= 1) eval_inv.template hessians<0, false, false>(data_ptr, data_ptr);
}
// clang-format on
// write into global structure back
phi_inv.set_dof_values(dst);
}
/**
* Advection cell operation -> FCL.
*/
void
local_apply_cell(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
VectorType & dst,
const VectorType & src,
const ID cell)
{
(void)data;
auto &phi = *this->phi_cell;
// get data and scratch
VNumber *data_ptr = phi.get_data_ptr();
// initialize tensor product kernels
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
degree + 1,
n_points,
VNumber,
Number>
eval(*phi.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim,
n_points,
n_points,
VNumber,
Number>
eval_(dealii::AlignedVector<Number>(),
*phi.get_shape_gradients(),
dealii::AlignedVector<Number>());
// clang-format off
this->velocity_field->reinit(cell);
// load from global structure
phi.reinit(cell);
phi.read_dof_values(src);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 1) eval.template values<0, true, false>(data_ptr, data_ptr);
if (dim >= 2) eval.template values<1, true, false>(data_ptr, data_ptr);
if (dim >= 3) eval.template values<2, true, false>(data_ptr, data_ptr);
if (dim >= 4) eval.template values<3, true, false>(data_ptr, data_ptr);
if (dim >= 5) eval.template values<4, true, false>(data_ptr, data_ptr);
if (dim >= 6) eval.template values<5, true, false>(data_ptr, data_ptr);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim,
degree + 1,
n_points>::
do_forward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
data_ptr,
data_ptr);
}
}
// copy quadrature values into buffer
VNumber *buffer = phi_cell_inv->get_data_ptr();
for (auto i = 0u; i < dealii::Utilities::pow<unsigned int>(n_points, dim); i++)
buffer[i] = data_ptr[i];
// x-space
{
dealii::AlignedVector<VNumber> scratch_data_array;
scratch_data_array.resize_fast(dealii::Utilities::pow(n_points, dim) * dim_x);
VNumber *tempp = scratch_data_array.begin();
if(factor_skew != 0.0)
{
if (dim_x >= 1) eval_.template gradients<0, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 0);
if (dim_x >= 2) eval_.template gradients<1, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 1);
if (dim_x >= 3) eval_.template gradients<2, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 2);
}
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
VNumber grad_in[dim_x];
const auto vel = velocity_field->evaluate_x(q, qx, qv);
if(factor_skew != 0.0)
phi.template submit_value<false>(data_ptr, - factor_skew * (phi.get_gradient_x(tempp, q, qx, qv) * vel), q, qx, qv);
if (factor_skew != 1.0)
{
for (int d = 0; d < dim_x; d++)
grad_in[d] = (1.0-factor_skew) * buffer[q] * vel[d];
phi.submit_gradient_x(tempp, grad_in, q, qx, qv);
}
}
if(factor_skew != 1.0)
{
if (dim_x >= 1 && (factor_skew != 0.0))
eval_.template gradients<0, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
else if (dim_x >= 1)
eval_.template gradients<0, false, false>(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
if (dim_x >= 2) eval_.template gradients<1, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 1, data_ptr);
if (dim_x >= 3) eval_.template gradients<2, false, true >(tempp + dealii::Utilities::pow(n_points, dim) * 2, data_ptr);
}
}
// v-space
{
dealii::AlignedVector<VNumber> scratch_data_array;
scratch_data_array.resize_fast(dealii::Utilities::pow(n_points, dim) * dim_v);
VNumber *tempp = scratch_data_array.begin();
if(factor_skew != 0.0)
{
if (dim_v >= 1) eval_.template gradients<0 + dim_x, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 0);
if (dim_v >= 2) eval_.template gradients<1 + dim_x, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 1);
if (dim_v >= 3) eval_.template gradients<2 + dim_x, true, false>(buffer, tempp + dealii::Utilities::pow(n_points, dim) * 2);
}
for (auto qv = 0u, q = 0u; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (auto qx = 0u; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
VNumber grad_in[dim_v];
const auto vel = velocity_field->evaluate_v(q, qx, qv);
if(factor_skew != 0.0)
phi.template submit_value<true>(data_ptr, - factor_skew * (phi.get_gradient_v(tempp, q, qx, qv) * vel), q, qx, qv);
if (factor_skew != 1.0)
{
for (int d = 0; d < dim_v; d++)
grad_in[d] = (1.0-factor_skew) * buffer[q] * vel[d];
phi.submit_gradient_v(tempp, grad_in, q, qx, qv);
}
}
if(factor_skew != 1.0)
{
if (dim_v >= 1) eval_.template gradients<0 + dim_x, false, true>(tempp + dealii::Utilities::pow(n_points, dim) * 0, data_ptr);
if (dim_v >= 2) eval_.template gradients<1 + dim_x, false, true>(tempp + dealii::Utilities::pow(n_points, dim) * 1, data_ptr);
if (dim_v >= 3) eval_.template gradients<2 + dim_x, false, true>(tempp + dealii::Utilities::pow(n_points, dim) * 2, data_ptr);
}
}
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if(dim >= 6) eval.template values<5, false, false>(data_ptr, data_ptr);
if(dim >= 5) eval.template values<4, false, false>(data_ptr, data_ptr);
if(dim >= 4) eval.template values<3, false, false>(data_ptr, data_ptr);
if(dim >= 3) eval.template values<2, false, false>(data_ptr, data_ptr);
if(dim >= 2) eval.template values<1, false, false>(data_ptr, data_ptr);
if(dim >= 1) eval.template values<0, false, false>(data_ptr, data_ptr);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim,
degree + 1,
n_points>::
do_backward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
false,
data_ptr,
data_ptr);
}
}
// clang-format on
// write into global structure back
phi.set_dof_values(dst);
}
/**
* Advection face operation -> FCL.
*/
void
local_apply_face(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
VectorType & dst,
const VectorType & src,
const ID face)
{
(void)data;
auto &phi_m = *this->phi_face_m;
auto &phi_p = *this->phi_face_p;
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim - 1,
degree + 1,
n_points,
VNumber,
Number>
eval1(*phi_m.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim - 1,
degree + 1,
n_points,
VNumber,
Number>
eval2(*phi_p.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
this->velocity_field->reinit_face(face);
// get data and scratch
VNumber *data_ptr1 = phi_m.get_data_ptr();
VNumber *data_ptr2 = phi_p.get_data_ptr();
// load from global structure
phi_m.reinit(face);
phi_p.reinit(face);
// clang-format off
phi_m.read_dof_values(src);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 2) eval1.template values<0, true, false>(data_ptr1, data_ptr1);
if (dim >= 3) eval1.template values<1, true, false>(data_ptr1, data_ptr1);
if (dim >= 4) eval1.template values<2, true, false>(data_ptr1, data_ptr1);
if (dim >= 5) eval1.template values<3, true, false>(data_ptr1, data_ptr1);
if (dim >= 6) eval1.template values<4, true, false>(data_ptr1, data_ptr1);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::
do_forward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
data_ptr1,
data_ptr1);
}
}
phi_p.read_dof_values(src);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 2) eval2.template values<0, true, false>(data_ptr2, data_ptr2);
if (dim >= 3) eval2.template values<1, true, false>(data_ptr2, data_ptr2);
if (dim >= 4) eval2.template values<2, true, false>(data_ptr2, data_ptr2);
if (dim >= 5) eval2.template values<3, true, false>(data_ptr2, data_ptr2);
if (dim >= 6) eval2.template values<4, true, false>(data_ptr2, data_ptr2);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::
do_forward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
data_ptr2,
data_ptr2);
}
}
if (face.type == ID::SpaceType::X)
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x - 1); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_x(q, qx, qv) * phi_m.get_normal_vector_x(qx);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::X>(data_ptr1, +flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
phi_p.template submit_value<ID::SpaceType::X>(data_ptr2, -flux_times_normal_of_minus + factor_skew*u_plus*normal_times_speed, q, qx, qv);
}
}
else
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v - 1); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = data_ptr2[q];
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_v(q, qx, qv) * phi_m.get_normal_vector_v(qv);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::V>(data_ptr1, +flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
phi_p.template submit_value<ID::SpaceType::V>(data_ptr2, -flux_times_normal_of_minus + factor_skew*u_plus*normal_times_speed, q, qx, qv);
}
}
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 6) eval1.template values<4, false, false>(data_ptr1, data_ptr1);
if (dim >= 5) eval1.template values<3, false, false>(data_ptr1, data_ptr1);
if (dim >= 4) eval1.template values<2, false, false>(data_ptr1, data_ptr1);
if (dim >= 3) eval1.template values<1, false, false>(data_ptr1, data_ptr1);
if (dim >= 2) eval1.template values<0, false, false>(data_ptr1, data_ptr1);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::
do_backward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo, false,
data_ptr1,
data_ptr1);
}
}
// write into global structure back
phi_m.distribute_local_to_global(dst);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 6) eval2.template values<4, false, false>(data_ptr2, data_ptr2);
if (dim >= 5) eval2.template values<3, false, false>(data_ptr2, data_ptr2);
if (dim >= 4) eval2.template values<2, false, false>(data_ptr2, data_ptr2);
if (dim >= 3) eval2.template values<1, false, false>(data_ptr2, data_ptr2);
if (dim >= 2) eval2.template values<0, false, false>(data_ptr2, data_ptr2);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::
do_backward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo, false,
data_ptr2,
data_ptr2);
}
}
// clang-format on
// write into global structure back
phi_p.distribute_local_to_global(dst);
}
/**
* Advection boundary operation -> FCL.
*
* @note Not implemented yet (TODO).
*/
void
local_apply_boundary(
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data,
VectorType & dst,
const VectorType & src,
const ID face)
{
(void)data;
const auto bid = data.get_boundary_id(face);
Assert(bid != dealii::numbers::internal_face_boundary_id,
dealii::StandardExceptions::ExcInternalError());
const auto boundary_pair = boundary_descriptor->get_boundary(bid);
auto &phi_m = *this->phi_face_m;
const dealii::internal::EvaluatorTensorProduct<tensorproduct,
dim - 1,
degree + 1,
n_points,
VNumber,
Number>
eval1(*phi_m.get_shape_values(),
dealii::AlignedVector<Number>(),
dealii::AlignedVector<Number>());
this->velocity_field->reinit_face(face);
// get data and scratch
VNumber *data_ptr1 = phi_m.get_data_ptr();
// load from global structure
phi_m.reinit(face);
// clang-format off
phi_m.read_dof_values(src);
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 2) eval1.template values<0, true, false>(data_ptr1, data_ptr1);
if (dim >= 3) eval1.template values<1, true, false>(data_ptr1, data_ptr1);
if (dim >= 4) eval1.template values<2, true, false>(data_ptr1, data_ptr1);
if (dim >= 5) eval1.template values<3, true, false>(data_ptr1, data_ptr1);
if (dim >= 6) eval1.template values<4, true, false>(data_ptr1, data_ptr1);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::
do_forward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
data_ptr1,
data_ptr1);
}
}
if (face.type == ID::SpaceType::X)
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x - 1); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = (boundary_pair.first == BoundaryType::DirichletHomogenous) ?
(-u_minus) :
(-u_minus + 2.0 * hyperdeal::MatrixFreeTools::evaluate_scalar_function(phi_m.template get_quadrature_point<ID::SpaceType::X>(qx, qv), *boundary_pair.second, phi_m.n_vectorization_lanes_filled()));
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_x(q, qx, qv) * phi_m.get_normal_vector_x(qx);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::X>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
else
{
for (unsigned int qv = 0, q = 0; qv < dealii::Utilities::pow<unsigned int>(n_points, dim_v - 1); ++qv)
for (unsigned int qx = 0; qx < dealii::Utilities::pow<unsigned int>(n_points, dim_x); ++qx, ++q)
{
const VectorizedArrayType u_minus = data_ptr1[q];
const VectorizedArrayType u_plus = (boundary_pair.first == BoundaryType::DirichletHomogenous) ?
(-u_minus) :
(-u_minus + 2.0 * hyperdeal::MatrixFreeTools::evaluate_scalar_function(phi_m.template get_quadrature_point<ID::SpaceType::V>(qx, qv), *boundary_pair.second, phi_m.n_vectorization_lanes_filled()));
const VectorizedArrayType normal_times_speed = velocity_field->evaluate_face_v(q, qx, qv) * phi_m.get_normal_vector_v(qv);
const VectorizedArrayType flux_times_normal_of_minus = 0.5 * ((u_minus + u_plus) * normal_times_speed + std::abs(normal_times_speed) * (u_minus - u_plus)) * alpha;
phi_m.template submit_value<ID::SpaceType::V>(data_ptr1, flux_times_normal_of_minus - factor_skew*u_minus*normal_times_speed, q, qx, qv);
}
}
if(do_collocation == false)
{
if(degree + 1 == n_points)
{
if (dim >= 6) eval1.template values<4, false, false>(data_ptr1, data_ptr1);
if (dim >= 5) eval1.template values<3, false, false>(data_ptr1, data_ptr1);
if (dim >= 4) eval1.template values<2, false, false>(data_ptr1, data_ptr1);
if (dim >= 3) eval1.template values<1, false, false>(data_ptr1, data_ptr1);
if (dim >= 2) eval1.template values<0, false, false>(data_ptr1, data_ptr1);
}
else
{
dealii::internal::FEEvaluationImplBasisChange<tensorproduct,
dealii::internal::EvaluatorQuantity::value,
dim - 1,
degree + 1,
n_points>::
do_backward(1, data.get_matrix_free_x().get_shape_info().data.front().shape_values_eo,
false,
data_ptr1,
data_ptr1);
}
}
// write into global structure back
phi_m.distribute_local_to_global(dst);
}
const MatrixFree<dim_x, dim_v, Number, VectorizedArrayType> &data;
DynamicConvergenceTable & table;
// clang-format off
std::shared_ptr<FEEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_cell;
std::shared_ptr<FEEvaluationInverse<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_cell_inv;
std::shared_ptr<FEEvaluationInverse<dim_x, dim_v, degree, degree + 1, Number, VNumber>> phi_cell_inv_co;
std::shared_ptr<FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_face_m;
std::shared_ptr<FEFaceEvaluation<dim_x, dim_v, degree, n_points, Number, VNumber>> phi_face_p;
// clang-format on
std::shared_ptr<BoundaryDescriptor<dim, Number>> boundary_descriptor;
std::shared_ptr<VelocityField> velocity_field;
bool do_collocation;
const double alpha = 1.0;
// skew factor: conservative (skew=0) and convective (skew=1)
double factor_skew = 0.0;
};
} // namespace advection
} // namespace hyperdeal
#endif
| 56,004
|
C++
|
.h
| 994
| 37.947686
| 271
| 0.485616
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,154
|
advection_operation_parameters.h
|
hyperdeal_hyperdeal/include/hyper.deal/operators/advection/advection_operation_parameters.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_NDIM_OPERATORS_ADVECTIONOPERATION_PARAMTERS
#define HYPERDEAL_NDIM_OPERATORS_ADVECTIONOPERATION_PARAMTERS
#include <hyper.deal/base/config.h>
#include <deal.II/base/parameter_handler.h>
#include <functional>
namespace hyperdeal
{
namespace advection
{
struct AdvectionOperationParamters
{
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.add_parameter(
"SkewFactor",
factor_skew,
"Factor to blend between conservative and convective implementation of DG.");
}
// skew factor: conservative (skew=0) and convective (skew=1)
double factor_skew = 0.0;
};
} // namespace advection
} // namespace hyperdeal
#endif
| 1,380
|
C++
|
.h
| 39
| 31.846154
| 87
| 0.649925
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,155
|
cfl.h
|
hyperdeal_hyperdeal/include/hyper.deal/operators/advection/cfl.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_CFL
#define HYPERDEAL_CFL
#include <hyper.deal/base/config.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/fe_values.h>
namespace hyperdeal
{
namespace advection
{
/**
* Return critical time step.
*/
template <int dim, typename Number>
Number
compute_critical_time_step(dealii::DoFHandler<dim> & dof_handler,
dealii::Tensor<1, dim, Number> u,
const unsigned int degree,
const unsigned int n_points,
MPI_Comm comm);
/**
* Return critical time step phase space.
*/
template <int dim_x, int dim_v, typename Number>
Number
compute_critical_time_step(dealii::DoFHandler<dim_x> &dof_handler_x,
dealii::DoFHandler<dim_v> &dof_handler_v,
dealii::Tensor<1, dim_x + dim_v, Number> uu,
const unsigned int degree_x,
const unsigned int n_points_x,
MPI_Comm comm_row,
const unsigned int degree_v,
const unsigned int n_points_v,
MPI_Comm comm_column);
template <int dim, typename Number>
Number
compute_critical_time_step(dealii::DoFHandler<dim> & dof_handler,
dealii::Tensor<1, dim, Number> u,
const unsigned int degree,
const unsigned int n_points,
MPI_Comm comm)
{
dealii::FE_DGQ<dim> fe(degree);
dealii::QGauss<dim> quad(n_points);
dealii::FEValues<dim> fe_values(fe,
quad,
dealii::update_inverse_jacobians);
Number v_max = 0.0;
for (auto &cell : dof_handler.active_cell_iterators())
if (cell->is_locally_owned())
{
fe_values.reinit(cell);
for (unsigned int q = 0; q < quad.size(); ++q)
{
dealii::Tensor<1, dim, Number> v;
for (unsigned int i = 0; i < dim; i++)
for (unsigned int j = 0; j < dim; j++)
v[j] += fe_values.inverse_jacobian(q)[i][j] * u[i];
for (unsigned int i = 0; i < dim; i++)
v_max = std::max(v_max, std::abs(v[i]));
}
}
return 1.0 / dealii::Utilities::MPI::max(v_max, comm);
}
template <int dim_x, int dim_v, typename Number>
Number
compute_critical_time_step(dealii::DoFHandler<dim_x> &dof_handler_x,
dealii::DoFHandler<dim_v> &dof_handler_v,
dealii::Tensor<1, dim_x + dim_v, Number> uu,
const unsigned int degree_x,
const unsigned int n_points_x,
MPI_Comm comm_row,
const unsigned int degree_v,
const unsigned int n_points_v,
MPI_Comm comm_column)
{
Number v1, v2;
{
dealii::Tensor<1, dim_x, Number> u;
for (unsigned int i = 0; i < dim_x; i++)
u[i] = uu[i];
v1 = compute_critical_time_step(
dof_handler_x, u, degree_x, n_points_x, comm_row);
}
{
dealii::Tensor<1, dim_v, Number> u;
for (unsigned int i = 0; i < dim_v; i++)
u[i] = uu[i + dim_x];
v2 = compute_critical_time_step(
dof_handler_v, u, degree_v, n_points_v, comm_column);
}
return std::min(v1, v2);
}
} // namespace advection
} // namespace hyperdeal
#endif
| 4,622
|
C++
|
.h
| 109
| 29.642202
| 75
| 0.478077
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,156
|
boundary_descriptor.h
|
hyperdeal_hyperdeal/include/hyper.deal/operators/advection/boundary_descriptor.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_USERINTERFACE_BOUNDARYDESCRIPTOR
#define HYPERDEAL_USERINTERFACE_BOUNDARYDESCRIPTOR
#include <hyper.deal/base/config.h>
#include <deal.II/base/function.h>
#include <deal.II/base/types.h>
namespace hyperdeal
{
namespace advection
{
/**
* Type of the boundary.
*/
enum class BoundaryType
{
Undefined,
DirichletInhomogenous,
DirichletHomogenous,
};
/**
* Class managing different types of boundary conditions.
*/
template <int dim, typename Number>
struct BoundaryDescriptor
{
/**
* Dirichlet boundaries.
*/
std::map<dealii::types::boundary_id,
std::shared_ptr<dealii::Function<dim, Number>>>
dirichlet_bc;
std::set<dealii::types::boundary_id> homogeneous_dirichlet_bc;
/**
* Return boundary type.
*/
inline DEAL_II_ALWAYS_INLINE //
BoundaryType
get_boundary_type(dealii::types::boundary_id const &boundary_id) const
{
if (this->dirichlet_bc.find(boundary_id) != this->dirichlet_bc.end())
return BoundaryType::DirichletInhomogenous;
if (this->homogeneous_dirichlet_bc.find(boundary_id) !=
this->homogeneous_dirichlet_bc.end())
return BoundaryType::DirichletInhomogenous;
AssertThrow(false,
dealii::ExcMessage(
"Boundary type of face is invalid or not implemented."));
return BoundaryType::Undefined;
}
/**
* Return boundary type and the associated function.
*/
inline DEAL_II_ALWAYS_INLINE //
std::pair<BoundaryType, std::shared_ptr<dealii::Function<dim, Number>>>
get_boundary(dealii::types::boundary_id const &boundary_id) const
{
// process inhomogeneous Dirichlet BC
{
auto res = this->dirichlet_bc.find(boundary_id);
if (res != this->dirichlet_bc.end())
return {BoundaryType::DirichletInhomogenous, res->second};
}
// process homogeneous Dirichlet BC
{
auto res = this->homogeneous_dirichlet_bc.find(boundary_id);
if (res != this->homogeneous_dirichlet_bc.end())
return {BoundaryType::DirichletHomogenous,
std::shared_ptr<dealii::Function<dim, Number>>(
new dealii::Functions::ZeroFunction<dim, Number>())};
}
AssertThrow(false,
dealii::ExcMessage(
"Boundary type of face is invalid or not implemented."));
return {BoundaryType::Undefined,
std::shared_ptr<dealii::Function<dim>>(
new dealii::Functions::ZeroFunction<dim, Number>())};
}
/**
* Set time for all internal functions.
*/
void
set_time(const Number time)
{
for (auto &bc : dirichlet_bc)
bc.second->set_time(time);
}
};
} // namespace advection
} // namespace hyperdeal
#endif
| 3,677
|
C++
|
.h
| 103
| 28.15534
| 79
| 0.602755
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,157
|
velocity_field_view.h
|
hyperdeal_hyperdeal/include/hyper.deal/operators/advection/velocity_field_view.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_FUNCTIONALITIES_VELOCITY_FIELD_VIEW
#define HYPERDEAL_FUNCTIONALITIES_VELOCITY_FIELD_VIEW
#include <hyper.deal/base/config.h>
#include <hyper.deal/matrix_free/id.h>
namespace hyperdeal
{
namespace advection
{
template <int dim,
typename Number,
typename ID,
typename VectorizedArrayType,
int dim_x = dim,
int dim_v = dim>
class VelocityFieldView
{
public:
virtual ~VelocityFieldView() = default;
virtual void
reinit(ID id) = 0;
virtual void
reinit_face(ID id) = 0;
virtual void
reinit_face(ID id, unsigned int face) = 0;
virtual dealii::Tensor<1, dim_x, VectorizedArrayType>
evaluate_x(unsigned int q, unsigned int qx, unsigned int qv) const = 0;
virtual dealii::Tensor<1, dim_v, VectorizedArrayType>
evaluate_v(unsigned int q, unsigned int qx, unsigned int qv) const = 0;
virtual dealii::Tensor<1, dim_x, VectorizedArrayType>
evaluate_face_x(unsigned int q,
unsigned int qx,
unsigned int qv) const = 0;
virtual dealii::Tensor<1, dim_v, VectorizedArrayType>
evaluate_face_v(unsigned int q,
unsigned int qx,
unsigned int qv) const = 0;
};
template <int dim,
typename Number,
typename VectorizedArrayType,
int dim_x,
int dim_v>
class ConstantVelocityFieldView
: public VelocityFieldView<dim,
Number,
TensorID,
VectorizedArrayType,
dim_x,
dim_v>
{
public:
ConstantVelocityFieldView(
const dealii::Tensor<1, dim, VectorizedArrayType> &transport_direction)
: transport_direction(transport_direction)
, transport_direction_x(extract<dim_x>(transport_direction, 0))
, transport_direction_v(extract<dim_v>(transport_direction, dim_x))
{}
void reinit(TensorID /*id*/) override
{
// nothing to do
}
void reinit_face(TensorID /*id*/) override
{
// nothing to do
}
void
reinit_face(TensorID /*id*/, unsigned int /*face*/) override
{
// nothing to do
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_x, VectorizedArrayType>
evaluate_x(unsigned int /*q*/,
unsigned int /*qx*/,
unsigned int /*qv*/) const override
{
return transport_direction_x;
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_v, VectorizedArrayType>
evaluate_v(unsigned int /*q*/,
unsigned int /*qx*/,
unsigned int /*qv*/) const override
{
return transport_direction_v;
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_x, VectorizedArrayType>
evaluate_face_x(unsigned int /*q*/,
unsigned int /*qx*/,
unsigned int /*qv*/) const override
{
return transport_direction_x;
}
inline DEAL_II_ALWAYS_INLINE //
dealii::Tensor<1, dim_v, VectorizedArrayType>
evaluate_face_v(unsigned int /*q*/,
unsigned int /*qx*/,
unsigned int /*qv*/) const override
{
return transport_direction_v;
}
private:
template <int dim_>
static dealii::Tensor<1, dim_, VectorizedArrayType>
extract(dealii::Tensor<1, dim, VectorizedArrayType> input,
unsigned int offset)
{
dealii::Tensor<1, dim_, VectorizedArrayType> output;
for (auto i = 0u; i < dim_; i++)
output[i] = input[offset + i];
return output;
}
const dealii::Tensor<1, dim, VectorizedArrayType> transport_direction;
const dealii::Tensor<1, dim_x, VectorizedArrayType> transport_direction_x;
const dealii::Tensor<1, dim_v, VectorizedArrayType> transport_direction_v;
};
} // namespace advection
} // namespace hyperdeal
#endif
| 4,956
|
C++
|
.h
| 134
| 27.552239
| 80
| 0.570324
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,158
|
dynamic_convergence_table.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/dynamic_convergence_table.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_DYNAMIC_CONVERGENCE_TABLE
#define HYPERDEAL_DYNAMIC_CONVERGENCE_TABLE
#include <hyper.deal/base/config.h>
#include <deal.II/base/timer.h>
#include <algorithm>
namespace hyperdeal
{
/**
* A convergence table (+timer), which allows varying number of columns.
*
* TODO: still needed?
*/
class DynamicConvergenceTable
{
public:
DynamicConvergenceTable()
{
this->add_new_row();
}
void
start(std::string label, bool reset = false)
{
auto it = timers.find(label);
if (it != timers.end())
{
if (reset)
it->second.reset();
it->second.start();
}
else
{
timers[label] = dealii::Timer();
timers[label].start();
}
}
double
stop(std::string label)
{
return timers[label].stop();
}
void
stop_and_set(std::string label)
{
double value = stop(label);
set(label, value);
}
void
stop_and_put(std::string label)
{
double value = stop(label);
put(label, value);
}
void
add_new_row()
{
vec.push_back(std::map<std::string, double>());
}
void
put(std::string label, double value) const
{
auto &map = vec.back();
auto it = map.find(label);
if (it != map.end())
it->second += value;
else
map[label] = value;
}
double
get(std::string label) const
{
auto &map = vec.back();
auto it = map.find(label);
if (it != map.end())
return it->second;
else
return 0;
}
void
set(std::string label, double value) const
{
auto &map = vec.back();
auto it = map.find(label);
if (it != map.end())
it->second = value;
else
map[label] = value;
}
void
print(FILE *f, bool do_horizontal = true) const
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank)
return;
std::vector<std::string> header;
for (auto &map : vec)
for (auto &it : map)
if (std::find(header.begin(), header.end(), it.first) == header.end())
header.push_back(it.first);
std::sort(header.begin(), header.end());
if (do_horizontal)
{
for (auto it : header)
fprintf(f, "%12s", it.c_str());
fprintf(f, "\n");
for (auto &map : vec)
{
if (map.size() == 0)
continue;
for (auto h : header)
{
auto it = map.find(h);
if (it == map.end())
fprintf(f, "%12.4e", 0.0);
else
fprintf(f, "%12.4e", it->second);
}
fprintf(f, "\n");
}
}
else
{
size_t length = 0;
for (auto head : header)
{
length = std::max(length, head.size());
}
const auto hline = [&]() {
// hline
printf("+%s+", std::string((int)length + 5, '-').c_str());
for (auto &map : vec)
{
if (map.size() == 0)
continue;
fprintf(f, "--------------+");
}
fprintf(f, "\n");
};
hline();
// header
printf("| %-*s|", (int)length + 4, "category");
int counter = 0;
for (auto &map : vec)
{
if (map.size() == 0)
continue;
fprintf(f, " item %2d |", counter++);
}
fprintf(f, "\n");
hline();
// categories
for (auto head : header)
{
fprintf(f, "| %-*s|", (int)length + 4, head.c_str());
for (auto &map : vec)
{
if (map.size() == 0)
continue;
auto it = map.find(head);
if (it == map.end())
fprintf(f, " %12.4e |", 0.0);
else
fprintf(f, " %12.4e |", it->second);
}
fprintf(f, "\n");
}
hline();
fprintf(f, "\n");
}
}
void
print(bool do_horizontal = true) const
{
this->print(stdout, do_horizontal);
}
void
print(std::string filename) const
{
FILE *f = fopen(filename.c_str(), "w");
this->print(f);
fclose(f);
}
private:
mutable std::vector<std::map<std::string, double>> vec;
std::map<std::string, dealii::Timer> timers;
};
} // namespace hyperdeal
#endif
| 5,419
|
C++
|
.h
| 202
| 18.30198
| 80
| 0.464995
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,159
|
time_loop_parameters.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/time_loop_parameters.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_FUNCTIONALITIES_TIME_LOOP_PARAMTERS
#define HYPERDEAL_FUNCTIONALITIES_TIME_LOOP_PARAMTERS
#include <hyper.deal/base/config.h>
#include <deal.II/base/parameter_handler.h>
#include <functional>
namespace hyperdeal
{
template <typename Number>
struct TimeLoopParamters
{
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.add_parameter(
"TimeStep",
time_step,
"Time-step size: we take the minimum of this quantity and the maximum time step obtained by the CFL condition.");
prm.add_parameter("StartTime", start_time, "Start time.");
prm.add_parameter("FinalTime", final_time, "Final time.");
prm.add_parameter(
"MaxTimeStepNumber",
max_time_step_number,
"Terminate simulation after a maximum number of iterations (useful for performance studies).");
}
Number time_step = 0.1;
Number start_time = 0.0;
Number final_time = 20.0;
unsigned int max_time_step_number = 100000000;
};
} // namespace hyperdeal
#endif
| 1,744
|
C++
|
.h
| 45
| 35.133333
| 121
| 0.639693
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,160
|
mpi.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/mpi.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_MPI
#define HYPERDEAL_MPI
#include <hyper.deal/base/config.h>
#include <deal.II/base/mpi.h>
namespace hyperdeal
{
namespace mpi
{
/**
* Split up given MPI communicator @p comm in new MPI communicators
* only containing processes on the same shared-memory domain.
*/
MPI_Comm
create_sm(const MPI_Comm &comm);
/**
* Get size of shared-memory domain.
*
* @note As approximation this function takes the maximum of the sizes
* of all shared-memory communicators @p comm_sm in @comm.
*/
unsigned int
n_procs_of_sm(const MPI_Comm &comm, const MPI_Comm &comm_sm);
/**
* Return a list of IDs of processes living in @comm_shared.
*
* @note As ID the rank in @comm is used.
*/
std::vector<unsigned int>
procs_of_sm(const MPI_Comm &comm, const MPI_Comm &comm_shared);
/**
* Let rank 0 print information of all shared memory domains to the
* screen.
*
* TODO: specify stream.
*
* TODO: add test
*/
void
print_sm(const MPI_Comm &comm, const MPI_Comm &comm_sm);
/**
* Let rank 0 print the rank in @p comm_old and @p comm_new of each
* process to the screen.
*
* TODO: specify stream.
*
* TODO: add test
*/
void
print_new_order(const MPI_Comm &comm_old, const MPI_Comm &comm_new);
/**
* Create rectangular Cartesian communicator of @p size_x and @p size_v
* from a given communicator @p comm.
*
* @note: Processes with rank >= @p size_x * @p size_v are assigned
* MPI_COMM_NULL, so that the user can check for
* if(new_comm!=MPI_COMM_NULL) and only proceed computation with processes
* fulfilling the condition.
*/
MPI_Comm
create_rectangular_comm(const MPI_Comm & comm,
const unsigned int size_x,
const unsigned int size_v);
/**
* Sort processes in blocks of size @p group_size and sort the blocks
* along a z-curve/Morton-order.
*
* @onte Processes within a block are enumerated lexicographically.
*
* @note We also call the result of this function `virtual topology`.
*/
MPI_Comm
create_z_order_comm(const MPI_Comm & comm,
const std::pair<unsigned int, unsigned int> procs,
const std::pair<unsigned int, unsigned int> group_size);
/**
* Create a new row communicator from a Cartesian communicator @p comm of
* size @p size1 and @p size2.
*
* @note Size we use a lexicographical numbering, all processes with
* `rank / size1` are grouped together.
*
* @pre The size of @p @comm has to match the product of @p size1 and
* @size2.
*/
MPI_Comm
create_row_comm(const MPI_Comm & comm,
const unsigned int size1,
const unsigned int size2);
/**
* The same as above, just for column..
*
* @note Size we use a lexicographical numbering, all processes with
* `rank % size1` are grouped together.
*/
MPI_Comm
create_column_comm(const MPI_Comm & comm,
const unsigned int size1,
const unsigned int size2);
} // namespace mpi
} // namespace hyperdeal
#endif
| 4,032
|
C++
|
.h
| 115
| 28.913043
| 80
| 0.603996
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,161
|
mpi_tags.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/mpi_tags.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_BASE_MPI_TAGS
#define HYPERDEAL_BASE_MPI_TAGS
#include <hyper.deal/base/config.h>
#include <deal.II/base/mpi.h>
namespace hyperdeal
{
namespace mpi
{
namespace internal
{
namespace Tags
{
enum enumeration : std::uint16_t
{
// Partitioner::sync() -> MPI_Isend/MPI_Irecv
partitioner_sync,
};
}
} // namespace internal
} // namespace mpi
} // namespace hyperdeal
#endif
| 1,120
|
C++
|
.h
| 36
| 27.722222
| 72
| 0.602041
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,162
|
memory_consumption.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/memory_consumption.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_MEMORY_CONSUMPTION
#define HYPERDEAL_MEMORY_CONSUMPTION
#include <hyper.deal/base/config.h>
#include <deal.II/base/utilities.h>
#include <iomanip>
#include <vector>
namespace hyperdeal
{
namespace internal
{
template <typename StreamType, long unsigned int N>
void
print(
StreamType & stream,
const MPI_Comm & comm,
const std::vector<std::pair<std::string, std::array<double, N>>> &list,
const std::vector<std::string> & labels,
const unsigned int mm)
{
std::vector<double> temp1(list.size() * N);
for (unsigned int i = 0, k = 0; i < list.size(); i++)
for (unsigned int j = 0; j < N; j++, k++)
temp1[k] = list[i].second[j];
const auto temp2 = dealii::Utilities::MPI::min_max_avg(temp1, comm);
std::vector<std::pair<std::string,
std::array<dealii::Utilities::MPI::MinMaxAvg, N>>>
list_min_max(list.size());
for (unsigned int i = 0, k = 0; i < list.size(); i++)
{
list_min_max[i].first = list[i].first;
for (unsigned int j = 0; j < N; j++, k++)
list_min_max[i].second[j] = temp2[k];
}
const auto max_width =
std::max_element(list_min_max.begin(),
list_min_max.end(),
[](const auto &a, const auto &b) {
return a.first.size() < b.first.size();
})
->first.size();
// print header
const auto print_lines = [&]() {
stream << "+-" << std::string(max_width + 2, '-') << "+";
for (unsigned int i = 0; i < labels.size(); i++)
{
auto j = list_min_max[mm].second[i];
auto label = labels[i];
// clang-format off
const unsigned int width = static_cast<unsigned int>(4 + std::log(j.sum) / log(10.0))+
static_cast<unsigned int>(8)+
static_cast<unsigned int>(4 + std::log(j.min) / log(10.0))+
static_cast<unsigned int>(4 + std::log(j.avg) / log(10.0))+
static_cast<unsigned int>(4 + std::log(j.max) / log(10.0));
stream << std::string(width, '-');
stream << "-+";
// clang-format on
}
stream << std::endl;
};
print_lines();
{
stream << "| " << std::left << std::setw(max_width + 2) << ""
<< "|";
for (unsigned int i = 0; i < labels.size(); i++)
{
auto j = list_min_max[mm].second[i];
auto label = labels[i];
// clang-format off
const unsigned int width = static_cast<unsigned int>(4 + std::log(j.sum) / log(10.0))+
static_cast<unsigned int>(8)+
static_cast<unsigned int>(4 + std::log(j.min) / log(10.0))+
static_cast<unsigned int>(4 + std::log(j.avg) / log(10.0))+
static_cast<unsigned int>(4 + std::log(j.max) / log(10.0));
stream << std::setw((width-label.size())/2) << "" << label << std::setw(width - label.size() - (width-label.size())/2) << "" ;
stream << " |";
// clang-format on
}
stream << std::endl;
}
// print header
{
stream << "| " << std::left << std::setw(max_width + 2) << ""
<< "|";
for (auto j : list_min_max[mm].second)
{
// clang-format off
stream << std::setw(4 + std::log(j.sum) / log(10.0)) << std::right << "total";
stream << std::setw(8) << "%";
stream << std::setw(4 + std::log(j.min) / log(10.0)) << std::right << "min";
stream << std::setw(4 + std::log(j.avg) / log(10.0)) << std::right << "avg";
stream << std::setw(4 + std::log(j.max) / log(10.0)) << std::right << "max";
stream << " |";
// clang-format on
}
stream << std::endl;
}
print_lines();
// print rows
for (auto j : list_min_max)
{
stream << "| " << std::left << std::setw(max_width + 2) << j.first
<< "|";
for (unsigned int col = 0; col < j.second.size(); col++)
{
auto i = j.second[col];
auto m = list_min_max[mm].second[col];
// clang-format off
stream << std::fixed << std::setprecision(0) << std::setw(4 + std::log(m.sum) / log(10.0)) << std::right << i.sum;
stream << std::fixed << std::setprecision(2) << std::setw(8) << std::right << (i.sum * 100 / m.sum);
stream << std::fixed << std::setprecision(0) << std::setw(4 + std::log(m.min) / log(10.0)) << std::right << i.min;
stream << std::fixed << std::setprecision(0) << std::setw(4 + std::log(m.avg) / log(10.0)) << std::right << i.avg;
stream << std::fixed << std::setprecision(0) << std::setw(4 + std::log(m.max) / log(10.0)) << std::right << i.max;
stream << " |";
// clang-format on
}
stream << std::endl;
}
print_lines();
stream << std::endl << std::endl;
}
template <typename StreamType, long unsigned int N>
void
print_(
StreamType & stream,
const MPI_Comm & comm,
const std::vector<std::pair<std::string, std::array<double, N>>> &list,
const std::vector<std::pair<std::string, unsigned int>> &list_count,
const std::vector<std::string> & labels,
const unsigned int mm)
{
unsigned int max_count = 0;
for (const auto &i : list_count)
max_count = std::max(max_count, i.second);
std::vector<double> temp1(list.size() * N);
for (unsigned int i = 0, k = 0; i < list.size(); i++)
for (unsigned int j = 0; j < N; j++, k++)
temp1[k] = list[i].second[j];
const auto temp2 = dealii::Utilities::MPI::min_max_avg(temp1, comm);
std::vector<std::pair<std::string,
std::array<dealii::Utilities::MPI::MinMaxAvg, N>>>
list_min_max(list.size());
for (unsigned int i = 0, k = 0; i < list.size(); i++)
{
list_min_max[i].first = list[i].first;
for (unsigned int j = 0; j < N; j++, k++)
list_min_max[i].second[j] = temp2[k];
}
const auto max_width =
std::max_element(list_min_max.begin(),
list_min_max.end(),
[](const auto &a, const auto &b) {
return a.first.size() < b.first.size();
})
->first.size();
// print header
const auto print_lines = [&]() {
stream << "+-" << std::string(max_width + 2, '-') << "+";
for (unsigned int i = 0; i < labels.size(); i++)
{
auto j = list_min_max[mm].second[i];
auto label = labels[i];
// clang-format off
const unsigned int width = static_cast<unsigned int>(3 + std::log(max_count) / log(10.0))+
static_cast<unsigned int>(8)+
static_cast<unsigned int>(8 + std::log(j.min) / log(10.0))+
static_cast<unsigned int>(8 + std::log(j.avg) / log(10.0))+
static_cast<unsigned int>(8 + std::log(j.max) / log(10.0));
stream << std::string(width, '-');
stream << "-+";
// clang-format on
}
stream << std::endl;
};
print_lines();
{
stream << "| " << std::left << std::setw(max_width + 2) << ""
<< "|";
for (unsigned int i = 0; i < labels.size(); i++)
{
auto j = list_min_max[mm].second[i];
auto label = labels[i];
// clang-format off
const unsigned int width = static_cast<unsigned int>(3 + std::log(max_count) / log(10.0))+
static_cast<unsigned int>(8)+
static_cast<unsigned int>(8 + std::log(j.min) / log(10.0))+
static_cast<unsigned int>(8 + std::log(j.avg) / log(10.0))+
static_cast<unsigned int>(8 + std::log(j.max) / log(10.0));
stream << std::setw((width-label.size())/2) << "" << label << std::setw(width - label.size() - (width-label.size())/2) << "" ;
stream << " |";
// clang-format on
}
stream << std::endl;
}
// print header
{
stream << "| " << std::left << std::setw(max_width + 2) << ""
<< "|";
for (auto j : list_min_max[mm].second)
{
// clang-format off
stream << std::setw(3 + std::log(max_count) / log(10.0)) << std::right << "#";
stream << std::setw(8) << "%";
stream << std::setw(8 + std::log(j.min) / log(10.0)) << std::right << "min";
stream << std::setw(8 + std::log(j.avg) / log(10.0)) << std::right << "avg";
stream << std::setw(8 + std::log(j.max) / log(10.0)) << std::right << "max";
stream << " |";
// clang-format on
}
stream << std::endl;
}
print_lines();
// print rows
unsigned int row = 0;
for (auto j : list_min_max)
{
stream << "| " << std::left << std::setw(max_width + 2) << j.first
<< "|";
for (unsigned int col = 0; col < j.second.size(); col++)
{
auto i = j.second[col];
auto m = list_min_max[mm].second[col];
// clang-format off
stream << std::fixed << std::setw(3 + std::log(max_count) / log(10.0)) << std::right << list_count[row].second;
stream << std::fixed << std::setprecision(2) << std::setw(8) << std::right << (i.sum * 100 / m.sum);
stream << std::fixed << std::setprecision(2) << std::setw(8 + std::log(m.min) / log(10.0)) << std::right << i.min;
stream << std::fixed << std::setprecision(2) << std::setw(8 + std::log(m.avg) / log(10.0)) << std::right << i.avg;
stream << std::fixed << std::setprecision(2) << std::setw(8 + std::log(m.max) / log(10.0)) << std::right << i.max;
stream << " |";
// clang-format on
}
stream << std::endl;
row++;
}
print_lines();
stream << std::endl << std::endl;
}
} // namespace internal
class MemoryStatMonitor
{
public:
MemoryStatMonitor(const MPI_Comm &comm)
: comm(comm)
{}
void
monitor(const std::string &label)
{
MPI_Barrier(comm);
dealii::Utilities::System::MemoryStats stats;
dealii::Utilities::System::get_memory_stats(stats);
list.emplace_back(label,
std::array<double, 4>{
{static_cast<double>(stats.VmPeak),
static_cast<double>(stats.VmSize),
static_cast<double>(stats.VmHWM),
static_cast<double>(stats.VmRSS)}});
MPI_Barrier(comm);
}
template <typename StreamType>
void
print(StreamType &stream, const bool do_monitor = true)
{
if (do_monitor)
this->monitor("");
internal::print(
stream,
comm,
list,
{"VmPeak [kB]", "VmSize [kB]", "VmHWM [kB]", "VmRSS [kB]"},
list.size() - 1);
}
private:
const MPI_Comm &comm;
std::vector<std::pair<std::string, std::array<double, 4>>> list;
};
class MemoryConsumption
{
public:
MemoryConsumption(std::string label, const std::size_t &val = 0)
: label(label)
, memory_consumpition_leaf(val)
{}
void
insert(const MemoryConsumption &m)
{
vec.emplace_back(m);
}
void
insert(const std::string &label, const std::size_t &val)
{
vec.emplace_back(label, val);
}
template <typename StreamType>
void
print(const MPI_Comm &comm, StreamType &stream) const
{
const std::vector<std::pair<std::string, std::size_t>> collection =
collect();
std::vector<std::pair<std::string, std::array<double, 1>>> collection_(
collection.size());
for (unsigned int i = 0; i < collection.size(); i++)
collection_[i] = std::pair<std::string, std::array<double, 1>>{
collection[i].first,
std::array<double, 1>{{static_cast<double>(collection[i].second)}}};
internal::print(
stream, comm, collection_, {"Memory consumption [Byte]"}, 0);
}
std::size_t
memory_consumption() const
{
return std::accumulate(vec.begin(),
vec.end(),
memory_consumpition_leaf,
[](const auto &a, const auto &b) {
return a + b.memory_consumption();
});
}
private:
std::vector<std::pair<std::string, std::size_t>>
collect() const
{
std::vector<std::pair<std::string, std::size_t>> all;
all.emplace_back(label, this->memory_consumption());
for (const auto &v : vec)
for (const auto &i : v.collect())
all.emplace_back(label + ":" + i.first, i.second);
return all;
}
const std::string label;
const std::size_t memory_consumpition_leaf;
std::vector<MemoryConsumption> vec;
};
} // namespace hyperdeal
#endif
| 14,815
|
C++
|
.h
| 347
| 31.697406
| 138
| 0.476615
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,163
|
utilities.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/utilities.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_FUNCTIONALITIES_UTIL
#define HYPERDEAL_FUNCTIONALITIES_UTIL
#include <hyper.deal/base/config.h>
#include <deal.II/base/exceptions.h>
#include <algorithm>
#include <utility>
#include <vector>
namespace hyperdeal
{
namespace Utilities
{
/**
* Given an @id and the sizes of a Cartesian system @size1 and @size2,
* return the position in 2D space.
*
* @note A lexicographical numbering is used.
*/
std::pair<unsigned int, unsigned int>
lex_to_pair(const unsigned int id,
const unsigned int size1,
const unsigned int size2);
/**
* Factorize @p number into number=number1*number2 with the following
* properties:
* - min(number1 - number2) and
* - number1 >= number2
*/
std::pair<unsigned int, unsigned int>
decompose(const unsigned int &number);
/**
* Print hyper.deal and deal.II git version information.
*/
template <typename StreamType>
void
print_version(const StreamType &stream);
} // namespace Utilities
} // namespace hyperdeal
#endif
| 1,751
|
C++
|
.h
| 52
| 29.865385
| 74
| 0.642224
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,164
|
time_integrators.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/time_integrators.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_FUNCTIONALITIES_TIME_INGEGRATORS
#define HYPERDEAL_FUNCTIONALITIES_TIME_INGEGRATORS
#include <hyper.deal/base/config.h>
#include <deal.II/base/config.h>
#include <deal.II/base/exceptions.h>
#include <deal.II/lac/petsc_block_vector.h>
#include <deal.II/lac/petsc_vector.h>
#include <deal.II/lac/trilinos_parallel_block_vector.h>
#include <deal.II/lac/trilinos_vector.h>
#include <functional>
#include <string>
#include <type_traits>
#include <vector>
namespace hyperdeal
{
/**
* Efficient specialized low-storage Runge-Kutta implementations.
*
* We provide an implementation, which only needs one vector (vec_Ti) to be
* ghosted. This is in particular useful in high-dimensions, where
* memory is scarce.
*
* @note For details on the basic low-storage implementation, see step-69
* in deal.II.
*/
template <typename Number, typename VectorType>
class LowStorageRungeKuttaIntegrator
{
public:
/**
* Constructor. The user provides from outside two register vectors
* @p vec_Ki and @p vev_Ti.
*
* @note Currently rk33, rk45, rk47, rk59 (order, stages) are supported.
*/
LowStorageRungeKuttaIntegrator(VectorType & vec_Ki,
VectorType & vec_Ti,
const std::string type,
const bool only_Ti_is_ghosted = true);
/**
* Perform time step: evaluate right-hand side provided by @p op at
* a specified time @p current_time and with a given @p time_step. The
* previous solution is provided by @p solution and the new solution
* is written into the same vector.
*/
void
perform_time_step(
VectorType & solution,
const Number ¤t_time,
const Number &time_step,
const std::function<void(const VectorType &, VectorType &, const Number)>
&op);
unsigned int
n_stages() const;
private:
/**
* First register (does not have to be ghosted - see the comments in the
* constructor).
*/
VectorType &vec_Ki;
/**
* Second register (has to be ghosted).
*/
VectorType &vec_Ti;
/**
* Is only vector Ti ghosted or are all vectors ghosted.
*/
const bool only_Ti_is_ghosted;
/**
* Coefficients of the Runge-Kutta stages.
*/
std::vector<Number> ai, bi;
/**
* If manual vector compression is needed.
*/
static constexpr bool manual_compress =
false
#ifdef DEAL_II_WITH_PETSC
|| std::is_same_v<VectorType, dealii::PETScWrappers::MPI::Vector> ||
std::is_same_v<VectorType, dealii::PETScWrappers::MPI::BlockVector>
#endif
#ifdef DEAL_II_WITH_TRILINOS
|| std::is_same_v<VectorType, dealii::TrilinosWrappers::MPI::Vector> ||
std::is_same_v<VectorType, dealii::TrilinosWrappers::MPI::BlockVector>
#endif
;
};
} // namespace hyperdeal
#endif
| 3,591
|
C++
|
.h
| 103
| 29.941748
| 80
| 0.647076
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,165
|
time_integrators.templates.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/time_integrators.templates.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/base/exceptions.h>
#include <hyper.deal/base/time_integrators.h>
namespace hyperdeal
{
template <typename Number, typename VectorType>
LowStorageRungeKuttaIntegrator<Number, VectorType>::
LowStorageRungeKuttaIntegrator(VectorType & vec_Ki,
VectorType & vec_Ti,
const std::string type,
const bool only_Ti_is_ghosted)
: vec_Ki(vec_Ki)
, vec_Ti(vec_Ti)
, only_Ti_is_ghosted(only_Ti_is_ghosted)
{
// Runge-Kutta coefficients
// see: Kennedy, Carpenter, Lewis, 2000
if (type == "rk33")
{
bi = {{0.245170287303492, 0.184896052186740, 0.569933660509768}};
ai = {{0.755726351946097, 0.386954477304099}};
}
else if (type == "rk45")
{
bi = {{1153189308089. / 22510343858157.,
1772645290293. / 4653164025191.,
-1672844663538. / 4480602732383.,
2114624349019. / 3568978502595.,
5198255086312. / 14908931495163.}};
ai = {{970286171893. / 4311952581923.,
6584761158862. / 12103376702013.,
2251764453980. / 15575788980749.,
26877169314380. / 34165994151039.}};
}
else if (type == "rk47")
{
bi = {{0.0941840925477795334,
0.149683694803496998,
0.285204742060440058,
-0.122201846148053668,
0.0605151571191401122,
0.345986987898399296,
0.186627171718797670}};
ai = {{0.241566650129646868 + bi[0],
0.0423866513027719953 + bi[1],
0.215602732678803776 + bi[2],
0.232328007537583987 + bi[3],
0.256223412574146438 + bi[4],
0.0978694102142697230 + bi[5]}};
}
else if (type == "rk59")
{
bi = {{2274579626619. / 23610510767302.,
693987741272. / 12394497460941.,
-347131529483. / 15096185902911.,
1144057200723. / 32081666971178.,
1562491064753. / 11797114684756.,
13113619727965. / 44346030145118.,
393957816125. / 7825732611452.,
720647959663. / 6565743875477.,
3559252274877. / 14424734981077.}};
ai = {{1107026461565. / 5417078080134.,
38141181049399. / 41724347789894.,
493273079041. / 11940823631197.,
1851571280403. / 6147804934346.,
11782306865191. / 62590030070788.,
9452544825720. / 13648368537481.,
4435885630781. / 26285702406235.,
2357909744247. / 11371140753790.}};
}
else
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
template <typename Number, typename VectorType>
void
LowStorageRungeKuttaIntegrator<Number, VectorType>::perform_time_step(
VectorType & solution,
const Number ¤t_time,
const Number &time_step,
const std::function<void(const VectorType &, VectorType &, const Number)>
&op)
{
const auto &local_elements = solution.locally_owned_elements();
// definition of a stage
auto perform_stage = [&](const Number current_time,
const Number factor_solution,
const Number factor_ai,
const VectorType ¤t_Ti,
VectorType & vec_Ki,
VectorType & solution,
VectorType & next_Ti) {
// call operator
op(current_Ti, vec_Ki, current_time);
const Number ai = factor_ai;
const Number bi = factor_solution;
if (ai == Number())
{
for (const auto i : local_elements)
{
const Number K_i = vec_Ki(i);
const Number sol_i = solution(i);
solution(i) = sol_i + bi * K_i;
}
}
else
{
for (const auto i : local_elements)
{
const Number K_i = vec_Ki(i);
const Number sol_i = solution(i);
solution(i) = sol_i + bi * K_i;
next_Ti(i) = sol_i + ai * K_i;
}
if constexpr (manual_compress)
next_Ti.compress(dealii::VectorOperation::insert);
}
if constexpr (manual_compress)
solution.compress(dealii::VectorOperation::insert);
};
// perform first stage
if (only_Ti_is_ghosted)
{
// swap solution and Ti
for (const auto i : local_elements)
vec_Ti(i) = solution(i);
if constexpr (manual_compress)
vec_Ti.compress(dealii::VectorOperation::insert);
perform_stage(current_time,
bi[0] * time_step,
ai[0] * time_step,
vec_Ti,
vec_Ki,
solution,
vec_Ti);
}
else
{
perform_stage(current_time,
bi[0] * time_step,
ai[0] * time_step,
solution,
vec_Ti,
solution,
vec_Ti);
}
// perform rest stages
Number sum_previous_bi = 0;
for (unsigned int stage = 1; stage < bi.size(); ++stage)
{
const Number c_i = sum_previous_bi + ai[stage - 1];
perform_stage(current_time + c_i * time_step,
bi[stage] * time_step,
(stage == bi.size() - 1 ? 0 : ai[stage] * time_step),
vec_Ti,
vec_Ki,
solution,
vec_Ti);
sum_previous_bi += bi[stage - 1];
}
}
template <typename Number, typename VectorType>
unsigned int
LowStorageRungeKuttaIntegrator<Number, VectorType>::n_stages() const
{
return bi.size();
}
} // namespace hyperdeal
| 6,760
|
C++
|
.h
| 180
| 26.394444
| 77
| 0.523679
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,166
|
time_loop.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/time_loop.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_FUNCTIONALITIES_TIME_LOOP
#define HYPERDEAL_FUNCTIONALITIES_TIME_LOOP
#include <hyper.deal/base/config.h>
#include <hyper.deal/base/time_loop_parameters.h>
#include <functional>
namespace hyperdeal
{
/**
* Time loop class.
*/
template <typename Number, typename VectorType>
class TimeLoop
{
public:
/**
* Configure time loop.
*/
void
reinit(const TimeLoopParamters<Number> ¶meters);
/**
* Run time loop. For each time step, a @p time_integrator, which evaluates
* the right-hand side function @runnable, and a postprocessor
* @p diagnostics is called.
*/
int
loop(
VectorType &solution,
const std::function<
void(VectorType &,
const Number,
const Number,
const std::function<
void(const VectorType &, VectorType &, const Number)> &)>
&time_integrator,
const std::function<void(const VectorType &, VectorType &, const Number)>
& runnable,
const std::function<void(const Number)> &diagnostics);
/**
* Constant time step size.
*/
Number time_step;
/**
* Start time. The default is zero, however, in the case of restarts
* one might specify a different value.
*/
Number start_time;
/**
* Final time.
*/
Number final_time;
/**
* Maximal number of time steps, after which the simulation terminates
* even if the final time has not been reached.
*/
unsigned int max_time_step_number;
};
} // namespace hyperdeal
#endif
| 2,284
|
C++
|
.h
| 72
| 27.027778
| 79
| 0.61535
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,167
|
time_integrators_parameters.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/time_integrators_parameters.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_FUNCTIONALITIES_TIME_INGEGRATORS_PARAMTERS
#define HYPERDEAL_FUNCTIONALITIES_TIME_INGEGRATORS_PARAMTERS
#include <hyper.deal/base/config.h>
#include <deal.II/base/parameter_handler.h>
#include <functional>
namespace hyperdeal
{
/**
* Parameters of the class LowStorageRungeKuttaIntegrator.
*/
struct LowStorageRungeKuttaIntegratorParamters
{
/**
* Register parameters.
*/
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.add_parameter("RKType",
type,
"Type of the low-storage Runge-Kutta scheme.");
}
/*
* Type of Runge-Kutta scheme. Default: RK45.
*/
std::string type = "rk45";
};
} // namespace hyperdeal
#endif
| 1,410
|
C++
|
.h
| 43
| 28.930233
| 72
| 0.630882
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,168
|
timers.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/timers.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_TIMERS
#define HYPERDEAL_TIMERS
#include <hyper.deal/base/config.h>
#include <deal.II/base/mpi.templates.h>
#include <hyper.deal/base/memory_consumption.h>
#include <chrono>
#include <fstream>
#include <ios>
#include <map>
#ifdef LIKWID_PERFMON
# include <likwid.h>
#endif
namespace hyperdeal
{
class Timer
{
public:
void
reserve(const unsigned int max_size)
{
times.reserve(max_size);
}
void
reset()
{
counter = 0;
accumulated_time = 0.0;
}
void
start()
{
temp = std::chrono::system_clock::now();
}
void
stop()
{
const double dt = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now() - temp)
.count();
accumulated_time += dt;
if (times.capacity() > 0)
times.push_back(dt);
counter++;
}
unsigned int
get_counter() const
{
return counter;
}
double
get_accumulated_time() const
{
return accumulated_time;
}
const std::vector<double> &
get_log() const
{
return times;
}
private:
unsigned int counter = 0;
std::chrono::time_point<std::chrono::system_clock> temp;
double accumulated_time = 0.0;
std::vector<double> times;
};
class Timers
{
static const unsigned int max_levels = 10;
static const unsigned int max_timers = 100;
static const unsigned int max_iterations = 1000;
public:
Timers(const bool log_all_calls)
: log_all_calls(log_all_calls)
{
path.reserve(max_levels);
timers.reserve(max_timers);
path.emplace_back("");
}
Timer &operator[](const std::string &label)
{
const std::string label_ = path.back() + label;
const auto ptr = map.find(label_);
if (ptr == map.end())
{
timers.resize(timers.size() + 1);
map[label_] = timers.size() - 1;
if (this->log_all_calls)
timers.back().reserve(max_iterations);
return timers.back();
}
else
return timers[ptr->second];
}
void
reset()
{
for (auto &timer : timers)
timer.reset();
}
void
enter(const std::string &label)
{
path.emplace_back(path.back() + label + ":");
}
void
leave()
{
path.resize(path.size() - 1);
}
template <typename StreamType>
void
print(const MPI_Comm &comm, StreamType &stream) const
{
std::vector<std::pair<std::string, std::array<double, 1>>> list;
std::vector<std::pair<std::string, unsigned int>> list_count;
unsigned int counter = 0;
unsigned int max_counter = 0;
for (const auto &time : map)
{
list.emplace_back(time.first,
std::array<double, 1>{
{timers[time.second].get_accumulated_time() /
1000000}});
list_count.emplace_back(time.first,
timers[time.second].get_counter());
if (time.first == "id_total")
max_counter = counter;
counter++;
}
internal::print_(
stream, comm, list, list_count, {"Time [sec]"}, max_counter);
}
void
print_log(const MPI_Comm &comm_global, const std::string &prefix) const
{
const auto print_statistics =
[&](const auto &v, std::string slabel, const unsigned int tag) {
const auto my_rank =
dealii::Utilities::MPI::this_mpi_process(comm_global);
if (my_rank == 0)
{
std::ofstream myfile;
myfile.open(prefix + "_" + slabel + ".stat");
for (unsigned int i = 0;
i < dealii::Utilities::MPI::n_mpi_processes(comm_global);
i++)
{
std::vector<double> recv_data;
if (i == 0)
{
recv_data = v;
}
else
{
// wait for any request
MPI_Status status;
auto ierr =
MPI_Probe(MPI_ANY_SOURCE, tag, comm_global, &status);
AssertThrowMPI(ierr);
// determine number of ghost faces * 2 (since we are
// considering pairs)
int len;
MPI_Get_count(
&status,
dealii::Utilities::MPI::mpi_type_id_for_type<double>,
&len);
recv_data.resize(len);
// receive data
MPI_Recv(
recv_data.data(),
len,
dealii::Utilities::MPI::mpi_type_id_for_type<double>,
status.MPI_SOURCE,
status.MPI_TAG,
comm_global,
&status);
}
for (const auto j : recv_data)
myfile << i << " " << j << std::endl;
}
myfile.close();
}
else
{
MPI_Send(v.data(),
v.size(),
dealii::Utilities::MPI::mpi_type_id_for_type<double>,
0,
tag,
comm_global);
}
MPI_Barrier(comm_global);
};
unsigned int tag = 110;
for (const auto &time : map)
print_statistics(timers[time.second].get_log(),
std::string(time.first),
tag++);
}
private:
// translator label -> unique id
std::map<std::string, unsigned int> map;
// list of timers
std::vector<Timer> timers;
std::vector<std::string> path;
const bool log_all_calls;
};
class ScopedTimerWrapper
{
public:
ScopedTimerWrapper(Timer &timer)
: timer(&timer)
{
#ifdef PERFORMANCE_TIMING
this->timer->start();
#endif
}
ScopedTimerWrapper(Timers &timers, const std::string &label)
: ScopedTimerWrapper(&timers, label)
{}
ScopedTimerWrapper(Timers *timers, const std::string &label)
:
#ifdef PERFORMANCE_TIMING
timer(timers == nullptr ? nullptr : &timers->operator[](label))
#else
timer(nullptr)
#endif
{
#ifdef PERFORMANCE_TIMING
if (timer != nullptr)
timer->start();
#endif
}
~ScopedTimerWrapper()
{
#ifdef PERFORMANCE_TIMING
if (timer != nullptr)
timer->stop();
#endif
}
Timer *timer;
};
class ScopedLikwidTimerWrapper
{
public:
ScopedLikwidTimerWrapper(const std::string label)
: label(label)
{
#ifdef LIKWID_PERFMON
LIKWID_MARKER_START(label.c_str());
#endif
}
~ScopedLikwidTimerWrapper()
{
#ifdef LIKWID_PERFMON
LIKWID_MARKER_STOP(label.c_str());
#endif
}
private:
const std::string label;
};
} // namespace hyperdeal
#endif
| 8,022
|
C++
|
.h
| 277
| 20.079422
| 78
| 0.510926
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,169
|
config.h
|
hyperdeal_hyperdeal/include/hyper.deal/base/config.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_CONFIG
#define HYPERDEAL_CONFIG
#define PERFORMANCE_TIMING
#endif
| 734
|
C++
|
.h
| 18
| 39.611111
| 72
| 0.611501
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,170
|
tests_mf.h
|
hyperdeal_hyperdeal/tests/tests_mf.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#include <deal.II/base/parameter_handler.h>
#include <deal.II/distributed/fully_distributed_tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/matrix_free/matrix_free.h>
#include <hyper.deal/base/mpi.h>
#include <hyper.deal/matrix_free/matrix_free.h>
#include "tests.h"
namespace hyperdeal
{
struct Parameters
{
std::string triangulation_type;
unsigned int degree = 1;
unsigned int mapping_degree = 1;
bool do_collocation = false;
bool do_ghost_faces = true;
bool do_buffering = false;
bool use_ecl = true;
unsigned int overlapping_level = 0;
bool print_parameter = false;
Parameters() = default;
Parameters(const std::string & file_name,
const dealii::ConditionalOStream &pcout)
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
add_parameters(prm);
prm.parse_input_from_json(file, true);
if (print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("General");
prm.add_parameter("Degree", degree);
prm.add_parameter("Verbose", print_parameter);
prm.leave_subsection();
prm.enter_subsection("Triangulation");
prm.add_parameter("Type", triangulation_type);
prm.leave_subsection();
prm.enter_subsection("SpatialDiscretization");
prm.add_parameter("Mapping", mapping_degree);
prm.add_parameter("DoCollocation", do_collocation);
prm.leave_subsection();
prm.enter_subsection("MatrixFree");
prm.add_parameter("GhostFaces", do_ghost_faces);
prm.add_parameter("DoBuffering", do_buffering);
prm.add_parameter("UseECL", use_ecl);
prm.add_parameter("OverlappingLevel", overlapping_level);
prm.leave_subsection();
}
};
template <int dim_x, int dim_v, typename Number, typename VectorizedArrayType>
class MatrixFreeWrapper
{
public:
static const int dim = dim_x + dim_v;
using MF = hyperdeal::MatrixFree<dim_x, dim_v, Number, VectorizedArrayType>;
using VectorizedArrayTypeX = typename MF::VectorizedArrayTypeX;
using VectorizedArrayTypeV = typename MF::VectorizedArrayTypeV;
MatrixFreeWrapper(const MPI_Comm & comm_global,
const MPI_Comm & comm_sm,
const unsigned int size_x,
const unsigned int size_v)
: comm_global(comm_global)
, comm_sm(comm_sm)
, comm_row(mpi::create_row_comm(comm_global, size_x, size_v))
, comm_column(mpi::create_column_comm(comm_global, size_x, size_v))
, matrix_free(comm_global, comm_sm, matrix_free_x, matrix_free_v)
{}
template <typename Fu>
void
init(const Parameters param, const Fu &create_grid)
{
const auto degree_x = param.degree;
const auto degree_v = param.degree;
const auto n_points_x = degree_x + 1;
const auto n_points_v = degree_v + 1;
const auto mapping_degree_x = param.mapping_degree;
const auto mapping_degree_v = param.mapping_degree;
// step 1: create two low-dimensional triangulations
{
// clang-format off
if(param.triangulation_type == "fullydistributed")
{
triangulation_x.reset(new dealii::parallel::fullydistributed::Triangulation<dim_x>(comm_row));
triangulation_v.reset(new dealii::parallel::fullydistributed::Triangulation<dim_v>(comm_column));
}
#ifdef DEAL_II_WITH_P4EST
else if(param.triangulation_type == "distributed")
{
triangulation_x.reset(new dealii::parallel::distributed::Triangulation<dim_x>(comm_row,
dealii::Triangulation<dim_x>::none,
dealii::parallel::distributed::Triangulation<dim_x>::construct_multigrid_hierarchy));
triangulation_v.reset(new dealii::parallel::distributed::Triangulation<dim_v>(comm_column,
dealii::Triangulation<dim_v>::none,
dealii::parallel::distributed::Triangulation<dim_v>::construct_multigrid_hierarchy));
}
#endif
else
AssertThrow(false, dealii::ExcMessage("Unknown triangulation!"));
// clang-format on
create_grid(triangulation_x, triangulation_v);
}
// step 2: create two low-dimensional dof-handler
{
dof_handler_x.reset(new dealii::DoFHandler<dim_x>(*triangulation_x));
dof_handler_v.reset(new dealii::DoFHandler<dim_v>(*triangulation_v));
dealii::FE_DGQ<dim_x> fe_x(degree_x);
dealii::FE_DGQ<dim_v> fe_v(degree_v);
dof_handler_x->distribute_dofs(fe_x);
dof_handler_v->distribute_dofs(fe_v);
}
// step 3: setup two low-dimensional matrix-frees
{
dealii::AffineConstraints<Number> constraint;
constraint.close();
{
typename dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX>::
AdditionalData additional_data;
additional_data.mapping_update_flags =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.mapping_update_flags_inner_faces =
dealii::update_gradients | dealii::update_JxW_values;
additional_data.mapping_update_flags_boundary_faces =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.hold_all_faces_to_owned_cells = true;
additional_data.mapping_update_flags_faces_by_cells =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
dealii::MappingQGeneric<dim_x> mapping_x(mapping_degree_x);
std::vector<const dealii::DoFHandler<dim_x> *> dof_handlers{
&*dof_handler_x};
std::vector<const dealii::AffineConstraints<Number> *> constraints{
&constraint};
std::vector<dealii::Quadrature<1>> quads;
if (param.do_collocation)
quads.push_back(dealii::QGaussLobatto<1>(n_points_x));
else
quads.push_back(dealii::QGauss<1>(n_points_x));
quads.push_back(dealii::QGauss<1>(degree_x + 1));
quads.push_back(dealii::QGaussLobatto<1>(degree_x + 1));
matrix_free_x.reinit(
mapping_x, dof_handlers, constraints, quads, additional_data);
}
{
typename dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV>::
AdditionalData additional_data;
additional_data.mapping_update_flags =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.mapping_update_flags_inner_faces =
dealii::update_gradients | dealii::update_JxW_values;
additional_data.mapping_update_flags_boundary_faces =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
additional_data.hold_all_faces_to_owned_cells = true;
additional_data.mapping_update_flags_faces_by_cells =
dealii::update_gradients | dealii::update_JxW_values |
dealii::update_quadrature_points;
dealii::MappingQGeneric<dim_v> mapping_v(mapping_degree_v);
std::vector<const dealii::DoFHandler<dim_v> *> dof_handlers{
&*dof_handler_v};
std::vector<const dealii::AffineConstraints<Number> *> constraints{
&constraint};
std::vector<dealii::Quadrature<1>> quads;
if (param.do_collocation)
quads.push_back(dealii::QGaussLobatto<1>(n_points_v));
else
quads.push_back(dealii::QGauss<1>(n_points_v));
quads.push_back(dealii::QGauss<1>(degree_v + 1));
quads.push_back(dealii::QGaussLobatto<1>(degree_v + 1));
matrix_free_v.reinit(
mapping_v, dof_handlers, constraints, quads, additional_data);
}
}
// step 4: setup tensor-product matrixfree
{
typename MF::AdditionalData ad;
ad.do_ghost_faces = param.do_ghost_faces;
ad.do_buffering = param.do_buffering;
ad.use_ecl = param.use_ecl;
ad.overlapping_level = param.overlapping_level;
matrix_free.reinit(ad);
}
}
const MF &
get_matrix_free() const
{
return matrix_free;
}
dealii::types::global_dof_index
n_dofs() const
{
return dof_handler_x->n_dofs() * dof_handler_v->n_dofs();
}
dealii::types::global_dof_index
n_dofs_x() const
{
return dof_handler_x->n_dofs();
}
dealii::types::global_dof_index
n_dofs_v() const
{
return dof_handler_v->n_dofs();
}
const MPI_Comm &
get_comm_row()
{
return comm_row;
}
const MPI_Comm &
get_comm_column()
{
return comm_column;
}
protected:
const MPI_Comm &comm_global;
const MPI_Comm &comm_sm;
MPI_Comm comm_row;
MPI_Comm comm_column;
// x- and v-space objects
std::shared_ptr<dealii::parallel::TriangulationBase<dim_x>> triangulation_x;
std::shared_ptr<dealii::parallel::TriangulationBase<dim_v>> triangulation_v;
std::shared_ptr<dealii::DoFHandler<dim_x>> dof_handler_x;
std::shared_ptr<dealii::DoFHandler<dim_v>> dof_handler_v;
dealii::MatrixFree<dim_x, Number, VectorizedArrayTypeX> matrix_free_x;
dealii::MatrixFree<dim_v, Number, VectorizedArrayTypeV> matrix_free_v;
MF matrix_free;
};
} // namespace hyperdeal
| 10,707
|
C++
|
.h
| 253
| 34.44664
| 111
| 0.627368
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,172
|
tests_functions.h
|
hyperdeal_hyperdeal/tests/tests_functions.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_TESTS_FUNCTIONS
#define HYPERDEAL_TESTS_FUNCTIONS
#include <deal.II/base/function.h>
template <int DIM, typename Number>
class SinusConsinusFunction : public dealii::Function<DIM, Number>
{
public:
SinusConsinusFunction()
: dealii::Function<DIM, Number>(1)
{}
virtual Number
value(const dealii::Point<DIM> &p, const unsigned int = 1) const override
{
Number result = std::sin(p[0] * dealii::numbers::PI);
for (unsigned int d = 1; d < DIM; ++d)
result *= std::cos(p[d] * dealii::numbers::PI);
return result;
}
};
template <int DIM, typename Number>
class DistanceFunction : public dealii::Function<DIM, Number>
{
public:
DistanceFunction()
: dealii::Function<DIM, Number>(1)
{}
virtual Number
value(const dealii::Point<DIM> &p, const unsigned int = 1) const override
{
return std::max(0.0, (0.5 - p.norm()));
}
};
#endif
| 1,548
|
C++
|
.h
| 47
| 30.595745
| 75
| 0.648123
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,173
|
driver.h
|
hyperdeal_hyperdeal/performance/util/driver.h
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2020 by the hyper.deal authors
//
// This file is part of the hyper.deal library.
//
// The hyper.deal library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.MD at
// the top level directory of hyper.deal.
//
// ---------------------------------------------------------------------
#ifndef HYPERDEAL_PERFORMANCE_UTIL_DRIVER
#define HYPERDEAL_PERFORMANCE_UTIL_DRIVER
#include <hyper.deal/base/config.h>
#include <deal.II/base/mpi.h>
#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/revision.h>
#include <hyper.deal/base/dynamic_convergence_table.h>
#include <hyper.deal/base/mpi.h>
#include <hyper.deal/base/utilities.h>
#include <fstream>
const MPI_Comm comm = MPI_COMM_WORLD;
#ifdef LIKWID_PERFMON
# include <likwid.h>
#endif
#ifndef NUMBER_TYPE
# define NUMBER_TYPE double
#endif
#ifndef MIN_DEGREE
# define MIN_DEGREE 2
#endif
#ifndef MAX_DEGREE
# define MAX_DEGREE 6
#endif
#ifndef MIN_DIM
# define MIN_DIM 2
#endif
#ifndef MAX_DIM
# define MAX_DIM 6
#endif
#ifndef MIN_SIMD_LENGTH
# define MIN_SIMD_LENGTH 0
#endif
#ifndef MAX_SIMD_LENGTH
# define MAX_SIMD_LENGTH 8
#endif
template <int dim_x,
int dim_v,
int degree,
int n_points,
typename Number,
typename VectorizedArrayType>
void
test(const MPI_Comm & comm_global,
const MPI_Comm & comm_sm,
const unsigned int size_x,
const unsigned int size_v,
hyperdeal::DynamicConvergenceTable &table,
const std::string file_name);
struct ParametersDriver
{
ParametersDriver()
{}
ParametersDriver(const std::string & file_name,
const dealii::ConditionalOStream &pcout)
{
dealii::ParameterHandler prm;
std::ifstream file;
file.open(file_name);
add_parameters(prm);
prm.parse_input_from_json(file, true);
if (print_parameter && pcout.is_active())
prm.print_parameters(pcout.get_stream(),
dealii::ParameterHandler::OutputStyle::PRM);
file.close();
}
void
add_parameters(dealii::ParameterHandler &prm)
{
prm.enter_subsection("General");
prm.add_parameter("VLen", v_len);
prm.add_parameter("Dim", dim);
prm.add_parameter("Degree", degree);
prm.add_parameter("PartitionX", partition_x);
prm.add_parameter("PartitionV", partition_v);
prm.add_parameter("UseVirtualTopology", use_virtual_topology);
prm.add_parameter("UseSharedMemory", use_shared_memory);
prm.add_parameter("Verbose", print_parameter);
prm.leave_subsection();
}
unsigned int v_len = 0;
unsigned int dim = 4;
unsigned int degree = 3;
unsigned int partition_x = 1;
unsigned int partition_v = 1;
bool use_virtual_topology = true;
bool use_shared_memory = true;
bool print_parameter = false;
};
template <typename VectorizedArrayType,
int dim_x,
int dim_v,
int degree,
int n_points = degree + 1>
void
run_degree(const ParametersDriver & param,
hyperdeal::DynamicConvergenceTable &table,
const std::string file_name)
{
// partitions of x- and v-space
const unsigned int size_x = param.partition_x;
const unsigned int size_v = param.partition_v;
// create rectangular communicator
MPI_Comm comm_global =
hyperdeal::mpi::create_rectangular_comm(comm, size_x, size_v);
// only proceed if process part of new communicator
if (comm_global != MPI_COMM_NULL)
{
// create communicator for shared memory (only create once since
// expensive)
MPI_Comm comm_sm = hyperdeal::mpi::create_sm(comm_global);
// optionally create virtual topology (blocked Morton order)
MPI_Comm comm_z =
param.use_virtual_topology ?
hyperdeal::mpi::create_z_order_comm(
comm_global,
{size_x, size_v},
hyperdeal::Utilities::decompose(
hyperdeal::mpi::n_procs_of_sm(comm_global, comm_sm))) :
comm_global;
#ifdef DEBUG
if (param.print_parameter)
{
hyperdeal::mpi::print_sm(comm_z, comm_sm);
hyperdeal::mpi::print_new_order(comm, comm_z);
}
#endif
// process problem
test<dim_x, dim_v, degree, n_points, NUMBER_TYPE, VectorizedArrayType>(
comm_z,
param.use_shared_memory ? comm_sm : MPI_COMM_SELF,
size_x,
size_v,
table,
file_name);
// free communicators
if (param.use_virtual_topology)
MPI_Comm_free(&comm_z);
MPI_Comm_free(&comm_sm);
MPI_Comm_free(&comm_global);
// print results
table.add_new_row();
table.print(false);
}
else
{
#ifdef DEBUG
if (param.print_parameter)
hyperdeal::mpi::print_new_order(comm, MPI_COMM_NULL);
#endif
}
}
template <typename VectorizedArrayType, int dim_x, int dim_v>
void
run_dim(const ParametersDriver & param,
hyperdeal::DynamicConvergenceTable &table,
const std::string file_name)
{
// clang-format off
switch(param.degree)
{
#if MIN_DEGREE <= 2 && 2 <= MAX_DEGREE
case 2: run_degree<VectorizedArrayType, dim_x, dim_v, 2>(param, table, file_name); break;
#endif
#if MIN_DEGREE <= 3 && 3 <= MAX_DEGREE
case 3: run_degree<VectorizedArrayType, dim_x, dim_v, 3>(param, table, file_name); break;
#endif
#if MIN_DEGREE <= 4 && 4 <= MAX_DEGREE
case 4: run_degree<VectorizedArrayType, dim_x, dim_v, 4>(param, table, file_name); break;
#endif
#if MIN_DEGREE <= 5 && 5 <= MAX_DEGREE
case 5: run_degree<VectorizedArrayType, dim_x, dim_v, 5>(param, table, file_name); break;
#endif
#if MIN_DEGREE <= 6 && 6 <= MAX_DEGREE
case 6: run_degree<VectorizedArrayType, dim_x, dim_v, 6>(param, table, file_name); break;
#endif
default:
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
// clang-format on
}
template <typename VectorizedArrayType>
void
run_simd(const ParametersDriver & param,
hyperdeal::DynamicConvergenceTable &table,
const std::string file_name)
{
// clang-format off
switch(param.dim)
{
#if MIN_DIM <= 2 && 2 <= MAX_DIM
case 2: run_dim<VectorizedArrayType, 1, 1>(param, table, file_name); break;
#endif
#if MIN_DIM <= 3 && 3 <= MAX_DIM
case 3: run_dim<VectorizedArrayType, 2, 1>(param, table, file_name); break;
#endif
#if MIN_DIM <= 4 && 4 <= MAX_DIM
case 4: run_dim<VectorizedArrayType, 2, 2>(param, table, file_name); break;
#endif
#if MIN_DIM <= 5 && 5 <= MAX_DIM
case 5: run_dim<VectorizedArrayType, 3, 2>(param, table, file_name); break;
#endif
#if MIN_DIM <= 6 && 6 <= MAX_DIM
case 6: run_dim<VectorizedArrayType, 3, 3>(param, table, file_name); break;
#endif
default:
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
// clang-format on
}
void
run(hyperdeal::DynamicConvergenceTable &table, const std::string file_name)
{
// read input parameter file
const ParametersDriver param(
file_name,
dealii::ConditionalOStream(std::cout,
dealii::Utilities::MPI::this_mpi_process(comm) ==
0));
// clang-format off
switch(param.v_len)
{
case 0: run_simd<dealii::VectorizedArray<NUMBER_TYPE> >(param, table, file_name); break;
#if MIN_SIMD_LENGTH <= 1 && 1 <= MAX_SIMD_LENGTH
case 1: run_simd<dealii::VectorizedArray<NUMBER_TYPE,1>>(param, table, file_name); break;
#endif
#if MIN_SIMD_LENGTH <= 2 && 2 <= MAX_SIMD_LENGTH
case 2: run_simd<dealii::VectorizedArray<NUMBER_TYPE,2>>(param, table, file_name); break;
#endif
#if MIN_SIMD_LENGTH <= 4 && 4 <= MAX_SIMD_LENGTH
case 4: run_simd<dealii::VectorizedArray<NUMBER_TYPE,4>>(param, table, file_name); break;
#endif
#if MIN_SIMD_LENGTH <= 8 && 8 <= MAX_SIMD_LENGTH
case 8: run_simd<dealii::VectorizedArray<NUMBER_TYPE,8>>(param, table, file_name); break;
#endif
default:
AssertThrow(false, dealii::StandardExceptions::ExcNotImplemented());
}
// clang-format on
}
int
main(int argc, char **argv)
{
try
{
dealii::Utilities::MPI::MPI_InitFinalize mpi(argc, argv, 1);
if (dealii::Utilities::MPI::this_mpi_process(comm) == 0)
printf("deal.II git version %s on branch %s\n\n",
DEAL_II_GIT_SHORTREV,
DEAL_II_GIT_BRANCH);
dealii::deallog.depth_console(0);
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
LIKWID_MARKER_THREADINIT;
#endif
hyperdeal::DynamicConvergenceTable table;
if (argc == 1)
{
if (dealii::Utilities::MPI::this_mpi_process(comm) == 0)
printf("ERROR: No .json parameter files has been provided!\n");
return 1;
}
for (int i = 1; i < argc; i++)
{
if (dealii::Utilities::MPI::this_mpi_process(comm) == 0)
std::cout << std::string(argv[i]) << std::endl;
run(table, std::string(argv[i]));
}
table.print(false);
#ifdef LIKWID_PERFMON
LIKWID_MARKER_CLOSE;
#endif
}
catch (std::exception &exc)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
return 0;
}
#endif
| 10,515
|
C++
|
.h
| 314
| 28.149682
| 94
| 0.603467
|
hyperdeal/hyperdeal
| 32
| 9
| 9
|
LGPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,174
|
obs-ssp-source.cpp
|
summershrimp_obs-ssp/src/obs-ssp-source.cpp
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#include <string>
#include <string.h>
#include <stdlib.h>
#include "ssp-mdns.h"
#ifdef _WIN32
#include <Windows.h>
#endif
#include <functional>
#include <QObject>
#include <mutex>
#include <obs-module.h>
#include <obs.h>
#include <util/platform.h>
#include <util/threading.h>
#include <chrono>
#include <thread>
#include "obs-ssp.h"
#include "imf/ISspClient.h"
#include "imf/threadloop.h"
#include "ssp-controller.h"
#include "ssp-client-iso.h"
#include "VFrameQueue.h"
extern "C" {
#include "ffmpeg-decode.h"
}
#define PROP_SOURCE_IP "ssp_source_ip"
#define PROP_CUSTOM_SOURCE_IP "ssp_custom_source_ip"
#define PROP_NO_CHECK "ssp_no_check"
#define PROP_CHECK_IP "ssp_check_ip"
#define PROP_CUSTOM_VALUE "\x01\x02custom"
#define PROP_HW_ACCEL "ssp_recv_hw_accel"
#define PROP_SYNC "ssp_sync"
#define PROP_LATENCY "latency"
#define PROP_VIDEO_RANGE "video_range"
#define PROP_EXP_WAIT_I "exp_wait_i_frame"
#define PROP_BW_HIGHEST 0
#define PROP_BW_LOWEST 1
#define PROP_BW_AUDIO_ONLY 2
#define PROP_SYNC_INTERNAL 0
#define PROP_SYNC_SSP_TIMESTAMP 1
#define PROP_LATENCY_NORMAL 0
#define PROP_LATENCY_LOW 1
#define PROP_LED_TALLY "led_as_tally_light"
#define PROP_RESOLUTION "ssp_resolution"
#define PROP_FRAME_RATE "ssp_frame_rate"
#define PROP_LOW_NOISE "ssp_low_noise"
#define PROP_BITRATE "ssp_bitrate"
#define PROP_STREAM_INDEX "ssp_stream_index"
#define PROP_ENCODER "ssp_encoding"
#define SSP_IP_DIRECT "10.98.32.1"
#define SSP_IP_WIFI "10.98.33.1"
#define SSP_IP_USB "172.18.18.1"
using namespace std::placeholders;
struct ssp_source;
struct ssp_connection {
SSPClientIso *client;
ffmpeg_decode vdecoder;
uint32_t width;
uint32_t height;
AVCodecID vformat;
obs_source_frame2 frame;
ffmpeg_decode adecoder;
uint32_t sample_size;
AVCodecID aformat;
obs_source_audio audio;
VFrameQueue *queue;
bool running;
int i_frame_shown;
// copy from ssp_source
char *source_ip;
int hwaccel;
int bitrate;
int wait_i_frame;
int sync_mode;
obs_source_t *source;
// not used
int video_range;
pthread_mutex_t lck;
};
struct ssp_source {
obs_source_t *source;
CameraStatus *cameraStatus;
int sync_mode;
int video_range;
int hwaccel;
int bitrate;
int wait_i_frame;
int tally;
bool do_check;
bool no_check;
bool ip_checked;
const char *source_ip;
ssp_connection *conn;
};
static void ssp_conn_start(ssp_connection *s);
static void ssp_conn_stop(ssp_connection *s);
static void ssp_stop(ssp_source *s);
static void ssp_start(ssp_source *s);
void *thread_ssp_reconnect(void *data);
static void ssp_video_data_enqueue(struct imf::SspH264Data *video,
ssp_connection *s)
{
if (!s->running) {
return;
}
if (!s->queue) {
return;
}
s->queue->enqueue(*video, video->pts, video->type == 5);
}
static void ssp_on_video_data(struct imf::SspH264Data *video, ssp_connection *s)
{
if (!s->running) {
return;
}
if (!ffmpeg_decode_valid(&s->vdecoder)) {
assert(s->vformat == AV_CODEC_ID_H264 ||
s->vformat == AV_CODEC_ID_HEVC);
if (ffmpeg_decode_init(&s->vdecoder, s->vformat, s->hwaccel) <
0) {
ssp_blog(LOG_WARNING,
"Could not initialize video decoder");
return;
}
}
if (s->wait_i_frame && !s->i_frame_shown) {
if (video->type == 5) {
s->i_frame_shown = true;
} else {
return;
}
}
int64_t ts = video->pts;
bool got_output;
bool success = ffmpeg_decode_video(&s->vdecoder, video->data,
video->len, &ts, VIDEO_CS_DEFAULT,
VIDEO_RANGE_PARTIAL, &s->frame,
&got_output);
if (!success) {
ssp_blog(LOG_WARNING, "Error decoding video");
return;
}
if (got_output) {
if (s->sync_mode == PROP_SYNC_INTERNAL) {
s->frame.timestamp = os_gettime_ns();
} else {
s->frame.timestamp = (uint64_t)video->pts * 1000;
}
// if (flip)
// frame.flip = !frame.flip;
obs_source_output_video2(s->source, &s->frame);
}
}
static void ssp_on_audio_data(struct imf::SspAudioData *audio,
ssp_connection *s)
{
if (!s->running) {
return;
}
if (!ffmpeg_decode_valid(&s->adecoder)) {
if (ffmpeg_decode_init(&s->adecoder, s->aformat, false) < 0) {
ssp_blog(LOG_WARNING,
"Could not initialize audio decoder");
return;
}
}
uint8_t *data = audio->data;
size_t size = audio->len;
bool got_output = false;
do {
bool success = ffmpeg_decode_audio(&s->adecoder, data, size,
&s->audio, &got_output);
if (!success) {
ssp_blog(LOG_WARNING, "Error decoding audio");
return;
}
if (got_output) {
if (s->sync_mode == PROP_SYNC_INTERNAL) {
s->audio.timestamp = os_gettime_ns();
s->audio.timestamp +=
((uint64_t)s->audio.samples_per_sec *
1000000000ULL /
(uint64_t)s->sample_size);
} else {
s->audio.timestamp =
(uint64_t)audio->pts * 1000;
}
obs_source_output_audio(s->source, &s->audio);
} else {
break;
}
size = 0;
data = nullptr;
} while (got_output);
}
static void ssp_on_meta_data(struct imf::SspVideoMeta *v,
struct imf::SspAudioMeta *a,
struct imf::SspMeta *m, ssp_connection *s)
{
ssp_blog(
LOG_INFO,
"ssp v meta: encoder: %u, gop:%u, height:%u, timescale:%u, unit:%u, width:%u",
v->encoder, v->gop, v->height, v->timescale, v->unit, v->width);
ssp_blog(
LOG_INFO,
"ssp a meta: uinit: %u, timescale:%u, encoder:%u, bitrate:%u, channel:%u, sample_rate:%u, sample_size:%u",
a->unit, a->timescale, a->encoder, a->bitrate, a->channel,
a->sample_rate, a->sample_size);
ssp_blog(
LOG_INFO,
"ssp i meta: pts_is_wall_clock: %u, tc_drop_frame:%u, timecode:%u,",
m->pts_is_wall_clock, m->tc_drop_frame, m->timecode);
s->vformat = v->encoder == VIDEO_ENCODER_H264 ? AV_CODEC_ID_H264
: AV_CODEC_ID_H265;
s->frame.width = v->width;
s->frame.height = v->height;
s->sample_size = a->sample_size;
s->audio.samples_per_sec = a->sample_rate;
s->aformat = a->encoder == AUDIO_ENCODER_AAC ? AV_CODEC_ID_AAC
: AV_CODEC_ID_NONE;
}
static void ssp_on_disconnected(ssp_connection *s)
{
ssp_blog(LOG_INFO, "ssp device disconnected.");
pthread_t thread;
if (s->running) {
ssp_blog(LOG_INFO, "still running, reconnect...");
pthread_create(&thread, nullptr, thread_ssp_reconnect,
(void *)s);
pthread_detach(thread);
}
}
static void ssp_on_exception(int code, const char *description,
ssp_connection *s)
{
ssp_blog(LOG_ERROR, "ssp exception %d: %s", code, description);
//s->running = false;
}
static void ssp_start(ssp_source *s)
{
auto conn = (ssp_connection *)bzalloc(sizeof(ssp_connection));
conn->source = s->source;
conn->source_ip = strdup(s->source_ip);
conn->wait_i_frame = s->wait_i_frame;
conn->hwaccel = s->hwaccel;
conn->bitrate = s->bitrate;
conn->sync_mode = s->sync_mode;
conn->video_range = s->video_range;
pthread_mutex_init(&conn->lck, nullptr);
s->conn = conn;
ssp_conn_start(conn);
}
static void ssp_conn_stop(ssp_connection *conn)
{
ssp_blog(LOG_INFO, "Stopping ssp client...");
pthread_mutex_lock(&conn->lck);
conn->running = false;
auto client = conn->client;
auto queue = conn->queue;
if (client) {
client->Stop();
delete client;
}
if (queue) {
queue->stop();
delete queue;
}
ssp_blog(LOG_INFO, "SSP client stopped.");
if (ffmpeg_decode_valid(&conn->adecoder)) {
ffmpeg_decode_free(&conn->adecoder);
}
if (ffmpeg_decode_valid(&conn->vdecoder)) {
ffmpeg_decode_free(&conn->vdecoder);
}
ssp_blog(LOG_INFO, "SSP conn stopped.");
pthread_mutex_unlock(&conn->lck);
}
static void ssp_stop(ssp_source *s)
{
if (!s) {
return;
}
auto conn = s->conn;
s->conn = nullptr;
if (!conn) {
return;
}
ssp_conn_stop(conn);
free((void *)conn->source_ip);
bfree(conn);
}
static void ssp_conn_start(ssp_connection *s)
{
ssp_blog(LOG_INFO, "Starting ssp client...");
assert(s->client == nullptr);
assert(s->source != nullptr);
std::string ip = s->source_ip;
ssp_blog(LOG_INFO, "target ip: %s", s->source_ip);
ssp_blog(LOG_INFO, "source bitrate: %d", s->bitrate);
if (strlen(s->source_ip) == 0) {
return;
}
pthread_mutex_lock(&s->lck);
s->client = new SSPClientIso(ip, s->bitrate / 8);
s->client->setOnH264DataCallback(
std::bind(ssp_video_data_enqueue, _1, s));
s->client->setOnAudioDataCallback(std::bind(ssp_on_audio_data, _1, s));
s->client->setOnMetaCallback(
std::bind(ssp_on_meta_data, _1, _2, _3, s));
s->client->setOnConnectionConnectedCallback(
[]() { ssp_blog(LOG_INFO, "ssp connected."); });
s->client->setOnDisconnectedCallback(std::bind(ssp_on_disconnected, s));
s->client->setOnExceptionCallback(
std::bind(ssp_on_exception, _1, _2, s));
assert(s->queue == nullptr);
s->queue = new VFrameQueue;
s->queue->setFrameCallback(std::bind(ssp_on_video_data, _1, s));
s->queue->start();
emit s->client->Start();
s->running = true;
pthread_mutex_unlock(&s->lck);
ssp_blog(LOG_INFO, "SSP client started.");
}
void *thread_ssp_reconnect(void *data)
{
auto conn = (ssp_connection *)data;
ssp_blog(LOG_INFO, "Stopping ssp client...");
pthread_mutex_lock(&conn->lck);
if (!conn->running) {
pthread_mutex_unlock(&conn->lck);
return nullptr;
}
auto client = conn->client;
auto queue = conn->queue;
if (client) {
client->Stop();
delete client;
}
if (queue) {
queue->stop();
delete queue;
}
ssp_blog(LOG_INFO, "SSP client stopped.");
if (ffmpeg_decode_valid(&conn->adecoder)) {
ffmpeg_decode_free(&conn->adecoder);
}
if (ffmpeg_decode_valid(&conn->vdecoder)) {
ffmpeg_decode_free(&conn->vdecoder);
}
ssp_blog(LOG_INFO, "SSP conn stopped.");
ssp_blog(LOG_INFO, "Starting ssp client...");
assert(conn->client == nullptr);
assert(conn->source != nullptr);
std::string ip = conn->source_ip;
ssp_blog(LOG_INFO, "target ip: %s", conn->source_ip);
ssp_blog(LOG_INFO, "source bitrate: %d", conn->bitrate);
if (strlen(conn->source_ip) == 0) {
pthread_mutex_unlock(&conn->lck);
return nullptr;
}
conn->client = new SSPClientIso(ip, conn->bitrate / 8);
conn->client->setOnH264DataCallback(
std::bind(ssp_video_data_enqueue, _1, conn));
conn->client->setOnAudioDataCallback(
std::bind(ssp_on_audio_data, _1, conn));
conn->client->setOnMetaCallback(
std::bind(ssp_on_meta_data, _1, _2, _3, conn));
conn->client->setOnConnectionConnectedCallback(
[]() { ssp_blog(LOG_INFO, "ssp connected."); });
conn->client->setOnDisconnectedCallback(
std::bind(ssp_on_disconnected, conn));
conn->client->setOnExceptionCallback(
std::bind(ssp_on_exception, _1, _2, conn));
assert(conn->queue == nullptr);
conn->queue = new VFrameQueue;
conn->queue->setFrameCallback(std::bind(ssp_on_video_data, _1, conn));
conn->queue->start();
emit conn->client->Start();
pthread_mutex_unlock(&conn->lck);
ssp_blog(LOG_INFO, "SSP client started.");
return nullptr;
}
static obs_source_frame *blank_video_frame()
{
obs_source_frame *frame =
obs_source_frame_create(VIDEO_FORMAT_NONE, 0, 0);
frame->timestamp = os_gettime_ns();
return frame;
}
const char *ssp_source_getname(void *data)
{
UNUSED_PARAMETER(data);
return obs_module_text("SSPPlugin.SSPSourceName");
}
bool source_ip_modified(void *data, obs_properties_t *props,
obs_property_t *property, obs_data_t *settings)
{
auto s = (struct ssp_source *)data;
const char *source_ip = obs_data_get_string(settings, PROP_SOURCE_IP);
s->ip_checked = false;
if (strcmp(source_ip, PROP_CUSTOM_VALUE) == 0) {
obs_property_t *custom_ip =
obs_properties_get(props, PROP_CUSTOM_SOURCE_IP);
obs_property_t *check_ip =
obs_properties_get(props, PROP_CHECK_IP);
obs_property_set_visible(property, false);
obs_property_set_visible(custom_ip, true);
obs_property_set_visible(check_ip, true);
return true;
}
if (s->cameraStatus->getIp() == source_ip) {
return false;
}
s->cameraStatus->setIp(source_ip);
s->cameraStatus->refreshAll([=](bool ok) {
if (ok) {
s->ip_checked = true;
}
obs_source_update_properties(s->source);
});
return false;
}
static bool custom_ip_modify_callback(void *data, obs_properties_t *props,
obs_property_t *property,
obs_data_t *settings)
{
auto s = (struct ssp_source *)data;
if (s->ip_checked || !s->do_check) {
s->ip_checked = false;
ssp_blog(LOG_INFO, "ip modified, no need to check.");
return false;
}
s->do_check = false;
ssp_blog(LOG_INFO, "ip modified, need to check.");
auto ip = obs_data_get_string(settings, PROP_CUSTOM_SOURCE_IP);
if (strcmp(ip, "") == 0) {
return false;
}
s->cameraStatus->setIp(ip);
s->cameraStatus->refreshAll([=](bool ok) {
if (ok) {
s->ip_checked = true;
}
obs_source_update_properties(s->source);
});
ssp_blog(LOG_INFO, "ip check queued.");
return false;
}
static bool resolution_modify_callback(void *data, obs_properties_t *props,
obs_property_t *property,
obs_data_t *settings)
{
auto s = (struct ssp_source *)data;
auto framerates = obs_properties_get(props, PROP_FRAME_RATE);
obs_property_list_clear(framerates);
if (s->cameraStatus->model.isEmpty()) {
return false;
}
auto resolution = obs_data_get_string(settings, PROP_RESOLUTION);
obs_property_list_add_string(framerates, "25 fps", "25");
obs_property_list_add_string(framerates, "30 fps", "29.97");
ssp_blog(LOG_INFO, "Camera model: %s",
s->cameraStatus->model.toStdString().c_str());
if (strcmp(resolution, "1920*1080") != 0 ||
!s->cameraStatus->model.contains(E2C_MODEL_CODE,
Qt::CaseInsensitive)) {
obs_property_list_add_string(framerates, "50 fps", "50");
obs_property_list_add_string(framerates, "60 fps", "59.94");
}
return true;
}
static bool check_ip_callback(obs_properties_t *props, obs_property_t *property,
void *data)
{
auto s = (struct ssp_source *)data;
s->do_check = true;
obs_source_update_properties(s->source);
return false;
}
obs_properties_t *ssp_source_getproperties(void *data)
{
char nametext[256];
auto s = (struct ssp_source *)data;
obs_properties_t *props = obs_properties_create();
obs_properties_set_flags(props, OBS_PROPERTIES_DEFER_UPDATE);
obs_property_t *source_ip = obs_properties_add_list(
props, PROP_SOURCE_IP,
obs_module_text("SSPPlugin.SourceProps.SourceIp"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
snprintf(nametext, 256, "%s (%s)",
obs_module_text("SSPPlugin.IP.Fixed"), SSP_IP_DIRECT);
obs_property_list_add_string(source_ip, nametext, SSP_IP_DIRECT);
snprintf(nametext, 256, "%s (%s)", obs_module_text("SSPPlugin.IP.Wifi"),
SSP_IP_WIFI);
obs_property_list_add_string(source_ip, nametext, SSP_IP_WIFI);
snprintf(nametext, 256, "%s (%s)", obs_module_text("SSPPlugin.IP.USB"),
SSP_IP_USB);
obs_property_list_add_string(source_ip, nametext, SSP_IP_USB);
int count = 0;
SspMDnsIterator iter;
while (iter.hasNext()) {
ssp_device_item *item = iter.next();
if (item == nullptr) {
continue;
}
snprintf(nametext, 256, "%s (%s)", item->device_name.c_str(),
item->ip_address.c_str());
obs_property_list_add_string(source_ip, nametext,
item->ip_address.c_str());
++count;
}
if (count == 0)
obs_property_list_add_string(
source_ip,
obs_module_text("SSPPlugin.SourceProps.NotFound"), "");
obs_property_list_add_string(
source_ip, obs_module_text("SSPPlugin.SourceProps.Custom"),
PROP_CUSTOM_VALUE);
obs_property_t *custom_source_ip = obs_properties_add_text(
props, PROP_CUSTOM_SOURCE_IP,
obs_module_text("SSPPlugin.SourceProps.SourceIp"),
OBS_TEXT_DEFAULT);
obs_property_t *no_check = obs_properties_add_bool(
props, PROP_NO_CHECK,
obs_module_text("SSPPlugin.SourceProps.DontCheck"));
obs_property_t *check_button = obs_properties_add_button2(
props, PROP_CHECK_IP,
obs_module_text("SSPPlugin.SourceProps.CheckIp"),
check_ip_callback, data);
obs_property_set_visible(custom_source_ip, false);
obs_property_set_visible(check_button, false);
obs_property_set_modified_callback2(source_ip, source_ip_modified,
data);
obs_property_set_modified_callback2(custom_source_ip,
custom_ip_modify_callback, data);
obs_property_t *sync_modes = obs_properties_add_list(
props, PROP_SYNC, obs_module_text("SSPPlugin.SourceProps.Sync"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(
sync_modes, obs_module_text("SSPPlugin.SyncMode.Internal"),
PROP_SYNC_INTERNAL);
obs_property_list_add_int(
sync_modes, obs_module_text("SSPPlugin.SyncMode.SSPTimestamp"),
PROP_SYNC_SSP_TIMESTAMP);
obs_properties_add_bool(
props, PROP_HW_ACCEL,
obs_module_text("SSPPlugin.SourceProps.HWAccel"));
obs_property_t *latency_modes = obs_properties_add_list(
props, PROP_LATENCY,
obs_module_text("SSPPlugin.SourceProps.Latency"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(
latency_modes,
obs_module_text("SSPPlugin.SourceProps.Latency.Normal"),
PROP_LATENCY_NORMAL);
obs_property_list_add_int(
latency_modes,
obs_module_text("SSPPlugin.SourceProps.Latency.Low"),
PROP_LATENCY_LOW);
obs_property_t *encoders = obs_properties_add_list(
props, PROP_ENCODER,
obs_module_text("SSPPlugin.SourceProps.Encoder"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
obs_property_list_add_string(encoders, "H264", "H264");
obs_property_list_add_string(encoders, "H265", "H265");
obs_properties_add_bool(
props, PROP_EXP_WAIT_I,
obs_module_text("SSPPlugin.SourceProps.WaitIFrame"));
obs_property_t *resolutions = obs_properties_add_list(
props, PROP_RESOLUTION,
obs_module_text("SSPPlugin.SourceProps.Resolution"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
obs_property_list_add_string(resolutions, "4K-UHD", "3840*2160");
obs_property_list_add_string(resolutions, "4K-DCI", "4096*2160");
obs_property_list_add_string(resolutions, "1080p", "1920*1080");
obs_properties_add_bool(
props, PROP_LOW_NOISE,
obs_module_text("SSPPlugin.SourceProps.LowNoise"));
obs_property_set_modified_callback2(resolutions,
resolution_modify_callback, data);
obs_property_t *framerate = obs_properties_add_list(
props, PROP_FRAME_RATE,
obs_module_text("SSPPlugin.SourceProps.FrameRate"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
obs_properties_add_int(props, PROP_BITRATE,
obs_module_text("SSPPlugin.SourceProps.Bitrate"),
5, 300, 5);
obs_property_t *tally = obs_properties_add_bool(
props, PROP_LED_TALLY,
obs_module_text("SSPPlugin.SourceProps.LedAsTally"));
if (s->cameraStatus->model.contains(IPMANS_MODEL_CODE,
Qt::CaseInsensitive)) {
obs_property_set_visible(resolutions, false);
obs_property_set_visible(encoders, false);
obs_property_set_visible(framerate, false);
obs_property_set_visible(tally, false);
}
return props;
}
void ssp_source_getdefaults(obs_data_t *settings)
{
obs_data_set_default_int(settings, PROP_SYNC, PROP_SYNC_SSP_TIMESTAMP);
obs_data_set_default_int(settings, PROP_LATENCY, PROP_LATENCY_LOW);
obs_data_set_default_string(settings, PROP_SOURCE_IP, "");
obs_data_set_default_string(settings, PROP_CUSTOM_SOURCE_IP, "");
obs_data_set_default_int(settings, PROP_BITRATE, 20);
obs_data_set_default_bool(settings, PROP_HW_ACCEL, false);
obs_data_set_default_bool(settings, PROP_EXP_WAIT_I, true);
obs_data_set_default_bool(settings, PROP_LED_TALLY, false);
obs_data_set_default_bool(settings, PROP_LOW_NOISE, false);
obs_data_set_default_string(settings, PROP_ENCODER, "H264");
obs_data_set_default_string(settings, PROP_FRAME_RATE, "29.97");
}
void ssp_source_update(void *data, obs_data_t *settings)
{
auto s = (struct ssp_source *)data;
const char *source_ip;
ssp_stop(s);
s->hwaccel = obs_data_get_bool(settings, PROP_HW_ACCEL);
s->sync_mode = (int)obs_data_get_int(settings, PROP_SYNC);
source_ip = obs_data_get_string(settings, PROP_SOURCE_IP);
if (strcmp(source_ip, PROP_CUSTOM_VALUE) == 0) {
source_ip =
obs_data_get_string(settings, PROP_CUSTOM_SOURCE_IP);
}
if (strlen(source_ip) == 0) {
return;
}
if (s->source_ip) {
free((void *)s->source_ip);
}
s->source_ip = strdup(source_ip);
// Set the IP of our camera from the configuration (used to build the url)
s->cameraStatus->setIp(s->source_ip);
const bool is_unbuffered =
(obs_data_get_int(settings, PROP_LATENCY) == PROP_LATENCY_LOW);
obs_source_set_async_unbuffered(s->source, is_unbuffered);
s->wait_i_frame = obs_data_get_bool(settings, PROP_EXP_WAIT_I);
s->tally = obs_data_get_bool(settings, PROP_LED_TALLY);
auto encoder = obs_data_get_string(settings, PROP_ENCODER);
auto resolution = obs_data_get_string(settings, PROP_RESOLUTION);
auto low_noise = obs_data_get_bool(settings, PROP_LOW_NOISE);
auto framerate = obs_data_get_string(settings, PROP_FRAME_RATE);
auto bitrate = obs_data_get_int(settings, PROP_BITRATE);
auto nocheck = obs_data_get_bool(settings, PROP_NO_CHECK);
int stream_index;
if (strcmp(encoder, "H265") == 0) {
stream_index = 0;
} else {
stream_index = 1;
}
bitrate *= 1024 * 1024;
s->bitrate = bitrate;
ssp_blog(LOG_INFO, "Calling setStream on ssp source");
s->cameraStatus->setStream(
stream_index, resolution, low_noise, framerate, bitrate,
[=](bool ok, QString reason) {
if (!ok && !nocheck) {
blog(LOG_INFO, "%s",
QString("setStream failed, not starting ssp: %1")
.arg(reason)
.toStdString()
.c_str());
return;
}
ssp_blog(LOG_INFO,
"Set stream succeeded, starting ssp");
ssp_start(s);
});
}
void ssp_source_shown(void *data)
{
auto s = (struct ssp_source *)data;
if (s->tally) {
s->cameraStatus->setLed(true);
}
ssp_blog(LOG_INFO, "ssp source shown.");
}
void ssp_source_hidden(void *data)
{
auto s = (struct ssp_source *)data;
if (s->tally) {
s->cameraStatus->setLed(false);
}
ssp_blog(LOG_INFO, "ssp source hidden.");
}
void ssp_source_activated(void *data)
{
ssp_blog(LOG_INFO, "ssp source activated.");
}
void ssp_source_deactivated(void *data)
{
ssp_blog(LOG_INFO, "ssp source deactivated.");
}
void *ssp_source_create(obs_data_t *settings, obs_source_t *source)
{
auto s = (struct ssp_source *)bzalloc(sizeof(struct ssp_source));
s->source = source;
s->do_check = false;
s->no_check = false;
s->ip_checked = false;
s->cameraStatus = new CameraStatus();
s->source_ip = nullptr;
ssp_source_update(s, settings);
return s;
}
void ssp_source_destroy(void *data)
{
auto s = (struct ssp_source *)data;
ssp_blog(LOG_INFO, "destroying source...");
delete s->cameraStatus;
s->cameraStatus = nullptr;
if (s->source_ip) {
free((void *)s->source_ip);
s->source_ip = nullptr;
}
ssp_stop(s);
bfree(s);
ssp_blog(LOG_INFO, "source destroyed.");
}
struct obs_source_info create_ssp_source_info()
{
struct obs_source_info ssp_source_info = {};
ssp_source_info.id = "ssp_source";
ssp_source_info.type = OBS_SOURCE_TYPE_INPUT;
ssp_source_info.output_flags = OBS_SOURCE_ASYNC_VIDEO |
OBS_SOURCE_AUDIO |
OBS_SOURCE_DO_NOT_DUPLICATE;
ssp_source_info.get_name = ssp_source_getname;
ssp_source_info.get_properties = ssp_source_getproperties;
ssp_source_info.get_defaults = ssp_source_getdefaults;
ssp_source_info.update = ssp_source_update;
ssp_source_info.show = ssp_source_shown;
ssp_source_info.hide = ssp_source_hidden;
ssp_source_info.activate = ssp_source_activated;
ssp_source_info.deactivate = ssp_source_deactivated;
ssp_source_info.create = ssp_source_create;
ssp_source_info.destroy = ssp_source_destroy;
return ssp_source_info;
}
| 24,019
|
C++
|
.cpp
| 754
| 29.168435
| 108
| 0.706032
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,175
|
ssp-client-iso.cpp
|
summershrimp_obs-ssp/src/ssp-client-iso.cpp
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#include <obs.h>
#include <util/dstr.h>
#include <util/platform.h>
#ifdef _WIN32
#include <windows.h>
#endif
#if defined(__APPLE__)
#include <dlfcn.h>
#endif
#include <QUuid>
#include <QFileInfo>
#include <QDir>
#include <pthread.h>
#include "obs-ssp.h"
#include "ssp-client-iso.h"
static size_t os_process_pipe_read_retry(os_process_pipe *pipe, uint8_t *dst,
size_t size)
{
size_t pos = 0, cur = 0;
while (pos < size) {
cur = os_process_pipe_read(pipe, dst + pos, size - pos);
if (!cur) {
break;
}
pos += cur;
}
return pos;
}
static Message *msg_recv(os_process_pipe *pipe)
{
size_t sz = 0;
Message *msg = (Message *)bmalloc(sizeof(Message));
if (!msg) {
return nullptr;
}
sz = os_process_pipe_read_retry(pipe, (uint8_t *)msg, sizeof(Message));
if (sz != sizeof(Message)) {
ssp_blog(LOG_WARNING, "pipe protocol header error, recv: %d!",
sz);
bfree(msg);
return nullptr;
}
if (msg->length == 0) {
return msg;
}
Message *msg_all = nullptr;
msg_all = (Message *)bmalloc(sizeof(Message) + msg->length);
memcpy(msg_all, msg, sizeof(Message));
bfree(msg);
//ssp_blog(LOG_INFO, "receive msg type: %d, size: %d", msg_all->type, msg_all->length);
sz = os_process_pipe_read_retry(pipe, msg_all->value, msg_all->length);
if (sz != msg_all->length) {
ssp_blog(LOG_WARNING, "pipe protocol body error, recv: %d!",
sz);
bfree(msg_all);
return nullptr;
}
return msg_all;
}
static void msg_free(Message *msg)
{
if (msg) {
bfree(msg);
}
}
static void *dump_stderr(os_process_pipe *pipe)
{
size_t sz;
char buf[1024];
while (true) {
sz = os_process_pipe_read_err(pipe, (uint8_t *)buf,
sizeof(buf) - 1);
if (sz == 0) {
break;
}
buf[sz] = '\0';
ssp_blog(LOG_INFO, "%s", buf);
}
ssp_blog(LOG_INFO, "read thread exited");
return nullptr;
}
SSPClientIso::SSPClientIso(const std::string &ip, uint32_t bufferSize)
{
this->ip = ip;
this->bufferSize = bufferSize;
this->running = false;
this->pipe = nullptr;
#if defined(__APPLE__)
Dl_info info;
dladdr((const void *)msg_free, &info);
QFileInfo plugin_path(info.dli_fname);
ssp_connector_path =
plugin_path.dir().filePath(QStringLiteral(SSP_CONNECTOR));
#else
ssp_connector_path = QStringLiteral(SSP_CONNECTOR);
#endif
connect(this, SIGNAL(Start()), this, SLOT(doStart()));
}
using namespace std::placeholders;
void SSPClientIso::doStart()
{
struct dstr cmd;
dstr_init_copy(&cmd, ssp_connector_path.toStdString().c_str());
dstr_insert_ch(&cmd, 0, '\"');
dstr_cat(&cmd, "\" ");
#if defined(__APPLE__) && defined(__arm64__)
dstr_insert(&cmd, 0, "arch -x86_64 ");
#endif
dstr_cat(&cmd, "--host ");
dstr_cat(&cmd, this->ip.c_str());
dstr_cat(&cmd, " --port ");
dstr_cat(&cmd, "9999");
auto tpipe = os_process_pipe_create(cmd.array, "r");
blog(LOG_INFO, "Start ssp-connector at: %s", cmd.array);
dstr_free(&cmd);
if (!tpipe) {
blog(LOG_WARNING, "Start ssp-connector failed.");
return;
}
this->statusLock.lock();
this->running = true;
this->pipe = tpipe;
this->worker = std::thread(SSPClientIso::ReceiveThread, this);
this->statusLock.unlock();
}
void *SSPClientIso::ReceiveThread(void *arg)
{
auto th = (SSPClientIso *)arg;
Message *msg;
th->statusLock.lock();
auto pipe = th->pipe;
th->statusLock.unlock();
#ifdef _WIN32
std::thread(dump_stderr, pipe).detach();
#endif
msg = msg_recv(pipe);
if (!msg) {
blog(LOG_WARNING, "Receive error !");
return nullptr;
}
if (msg->type != MessageType::ConnectorOkMsg) {
blog(LOG_WARNING, "Protocol error !");
return nullptr;
}
while (th->running) {
msg = msg_recv(pipe);
if (!msg) {
blog(LOG_WARNING, "Receive error !");
break;
}
switch (msg->type) {
case MessageType::MetaDataMsg:
th->OnMetadata((Metadata *)msg->value);
break;
case MessageType::VideoDataMsg:
th->OnH264Data((VideoData *)msg->value);
break;
case MessageType::AudioDataMsg:
th->OnAudioData((AudioData *)msg->value);
break;
case MessageType::RecvBufferFullMsg:
th->OnRecvBufferFull();
break;
case MessageType::DisconnectMsg:
th->OnDisconnected();
break;
case MessageType::ConnectionConnectedMsg:
th->OnConnectionConnected();
break;
case MessageType::ExceptionMsg:
th->OnException((Message *)msg->value);
break;
default:
blog(LOG_WARNING, "Protocol error !");
break;
}
msg_free(msg);
}
return nullptr;
}
void SSPClientIso::Restart()
{
this->Stop();
emit this->Start();
}
void SSPClientIso::Stop()
{
blog(LOG_INFO, "ssp client stopping...");
this->statusLock.lock();
this->running = false;
if (this->worker.joinable()) {
this->worker.join();
}
if (this->pipe) {
os_process_pipe_destroy(this->pipe);
this->pipe = nullptr;
}
this->statusLock.unlock();
}
void SSPClientIso::OnRecvBufferFull()
{
this->bufferFullCallback();
}
void SSPClientIso::OnH264Data(VideoData *videoData)
{
imf::SspH264Data video;
video.frm_no = videoData->frm_no;
video.ntp_timestamp = videoData->ntp_timestamp;
video.pts = videoData->pts;
video.type = videoData->type;
video.len = videoData->len;
video.data = videoData->data;
this->h264DataCallback(&video);
}
void SSPClientIso::OnAudioData(AudioData *audioData)
{
struct imf::SspAudioData audio;
audio.ntp_timestamp = audioData->ntp_timestamp;
audio.pts = audioData->pts;
audio.len = audioData->len;
audio.data = audioData->data;
this->audioDataCallback(&audio);
}
void SSPClientIso::OnMetadata(Metadata *metadata)
{
struct imf::SspVideoMeta vmeta;
struct imf::SspAudioMeta ameta;
struct imf::SspMeta meta;
ameta.bitrate = metadata->ameta.bitrate;
ameta.channel = metadata->ameta.channel;
ameta.encoder = metadata->ameta.encoder;
ameta.sample_rate = metadata->ameta.sample_rate;
ameta.sample_size = metadata->ameta.sample_size;
ameta.timescale = metadata->ameta.timescale;
ameta.unit = metadata->ameta.unit;
vmeta.encoder = metadata->vmeta.encoder;
vmeta.gop = metadata->vmeta.gop;
vmeta.height = metadata->vmeta.height;
vmeta.timescale = metadata->vmeta.timescale;
vmeta.unit = metadata->vmeta.unit;
vmeta.width = metadata->vmeta.width;
meta.pts_is_wall_clock = metadata->meta.pts_is_wall_clock;
meta.tc_drop_frame = metadata->meta.tc_drop_frame;
meta.timecode = metadata->meta.timecode;
this->metaCallback(&vmeta, &ameta, &meta);
}
void SSPClientIso::OnDisconnected()
{
this->disconnectedCallback();
}
void SSPClientIso::OnConnectionConnected()
{
this->connectedCallback();
}
void SSPClientIso::OnException(Message *exception)
{
this->exceptionCallback(exception->type, (char *)exception->value);
}
void SSPClientIso::setOnRecvBufferFullCallback(
const imf::OnRecvBufferFullCallback &cb)
{
this->bufferFullCallback = cb;
}
void SSPClientIso::setOnAudioDataCallback(const imf::OnAudioDataCallback &cb)
{
this->audioDataCallback = cb;
}
void SSPClientIso::setOnMetaCallback(const imf::OnMetaCallback &cb)
{
this->metaCallback = cb;
}
void SSPClientIso::setOnDisconnectedCallback(
const imf::OnDisconnectedCallback &cb)
{
this->disconnectedCallback = cb;
}
void SSPClientIso::setOnConnectionConnectedCallback(
const imf::OnConnectionConnectedCallback &cb)
{
this->connectedCallback = cb;
}
void SSPClientIso::setOnH264DataCallback(const imf::OnH264DataCallback &cb)
{
this->h264DataCallback = cb;
}
void SSPClientIso::setOnExceptionCallback(const imf::OnExceptionCallback &cb)
{
this->exceptionCallback = cb;
}
| 8,054
|
C++
|
.cpp
| 303
| 24.448845
| 88
| 0.726294
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,176
|
obs-ssp.cpp
|
summershrimp_obs-ssp/src/obs-ssp.cpp
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#include "ssp-mdns.h"
#ifdef _WIN32
#include <Windows.h>
#endif
#include <obs-module.h>
#include <util/platform.h>
#include <util/dstr.h>
#include <QDir>
#include "obs-ssp.h"
#include "ssp-controller.h"
#if defined(__APPLE__)
#include <dlfcn.h>
#endif
OBS_DECLARE_MODULE()
OBS_MODULE_AUTHOR("Yibai Zhang")
OBS_MODULE_USE_DEFAULT_LOCALE("obs-ssp", "en-US")
extern struct obs_source_info create_ssp_source_info();
struct obs_source_info ssp_source_info;
create_ssp_class_ptr create_ssp_class;
create_loop_class_ptr create_loop_class;
bool obs_module_load(void)
{
ssp_blog(LOG_INFO, "hello ! (obs-ssp version %s) size: %lu",
PLUGIN_VERSION, sizeof(ssp_source_info));
create_mdns_loop();
ssp_source_info = create_ssp_source_info();
obs_register_source(&ssp_source_info);
return true;
}
void obs_module_unload()
{
stop_mdns_loop();
ssp_blog(LOG_INFO, "goodbye !");
}
const char *obs_module_name()
{
return "obs-ssp";
}
const char *obs_module_description()
{
return "Simple Stream Protocol input integration for OBS Studio";
}
| 1,709
|
C++
|
.cpp
| 56
| 29
| 68
| 0.769701
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,177
|
ssp-controller.cpp
|
summershrimp_obs-ssp/src/ssp-controller.cpp
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#include <QMetaType>
#include "ssp-controller.h"
#include <obs-module.h>
CameraStatus::CameraStatus() : QObject()
{
controller = new CameraController(this);
qRegisterMetaType<StatusUpdateCallback>("StatusUpdateCallback");
qRegisterMetaType<StatusReasonUpdateCallback>(
"StatusReasonUpdateCallback");
connect(this,
SIGNAL(onSetStream(int, QString, bool, QString, int,
StatusReasonUpdateCallback)),
this,
SLOT(doSetStream(int, QString, bool, QString, int,
StatusReasonUpdateCallback)));
connect(this, SIGNAL(onSetLed(bool)), this, SLOT(doSetLed(bool)));
connect(this, SIGNAL(onRefresh(StatusUpdateCallback)), this,
SLOT(doRefresh(StatusUpdateCallback)));
};
void CameraStatus::setIp(const QString &ip)
{
controller->setIp(ip);
}
void CameraStatus::getResolution(const StatusUpdateCallback &callback)
{
controller->getCameraConfig(
CONFIG_KEY_MOVIE_RESOLUTION, [=](HttpResponse *rsp) {
if (rsp->statusCode == 999) {
callback(false);
return false;
}
if (rsp->choices.count() > 0) {
resolutions.clear();
}
for (const auto &i : rsp->choices) {
resolutions.push_back(i);
}
current_framerate = rsp->currentValue;
callback(true);
return true;
});
}
void CameraStatus::getFramerate(const StatusUpdateCallback &callback)
{
controller->getCameraConfig(
CONFIG_KEY_PROJECT_FPS, [=](HttpResponse *rsp) {
if (rsp->statusCode == 999) {
callback(false);
return false;
}
if (rsp->choices.count() > 0) {
framerates.clear();
}
for (const auto &i : rsp->choices) {
framerates.push_back(i);
}
current_framerate = rsp->currentValue;
callback(true);
return true;
});
}
void CameraStatus::getCurrentStream(const StatusUpdateCallback &callback)
{
controller->getCameraConfig(
CONFIG_KEY_SEND_STREAM, [=](HttpResponse *rsp) {
if (rsp->statusCode == 999) {
callback(false);
return false;
}
controller->getStreamInfo(
rsp->currentValue, [=](HttpResponse *rsp) {
if (rsp->statusCode == 999) {
callback(false);
return false;
}
current_streamInfo = rsp->streamInfo;
callback(true);
return true;
});
return true;
});
}
void CameraStatus::refreshAll(const StatusUpdateCallback &cb)
{
emit onRefresh(cb);
}
void CameraStatus::doRefresh(StatusUpdateCallback cb)
{
this->model = "";
getInfo([=](bool ok) {
cb(ok);
return ok;
});
}
void CameraStatus::getInfo(const StatusUpdateCallback &callback)
{
controller->getInfo([=](HttpResponse *rsp) {
if (rsp->statusCode == 999) {
callback(false);
return false;
}
model = rsp->currentValue;
callback(true);
return true;
});
}
void CameraStatus::setLed(bool isOn)
{
emit onSetLed(isOn);
}
void CameraStatus::doSetLed(bool isOn)
{
controller->setCameraConfig(CONFIG_KEY_LED, isOn ? "On" : "Off",
[=](HttpResponse *rsp) {
});
}
void CameraStatus::setStream(int stream_index, QString resolution,
bool low_noise, QString fps, int bitrate,
StatusReasonUpdateCallback cb)
{
blog(LOG_INFO, "In ::setStream emitting onSetStream");
emit onSetStream(stream_index, resolution, low_noise, fps, bitrate, cb);
}
void CameraStatus::doSetStream(int stream_index, QString resolution,
bool low_noise, QString fps, int bitrate,
StatusReasonUpdateCallback cb)
{
bool need_downresolution = false;
blog(LOG_INFO, "In doSetStream");
if (model.contains(E2C_MODEL_CODE, Qt::CaseInsensitive)) {
if (resolution != "1920*1080" && fps.toDouble() > 30) {
return cb(
false,
QString("Cannot go higher than 30fps for >1920x1080 resolution on E2C"));
}
if (resolution == "1920*1080" && fps.toDouble() > 30) {
need_downresolution = true;
}
}
auto bitrate2 = QString::number(bitrate);
if (model.contains(IPMANS_MODEL_CODE, Qt::CaseInsensitive)) {
auto index =
QString("stream") + QString::number(stream_index + 1);
controller->setStreamBitrate(
index, bitrate2, [=](HttpResponse *rsp) {
if (rsp->statusCode != 200 || rsp->code != 0) {
return cb(
false,
QString("Could not set bitrate to %1")
.arg(bitrate2));
}
return cb(true, "Success");
});
return;
}
QString real_resolution;
QString width, height;
auto arr = resolution.split("*");
if (arr.size() < 2) {
return cb(
false,
"Resolution doesn't have a single * to seperate w from h");
}
width = arr[0];
height = arr[1];
if (need_downresolution) {
real_resolution = "1920x1080";
} else if (resolution == "3840*2160" || resolution == "1920*1080") {
real_resolution = "4K";
if (low_noise)
real_resolution += " (Low Noise)";
} else if (resolution == "4096*2160") {
real_resolution = "C4K";
if (low_noise)
real_resolution += " (Low Noise)";
} else {
return cb(false,
QString("Unknown resolution: ").arg(resolution));
}
auto index = QString("Stream") + QString::number(stream_index);
blog(LOG_INFO, "Setting movie resolution");
controller->setCameraConfig(CONFIG_KEY_MOVIE_RESOLUTION, real_resolution, [=](HttpResponse *rsp) {
if (rsp->statusCode != 200 || rsp->code != 0) {
return cb(
false,
QString("Failed to set movie resolution to %1")
.arg(real_resolution));
}
blog(LOG_INFO, "Setting fps");
controller->setCameraConfig(CONFIG_KEY_PROJECT_FPS, fps, [=](HttpResponse *rsp) {
if (rsp->statusCode != 200 || rsp->code != 0) {
return cb(false,
QString("Failed to set fps to %1")
.arg(fps));
}
blog(LOG_INFO, "Setting encoder");
controller->setCameraConfig(CONFIG_KEY_VIDEO_ENCODER, "H.265", [=](HttpResponse *rsp) {
blog(LOG_INFO, "Setting sendStream");
controller->setSendStream(index, [=](HttpResponse
*rsp) {
if (rsp->statusCode != 200 ||
rsp->code != 0) {
return cb(
false,
QString("Could not set video encoder to H.265"));
}
blog(LOG_INFO,
"Setting bitrate andn gop");
controller->setStreamBitrateAndGop(
index.toLower(), bitrate2, "10",
[=](HttpResponse *rsp) {
if (rsp->statusCode !=
200 ||
rsp->code != 0) {
return cb(
false,
QString("Could not set bitrate to %1 or GOP to 10")
.arg(bitrate2));
}
if (stream_index == 0) {
return cb(
true,
"Success");
}
blog(LOG_INFO,
"Setting stream resolution");
controller->setStreamResolution(
index.toLower(),
width, height,
[=](HttpResponse
*rsp) {
if (rsp->statusCode !=
200 ||
rsp->code !=
0) {
return cb(
false,
QString("Could not set stream resolution to %1 x %2")
.arg(width)
.arg(height));
}
return cb(
true,
"Success");
});
});
});
});
});
});
}
CameraStatus::~CameraStatus()
{
controller->cancelAllReqs();
delete controller;
}
| 7,676
|
C++
|
.cpp
| 270
| 24.014815
| 99
| 0.660526
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,178
|
ssp-mdns.cpp
|
summershrimp_obs-ssp/src/ssp-mdns.cpp
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS 1
#endif
#include <map>
#include <string>
#include <mutex>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <mdns.h>
#ifdef _WIN32
#include <iphlpapi.h>
#define sleep(x) Sleep(x * 1000)
#else
#include <netdb.h>
#include <ifaddrs.h>
#endif
#include <obs-module.h>
#include <util/platform.h>
#include <util/threading.h>
#include "obs-ssp.h"
#include "ssp-mdns.h"
#define DEFAULT_TTL 60
struct mdns_args {
bool running;
const char *service_str;
size_t service_str_size;
} g_mdns_args;
static uint32_t service_address_ipv4;
static uint8_t service_address_ipv6[16];
static int has_ipv4;
static int has_ipv6;
uint16_t current_transaction_id;
struct mdns_record current_mdns_record;
pthread_t mdns_thread;
#define MDNS_BUFFER_SIZE 2048
static char addrbuffer[64];
static char namebuffer[256];
static char sendbuffer[256];
static char entrybuffer[256];
static mdns_record_txt_t txtbuffer[128];
std::map<std::string, mdns_record> ssp_records;
std::mutex ssp_records_lock;
static mdns_string_t ipv4_address_to_string(char *buffer, size_t capacity,
const struct sockaddr_in *addr,
size_t addrlen)
{
char host[NI_MAXHOST] = {0};
char service[NI_MAXSERV] = {0};
int ret = getnameinfo((const struct sockaddr *)addr, addrlen, host,
NI_MAXHOST, service, NI_MAXSERV,
NI_NUMERICSERV | NI_NUMERICHOST);
int len = 0;
if (ret == 0) {
if (addr->sin_port != 0)
len = snprintf(buffer, capacity, "%s:%s", host,
service);
else
len = snprintf(buffer, capacity, "%s", host);
}
if (len >= (int)capacity)
len = (int)capacity - 1;
mdns_string_t str = {buffer, (size_t)len};
return str;
}
static mdns_string_t ipv6_address_to_string(char *buffer, size_t capacity,
const struct sockaddr_in6 *addr,
size_t addrlen)
{
char host[NI_MAXHOST] = {0};
char service[NI_MAXSERV] = {0};
int ret = getnameinfo((const struct sockaddr *)addr, addrlen, host,
NI_MAXHOST, service, NI_MAXSERV,
NI_NUMERICSERV | NI_NUMERICHOST);
int len = 0;
if (ret == 0) {
if (addr->sin6_port != 0)
len = snprintf(buffer, capacity, "[%s]:%s", host,
service);
else
len = snprintf(buffer, capacity, "%s", host);
}
if (len >= (int)capacity)
len = (int)capacity - 1;
mdns_string_t str = {buffer, (size_t)len};
return str;
}
static mdns_string_t ip_address_to_string(char *buffer, size_t capacity,
const struct sockaddr *addr,
size_t addrlen)
{
if (addr->sa_family == AF_INET6)
return ipv6_address_to_string(buffer, capacity,
(const struct sockaddr_in6 *)addr,
addrlen);
return ipv4_address_to_string(
buffer, capacity, (const struct sockaddr_in *)addr, addrlen);
}
static int query_callback(int sock, const struct sockaddr *from, size_t addrlen,
mdns_entry_type_t entry, uint16_t transaction_id,
uint16_t rtype, uint16_t rclass, uint32_t ttl,
const void *data, size_t size, size_t name_offset,
size_t name_length, size_t record_offset,
size_t record_length, void *user_data)
{
if (transaction_id != current_transaction_id) {
current_mdns_record.has_ptr = false;
current_mdns_record.has_a = false;
current_mdns_record.has_aaaa = false;
current_transaction_id = transaction_id;
}
ttl = DEFAULT_TTL; // The mdns library we use cannot query all interface so we use a longer ttl.
if (rtype == MDNS_RECORDTYPE_PTR) {
mdns_string_t ptr_str = mdns_record_parse_ptr(
data, size, record_offset, record_length, namebuffer,
sizeof(namebuffer));
std::string ptr(ptr_str.str,
ptr_str.length - strlen(ZCAM_QUERY_DOMAIN) - 2);
current_mdns_record.ptr_record = ptr;
current_mdns_record.last_available =
os_gettime_ns() / 1000000 + ttl * 1000;
current_mdns_record.has_ptr = true;
} else if (current_mdns_record.has_ptr && rtype == MDNS_RECORDTYPE_A &&
from->sa_family == AF_INET) {
struct sockaddr_in addr;
mdns_record_parse_a(data, size, record_offset, record_length,
&addr);
memcpy(&(current_mdns_record.a_record), &addr,
sizeof(current_mdns_record.a_record));
current_mdns_record.has_a = true;
current_mdns_record.last_available =
os_gettime_ns() / 1000000 + ttl * 1000;
ssp_records_lock.lock();
ssp_records[current_mdns_record.ptr_record] =
current_mdns_record;
ssp_records_lock.unlock();
} else if (current_mdns_record.has_ptr &&
rtype == MDNS_RECORDTYPE_AAAA &&
from->sa_family == AF_INET6) {
struct sockaddr_in6 addr;
mdns_record_parse_aaaa(data, size, record_offset, record_length,
&addr);
memcpy(&(current_mdns_record.aaaa_record), &addr,
sizeof(current_mdns_record.aaaa_record));
current_mdns_record.has_aaaa = true;
current_mdns_record.last_available =
os_gettime_ns() / 1000000 + ttl * 1000;
ssp_records_lock.lock();
ssp_records[current_mdns_record.ptr_record] =
current_mdns_record;
ssp_records_lock.unlock();
}
return 0;
}
static int open_client_sockets(int *sockets, int max_sockets, int port)
{
// When sending, each socket can only send to one network interface
// Thus we need to open one socket for each interface and address family
int num_sockets = 0;
#ifdef _WIN32
IP_ADAPTER_ADDRESSES *adapter_address = 0;
ULONG address_size = 8000;
unsigned int ret;
unsigned int num_retries = 4;
do {
adapter_address = (IP_ADAPTER_ADDRESSES *)malloc(address_size);
ret = GetAdaptersAddresses(AF_UNSPEC,
GAA_FLAG_SKIP_MULTICAST |
GAA_FLAG_SKIP_ANYCAST,
0, adapter_address, &address_size);
if (ret == ERROR_BUFFER_OVERFLOW) {
free(adapter_address);
adapter_address = 0;
} else {
break;
}
} while (num_retries-- > 0);
if (!adapter_address || (ret != NO_ERROR)) {
free(adapter_address);
ssp_blog(LOG_ERROR, "Failed to get network adapter addresses");
return num_sockets;
}
int first_ipv4 = 1;
int first_ipv6 = 1;
for (PIP_ADAPTER_ADDRESSES adapter = adapter_address; adapter;
adapter = adapter->Next) {
if (adapter->TunnelType == TUNNEL_TYPE_TEREDO)
continue;
if (adapter->OperStatus != IfOperStatusUp)
continue;
for (IP_ADAPTER_UNICAST_ADDRESS *unicast =
adapter->FirstUnicastAddress;
unicast; unicast = unicast->Next) {
if (unicast->Address.lpSockaddr->sa_family == AF_INET) {
struct sockaddr_in *saddr =
(struct sockaddr_in *)
unicast->Address.lpSockaddr;
if ((saddr->sin_addr.S_un.S_un_b.s_b1 != 127) ||
(saddr->sin_addr.S_un.S_un_b.s_b2 != 0) ||
(saddr->sin_addr.S_un.S_un_b.s_b3 != 0) ||
(saddr->sin_addr.S_un.S_un_b.s_b4 != 1)) {
int log_addr = 0;
if (first_ipv4) {
service_address_ipv4 =
saddr->sin_addr.S_un
.S_addr;
first_ipv4 = 0;
log_addr = 1;
}
has_ipv4 = 1;
if (num_sockets < max_sockets) {
saddr->sin_port = htons(
(unsigned short)port);
int sock =
mdns_socket_open_ipv4(
saddr);
if (sock >= 0) {
sockets[num_sockets++] =
sock;
log_addr = 1;
} else {
log_addr = 0;
}
}
if (log_addr) {
char buffer[128];
mdns_string_t addr = ipv4_address_to_string(
buffer, sizeof(buffer),
saddr,
sizeof(struct sockaddr_in));
}
}
} else if (unicast->Address.lpSockaddr->sa_family ==
AF_INET6) {
struct sockaddr_in6 *saddr =
(struct sockaddr_in6 *)
unicast->Address.lpSockaddr;
static const unsigned char localhost[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1};
static const unsigned char localhost_mapped[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0xff, 0xff, 0x7f, 0, 0, 1};
if ((unicast->DadState == NldsPreferred) &&
memcmp(saddr->sin6_addr.s6_addr, localhost,
16) &&
memcmp(saddr->sin6_addr.s6_addr,
localhost_mapped, 16)) {
int log_addr = 0;
if (first_ipv6) {
memcpy(service_address_ipv6,
&saddr->sin6_addr, 16);
first_ipv6 = 0;
log_addr = 1;
}
has_ipv6 = 1;
if (num_sockets < max_sockets) {
saddr->sin6_port = htons(
(unsigned short)port);
int sock =
mdns_socket_open_ipv6(
saddr);
if (sock >= 0) {
sockets[num_sockets++] =
sock;
log_addr = 1;
} else {
log_addr = 0;
}
}
if (log_addr) {
char buffer[128];
mdns_string_t addr = ipv6_address_to_string(
buffer, sizeof(buffer),
saddr,
sizeof(struct sockaddr_in6));
}
}
}
}
}
free(adapter_address);
#else
struct ifaddrs *ifaddr = 0;
struct ifaddrs *ifa = 0;
if (getifaddrs(&ifaddr) < 0)
ssp_blog(LOG_ERROR, "Unable to get interface addresses");
int first_ipv4 = 1;
int first_ipv6 = 1;
for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr)
continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in *saddr =
(struct sockaddr_in *)ifa->ifa_addr;
if (saddr->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
int log_addr = 0;
if (first_ipv4) {
service_address_ipv4 =
saddr->sin_addr.s_addr;
first_ipv4 = 0;
log_addr = 1;
}
has_ipv4 = 1;
if (num_sockets < max_sockets) {
saddr->sin_port = htons(port);
int sock = mdns_socket_open_ipv4(saddr);
if (sock >= 0) {
sockets[num_sockets++] = sock;
log_addr = 1;
} else {
log_addr = 0;
}
}
if (log_addr) {
char buffer[128];
mdns_string_t addr = ipv4_address_to_string(
buffer, sizeof(buffer), saddr,
sizeof(struct sockaddr_in));
}
}
} else if (ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *saddr =
(struct sockaddr_in6 *)ifa->ifa_addr;
static const unsigned char localhost[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
static const unsigned char localhost_mapped[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0xff, 0xff, 0x7f, 0, 0, 1};
if (memcmp(saddr->sin6_addr.s6_addr, localhost, 16) &&
memcmp(saddr->sin6_addr.s6_addr, localhost_mapped,
16)) {
int log_addr = 0;
if (first_ipv6) {
memcpy(service_address_ipv6,
&saddr->sin6_addr, 16);
first_ipv6 = 0;
log_addr = 1;
}
has_ipv6 = 1;
if (num_sockets < max_sockets) {
saddr->sin6_port = htons(port);
int sock = mdns_socket_open_ipv6(saddr);
if (sock >= 0) {
sockets[num_sockets++] = sock;
log_addr = 1;
} else {
log_addr = 0;
}
}
if (log_addr) {
char buffer[128];
mdns_string_t addr = ipv6_address_to_string(
buffer, sizeof(buffer), saddr,
sizeof(struct sockaddr_in6));
}
}
}
}
freeifaddrs(ifaddr);
#endif
return num_sockets;
}
static int send_mdns_query(const char *service, size_t service_len)
{
static int current_id = 1;
int sockets[32];
int query_id[32];
int num_sockets = open_client_sockets(
sockets, sizeof(sockets) / sizeof(sockets[0]), 0);
if (num_sockets <= 0) {
ssp_blog(LOG_ERROR, "Failed to open any client sockets");
return -1;
}
size_t capacity = 2048;
void *buffer = malloc(capacity);
void *user_data = 0;
size_t records;
for (int isock = 0; isock < num_sockets; ++isock) {
query_id[isock] = mdns_query_send(sockets[isock],
MDNS_RECORDTYPE_PTR, service,
service_len, buffer, capacity,
current_id++);
if (query_id[isock] < 0)
ssp_blog(LOG_DEBUG, "Failed to send mDNS query: %s",
strerror(errno));
}
// This is a simple implementation that loops for 5 seconds or as long as we get replies
int res;
do {
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
int nfds = 0;
fd_set readfs;
FD_ZERO(&readfs);
for (int isock = 0; isock < num_sockets; ++isock) {
if (sockets[isock] >= nfds)
nfds = sockets[isock] + 1;
FD_SET(sockets[isock], &readfs);
}
records = 0;
res = select(nfds, &readfs, 0, 0, &timeout);
if (res > 0) {
for (int isock = 0; isock < num_sockets; ++isock) {
if (FD_ISSET(sockets[isock], &readfs)) {
records += mdns_query_recv(
sockets[isock], buffer,
capacity, query_callback,
user_data, query_id[isock]);
}
FD_SET(sockets[isock], &readfs);
}
}
} while (res > 0);
free(buffer);
for (int isock = 0; isock < num_sockets; ++isock)
mdns_socket_close(sockets[isock]);
return 0;
}
static void *mdns_loop(void *ptr)
{
mdns_args *arg = (mdns_args *)ptr;
void *buffer = bzalloc(MDNS_BUFFER_SIZE);
int sock = mdns_socket_open_ipv4(0);
while (arg->running) {
send_mdns_query(arg->service_str, arg->service_str_size);
}
mdns_socket_close(sock);
bfree(buffer);
return nullptr;
}
void create_mdns_loop()
{
ssp_records_lock.lock();
ssp_records.clear();
ssp_records_lock.unlock();
g_mdns_args.service_str = ZCAM_QUERY_DOMAIN;
g_mdns_args.service_str_size = strlen(ZCAM_QUERY_DOMAIN);
g_mdns_args.running = true;
pthread_create(&mdns_thread, nullptr, mdns_loop, (void *)&g_mdns_args);
ssp_blog(LOG_INFO, "mdns query thread started.");
}
void stop_mdns_loop()
{
ssp_records_lock.lock();
ssp_records.clear();
ssp_records_lock.unlock();
ssp_blog(LOG_INFO, "stop mdns query thread...");
while (g_mdns_args.running)
g_mdns_args.running = false;
pthread_join(mdns_thread, nullptr);
ssp_blog(LOG_INFO, "mdns query thread stopped.");
}
SspMDnsIterator::SspMDnsIterator()
{
ssp_records_lock.lock();
iter = ssp_records.begin();
current_time = os_gettime_ns() / 1000000;
}
SspMDnsIterator::~SspMDnsIterator()
{
ssp_records_lock.unlock();
}
bool SspMDnsIterator::hasNext()
{
return iter != ssp_records.end();
}
ssp_device_item *SspMDnsIterator::next()
{
static ssp_device_item ret;
while (hasNext()) {
if (iter->second.last_available < current_time) {
++iter;
continue;
}
ret.device_name = iter->second.ptr_record;
if (iter->second.has_a) {
mdns_string_t addr = ipv4_address_to_string(
addrbuffer, sizeof(addrbuffer),
&(iter->second.a_record),
sizeof(iter->second.a_record));
ret.ip_address = std::string(addr.str, addr.length);
++iter;
return &ret;
} else if (iter->second.has_aaaa) {
mdns_string_t addr = ipv6_address_to_string(
addrbuffer, sizeof(addrbuffer),
&(iter->second.aaaa_record),
sizeof(iter->second.aaaa_record));
ret.ip_address = std::string(addr.str, addr.length);
++iter;
return &ret;
} else {
++iter;
continue;
}
}
return nullptr;
}
| 15,192
|
C++
|
.cpp
| 515
| 25.43301
| 97
| 0.65377
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,179
|
VFrameQueue.cpp
|
summershrimp_obs-ssp/src/VFrameQueue.cpp
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#include <util/platform.h>
#include "VFrameQueue.h"
#include <QDebug>
VFrameQueue::VFrameQueue()
{
maxTime = 0;
}
void VFrameQueue::start()
{
running = true;
pthread_create(&thread, nullptr, pthread_run, (void *)this);
}
void VFrameQueue::stop()
{
running = false;
sem.release();
pthread_join(thread, nullptr);
}
void VFrameQueue::setFrameCallback(VFrameQueue::CallbackFunc cb)
{
callback = std::move(cb);
}
void VFrameQueue::setFrameTime(uint64_t time_us)
{
maxTime = time_us;
}
void VFrameQueue::enqueue(imf::SspH264Data data, uint64_t time_us, bool noDrop)
{
QMutexLocker locker(&queueLock);
uint8_t *copy_data = (uint8_t *)malloc(data.len);
memcpy(copy_data, data.data, data.len);
data.data = copy_data;
frameQueue.enqueue({data, time_us, noDrop});
sem.release();
}
void *VFrameQueue::pthread_run(void *q)
{
run((VFrameQueue *)q);
return nullptr;
}
void VFrameQueue::run(VFrameQueue *q)
{
Frame current;
uint64_t lastFrameTime = 0, lastStartTime = 0, processingTime = 0;
q->sem.acquire();
q->queueLock.lock();
if (q->frameQueue.empty()) {
q->queueLock.unlock();
return;
}
current = q->frameQueue.dequeue();
q->queueLock.unlock();
lastStartTime = os_gettime_ns() / 1000;
q->callback(¤t.data);
lastFrameTime = current.time;
processingTime = os_gettime_ns() / 1000 - lastStartTime;
free((void *)current.data.data);
while (q->running) {
q->sem.acquire();
q->queueLock.lock();
if (q->frameQueue.empty()) {
q->queueLock.unlock();
continue;
}
current = q->frameQueue.dequeue();
q->queueLock.unlock();
if (current.time < lastFrameTime) {
free((void *)current.data.data);
continue;
}
if (current.noDrop) {
lastStartTime = os_gettime_ns() / 1000;
q->callback(¤t.data);
lastFrameTime = current.time;
processingTime = os_gettime_ns() / 1000 - lastStartTime;
} else if (current.time - lastFrameTime + 15000 >
processingTime) {
lastStartTime = os_gettime_ns() / 1000;
q->callback(¤t.data);
lastFrameTime = current.time;
processingTime = os_gettime_ns() / 1000 - lastStartTime;
} else {
qDebug() << "dropped" << current.time - lastFrameTime
<< processingTime;
} // else we drop the frame
free((void *)current.data.data);
}
}
| 2,915
|
C++
|
.cpp
| 102
| 26.362745
| 79
| 0.727954
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,180
|
cameracontroller.cpp
|
summershrimp_obs-ssp/src/controller/cameracontroller.cpp
|
/*
* Copyright (c) 2015-2020, Shenzhen Imaginevision Technology Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Shenzhen Imaginevision Technology Limited ("ZCAM")
* nor the names contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QThread>
#include <QUrl>
#include <QQueue>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>
#include <QBuffer>
#include <QTcpSocket>
#include <stdio.h>
#include "cameracontroller.h"
CameraController::CameraController(QObject *parent)
: QObject(parent),
requesting_(false),
reply_(Q_NULLPTR),
networkManager_(new QNetworkAccessManager(this)),
httpRequestQueue_(new QQueue<struct HttpRequest *>())
{
//connect(networkManager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleReqeustResult()));
}
CameraController::~CameraController()
{
disconnect(this);
while (!httpRequestQueue_->isEmpty()) {
delete httpRequestQueue_->dequeue();
}
delete httpRequestQueue_;
httpRequestQueue_ = nullptr;
delete networkManager_;
networkManager_ = nullptr;
reply_ = nullptr;
}
void CameraController::setIp(const QString &ip)
{
cancelAllReqs();
ip_ = ip;
}
void CameraController::clearConnectionStatus()
{
cancelAllReqs();
}
void CameraController::cancelAllReqs()
{
while (!httpRequestQueue_->isEmpty()) {
delete httpRequestQueue_->dequeue();
}
cancelCurrentReq();
}
void CameraController::cancelReqs(QStringList keys)
{
if (keys.size() <= 0) {
return;
}
for (int i = 0; i < httpRequestQueue_->size(); i++) {
HttpRequest *req = httpRequestQueue_->at(i);
if (i != 0 && req != NULL && keys.contains(req->key)) {
httpRequestQueue_->removeAt(i);
}
}
}
void CameraController::resetNetwork()
{
// cancelAllReqs();
// networkManager_->deleteLater();
// networkManager_ = new QNetworkAccessManager(this);
}
void CameraController::cancelCurrentReq()
{
// if (requesting_) {
// requesting_ = false;
//
// if (httpRequestQueue_->size() == 0) {
// HttpRequest *req = new HttpRequest();
// req->key = HTTP_REQUEST_KEY_INVALID;
// httpRequestQueue_->enqueue(req);
// }
// QTimer::singleShot(1, reply_, SLOT(abort()));
// }
}
void CameraController::getCameraConfig(const QString &key,
OnRequestCallback callback)
{
getCameraConfig(key, HTTP_COMMAND_TIMEOUT, callback);
}
void CameraController::getCameraConfig(const QString &key, int timeout,
OnRequestCallback callback)
{
struct HttpRequest *req = new HttpRequest();
QString shortPath;
shortPath.append(URL_CTRL_GET).append("?").append("k=").append(key);
req->useShortPath = true;
req->shortPath = shortPath;
req->key = key;
req->reqType = RequestType::REQUEST_TYPE_CONFIG;
req->timeout = timeout;
req->callback = callback;
commonRequest(req);
}
void CameraController::getInfo(OnRequestCallback callback)
{
auto *req = new HttpRequest();
QString shortPath;
shortPath.append(URL_INFO);
req->useShortPath = true;
req->shortPath = shortPath;
req->reqType = RequestType::REQUEST_TYPE_INFO;
req->timeout = HTTP_COMMAND_TIMEOUT;
req->callback = callback;
commonRequest(req);
}
void CameraController::requestForCode(const QString &shortPath,
OnRequestCallback callback)
{
requestForCode(shortPath, HTTP_COMMAND_TIMEOUT, callback);
}
void CameraController::requestForCode(const QString &shortPath, int timeout,
OnRequestCallback callback)
{
struct HttpRequest *req = new HttpRequest();
req->useShortPath = true;
req->shortPath = shortPath;
req->reqType = RequestType::REQUEST_TYPE_CODE;
req->timeout = timeout;
req->callback = callback;
commonRequest(req);
}
void CameraController::setCameraConfig(const QString &key, const QString &value,
OnRequestCallback callback)
{
QString shortPath;
// /ctrl/stream_setting?index=stream1&width=1920&height=1080
shortPath.append(URL_CTRL_SET)
.append("?")
.append(key)
.append("=")
.append(value);
requestForCode(shortPath, callback);
}
void CameraController::setSendStream(const QString &value,
OnRequestCallback callback)
{
QString shortPath;
shortPath.append(URL_CTRL_SET).append("?send_stream=").append(value);
requestForCode(shortPath, callback);
}
void CameraController::setStreamBitrate(const QString &index,
const QString &bitrate,
OnRequestCallback callback)
{
QString shortPath;
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index)
.append("&bitrate=")
.append(bitrate);
requestForCode(shortPath, callback);
}
void CameraController::setStreamBitrateAndGop(const QString &index,
const QString &bitrate,
const QString &gop,
OnRequestCallback callback)
{
QString shortPath;
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index)
.append("&bitrate=")
.append(bitrate)
.append("&gop_n=")
.append(gop)
.append("&bitwidth=8bit");
requestForCode(shortPath, callback);
}
void CameraController::setStreamBitwidth(const QString &index,
const QString &bitwidth,
OnRequestCallback callback)
{
QString shortPath;
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index)
.append("&bitwidth=")
.append(bitwidth);
requestForCode(shortPath, callback);
}
void CameraController::setStreamResolution(const QString &index,
const QString &width,
const QString &height,
OnRequestCallback callback)
{
QString shortPath;
// /ctrl/stream_setting?index=stream1&width=1920&height=1080
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index)
.append("&width=")
.append(width)
.append("&height=")
.append(height);
requestForCode(shortPath, callback);
}
void CameraController::setStreamCodec(const QString &index,
const QString &codec,
OnRequestCallback callback)
{
QString shortPath;
// /ctrl/stream_setting?index=stream1&width=1920&height=1080
//shortPath.append(URL_CTRL_STREAM_SETTING).append("?index=").append(index).append("&encoderType=").append(codec).append("bitwidth=8bit");
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index.toLower())
.append("&bitwidth=8bit");
requestForCode(shortPath, callback);
}
void CameraController::setStreamGop(const QString &index, const QString &gop,
OnRequestCallback callback)
{
QString shortPath;
// /ctrl/stream_setting?index=stream1&width=1920&height=1080
//shortPath.append(URL_CTRL_STREAM_SETTING).append("?index=").append(index).append("&encoderType=").append(codec).append("bitwidth=8bit");
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index.toLower())
.append("&gop_n=")
.append(gop);
requestForCode(shortPath, callback);
}
void CameraController::setStreamFPS(const QString &index, const QString &fps,
OnRequestCallback callback)
{
QString shortPath;
// /ctrl/stream_setting?index=stream1&width=1920&height=1080
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index)
.append("&fps=")
.append(fps);
requestForCode(shortPath, callback);
}
void CameraController::getStreamInfo(const QString &index,
OnRequestCallback callback)
{
QString shortPath;
shortPath.append(URL_CTRL_STREAM_SETTING)
.append("?index=")
.append(index)
.append("&action=query");
struct HttpRequest *req = new HttpRequest();
req->useShortPath = true;
req->key = URL_CTRL_STREAM_SETTING;
req->shortPath = shortPath;
req->reqType = RequestType::REQUEST_TYPE_STREAM_INFO;
req->timeout = HTTP_COMMAND_TIMEOUT;
req->callback = callback;
commonRequest(req);
}
void CameraController::commonRequest(HttpRequest *req)
{
//httpRequestQueue_->enqueue(req);
nextRequest(req);
}
void CameraController::nextRequest(HttpRequest *req)
{
if (networkManager_ == NULL) {
return;
}
requesting_ = true;
QString path = buildRequestPath(req->shortPath, req->fullPath,
req->useShortPath);
QUrl url(path);
qDebug() << url;
QNetworkRequest request;
request.setRawHeader("Connection", "Keep-Alive");
request.setUrl(url);
auto reply_ = networkManager_->get(request);
QTimer::singleShot(req->timeout, reply_, SLOT(abort()));
connect(reply_, &QNetworkReply::finished,
[=]() { handleRequestResult(req, reply_); });
}
void CameraController::nextRequest()
{
if (httpRequestQueue_->size() > 0 && !requesting_ &&
networkManager_ != NULL) {
requesting_ = true;
const struct HttpRequest *req = httpRequestQueue_->head();
QString path = buildRequestPath(req->shortPath, req->fullPath,
req->useShortPath);
QUrl url(path);
QNetworkRequest request;
request.setRawHeader("Connection", "Keep-Alive");
request.setUrl(url);
reply_ = networkManager_->get(request);
QTimer::singleShot(req->timeout, reply_, SLOT(abort()));
}
}
void CameraController::handleRequestResult(HttpRequest *req,
QNetworkReply *reply_)
{
int httpCode = 999;
if (reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute)
.isValid()) {
httpCode =
reply_->attribute(
QNetworkRequest::HttpStatusCodeAttribute)
.toInt();
}
requesting_ = false;
// if (req->key == HTTP_REQUEST_KEY_INVALID) {
// reply_->deleteLater();
//
// nextRequest();
// delete req;
// return;
// }
struct HttpResponse *rsp = new HttpResponse();
rsp->reqKey = req->key;
rsp->reqValue = req->value;
rsp->shortPath = req->shortPath;
rsp->reqType = req->reqType;
rsp->statusCode = httpCode;
rsp->responseError = reply_->error();
QString info = req->useShortPath ? ip_ + rsp->shortPath : req->fullPath;
if (reply_->error() == QNetworkReply::NetworkError::NoError) {
parseResponse(reply_->readAll(), rsp, req->reqType);
} else {
if (info.contains(SESSION_HEARTBEAT) &&
rsp->responseError ==
QNetworkReply::NetworkError::UnknownNetworkError) {
resetNetwork();
}
}
reply_->deleteLater();
reply_ = nullptr;
if (rsp->shortPath == URL_CTRL_SESSION) {
}
if (req->callback != NULL) {
req->callback(rsp);
} else {
delete rsp;
}
delete req;
}
void CameraController::handleReqeustResult()
{
requesting_ = false;
if (httpRequestQueue_->size() > 0) {
struct HttpRequest *req = httpRequestQueue_->dequeue();
handleRequestResult(req, reply_);
}
nextRequest();
}
void CameraController::parseResponse(const QByteArray &byteData,
struct HttpResponse *rsp,
RequestType reqType)
{
qDebug() << byteData;
QJsonDocument doc(QJsonDocument::fromJson(byteData));
if (!doc.isNull() && doc.isObject()) {
if (reqType == REQUEST_TYPE_CONFIG) {
CameraConfig::parseForConfig(doc.object(), rsp);
} else if (reqType == REQUEST_TYPE_INFO) {
rsp->code = 0;
rsp->currentValue = doc["model"].toString();
} else if (reqType == REQUEST_TYPE_FILES) {
} else if (reqType == REQUEST_TYPE_MEDIA_INFO) {
} else if (reqType == REQUEST_TYPE_NETINFO) {
} else if (reqType == REQUEST_TYPE_STREAM_INFO) {
CameraConfig::parseForStreamInfo(doc.object(), rsp);
} else {
CameraConfig::parseForCommon(doc.object(), rsp);
}
}
}
QString CameraController::buildRequestPath(const QString &shortPath,
const QString &ip, bool useShortPath)
{
if (useShortPath) {
QString path;
path.append("http://").append(ip_).append(shortPath);
return path;
} else {
QString path;
path.append("http://").append(ip);
return path;
}
}
| 12,841
|
C++
|
.cpp
| 415
| 28.286747
| 139
| 0.730508
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,181
|
cameraconfig.cpp
|
summershrimp_obs-ssp/src/controller/cameraconfig.cpp
|
/*
* Copyright (c) 2015-2020, Shenzhen Imaginevision Technology Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Shenzhen Imaginevision Technology Limited ("ZCAM")
* nor the names contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include "cameraconfig.h"
CameraConfig::CameraConfig() {}
CameraConfig::~CameraConfig()
{
//TODO delete something
}
void CameraConfig::parseForConfig(const QJsonObject &json,
HttpResponse *response)
{
response->readOnly = json["ro"].toInt() == 0 ? false : true;
response->key = json["key"].toString();
response->code = json["code"].toInt();
int t = json["type"].toInt();
if (t == CONFIG_TYPE_CHOICE) {
response->type = CONFIG_TYPE_CHOICE;
response->currentValue = json["value"].toString();
response->choices.clear();
QJsonArray opts = json["opts"].toArray();
for (int index = 0; index < opts.size(); index++) {
QString val = opts[index].toString();
response->choices.append(val);
}
} else if (t == CONFIG_TYPE_RANGE) {
response->type = CONFIG_TYPE_RANGE;
response->intValue = json["value"].toInt();
response->min = json["min"].toInt();
response->max = json["max"].toInt();
response->step = json["step"].toInt();
} else {
response->type = CONFIG_TYPE_STRING;
response->currentValue = json["value"].toString();
}
}
void CameraConfig::parseForCommon(const QJsonObject &json,
HttpResponse *response)
{
response->code = json["code"].toInt();
response->msg = json["msg"].toString();
}
void CameraConfig::parseForStreamInfo(const QJsonObject &json,
HttpResponse *response)
{
response->code = 0;
response->streamInfo.bitrate_ = json["bitrate"].toInt();
response->streamInfo.encoderType_ = json["encoderType"].toString();
response->streamInfo.gop_ = json["gop_n"].toInt();
response->streamInfo.height_ = json["height"].toInt();
response->streamInfo.rotation_ = json["rotation"].toInt();
response->streamInfo.splitDuration_ = json["splitDuration"].toInt();
response->streamInfo.status_ = json["status"].toString();
response->streamInfo.steamIndex_ = json["streamIndex"].toString();
response->streamInfo.width_ = json["width"].toInt();
if (json.contains("bitwidth")) {
response->streamInfo.bitWidth_ = json["bitwidth"].toString();
}
if (json.contains("fps")) {
response->streamInfo.fps = json["fps"].toInt();
}
}
| 3,781
|
C++
|
.cpp
| 89
| 40.157303
| 80
| 0.735142
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,182
|
main.cpp
|
summershrimp_obs-ssp/ssp_connector/main.cpp
|
/*
* Copyright (c) 2015-2021, Yibai Zhang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Yibai Zhang, obs-ssp, ssp_connector
* nor the names contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#include <imf/ssp/sspclient.h>
#include <imf/net/threadloop.h>
#include "main.h"
#include "ssp_connector_proto.h"
char address[256] = {0};
unsigned int port = 0;
char uuid[64] = {0};
imf::SspClient *gSspClient = nullptr;
imf::Loop *gLoop = nullptr;
int msg_write(char *buf, size_t size)
{
Message *msg = (Message *)buf;
size_t writed = 0, cur = 0;
//log_conn("send msg type: %d, size %d", msg->type, msg->length);
return fwrite(buf, 1, size, stdout);
}
int process_args(int argc, char **argv)
{
int t = 1;
while (t < argc) {
if (t + 1 >= argc) {
return -1;
}
if ((!strcmp(argv[t], "-h") || !strcmp(argv[t], "--host"))) {
++t;
strncpy(address, argv[t], sizeof(address));
} else if (!strcmp(argv[t], "-p") ||
!strcmp(argv[t], "--port")) {
++t;
port = strtoul(argv[t], NULL, 0);
} else if (!strcmp(argv[t], "-u") ||
!strcmp(argv[t], "--uuid")) {
++t;
strncpy(uuid, argv[t], sizeof(uuid));
} else {
return -1;
}
++t;
}
if (strlen(address) == 0 || port == 0) {
return -1;
}
return 0;
}
void print_usage(void)
{
fprintf(stderr,
"Usage: ssp_connector --host host --port port [--uuid uuid]");
}
static void on_general_message(MessageType type)
{
Message msg;
msg.length = 0;
msg.type = type;
int sz = msg_write((char *)&msg, sizeof(msg));
if (sz != sizeof(msg)) {
log_conn("stopped.");
gSspClient->stop();
gLoop->quit();
}
}
static void on_video(imf::SspH264Data *video)
{
size_t len = sizeof(Message) + sizeof(VideoData) + video->len;
auto *msg = (Message *)malloc(len);
msg->type = VideoDataMsg;
msg->length = sizeof(VideoData) + video->len;
auto *videoData = (VideoData *)msg->value;
videoData->frm_no = video->frm_no;
videoData->ntp_timestamp = video->ntp_timestamp;
videoData->pts = video->pts;
videoData->type = video->type;
videoData->len = video->len;
memcpy(videoData->data, video->data, video->len);
int sz = msg_write((char *)msg, len);
free(msg);
if (sz != len) {
log_conn("stopped.");
gSspClient->stop();
gLoop->quit();
}
}
static void on_audio(imf::SspAudioData *audio)
{
size_t len = sizeof(Message) + sizeof(AudioData) + audio->len;
auto *msg = (Message *)malloc(len);
msg->type = AudioDataMsg;
msg->length = sizeof(AudioData) + audio->len;
auto *audioData = (AudioData *)msg->value;
audioData->ntp_timestamp = audio->ntp_timestamp;
audioData->pts = audio->pts;
audioData->len = audio->len;
memcpy(audioData->data, audio->data, audio->len);
int sz = msg_write((char *)msg, len);
free(msg);
if (sz != len) {
log_conn("stopped.");
gSspClient->stop();
gLoop->quit();
}
}
static void on_meta(imf::SspVideoMeta *vmeta, struct imf::SspAudioMeta *ameta,
struct imf::SspMeta *meta)
{
size_t len = sizeof(Message) + sizeof(Metadata);
auto *msg = (Message *)malloc(len);
msg->type = MetaDataMsg;
msg->length = sizeof(Metadata);
auto *metadata = (Metadata *)msg->value;
metadata->ameta.bitrate = ameta->bitrate;
metadata->ameta.channel = ameta->channel;
metadata->ameta.encoder = ameta->encoder;
metadata->ameta.sample_rate = ameta->sample_rate;
metadata->ameta.sample_size = ameta->sample_size;
metadata->ameta.timescale = ameta->timescale;
metadata->ameta.unit = ameta->unit;
metadata->vmeta.encoder = vmeta->encoder;
metadata->vmeta.gop = vmeta->gop;
metadata->vmeta.height = vmeta->height;
metadata->vmeta.timescale = vmeta->timescale;
metadata->vmeta.unit = vmeta->unit;
metadata->vmeta.width = vmeta->width;
metadata->meta.pts_is_wall_clock = meta->pts_is_wall_clock;
metadata->meta.tc_drop_frame = meta->tc_drop_frame;
metadata->meta.timecode = meta->timecode;
int sz = msg_write((char *)msg, len);
free(msg);
if (sz != len) {
log_conn("stopped sz != len %d != %d.", sz, len);
gSspClient->stop();
gLoop->quit();
}
}
static void on_exception(int code, const char *description)
{
size_t len =
sizeof(Message) + sizeof(Message) + strlen(description) + 1;
auto *msg = (Message *)malloc(len);
msg->type = ExceptionMsg;
msg->length = sizeof(Message) + strlen(description) + 1;
auto *errmsg = (Message *)msg->value;
errmsg->length = strlen(description) + 1;
errmsg->type = code;
strcpy((char *)errmsg->value, description);
int sz = msg_write((char *)msg, len);
free(msg);
if (sz != len) {
log_conn("exception error.");
}
gSspClient->stop();
gLoop->quit();
}
static void setup(imf::Loop *loop)
{
auto client = new imf::SspClient(address, loop, 0x400000, port, 0);
client->init();
gSspClient = client;
client->setOnH264DataCallback(on_video);
client->setOnMetaCallback(on_meta);
client->setOnAudioDataCallback(on_audio);
client->setOnExceptionCallback(on_exception);
client->setOnConnectionConnectedCallback(
std::bind(on_general_message, ConnectionConnectedMsg));
client->setOnRecvBufferFullCallback(
std::bind(on_general_message, RecvBufferFullMsg));
client->setOnDisconnectedCallback([=]() {
on_general_message(DisconnectMsg);
client->stop();
loop->quit();
});
client->start();
Message msg;
msg.length = 0;
msg.type = ConnectorOkMsg;
int sz = msg_write((char *)&msg, sizeof(msg));
if (sz != sizeof(msg)) {
log_conn("stopped.");
client->stop();
gLoop->quit();
}
}
int main(int argc, char **argv)
{
int ret = process_args(argc, argv);
if (ret) {
print_usage();
return -1;
}
#ifdef _WIN32
_setmode(_fileno(stdout), O_BINARY);
#endif
setbuf(stdout, nullptr); // unbuffered stdout
log_conn("host: %s\nport: %d\nuuid: %s\n", address, port, uuid);
auto loop = new imf::Loop();
loop->init();
gLoop = loop;
setup(gLoop);
loop->loop();
log_conn("loop finished");
delete loop;
if (gSspClient) {
delete gSspClient;
}
return 0;
}
| 7,374
|
C++
|
.cpp
| 240
| 28.558333
| 80
| 0.69962
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,183
|
threadloop.h
|
summershrimp_obs-ssp/lib/ssp/include/imf/threadloop.h
|
#pragma once
#include <functional>
#include <thread>
#include <memory>
#include "constructormagic.h"
#include "ISspClient.h"
namespace imf {
class ThreadLoop {
public:
typedef std::function<void(Loop *)> PreLoopCallback;
typedef std::function<ILoop_class *(void)> LoopCreater;
explicit ThreadLoop(const PreLoopCallback &pre = PreLoopCallback(),
const LoopCreater &loop = LoopCreater())
: preLoopCb_(pre),
create_loop(loop),
loop_(nullptr),
started_(false)
{
}
~ThreadLoop()
{
// Buggy
if (started_ && loop_) {
loop_->quit();
thread_.join();
}
if (loop_) {
loop_->destroy();
}
}
void start(void)
{
if (started_ == false) {
started_ = true;
thread_ = std::thread(&ThreadLoop::run, this);
}
}
void stop(void)
{
started_ = false;
loop_->quit();
thread_.join();
}
void run(void)
{
if (loop_) {
loop_->destroy();
}
loop_ = create_loop();
loop_->init();
if (preLoopCb_) {
preLoopCb_((Loop *)loop_->getLoop());
}
loop_->loop();
}
private:
PreLoopCallback preLoopCb_;
bool started_;
std::thread thread_;
ILoop_class *loop_;
LoopCreater create_loop;
DISALLOW_COPY_AND_ASSIGN(ThreadLoop);
};
}
| 1,192
|
C++
|
.h
| 64
| 15.921875
| 68
| 0.661002
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,184
|
ISspClient.h
|
summershrimp_obs-ssp/lib/ssp/include/imf/ISspClient.h
|
#pragma once
#include <string>
#include <stdint.h>
#include <functional>
namespace imf {
#ifdef _WIN32
#define LIBSSP_API __declspec(dllexport)
#else
#define LIBSSP_API
#endif
#define ERROR_SSP_PROTOCOL_VERSION_GT_SERVER (-1000)
#define ERROR_SSP_PROTOCOL_VERSION_LT_SERVER (-1001)
#define ERROR_SSP_CONNECTION_FAILED (-1002)
#define ERROR_SSP_CONNECTION_EXIST (-1003)
#define VIDEO_ENCODER_UNKNOWN (0)
#define VIDEO_ENCODER_H264 (96)
#define VIDEO_ENCODER_H265 (265)
#define AUDIO_ENCODER_UNKNOWN (0)
#define AUDIO_ENCODER_AAC (37)
#define AUDIO_ENCODER_PCM (23)
enum { STREAM_DEFAULT = 0, STREAM_MAIN = 1, STREAM_SEC = 2 };
struct LIBSSP_API SspVideoMeta {
uint32_t width;
uint32_t height;
uint32_t timescale;
uint32_t unit;
uint32_t gop;
uint32_t encoder;
};
struct LIBSSP_API SspAudioMeta {
uint32_t timescale;
uint32_t unit;
uint32_t sample_rate;
uint32_t sample_size;
uint32_t channel;
uint32_t bitrate;
uint32_t encoder;
};
struct LIBSSP_API SspMeta {
bool pts_is_wall_clock;
bool tc_drop_frame;
uint32_t timecode;
};
struct LIBSSP_API SspH264Data {
uint8_t *data;
size_t len;
uint64_t pts;
uint64_t ntp_timestamp;
uint32_t frm_no;
uint32_t type; // I or P
};
struct LIBSSP_API SspAudioData {
uint8_t *data;
size_t len;
uint64_t pts;
uint64_t ntp_timestamp;
};
typedef std::function<void(void)>
OnRecvBufferFullCallback; // called when the recv buffer is full
typedef std::function<void(void)>
OnDisconnectedCallback; // called when the session is closed
typedef std::function<void(void)>
OnConnectionConnectedCallback; // called when the session is est
typedef std::function<void(struct SspH264Data *h264)>
OnH264DataCallback; // called every video frame is ready. Actually, it's a video callback, no matter it's compression format
typedef std::function<void(struct SspAudioData *audio)>
OnAudioDataCallback; // called every audio frame is ready
typedef std::function<void(struct SspVideoMeta *, struct SspAudioMeta *,
struct SspMeta *)>
OnMetaCallback; // meta data callback
typedef std::function<void(int code, const char *description)>
OnExceptionCallback; // exception
class Loop;
class ISspClient_class {
public:
virtual void destroy() = 0;
virtual int init(void) = 0;
virtual int start(void) = 0;
virtual int stop(void) = 0;
virtual void
setOnRecvBufferFullCallback(const OnRecvBufferFullCallback &cb) = 0;
virtual void setOnH264DataCallback(const OnH264DataCallback &cb) = 0;
virtual void setOnAudioDataCallback(const OnAudioDataCallback &cb) = 0;
virtual void setOnMetaCallback(const OnMetaCallback &cb) = 0;
virtual void
setOnDisconnectedCallback(const OnDisconnectedCallback &cb) = 0;
virtual void setOnConnectionConnectedCallback(
const OnConnectionConnectedCallback &cb) = 0;
virtual void setOnExceptionCallback(const OnExceptionCallback &cb) = 0;
};
class ILoop_class {
public:
virtual void destroy() = 0;
virtual int init(void) = 0;
virtual int loop(void) = 0;
virtual int quit(void) = 0;
virtual void *getLoop(void) = 0;
};
}
typedef imf::ISspClient_class *(*create_ssp_class_ptr)(const std::string &ip,
imf::Loop *loop,
size_t bufSize,
unsigned short port,
uint32_t streamStyle);
typedef imf::ILoop_class *(*create_loop_class_ptr)();
| 3,279
|
C++
|
.h
| 105
| 29.07619
| 125
| 0.765171
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,185
|
sspclient.h
|
summershrimp_obs-ssp/lib/ssp/include/imf/sspclient.h
|
#pragma once
#include "ISspClient.h"
namespace imf {
extern "C" {
ISspClient_class *create_ssp_class(const std::string &ip, Loop *loop,
size_t bufSize, unsigned short port,
uint32_t streamStyle);
ILoop_class *create_loop_class();
}
}
| 248
|
C++
|
.h
| 10
| 22.4
| 69
| 0.722689
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,187
|
ssp-client-iso.h
|
summershrimp_obs-ssp/src/ssp-client-iso.h
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#ifndef OBS_SSP_SSP_CLIENT_ISO_H
#define OBS_SSP_SSP_CLIENT_ISO_H
#include <QObject>
#include <QProcess>
#include <mutex>
#include <thread>
#include <imf/ISspClient.h>
extern "C" {
#include <util/pipe.h>
}
#include <ssp_connector_proto.h>
#ifdef _WIN64
#define SSP_CONNECTOR "../../obs-plugins/" OBS_SSP_BITSTR "/ssp-connector.exe"
#else
#define SSP_CONNECTOR "ssp-connector"
#endif
class SSPClientIso : public QObject {
Q_OBJECT
public:
SSPClientIso(const std::string &ip, uint32_t bufferSize);
virtual void
setOnRecvBufferFullCallback(const imf::OnRecvBufferFullCallback &cb);
virtual void setOnH264DataCallback(const imf::OnH264DataCallback &cb);
virtual void setOnAudioDataCallback(const imf::OnAudioDataCallback &cb);
virtual void setOnMetaCallback(const imf::OnMetaCallback &cb);
virtual void
setOnDisconnectedCallback(const imf::OnDisconnectedCallback &cb);
virtual void setOnConnectionConnectedCallback(
const imf::OnConnectionConnectedCallback &cb);
virtual void setOnExceptionCallback(const imf::OnExceptionCallback &cb);
void Stop();
void Restart();
static void *ReceiveThread(void *arg);
signals:
void Start();
private slots:
void doStart();
private:
virtual void OnRecvBufferFull();
virtual void OnH264Data(VideoData *video);
virtual void OnAudioData(AudioData *audio);
virtual void OnMetadata(Metadata *meta);
virtual void OnDisconnected();
virtual void OnConnectionConnected();
virtual void OnException(Message *exception);
std::mutex statusLock;
bool running;
std::string ip;
uint32_t bufferSize;
QString ssp_connector_path;
os_process_pipe_t *pipe;
std::thread worker;
imf::OnRecvBufferFullCallback bufferFullCallback;
imf::OnH264DataCallback h264DataCallback;
imf::OnAudioDataCallback audioDataCallback;
imf::OnConnectionConnectedCallback connectedCallback;
imf::OnDisconnectedCallback disconnectedCallback;
imf::OnMetaCallback metaCallback;
imf::OnExceptionCallback exceptionCallback;
};
#endif //OBS_SSP_SSP_CLIENT_ISO_H
| 2,656
|
C++
|
.h
| 75
| 33.666667
| 78
| 0.812865
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,188
|
ssp-controller.h
|
summershrimp_obs-ssp/src/ssp-controller.h
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#ifndef OBS_SSP_SSP_CONTROLLER_H
#define OBS_SSP_SSP_CONTROLLER_H
#include <functional>
#include <QObject>
#include "controller/cameracontroller.h"
#define E2C_MODEL_CODE "elephant"
#define IPMANS_MODEL_CODE "wlm"
typedef std::function<void(bool ok)> StatusUpdateCallback;
typedef std::function<void(bool ok, QString)> StatusReasonUpdateCallback;
class CameraStatus : QObject {
Q_OBJECT
public:
CameraStatus();
void setIp(const QString &ip);
QString getIp() { return controller->ip(); }
void getResolution(const StatusUpdateCallback &);
void getFramerate(const StatusUpdateCallback &);
void getCurrentStream(const StatusUpdateCallback &);
void getInfo(const StatusUpdateCallback &);
void refreshAll(const StatusUpdateCallback &);
CameraController *getController() { return controller; }
~CameraStatus();
void setLed(bool isOn);
QString model;
std::vector<QString> resolutions;
QString current_resolution;
std::vector<QString> framerates;
QString current_framerate;
StreamInfo current_streamInfo;
void setStream(int stream_index, QString resolution, bool low_noise,
QString fps, int bitrate, StatusReasonUpdateCallback cb);
signals:
void onSetStream(int stream_index, QString resolution, bool low_noise,
QString fps, int bitrate,
StatusReasonUpdateCallback cb);
void onRefresh(StatusUpdateCallback cb);
void onSetLed(bool on);
private slots:
void doSetStream(int stream_index, QString resolution, bool low_noise,
QString fps, int bitrate,
StatusReasonUpdateCallback cb);
void doRefresh(StatusUpdateCallback cb);
void doSetLed(bool on);
private:
CameraController *controller;
};
#endif //OBS_SSP_SSP_CONTROLLER_H
| 2,335
|
C++
|
.h
| 61
| 36.213115
| 73
| 0.802742
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,189
|
obs-ssp.h
|
summershrimp_obs-ssp/src/obs-ssp.h
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#ifndef OBSSSP_H
#define OBSSSP_H
#include <string>
#include "imf/ISspClient.h"
#include <stdint.h>
#include "plugin-support.h"
#if INTPTR_MAX == INT64_MAX
#define OBS_SSP_BITSTR "64bit"
#elif INTPTR_MAX == INT32_MAX
#define OBS_SSP_BITSTR "32bit"
#else
#error Unknown pointer size or missing size macros!
#endif
#define ssp_blog(level, msg, ...) \
blog(level, "[%s] " msg, PLUGIN_NAME, ##__VA_ARGS__)
extern create_ssp_class_ptr create_ssp_class;
extern create_loop_class_ptr create_loop_class;
#ifdef _WIN64
#define LIBSSP_LIBRARY_NAME "../../obs-plugins/" OBS_SSP_BITSTR "/libssp.dll"
#elif defined(__APPLE__)
#define LIBSSP_LIBRARY_NAME "../Frameworks/libssp.dylib"
#else
#define LIBSSP_LIBRARY_NAME "libssp.so"
#endif
#define ZCAM_QUERY_DOMAIN "_eagle._tcp.local"
#endif // OBSSSP_H
| 1,460
|
C++
|
.h
| 40
| 35.175
| 77
| 0.772889
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,190
|
obs-ffmpeg-compat.h
|
summershrimp_obs-ssp/src/obs-ffmpeg-compat.h
|
#pragma once
#include <libavcodec/avcodec.h>
/* LIBAVCODEC_VERSION_CHECK checks for the right version of libav and FFmpeg
* a is the major version
* b and c the minor and micro versions of libav
* d and e the minor and micro versions of FFmpeg */
#define LIBAVCODEC_VERSION_CHECK(a, b, c, d, e) \
((LIBAVCODEC_VERSION_MICRO < 100 && \
LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, b, c)) || \
(LIBAVCODEC_VERSION_MICRO >= 100 && \
LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, d, e)))
#define INPUT_BUFFER_PADDING_SIZE AV_INPUT_BUFFER_PADDING_SIZE
| 614
|
C++
|
.h
| 12
| 48.916667
| 76
| 0.656093
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,191
|
VFrameQueue.h
|
summershrimp_obs-ssp/src/VFrameQueue.h
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#ifndef OBS_SSP_VFRAMEQUEUE_H
#define OBS_SSP_VFRAMEQUEUE_H
#include <QQueue>
#include <QAtomicInt>
#include <QSemaphore>
#include <QMutex>
#include <imf/ISspClient.h>
#include "pthread.h"
class VFrameQueue {
struct Frame {
imf::SspH264Data data;
uint64_t time;
bool noDrop;
};
typedef std::function<void(imf::SspH264Data *)> CallbackFunc;
public:
VFrameQueue();
void enqueue(imf::SspH264Data, uint64_t time_us, bool noDrop);
void setFrameTime(uint64_t time_us);
void setFrameCallback(CallbackFunc);
void start();
void stop();
private:
static void run(VFrameQueue *q);
static void *pthread_run(void *q);
CallbackFunc callback;
QQueue<Frame> frameQueue;
QSemaphore sem;
QMutex queueLock;
pthread_t thread;
QAtomicInt running;
uint64_t maxTime;
};
#endif //OBS_SSP_VFRAMEQUEUE_H
| 1,469
|
C++
|
.h
| 48
| 28.916667
| 68
| 0.789809
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,192
|
ssp-mdns.h
|
summershrimp_obs-ssp/src/ssp-mdns.h
|
/*
obs-ssp
Copyright (C) 2019-2020 Yibai Zhang
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <https://www.gnu.org/licenses/>
*/
#ifndef OBS_SSP_SSP_MDNS_H
#define OBS_SSP_SSP_MDNS_H
#include <mdns.h>
#include <string>
#include <map>
struct ssp_device_item {
std::string device_name;
std::string ip_address;
};
struct mdns_record {
bool has_ptr;
std::string ptr_record;
bool has_a;
sockaddr_in a_record;
bool has_aaaa;
sockaddr_in6 aaaa_record;
uint64_t last_available;
};
class SspMDnsIterator {
public:
SspMDnsIterator();
~SspMDnsIterator();
bool hasNext();
ssp_device_item *next();
private:
uint64_t current_time;
std::map<std::string, mdns_record>::const_iterator iter;
};
void create_mdns_loop();
void stop_mdns_loop();
#endif //OBS_SSP_SSP_MDNS_H
| 1,309
|
C++
|
.h
| 45
| 27.511111
| 68
| 0.779107
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,193
|
ffmpeg-decode.h
|
summershrimp_obs-ssp/src/ffmpeg-decode.h
|
/******************************************************************************
Copyright (C) 2014 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <obs.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4204)
#endif
#include <libavcodec/avcodec.h>
#include <libavutil/log.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
struct ffmpeg_decode {
AVBufferRef *hw_device_ctx;
AVCodecContext *decoder;
const AVCodec *codec;
AVFrame *hw_frame;
AVFrame *frame;
bool hw;
uint8_t *packet_buffer;
size_t packet_size;
};
extern int ffmpeg_decode_init(struct ffmpeg_decode *decode, enum AVCodecID id,
bool use_hw);
extern void ffmpeg_decode_free(struct ffmpeg_decode *decode);
extern bool ffmpeg_decode_audio(struct ffmpeg_decode *decode, uint8_t *data,
size_t size, struct obs_source_audio *audio,
bool *got_output);
extern bool ffmpeg_decode_video(struct ffmpeg_decode *decode, uint8_t *data,
size_t size, long long *ts,
enum video_colorspace cs,
enum video_range_type range,
struct obs_source_frame2 *frame,
bool *got_output);
static inline bool ffmpeg_decode_valid(struct ffmpeg_decode *decode)
{
return decode->decoder != NULL;
}
#ifdef __cplusplus
}
#endif
| 2,042
|
C++
|
.h
| 57
| 32.947368
| 79
| 0.694614
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,194
|
cameraconfig.h
|
summershrimp_obs-ssp/src/controller/cameraconfig.h
|
/*
* Copyright (c) 2015-2020, Shenzhen Imaginevision Technology Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Shenzhen Imaginevision Technology Limited ("ZCAM")
* nor the names contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CAMERACONFIG_H
#define CAMERACONFIG_H
#include <QList>
#include <QNetworkReply>
#include <functional>
#include <cstdio>
class CameraController;
#define CONFIG_KEY_SATURATION "saturation"
#define CONFIG_KEY_SHARPNESS "sharpness"
#define CONFIG_KEY_CONTRAST "contrast"
#define CONFIG_KEY_BRIGHTNESS "brightness"
#define CONFIG_KEY_LUMA_LEVEL "luma_level"
#define CONFIG_KEY_METERING "meter_mode"
#define CONFIG_KEY_FLICKER "flicker"
#define CONFIG_KEY_ISO "iso"
#define CONFIG_KEY_MAX_ISO "max_iso"
#define CONFIG_KEY_WB "wb"
#define CONFIG_KEY_MWB "mwb"
#define CONFIG_KEY_WB_PRIORITY "wb_priority"
#define CONFIG_KEY_IRIS "iris"
#define CONFIG_KEY_AF_MODE "af_mode"
#define CONFIG_KEY_AF_AREA "af_area"
#define CONFIG_KEY_FOCUS_METHOD "focus"
#define CONFIG_KEY_MF_DRIVE "mf_drive"
#define CONFIG_KEY_CAF "caf"
#define CONFIG_KEY_CAF_RANGE "caf_range"
#define CONFIG_KEY_CAF_SENSITIVITY "caf_sens"
#define CONFIG_KEY_CAF_LIVE "live_caf"
#define CONFIG_KEY_MF_MAG "mf_mag"
#define CONFIG_KEY_MF_ASSIST "mf_assist"
#define CONFIG_KEY_PHOTO_QUALITY "photo_q"
#define CONFIG_KEY_PHOTO_TIMELAPSE "photo_tl"
#define CONFIG_KEY_PHOTO_BURST "burst"
#define CONFIG_KEY_PHOTO_BURST_SPD "burst_spd"
#define CONFIG_KEY_SHUTTER_SPEED "shutter_spd"
#define CONFIG_KEY_SHUTTER_ANGLE "shutter_angle"
#define CONFIG_KEY_SHUTTER_TIME "shutter_time"
#define CONFIG_KEY_EXPOSURE_MODE "shoot_mode"
#define CONFIG_KEY_SHUTTER_OP "sht_operation"
#define CONFIG_KEY_SPLIT_DURATION "split_duration"
#define CONFIG_KEY_LENS_ZOOM "lens_zoom"
#define CONFIG_KEY_LENS_ZOOM_POS "lens_zoom_pos"
#define CONFIG_KEY_LENS_FOCUS_POS "lens_focus_pos"
#define CONFIG_KEY_DRIVE_MODE "drive_mode"
#define CONFIG_KEY_RECORD_MODE "record_mode"
#define CONFIG_KEY_SELF_TIMER_INTERVAL "photo_self_interval"
#define CONFIG_KEY_RECORD_TL_INTERVAL "record_tl_interval"
#define CONFIG_KEY_TIMELAPSE_INTERVAL "photo_tl_interval"
#define CONFIG_KEY_TIMELAPSE_NUM "photo_tl_num"
#define CONFIG_KEY_VIDEO_SYSTEM "video_system"
#define CONFIG_KEY_HDMI_OSD "hdmi_osd"
#define CONFIG_KEY_FN_BTN_FUN "Fn"
#define CONFIG_KEY_CAMERA_ROT "camera_rot"
#define CONFIG_KEY_HDMI_FMT "hdmi_fmt"
#define CONFIG_KEY_TINT "tint"
#define CONFIG_KEY_LCD_BACK_LIGHT "lcd_backlight"
#define CONFIG_KEY_FILE_NUMBER "file_number"
#define CONFIG_KEY_VIDEO_OUTPUT "video_output"
#define CONFIG_KEY_POWER_BTN_FUN "F2"
#define CONFIG_KEY_OLED "oled"
#define CONFIG_KEY_BEEP "beep"
#define CONFIG_KEY_LED "led"
#define CONFIG_KEY_LCD "lcd"
#define CONFIG_KEY_LCD_AUTO_OFF "auto_off_lcd"
#define CONFIG_KEY_ROTATION "rotation"
#define CONFIG_KEY_MAX_EXPOSSURE_TIME "max_exp"
#define CONFIG_KEY_MAX_EXPOSSURE_SHUTTER_TIME "max_exp_shutter_time"
#define CONFIG_KEY_MAX_EXPOSSURE_SHUTTER_ANGLE "max_exp_shutter_angle"
#define CONFIG_KEY_NOISE_REDUCTION "??"
#define CONFIG_KEY_AUTO_POWER_OFF "auto_off"
#define CONFIG_KEY_LUT "lut"
#define CONFIG_KEY_DISTORTION "dewarp"
#define CONFIG_KEY_VIGNETTE "vignette"
#define CONFIG_KEY_MULTIPLE_MODE "multiple_mode"
#define CONFIG_KEY_GRID_DISPLAY "grid_display"
#define CONFIG_KEY_FUCOS_POS "lens_focus_spd"
#define CONFIG_KEY_FOCUS_SPD "lens_focus_pos"
#define CONFIG_KEY_MOVIE_FORMAT "movfmt"
#define CONFIG_KEY_MOVIE_RESOLUTION "resolution"
#define CONFIG_KEY_PROJECT_FPS "project_fps"
#define CONFIG_KEY_BITRATE "bitrate_level"
#define CONFIG_KEY_VIDEO_ENCODER "video_encoder"
#define CONFIG_KEY_LIVE_FNO "live_ae_fno"
#define CONFIG_KEY_LIVE_ISO "live_ae_iso"
#define CONFIG_KEY_LIVE_SHUTTER "live_ae_shutter"
#define CONFIG_KEY_PHOTO_SIZE "photosize"
#define CONFIG_KEY_SSID "ssid"
#define CONFIG_KEY_AP_KEY "ap_key"
#define CONFIG_KEY_BATTERY "battery"
#define CONFIG_KEY_EV "ev"
#define CONFIG_KEY_PRIMARY_BITRATE "primary_bitrate"
#define CONFIG_KEY_SEC_RATE_CONTROL "sec_rate_control"
#define CONFIG_KEY_SEC_STREAM_ROTATION "sec_rotate"
#define CONFIG_KEY_SEC_AUDIO "sec_audio"
#define CONFIG_KEY_SEC_RESOLUTION "sec_resolution"
#define CONFIG_KEY_SEC_GOP_M "sec_gop_m"
#define CONFIG_KEY_SEC_GOP_N "sec_gop_n"
#define CONFIG_KEY_SEC_BITRATE "sec_bitrate"
#define CONFIG_KEY_SUPPORT_PREVIEW "support_sec"
#define CONFIG_KEY_UNION_AE "union_ae"
#define CONFIG_KEY_UNION_AE_DELTA "union_ae_delta"
#define CONFIG_KEY_UNION_AE_PRIORITY "union_ae_priority"
#define CONFIG_KEY_UNION_AWB "union_awb"
#define CONFIG_KEY_UNION_AWB_DELTA "union_awb_delta"
#define CONFIG_KEY_UNION_AWB_PRIORITY "union_awb_priority"
#define CONFIG_KEY_NETWORK_MODE "Network"
#define CONFIG_KEY_AWB_COORDINATE "-awb_coordinate-"
#define CONFIG_KEY_AWB_METERING "-awb_metering-"
#define CONFIG_KEY_AE_COORDINATE "-ae_coordinate-"
#define CONFIG_KEY_AE_METERING "-ae_metering-"
#define CONFIG_KEY_VIDEO_RECORD_DURATION "rec_duration"
#define CONFIG_KEY_VIDEO_TIMELASE_ENABLE "enable_video_tl"
#define CONFIG_KEY_VIDEO_TIMELAPSE_INTERVAL "video_tl_interval"
#define CONFIG_KEY_SNAP_INTERVAL "vr_snap_interval"
#define CONFIG_KEY_SNAP_ENABLE "enable_vr_snap"
#define CONFIG_KEY_SNAP_COUNT "vr_snap_count"
#define CONFIG_KEY_SNAP_TOKEN "vr_snap_token"
#define CONFIG_KEY_MULTIPLE_ID "multiple_id"
#define CONFIG_KEY_MULTIPLE_MODE "multiple_mode"
#define CONFIG_KEY_SN "sn"
#define CONFIG_KEY_SEND_STREAM "send_stream"
#define CONFIG_KEY_AE_LOCK "ae_lock"
#define SESSION_HEARTBEAT "heart_x_beat"
#define MUTIPLE_MODE_MASTER "master"
#define MUTIPLE_MODE_SLAVE "slave"
#define MUTIPLE_MODE_NONE "none"
#define NETWORK_MODE_ROUTER "Router"
#define NETWORK_MODE_DIRECT "Direct"
#define NETWORK_MODE_STATIC "Static"
#define SEND_STREAM_0 "Stream0"
#define SEND_STREAM_1 "Stream1"
#define AE_LOCK "Lock"
#define AE_UNLOCK "Unlock"
#define CONFIG_KEY_AUDIO_ENCODER "primary_audio"
#define CONFIG_KEY_AUDIO_CHANNEL "audio_channel"
#define CONFIG_KEY_AUDIO_IN_GAIN "audio_input_gain"
#define CONFIG_KEY_AUDIO_OUT_GAIN "audio_output_gain"
#define CONFIG_KEY_AUDIO_PHANTOM_POWER "audio_phantom_power"
#define CONFIG_KEY_TC_COUNT_UP "tc_count_up"
#define CONFIG_KEY_TC_HDMI "tc_hdmi_dispaly"
#define CONFIG_KEY_MOVVFR "movvfr"
#define CONFIG_KEY_WDR "compose_mode"
#define CONFIG_KEY_DUAL_ISO "dual_iso"
#define CONFIG_KEY_RECORD_FILE_FORMAT "record_file_format"
#define CONFIG_KEY_REC_PROXY "rec_proxy_file"
#define CONFIG_KEY_REC_FPS "rec_fps"
#define CONFIG_KEY_WIFI "wifi"
#define CAMERA_CONFIG_MOVIE_FORMAT 0
#define CAMERA_CONFIG_PHOTO_SIZE 1
#define CAMERA_CONFIG_WB 2
#define CAMERA_CONFIG_ISO 3
#define CAMERA_CONFIG_SHARPNESS 4
#define CAMERA_CONFIG_CONTRAST 5
#define CAMERA_CONFIG_AE_METER_MODE 6
#define SAVE_IP_DEPARATOR "-"
#define DOWNLOAD_THREAD_POOL_MAX_DEFAULT_SIZE 2
#define HTTP_DEFAULT_PORT 80
#define HEART_BEAT_INTERVAL (1000 * 5)
#define SET_CONFIG_DELAY_TIME 1000
enum RequestType {
REQUEST_TYPE_CODE,
REQUEST_TYPE_MESSAGE,
REQUEST_TYPE_CONFIG,
REQUEST_TYPE_INFO,
REQUEST_TYPE_FILES,
REQUEST_TYPE_MEDIA_INFO,
REQUEST_TYPE_NETINFO,
REQUEST_TYPE_STREAM_INFO
};
enum ConfigType {
CONFIG_TYPE_CHOICE = 1,
CONFIG_TYPE_RANGE,
CONFIG_TYPE_STRING
};
struct CameraConfigInfo {
int code;
int min;
int max;
int step;
int intValue;
bool readOnly;
QString msg;
QString key;
QString currentValue;
ConfigType type;
QList<QString> choices;
};
struct StreamInfo {
QString steamIndex_;
QString encoderType_;
QString bitWidth_;
int width_;
int height_;
int fps;
int bitrate_;
int gop_;
int rotation_;
int splitDuration_;
QString status_;
};
struct HttpResponse {
struct StreamInfo streamInfo;
//Config type
int intValue;
int min;
int max;
int step;
int code;
int statusCode;
bool readOnly;
ConfigType type;
RequestType reqType;
QString reqKey;
QString reqValue;
QString key;
QString msg;
QString shortPath;
QString currentValue;
QList<QString> choices;
QList<QString> files;
QNetworkReply::NetworkError responseError;
};
typedef std::function<void(struct HttpResponse *rsp)> OnRequestCallback;
struct HttpRequest {
bool useShortPath;
int timeout;
QString key;
QString value;
QString shortPath;
QString fullPath;
RequestType reqType;
OnRequestCallback callback;
};
typedef struct {
QString name;
QString sn;
QString inputFmt;
QString outputFmt;
QString time;
QStringList configs;
} SBOConfig;
class CameraConfig {
public:
static ConfigType getConfigType(const QString &key);
static void parseForConfig(const QJsonObject &json,
struct HttpResponse *response);
static void parseForCommon(const QJsonObject &json,
struct HttpResponse *response);
static void parseForStreamInfo(const QJsonObject &json,
struct HttpResponse *response);
CameraConfig();
~CameraConfig();
};
#endif // CAMERACONFIG_H
| 10,179
|
C++
|
.h
| 281
| 34.676157
| 80
| 0.78926
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,195
|
cameracontroller.h
|
summershrimp_obs-ssp/src/controller/cameracontroller.h
|
/*
* Copyright (c) 2015-2020, Shenzhen Imaginevision Technology Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Shenzhen Imaginevision Technology Limited ("ZCAM")
* nor the names contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CAMERACONTROLLER_H
#define CAMERACONTROLLER_H
#define ZCAM_RTMP 1
#include <QObject>
#include <QQueue>
#include <QNetworkReply>
#include <QAbstractSocket>
#include <functional>
#include <cstdio>
#include "cameraconfig.h"
#define URL_INFO "/info"
#define URL_CTRL_GET "/ctrl/get"
#define URL_CTRL_SET "/ctrl/set"
#define URL_CTRL_STREAM "/ctrl/primary_stream"
#define URL_CTRL_STREAM_SETTING "/ctrl/stream_setting"
#define URL_CTRL_SESSION "/ctrl/session"
#define HTTP_REQUEST_KEY_INVALID "invalid"
#define HTTP_SHORT_TIMEOUT 3 * 1000
#define HTTP_NORMAL_TIMEOUT 5 * 1000
#define HTTP_COMMAND_TIMEOUT 3 * 1000
#define HTTP_LONG_TIMEOUT 8 * 1000
#define HTTP_GET_MODE_LONG_TIMEOUT 20 * 1000
#define SESSION_HEARTBEAT_FAIL_TIME 2
class CameraConfig;
class QTimer;
class QUrl;
class QNetworkAccessManager;
class QBuffer;
class QTcpSocket;
class CameraController : public QObject {
Q_OBJECT
public:
explicit CameraController(QObject *parent = 0);
~CameraController();
void getCameraConfig(const QString &key, int timeout,
OnRequestCallback callback);
void getCameraConfig(const QString &key, OnRequestCallback callback);
void setCameraConfig(const QString &key, const QString &value,
OnRequestCallback callback);
void getInfo(OnRequestCallback callback);
void requestForCode(const QString &shortPath, int timeout,
OnRequestCallback callback);
void requestForCode(const QString &shortPath,
OnRequestCallback callback);
void setSendStream(const QString &value, OnRequestCallback callback);
void setStreamBitrate(const QString &index, const QString &bitrate,
OnRequestCallback callback);
void setStreamBitrateAndGop(const QString &index,
const QString &bitrate, const QString &gop,
OnRequestCallback callback);
void setStreamResolution(const QString &index, const QString &width,
const QString &height,
OnRequestCallback callback);
void setStreamFPS(const QString &index, const QString &fps,
OnRequestCallback callback);
void setStreamCodec(const QString &index, const QString &codec,
OnRequestCallback callback);
void setStreamGop(const QString &index, const QString &gop,
OnRequestCallback callback);
void setStreamBitwidth(const QString &index, const QString &bitwidth,
OnRequestCallback callback);
void getStreamInfo(const QString &index, OnRequestCallback callback);
void setIp(const QString &ip);
void clearConnectionStatus();
void cancelCurrentReq();
void cancelAllReqs();
void cancelReqs(QStringList keys);
void resetNetwork();
QString ip() const { return ip_; }
private slots:
void handleReqeustResult();
private:
void handleRequestResult(HttpRequest *req, QNetworkReply *reply);
//Http request
void nextRequest();
void nextRequest(HttpRequest *req);
void commonRequest(struct HttpRequest *req);
void parseResponse(const QByteArray &byteData, struct HttpResponse *rsp,
RequestType reqType);
QString buildRequestPath(const QString &shortPath, const QString &ip,
bool useShortPath);
QString ip_;
bool requesting_;
QNetworkReply *reply_;
QNetworkAccessManager *networkManager_;
QQueue<struct HttpRequest *> *httpRequestQueue_;
};
#endif // CAMERACONTROLLER_H
| 4,842
|
C++
|
.h
| 115
| 39.486957
| 80
| 0.787686
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,196
|
main.h
|
summershrimp_obs-ssp/ssp_connector/main.h
|
/*
* Copyright (c) 2015-2022, Yibai Zhang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Yibai Zhang, obs-ssp, ssp_connector
* nor the names contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define log_conn(fmt, ...) \
fprintf(stderr, "%s:%d " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
// #define log_conn(fmt, ...) (void *)0;
| 1,715
|
C++
|
.h
| 30
| 55.2
| 80
| 0.753563
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,197
|
ssp_connector_proto.h
|
summershrimp_obs-ssp/ssp_connector/ssp_connector_proto.h
|
/*
* Copyright (c) 2015-2021, Yibai Zhang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Yibai Zhang, obs-ssp, ssp_connector
* nor the names contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SSP_CONNECTOR_PROTO_H_
#define SSP_CONNECTOR_PROTO_H_
#include <stdint.h>
#pragma pack(1)
#define SSP_PROTO
struct SSP_PROTO VideoMeta {
uint32_t width;
uint32_t height;
uint32_t timescale;
uint32_t unit;
uint32_t gop;
uint32_t encoder;
};
struct SSP_PROTO AudioMeta {
uint32_t timescale;
uint32_t unit;
uint32_t sample_rate;
uint32_t sample_size;
uint32_t channel;
uint32_t bitrate;
uint32_t encoder;
};
struct SSP_PROTO BaseMeta {
uint16_t pts_is_wall_clock;
uint16_t tc_drop_frame;
uint32_t timecode;
};
struct SSP_PROTO Metadata {
struct BaseMeta meta;
struct VideoMeta vmeta;
struct AudioMeta ameta;
};
struct SSP_PROTO VideoData {
uint64_t pts;
uint64_t ntp_timestamp;
uint32_t frm_no;
uint32_t type; // I or P
size_t len;
uint8_t data[0];
};
struct SSP_PROTO AudioData {
uint64_t pts;
uint64_t ntp_timestamp;
size_t len;
uint8_t data[0];
};
enum MessageType {
MetaDataMsg = 1,
VideoDataMsg,
AudioDataMsg,
RecvBufferFullMsg,
DisconnectMsg,
ConnectionConnectedMsg,
ExceptionMsg,
ConnectorOkMsg,
};
struct Message {
uint32_t type;
uint32_t length;
uint8_t value[0];
};
#pragma pack()
#endif
| 2,729
|
C++
|
.h
| 90
| 28.433333
| 80
| 0.772658
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,198
|
pthread-barrier.h
|
summershrimp_obs-ssp/ssp_connector/libuv/include/pthread-barrier.h
|
/*
Copyright (c) 2016, Kari Tristan Helgason <kthelgason@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _UV_PTHREAD_BARRIER_
#define _UV_PTHREAD_BARRIER_
#include <errno.h>
#include <pthread.h>
#include <semaphore.h> /* sem_t */
#define PTHREAD_BARRIER_SERIAL_THREAD 0x12345
/*
* To maintain ABI compatibility with
* libuv v1.x struct is padded according
* to target platform
*/
#if defined(__ANDROID__)
#define UV_BARRIER_STRUCT_PADDING \
sizeof(pthread_mutex_t) + sizeof(pthread_cond_t) + \
sizeof(unsigned int) - sizeof(void *)
#elif defined(__APPLE__)
#define UV_BARRIER_STRUCT_PADDING \
sizeof(pthread_mutex_t) + 2 * sizeof(sem_t) + \
2 * sizeof(unsigned int) - sizeof(void *)
#endif
typedef struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
unsigned threshold;
unsigned in;
unsigned out;
} _uv_barrier;
typedef struct {
_uv_barrier *b;
char _pad[UV_BARRIER_STRUCT_PADDING];
} pthread_barrier_t;
int pthread_barrier_init(pthread_barrier_t *barrier, const void *barrier_attr,
unsigned count);
int pthread_barrier_wait(pthread_barrier_t *barrier);
int pthread_barrier_destroy(pthread_barrier_t *barrier);
#endif /* _UV_PTHREAD_BARRIER_ */
| 1,891
|
C++
|
.h
| 49
| 36.979592
| 78
| 0.75832
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
1,537,199
|
uv-darwin.h
|
summershrimp_obs-ssp/ssp_connector/libuv/include/uv-darwin.h
|
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef UV_DARWIN_H
#define UV_DARWIN_H
#if defined(__APPLE__) && defined(__MACH__)
#include <mach/mach.h>
#include <mach/task.h>
#include <mach/semaphore.h>
#include <TargetConditionals.h>
#define UV_PLATFORM_SEM_T semaphore_t
#endif
#define UV_IO_PRIVATE_PLATFORM_FIELDS \
int rcount; \
int wcount;
#define UV_PLATFORM_LOOP_FIELDS \
uv_thread_t cf_thread; \
void *_cf_reserved; \
void *cf_state; \
uv_mutex_t cf_mutex; \
uv_sem_t cf_sem; \
void *cf_signals[2];
#define UV_PLATFORM_FS_EVENT_FIELDS \
uv__io_t event_watcher; \
char *realpath; \
int realpath_len; \
int cf_flags; \
uv_async_t *cf_cb; \
void *cf_events[2]; \
void *cf_member[2]; \
int cf_error; \
uv_mutex_t cf_mutex;
#define UV_STREAM_PRIVATE_PLATFORM_FIELDS void *select;
#define UV_HAVE_KQUEUE 1
#endif /* UV_DARWIN_H */
| 2,089
|
C++
|
.h
| 52
| 38.326923
| 79
| 0.706752
|
summershrimp/obs-ssp
| 32
| 10
| 8
|
GPL-2.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,200
|
sigmap.cc
|
haowenz_sigmap/src/sigmap.cc
|
#include "sigmap.h"
#include <omp.h>
#include <cassert>
#include <iostream>
#include <string>
#include "cxxopts.hpp"
#include "khash.h"
#include "nanoflann.hpp"
#include "pore_model.h"
#include "sequence_batch.h"
#include "spatial_index.h"
KHASH_MAP_INIT_INT(k64, uint64_t);
namespace sigmap {
void Sigmap::GenerateMaskedPositions(
int kmer_size, float frequency, uint32_t num_sequences,
const SequenceBatch &sequence_batch,
std::vector<std::vector<bool> > &positive_is_masked,
std::vector<std::vector<bool> > &negative_is_masked) {
double real_start_time = GetRealTime();
khash_t(k64) *kmer_hist = kh_init(k64);
uint64_t num_shifted_bits = 2 * (kmer_size - 1);
uint64_t mask = (((uint64_t)1) << (2 * kmer_size)) - 1;
uint64_t seeds_in_two_strands[2] = {0, 0};
uint64_t num_kmers = 0;
int unambiguous_length = 0;
// Count kmers
for (uint32_t sequence_index = 0; sequence_index < num_sequences;
++sequence_index) {
uint32_t sequence_length =
sequence_batch.GetSequenceLengthAt(sequence_index);
const char *sequence = sequence_batch.GetSequenceAt(sequence_index);
unambiguous_length = 0;
seeds_in_two_strands[0] = 0;
seeds_in_two_strands[1] = 0;
for (uint32_t position = 0; position < sequence_length; ++position) {
uint8_t current_base = SequenceBatch::CharToUint8(sequence[position]);
if (current_base < 4) { // not an ambiguous base
seeds_in_two_strands[0] =
((seeds_in_two_strands[0] << 2) | current_base) &
mask; // forward k-mer
seeds_in_two_strands[1] = (seeds_in_two_strands[1] >> 2) |
(((uint64_t)(3 ^ current_base))
<< num_shifted_bits); // reverse k-mer
// if (seeds_in_two_strands[0] == seeds_in_two_strands[1]) {
// continue; // skip "symmetric k-mers" as we don't know it strand
//}
++unambiguous_length;
if (unambiguous_length >= kmer_size) {
uint64_t strand = seeds_in_two_strands[0] < seeds_in_two_strands[1]
? 0
: 1; // strand
khiter_t kmer_hist_iterator =
kh_get(k64, kmer_hist, seeds_in_two_strands[strand]);
if (kmer_hist_iterator != kh_end(kmer_hist)) {
kh_value(kmer_hist, kmer_hist_iterator) += 1;
} else {
int khash_return_code;
khiter_t kmer_hist_insert_iterator =
kh_put(k64, kmer_hist, seeds_in_two_strands[strand],
&khash_return_code);
assert(khash_return_code != -1 && khash_return_code != 0);
kh_value(kmer_hist, kmer_hist_insert_iterator) = 1;
}
++num_kmers;
}
} else {
unambiguous_length = 0;
seeds_in_two_strands[0] = 0;
seeds_in_two_strands[1] = 0;
}
}
}
std::cout << "# " << kmer_size << "mers: " << num_kmers << "\n";
// Mask kmers
uint64_t num_masked_kmers = 0;
for (uint32_t sequence_index = 0; sequence_index < num_sequences;
++sequence_index) {
uint32_t sequence_length =
sequence_batch.GetSequenceLengthAt(sequence_index);
const char *sequence = sequence_batch.GetSequenceAt(sequence_index);
positive_is_masked.emplace_back(
std::vector<bool>(sequence_length - kmer_size + 1, false));
unambiguous_length = 0;
seeds_in_two_strands[0] = 0;
seeds_in_two_strands[1] = 0;
for (uint32_t position = 0; position < sequence_length; ++position) {
uint8_t current_base = SequenceBatch::CharToUint8(sequence[position]);
if (current_base < 4) { // not an ambiguous base
seeds_in_two_strands[0] =
((seeds_in_two_strands[0] << 2) | current_base) &
mask; // forward k-mer
seeds_in_two_strands[1] = (seeds_in_two_strands[1] >> 2) |
(((uint64_t)(3 ^ current_base))
<< num_shifted_bits); // reverse k-mer
++unambiguous_length;
if (unambiguous_length >= kmer_size) {
uint64_t strand = seeds_in_two_strands[0] < seeds_in_two_strands[1]
? 0
: 1; // strand
khiter_t kmer_hist_iterator =
kh_get(k64, kmer_hist, seeds_in_two_strands[strand]);
assert(kmer_hist_iterator != kh_end(kmer_hist));
uint64_t kmer_freq = kh_value(kmer_hist, kmer_hist_iterator);
// std::cerr << "count: " << kh_value(kmer_hist, kmer_hist_iterator)
// << " position: " << position << " sequence_i: " << sequence_index
// <<
// "\n"; std::cerr << "size: " << is_masked[sequence_index].size() <<
// "\n";
if ((kmer_freq / (float)num_kmers) > frequency) {
positive_is_masked[sequence_index][position + 1 - kmer_size] = true;
++num_masked_kmers;
} else {
positive_is_masked[sequence_index][position + 1 - kmer_size] =
false;
}
}
} else {
unambiguous_length = 0;
seeds_in_two_strands[0] = 0;
seeds_in_two_strands[1] = 0;
if (position >= (uint32_t)kmer_size - 1) {
positive_is_masked[sequence_index][position + 1 - kmer_size] = true;
++num_masked_kmers;
}
}
}
const char *negative_sequence =
sequence_batch.GetNegativeSequenceAt(sequence_index).data();
negative_is_masked.emplace_back(
std::vector<bool>(sequence_length - kmer_size + 1, false));
unambiguous_length = 0;
seeds_in_two_strands[0] = 0;
seeds_in_two_strands[1] = 0;
for (uint32_t position = 0; position < sequence_length; ++position) {
uint8_t current_base =
SequenceBatch::CharToUint8(negative_sequence[position]);
if (current_base < 4) { // not an ambiguous base
seeds_in_two_strands[0] =
((seeds_in_two_strands[0] << 2) | current_base) &
mask; // forward k-mer
seeds_in_two_strands[1] = (seeds_in_two_strands[1] >> 2) |
(((uint64_t)(3 ^ current_base))
<< num_shifted_bits); // reverse k-mer
++unambiguous_length;
if (unambiguous_length >= kmer_size) {
uint64_t strand = seeds_in_two_strands[0] < seeds_in_two_strands[1]
? 0
: 1; // strand
khiter_t kmer_hist_iterator =
kh_get(k64, kmer_hist, seeds_in_two_strands[strand]);
assert(kmer_hist_iterator != kh_end(kmer_hist));
uint64_t kmer_freq = kh_value(kmer_hist, kmer_hist_iterator);
// std::cerr << "count: " << kh_value(kmer_hist, kmer_hist_iterator)
// << " position: " << position << " sequence_i: " << sequence_index
// <<
// "\n"; std::cerr << "size: " << is_masked[sequence_index].size() <<
// "\n";
if ((kmer_freq / (float)num_kmers) > frequency) {
negative_is_masked[sequence_index][position + 1 - kmer_size] = true;
++num_masked_kmers;
} else {
negative_is_masked[sequence_index][position + 1 - kmer_size] =
false;
}
}
} else {
unambiguous_length = 0;
seeds_in_two_strands[0] = 0;
seeds_in_two_strands[1] = 0;
if (position >= (uint32_t)kmer_size - 1) {
negative_is_masked[sequence_index][position + 1 - kmer_size] = true;
++num_masked_kmers;
}
}
}
}
kh_destroy(k64, kmer_hist);
std::cerr << "Mask " << num_masked_kmers << " high frequency kmer in "
<< GetRealTime() - real_start_time << "s.\n";
}
// void Sigmap::EmplaceBackMappingRecord(uint32_t read_id, const char
// *read_name, uint32_t read_length, uint32_t read_start_position, uint32_t
// read_end_position, uint32_t barcode, uint32_t fragment_start_position,
// uint32_t fragment_length, uint8_t mapq, uint8_t direction, uint8_t is_unique,
// std::vector<PAFMapping> *mappings_on_diff_ref_seqs) {
// mappings_on_diff_ref_seqs->emplace_back(PAFMapping{read_id,
// std::string(read_name), read_length, read_start_position, read_end_position,
// fragment_start_position, fragment_length, mapq, direction, is_unique});
//}
void Sigmap::OutputMappingsInVector(
uint8_t mapq_threshold, uint32_t num_reference_sequences,
const SequenceBatch &reference,
const std::vector<std::vector<PAFMapping> > &mappings) {
for (uint32_t ri = 0; ri < num_reference_sequences; ++ri) {
for (auto it = mappings[ri].begin(); it != mappings[ri].end(); ++it) {
uint8_t mapq = (it->mapq);
// uint8_t is_unique = (it->is_unique);
if (mapq >= mapq_threshold && mapq <= 60) {
// if (allocate_multi_mappings_ || (only_output_unique_mappings_ &&
// is_unique == 1)) {
output_tools_->AppendMapping(ri, reference, *it);
//}
} else {
output_tools_->AppendUnmappedRead(ri, reference, *it);
}
}
}
}
uint32_t Sigmap::MoveMappingsInBuffersToMappingContainer(
uint32_t num_reference_sequences,
std::vector<std::vector<std::vector<PAFMapping> > >
*mappings_on_diff_ref_seqs_for_diff_threads_for_saving) {
double real_start_time = GetRealTime();
uint32_t num_moved_mappings = 0;
for (int ti = 0; ti < num_threads_; ++ti) {
for (uint32_t i = 0; i < num_reference_sequences; ++i) {
num_moved_mappings +=
(*mappings_on_diff_ref_seqs_for_diff_threads_for_saving)[ti][i]
.size();
mappings_on_diff_ref_seqs_[i].insert(
mappings_on_diff_ref_seqs_[i].end(),
std::make_move_iterator(
(*mappings_on_diff_ref_seqs_for_diff_threads_for_saving)[ti][i]
.begin()),
std::make_move_iterator(
(*mappings_on_diff_ref_seqs_for_diff_threads_for_saving)[ti][i]
.end()));
(*mappings_on_diff_ref_seqs_for_diff_threads_for_saving)[ti][i].clear();
}
}
std::cerr << "Move mappings in " << GetRealTime() - real_start_time << "s.\n";
return num_moved_mappings;
}
void Sigmap::Map() {
// Load read signals
SignalBatch read_signal_batch;
read_signal_batch.InitializeLoading(signal_directory_);
size_t num_loaded_read_signals = read_signal_batch.LoadAllReadSignals();
// Load pore model
PoreModel pore_model;
pore_model.Load(pore_model_file_path_);
// Load reference genome
SequenceBatch reference_sequence_batch;
reference_sequence_batch.InitializeLoading(reference_file_path_);
uint32_t num_reference_sequences =
reference_sequence_batch.LoadAllSequences();
// Get reverse complement of each ref seq
for (size_t reference_sequence_index = 0;
reference_sequence_index < num_reference_sequences;
++reference_sequence_index) {
reference_sequence_batch.PrepareNegativeSequenceAt(
reference_sequence_index);
}
// Use pore model to convert reference sequence to signal
SignalBatch reference_signal_batch;
reference_signal_batch.ConvertSequencesToSignals(
reference_sequence_batch, pore_model, num_reference_sequences);
// Normalize reference signals
std::vector<std::vector<float> > positive_reference_feature_signals;
std::vector<std::vector<float> > negative_reference_feature_signals;
for (size_t reference_signal_index = 0;
reference_signal_index < num_reference_sequences;
++reference_signal_index) {
positive_reference_feature_signals.push_back(std::vector<float>());
negative_reference_feature_signals.push_back(std::vector<float>());
GenerateZscoreNormalizedSignal(
reference_signal_batch.GetSignalAt(reference_signal_index)
.signal_values.data(),
reference_signal_batch.GetSignalLengthAt(reference_signal_index),
positive_reference_feature_signals.back());
GenerateZscoreNormalizedSignal(
reference_signal_batch.GetSignalAt(reference_signal_index)
.negative_signal_values.data(),
reference_signal_batch.GetSignalLengthAt(reference_signal_index),
negative_reference_feature_signals.back());
}
// Load spatial index for reference signals
SpatialIndex reference_spatial_index(1000, std::vector<int>(1000, 5000),
reference_index_file_path_);
reference_spatial_index.Load();
mappings_on_diff_ref_seqs_.reserve(num_reference_sequences);
for (uint32_t i = 0; i < num_reference_sequences; ++i) {
mappings_on_diff_ref_seqs_.emplace_back(std::vector<PAFMapping>());
}
output_tools_ = std::unique_ptr<PAFOutputTools<PAFMapping> >(
new PAFOutputTools<PAFMapping>);
// std::vector<std::vector<PAFMapping> > &mappings;
std::vector<std::vector<std::vector<PAFMapping> > >
mappings_on_diff_ref_seqs_for_diff_threads;
mappings_on_diff_ref_seqs_for_diff_threads.reserve(num_threads_);
// mappings_on_diff_ref_seqs_for_diff_threads_for_saving.reserve(num_threads_);
for (int ti = 0; ti < num_threads_; ++ti) {
mappings_on_diff_ref_seqs_for_diff_threads.emplace_back(
std::vector<std::vector<PAFMapping> >(num_reference_sequences));
// mappings_on_diff_ref_seqs_for_diff_threads_for_saving.emplace_back(std::vector<std::vector<MappingRecord>
// >(num_reference_sequences));
for (uint32_t i = 0; i < num_reference_sequences; ++i) {
mappings_on_diff_ref_seqs_for_diff_threads[ti][i].reserve(
5000 / num_threads_ / num_reference_sequences);
// mappings_on_diff_ref_seqs_for_diff_threads[ti][i].reserve((num_loaded_pairs
// + num_loaded_pairs / 1000 * max_num_best_mappings_) / num_threads_ /
// num_reference_sequences);
// mappings_on_diff_ref_seqs_for_diff_threads_for_saving[ti][i].reserve((num_loaded_pairs
// + num_loaded_pairs / 1000 * max_num_best_mappings_) / num_threads_ /
// num_reference_sequences);
}
}
output_tools_->InitializeMappingOutput(output_file_path_);
// output_tools_->AppendMapping(last_rid, reference, last_mapping);
// Map each reads
double real_start_time = GetRealTime();
#pragma omp parallel default(none) shared( \
reference_sequence_batch, positive_reference_feature_signals, \
negative_reference_feature_signals, reference_spatial_index, \
read_signal_batch, std::cerr, num_loaded_read_signals, \
num_reference_sequences, mappings_on_diff_ref_seqs_for_diff_threads) \
num_threads(num_threads_)
{
std::vector<float> read_feature_signal;
std::vector<float> read_feature_signal_stdvs;
std::vector<Point> read_point_cloud;
std::vector<SignalAnchorChain> chains;
#pragma omp single
{
// int grain_size = num_loaded_read_signals / num_threads_ / 100;
// grain_size = grain_size > 0 ? grain_size : 1;
#pragma omp taskloop // grainsize(grain_size) //num_tasks(num_threads_* 50)
for (size_t read_signal_index = 0;
read_signal_index < num_loaded_read_signals; ++read_signal_index) {
double real_mapping_start_time = GetRealTime();
// std::cerr << "mapping read " << read_signal_index << ".\n";
read_feature_signal.clear();
read_feature_signal_stdvs.clear();
// read_signal_batch.MovingMedianSignalAt(read_signal_index, 8);
// read_signal_batch.NormalizeSignalAt(read_signal_index);
GenerateEvents(0,
read_signal_batch.GetSignalLengthAt(read_signal_index),
read_signal_batch.GetSignalAt(read_signal_index),
read_feature_signal, read_feature_signal_stdvs);
// if (read_feature_signal.size() > 2000) {
// read_feature_signal.erase(read_feature_signal.begin() + 2000,
// read_feature_signal.end());
//}
if (read_feature_signal.size() > 50) {
read_point_cloud.clear();
chains.clear();
// float search_radius = 0.08;
// float search_radius = 0.05;
int read_signal_point_cloud_step_size = 8;
// if (read_feature_signal.size() < 10000) {
// read_signal_point_cloud_step_size = 7;
//}
// if (read_feature_signal.size() < 8000) {
// read_signal_point_cloud_step_size = 5;
//}
// if (read_feature_signal.size() < 5000) {
// read_signal_point_cloud_step_size = 3;
//}
// if (read_feature_signal.size() < 2000) {
// read_signal_point_cloud_step_size = 1;
//}
read_signal_point_cloud_step_size = 1;
reference_spatial_index.GenerateChains(
read_feature_signal, read_feature_signal_stdvs, 0,
read_signal_point_cloud_step_size, search_radius_,
num_reference_sequences, chains);
// Save results in vector and output PAF
double mapping_time = GetRealTime() - real_mapping_start_time;
std::vector<std::vector<PAFMapping> > &mappings_on_diff_ref_seqs =
mappings_on_diff_ref_seqs_for_diff_threads[omp_get_thread_num()];
if (chains.size() > 0) {
float anchor_ref_gap_avg_length = 0;
float anchor_read_gap_avg_length = 0;
float average_anchor_distance = 0;
for (size_t ai = 0; ai < chains[0].anchors.size(); ++ai) {
average_anchor_distance += chains[0].anchors[ai].distance;
if (ai < chains[0].anchors.size() - 1) {
anchor_ref_gap_avg_length +=
chains[0].anchors[ai].target_position -
chains[0].anchors[ai + 1].target_position;
anchor_read_gap_avg_length +=
chains[0].anchors[ai].query_position -
chains[0].anchors[ai + 1].query_position;
}
// std::cerr << "(" << chains[i].anchors[ai].target_position <<
// "," << chains[i].anchors[ai].query_position << "," <<
// chains[i].anchors[ai].distance << "), ";
}
average_anchor_distance /= chains[0].num_anchors;
anchor_ref_gap_avg_length /= chains[0].num_anchors;
anchor_read_gap_avg_length /= chains[0].num_anchors;
std::string tags;
tags.append("mt:f:" + std::to_string(mapping_time * 1000));
tags.append("\tsl:i:" +
std::to_string(read_signal_batch.GetSignalLengthAt(
read_signal_index)));
tags.append("\tcm:i:" + std::to_string(chains[0].num_anchors));
tags.append("\ts1:f:" + std::to_string(chains[0].score));
tags.append("\ts2:f:" + std::to_string(chains.size() > 1
? chains[1].score
: 0));
tags.append("\tad:f:" + std::to_string(average_anchor_distance));
tags.append("\tat:f:" + std::to_string(anchor_ref_gap_avg_length));
tags.append("\taq:f:" + std::to_string(anchor_read_gap_avg_length));
mappings_on_diff_ref_seqs[chains[0].reference_sequence_index]
.emplace_back(PAFMapping{
(uint32_t)read_signal_index,
std::string(
read_signal_batch.GetSignalNameAt(read_signal_index)),
(uint32_t)read_feature_signal.size(),
chains[0].anchors.back().query_position,
chains[0].anchors[0].query_position,
chains[0].direction == Positive
? (uint32_t)chains[0].start_position
: (uint32_t)(reference_sequence_batch
.GetSequenceLengthAt(
chains[0]
.reference_sequence_index) +
1 - chains[0].end_position),
(uint32_t)(chains[0].end_position -
chains[0].start_position + 1),
chains[0].mapq,
chains[0].direction == Positive ? (uint8_t)1 : (uint8_t)0,
(uint8_t)1, tags});
// EmplaceBackMappingRecord(read_signal_index,
// read_signal_batch.GetSignalNameAt(read_signal_index),
// read_signal_batch.GetSignalLengthAt(read_signal_index),
// chains[0].direction == Positive ? 0 : 1, chains[0].direction ==
// Positive ? chains[0].start_position :
// reference_sequence_batch.GetSequenceLengthAt(chains[0].reference_sequence_index)
// + 1 - chains[0].end_position, chains[0].end_position -
// chains[0].start_position + 1, chains[0].mapq, chains[0].direction
// == Positive ? 1 : 0, 1,
// &(mappings_on_diff_ref_seqs[chains[0].reference_sequence_index]));
#ifdef DEBUG
// if (chains[0].direction == Positive) {
// std::cerr << "Direction: positive.\n";
//} else {
// std::cerr << "Direction: negative.\n";
//}
// std::cerr << "Best chaining score: " << chains[0].score << ",
// signal_index: " << chains[0].reference_sequence_index << ",
// anchor target start postion: " << chains[0].start_position << ",
// anchor target end postion: " << chains[0].end_position << ", #
// anchors: "
// << chains[0].num_anchors << ", mapq: " << (int)chains[0].mapq <<
// ".\n";
for (size_t i = 0; i < chains.size(); ++i) {
if (chains[i].direction == Positive) {
std::cerr << i << " best chaining score: " << chains[i].score
<< ", direction: +"
<< ", reference name: "
<< reference_sequence_batch.GetSequenceNameAt(
chains[i].reference_sequence_index)
<< ", anchor target start postion: "
<< chains[i].start_position
<< ", anchor target end postion: "
<< chains[i].end_position
<< ", # anchors: " << chains[i].num_anchors
<< ", mapq: " << (int)chains[i].mapq << ".\n";
for (size_t ai = 0; ai < chains[i].anchors.size(); ++ai) {
std::cerr << "(" << chains[i].anchors[ai].target_position
<< "," << chains[i].anchors[ai].query_position
<< "," << chains[i].anchors[ai].distance << "), ";
}
} else {
std::cerr << i << " best chaining score: " << chains[i].score
<< ", direction: -"
<< ", reference name: "
<< reference_sequence_batch.GetSequenceNameAt(
chains[i].reference_sequence_index)
<< ", anchor target start postion: "
<< reference_sequence_batch.GetSequenceLengthAt(
chains[i].reference_sequence_index) +
1 - chains[i].end_position
<< ", anchor target end postion: "
<< reference_sequence_batch.GetSequenceLengthAt(
chains[i].reference_sequence_index) -
chains[i].start_position
<< ", # anchors: " << chains[i].num_anchors
<< ", mapq: " << (int)chains[i].mapq << ".\n";
for (size_t ai = 0; ai < chains[i].anchors.size(); ++ai) {
std::cerr << "(" << chains[i].anchors[ai].target_position
<< "," << chains[i].anchors[ai].query_position
<< "," << chains[i].anchors[ai].distance << "), ";
}
}
std::cerr << "\n";
std::cerr << "\n";
}
std::cerr << "Read name: "
<< read_signal_batch.GetSignalNameAt(read_signal_index)
<< ", length: " << read_feature_signal.size()
<< ", reference name: "
<< reference_sequence_batch.GetSequenceNameAt(
chains[0].reference_sequence_index)
<< ", length: "
<< positive_reference_feature_signals
[chains[0].reference_sequence_index]
.size()
<< "\n";
std::cerr << "\n";
#endif
} else {
std::string tags;
tags.append("mt:f:" + std::to_string(mapping_time * 1000));
tags.append("\tsl:i:" +
std::to_string(read_signal_batch.GetSignalLengthAt(
read_signal_index)));
tags.append("\tcm:i:" + std::to_string(0));
tags.append("\ts1:f:" + std::to_string(0));
tags.append("\ts2:f:" + std::to_string(0));
mappings_on_diff_ref_seqs[0].emplace_back(PAFMapping{
(uint32_t)read_signal_index,
std::string(
read_signal_batch.GetSignalNameAt(read_signal_index)),
(uint32_t)read_feature_signal.size(), 0, 0, 0, 0, 61,
(uint8_t)0, (uint8_t)1, tags});
}
}
}
} // end of openmp single
} // end of openmp parallel
std::cerr << "Finished mapping in " << GetRealTime() - real_start_time
<< ", # reads: " << num_loaded_read_signals << "\n";
MoveMappingsInBuffersToMappingContainer(
num_reference_sequences, &mappings_on_diff_ref_seqs_for_diff_threads);
OutputMappingsInVector(0, num_reference_sequences, reference_sequence_batch,
mappings_on_diff_ref_seqs_);
output_tools_->FinalizeMappingOutput();
read_signal_batch.FinalizeLoading();
reference_sequence_batch.FinalizeLoading();
reference_signal_batch.FinalizeLoading();
}
void Sigmap::StreamingMap() {
// Load read signals
SignalBatch read_signal_batch;
read_signal_batch.InitializeLoading(signal_directory_);
size_t num_loaded_read_signals = read_signal_batch.LoadAllReadSignals();
// Load pore model
PoreModel pore_model;
pore_model.Load(pore_model_file_path_);
// Load reference genome
SequenceBatch reference_sequence_batch;
reference_sequence_batch.InitializeLoading(reference_file_path_);
uint32_t num_reference_sequences =
reference_sequence_batch.LoadAllSequences();
// Get reverse complement of each ref seq
for (size_t reference_sequence_index = 0;
reference_sequence_index < num_reference_sequences;
++reference_sequence_index) {
reference_sequence_batch.PrepareNegativeSequenceAt(
reference_sequence_index);
}
// Use pore model to convert reference sequence to signal
SignalBatch reference_signal_batch;
reference_signal_batch.ConvertSequencesToSignals(
reference_sequence_batch, pore_model, num_reference_sequences);
// Normalize reference signals
std::vector<std::vector<float> > positive_reference_feature_signals;
std::vector<std::vector<float> > negative_reference_feature_signals;
for (size_t reference_signal_index = 0;
reference_signal_index < num_reference_sequences;
++reference_signal_index) {
positive_reference_feature_signals.push_back(std::vector<float>());
negative_reference_feature_signals.push_back(std::vector<float>());
GenerateZscoreNormalizedSignal(
reference_signal_batch.GetSignalAt(reference_signal_index)
.signal_values.data(),
reference_signal_batch.GetSignalLengthAt(reference_signal_index),
positive_reference_feature_signals.back());
GenerateZscoreNormalizedSignal(
reference_signal_batch.GetSignalAt(reference_signal_index)
.negative_signal_values.data(),
reference_signal_batch.GetSignalLengthAt(reference_signal_index),
negative_reference_feature_signals.back());
}
// Load spatial index for reference signals
SpatialIndex reference_spatial_index(1000, std::vector<int>(1000, 5000),
reference_index_file_path_);
reference_spatial_index.Load();
mappings_on_diff_ref_seqs_.reserve(num_reference_sequences);
for (uint32_t i = 0; i < num_reference_sequences; ++i) {
mappings_on_diff_ref_seqs_.emplace_back(std::vector<PAFMapping>());
}
output_tools_ = std::unique_ptr<PAFOutputTools<PAFMapping> >(
new PAFOutputTools<PAFMapping>);
std::vector<std::vector<std::vector<PAFMapping> > >
mappings_on_diff_ref_seqs_for_diff_threads;
mappings_on_diff_ref_seqs_for_diff_threads.reserve(num_threads_);
for (int ti = 0; ti < num_threads_; ++ti) {
mappings_on_diff_ref_seqs_for_diff_threads.emplace_back(
std::vector<std::vector<PAFMapping> >(num_reference_sequences));
for (uint32_t i = 0; i < num_reference_sequences; ++i) {
mappings_on_diff_ref_seqs_for_diff_threads[ti][i].reserve(
5000 / num_threads_ / num_reference_sequences);
}
}
output_tools_->InitializeMappingOutput(output_file_path_);
// Map each reads
double real_start_time = GetRealTime();
#pragma omp parallel default(none) shared( \
reference_sequence_batch, positive_reference_feature_signals, \
negative_reference_feature_signals, reference_spatial_index, \
read_signal_batch, std::cerr, num_loaded_read_signals, \
num_reference_sequences, mappings_on_diff_ref_seqs_for_diff_threads) \
num_threads(num_threads_)
{
std::vector<float> read_feature_signal;
std::vector<float> read_feature_signal_stdvs;
std::vector<SignalAnchorChain> chains;
#pragma omp single
{
#pragma omp taskloop
for (size_t read_signal_index = 0;
read_signal_index < num_loaded_read_signals; ++read_signal_index) {
double real_mapping_start_time = GetRealTime();
// std::cerr << "mapping read " << read_signal_index << ".\n";
// read_signal_batch.MovingMedianSignalAt(read_signal_index, 8);
// read_signal_batch.NormalizeSignalAt(read_signal_index);
uint32_t bp_per_sec = 450;
uint32_t sample_rate = 4000;
uint32_t chunk_size = 4000;
// uint32_t max_num_chunks = 60;
size_t signal_length =
read_signal_batch.GetSignalLengthAt(read_signal_index);
size_t num_chunks = signal_length / chunk_size;
chains.clear();
uint32_t num_events = 0;
uint32_t chunk_index = 0;
for (chunk_index = 0; chunk_index < num_chunks &&
chunk_index < (uint32_t)max_num_chunks_;
++chunk_index) {
read_feature_signal.clear();
read_feature_signal_stdvs.clear();
size_t signal_start = chunk_size * chunk_index;
size_t signal_end = chunk_size * (chunk_index + 1);
if (signal_end > signal_length) {
signal_end = signal_length;
}
GenerateEvents(signal_start, signal_end,
read_signal_batch.GetSignalAt(read_signal_index),
read_feature_signal, read_feature_signal_stdvs);
if (read_feature_signal.size() > 50) {
// float search_radius = 0.08;
reference_spatial_index.GenerateChains(
read_feature_signal, read_feature_signal_stdvs, num_events,
read_seeding_step_size_, search_radius_,
num_reference_sequences, chains);
num_events += read_feature_signal.size();
if (chains.size() >= 2) {
if (chains[0].score / chains[1].score >= stop_mapping_ratio_) {
break;
}
float mean_chain_score = 0;
for (uint32_t chain_index = 0; chain_index < chains.size();
++chain_index) {
mean_chain_score += chains[chain_index].score;
}
mean_chain_score /= chains.size();
if (chains[0].score >=
stop_mapping_mean_ratio_ * mean_chain_score) {
break;
}
} else if (chains.size() == 1 &&
chains[0].num_anchors >=
(uint32_t)stop_mapping_min_num_anchors_) {
if (chunk_index >= 0) {
break;
}
}
}
}
if (chunk_index > 0 && (chunk_index == num_chunks ||
chunk_index == (uint32_t)max_num_chunks_)) {
--chunk_index;
}
float read_position_scale =
((float)(chunk_index + 1) * chunk_size / num_events) /
((float)sample_rate / bp_per_sec);
// Save results in vector and output PAF
double mapping_time = GetRealTime() - real_mapping_start_time;
std::vector<std::vector<PAFMapping> > &mappings_on_diff_ref_seqs =
mappings_on_diff_ref_seqs_for_diff_threads[omp_get_thread_num()];
float mean_chain_score = 0;
for (uint32_t chain_index = 0; chain_index < chains.size();
++chain_index) {
mean_chain_score += chains[chain_index].score;
}
mean_chain_score /= chains.size();
if ((chains.size() >= 2 &&
(chains[0].score / chains[1].score >= output_mapping_ratio_ ||
chains[0].score >=
output_mapping_mean_ratio_ * mean_chain_score)) ||
(chains.size() == 1 &&
chains[0].num_anchors >=
(uint32_t)output_mapping_min_num_anchors_)) {
float anchor_ref_gap_avg_length = 0;
float anchor_read_gap_avg_length = 0;
float average_anchor_distance = 0;
for (size_t ai = 0; ai < chains[0].anchors.size(); ++ai) {
average_anchor_distance += chains[0].anchors[ai].distance;
if (ai < chains[0].anchors.size() - 1) {
anchor_ref_gap_avg_length +=
chains[0].anchors[ai].target_position -
chains[0].anchors[ai + 1].target_position;
anchor_read_gap_avg_length +=
chains[0].anchors[ai].query_position -
chains[0].anchors[ai + 1].query_position;
}
}
average_anchor_distance /= chains[0].num_anchors;
anchor_ref_gap_avg_length /= chains[0].num_anchors;
anchor_read_gap_avg_length /= chains[0].num_anchors;
std::string tags;
tags.append("mt:f:" + std::to_string(mapping_time * 1000));
tags.append("\tci:i:" + std::to_string(chunk_index + 1));
tags.append("\tsl:i:" +
std::to_string(read_signal_batch.GetSignalLengthAt(
read_signal_index)));
tags.append("\tcm:i:" + std::to_string(chains[0].num_anchors));
tags.append("\tnc:i:" + std::to_string(chains.size()));
tags.append("\ts1:f:" + std::to_string(chains[0].score));
tags.append("\ts2:f:" +
std::to_string(chains.size() > 1 ? chains[1].score : 0));
tags.append("\tsm:f:" + std::to_string(mean_chain_score));
tags.append("\tad:f:" + std::to_string(average_anchor_distance));
tags.append("\tat:f:" + std::to_string(anchor_ref_gap_avg_length));
tags.append("\taq:f:" + std::to_string(anchor_read_gap_avg_length));
mappings_on_diff_ref_seqs[chains[0].reference_sequence_index]
.emplace_back(PAFMapping{
(uint32_t)read_signal_index,
std::string(
read_signal_batch.GetSignalNameAt(read_signal_index)),
(uint32_t)read_signal_batch.GetSignalLengthAt(
read_signal_index),
(uint32_t)(read_position_scale *
chains[0].anchors.back().query_position),
(uint32_t)(read_position_scale *
chains[0].anchors[0].query_position),
chains[0].direction == Positive
? (uint32_t)chains[0].start_position
: (uint32_t)(reference_sequence_batch.GetSequenceLengthAt(
chains[0].reference_sequence_index) +
1 - chains[0].end_position),
(uint32_t)(chains[0].end_position - chains[0].start_position +
1),
chains[0].mapq,
chains[0].direction == Positive ? (uint8_t)1 : (uint8_t)0,
(uint8_t)1, tags});
#ifdef DEBUG
for (size_t i = 0; i < chains.size(); ++i) {
if (chains[i].direction == Positive) {
std::cerr << i << " best chaining score: " << chains[i].score
<< ", direction: +"
<< ", reference name: "
<< reference_sequence_batch.GetSequenceNameAt(
chains[i].reference_sequence_index)
<< ", anchor target start postion: "
<< chains[i].start_position
<< ", anchor target end postion: "
<< chains[i].end_position
<< ", # anchors: " << chains[i].num_anchors
<< ", mapq: " << (int)chains[i].mapq << ".\n";
for (size_t ai = 0; ai < chains[i].anchors.size(); ++ai) {
std::cerr << "(" << chains[i].anchors[ai].target_position << ","
<< chains[i].anchors[ai].query_position << ","
<< chains[i].anchors[ai].distance << "), ";
}
} else {
std::cerr << i << " best chaining score: " << chains[i].score
<< ", direction: -"
<< ", reference name: "
<< reference_sequence_batch.GetSequenceNameAt(
chains[i].reference_sequence_index)
<< ", anchor target start postion: "
<< reference_sequence_batch.GetSequenceLengthAt(
chains[i].reference_sequence_index) +
1 - chains[i].end_position
<< ", anchor target end postion: "
<< reference_sequence_batch.GetSequenceLengthAt(
chains[i].reference_sequence_index) -
chains[i].start_position
<< ", # anchors: " << chains[i].num_anchors
<< ", mapq: " << (int)chains[i].mapq << ".\n";
for (size_t ai = 0; ai < chains[i].anchors.size(); ++ai) {
std::cerr << "(" << chains[i].anchors[ai].target_position << ","
<< chains[i].anchors[ai].query_position << ","
<< chains[i].anchors[ai].distance << "), ";
}
}
std::cerr << "\n";
std::cerr << "\n";
}
std::cerr << "Read name: "
<< read_signal_batch.GetSignalNameAt(read_signal_index)
<< ", length: " << read_feature_signal.size()
<< ", reference name: "
<< reference_sequence_batch.GetSequenceNameAt(
chains[0].reference_sequence_index)
<< ", length: "
<< positive_reference_feature_signals
[chains[0].reference_sequence_index]
.size()
<< "\n";
std::cerr << "\n";
#endif
} else {
std::string tags;
tags.append("mt:f:" + std::to_string(mapping_time * 1000));
tags.append("\tci:i:" + std::to_string(chunk_index + 1));
tags.append("\tsl:i:" +
std::to_string(read_signal_batch.GetSignalLengthAt(
read_signal_index)));
if (chains.size() >= 1) {
float anchor_ref_gap_avg_length = 0;
float anchor_read_gap_avg_length = 0;
float average_anchor_distance = 0;
for (size_t ai = 0; ai < chains[0].anchors.size(); ++ai) {
average_anchor_distance += chains[0].anchors[ai].distance;
if (ai < chains[0].anchors.size() - 1) {
anchor_ref_gap_avg_length +=
chains[0].anchors[ai].target_position -
chains[0].anchors[ai + 1].target_position;
anchor_read_gap_avg_length +=
chains[0].anchors[ai].query_position -
chains[0].anchors[ai + 1].query_position;
}
}
average_anchor_distance /= chains[0].num_anchors;
anchor_ref_gap_avg_length /= chains[0].num_anchors;
anchor_read_gap_avg_length /= chains[0].num_anchors;
tags.append("\tcm:i:" + std::to_string(chains[0].num_anchors));
tags.append("\tnc:i:" + std::to_string(chains.size()));
tags.append("\ts1:f:" + std::to_string(chains[0].score));
tags.append("\ts2:f:" + std::to_string(chains.size() > 1
? chains[1].score
: 0));
tags.append("\tsm:f:" + std::to_string(mean_chain_score));
tags.append("\tad:f:" + std::to_string(average_anchor_distance));
tags.append("\tat:f:" + std::to_string(anchor_ref_gap_avg_length));
tags.append("\taq:f:" + std::to_string(anchor_read_gap_avg_length));
}
mappings_on_diff_ref_seqs[0].emplace_back(PAFMapping{
(uint32_t)read_signal_index,
std::string(read_signal_batch.GetSignalNameAt(read_signal_index)),
(uint32_t)read_signal_batch.GetSignalLengthAt(read_signal_index),
0, 0, 0, 0, 61, (uint8_t)0, (uint8_t)1, tags});
}
} // end of task loop
} // end of openmp single
} // end of openmp parallel
std::cerr << "Finished mapping in " << GetRealTime() - real_start_time
<< ", # reads: " << num_loaded_read_signals << "\n";
MoveMappingsInBuffersToMappingContainer(
num_reference_sequences, &mappings_on_diff_ref_seqs_for_diff_threads);
OutputMappingsInVector(0, num_reference_sequences, reference_sequence_batch,
mappings_on_diff_ref_seqs_);
output_tools_->FinalizeMappingOutput();
read_signal_batch.FinalizeLoading();
reference_sequence_batch.FinalizeLoading();
reference_signal_batch.FinalizeLoading();
}
void Sigmap::DTWAlign() {
SignalBatch read_signal_batch;
read_signal_batch.InitializeLoading(signal_directory_);
size_t num_loaded_read_signals = read_signal_batch.LoadAllReadSignals();
double real_normalization_start_time = GetRealTime();
for (size_t read_index = 0; read_index < num_loaded_read_signals;
++read_index) {
read_signal_batch.NormalizeSignalAt(read_index);
}
std::cerr << "Normalize " << num_loaded_read_signals << " read signals in "
<< GetRealTime() - real_normalization_start_time << "s.\n";
PoreModel pore_model;
pore_model.Load(pore_model_file_path_);
SequenceBatch reference;
reference.InitializeLoading(reference_file_path_);
uint32_t num_reference_sequences = reference.LoadAllSequences();
SignalBatch reference_signal_batch;
reference_signal_batch.ConvertSequencesToSignals(reference, pore_model,
num_reference_sequences);
real_normalization_start_time = GetRealTime();
for (size_t reference_signal_index = 0;
reference_signal_index < num_reference_sequences;
++reference_signal_index) {
reference_signal_batch.NormalizeSignalAt(reference_signal_index);
}
std::cerr << "Normalize " << num_reference_sequences
<< " reference signals in "
<< GetRealTime() - real_normalization_start_time << "s.\n";
double real_start_time = GetRealTime();
for (size_t read_signal_index = 0;
read_signal_index < num_loaded_read_signals; ++read_signal_index) {
for (size_t reference_signal_index = 0;
reference_signal_index < num_reference_sequences;
++reference_signal_index) {
std::cerr << "Read name: "
<< read_signal_batch.GetSignalNameAt(read_signal_index)
<< ", reference name: "
<< reference.GetSequenceNameAt(reference_signal_index) << "\n";
sDTW(reference_signal_batch.GetSignalAt(reference_signal_index),
read_signal_batch.GetSignalAt(read_signal_index));
}
std::cerr << num_loaded_read_signals << "\n";
}
std::cerr << "Finished mapping in " << GetRealTime() - real_start_time
<< ", # reads: " << num_loaded_read_signals << "\n";
read_signal_batch.FinalizeLoading();
reference.FinalizeLoading();
reference_signal_batch.FinalizeLoading();
}
void Sigmap::CWTAlign() {
SignalBatch read_signal_batch;
read_signal_batch.InitializeLoading(signal_directory_);
size_t num_loaded_read_signals = read_signal_batch.LoadAllReadSignals();
PoreModel pore_model;
pore_model.Load(pore_model_file_path_);
SequenceBatch reference_sequence_batch;
reference_sequence_batch.InitializeLoading(reference_file_path_);
uint32_t num_reference_sequences =
reference_sequence_batch.LoadAllSequences();
SignalBatch reference_signal_batch;
reference_signal_batch.ConvertSequencesToSignals(
reference_sequence_batch, pore_model, num_reference_sequences);
std::vector<std::vector<float> > reference_feature_signals;
std::vector<std::vector<size_t> > reference_feature_positions;
float cwt_scale0 = 1;
for (size_t reference_signal_index = 0;
reference_signal_index < num_reference_sequences;
++reference_signal_index) {
reference_feature_signals.push_back(std::vector<float>());
reference_feature_positions.push_back(std::vector<size_t>());
GenerateFeatureSignalUsingCWT(
reference_signal_batch.GetSignalAt(reference_signal_index), cwt_scale0,
reference_feature_signals.back(), reference_feature_positions.back());
}
double real_start_time = GetRealTime();
std::vector<float> read_feature_signal;
std::vector<size_t> read_feature_positions;
for (size_t read_signal_index = 0;
read_signal_index < num_loaded_read_signals; ++read_signal_index) {
read_feature_signal.clear();
read_feature_positions.clear();
ssize_t feature_mapping_end_position = -1;
GenerateFeatureSignalUsingCWT(
read_signal_batch.GetSignalAt(read_signal_index), 8 * cwt_scale0,
read_feature_signal, read_feature_positions);
for (size_t reference_signal_index = 0;
reference_signal_index < num_reference_sequences;
++reference_signal_index) {
std::cerr << "Read name: "
<< read_signal_batch.GetSignalNameAt(read_signal_index)
<< ", reference name: "
<< reference_sequence_batch.GetSequenceNameAt(
reference_signal_index)
<< "\n";
float dtw_distance =
sDTW(reference_feature_signals[reference_signal_index].data(),
reference_feature_signals[reference_signal_index].size(),
read_feature_signal.data(), read_feature_signal.size(),
feature_mapping_end_position);
std::cerr << "DTW distance: " << dtw_distance
<< ", feature_mapping_end_position: "
<< feature_mapping_end_position
<< ", rough mapping end postion: "
<< reference_feature_positions[reference_signal_index]
[feature_mapping_end_position]
<< ".\n";
}
std::cerr << "\n";
}
std::cerr << "Finished mapping in " << GetRealTime() - real_start_time
<< "s, # reads: " << num_loaded_read_signals << "\n";
read_signal_batch.FinalizeLoading();
reference_sequence_batch.FinalizeLoading();
reference_signal_batch.FinalizeLoading();
}
void Sigmap::ConstructIndex() {
PoreModel pore_model;
pore_model.Load(pore_model_file_path_);
SequenceBatch reference_sequence_batch;
reference_sequence_batch.InitializeLoading(reference_file_path_);
uint32_t num_reference_sequences =
reference_sequence_batch.LoadAllSequences();
for (size_t reference_sequence_index = 0;
reference_sequence_index < num_reference_sequences;
++reference_sequence_index) {
reference_sequence_batch.PrepareNegativeSequenceAt(
reference_sequence_index);
}
std::vector<std::vector<bool> > positive_is_masked;
std::vector<std::vector<bool> > negative_is_masked;
GenerateMaskedPositions(dimension_ + pore_model.GetKmerSize() - 1, 0.0002,
num_reference_sequences, reference_sequence_batch,
positive_is_masked, negative_is_masked);
SignalBatch reference_signal_batch;
reference_signal_batch.ConvertSequencesToSignals(
reference_sequence_batch, pore_model, num_reference_sequences);
std::vector<std::vector<float> > positive_reference_feature_signals;
std::vector<std::vector<float> > negative_reference_feature_signals;
for (size_t reference_signal_index = 0;
reference_signal_index < num_reference_sequences;
++reference_signal_index) {
positive_reference_feature_signals.push_back(std::vector<float>());
negative_reference_feature_signals.push_back(std::vector<float>());
GenerateZscoreNormalizedSignal(
reference_signal_batch.GetSignalAt(reference_signal_index)
.signal_values.data(),
reference_signal_batch.GetSignalLengthAt(reference_signal_index),
positive_reference_feature_signals.back());
GenerateZscoreNormalizedSignal(
reference_signal_batch.GetSignalAt(reference_signal_index)
.negative_signal_values.data(),
reference_signal_batch.GetSignalLengthAt(reference_signal_index),
negative_reference_feature_signals.back());
}
SpatialIndex spatial_index(dimension_, max_leaf_, 1, output_file_path_);
spatial_index.Construct(positive_reference_feature_signals.size(),
positive_is_masked, negative_is_masked,
positive_reference_feature_signals,
negative_reference_feature_signals);
spatial_index.Save();
reference_signal_batch.FinalizeLoading();
// yak_ch_destroy(h);
}
void Sigmap::GenerateEvents(size_t start, size_t end, const Signal &signal,
std::vector<float> &feature_signal,
std::vector<float> &feature_signal_stdvs) {
assert(start >= 0);
assert(start < end);
assert(end <= signal.GetSignalLength());
size_t signal_length = end - start;
std::vector<float> buffer;
std::vector<Event> events;
std::vector<float> prefix_sum;
std::vector<float> prefix_sum_square;
std::vector<float> tstat1;
std::vector<float> tstat2;
std::vector<size_t> peaks;
const DetectorArgs ed_params = event_detection_defaults;
DetectEvents(signal.signal_values.data() + start, signal_length, ed_params,
prefix_sum, prefix_sum_square, tstat1, tstat2, peaks, events);
feature_signal.clear();
for (size_t ei = 0; ei < events.size(); ++ei) {
feature_signal.emplace_back(events[ei].mean);
}
// feature_signal.swap(buffer);
GenerateZscoreNormalizedSignal(feature_signal.data(), feature_signal.size(),
buffer);
feature_signal.clear();
for (size_t i = 0; i < buffer.size(); i += 1) {
// feature_signal.emplace_back(buffer[i]);
if (i == 0 || (i >= 1 && (abs(buffer[i] - feature_signal.back()) > 0.1))) {
feature_signal.emplace_back(buffer[i]);
feature_signal_stdvs.emplace_back(events[i].stdv);
}
}
#ifdef DEBUG
std::cerr << "After compression: " << feature_signal.size() << "\n";
#endif
}
void Sigmap::GenerateFeatureSignalUsingCWT(
const Signal &signal, float scale0, std::vector<float> &feature_signal,
std::vector<size_t> &feature_positions) {
std::vector<float> buffer;
GenerateMADNormalizedSignal(signal.signal_values.data(),
signal.GetSignalLength(), buffer);
GenerateCWTSignal(buffer.data(), buffer.size(), scale0, feature_signal);
buffer.clear();
float mean = GenerateZscoreNormalizedSignal(feature_signal.data(),
feature_signal.size(), buffer);
feature_signal.clear();
GeneratePeaks(buffer.data(), buffer.size(), mean / 4, feature_signal,
feature_positions);
}
float Sigmap::GenerateMADNormalizedSignal(
const float *signal_values, size_t signal_length,
std::vector<float> &normalized_signal) {
// Should use a linear algorithm like median of medians
// One such better algorithm can be found here:
// https://rcoh.me/posts/linear-time-median-finding/ But for now let us use
// sort
normalized_signal.assign(signal_values, signal_values + signal_length);
std::nth_element(normalized_signal.begin(),
normalized_signal.begin() + signal_length / 2,
normalized_signal.end());
float signal_median =
normalized_signal[signal_length /
2]; // This is a fake median, but should be okay for a
// quick implementation
for (size_t i = 0; i < signal_length; ++i) {
normalized_signal[i] = std::abs(normalized_signal[i] - signal_median);
}
std::nth_element(normalized_signal.begin(),
normalized_signal.begin() + signal_length / 2,
normalized_signal.end());
float MAD =
normalized_signal[signal_length /
2]; // Again, fake MAD, ok for a quick implementation
// Now we can normalize signal
for (size_t i = 0; i < signal_length; ++i) {
normalized_signal[i] = (signal_values[i] - signal_median) / MAD;
}
return MAD;
}
float Sigmap::GenerateZscoreNormalizedSignal(
const float *signal_values, size_t signal_length,
std::vector<float> &normalized_signal) {
// Calculate mean
double mean = 0;
for (size_t i = 0; i < signal_length; ++i) {
mean += signal_values[i];
}
mean /= signal_length;
// Calculate standard deviation
double SD = 0;
for (size_t i = 0; i < signal_length; ++i) {
SD += (signal_values[i] - mean) * (signal_values[i] - mean);
}
SD /= (signal_length - 1);
SD = sqrt(SD);
#ifdef DEBUG
std::cerr << "mean: " << mean << ", stdv: " << SD << "\n";
#endif
// Now we can normalize signal
for (size_t i = 0; i < signal_length; ++i) {
normalized_signal.emplace_back((signal_values[i] - mean) / SD);
}
return SD;
}
void Sigmap::GenerateCWTSignal(const float *signal_values, size_t signal_length,
float scale0, std::vector<float> &cwt_signal) {
char wave[] = "dog";
char type[] = "pow";
double param = 2.0;
double dt = 1;
double dj = 1; // Separation bewteen scales.
int J = 1;
int N = signal_length;
cwt_object wt = cwt_init(wave, param, N, dt, J);
setCWTScales(wt, scale0, dj, type, 2.0);
cwt(wt, signal_values);
for (size_t i = 0; i < signal_length; ++i) {
cwt_signal.push_back(wt->output[i].re);
}
// cwt_summary(wt);
cwt_free(wt);
}
void Sigmap::GeneratePeaks(const float *signal_values, size_t signal_length,
float selective, std::vector<float> &peaks,
std::vector<size_t> &peak_positions) {
float previous_valley = signal_values[0];
float previous_peak = signal_values[0];
for (size_t i = 1; i < signal_length - 1; ++i) {
if (signal_values[i] > signal_values[i - 1] &&
signal_values[i] >= signal_values[i + 1] &&
signal_values[i] >= previous_valley + selective) {
peaks.push_back(signal_values[i]);
peak_positions.push_back(i);
previous_peak = signal_values[i];
} else if (signal_values[i] < signal_values[i - 1] &&
signal_values[i] <= signal_values[i + 1] &&
signal_values[i] <= previous_peak - selective) {
peaks.push_back(signal_values[i]);
peak_positions.push_back(i);
previous_valley = signal_values[i];
}
}
}
void Sigmap::EventsToText() {
SignalBatch read_signal_batch;
read_signal_batch.InitializeLoading(signal_directory_);
size_t num_loaded_read_signals = read_signal_batch.LoadAllReadSignals();
std::vector<Event> events;
const DetectorArgs ed_params = event_detection_defaults;
FILE *output_file = fopen((output_file_path_ + "_event").c_str(), "w");
assert(output_file != NULL);
for (size_t i = 0; i < num_loaded_read_signals; ++i) {
std::vector<float> prefix_sum;
std::vector<float> prefix_sum_square;
std::vector<float> tstat1;
std::vector<float> tstat2;
std::vector<size_t> peaks;
const Signal &read_signal = read_signal_batch.GetSignalAt(i);
events.clear();
DetectEvents(read_signal.signal_values.data(),
read_signal.GetSignalLength(), ed_params, prefix_sum,
prefix_sum_square, tstat1, tstat2, peaks, events);
std::vector<float> buffer;
std::vector<float> normalized_events;
for (size_t ei = 0; ei < events.size(); ++ei) {
buffer.emplace_back(events[ei].mean);
}
// GenerateMADNormalizedSignal(buffer.data(), buffer.size(),
// normalized_events);
GenerateZscoreNormalizedSignal(buffer.data(), buffer.size(),
normalized_events);
// fprintf(output_file, "%s\t", read_signal.name);
for (size_t ei = 0; ei < events.size(); ++ei) {
fprintf(output_file, "%f\n", normalized_events[ei]);
}
// fprintf(output_file, "%f\n", normalized_events[events.size() - 1]);
}
fclose(output_file);
read_signal_batch.FinalizeLoading();
}
void Sigmap::FAST5ToText() {
SignalBatch read_signal_batch;
read_signal_batch.InitializeLoading(signal_directory_);
size_t num_loaded_read_signals = read_signal_batch.LoadAllReadSignals();
FILE *output_file = fopen((output_file_path_ + "_fast5").c_str(), "w");
assert(output_file != NULL);
for (size_t i = 0; i < num_loaded_read_signals; ++i) {
const Signal &read_signal = read_signal_batch.GetSignalAt(i);
// fprintf(output_file, "%s\t", read_signal.name);
for (size_t signal_position = 0;
signal_position < read_signal.signal_values.size() - 1;
++signal_position) {
// fprintf(output_file, "%f\t",
// read_signal.signal_values[signal_position]);
fprintf(output_file, "%f\n", read_signal.signal_values[signal_position]);
}
fprintf(output_file, "%f\n",
read_signal.signal_values[read_signal.signal_values.size() - 1]);
}
fclose(output_file);
read_signal_batch.FinalizeLoading();
}
float Sigmap::sDTW(const float *target_signal_values, size_t target_length,
const float *query_signal_values, size_t query_length,
ssize_t &mapping_end_position) {
double real_start_time = GetRealTime();
float min_dtw_distance = std::numeric_limits<float>::max();
mapping_end_position = -1;
std::vector<float> previous_row(query_length + 1,
std::numeric_limits<float>::max());
previous_row[0] = 0;
std::vector<float> current_row(query_length + 1);
for (size_t target_position = 1; target_position <= target_length;
++target_position) {
current_row[0] = 0;
for (size_t query_position = 1; query_position <= query_length;
++query_position) {
float cost = std::abs(target_signal_values[target_position - 1] -
query_signal_values[query_position - 1]);
current_row[query_position] =
cost + std::min({previous_row[query_position - 1],
previous_row[query_position],
current_row[query_position - 1]});
}
if (current_row[query_length] < min_dtw_distance) {
min_dtw_distance = current_row[query_length];
mapping_end_position = target_position;
}
current_row.swap(previous_row);
}
std::cerr << "Finished sDTW in " << GetRealTime() - real_start_time
<< ", target length: " << target_length
<< ", query length: " << query_length << "\n";
return min_dtw_distance;
}
float Sigmap::sDTW(const Signal &target_signal, const Signal &query_signal) {
double real_start_time = GetRealTime();
size_t query_length = query_signal.GetSignalLength();
size_t target_length = target_signal.GetSignalLength();
float min_cost = std::numeric_limits<float>::max();
size_t mapping_end_position = 0;
std::vector<float> previous_row(query_length + 1,
std::numeric_limits<float>::max());
previous_row[0] = 0;
std::vector<float> current_row(query_length + 1);
for (size_t target_position = 1; target_position <= target_length;
++target_position) {
current_row[0] = 0;
for (size_t query_position = 1; query_position <= query_length;
++query_position) {
float cost = std::abs(target_signal.signal_values[target_position - 1] -
query_signal.signal_values[query_position - 1]);
current_row[query_position] =
cost + std::min({previous_row[query_position - 1],
previous_row[query_position],
current_row[query_position - 1]});
}
if (current_row[query_length] < min_cost) {
min_cost = current_row[query_length];
mapping_end_position = target_position;
}
current_row.swap(previous_row);
}
std::cerr << "Finished sDTW in " << GetRealTime() - real_start_time
<< ", target length: " << target_length
<< ", query length: " << query_length << "\n";
std::cerr << "DTW distance: " << min_cost
<< ", mapping_end_position: " << mapping_end_position << ".\n";
return min_cost;
}
void SigmapDriver::ParseArgsAndRun(int argc, char *argv[]) {
cxxopts::Options options("sigmap", "Map ONT raw signal data");
options.add_options("Indexing")("i,build-index",
"Build spatial index for reference")(
"d,dimension", "Dimension of spatial index [6]", cxxopts::value<int>(),
"INT")("l,max-leaf", "Max leaf of spatial index [20]",
cxxopts::value<int>(), "INT");
// options.add_options("Signal data indexing")
// ("build-sig-index", "Build index for signal data directory");
options.add_options("Mapping")("m,map", "Map signal data")(
"step-size", "Seeding step size in reads [2]", cxxopts::value<int>(),
"INT")("t,num-threads", "# threads for mapping [1]",
cxxopts::value<int>(), "INT");
options.add_options("Input")("r,ref", "Reference file",
cxxopts::value<std::string>(), "FILE")(
"p,pore-model", "Pore model file", cxxopts::value<std::string>(), "FILE")(
"x,ref-index", "Reference index file", cxxopts::value<std::string>(),
"FILE")
//("sig-index", "Signal data directory index file",
// cxxopts::value<std::string>(), "FILE")
("s,sig-dir", "Signal data directory", cxxopts::value<std::string>(),
"DIR");
//("b,read-file", "Basecalled FASTA/FASTQ read file",
// cxxopts::value<std::string>());
options.add_options("Output")("o,output", "Output file",
cxxopts::value<std::string>());
options.add_options("Development")("search-radius",
"Search radius for each seed [0.08]",
cxxopts::value<float>(), "FLT")(
"max-num-chunks", "Max # chunks before stop trying to map a read [30]",
cxxopts::value<int>(),
"INT")("min-num-anchors", "Min # anchors to stop mapping [10]",
cxxopts::value<int>(), "INT")(
"min-num-anchors-output", "Min # anchors to output mappings [10]",
cxxopts::value<int>(), "INT")("stop-mapping",
"The ratio between best and second best "
"chaining score to stop mapping [1.4]",
cxxopts::value<float>(), "FLOAT")(
"stop-mapping-output",
"The ratio between best and second best chaining score to output "
"mappings [1.2]",
cxxopts::value<float>(), "FLOAT")(
"stop-mapping-mean",
"The ratio between best and mean chaining score to stop mapping [5]",
cxxopts::value<float>(), "FLOAT")(
"stop-mapping-mean-output",
"The ratio between best and mean chaining score to output mappings [5]",
cxxopts::value<float>(), "FLOAT");
options.add_options()("h,help", "Print help");
auto result = options.parse(argc, argv);
float search_radius = 0.08;
if (result.count("search-radius")) {
search_radius = result["search-radius"].as<float>();
}
int read_seeding_step_size = 2;
if (result.count("step-size")) {
read_seeding_step_size = result["step-size"].as<int>();
}
int num_threads = 1;
if (result.count("t")) {
num_threads = result["num-threads"].as<int>();
}
int max_num_chunks = 30;
if (result.count("max-num-chunks")) {
max_num_chunks = result["max-num-chunks"].as<int>();
}
int stop_mapping_min_num_anchors = 10;
if (result.count("min-num-anchors")) {
stop_mapping_min_num_anchors = result["min-num-anchors"].as<int>();
}
int output_mapping_min_num_anchors = 10;
if (result.count("min-num-anchors-output")) {
output_mapping_min_num_anchors = result["min-num-anchors-output"].as<int>();
}
float stop_mapping_ratio = 1.4;
if (result.count("stop-mapping")) {
stop_mapping_ratio = result["stop-mapping"].as<float>();
}
float output_mapping_ratio = 1.2;
if (result.count("stop-mapping-output")) {
output_mapping_ratio = result["stop-mapping-output"].as<float>();
}
float stop_mapping_mean_ratio = 5;
if (result.count("stop-mapping-mean")) {
stop_mapping_mean_ratio = result["stop-mapping-mean"].as<float>();
}
float output_mapping_mean_ratio = 5;
if (result.count("stop-mapping-mean-output")) {
output_mapping_mean_ratio = result["stop-mapping-mean-output"].as<float>();
}
if (result.count("i")) {
int dimension = 6;
if (result.count("d")) {
dimension = result["dimension"].as<int>();
}
int max_leaf = 20;
if (result.count("l")) {
max_leaf = result["max-leaf"].as<int>();
}
std::cerr << "Dimension: " << dimension << ", max leaf: " << max_leaf
<< "\n";
std::string reference_file_path;
if (result.count("r")) {
reference_file_path = result["ref"].as<std::string>();
} else {
sigmap::ExitWithMessage("No reference file specified!");
}
std::cerr << "Reference file: " << reference_file_path << "\n";
std::string pore_model_file_path;
if (result.count("p")) {
pore_model_file_path = result["pore-model"].as<std::string>();
} else {
sigmap::ExitWithMessage("No pore model file specified!");
}
std::cerr << "Pore model file: " << pore_model_file_path << "\n";
std::string output_file_path;
if (result.count("o")) {
output_file_path = result["output"].as<std::string>();
} else {
sigmap::ExitWithMessage("No output file specified!");
}
std::cerr << "Output file: " << output_file_path << "\n";
Sigmap sigmap_for_indexing(dimension, max_leaf, reference_file_path,
pore_model_file_path, output_file_path);
sigmap_for_indexing.ConstructIndex();
} else if (result.count("m")) {
std::cerr << "Number of threads: " << num_threads << "\n";
std::string reference_file_path;
if (result.count("r")) {
reference_file_path = result["ref"].as<std::string>();
} else {
sigmap::ExitWithMessage("No reference file specified!");
}
std::cerr << "Reference file: " << reference_file_path << "\n";
std::string pore_model_file_path;
if (result.count("p")) {
pore_model_file_path = result["pore-model"].as<std::string>();
} else {
sigmap::ExitWithMessage("No pore model file specified!");
}
std::cerr << "Pore model file: " << pore_model_file_path << "\n";
std::string reference_index_file_path;
if (result.count("x")) {
reference_index_file_path = result["ref-index"].as<std::string>();
} else {
sigmap::ExitWithMessage("No reference index file specified!");
}
std::cerr << "Reference index file: " << reference_index_file_path << "\n";
std::string signal_dir;
if (result.count("sig-dir")) {
signal_dir = result["sig-dir"].as<std::string>();
} else {
sigmap::ExitWithMessage("No signal data directory specified!");
}
std::cerr << "Signal directory: " << signal_dir << "\n";
std::string output_file_path;
if (result.count("o")) {
output_file_path = result["output"].as<std::string>();
} else {
sigmap::ExitWithMessage("No output file specified!");
}
std::cerr << "Output file: " << output_file_path << "\n";
Sigmap sigmap_for_mapping(
search_radius, read_seeding_step_size, num_threads, max_num_chunks,
stop_mapping_min_num_anchors, output_mapping_min_num_anchors,
stop_mapping_ratio, output_mapping_ratio, stop_mapping_mean_ratio,
output_mapping_mean_ratio, reference_file_path, pore_model_file_path,
signal_dir, reference_index_file_path, output_file_path);
// sigmap_for_mapping.CWTAlign();
// sigmap_for_mapping.DTWAlign();
// sigmap_for_mapping.Map();
sigmap_for_mapping.StreamingMap();
// sigmap_for_mapping.FAST5ToText();
// sigmap_for_mapping.EventsToText();
} else if (result.count("h")) {
std::cerr << options.help(
{"", "Indexing", "Mapping", "Input", "Output", "Development"});
} else {
std::cerr << options.help(
{"", "Indexing", "Mapping", "Input", "Output", "Development"});
}
// std::string read_file_path;
// if (result.count("b")) {
// read_file_path = result["read-file"].as<std::string>();
//} else {
// sigmap::ExitWithMessage("No read file specified!");
//}
// std::cerr << "Read file: " << read_file_path << "\n";
}
} // namespace sigmap
int main(int argc, char *argv[]) {
sigmap::SigmapDriver sigmap_driver;
sigmap_driver.ParseArgsAndRun(argc, argv);
return 0;
}
| 71,018
|
C++
|
.cc
| 1,492
| 37.55429
| 112
| 0.586629
|
haowenz/sigmap
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,202
|
cwt.cc
|
haowenz_sigmap/src/cwt.cc
|
#include "cwt.h"
namespace sigmap {
// FFT
int dividebyN(int N) {
while (N % 53 == 0) {
N = N / 53;
}
while (N % 47 == 0) {
N = N / 47;
}
while (N % 43 == 0) {
N = N / 43;
}
while (N % 41 == 0) {
N = N / 41;
}
while (N % 37 == 0) {
N = N / 37;
}
while (N % 31 == 0) {
N = N / 31;
}
while (N % 29 == 0) {
N = N / 29;
}
while (N % 23 == 0) {
N = N / 23;
}
while (N % 17 == 0) {
N = N / 17;
}
while (N % 13 == 0) {
N = N / 13;
}
while (N % 11 == 0) {
N = N / 11;
}
while (N % 8 == 0) {
N = N / 8;
}
while (N % 7 == 0) {
N = N / 7;
}
while (N % 5 == 0) {
N = N / 5;
}
while (N % 4 == 0) {
N = N / 4;
}
while (N % 3 == 0) {
N = N / 3;
}
while (N % 2 == 0) {
N = N / 2;
}
if (N == 1) {
return 1;
}
return 0;
}
int factors(int M, int *arr) {
int i, N, num, mult, m1, m2;
i = 0;
N = M;
while (N % 53 == 0) {
N = N / 53;
arr[i] = 53;
i++;
}
while (N % 47 == 0) {
N = N / 47;
arr[i] = 47;
i++;
}
while (N % 43 == 0) {
N = N / 43;
arr[i] = 43;
i++;
}
while (N % 41 == 0) {
N = N / 41;
arr[i] = 41;
i++;
}
while (N % 37 == 0) {
N = N / 37;
arr[i] = 37;
i++;
}
while (N % 31 == 0) {
N = N / 31;
arr[i] = 31;
i++;
}
while (N % 29 == 0) {
N = N / 29;
arr[i] = 29;
i++;
}
while (N % 23 == 0) {
N = N / 23;
arr[i] = 23;
i++;
}
while (N % 19 == 0) {
N = N / 19;
arr[i] = 19;
i++;
}
while (N % 17 == 0) {
N = N / 17;
arr[i] = 17;
i++;
}
while (N % 13 == 0) {
N = N / 13;
arr[i] = 13;
i++;
}
while (N % 11 == 0) {
N = N / 11;
arr[i] = 11;
i++;
}
while (N % 8 == 0) {
N = N / 8;
arr[i] = 8;
i++;
}
while (N % 7 == 0) {
N = N / 7;
arr[i] = 7;
i++;
}
while (N % 5 == 0) {
N = N / 5;
arr[i] = 5;
i++;
}
while (N % 4 == 0) {
N = N / 4;
arr[i] = 4;
i++;
}
while (N % 3 == 0) {
N = N / 3;
arr[i] = 3;
i++;
}
while (N % 2 == 0) {
N = N / 2;
arr[i] = 2;
i++;
}
if (N > 31) {
num = 2;
while (N > 1) {
mult = num * 6;
m1 = mult - 1;
m2 = mult + 1;
while (N % m1 == 0) {
arr[i] = m1;
i++;
N = N / m1;
}
while (N % m2 == 0) {
arr[i] = m2;
i++;
N = N / m2;
}
num += 1;
}
}
return i;
}
void longvectorN(fft_data *sig, int *array, int tx) {
int L, i, Ls, ct, j, k;
fft_type theta;
L = 1;
ct = 0;
for (i = 0; i < tx; i++) {
L = L * array[tx - 1 - i];
Ls = L / array[tx - 1 - i];
theta = -1.0 * PI2 / L;
for (j = 0; j < Ls; j++) {
for (k = 0; k < array[tx - 1 - i] - 1; k++) {
sig[ct].re = cos((k + 1) * j * theta);
sig[ct].im = sin((k + 1) * j * theta);
ct++;
}
}
}
}
fft_object fft_init(int N, int sgn) {
fft_object obj = NULL;
// Change N/2 to N-1 for longvector case
int twi_len, ct, out;
out = dividebyN(N);
if (out == 1) {
obj =
(fft_object)malloc(sizeof(struct fft_set) + sizeof(fft_data) * (N - 1));
obj->lf = factors(N, obj->factors);
longvectorN(obj->twiddle, obj->factors, obj->lf);
twi_len = N;
obj->lt = 0;
} else {
int K, M;
K = (int)pow(2.0, ceil(log10(N) / log10(2.0)));
if (K < 2 * N - 2) {
M = K * 2;
} else {
M = K;
}
obj =
(fft_object)malloc(sizeof(struct fft_set) + sizeof(fft_data) * (M - 1));
obj->lf = factors(M, obj->factors);
longvectorN(obj->twiddle, obj->factors, obj->lf);
obj->lt = 1;
twi_len = M;
}
obj->N = N;
obj->sgn = sgn;
if (sgn == -1) {
for (ct = 0; ct < twi_len; ct++) {
(obj->twiddle + ct)->im = -(obj->twiddle + ct)->im;
}
}
return obj;
}
static void bluestein_exp(fft_data *hl, fft_data *hlt, int len, int M) {
fft_type PI, theta, angle;
int l2, len2, i;
PI = 3.1415926535897932384626433832795;
theta = PI / len;
l2 = 0;
len2 = 2 * len;
for (i = 0; i < len; ++i) {
angle = theta * l2;
hlt[i].re = cos(angle);
hlt[i].im = sin(angle);
hl[i].re = hlt[i].re;
hl[i].im = hlt[i].im;
l2 += 2 * i + 1;
while (l2 > len2) {
l2 -= len2;
}
}
for (i = len; i < M - len + 1; i++) {
hl[i].re = 0.0;
hl[i].im = 0.0;
}
for (i = M - len + 1; i < M; i++) {
hl[i].re = hlt[M - i].re;
hl[i].im = hlt[M - i].im;
}
}
static void bluestein_fft(fft_data *data, fft_data *oup, fft_object obj,
int sgn, int N) {
int K, M, ii, i;
int def_lt, def_N, def_sgn;
fft_type scale, temp;
fft_data *yn;
fft_data *hk;
fft_data *tempop;
fft_data *yno;
fft_data *hlt;
obj->lt = 0;
K = (int)pow(2.0, ceil((double)log10((double)N) / log10((double)2.0)));
def_lt = 1;
def_sgn = obj->sgn;
def_N = obj->N;
if (K < 2 * N - 2) {
M = K * 2;
} else {
M = K;
}
obj->N = M;
yn = (fft_data *)malloc(sizeof(fft_data) * M);
hk = (fft_data *)malloc(sizeof(fft_data) * M);
tempop = (fft_data *)malloc(sizeof(fft_data) * M);
yno = (fft_data *)malloc(sizeof(fft_data) * M);
hlt = (fft_data *)malloc(sizeof(fft_data) * N);
// fft_data* twi = (fft_data*) malloc (sizeof(fft_data) * M);
bluestein_exp(tempop, hlt, N, M);
scale = 1.0 / M;
for (ii = 0; ii < M; ++ii) {
tempop[ii].im *= scale;
tempop[ii].re *= scale;
}
// fft_object obj = initialize_fft2(M,1);
fft_exec(obj, tempop, hk);
if (sgn == 1) {
for (i = 0; i < N; i++) {
tempop[i].re = data[i].re * hlt[i].re + data[i].im * hlt[i].im;
tempop[i].im = -data[i].re * hlt[i].im + data[i].im * hlt[i].re;
}
} else {
for (i = 0; i < N; i++) {
tempop[i].re = data[i].re * hlt[i].re - data[i].im * hlt[i].im;
tempop[i].im = data[i].re * hlt[i].im + data[i].im * hlt[i].re;
}
}
for (i = N; i < M; i++) {
tempop[i].re = 0.0;
tempop[i].im = 0.0;
}
fft_exec(obj, tempop, yn);
if (sgn == 1) {
for (i = 0; i < M; i++) {
temp = yn[i].re * hk[i].re - yn[i].im * hk[i].im;
yn[i].im = yn[i].re * hk[i].im + yn[i].im * hk[i].re;
yn[i].re = temp;
}
} else {
for (i = 0; i < M; i++) {
temp = yn[i].re * hk[i].re + yn[i].im * hk[i].im;
yn[i].im = -yn[i].re * hk[i].im + yn[i].im * hk[i].re;
yn[i].re = temp;
}
}
// IFFT
for (ii = 0; ii < M; ++ii) {
(obj->twiddle + ii)->im = -(obj->twiddle + ii)->im;
}
obj->sgn = -1 * sgn;
fft_exec(obj, yn, yno);
if (sgn == 1) {
for (i = 0; i < N; i++) {
oup[i].re = yno[i].re * hlt[i].re + yno[i].im * hlt[i].im;
oup[i].im = -yno[i].re * hlt[i].im + yno[i].im * hlt[i].re;
}
} else {
for (i = 0; i < N; i++) {
oup[i].re = yno[i].re * hlt[i].re - yno[i].im * hlt[i].im;
oup[i].im = yno[i].re * hlt[i].im + yno[i].im * hlt[i].re;
}
}
obj->sgn = def_sgn;
obj->N = def_N;
obj->lt = def_lt;
for (ii = 0; ii < M; ++ii) {
(obj->twiddle + ii)->im = -(obj->twiddle + ii)->im;
}
free(yn);
free(yno);
free(tempop);
free(hk);
free(hlt);
}
static void mixed_radix_dit_rec(fft_data *op, fft_data *ip,
const fft_object obj, int sgn, int N, int l,
int inc) {
int radix = 9, m, ll;
if (N > 1) {
radix = obj->factors[inc];
// printf("%d \n",radix);
}
if (N == 1) {
op[0].re = ip[0].re;
op[0].im = ip[0].im;
} else if (N == 2) {
fft_type tau1r, tau1i;
op[0].re = ip[0].re;
op[0].im = ip[0].im;
op[1].re = ip[l].re;
op[1].im = ip[l].im;
tau1r = op[0].re;
tau1i = op[0].im;
op[0].re = tau1r + op[1].re;
op[0].im = tau1i + op[1].im;
op[1].re = tau1r - op[1].re;
op[1].im = tau1i - op[1].im;
} else if (N == 3) {
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i;
op[0].re = ip[0].re;
op[0].im = ip[0].im;
op[1].re = ip[l].re;
op[1].im = ip[l].im;
op[2].re = ip[2 * l].re;
op[2].im = ip[2 * l].im;
tau0r = op[1].re + op[2].re;
tau0i = op[1].im + op[2].im;
tau1r = sgn * 0.86602540378 * (op[1].re - op[2].re);
tau1i = sgn * 0.86602540378 * (op[1].im - op[2].im);
tau2r = op[0].re - tau0r * 0.5000000000;
tau2i = op[0].im - tau0i * 0.5000000000;
op[0].re = tau0r + op[0].re;
op[0].im = tau0i + op[0].im;
op[1].re = tau2r + tau1i;
op[1].im = tau2i - tau1r;
op[2].re = tau2r - tau1i;
op[2].im = tau2i + tau1r;
return;
} else if (N == 4) {
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i;
op[0].re = ip[0].re;
op[0].im = ip[0].im;
op[1].re = ip[l].re;
op[1].im = ip[l].im;
op[2].re = ip[2 * l].re;
op[2].im = ip[2 * l].im;
op[3].re = ip[3 * l].re;
op[3].im = ip[3 * l].im;
tau0r = op[0].re + op[2].re;
tau0i = op[0].im + op[2].im;
tau1r = op[0].re - op[2].re;
tau1i = op[0].im - op[2].im;
tau2r = op[1].re + op[3].re;
tau2i = op[1].im + op[3].im;
tau3r = sgn * (op[1].re - op[3].re);
tau3i = sgn * (op[1].im - op[3].im);
op[0].re = tau0r + tau2r;
op[0].im = tau0i + tau2i;
op[1].re = tau1r + tau3i;
op[1].im = tau1i - tau3r;
op[2].re = tau0r - tau2r;
op[2].im = tau0i - tau2i;
op[3].re = tau1r - tau3i;
op[3].im = tau1i + tau3r;
} else if (N == 5) {
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i, tau4r,
tau4i, tau5r, tau5i, tau6r, tau6i;
fft_type c1, c2, s1, s2;
op[0].re = ip[0].re;
op[0].im = ip[0].im;
op[1].re = ip[l].re;
op[1].im = ip[l].im;
op[2].re = ip[2 * l].re;
op[2].im = ip[2 * l].im;
op[3].re = ip[3 * l].re;
op[3].im = ip[3 * l].im;
op[4].re = ip[4 * l].re;
op[4].im = ip[4 * l].im;
c1 = 0.30901699437;
c2 = -0.80901699437;
s1 = 0.95105651629;
s2 = 0.58778525229;
tau0r = op[1].re + op[4].re;
tau2r = op[1].re - op[4].re;
tau0i = op[1].im + op[4].im;
tau2i = op[1].im - op[4].im;
tau1r = op[2].re + op[3].re;
tau3r = op[2].re - op[3].re;
tau1i = op[2].im + op[3].im;
tau3i = op[2].im - op[3].im;
tau4r = c1 * tau0r + c2 * tau1r;
tau4i = c1 * tau0i + c2 * tau1i;
// tau5r = sgn * ( s1 * tau2r + s2 * tau3r);
// tau5i = sgn * ( s1 * tau2i + s2 * tau3i);
if (sgn == 1) {
tau5r = s1 * tau2r + s2 * tau3r;
tau5i = s1 * tau2i + s2 * tau3i;
} else {
tau5r = -s1 * tau2r - s2 * tau3r;
tau5i = -s1 * tau2i - s2 * tau3i;
}
tau6r = op[0].re + tau4r;
tau6i = op[0].im + tau4i;
op[1].re = tau6r + tau5i;
op[1].im = tau6i - tau5r;
op[4].re = tau6r - tau5i;
op[4].im = tau6i + tau5r;
tau4r = c2 * tau0r + c1 * tau1r;
tau4i = c2 * tau0i + c1 * tau1i;
// tau5r = sgn * ( s2 * tau2r - s1 * tau3r);
// tau5i = sgn * ( s2 * tau2i - s1 * tau3i);
if (sgn == 1) {
tau5r = s2 * tau2r - s1 * tau3r;
tau5i = s2 * tau2i - s1 * tau3i;
} else {
tau5r = -s2 * tau2r + s1 * tau3r;
tau5i = -s2 * tau2i + s1 * tau3i;
}
tau6r = op[0].re + tau4r;
tau6i = op[0].im + tau4i;
op[2].re = tau6r + tau5i;
op[2].im = tau6i - tau5r;
op[3].re = tau6r - tau5i;
op[3].im = tau6i + tau5r;
op[0].re += tau0r + tau1r;
op[0].im += tau0i + tau1i;
} else if (N == 7) {
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i, tau4r,
tau4i, tau5r, tau5i, tau6r, tau6i, tau7r, tau7i;
fft_type c1, c2, c3, s1, s2, s3;
op[0].re = ip[0].re;
op[0].im = ip[0].im;
op[1].re = ip[l].re;
op[1].im = ip[l].im;
op[2].re = ip[2 * l].re;
op[2].im = ip[2 * l].im;
op[3].re = ip[3 * l].re;
op[3].im = ip[3 * l].im;
op[4].re = ip[4 * l].re;
op[4].im = ip[4 * l].im;
op[5].re = ip[5 * l].re;
op[5].im = ip[5 * l].im;
op[6].re = ip[6 * l].re;
op[6].im = ip[6 * l].im;
c1 = 0.62348980185;
c2 = -0.22252093395;
c3 = -0.9009688679;
s1 = 0.78183148246;
s2 = 0.97492791218;
s3 = 0.43388373911;
tau0r = op[1].re + op[6].re;
tau3r = op[1].re - op[6].re;
tau0i = op[1].im + op[6].im;
tau3i = op[1].im - op[6].im;
tau1r = op[2].re + op[5].re;
tau4r = op[2].re - op[5].re;
tau1i = op[2].im + op[5].im;
tau4i = op[2].im - op[5].im;
tau2r = op[3].re + op[4].re;
tau5r = op[3].re - op[4].re;
tau2i = op[3].im + op[4].im;
tau5i = op[3].im - op[4].im;
tau6r = op[0].re + c1 * tau0r + c2 * tau1r + c3 * tau2r;
tau6i = op[0].im + c1 * tau0i + c2 * tau1i + c3 * tau2i;
// tau7r = sgn * ( -s1 * tau3r - s2 * tau4r - s3 * tau5r);
// tau7i = sgn * ( -s1 * tau3i - s2 * tau4i - s3 * tau5i);
if (sgn == 1) {
tau7r = -s1 * tau3r - s2 * tau4r - s3 * tau5r;
tau7i = -s1 * tau3i - s2 * tau4i - s3 * tau5i;
} else {
tau7r = s1 * tau3r + s2 * tau4r + s3 * tau5r;
tau7i = s1 * tau3i + s2 * tau4i + s3 * tau5i;
}
op[1].re = tau6r - tau7i;
op[6].re = tau6r + tau7i;
op[1].im = tau6i + tau7r;
op[6].im = tau6i - tau7r;
tau6r = op[0].re + c2 * tau0r + c3 * tau1r + c1 * tau2r;
tau6i = op[0].im + c2 * tau0i + c3 * tau1i + c1 * tau2i;
// tau7r = sgn * ( -s2 * tau3r + s3 * tau4r + s1 * tau5r);
// tau7i = sgn * ( -s2 * tau3i + s3 * tau4i + s1 * tau5i);
if (sgn == 1) {
tau7r = -s2 * tau3r + s3 * tau4r + s1 * tau5r;
tau7i = -s2 * tau3i + s3 * tau4i + s1 * tau5i;
} else {
tau7r = s2 * tau3r - s3 * tau4r - s1 * tau5r;
tau7i = s2 * tau3i - s3 * tau4i - s1 * tau5i;
}
op[2].re = tau6r - tau7i;
op[5].re = tau6r + tau7i;
op[2].im = tau6i + tau7r;
op[5].im = tau6i - tau7r;
tau6r = op[0].re + c3 * tau0r + c1 * tau1r + c2 * tau2r;
tau6i = op[0].im + c3 * tau0i + c1 * tau1i + c2 * tau2i;
// tau7r = sgn * ( -s3 * tau3r + s1 * tau4r - s2 * tau5r);
// tau7i = sgn * ( -s3 * tau3i + s1 * tau4i - s2 * tau5i);
if (sgn == 1) {
tau7r = -s3 * tau3r + s1 * tau4r - s2 * tau5r;
tau7i = -s3 * tau3i + s1 * tau4i - s2 * tau5i;
} else {
tau7r = s3 * tau3r - s1 * tau4r + s2 * tau5r;
tau7i = s3 * tau3i - s1 * tau4i + s2 * tau5i;
}
op[3].re = tau6r - tau7i;
op[4].re = tau6r + tau7i;
op[3].im = tau6i + tau7r;
op[4].im = tau6i - tau7r;
op[0].re += tau0r + tau1r + tau2r;
op[0].im += tau0i + tau1i + tau2i;
} else if (N == 8) {
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i, tau4r,
tau4i, tau5r, tau5i, tau6r, tau6i, tau7r, tau7i, tau8r, tau8i, tau9r,
tau9i;
fft_type c1, s1, temp1r, temp1i, temp2r, temp2i;
op[0].re = ip[0].re;
op[0].im = ip[0].im;
op[1].re = ip[l].re;
op[1].im = ip[l].im;
op[2].re = ip[2 * l].re;
op[2].im = ip[2 * l].im;
op[3].re = ip[3 * l].re;
op[3].im = ip[3 * l].im;
op[4].re = ip[4 * l].re;
op[4].im = ip[4 * l].im;
op[5].re = ip[5 * l].re;
op[5].im = ip[5 * l].im;
op[6].re = ip[6 * l].re;
op[6].im = ip[6 * l].im;
op[7].re = ip[7 * l].re;
op[7].im = ip[7 * l].im;
c1 = 0.70710678118654752440084436210485;
s1 = 0.70710678118654752440084436210485;
tau0r = op[0].re + op[4].re;
tau4r = op[0].re - op[4].re;
tau0i = op[0].im + op[4].im;
tau4i = op[0].im - op[4].im;
tau1r = op[1].re + op[7].re;
tau5r = op[1].re - op[7].re;
tau1i = op[1].im + op[7].im;
tau5i = op[1].im - op[7].im;
tau2r = op[3].re + op[5].re;
tau6r = op[3].re - op[5].re;
tau2i = op[3].im + op[5].im;
tau6i = op[3].im - op[5].im;
tau3r = op[2].re + op[6].re;
tau7r = op[2].re - op[6].re;
tau3i = op[2].im + op[6].im;
tau7i = op[2].im - op[6].im;
op[0].re = tau0r + tau1r + tau2r + tau3r;
op[0].im = tau0i + tau1i + tau2i + tau3i;
op[4].re = tau0r - tau1r - tau2r + tau3r;
op[4].im = tau0i - tau1i - tau2i + tau3i;
temp1r = tau1r - tau2r;
temp1i = tau1i - tau2i;
temp2r = tau5r + tau6r;
temp2i = tau5i + tau6i;
tau8r = tau4r + c1 * temp1r;
tau8i = tau4i + c1 * temp1i;
// tau9r = sgn * ( -s1 * temp2r - tau7r);
// tau9i = sgn * ( -s1 * temp2i - tau7i);
if (sgn == 1) {
tau9r = -s1 * temp2r - tau7r;
tau9i = -s1 * temp2i - tau7i;
} else {
tau9r = s1 * temp2r + tau7r;
tau9i = s1 * temp2i + tau7i;
}
op[1].re = tau8r - tau9i;
op[1].im = tau8i + tau9r;
op[7].re = tau8r + tau9i;
op[7].im = tau8i - tau9r;
tau8r = tau0r - tau3r;
tau8i = tau0i - tau3i;
// tau9r = sgn * ( -tau5r + tau6r);
// tau9i = sgn * ( -tau5i + tau6i);
if (sgn == 1) {
tau9r = -tau5r + tau6r;
tau9i = -tau5i + tau6i;
} else {
tau9r = tau5r - tau6r;
tau9i = tau5i - tau6i;
}
op[2].re = tau8r - tau9i;
op[2].im = tau8i + tau9r;
op[6].re = tau8r + tau9i;
op[6].im = tau8i - tau9r;
tau8r = tau4r - c1 * temp1r;
tau8i = tau4i - c1 * temp1i;
// tau9r = sgn * ( -s1 * temp2r + tau7r);
// tau9i = sgn * ( -s1 * temp2i + tau7i);
if (sgn == 1) {
tau9r = -s1 * temp2r + tau7r;
tau9i = -s1 * temp2i + tau7i;
} else {
tau9r = s1 * temp2r - tau7r;
tau9i = s1 * temp2i - tau7i;
}
op[3].re = tau8r - tau9i;
op[3].im = tau8i + tau9r;
op[5].re = tau8r + tau9i;
op[5].im = tau8i - tau9r;
} else if (radix == 2) {
int k, tkm1, ind;
fft_type wlr, wli;
fft_type tau1r, tau1i, tau2r, tau2i;
m = N / 2;
ll = 2 * l;
mixed_radix_dit_rec(op, ip, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + m, ip + l, obj, sgn, m, ll, inc + 1);
for (k = 0; k < m; k++) {
ind = m - 1 + k;
wlr = (obj->twiddle + ind)->re;
wli = (obj->twiddle + ind)->im;
tkm1 = k + m;
tau1r = op[k].re;
tau1i = op[k].im;
tau2r = op[tkm1].re * wlr - op[tkm1].im * wli;
tau2i = op[tkm1].im * wlr + op[tkm1].re * wli;
op[k].re = tau1r + tau2r;
op[k].im = tau1i + tau2i;
op[tkm1].re = tau1r - tau2r;
op[tkm1].im = tau1i - tau2i;
}
} else if (radix == 3) {
int k, tkm1, tkm2, ind;
fft_type wlr, wli, wl2r, wl2i;
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i;
fft_type ar, ai, br, bi, cr, ci;
m = N / 3;
ll = 3 * l;
mixed_radix_dit_rec(op, ip, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + m, ip + l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 2 * m, ip + 2 * l, obj, sgn, m, ll, inc + 1);
// printf("%d \n",inc);
// mixed_radix3_dit_rec(op,ip,obj,sgn,ll,m);
for (k = 0; k < m; ++k) {
ind = m - 1 + 2 * k;
wlr = (obj->twiddle + ind)->re;
wli = (obj->twiddle + ind)->im;
ind++;
wl2r = (obj->twiddle + ind)->re;
wl2i = (obj->twiddle + ind)->im;
tkm1 = k + m;
tkm2 = tkm1 + m;
ar = op[k].re;
ai = op[k].im;
br = op[tkm1].re * wlr - op[tkm1].im * wli;
bi = op[tkm1].im * wlr + op[tkm1].re * wli;
cr = op[tkm2].re * wl2r - op[tkm2].im * wl2i;
ci = op[tkm2].im * wl2r + op[tkm2].re * wl2i;
tau0r = br + cr;
tau0i = bi + ci;
tau1r = sgn * 0.86602540378 * (br - cr);
tau1i = sgn * 0.86602540378 * (bi - ci);
tau2r = ar - tau0r * 0.5000000000;
tau2i = ai - tau0i * 0.5000000000;
op[k].re = ar + tau0r;
op[k].im = ai + tau0i;
op[tkm1].re = tau2r + tau1i;
op[tkm1].im = tau2i - tau1r;
op[tkm2].re = tau2r - tau1i;
op[tkm2].im = tau2i + tau1r;
}
} else if (radix == 4) {
int k, tkm1, tkm2, tkm3, ind;
fft_type wlr, wli, wl2r, wl2i, wl3r, wl3i;
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i;
fft_type ar, ai, br, bi, cr, ci, dr, di;
m = N / 4;
ll = 4 * l;
mixed_radix_dit_rec(op, ip, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + m, ip + l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 2 * m, ip + 2 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 3 * m, ip + 3 * l, obj, sgn, m, ll, inc + 1);
// mixed_radix4_dit_rec(op,ip,obj,sgn,ll,m);
tkm1 = m;
tkm2 = tkm1 + m;
tkm3 = tkm2 + m;
ar = op[0].re;
ai = op[0].im;
br = op[tkm1].re;
bi = op[tkm1].im;
cr = op[tkm2].re;
ci = op[tkm2].im;
dr = op[tkm3].re;
di = op[tkm3].im;
tau0r = ar + cr;
tau0i = ai + ci;
tau1r = ar - cr;
tau1i = ai - ci;
tau2r = br + dr;
tau2i = bi + di;
tau3r = sgn * (br - dr);
tau3i = sgn * (bi - di);
op[0].re = tau0r + tau2r;
op[0].im = tau0i + tau2i;
op[tkm1].re = tau1r + tau3i;
op[tkm1].im = tau1i - tau3r;
op[tkm2].re = tau0r - tau2r;
op[tkm2].im = tau0i - tau2i;
op[tkm3].re = tau1r - tau3i;
op[tkm3].im = tau1i + tau3r;
for (k = 1; k < m; k++) {
ind = m - 1 + 3 * k;
wlr = (obj->twiddle + ind)->re;
wli = (obj->twiddle + ind)->im;
ind++;
wl2r = (obj->twiddle + ind)->re;
wl2i = (obj->twiddle + ind)->im;
ind++;
wl3r = (obj->twiddle + ind)->re;
wl3i = (obj->twiddle + ind)->im;
tkm1 = k + m;
tkm2 = tkm1 + m;
tkm3 = tkm2 + m;
ar = op[k].re;
ai = op[k].im;
br = op[tkm1].re * wlr - op[tkm1].im * wli;
bi = op[tkm1].im * wlr + op[tkm1].re * wli;
cr = op[tkm2].re * wl2r - op[tkm2].im * wl2i;
ci = op[tkm2].im * wl2r + op[tkm2].re * wl2i;
dr = op[tkm3].re * wl3r - op[tkm3].im * wl3i;
di = op[tkm3].im * wl3r + op[tkm3].re * wl3i;
tau0r = ar + cr;
tau0i = ai + ci;
tau1r = ar - cr;
tau1i = ai - ci;
tau2r = br + dr;
tau2i = bi + di;
tau3r = sgn * (br - dr);
tau3i = sgn * (bi - di);
op[k].re = tau0r + tau2r;
op[k].im = tau0i + tau2i;
op[tkm1].re = tau1r + tau3i;
op[tkm1].im = tau1i - tau3r;
op[tkm2].re = tau0r - tau2r;
op[tkm2].im = tau0i - tau2i;
op[tkm3].re = tau1r - tau3i;
op[tkm3].im = tau1i + tau3r;
}
} else if (radix == 5) {
int k, tkm1, tkm2, tkm3, tkm4, ind;
fft_type wlr, wli, wl2r, wl2i, wl3r, wl3i, wl4r, wl4i;
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i;
fft_type ar, ai, br, bi, cr, ci, dr, di, er, ei;
fft_type tau4r, tau4i, tau5r, tau5i, tau6r, tau6i;
fft_type c1, c2, s1, s2;
m = N / 5;
ll = 5 * l;
mixed_radix_dit_rec(op, ip, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + m, ip + l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 2 * m, ip + 2 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 3 * m, ip + 3 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 4 * m, ip + 4 * l, obj, sgn, m, ll, inc + 1);
// printf("%d \n",inc);
// mixed_radix3_dit_rec(op,ip,obj,sgn,ll,m);
c1 = 0.30901699437;
c2 = -0.80901699437;
s1 = 0.95105651629;
s2 = 0.58778525229;
tkm1 = m;
tkm2 = tkm1 + m;
tkm3 = tkm2 + m;
tkm4 = tkm3 + m;
ar = op[0].re;
ai = op[0].im;
br = op[tkm1].re;
bi = op[tkm1].im;
cr = op[tkm2].re;
ci = op[tkm2].im;
dr = op[tkm3].re;
di = op[tkm3].im;
er = op[tkm4].re;
ei = op[tkm4].im;
tau0r = br + er;
tau0i = bi + ei;
tau1r = cr + dr;
tau1i = ci + di;
tau2r = br - er;
tau2i = bi - ei;
tau3r = cr - dr;
tau3i = ci - di;
op[0].re = ar + tau0r + tau1r;
op[0].im = ai + tau0i + tau1i;
tau4r = c1 * tau0r + c2 * tau1r;
tau4i = c1 * tau0i + c2 * tau1i;
tau5r = sgn * (s1 * tau2r + s2 * tau3r);
tau5i = sgn * (s1 * tau2i + s2 * tau3i);
tau6r = ar + tau4r;
tau6i = ai + tau4i;
op[tkm1].re = tau6r + tau5i;
op[tkm1].im = tau6i - tau5r;
op[tkm4].re = tau6r - tau5i;
op[tkm4].im = tau6i + tau5r;
tau4r = c2 * tau0r + c1 * tau1r;
tau4i = c2 * tau0i + c1 * tau1i;
tau5r = sgn * (s2 * tau2r - s1 * tau3r);
tau5i = sgn * (s2 * tau2i - s1 * tau3i);
tau6r = ar + tau4r;
tau6i = ai + tau4i;
op[tkm2].re = tau6r + tau5i;
op[tkm2].im = tau6i - tau5r;
op[tkm3].re = tau6r - tau5i;
op[tkm3].im = tau6i + tau5r;
for (k = 1; k < m; k++) {
ind = m - 1 + 4 * k;
wlr = (obj->twiddle + ind)->re;
wli = (obj->twiddle + ind)->im;
ind++;
wl2r = (obj->twiddle + ind)->re;
wl2i = (obj->twiddle + ind)->im;
ind++;
wl3r = (obj->twiddle + ind)->re;
wl3i = (obj->twiddle + ind)->im;
ind++;
wl4r = (obj->twiddle + ind)->re;
wl4i = (obj->twiddle + ind)->im;
tkm1 = k + m;
tkm2 = tkm1 + m;
tkm3 = tkm2 + m;
tkm4 = tkm3 + m;
ar = op[k].re;
ai = op[k].im;
br = op[tkm1].re * wlr - op[tkm1].im * wli;
bi = op[tkm1].im * wlr + op[tkm1].re * wli;
cr = op[tkm2].re * wl2r - op[tkm2].im * wl2i;
ci = op[tkm2].im * wl2r + op[tkm2].re * wl2i;
dr = op[tkm3].re * wl3r - op[tkm3].im * wl3i;
di = op[tkm3].im * wl3r + op[tkm3].re * wl3i;
er = op[tkm4].re * wl4r - op[tkm4].im * wl4i;
ei = op[tkm4].im * wl4r + op[tkm4].re * wl4i;
tau0r = br + er;
tau0i = bi + ei;
tau1r = cr + dr;
tau1i = ci + di;
tau2r = br - er;
tau2i = bi - ei;
tau3r = cr - dr;
tau3i = ci - di;
op[k].re = ar + tau0r + tau1r;
op[k].im = ai + tau0i + tau1i;
tau4r = c1 * tau0r + c2 * tau1r;
tau4i = c1 * tau0i + c2 * tau1i;
// tau5r = sgn * ( s1 * tau2r + s2 * tau3r);
// tau5i = sgn * ( s1 * tau2i + s2 * tau3i);
if (sgn == 1) {
tau5r = s1 * tau2r + s2 * tau3r;
tau5i = s1 * tau2i + s2 * tau3i;
} else {
tau5r = -s1 * tau2r - s2 * tau3r;
tau5i = -s1 * tau2i - s2 * tau3i;
}
tau6r = ar + tau4r;
tau6i = ai + tau4i;
op[tkm1].re = tau6r + tau5i;
op[tkm1].im = tau6i - tau5r;
op[tkm4].re = tau6r - tau5i;
op[tkm4].im = tau6i + tau5r;
tau4r = c2 * tau0r + c1 * tau1r;
tau4i = c2 * tau0i + c1 * tau1i;
// tau5r = sgn * ( s2 * tau2r - s1 * tau3r);
// tau5i = sgn * ( s2 * tau2i - s1 * tau3i);
if (sgn == 1) {
tau5r = s2 * tau2r - s1 * tau3r;
tau5i = s2 * tau2i - s1 * tau3i;
} else {
tau5r = -s2 * tau2r + s1 * tau3r;
tau5i = -s2 * tau2i + s1 * tau3i;
}
tau6r = ar + tau4r;
tau6i = ai + tau4i;
op[tkm2].re = tau6r + tau5i;
op[tkm2].im = tau6i - tau5r;
op[tkm3].re = tau6r - tau5i;
op[tkm3].im = tau6i + tau5r;
}
} else if (radix == 7) {
int k, tkm1, tkm2, tkm3, tkm4, tkm5, tkm6, ind;
fft_type wlr, wli, wl2r, wl2i, wl3r, wl3i, wl4r, wl4i, wl5r, wl5i, wl6r,
wl6i;
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i;
fft_type ar, ai, br, bi, cr, ci, dr, di, er, ei, fr, fi, gr, gi;
fft_type tau4r, tau4i, tau5r, tau5i, tau6r, tau6i, tau7r, tau7i;
fft_type c1, c2, c3, s1, s2, s3;
m = N / 7;
ll = 7 * l;
mixed_radix_dit_rec(op, ip, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + m, ip + l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 2 * m, ip + 2 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 3 * m, ip + 3 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 4 * m, ip + 4 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 5 * m, ip + 5 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 6 * m, ip + 6 * l, obj, sgn, m, ll, inc + 1);
// printf("%d \n",inc);
// mixed_radix3_dit_rec(op,ip,obj,sgn,ll,m);
c1 = 0.62348980185;
c2 = -0.22252093395;
c3 = -0.9009688679;
s1 = 0.78183148246;
s2 = 0.97492791218;
s3 = 0.43388373911;
tkm1 = m;
tkm2 = tkm1 + m;
tkm3 = tkm2 + m;
tkm4 = tkm3 + m;
tkm5 = tkm4 + m;
tkm6 = tkm5 + m;
ar = op[0].re;
ai = op[0].im;
br = op[tkm1].re;
bi = op[tkm1].im;
cr = op[tkm2].re;
ci = op[tkm2].im;
dr = op[tkm3].re;
di = op[tkm3].im;
er = op[tkm4].re;
ei = op[tkm4].im;
fr = op[tkm5].re;
fi = op[tkm5].im;
gr = op[tkm6].re;
gi = op[tkm6].im;
tau0r = br + gr;
tau3r = br - gr;
tau0i = bi + gi;
tau3i = bi - gi;
tau1r = cr + fr;
tau4r = cr - fr;
tau1i = ci + fi;
tau4i = ci - fi;
tau2r = dr + er;
tau5r = dr - er;
tau2i = di + ei;
tau5i = di - ei;
op[0].re = ar + tau0r + tau1r + tau2r;
op[0].im = ai + tau0i + tau1i + tau2i;
tau6r = ar + c1 * tau0r + c2 * tau1r + c3 * tau2r;
tau6i = ai + c1 * tau0i + c2 * tau1i + c3 * tau2i;
// tau7r = sgn * ( -s1 * tau3r - s2 * tau4r - s3 * tau5r);
// tau7i = sgn * ( -s1 * tau3i - s2 * tau4i - s3 * tau5i);
if (sgn == 1) {
tau7r = -s1 * tau3r - s2 * tau4r - s3 * tau5r;
tau7i = -s1 * tau3i - s2 * tau4i - s3 * tau5i;
} else {
tau7r = s1 * tau3r + s2 * tau4r + s3 * tau5r;
tau7i = s1 * tau3i + s2 * tau4i + s3 * tau5i;
}
op[tkm1].re = tau6r - tau7i;
op[tkm1].im = tau6i + tau7r;
op[tkm6].re = tau6r + tau7i;
op[tkm6].im = tau6i - tau7r;
tau6r = ar + c2 * tau0r + c3 * tau1r + c1 * tau2r;
tau6i = ai + c2 * tau0i + c3 * tau1i + c1 * tau2i;
// tau7r = sgn * ( -s2 * tau3r + s3 * tau4r + s1 * tau5r);
// tau7i = sgn * ( -s2 * tau3i + s3 * tau4i + s1 * tau5i);
if (sgn == 1) {
tau7r = -s2 * tau3r + s3 * tau4r + s1 * tau5r;
tau7i = -s2 * tau3i + s3 * tau4i + s1 * tau5i;
} else {
tau7r = s2 * tau3r - s3 * tau4r - s1 * tau5r;
tau7i = s2 * tau3i - s3 * tau4i - s1 * tau5i;
}
op[tkm2].re = tau6r - tau7i;
op[tkm2].im = tau6i + tau7r;
op[tkm5].re = tau6r + tau7i;
op[tkm5].im = tau6i - tau7r;
tau6r = ar + c3 * tau0r + c1 * tau1r + c2 * tau2r;
tau6i = ai + c3 * tau0i + c1 * tau1i + c2 * tau2i;
// tau7r = sgn * ( -s3 * tau3r + s1 * tau4r - s2 * tau5r);
// tau7i = sgn * ( -s3 * tau3i + s1 * tau4i - s2 * tau5i);
if (sgn == 1) {
tau7r = -s3 * tau3r + s1 * tau4r - s2 * tau5r;
tau7i = -s3 * tau3i + s1 * tau4i - s2 * tau5i;
} else {
tau7r = s3 * tau3r - s1 * tau4r + s2 * tau5r;
tau7i = s3 * tau3i - s1 * tau4i + s2 * tau5i;
}
op[tkm3].re = tau6r - tau7i;
op[tkm3].im = tau6i + tau7r;
op[tkm4].re = tau6r + tau7i;
op[tkm4].im = tau6i - tau7r;
for (k = 1; k < m; k++) {
ind = m - 1 + 6 * k;
wlr = (obj->twiddle + ind)->re;
wli = (obj->twiddle + ind)->im;
ind++;
wl2r = (obj->twiddle + ind)->re;
wl2i = (obj->twiddle + ind)->im;
ind++;
wl3r = (obj->twiddle + ind)->re;
wl3i = (obj->twiddle + ind)->im;
ind++;
wl4r = (obj->twiddle + ind)->re;
wl4i = (obj->twiddle + ind)->im;
ind++;
wl5r = (obj->twiddle + ind)->re;
wl5i = (obj->twiddle + ind)->im;
ind++;
wl6r = (obj->twiddle + ind)->re;
wl6i = (obj->twiddle + ind)->im;
tkm1 = k + m;
tkm2 = tkm1 + m;
tkm3 = tkm2 + m;
tkm4 = tkm3 + m;
tkm5 = tkm4 + m;
tkm6 = tkm5 + m;
ar = op[k].re;
ai = op[k].im;
br = op[tkm1].re * wlr - op[tkm1].im * wli;
bi = op[tkm1].im * wlr + op[tkm1].re * wli;
cr = op[tkm2].re * wl2r - op[tkm2].im * wl2i;
ci = op[tkm2].im * wl2r + op[tkm2].re * wl2i;
dr = op[tkm3].re * wl3r - op[tkm3].im * wl3i;
di = op[tkm3].im * wl3r + op[tkm3].re * wl3i;
er = op[tkm4].re * wl4r - op[tkm4].im * wl4i;
ei = op[tkm4].im * wl4r + op[tkm4].re * wl4i;
fr = op[tkm5].re * wl5r - op[tkm5].im * wl5i;
fi = op[tkm5].im * wl5r + op[tkm5].re * wl5i;
gr = op[tkm6].re * wl6r - op[tkm6].im * wl6i;
gi = op[tkm6].im * wl6r + op[tkm6].re * wl6i;
tau0r = br + gr;
tau3r = br - gr;
tau0i = bi + gi;
tau3i = bi - gi;
tau1r = cr + fr;
tau4r = cr - fr;
tau1i = ci + fi;
tau4i = ci - fi;
tau2r = dr + er;
tau5r = dr - er;
tau2i = di + ei;
tau5i = di - ei;
op[k].re = ar + tau0r + tau1r + tau2r;
op[k].im = ai + tau0i + tau1i + tau2i;
tau6r = ar + c1 * tau0r + c2 * tau1r + c3 * tau2r;
tau6i = ai + c1 * tau0i + c2 * tau1i + c3 * tau2i;
// tau7r = sgn * ( -s1 * tau3r - s2 * tau4r - s3 * tau5r);
// tau7i = sgn * ( -s1 * tau3i - s2 * tau4i - s3 * tau5i);
if (sgn == 1) {
tau7r = -s1 * tau3r - s2 * tau4r - s3 * tau5r;
tau7i = -s1 * tau3i - s2 * tau4i - s3 * tau5i;
} else {
tau7r = s1 * tau3r + s2 * tau4r + s3 * tau5r;
tau7i = s1 * tau3i + s2 * tau4i + s3 * tau5i;
}
op[tkm1].re = tau6r - tau7i;
op[tkm1].im = tau6i + tau7r;
op[tkm6].re = tau6r + tau7i;
op[tkm6].im = tau6i - tau7r;
tau6r = ar + c2 * tau0r + c3 * tau1r + c1 * tau2r;
tau6i = ai + c2 * tau0i + c3 * tau1i + c1 * tau2i;
// tau7r = sgn * ( -s2 * tau3r + s3 * tau4r + s1 * tau5r);
// tau7i = sgn * ( -s2 * tau3i + s3 * tau4i + s1 * tau5i);
if (sgn == 1) {
tau7r = -s2 * tau3r + s3 * tau4r + s1 * tau5r;
tau7i = -s2 * tau3i + s3 * tau4i + s1 * tau5i;
} else {
tau7r = s2 * tau3r - s3 * tau4r - s1 * tau5r;
tau7i = s2 * tau3i - s3 * tau4i - s1 * tau5i;
}
op[tkm2].re = tau6r - tau7i;
op[tkm2].im = tau6i + tau7r;
op[tkm5].re = tau6r + tau7i;
op[tkm5].im = tau6i - tau7r;
tau6r = ar + c3 * tau0r + c1 * tau1r + c2 * tau2r;
tau6i = ai + c3 * tau0i + c1 * tau1i + c2 * tau2i;
// tau7r = sgn * ( -s3 * tau3r + s1 * tau4r - s2 * tau5r);
// tau7i = sgn * ( -s3 * tau3i + s1 * tau4i - s2 * tau5i);
if (sgn == 1) {
tau7r = -s3 * tau3r + s1 * tau4r - s2 * tau5r;
tau7i = -s3 * tau3i + s1 * tau4i - s2 * tau5i;
} else {
tau7r = s3 * tau3r - s1 * tau4r + s2 * tau5r;
tau7i = s3 * tau3i - s1 * tau4i + s2 * tau5i;
}
op[tkm3].re = tau6r - tau7i;
op[tkm3].im = tau6i + tau7r;
op[tkm4].re = tau6r + tau7i;
op[tkm4].im = tau6i - tau7r;
}
} else if (radix == 8) {
int k, tkm1, tkm2, tkm3, tkm4, tkm5, tkm6, tkm7, ind;
fft_type wlr, wli, wl2r, wl2i, wl3r, wl3i, wl4r, wl4i, wl5r, wl5i, wl6r,
wl6i, wl7r, wl7i;
fft_type tau0r, tau0i, tau1r, tau1i, tau2r, tau2i, tau3r, tau3i;
fft_type ar, ai, br, bi, cr, ci, dr, di, er, ei, fr, fi, gr, gi, hr, hi;
fft_type tau4r, tau4i, tau5r, tau5i, tau6r, tau6i, tau7r, tau7i, tau8r,
tau8i, tau9r, tau9i;
fft_type c1, s1, temp1r, temp1i, temp2r, temp2i;
m = N / 8;
ll = 8 * l;
mixed_radix_dit_rec(op, ip, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + m, ip + l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 2 * m, ip + 2 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 3 * m, ip + 3 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 4 * m, ip + 4 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 5 * m, ip + 5 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 6 * m, ip + 6 * l, obj, sgn, m, ll, inc + 1);
mixed_radix_dit_rec(op + 7 * m, ip + 7 * l, obj, sgn, m, ll, inc + 1);
// printf("%d \n",inc);
// mixed_radix3_dit_rec(op,ip,obj,sgn,ll,m);
c1 = 0.70710678118654752440084436210485;
s1 = 0.70710678118654752440084436210485;
for (k = 0; k < m; k++) {
ind = m - 1 + 7 * k;
wlr = (obj->twiddle + ind)->re;
wli = (obj->twiddle + ind)->im;
ind++;
wl2r = (obj->twiddle + ind)->re;
wl2i = (obj->twiddle + ind)->im;
ind++;
wl3r = (obj->twiddle + ind)->re;
wl3i = (obj->twiddle + ind)->im;
ind++;
wl4r = (obj->twiddle + ind)->re;
wl4i = (obj->twiddle + ind)->im;
ind++;
wl5r = (obj->twiddle + ind)->re;
wl5i = (obj->twiddle + ind)->im;
ind++;
wl6r = (obj->twiddle + ind)->re;
wl6i = (obj->twiddle + ind)->im;
ind++;
wl7r = (obj->twiddle + ind)->re;
wl7i = (obj->twiddle + ind)->im;
tkm1 = k + m;
tkm2 = tkm1 + m;
tkm3 = tkm2 + m;
tkm4 = tkm3 + m;
tkm5 = tkm4 + m;
tkm6 = tkm5 + m;
tkm7 = tkm6 + m;
ar = op[k].re;
ai = op[k].im;
br = op[tkm1].re * wlr - op[tkm1].im * wli;
bi = op[tkm1].im * wlr + op[tkm1].re * wli;
cr = op[tkm2].re * wl2r - op[tkm2].im * wl2i;
ci = op[tkm2].im * wl2r + op[tkm2].re * wl2i;
dr = op[tkm3].re * wl3r - op[tkm3].im * wl3i;
di = op[tkm3].im * wl3r + op[tkm3].re * wl3i;
er = op[tkm4].re * wl4r - op[tkm4].im * wl4i;
ei = op[tkm4].im * wl4r + op[tkm4].re * wl4i;
fr = op[tkm5].re * wl5r - op[tkm5].im * wl5i;
fi = op[tkm5].im * wl5r + op[tkm5].re * wl5i;
gr = op[tkm6].re * wl6r - op[tkm6].im * wl6i;
gi = op[tkm6].im * wl6r + op[tkm6].re * wl6i;
hr = op[tkm7].re * wl7r - op[tkm7].im * wl7i;
hi = op[tkm7].im * wl7r + op[tkm7].re * wl7i;
tau0r = ar + er;
tau4r = ar - er;
tau0i = ai + ei;
tau4i = ai - ei;
tau1r = br + hr;
tau5r = br - hr;
tau1i = bi + hi;
tau5i = bi - hi;
tau2r = dr + fr;
tau6r = dr - fr;
tau6i = di - fi;
tau2i = di + fi;
tau3r = cr + gr;
tau7r = cr - gr;
tau7i = ci - gi;
tau3i = ci + gi;
op[k].re = tau0r + tau1r + tau2r + tau3r;
op[k].im = tau0i + tau1i + tau2i + tau3i;
op[tkm4].re = tau0r - tau1r - tau2r + tau3r;
op[tkm4].im = tau0i - tau1i - tau2i + tau3i;
temp1r = tau1r - tau2r;
temp1i = tau1i - tau2i;
temp2r = tau5r + tau6r;
temp2i = tau5i + tau6i;
tau8r = tau4r + c1 * temp1r;
tau8i = tau4i + c1 * temp1i;
// tau9r = sgn * ( -s1 * temp2r - tau7r);
// tau9i = sgn * ( -s1 * temp2i - tau7i);
if (sgn == 1) {
tau9r = -s1 * temp2r - tau7r;
tau9i = -s1 * temp2i - tau7i;
} else {
tau9r = s1 * temp2r + tau7r;
tau9i = s1 * temp2i + tau7i;
}
op[tkm1].re = tau8r - tau9i;
op[tkm1].im = tau8i + tau9r;
op[tkm7].re = tau8r + tau9i;
op[tkm7].im = tau8i - tau9r;
tau8r = tau0r - tau3r;
tau8i = tau0i - tau3i;
// tau9r = sgn * ( -tau5r + tau6r);
// tau9i = sgn * ( -tau5i + tau6i);
if (sgn == 1) {
tau9r = -tau5r + tau6r;
tau9i = -tau5i + tau6i;
} else {
tau9r = tau5r - tau6r;
tau9i = tau5i - tau6i;
}
op[tkm2].re = tau8r - tau9i;
op[tkm2].im = tau8i + tau9r;
op[tkm6].re = tau8r + tau9i;
op[tkm6].im = tau8i - tau9r;
tau8r = tau4r - c1 * temp1r;
tau8i = tau4i - c1 * temp1i;
// tau9r = sgn * ( -s1 * temp2r + tau7r);
// tau9i = sgn * ( -s1 * temp2i + tau7i);
if (sgn == 1) {
tau9r = -s1 * temp2r + tau7r;
tau9i = -s1 * temp2i + tau7i;
} else {
tau9r = s1 * temp2r - tau7r;
tau9i = s1 * temp2i - tau7i;
}
op[tkm3].re = tau8r - tau9i;
op[tkm3].im = tau8i + tau9r;
op[tkm5].re = tau8r + tau9i;
op[tkm5].im = tau8i - tau9r;
}
} else {
int k, i, ind;
int M, tkm, u, v, t, tt;
fft_type temp1r, temp1i, temp2r, temp2i;
fft_type *wlr = (fft_type *)malloc(sizeof(fft_type) * (radix - 1));
fft_type *wli = (fft_type *)malloc(sizeof(fft_type) * (radix - 1));
fft_type *taur = (fft_type *)malloc(sizeof(fft_type) * (radix - 1));
fft_type *taui = (fft_type *)malloc(sizeof(fft_type) * (radix - 1));
fft_type *c1 = (fft_type *)malloc(sizeof(fft_type) * (radix - 1));
fft_type *s1 = (fft_type *)malloc(sizeof(fft_type) * (radix - 1));
fft_type *yr = (fft_type *)malloc(sizeof(fft_type) * (radix));
fft_type *yi = (fft_type *)malloc(sizeof(fft_type) * (radix));
m = N / radix;
ll = radix * l;
for (i = 0; i < radix; ++i) {
mixed_radix_dit_rec(op + i * m, ip + i * l, obj, sgn, m, ll, inc + 1);
}
M = (radix - 1) / 2;
for (i = 1; i < M + 1; ++i) {
c1[i - 1] = cos(i * PI2 / radix);
s1[i - 1] = sin(i * PI2 / radix);
}
for (i = 0; i < M; ++i) {
s1[i + M] = -s1[M - 1 - i];
c1[i + M] = c1[M - 1 - i];
}
for (k = 0; k < m; ++k) {
ind = m - 1 + (radix - 1) * k;
yr[0] = op[k].re;
yi[0] = op[k].im;
for (i = 0; i < radix - 1; ++i) {
wlr[i] = (obj->twiddle + ind)->re;
wli[i] = (obj->twiddle + ind)->im;
tkm = k + (i + 1) * m;
yr[i + 1] = op[tkm].re * wlr[i] - op[tkm].im * wli[i];
yi[i + 1] = op[tkm].im * wlr[i] + op[tkm].re * wli[i];
ind++;
}
for (i = 0; i < M; ++i) {
taur[i] = yr[i + 1] + yr[radix - 1 - i];
taui[i + M] = yi[i + 1] - yi[radix - 1 - i];
taui[i] = yi[i + 1] + yi[radix - 1 - i];
taur[i + M] = yr[i + 1] - yr[radix - 1 - i];
}
temp1r = yr[0];
temp1i = yi[0];
for (i = 0; i < M; ++i) {
temp1r += taur[i];
temp1i += taui[i];
}
op[k].re = temp1r;
op[k].im = temp1i;
for (u = 0; u < M; u++) {
temp1r = yr[0];
temp1i = yi[0];
temp2r = 0.0;
temp2i = 0.0;
for (v = 0; v < M; v++) {
// int ind2 = (u+v)%M;
t = (u + 1) * (v + 1);
while (t >= radix) t -= radix;
tt = t - 1;
temp1r += c1[tt] * taur[v];
temp1i += c1[tt] * taui[v];
temp2r -= s1[tt] * taur[v + M];
temp2i -= s1[tt] * taui[v + M];
}
temp2r = sgn * temp2r;
temp2i = sgn * temp2i;
op[k + (u + 1) * m].re = temp1r - temp2i;
op[k + (u + 1) * m].im = temp1i + temp2r;
op[k + (radix - u - 1) * m].re = temp1r + temp2i;
op[k + (radix - u - 1) * m].im = temp1i - temp2r;
}
}
free(wlr);
free(wli);
free(taur);
free(taui);
free(c1);
free(s1);
free(yr);
free(yi);
}
}
void fft_exec(fft_object obj, fft_data *inp, fft_data *oup) {
if (obj->lt == 0) {
// fftct_radix3_dit_rec(inp,oup,obj, obj->sgn, obj->N);
// fftct_mixed_rec(inp,oup,obj, obj->sgn, obj->N);
// printf("%f \n", 1.785);
int l, inc;
int nn, sgn1;
nn = obj->N;
sgn1 = obj->sgn;
l = 1;
inc = 0;
// radix3_dit_rec(oup,inp,obj,sgn1,nn,l);
mixed_radix_dit_rec(oup, inp, obj, sgn1, nn, l, inc);
} else if (obj->lt == 1) {
// printf("%f \n", 1.785);
int nn, sgn1;
nn = obj->N;
sgn1 = obj->sgn;
bluestein_fft(inp, oup, obj, sgn1, nn);
}
}
void free_fft(fft_object object) { free(object); }
// CWT
cwt_type factorial(int N) {
// static const cwt_type fact[41] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
// 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200,
// 1307674368000,
// 20922789888000, 355687428096000, 6402373705728000, 121645100408832000,
// 2432902008176640000, 51090942171709440000.0, 1124000727777607680000.0,
// 25852016738884976640000.0, 620448401733239439360000.0,
// 15511210043330985984000000.0, 403291461126605635584000000.0,
// 10888869450418352160768000000.0, 304888344611713860501504000000.0,
// 8841761993739701954543616000000.0, 265252859812191058636308480000000.0,
// 8222838654177922817725562880000000.0,
// 263130836933693530167218012160000000.0,
// 8683317618811886495518194401280000000.0,
// 295232799039604140847618609643520000000.0,
// 10333147966386144929666651337523200000000.0,
// 371993326789901217467999448150835200000000.0,
// 13763753091226345046315979581580902400000000.0,
// 523022617466601111760007224100074291200000000.0,
// 20397882081197443358640281739902897356800000000.0,
// 815915283247897734345611269596115894272000000000.0 };
static const cwt_type fact[14] = {
1, 1, 2, 6, 24, 120, 720,
5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800};
// if (N > 40 || N < 0) {
// printf("This program is only valid for 0 <= N <= 40 \n");
// return -1.0;
// }
if (N > 14 || N < 0) {
printf("This program is only valid for 0 <= N <= 14 \n");
return -1.0;
}
return fact[N];
}
static cwt_type fix(cwt_type x) {
// Rounds to the integer nearest to zero
if (x >= 0.) {
return floor(x);
} else {
return ceil(x);
}
}
cwt_type cwt_gamma(cwt_type x) {
/*
* This C program code is based on W J Cody's fortran code.
* http://www.netlib.org/specfun/gamma
*
* References:
"An Overview of Software Development for Special Functions",
W. J. Cody, Lecture Notes in Mathematics, 506,
Numerical Analysis Dundee, 1975, G. A. Watson (ed.),
Springer Verlag, Berlin, 1976.
Computer Approximations, Hart, Et. Al., Wiley and sons, New York, 1968.
*/
// numerator and denominator coefficients for 1 <= x <= 2
cwt_type y, oup, fact, sum, y2, yi, z, nsum, dsum;
int swi, n, i;
cwt_type spi = 0.9189385332046727417803297;
cwt_type pi = 3.1415926535897932384626434;
cwt_type xmax = 171.624e+0;
cwt_type xinf = 1.79e308;
cwt_type eps = 2.22e-16;
cwt_type xninf = 1.79e-308;
cwt_type num[8] = {
-1.71618513886549492533811e+0, 2.47656508055759199108314e+1,
-3.79804256470945635097577e+2, 6.29331155312818442661052e+2,
8.66966202790413211295064e+2, -3.14512729688483675254357e+4,
-3.61444134186911729807069e+4, 6.64561438202405440627855e+4};
cwt_type den[8] = {
-3.08402300119738975254353e+1, 3.15350626979604161529144e+2,
-1.01515636749021914166146e+3, -3.10777167157231109440444e+3,
2.25381184209801510330112e+4, 4.75584627752788110767815e+3,
-1.34659959864969306392456e+5, -1.15132259675553483497211e+5};
// Coefficients for Hart's Minimax approximation x >= 12
cwt_type c[7] = {-1.910444077728e-03,
8.4171387781295e-04,
-5.952379913043012e-04,
7.93650793500350248e-04,
-2.777777777777681622553e-03,
8.333333333333333331554247e-02,
5.7083835261e-03};
y = x;
swi = 0;
fact = 1.0;
n = 0;
if (y < 0.) {
// Negative x
y = -x;
yi = fix(y);
oup = y - yi;
if (oup != 0.0) {
if (yi != fix(yi * .5) * 2.) {
swi = 1;
}
fact = -pi / sin(pi * oup);
y += 1.;
} else {
return xinf;
}
}
if (y < eps) {
if (y >= xninf) {
oup = 1.0 / y;
} else {
return xinf;
}
} else if (y < 12.) {
yi = y;
if (y < 1.) {
z = y;
y += 1.;
} else {
n = (int)y - 1;
y -= (cwt_type)n;
z = y - 1.0;
}
nsum = 0.;
dsum = 1.;
for (i = 0; i < 8; ++i) {
nsum = (nsum + num[i]) * z;
dsum = dsum * z + den[i];
}
oup = nsum / dsum + 1.;
if (yi < y) {
oup /= yi;
} else if (yi > y) {
for (i = 0; i < n; ++i) {
oup *= y;
y += 1.;
}
}
} else {
if (y <= xmax) {
y2 = y * y;
sum = c[6];
for (i = 0; i < 6; ++i) {
sum = sum / y2 + c[i];
}
sum = sum / y - y + spi;
sum += (y - .5) * log(y);
oup = exp(sum);
} else {
return (xinf);
}
}
if (swi) {
oup = -oup;
}
if (fact != 1.) {
oup = fact / oup;
}
return oup;
}
static void wave_function(int nk, cwt_type dt, int mother, cwt_type param,
cwt_type scale1, cwt_type *kwave, cwt_type pi,
cwt_type *period1, cwt_type *coi1,
fft_data *daughter) {
cwt_type norm, expnt, fourier_factor;
int k, m;
cwt_type temp;
int sign, re;
if (mother == 0) {
// MORLET
if (param < 0.0) {
param = 6.0;
}
norm = sqrt(2.0 * pi * scale1 / dt) * pow(pi, -0.25);
for (k = 1; k <= nk / 2 + 1; ++k) {
temp = (scale1 * kwave[k - 1] - param);
expnt = -0.5 * temp * temp;
daughter[k - 1].re = norm * exp(expnt);
daughter[k - 1].im = 0.0;
}
for (k = nk / 2 + 2; k <= nk; ++k) {
daughter[k - 1].re = daughter[k - 1].im = 0.0;
}
fourier_factor = (4.0 * pi) / (param + sqrt(2.0 + param * param));
*period1 = scale1 * fourier_factor;
*coi1 = fourier_factor / sqrt(2.0);
} else if (mother == 1) {
// PAUL
if (param < 0.0) {
param = 4.0;
}
m = (int)param;
norm = sqrt(2.0 * pi * scale1 / dt) *
(pow(2.0, (cwt_type)m) / sqrt((cwt_type)(m * factorial(2 * m - 1))));
for (k = 1; k <= nk / 2 + 1; ++k) {
temp = scale1 * kwave[k - 1];
expnt = -temp;
daughter[k - 1].re = norm * pow(temp, (cwt_type)m) * exp(expnt);
daughter[k - 1].im = 0.0;
}
for (k = nk / 2 + 2; k <= nk; ++k) {
daughter[k - 1].re = daughter[k - 1].im = 0.0;
}
fourier_factor = (4.0 * pi) / (2.0 * m + 1.0);
*period1 = scale1 * fourier_factor;
*coi1 = fourier_factor * sqrt(2.0);
} else if (mother == 2) {
if (param < 0.0) {
param = 2.0;
}
m = (int)param;
if (m % 2 == 0) {
re = 1;
} else {
re = 0;
}
if (m % 4 == 0 || m % 4 == 1) {
sign = -1;
} else {
sign = 1;
}
norm = sqrt(2.0 * pi * scale1 / dt) * sqrt(1.0 / cwt_gamma(m + 0.50));
norm *= sign;
if (re == 1) {
for (k = 1; k <= nk; ++k) {
temp = scale1 * kwave[k - 1];
daughter[k - 1].re =
norm * pow(temp, (cwt_type)m) * exp(-0.50 * pow(temp, 2.0));
daughter[k - 1].im = 0.0;
}
} else if (re == 0) {
for (k = 1; k <= nk; ++k) {
temp = scale1 * kwave[k - 1];
daughter[k - 1].re = 0.0;
daughter[k - 1].im =
norm * pow(temp, (cwt_type)m) * exp(-0.50 * pow(temp, 2.0));
}
}
fourier_factor = (2.0 * pi) * sqrt(2.0 / (2.0 * m + 1.0));
*period1 = scale1 * fourier_factor;
*coi1 = fourier_factor / sqrt(2.0);
}
}
cwt_object cwt_init(const char *wave, cwt_type param, int siglength,
cwt_type dt, int J) {
cwt_object obj = NULL;
int N, i, nj2, ibase2, mother = 0;
cwt_type s0 = 2 * dt, dj;
cwt_type t1;
int m, odd;
const char *pdefault = "pow";
m = (int)param;
odd = 1;
if (2 * (m / 2) == m) {
odd = 0;
}
N = siglength;
nj2 = 2 * N * J;
obj = (cwt_object)malloc(sizeof(struct cwt_set) +
sizeof(cwt_type) * (nj2 + 2 * J + N));
if (!strcmp(wave, "morlet") || !strcmp(wave, "morl")) {
s0 = 2 * dt;
dj = 0.4875;
mother = 0;
if (param < 0.0) {
printf("\n Morlet Wavelet Parameter should be >= 0 \n");
exit(-1);
}
if (param == 0) {
param = 6.0;
}
strcpy(obj->wave, "morlet");
} else if (!strcmp(wave, "paul")) {
s0 = 2 * dt;
dj = 0.4875;
mother = 1;
if (param < 0 || param > 20) {
printf("\n Paul Wavelet Parameter should be > 0 and <= 20 \n");
exit(-1);
}
if (param == 0) {
param = 4.0;
}
strcpy(obj->wave, "paul");
} else if (!strcmp(wave, "dgauss") || !strcmp(wave, "dog")) {
s0 = 2 * dt;
dj = 0.4875;
mother = 2;
if (param < 0 || odd == 1) {
printf("\n DOG Wavelet Parameter should be > 0 and even \n");
exit(-1);
}
if (param == 0) {
param = 2.0;
}
strcpy(obj->wave, "dog");
}
obj->pow = 2;
strcpy(obj->type, pdefault);
obj->s0 = s0;
obj->dj = dj;
obj->dt = dt;
obj->J = J;
obj->siglength = siglength;
obj->sflag = 0;
obj->pflag = 1;
obj->mother = mother;
obj->m = param;
t1 = 0.499999 + log((cwt_type)N) / log(2.0);
ibase2 = 1 + (int)t1;
obj->npad = (int)pow(2.0, (cwt_type)ibase2);
obj->output = (cplx_data *)&obj->params[0];
obj->scale = &obj->params[nj2];
obj->period = &obj->params[nj2 + J];
obj->coi = &obj->params[nj2 + 2 * J];
for (i = 0; i < nj2 + 2 * J + N; ++i) {
obj->params[i] = 0.0;
}
return obj;
}
void setCWTScales(cwt_object wt, cwt_type s0, cwt_type dj, const char *type,
int power) {
int i;
strcpy(wt->type, type);
// s0*pow(2.0, (double)(j - 1)*dj);
if (!strcmp(wt->type, "pow") || !strcmp(wt->type, "power")) {
for (i = 0; i < wt->J; ++i) {
wt->scale[i] = s0 * pow((cwt_type)power, (cwt_type)(i)*dj);
}
wt->sflag = 1;
wt->pow = power;
} else if (!strcmp(wt->type, "lin") || !strcmp(wt->type, "linear")) {
for (i = 0; i < wt->J; ++i) {
wt->scale[i] = s0 + (cwt_type)i * dj;
}
wt->sflag = 1;
} else {
printf("\n Type accepts only two values : pow and lin\n");
exit(-1);
}
wt->s0 = s0;
wt->dj = dj;
}
void cwt(cwt_object wt, const cwt_type *inp) {
int i, N, npad, nj2, j, j2;
N = wt->siglength;
if (wt->sflag == 0) {
for (i = 0; i < wt->J; ++i) {
wt->scale[i] = wt->s0 * pow(2.0, (cwt_type)(i)*wt->dj);
}
wt->sflag = 1;
}
if (wt->pflag == 0) {
npad = N;
} else {
npad = wt->npad;
}
nj2 = 2 * N * wt->J;
j = wt->J;
j2 = 2 * j;
wt->smean = 0.0;
for (i = 0; i < N; ++i) {
wt->smean += inp[i];
}
wt->smean /= N;
cwavelet(inp, N, wt->dt, wt->mother, wt->m, wt->s0, wt->dj, wt->J, npad,
wt->params, wt->params + nj2, wt->params + nj2 + j,
wt->params + nj2 + j2);
}
void cwavelet(const cwt_type *y, int N, cwt_type dt, int mother, cwt_type param,
cwt_type s0, cwt_type dj, int jtot, int npad, cwt_type *wave,
cwt_type *scale, cwt_type *period, cwt_type *coi) {
int i, j, k, iter;
cwt_type ymean, freq1, pi, period1, coi1;
cwt_type tmp1, tmp2;
cwt_type scale1;
cwt_type *kwave;
fft_object obj, iobj;
fft_data *ypad, *yfft, *daughter;
(void)s0;
(void)dj; /* yes, we need these parameters unused */
pi = 4.0 * atan(1.0);
if (npad < N) {
printf("npad must be >= N \n");
exit(-1);
}
obj = fft_init(npad, 1);
iobj = fft_init(npad, -1);
ypad = (fft_data *)malloc(sizeof(fft_data) * npad);
yfft = (fft_data *)malloc(sizeof(fft_data) * npad);
daughter = (fft_data *)malloc(sizeof(fft_data) * npad);
kwave = (cwt_type *)malloc(sizeof(cwt_type) * npad);
ymean = 0.0;
for (i = 0; i < N; ++i) {
ymean += y[i];
}
ymean /= N;
for (i = 0; i < N; ++i) {
ypad[i].re = y[i] - ymean;
ypad[i].im = 0.0;
}
for (i = N; i < npad; ++i) {
ypad[i].re = ypad[i].im = 0.0;
}
// Find FFT of the input y (ypad)
fft_exec(obj, ypad, yfft);
for (i = 0; i < npad; ++i) {
yfft[i].re /= (cwt_type)npad;
yfft[i].im /= (cwt_type)npad;
}
// Construct the wavenumber array
freq1 = 2.0 * pi / ((cwt_type)npad * dt);
kwave[0] = 0.0;
for (i = 1; i < npad / 2 + 1; ++i) {
kwave[i] = i * freq1;
}
for (i = npad / 2 + 1; i < npad; ++i) {
kwave[i] = -kwave[npad - i];
}
// Main loop
for (j = 1; j <= jtot; ++j) {
scale1 = scale[j - 1]; // = s0*pow(2.0, (double)(j - 1)*dj);
wave_function(npad, dt, mother, param, scale1, kwave, pi, &period1, &coi1,
daughter);
period[j - 1] = period1;
for (k = 0; k < npad; ++k) {
tmp1 = daughter[k].re * yfft[k].re - daughter[k].im * yfft[k].im;
tmp2 = daughter[k].re * yfft[k].im + daughter[k].im * yfft[k].re;
daughter[k].re = tmp1;
daughter[k].im = tmp2;
}
fft_exec(iobj, daughter, ypad);
iter = 2 * (j - 1) * N;
for (i = 0; i < N; ++i) {
wave[iter + 2 * i] = ypad[i].re;
wave[iter + 2 * i + 1] = ypad[i].im;
}
}
for (i = 1; i <= (N + 1) / 2; ++i) {
coi[i - 1] = coi1 * dt * ((cwt_type)i - 1.0);
coi[N - i] = coi[i - 1];
}
free(kwave);
free(ypad);
free(yfft);
free(daughter);
free_fft(obj);
free_fft(iobj);
}
void cwt_summary(cwt_object wt) {
printf("\n");
printf("Wavelet : %s Parameter %lf \n", wt->wave, wt->m);
printf("\n");
printf("Length of Input Signal : %d \n", wt->siglength);
printf("\n");
printf("Sampling Rate : %g \n", wt->dt);
printf("\n");
printf("Total Number of Scales : %d \n", wt->J);
printf("\n");
printf("Smallest Scale (s0) : %lf \n", wt->s0);
printf("\n");
printf("Separation Between Scales (dj) %lf \n", wt->dj);
printf("\n");
printf("Scale Type %s \n", wt->type);
printf("\n");
printf(
"Complex CWT Output Vector is of size %d * %d stored in Row Major format "
"\n",
wt->J, wt->siglength);
printf("\n");
printf(
"The ith real value can be accessed using wt->output[i].re and imaginary "
"value by wt->output[i].im \n");
printf("\n");
}
void cwt_free(cwt_object object) { free(object); }
} // namespace sigmap
| 56,241
|
C++
|
.cc
| 1,849
| 24.978908
| 80
| 0.491282
|
haowenz/sigmap
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,203
|
spatial_index.cc
|
haowenz_sigmap/src/spatial_index.cc
|
#include "spatial_index.h"
#include <assert.h>
#include <algorithm>
#include <iostream>
#include "utils.h"
namespace sigmap {
bool compare(const std::pair<float, size_t> &left,
const std::pair<float, size_t> &right) {
if (left.first > right.first) {
return true;
} else if (left.first == right.first) {
return (left.second > right.second);
} else {
return false;
}
}
bool compare1(const std::pair<float, size_t> &left,
const std::pair<float, size_t> &right) {
if (left.first > right.first) {
return true;
} else if (left.first == right.first) {
return (left.second < right.second);
} else {
return false;
}
}
void SpatialIndex::GeneratePointCloudOnOneDirection(
Direction direction, uint32_t signal_index,
const std::vector<std::vector<bool> > &is_masked,
const float *signal_values, size_t signal_length, int step_size,
std::vector<Point> &point_cloud) {
if (signal_length >= (uint32_t)dimension_) {
for (size_t signal_position = 0;
signal_position < signal_length - dimension_ + 1;
signal_position += step_size) {
if (!is_masked[signal_index][signal_position]) {
if (signal_position == 0 || point_cloud.empty() ||
(signal_position > 0 &&
std::fabs(signal_values[signal_position] -
point_cloud.back().value) > 0.01)) {
uint64_t strand = direction == Positive ? 0 : 1;
uint64_t position =
((((uint64_t)signal_index) << 32 | (uint32_t)signal_position)
<< 1) |
strand;
point_cloud.emplace_back(position, signal_values[signal_position]);
}
}
}
}
}
// void SpatialIndex::GetSignalIndexAndPosition(size_t point_index, size_t
// num_signals, const std::vector<std::vector<float> > &signals, size_t
// &signal_index, size_t &signal_position) {
// for (signal_index = 0; signal_index < num_signals; ++signal_index) {
// signal_position = signals[signal_index].size() - dimension_ + 1;
// if (point_index > signal_position) {
// point_index -= signal_position;
// } else {
// signal_position = point_index;
// break;
// }
// }
//}
void SpatialIndex::Construct(
size_t num_signals,
const std::vector<std::vector<bool> > &positive_is_masked,
const std::vector<std::vector<bool> > &negative_is_masked,
const std::vector<std::vector<float> > &positive_signals,
const std::vector<std::vector<float> > &negative_signals) {
double real_start_time = GetRealTime();
int signal_point_step_size = 1;
point_cloud_.reserve(2 * GetSignalsTotalLength(positive_signals));
for (size_t signal_index = 0; signal_index < num_signals; ++signal_index) {
GeneratePointCloudOnOneDirection(Positive, signal_index, positive_is_masked,
positive_signals[signal_index].data(),
positive_signals[signal_index].size(),
signal_point_step_size, point_cloud_);
}
for (size_t signal_index = 0; signal_index < num_signals; ++signal_index) {
GeneratePointCloudOnOneDirection(Negative, signal_index, negative_is_masked,
negative_signals[signal_index].data(),
negative_signals[signal_index].size(),
signal_point_step_size, point_cloud_);
}
std::cerr << "Collected " << point_cloud_.size() << " points.\n";
// sort(point_cloud_.begin(), point_cloud_.end());
// std::cerr << "Sorted " << point_cloud_.size() << " points.\n";
spatial_index_ = new SigmapAdaptor<float>(dimension_ /*dim*/, point_cloud_,
max_leaf_ /* max leaf */);
spatial_index_->index->buildIndex();
std::cerr << "Built spatial index.\n";
std::cerr << "Built index successfully in " << GetRealTime() - real_start_time
<< "s.\n";
}
void SpatialIndex::Save() {
double real_start_time = GetRealTime();
FILE *point_cloud_file =
fopen((index_file_path_prefix_ + ".pt").c_str(), "wb");
assert(point_cloud_file != NULL);
fwrite(&dimension_, sizeof(int), 1, point_cloud_file);
fwrite(&max_leaf_, sizeof(int), 1, point_cloud_file);
size_t point_cloud_size = point_cloud_.size();
fwrite(&point_cloud_size, sizeof(size_t), 1, point_cloud_file);
// TODO(Haowen): we don't have to save the whole point cloud. Instead, we can
// just save the feature signal and build the point cloud on the fly. I will
// leave this as an easy later code refactor work.
// for (size_t pi = 0; pi < point_cloud_size; ++pi) {
// fwrite(point_cloud_[pi].data(), sizeof(float), dimension_,
// point_cloud_file);
//}
fwrite(point_cloud_.data(), sizeof(Point), point_cloud_size,
point_cloud_file);
fclose(point_cloud_file);
FILE *spatial_index_file =
fopen((index_file_path_prefix_ + ".si").c_str(), "wb");
assert(spatial_index_file != NULL);
spatial_index_->index->saveIndex(spatial_index_file);
fclose(spatial_index_file);
std::cerr << "Saved in " << GetRealTime() - real_start_time << "s.\n";
}
void SpatialIndex::Load() {
double real_start_time = GetRealTime();
FILE *point_cloud_file =
fopen((index_file_path_prefix_ + ".pt").c_str(), "rb");
fread(&dimension_, sizeof(int), 1, point_cloud_file);
fread(&max_leaf_, sizeof(int), 1, point_cloud_file);
size_t point_cloud_size = 0;
fread(&point_cloud_size, sizeof(size_t), 1, point_cloud_file);
point_cloud_.resize(point_cloud_size);
// for (size_t pi = 0; pi < point_cloud_size; ++pi) {
// point_cloud_[pi].resize(dimension_);
// fread(point_cloud_[pi].data(), sizeof(float), dimension_,
// point_cloud_file);
//}
fread(point_cloud_.data(), sizeof(Point), point_cloud_size, point_cloud_file);
fclose(point_cloud_file);
std::cerr << "Load point cloud successfully! dim: " << dimension_
<< ", max leaf: " << max_leaf_
<< ", point cloud size: " << point_cloud_size << "\n";
FILE *spatial_index_file =
fopen((index_file_path_prefix_ + ".si").c_str(), "rb");
assert(spatial_index_file != NULL);
spatial_index_ = new SigmapAdaptor<float>(dimension_ /*dim*/, point_cloud_,
max_leaf_ /* max leaf */);
spatial_index_->index->loadIndex(spatial_index_file);
size_t used_memory =
spatial_index_->index->usedMemory(*(spatial_index_->index));
std::cerr << "Memory: " << used_memory << ".\n";
fclose(spatial_index_file);
std::cerr << "Loaded index successfully in "
<< GetRealTime() - real_start_time << "s.\n";
}
void SpatialIndex::TracebackChains(
int min_num_anchors, Direction direction, size_t chain_end_anchor_index,
uint32_t chain_target_signal_index,
const std::vector<float> &chaining_scores,
const std::vector<size_t> &chaining_predecessors,
const std::vector<std::vector<SignalAnchor> > &anchors_on_diff_signals,
std::vector<bool> &anchor_is_used, std::vector<SignalAnchorChain> &chains) {
if (!anchor_is_used[chain_end_anchor_index]) {
std::vector<SignalAnchor> anchors;
anchors.reserve(100);
bool stop_at_an_used_anchor = false;
size_t chain_start_anchor_index = chain_end_anchor_index;
// Add the end anchor
anchors.push_back(anchors_on_diff_signals[chain_target_signal_index]
[chain_start_anchor_index]);
// The end anchor has an used predecessor
if (chaining_predecessors[chain_start_anchor_index] !=
chain_start_anchor_index &&
anchor_is_used[chaining_predecessors[chain_start_anchor_index]]) {
stop_at_an_used_anchor = true;
}
anchor_is_used[chain_start_anchor_index] = true;
uint32_t chain_num_anchors = 1;
while (chaining_predecessors[chain_start_anchor_index] !=
chain_start_anchor_index &&
!anchor_is_used[chaining_predecessors[chain_start_anchor_index]]) {
chain_start_anchor_index =
chaining_predecessors[chain_start_anchor_index];
anchors.push_back(anchors_on_diff_signals[chain_target_signal_index]
[chain_start_anchor_index]);
if (chaining_predecessors[chain_start_anchor_index] !=
chain_start_anchor_index &&
anchor_is_used[chaining_predecessors[chain_start_anchor_index]]) {
stop_at_an_used_anchor = true;
}
anchor_is_used[chain_start_anchor_index] = true;
++chain_num_anchors;
}
if (chain_num_anchors >= (uint32_t)min_num_anchors) {
float adjusted_chaining_score = chaining_scores[chain_end_anchor_index];
if (stop_at_an_used_anchor) {
adjusted_chaining_score -=
chaining_scores[chaining_predecessors[chain_start_anchor_index]];
}
chains.emplace_back(
SignalAnchorChain{adjusted_chaining_score, chain_target_signal_index,
anchors_on_diff_signals[chain_target_signal_index]
[chain_start_anchor_index]
.target_position,
anchors_on_diff_signals[chain_target_signal_index]
[chain_end_anchor_index]
.target_position,
chain_num_anchors, 0, direction, anchors});
}
}
}
void SpatialIndex::GeneratePrimaryChains(
std::vector<SignalAnchorChain> &chains) {
std::sort(chains.begin(), chains.end(), std::greater<SignalAnchorChain>());
std::vector<SignalAnchorChain> primary_chains;
primary_chains.reserve(chains.size());
primary_chains.emplace_back(chains[0]);
for (uint32_t ci = 1; ci < chains.size(); ++ci) {
bool is_primary = true;
if (chains[ci].score < primary_chains.back().score / 3) {
break;
} else {
for (uint32_t pi = 0; pi < primary_chains.size(); ++pi) {
if (chains[ci].reference_sequence_index ==
primary_chains[pi].reference_sequence_index) {
if (std::max(chains[ci].start_position,
primary_chains[pi].start_position) >
std::min(chains[ci].end_position,
primary_chains[pi].end_position)) {
// primary_chains[pi].score += chains[ci].score;
} else {
is_primary = false;
break;
}
}
}
}
if (is_primary) {
primary_chains.emplace_back(chains[ci]);
}
}
chains.swap(primary_chains);
}
void SpatialIndex::ComputeMAPQ(std::vector<SignalAnchorChain> &chains) {
if (chains.size() == 1) {
chains[0].mapq = 60;
return;
} else {
int mapq =
40 *
(1 -
chains[1].score /
chains[0].score); // * std::min((size_t)1, chains[0].num_anchors /
// 20) * log(chains[0].score);
if (mapq > 60) {
mapq = 60;
}
if (mapq < 0) {
mapq = 0;
}
chains[0].mapq = (uint8_t)mapq;
}
}
void SpatialIndex::GenerateChains(const std::vector<float> &query_signal,
const std::vector<float> &query_signal_stdvs,
uint32_t query_start_offset,
int query_point_cloud_step_size,
float search_radius,
size_t num_target_signals,
std::vector<SignalAnchorChain> &chains) {
// Chaining parameters
int max_gap_length = 2000;
int max_target_gap_length = 5000;
int chaining_band_length = 5000;
int max_num_skips = 25;
int min_num_anchors = 2;
int num_best_chains = 3;
int num_nearest_points = 5000;
float min_chaining_score = 10;
std::vector<std::vector<std::vector<SignalAnchor> > > anchors_on_diff_signals(
2);
anchors_on_diff_signals[0] =
std::vector<std::vector<SignalAnchor> >(num_target_signals);
anchors_on_diff_signals[1] =
std::vector<std::vector<SignalAnchor> >(num_target_signals);
std::vector<std::vector<SignalAnchor> > &positive_anchors_on_diff_signals =
anchors_on_diff_signals[0];
std::vector<std::vector<SignalAnchor> > &negative_anchors_on_diff_signals =
anchors_on_diff_signals[1];
// Get anchors in previous chains
std::vector<SignalAnchorChain> previous_chains;
previous_chains.swap(chains);
if (previous_chains.size() > 0) {
for (uint32_t chain_index = 0; chain_index < previous_chains.size();
++chain_index) {
int strand = previous_chains[chain_index].direction == Positive ? 0 : 1;
uint32_t reference_sequence_index =
previous_chains[chain_index].reference_sequence_index;
assert(previous_chains[chain_index].num_anchors ==
previous_chains[chain_index].anchors.size());
anchors_on_diff_signals[strand][reference_sequence_index].reserve(
previous_chains[chain_index].num_anchors);
for (uint32_t anchor_index = 0;
anchor_index < previous_chains[chain_index].num_anchors;
++anchor_index) {
anchors_on_diff_signals[strand][reference_sequence_index].emplace_back(
previous_chains[chain_index].anchors[anchor_index]);
}
}
}
nanoflann::SearchParams params;
params.sorted = false;
std::vector<std::pair<size_t, float> > point_anchors;
// Find reliable seeds
std::vector<std::pair<float, size_t> > mean_diff_position;
mean_diff_position.reserve(
(query_signal.size() - dimension_ + 1) / query_point_cloud_step_size + 1);
for (uint32_t pi = 0; pi < query_signal.size() - dimension_ + 1; ++pi) {
float min_diff = std::numeric_limits<float>::max();
// for (int di = 0; di < dimension_; ++di) {
for (int di = 1; di < dimension_; ++di) {
float diff = std::fabs(query_signal[pi + di] - query_signal[pi + di - 1]);
// if (diff < min_diff) {
min_diff += diff;
//}
// float diff = query_signal_stdvs[pi + di];
// if (diff < min_diff) {
// min_diff = diff;
//}
// min_diff += query_signal_stdvs[pi + di];
}
mean_diff_position.emplace_back(min_diff, pi);
}
std::sort(mean_diff_position.begin(), mean_diff_position.end(), compare1);
// std::sort(mean_diff_position.begin(), mean_diff_position.end());
// Collect anchors
uint32_t previous_position = 0;
uint32_t num_positions = 0;
for (uint32_t pi = 0; pi < query_signal.size() - dimension_ + 1; ++pi) {
uint32_t position = mean_diff_position[pi].second;
if (position < previous_position + query_point_cloud_step_size &&
position + query_point_cloud_step_size > previous_position) {
continue;
}
// std::cout << position << "\n";
// size_t num_results = 100;
// std::vector<size_t> ret_indexes(num_results);
// std::vector<float> out_dists_sqr(num_results);
// nanoflann::KNNResultSet<float> resultSet(num_results);
// resultSet.init(&ret_indexes[0], &out_dists_sqr[0] );
// size_t num_point_anchors =
// spatial_index_->index->findNeighbors(resultSet, query_signal.data() +
// position, nanoflann::SearchParams(10));
size_t num_point_anchors = spatial_index_->index->radiusSearch(
query_signal.data() + position, search_radius, point_anchors, params);
// std::cout << "radiusSearch(): radius=" << search_radius << " -> " <<
// num_point_anchors << " matches\n"; for (size_t ai = 0; ai < num_results;
// ai++) { float previous_distance = dimension_;
for (size_t ai = 0;
ai < num_point_anchors && ai < (uint32_t)num_nearest_points; ai++) {
// if (point_anchors[ai].second > previous_distance * 2) {
// break;
//}
// std::cout << "cloud size =" << point_cloud_.size() << " -> " <<
// point_anchors[ai].first << " matches\n";
Point &point = point_cloud_[point_anchors[ai].first];
// Point &point = point_cloud_[ret_indexes[ai]];
uint32_t target_signal_index = point.position >> 33,
target_signal_position = point.position >> 1;
Direction target_signal_direction =
(point.position & 1) == 0 ? Positive : Negative;
// GetSignalIndexAndPosition(point_anchors[ai].first, num_target_signals,
// target_signals, target_signal_index, target_signal_position);
if (target_signal_direction == Positive) {
positive_anchors_on_diff_signals[target_signal_index].emplace_back(
SignalAnchor{target_signal_position, position + query_start_offset,
point_anchors[ai].second});
// positive_anchors_on_diff_signals[target_signal_index].emplace_back(SignalAnchor{target_signal_position,
// position, out_dists_sqr[ai]});
} else {
negative_anchors_on_diff_signals[target_signal_index].emplace_back(
SignalAnchor{target_signal_position, position + query_start_offset,
point_anchors[ai].second});
// negative_anchors_on_diff_signals[target_signal_index].emplace_back(SignalAnchor{target_signal_position,
// position, out_dists_sqr[ai]});
}
// previous_distance = point_anchors[ai].second;
// std::cout << "idx["<< ai << "]=" << point_anchors[ai].first << "
// dist["<< ai << "]=" << point_anchors[ai].second << std::endl;
}
++num_positions;
if (num_positions >=
(query_signal.size() - dimension_ + 1) / query_point_cloud_step_size) {
break;
}
previous_position = position;
}
// Sort the anchors based on their occurrence on target signal
for (size_t target_signal_index = 0; target_signal_index < num_target_signals;
++target_signal_index) {
std::sort(positive_anchors_on_diff_signals[target_signal_index].begin(),
positive_anchors_on_diff_signals[target_signal_index].end());
std::sort(negative_anchors_on_diff_signals[target_signal_index].begin(),
negative_anchors_on_diff_signals[target_signal_index].end());
}
// Chaining DP done on each individual target signal
float max_chaining_score = 0; // std::numeric_limits<float>::min();
for (size_t target_signal_index = 0; target_signal_index < num_target_signals;
++target_signal_index) {
for (int direction_i = 0; direction_i < 2; ++direction_i) {
std::vector<float> chaining_scores;
chaining_scores.reserve(
anchors_on_diff_signals[direction_i][target_signal_index].size());
std::vector<size_t> chaining_predecessors;
chaining_predecessors.reserve(
anchors_on_diff_signals[direction_i][target_signal_index].size());
std::vector<bool> anchor_is_used;
anchor_is_used.reserve(
anchors_on_diff_signals[direction_i][target_signal_index].size());
std::vector<std::pair<float, size_t> > end_anchor_index_chaining_scores;
end_anchor_index_chaining_scores.reserve(10);
for (size_t anchor_index = 0;
anchor_index <
anchors_on_diff_signals[direction_i][target_signal_index].size();
++anchor_index) {
float distance_coefficient =
1 - 0.2 *
anchors_on_diff_signals[direction_i][target_signal_index]
[anchor_index]
.distance /
search_radius;
chaining_scores.emplace_back(distance_coefficient * dimension_);
chaining_predecessors.emplace_back(anchor_index);
anchor_is_used.push_back(false);
int32_t current_anchor_target_position =
anchors_on_diff_signals[direction_i][target_signal_index]
[anchor_index]
.target_position;
int32_t current_anchor_query_position =
anchors_on_diff_signals[direction_i][target_signal_index]
[anchor_index]
.query_position;
int32_t start_anchor_index = 0;
if (anchor_index > (size_t)chaining_band_length) {
start_anchor_index = anchor_index - chaining_band_length;
}
int32_t previous_anchor_index = anchor_index - 1;
int32_t num_skips = 0;
for (; previous_anchor_index >= start_anchor_index;
--previous_anchor_index) {
// std::cerr << previous_anchor_index << " " << start_anchor_index <<
// " " << anchor_index << "\n";
int32_t previous_anchor_target_position =
anchors_on_diff_signals[direction_i][target_signal_index]
[previous_anchor_index]
.target_position;
int32_t previous_anchor_query_position =
anchors_on_diff_signals[direction_i][target_signal_index]
[previous_anchor_index]
.query_position;
if (previous_anchor_query_position == current_anchor_query_position) {
continue;
}
if (previous_anchor_target_position ==
current_anchor_target_position) {
continue;
}
if (previous_anchor_target_position + max_target_gap_length <
current_anchor_target_position) {
break;
}
int32_t target_position_diff =
current_anchor_target_position - previous_anchor_target_position;
assert(target_position_diff > 0);
int32_t query_position_diff =
current_anchor_query_position - previous_anchor_query_position;
float current_chaining_score = 0;
// std::cerr << "curr_ai: " << anchor_index << ", adjusted_d: " <<
// dimension_ * distance_coefficient << ", pre_ai: " <<
// previous_anchor_index << ", "; std::cerr << "target_diff: " <<
// target_position_diff << ", query_diff: " << query_position_diff <<
// "\n";
if (query_position_diff < 0) {
// current_chaining_score = std::numeric_limits<float>::min();
continue;
} else {
float matching_dimensions =
std::min(std::min(target_position_diff, query_position_diff),
dimension_) *
distance_coefficient;
int gap_length =
std::abs(target_position_diff - query_position_diff);
float gap_scale =
target_position_diff > 0
? (float)query_position_diff / target_position_diff
: 1;
// float gap_cost = 0;
// if (gap_length != 0) {
if (gap_length < max_gap_length && gap_scale < 5 &&
gap_scale > 0.75) {
current_chaining_score = chaining_scores[previous_anchor_index] +
matching_dimensions; // - gap_cost;
} else {
// gap_cost = std::numeric_limits<float>::max();
// current_chaining_score =
// std::numeric_limits<float>::min();//chaining_scores[previous_anchor_index]
// + matching_dimensions - gap_cost;
}
//}
// std::cerr << ", matching_d: " << matching_dimensions;
// std::cerr << ", gap_len: " << gap_length;
// std::cerr << ", gap_cost: " << gap_cost;
// std::cerr << ", current chaining score: " <<
// current_chaining_score << "\n";
}
if (current_chaining_score > chaining_scores[anchor_index]) {
chaining_scores[anchor_index] = current_chaining_score;
chaining_predecessors[anchor_index] = previous_anchor_index;
--num_skips;
// std::cerr << "update_curr_max: " << current_chaining_score <<
// "\n";
} else {
++num_skips;
if (num_skips > max_num_skips) {
break;
}
}
}
// Update chain with max score
if (chaining_scores[anchor_index] > max_chaining_score) {
max_chaining_score = chaining_scores[anchor_index];
}
if (chaining_scores.back() >= min_chaining_score &&
chaining_scores.back() > max_chaining_score / 2) {
end_anchor_index_chaining_scores.emplace_back(chaining_scores.back(),
anchor_index);
}
}
// Sort a vector of <end anchor index, chaining score>
std::sort(end_anchor_index_chaining_scores.begin(),
end_anchor_index_chaining_scores.end(), compare);
// Traceback all chains from higest score to lowest
for (size_t anchor_index = 0;
anchor_index < end_anchor_index_chaining_scores.size() &&
anchor_index < (size_t)num_best_chains;
++anchor_index) {
TracebackChains(
min_num_anchors, direction_i == 0 ? Positive : Negative,
end_anchor_index_chaining_scores[anchor_index].second,
target_signal_index, chaining_scores, chaining_predecessors,
anchors_on_diff_signals[direction_i], anchor_is_used, chains);
if (chaining_scores[end_anchor_index_chaining_scores[anchor_index]
.second] < max_chaining_score / 2) {
break;
}
}
}
}
if (chains.size() > 0) {
// Generate primary chains
GeneratePrimaryChains(chains);
// Compute MAPQ
ComputeMAPQ(chains);
}
}
} // namespace sigmap
| 25,700
|
C++
|
.cc
| 564
| 36.113475
| 114
| 0.591752
|
haowenz/sigmap
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,204
|
pore_model.cc
|
haowenz_sigmap/src/pore_model.cc
|
#include "pore_model.h"
#include <cassert>
#include <fstream>
#include <sstream>
#include <string>
#include "utils.h"
namespace sigmap {
void PoreModel::Load(const std::string &pore_model_file_path) {
double real_start_time = GetRealTime();
int num_kmers = 0;
std::ifstream pore_model_file_stream(pore_model_file_path);
std::string pore_model_file_line;
bool first_line = true;
while (getline(pore_model_file_stream, pore_model_file_line)) {
std::stringstream pore_model_file_line_string_stream(pore_model_file_line);
// skip the header
if (pore_model_file_line[0] == '#' ||
pore_model_file_line.find("kmer") == 0) {
continue;
}
std::string kmer;
pore_model_file_line_string_stream >> kmer;
if (first_line) {
kmer_size_ = kmer.length();
// Allocate memory to save pore model parameters
size_t num_pore_models = 1 << (kmer_size_ * 2);
pore_models_.assign(num_pore_models, PoreModelParameters());
first_line = false;
}
assert(kmer.length() == (size_t)kmer_size_);
uint64_t kmer_hash_value =
GenerateSeedFromSequence(kmer.data(), kmer_size_, 0, kmer_size_);
PoreModelParameters &pore_model_parameters = pore_models_[kmer_hash_value];
pore_model_file_line_string_stream >> pore_model_parameters.level_mean >>
pore_model_parameters.level_stdv >> pore_model_parameters.sd_mean >>
pore_model_parameters.sd_stdv;
++num_kmers;
}
std::cerr << "Loaded " << num_kmers << " kmers in "
<< GetRealTime() - real_start_time << "s.\n";
}
void PoreModel::Print() {
size_t num_pore_models = 1 << (kmer_size_ * 2);
for (size_t i = 0; i < num_pore_models; ++i) {
std::cerr << i << " " << pore_models_[i].level_mean << " "
<< pore_models_[i].level_stdv << " " << pore_models_[i].sd_mean
<< " " << pore_models_[i].sd_stdv << "\n";
}
}
// This funtion return a array of level means given the [start, end) positions
// (0-based).
std::vector<float> PoreModel::GetLevelMeansAt(const char *sequence,
uint32_t start_position,
uint32_t end_position) const {
// Note that the start and end positions should be checked before calling this
// function
int32_t signal_length = end_position - start_position - kmer_size_ + 1;
assert(signal_length > 0);
std::vector<float> signal_values;
signal_values.reserve(signal_length);
uint32_t mask = ((uint32_t)1 << (2 * kmer_size_)) - 1;
uint32_t hash_value = GenerateSeedFromSequence(
sequence, start_position + signal_length, start_position, kmer_size_);
signal_values.emplace_back(pore_models_[hash_value].level_mean);
for (uint32_t position = start_position + 1;
position < end_position - kmer_size_ + 1; ++position) {
uint8_t current_base = CharToUint8(sequence[position + kmer_size_]);
if (current_base < 4) {
hash_value = ((hash_value << 2) | current_base) & mask;
} else {
hash_value = (hash_value << 2) & mask;
}
signal_values.emplace_back(pore_models_[hash_value].level_mean);
}
return signal_values;
}
} // namespace sigmap
| 3,195
|
C++
|
.cc
| 77
| 35.922078
| 80
| 0.637649
|
haowenz/sigmap
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,205
|
fast_dtw.cc
|
haowenz_sigmap/src/fast_dtw.cc
|
#include "fast_dtw.h"
namespace sigmap {
void reduce_by_half(const float *signal, size_t length, float *signal_reduced, size_t &reduced_length){
reduced_length = 0;
for (size_t i = 0; i < length - length % 2; i += 2){
signal_reduced[reduced_length] = (signal[i] + signal[i + 1]) / 2;
reduced_length++;
}
}
void expand_window(std::vector<std::pair<Coordinate,int>> &path,size_t target_length,size_t query_length,int radius,std::vector<std::vector<Coordinate>> &window) {
std::set<Coordinate> path_set;
for (size_t i = 0;i<path.size();i++){
for (int j=-radius;j<=radius;j++){
for (int k=-radius;k<=radius;k++){
ssize_t new_target_coord = path[i].first.target_coord+j;
ssize_t new_query_coord = path[i].first.query_coord+k;
if ((new_target_coord>=0)&(new_query_coord>=0)&(new_target_coord<target_length)&(new_query_coord<query_length)){
path_set.insert(Coordinate(new_target_coord,new_query_coord));
}
}
}
}
std::set<Coordinate> window_set;
for (std::set<Coordinate>::iterator it=path_set.begin() ;it!=path_set.end();it++){
for (int x=0;x<2;x++){
for (int y=0;y<2;y++){
ssize_t new_target_coord = it->target_coord*2+x;
ssize_t new_query_coord = it->query_coord*2+y;
if ((new_target_coord>=0)&(new_query_coord>=0)&(new_target_coord<target_length)&(new_query_coord<query_length)){
window_set.insert(Coordinate(new_target_coord,new_query_coord));
}
}
}
}
//each vector in window represents a base
std::vector<std::vector<Coordinate>>().swap(window);
size_t last_target_coord = window_set.begin()->target_coord;
window.push_back(std::vector<Coordinate>());
for (std::set<Coordinate>::iterator it=window_set.begin() ;it!=window_set.end();it++){
if (last_target_coord!=it->target_coord){
window.push_back(std::vector<Coordinate>());
last_target_coord = it->target_coord;
}
window.back().push_back(Coordinate(it->target_coord,it->query_coord));
}
}
void generate_path(std::vector<std::vector<int>> &path_matrix,std::vector<std::vector<Coordinate>> &window,std::map<Coordinate,std::pair<size_t,size_t>> &coord_to_window_index_map,std::vector<std::pair<Coordinate,int>> &path,ssize_t end_target_position){
//trace back
size_t row = end_target_position;
size_t col = window[end_target_position].size()-1;
//clear the path
std::vector<std::pair<Coordinate,int>>().swap(path);
Coordinate coord = window[row][col];
while (coord.query_coord != 0) {
coord = window[row][col];
path.push_back(std::make_pair(Coordinate(coord.target_coord,coord.query_coord),path_matrix[row][col]));
//coordinate shift when trace back
int query_shift[] = {-1,-1,-1,0};
int target_shift[] = {-1,0,0,-1};
coord.query_coord += query_shift[path_matrix[row][col]];
coord.target_coord += target_shift[path_matrix[row][col]];
std::pair<size_t,size_t> index = coord_to_window_index_map[coord];
row = index.first;
col = index.second;
}
path.push_back(std::make_pair(window[row][col],path_matrix[row][col]));
std::reverse(path.begin(),path.end());
}
float DTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length, std::vector<std::vector<Coordinate>> &window,std::vector<std::pair<Coordinate,int>> &path,ssize_t &end_target_position){
float min_dtw_distance = std::numeric_limits<float>::max();
float skip_target_cost = 2;
float skip_query_cost = 2;
std::map<Coordinate,std::pair<size_t,size_t>> coord_to_window_index_map;
if ((window.empty())){
for (size_t i = 0; i < target_length; i++){
window.push_back(std::vector<Coordinate>());
for (size_t j = 0; j < query_length; j++){
window.back().push_back(Coordinate(i,j));
}
}
}
//path_matrix: 0 -> one-to-one map; 1 -> one base to multi signal; 2 -> skip one signal; 3 -> skip one base;
//initialize path_matrix and coord_to_window_index_map
std::vector<std::vector<int>> path_matrix(window.size(),std::vector<int>());
for (size_t i = 0; i < window.size(); i++){
path_matrix[i]= std::vector<int>(window[i].size(),0);
for (size_t j = 0; j < window[i].size(); j++){
coord_to_window_index_map[window[i][j]] = std::make_pair(i,j);
}
}
std::vector<float> previous_row(query_length + 1, std::numeric_limits<float>::max());
std::vector<float> current_row(query_length + 1, std::numeric_limits<float>::max());
previous_row[0] = 0;
end_target_position = -1;
size_t target_position;
size_t query_position;
for (size_t i = 0; i < window.size(); ++i){
// iterate to a new row (new signal on reference)
current_row[0] = 0;
for (size_t j = 0; j < window[i].size(); ++j){
target_position = window[i][j].target_coord + 1;
query_position = window[i][j].query_coord + 1;
float cost = std::abs(target_signal[target_position - 1] - query_signal[query_position - 1]);
std::vector<float> candidates;
std::vector<int> candidates_path_direction;
//for the start position
candidates = {previous_row[query_position-1]+cost,current_row[query_position-1]+cost,current_row[query_position-1]+skip_query_cost,previous_row[query_position]+skip_target_cost};
candidates_path_direction = {0,1,2,3};
// if ((target_position==1)&&(query_position==1)){
// candidates = {cost,skip_query_cost,skip_target_cost};
// candidates_path_direction = {0,2,3};
// } else if ((j>0) && (path_matrix[i][j-1]==3)){
// // if skip this base in the last step, one base to multi signal is not allowed
// candidates = {previous_row[query_position-1]+cost,current_row[query_position-1]+skip_query_cost,previous_row[query_position]+skip_target_cost};
// candidates_path_direction = {0,2,3};
// } else {
// candidates = {previous_row[query_position-1]+cost,current_row[query_position-1]+cost,current_row[query_position-1]+skip_query_cost,previous_row[query_position]+skip_target_cost};
// candidates_path_direction = {0,1,2,3};
// }
int argmin_candidates = std::min_element( candidates.begin(),candidates.end()) - candidates.begin();
current_row[query_position] = candidates[argmin_candidates];
path_matrix[i][j] = candidates_path_direction[argmin_candidates];
}
if ((query_position == query_length) && (current_row[query_position] < min_dtw_distance)) {
min_dtw_distance = current_row[query_position];
end_target_position = i;
}
current_row.swap(previous_row);
std::vector<float>(query_length + 1, std::numeric_limits<float>::max()).swap(current_row);
}
generate_path(path_matrix,window,coord_to_window_index_map,path,end_target_position);
end_target_position = window[end_target_position][0].target_coord;
return min_dtw_distance;
}
float _fastDTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length, int radius,std::vector<std::pair<Coordinate,int>> &path,std::vector<std::vector<Coordinate>> &window, ssize_t &end_target_position){
int min_time_size = radius + 2;
std::vector<std::vector<Coordinate>>().swap(window);
if ((target_length < min_time_size) || (query_length < min_time_size)){
return DTW(target_signal, target_length, query_signal, query_length,window,path,end_target_position);
}
size_t target_reduced_length = 0;
size_t query_reduced_length = 0;
float target_reduced[target_length / 2 + 1];
float query_reduced[query_length / 2 + 1];
reduce_by_half(target_signal, target_length, target_reduced, target_reduced_length);
reduce_by_half(query_signal, query_length, query_reduced, query_reduced_length);
float dist = _fastDTW(target_reduced,target_reduced_length, query_reduced,query_reduced_length,radius,path,window,end_target_position);
expand_window(path, target_length,query_length, radius,window);
return DTW(target_signal, target_length, query_signal, query_length,window,path,end_target_position);
}
std::string print_alignment(std::vector<std::pair<Coordinate,int>> &path){
//path[i].second: 0 -> one-to-one map; 1 -> one base to multi signal; 2 -> skip one signal; 3 -> skip one base;
std::string print_flags = "MMID";
if (path.empty()){
return "";
}
std::vector<std::string> per_base_cigar;
size_t num_same_continuous_flag = 1;
int last_flag;
// for the first base to signal alignment
if (path[0].second == 3){
per_base_cigar.push_back("1D");
last_flag = 3;
} else {
last_flag = path[0].second == 0 ? 1 : 2;
}
per_base_cigar.push_back("");
for (size_t i = 1; i < path.size(); ++i){
int flag = path[i].second;
// if within one base,counting the continous same flag
if ((flag == 1) || (flag == 2)){
if (last_flag == flag){
num_same_continuous_flag ++;
} else {
per_base_cigar.back() += std::to_string(num_same_continuous_flag) + print_flags[last_flag];
num_same_continuous_flag = 1;
last_flag = flag;
}
} else {
// if not within one base, finish the last base and adding new base
per_base_cigar.back() += std::to_string(num_same_continuous_flag) + print_flags[last_flag];
if (flag == 0){
last_flag = 1;
} else if (flag == 3){
// if skip one base
last_flag = 3;
}
if (i != path.size() - 1){
per_base_cigar.push_back("");
num_same_continuous_flag = 1;
}
}
}
std::string cigar = "";
for (size_t i = 0; i < per_base_cigar.size(); ++i){
cigar += "(" + per_base_cigar[i] + ")";
}
return cigar;
}
float fastDTW(const float *target_signal, size_t target_length, const float *query_signal, size_t query_length,int radius,ssize_t& end_target_position,std::string &cigar){
double real_start_time = GetRealTime();
std::vector<std::pair<Coordinate,int>> path;
std::vector<std::vector<Coordinate>> window;
float distance = _fastDTW(target_signal,target_length,query_signal,query_length,radius,path,window,end_target_position);
std::cerr << "Finished sDTW in "<< GetRealTime() - real_start_time << ", target length: " << target_length << ", query length: " << query_length << "\n";
std::cerr<< path[0].first.target_coord<<","<<path[0].first.query_coord<<'\n';
cigar = print_alignment(path);
return distance;
}
} // namespace sigmap
| 11,402
|
C++
|
.cc
| 210
| 44.714286
| 255
| 0.600717
|
haowenz/sigmap
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,537,206
|
signal_batch.cc
|
haowenz_sigmap/src/signal_batch.cc
|
#include "signal_batch.h"
#include <hdf5.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <vector>
#include "utils.h"
namespace sigmap {
void SignalBatch::InitializeLoading(const std::string &signal_directory) {
if (IsDirectory(signal_directory)) {
signal_directory_ = signal_directory;
} else {
ExitWithMessage("Signal directory is in valid!");
}
}
void SignalBatch::FinalizeLoading() {}
size_t SignalBatch::LoadAllReadSignals() {
double real_start_time = GetRealTime();
auto dir_list = ListDirectory(signal_directory_);
// two rounds, get all the fast5 absolute paths first and then load reads
std::vector<std::string> fast5_list;
std::vector<std::string> slow5_list;
for (size_t pi = 0; pi < dir_list.size(); ++pi) {
std::string &relative_path = dir_list[pi];
if (relative_path == "." or relative_path == "..") {
continue;
}
std::string absolute_path = signal_directory_ + "/" + relative_path;
if (IsDirectory(absolute_path)) {
auto sub_directory_list = ListDirectory(absolute_path);
std::vector<std::string> sub_relative_paths;
sub_relative_paths.reserve(sub_directory_list.size());
for (size_t si = 0; si < sub_directory_list.size(); ++si) {
sub_relative_paths.push_back(relative_path + "/" +
sub_directory_list[si]);
}
dir_list.insert(dir_list.end(), sub_relative_paths.begin(),
sub_relative_paths.end());
}
bool is_fast5 = absolute_path.find(".fast5") != std::string::npos;
bool is_slow5 = absolute_path.find(".blow5") != std::string::npos;
if (is_fast5) {
fast5_list.emplace_back(absolute_path);
}else if(is_slow5) {
slow5_list.emplace_back(absolute_path);
}else{
// don't put it into index
}
}
signals_.reserve(fast5_list.size());
for (size_t pi = 0; pi < fast5_list.size(); ++pi) {
AddSignalsFromFAST5(fast5_list[pi]);
}
for (size_t pi = 0; pi < slow5_list.size(); ++pi) {
AddSignalsFromSLOW5(slow5_list[pi]);
}
std::cerr << "Loaded " << signals_.size() << " reads in "
<< GetRealTime() - real_start_time << "s.\n";
return signals_.size();
}
void SignalBatch::AddSignalsFromFAST5(const std::string &fast5_file_path) {
hdf5_tools::File fast5_file;
fast5_file.open(fast5_file_path);
// Check format
bool is_single = false;
std::vector<std::string> fast5_file_groups = fast5_file.list_group("/");
for (std::string &group : fast5_file_groups) {
if (group == "Raw") {
is_single = true;
break;
}
}
if (is_single) {
for (std::string &read : fast5_file.list_group("/Raw/Reads")) {
std::string read_id = "";
for (auto a : fast5_file.get_attr_map("/Raw/Reads/" + read)) {
if (a.first == "read_id") {
read_id = a.second;
break;
}
}
if (read_id.empty()) {
std::cerr << "Error: failed to find read_id\n";
exit(-1);
}
std::string raw_path = "/Raw/Reads/" + read;
std::string ch_path = "/UniqueGlobalKey/channel_id";
AddSignal(fast5_file, raw_path, ch_path);
}
} else {
signals_.reserve(signals_.size() + fast5_file_groups.size());
for (std::string &read : fast5_file_groups) {
std::string raw_path = "/" + read + "/Raw";
std::string ch_path = "/" + read + "/channel_id";
AddSignal(fast5_file, raw_path, ch_path);
}
}
fast5_file.close();
}
void SignalBatch::AddSignal(const hdf5_tools::File &file,
const std::string &raw_path,
const std::string &ch_path) {
std::string id;
for (auto a : file.get_attr_map(raw_path)) {
if (a.first == "read_id") {
id = a.second;
} else if (a.first == "read_number") {
// number = atoi(a.second.c_str());
} else if (a.first == "start_time") {
// start_sample = atoi(a.second.c_str());
}
}
float digitisation = 0, range = 0, offset = 0;
for (auto a : file.get_attr_map(ch_path)) {
if (a.first == "channel_number") {
// channel_idx = atoi(a.second.c_str()) - 1;
} else if (a.first == "digitisation") {
digitisation = atof(a.second.c_str());
} else if (a.first == "range") {
range = atof(a.second.c_str());
} else if (a.first == "offset") {
offset = atof(a.second.c_str());
}
}
std::string sig_path = raw_path + "/Signal";
std::vector<float> signal_values;
file.read(sig_path, signal_values);
// convert to pA
uint32_t valid_signal_length = 0;
float scale = range / digitisation;
for (size_t i = 0; i < signal_values.size(); i++) {
if ((signal_values[i] + offset) * scale > 30 &&
(signal_values[i] + offset) * scale < 200) {
signal_values[valid_signal_length] = (signal_values[i] + offset) * scale;
++valid_signal_length;
}
}
if (valid_signal_length < signal_values.size()) {
signal_values.erase(signal_values.begin() + valid_signal_length,
signal_values.end());
}
signals_.emplace_back(Signal{id, digitisation, range, offset, signal_values,
std::vector<float>()});
}
void SignalBatch::AddSignalsFromSLOW5(const std::string &slow5_file_path) {
slow5_file_t *sp = slow5_open(slow5_file_path.c_str(),"r");
if(sp==NULL){
fprintf(stderr,"Error in opening file\n");
exit(EXIT_FAILURE);
}
slow5_rec_t *rec = NULL;
int ret=0;
while((ret = slow5_get_next(&rec,sp)) >= 0){
AddSignal(rec);
}
if(ret != SLOW5_ERR_EOF){ //check if proper end of file has been reached
fprintf(stderr,"Error in slow5_get_next. Error code %d\n",ret);
exit(EXIT_FAILURE);
}
slow5_rec_free(rec);
slow5_close(sp);
}
void SignalBatch::AddSignal(slow5_rec_t *rec) {
std::string id;
id = rec->read_id;
float digitisation = 0, range = 0, offset = 0;
digitisation = rec->digitisation;
range = rec->range;
offset = rec->offset;
std::vector<float> signal_values(rec->len_raw_signal);
// convert to pA
uint32_t valid_signal_length = 0;
float scale = range / digitisation;
for (size_t i = 0; i < rec->len_raw_signal; i++) {
if ((rec->raw_signal[i] + offset) * scale > 30 &&
(rec->raw_signal[i] + offset) * scale < 200) {
signal_values[valid_signal_length] = (rec->raw_signal[i] + offset) * scale;
++valid_signal_length;
}
}
if (valid_signal_length < signal_values.size()) {
signal_values.erase(signal_values.begin() + valid_signal_length,
signal_values.end());
}
signals_.emplace_back(Signal{id, digitisation, range, offset, signal_values,
std::vector<float>()});
}
void SignalBatch::NormalizeSignalAt(size_t signal_index) {
//// Should use a linear algorithm like median of medians
//// But for now let us use sort
// std::vector<float> tmp_signal((signals_[signal_index]).signal_values,
// (signals_[signal_index]).signal_values +
// (signals_[signal_index]).signal_length);
// std::nth_element(tmp_signal.begin(), tmp_signal.begin() + tmp_signal.size()
// / 2, tmp_signal.end()); float signal_median = tmp_signal[tmp_signal.size()
// / 2]; // This is a fake median, but should be okay for a quick
// implementation for (size_t i = 0; i < tmp_signal.size(); ++i) {
// tmp_signal[i] = std::abs(tmp_signal[i] - signal_median);
//}
// std::nth_element(tmp_signal.begin(), tmp_signal.begin() + tmp_signal.size()
// / 2, tmp_signal.end()); float MAD = tmp_signal[tmp_signal.size() / 2]; //
// Again, fake MAD, ok for a quick implementation
//// Now we can normalize signal
// for (size_t i = 0; i < signals_[signal_index].signal_length; ++i) {
// ((signals_[signal_index]).signal_values)[i] =
// (((signals_[signal_index]).signal_values)[i] - signal_median) / MAD;
//}
// Calculate mean
float mean = 0;
for (size_t i = 0; i < signals_[signal_index].GetSignalLength(); ++i) {
mean += signals_[signal_index].signal_values[i];
}
mean /= signals_[signal_index].signal_values.size();
// Calculate standard deviation
float stdv = 0;
for (size_t i = 0; i < signals_[signal_index].GetSignalLength(); ++i) {
stdv += (signals_[signal_index].signal_values[i] - mean) *
(signals_[signal_index].signal_values[i] - mean);
}
stdv /= (signals_[signal_index].signal_values.size() - 1);
stdv = sqrt(stdv);
// Now we can normalize signal
for (size_t i = 0; i < signals_[signal_index].signal_values.size(); ++i) {
signals_[signal_index].signal_values[i] =
(signals_[signal_index].signal_values[i] - mean) / stdv;
}
}
void SignalBatch::ConvertSequencesToSignals(const SequenceBatch &sequence_batch,
const PoreModel &pore_model,
size_t num_sequences) {
double real_start_time = GetRealTime();
for (size_t sequence_index = 0; sequence_index < num_sequences;
++sequence_index) {
size_t sequence_length = sequence_batch.GetSequenceLengthAt(sequence_index);
std::vector<float> signal_values = pore_model.GetLevelMeansAt(
sequence_batch.GetSequenceAt(sequence_index), 0, sequence_length);
std::vector<float> negative_signal_values = pore_model.GetLevelMeansAt(
sequence_batch.GetNegativeSequenceAt(sequence_index).data(), 0,
sequence_length);
std::string signal_id(sequence_batch.GetSequenceNameAt(sequence_index));
signals_.emplace_back(
Signal{signal_id, 0, 0, 0, signal_values, negative_signal_values});
}
std::cerr << "Convert " << num_sequences << " sequences to signals in "
<< GetRealTime() - real_start_time << "s.\n";
}
} // namespace sigmap
| 9,786
|
C++
|
.cc
| 247
| 33.919028
| 81
| 0.618142
|
haowenz/sigmap
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.