AutoMathText / data /code /cpp /0.05-0.10.jsonl
March07's picture
add batch 3/5 (200 files)
803451e verified
Raw
History Blame Contribute Delete
259 kB
{"text": "/* $Id: step-1.cc 27657 2012-11-21 13:19:08Z bangerth $\n *\n * Copyright (C) 1999-2003, 2005-2007, 2009, 2011-2012 by the deal.II authors\n *\n * This file is subject to QPL and may not be distributed\n * without copyright and license information. Please refer\n * to the file deal.II/doc/license.html for the text and\n * further information on this license.\n */\n\n// @sect3{Include files}\n\n// The most fundamental class in the library is the Triangulation class, which\n// is declared here:\n#include <deal.II/grid/tria.h>\n// We need the following two includes for loops over cells and/or faces:\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n// Here are some functions to generate standard grids:\n#include <deal.II/grid/grid_generator.h>\n// We would like to use boundaries which are not straight lines, so we import\n// some classes which predefine some boundary descriptions:\n#include <deal.II/grid/tria_boundary_lib.h>\n// Output of grids in various graphics formats:\n#include <deal.II/grid/grid_out.h>\n\n// This is needed for C++ output:\n#include <fstream>\n// And this for the declarations of the `sqrt' and `fabs' functions:\n#include <cmath>\n\n// The final step in importing deal.II is this: All deal.II functions and\n// classes are in a namespace <code>dealii</code>, to make sure they don't\n// clash with symbols from other libraries you may want to use in conjunction\n// with deal.II. One could use these functions and classes by prefixing every\n// use of these names by <code>dealii::</code>, but that would quickly become\n// cumbersome and annoying. Rather, we simply import the entire deal.II\n// namespace for general use:\nusing namespace dealii;\n\n// @sect3{Creating the first mesh}\n\n// In the following, first function, we simply use the unit square as domain\n// and produce a globally refined grid from it.\nvoid first_grid ()\n{\n // The first thing to do is to define an object for a triangulation of a\n // two-dimensional domain:\n Triangulation<2> triangulation;\n // Here and in many following cases, the string \"<2>\" after a class name\n // indicates that this is an object that shall work in two space\n // dimensions. Likewise, there are versions of the triangulation class that\n // are working in one (\"<1>\") and three (\"<3>\") space dimensions. The way\n // this works is through some template magic that we will investigate in\n // some more detail in later example programs; there, we will also see how\n // to write programs in an essentially dimension independent way.\n\n // Next, we want to fill the triangulation with a single cell for a square\n // domain. The triangulation is the refined four times, to yield 4^4=256\n // cells in total:\n GridGenerator::hyper_cube (triangulation);\n triangulation.refine_global (4);\n\n // Now we want to write a graphical representation of the mesh to an output\n // file. The GridOut class of deal.II can do that in a number of different\n // output formats; here, we choose encapsulated postscript (eps) format:\n std::ofstream out (\"grid-1.eps\");\n GridOut grid_out;\n grid_out.write_eps (triangulation, out);\n}\n\n\n\n// @sect3{Creating the second mesh}\n\n// The grid in the following, second function is slightly more complicated in\n// that we use a ring domain and refine the result once globally.\nvoid second_grid ()\n{\n // We start again by defining an object for a triangulation of a\n // two-dimensional domain:\n Triangulation<2> triangulation;\n\n // We then fill it with a ring domain. The center of the ring shall be the\n // point (1,0), and inner and outer radius shall be 0.5 and 1. The number of\n // circumferential cells could be adjusted automatically by this function,\n // but we choose to set it explicitely to 10 as the last argument:\n const Point<2> center (1,0);\n const double inner_radius = 0.5,\n outer_radius = 1.0;\n GridGenerator::hyper_shell (triangulation,\n center, inner_radius, outer_radius,\n 10);\n // By default, the triangulation assumes that all boundaries are straight\n // and given by the cells of the coarse grid (which we just created). It\n // uses this information when cells at the boundary are refined and new\n // points need to be introduced on the boundary; if the boundary is assumed\n // to be straight, then new points will simply be in the middle of the\n // surrounding ones.\n //\n // Here, however, we would like to have a curved boundary. Fortunately, some\n // good soul implemented an object which describes the boundary of a ring\n // domain; it only needs the center of the ring and automatically figures\n // out the inner and outer radius when needed. Note that we associate this\n // boundary object with that part of the boundary that has the \"boundary\n // indicator\" zero. By default (at least in 2d and 3d, the 1d case is\n // slightly different), all boundary parts have this number, but you can\n // change this number for some parts of the boundary. In that case, the\n // curved boundary thus associated with number zero will not apply on those\n // parts with a non-zero boundary indicator, but other boundary description\n // objects can be associated with those non-zero indicators. If no boundary\n // description is associated with a particular boundary indicator, a\n // straight boundary is implied.\n const HyperShellBoundary<2> boundary_description(center);\n triangulation.set_boundary (0, boundary_description);\n\n // In order to demonstrate how to write a loop over all cells, we will\n // refine the grid in five steps towards the inner circle of the domain:\n for (unsigned int step=0; step<5; ++step)\n {\n // Next, we need an iterator which points to a cell and which we will\n // move over all active cells one by one (active cells are those that\n // are not further refined, and the only ones that can be marked for\n // further refinement, obviously). By convention, we almost always use\n // the names <code>cell</code> and <code>endc</code> for the iterator\n // pointing to the present cell and to the <code>one-past-the-end</code>\n // iterator:\n Triangulation<2>::active_cell_iterator\n cell = triangulation.begin_active(),\n endc = triangulation.end();\n\n // The loop over all cells is then rather trivial, and looks like any\n // loop involving pointers instead of iterators:\n for (; cell!=endc; ++cell)\n // Next, we want to loop over all vertices of the cells. Since we are\n // in 2d, we know that each cell has exactly four vertices. However,\n // instead of penning down a 4 in the loop bound, we make a first\n // attempt at writing it in a dimension-independent way by which we\n // find out about the number of vertices of a cell. Using the\n // GeometryInfo class, we will later have an easier time getting the\n // program to also run in 3d: we only have to change all occurrences\n // of <code>&lt;2&gt;</code> to <code>&lt;3&gt;</code>, and do not\n // have to audit our code for the hidden appearance of magic numbers\n // like a 4 that needs to be replaced by an 8:\n for (unsigned int v=0;\n v < GeometryInfo<2>::vertices_per_cell;\n ++v)\n {\n // If this cell is at the inner boundary, then at least one of its\n // vertices must sit on the inner ring and therefore have a radial\n // distance from the center of exactly 0.5, up to floating point\n // accuracy. Compute this distance, and if we have found a vertex\n // with this property flag this cell for later refinement. We can\n // then also break the loop over all vertices and move on to the\n // next cell.\n const double distance_from_center\n = center.distance (cell->vertex(v));\n\n if (std::fabs(distance_from_center - inner_radius) < 1e-10)\n {\n cell->set_refine_flag ();\n break;\n }\n }\n\n // Now that we have marked all the cells that we want refined, we let\n // the triangulation actually do this refinement. The function that does\n // so owes its long name to the fact that one can also mark cells for\n // coarsening, and the function does coarsening and refinement all at\n // once:\n triangulation.execute_coarsening_and_refinement ();\n }\n\n\n // Finally, after these five iterations of refinement, we want to again\n // write the resulting mesh to a file, again in eps format. This works just\n // as above:\n std::ofstream out (\"grid-2.eps\");\n GridOut grid_out;\n grid_out.write_eps (triangulation, out);\n\n\n // At this point, all objects created in this function will be destroyed in\n // reverse order. Unfortunately, we defined the boundary object after the\n // triangulation, which still has a pointer to it and the library will\n // produce an error if the boundary object is destroyed before the\n // triangulation. We therefore have to release it, which can be done as\n // follows. Note that this sets the boundary object used for part \"0\" of the\n // boundary back to a default object, over which the triangulation has full\n // control.\n triangulation.set_boundary (0);\n // An alternative to doing so, and one that is frequently more convenient,\n // would have been to declare the boundary object before the triangulation\n // object. In that case, the triangulation would have let lose of the\n // boundary object upon its destruction, and everything would have been\n // fine.\n}\n\n\n\n// @sect3{The main function}\n\n// Finally, the main function. There isn't much to do here, only to call the\n// two subfunctions, which produce the two grids.\nint main ()\n{\n first_grid ();\n second_grid ();\n}\n", "meta": {"hexsha": "2da4f71da2cae933bae8fc87027396b4198ba2ce", "size": 9799, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-1/step-1.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-1/step-1.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-1/step-1.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 46.6619047619, "max_line_length": 78, "alphanum_fraction": 0.7018063068, "num_tokens": 2312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186968948485237, "lm_q2_score": 0.23370636225126956, "lm_q1q2_score": 0.09785212818095079}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2009 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Wolfgang Bangerth, Texas A&M University, 2009, 2010 \n * Timo Heister, University of Goettingen, 2009, 2010 \n */ \n\n\n// @sect3{Include files} \n\n// 我们在这个程序中需要的大部分包含文件已经在以前的程序中讨论过了。特别是,以下所有的文件都应该已经是熟悉的朋友了。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/timer.h> \n\n#include <deal.II/lac/generic_linear_algebra.h> \n\n// 这个程序可以使用PETSc或Trilinos来满足其并行代数的需要。默认情况下,如果deal.II已经被配置为PETSc,它将使用PETSc。否则,下面几行将检查deal.II是否已被配置为Trilinos,并采用它。\n\n// 但是在某些情况下,即使deal.II也被配置为PETSc,你还是想使用Trilinos,例如,比较这两个库的性能。要做到这一点,请在源代码中添加以下的\\#define。\n// @code\n// #define FORCE_USE_OF_TRILINOS\n// @endcode\n\n// 使用这个逻辑,下面几行将导入PETSc或Trilinos包装器到命名空间`LA`(代表 \"线性代数\")。在前一种情况下,我们还要定义宏 `USE_PETSC_LA`,这样我们就可以检测到我们是否在使用PETSc(参见solve()中需要用到的例子)。\n\nnamespace LA \n{ \n#if defined(DEAL_II_WITH_PETSC) && !defined(DEAL_II_PETSC_WITH_COMPLEX) && \\ \n !(defined(DEAL_II_WITH_TRILINOS) && defined(FORCE_USE_OF_TRILINOS)) \n using namespace dealii::LinearAlgebraPETSc; \n# define USE_PETSC_LA \n#elif defined(DEAL_II_WITH_TRILINOS) \n using namespace dealii::LinearAlgebraTrilinos; \n#else \n# error DEAL_II_WITH_PETSC or DEAL_II_WITH_TRILINOS required \n#endif \n} // namespace LA \n\n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// 然而,下面这些将是新的,或在新的角色中使用。让我们来看看它们。其中第一个将提供 Utilities::System 命名空间的工具,我们将用它来查询诸如与当前MPI宇宙相关的处理器数量,或者这个作业运行的处理器在这个宇宙中的编号。\n\n#include <deal.II/base/utilities.h> \n\n// 下一个提供了一个类,ConditionOStream,它允许我们编写代码,将东西输出到一个流中(例如在每个处理器上的 <code>std::cout</code> ,但在除了一个处理器以外的所有处理器上都将文本扔掉。我们可以通过简单地在每个可能产生输出的地方前面放一个 <code>if</code> 语句来实现同样的目的,但这并不能使代码更漂亮。此外,这个处理器是否应该向屏幕输出的条件每次都是一样的--因此,把它放在产生输出的语句中应该是很简单的。\n\n#include <deal.II/base/conditional_ostream.h> \n\n// 在这些预演之后,这里变得更加有趣。正如在 @ref distributed 模块中提到的,在大量处理器上解决问题的一个基本事实是,任何处理器都不可能存储所有的东西(例如,关于网格中所有单元的信息,所有的自由度,或者解向量中所有元素的值)。相反,每个处理器都会<i>own</i>其中的几个,如果有必要,还可能<i>know</i>另外几个,例如,位于与该处理器自己拥有的单元相邻的那些单元。我们通常称后者为<i>ghost cells</i>、<i>ghost nodes</i>或<i>ghost elements of a vector</i>。这里讨论的重点是,我们需要有一种方法来表明一个特定的处理器拥有或需要知道哪些元素。这就是IndexSet类的领域:如果总共有 $N$ 个单元、自由度或向量元素,与(非负)积分指数 $[0,N)$ 相关,那么当前处理器拥有的元素集以及它需要了解的(可能更大)指数集都是集合 $[0,N)$ 的子集。IndexSet是一个类,它以一种有效的格式存储这个集合的子集。\n\n#include <deal.II/base/index_set.h> \n\n// 下一个头文件是一个单一的函数所必需的, SparsityTools::distribute_sparsity_pattern. 这个函数的作用将在下面解释。\n\n#include <deal.II/lac/sparsity_tools.h> \n\n// 最后两个新的头文件提供了类 parallel::distributed::Triangulation ,它提供了分布在可能非常多的处理器上的网格,而第二个文件提供了命名空间 parallel::distributed::GridRefinement ,它提供了可以自适应细化这种分布式网格的函数。\n\n#include <deal.II/distributed/tria.h> \n#include <deal.II/distributed/grid_refinement.h> \n\n#include <fstream> \n#include <iostream> \n\nnamespace Step40 \n{ \n using namespace dealii; \n// @sect3{The <code>LaplaceProblem</code> class template} \n\n// 接下来我们来声明这个程序的主类。它的结构几乎与 step-6 的教程程序一模一样。唯一显著的区别是。\n\n// -- <code>mpi_communicator</code> 变量,它描述了我们希望这段代码运行在哪一组处理器上。在实践中,这将是MPI_COMM_WORLD,即批处理调度系统分配给这个特定作业的所有处理器。\n\n// - ConditionOStream类型的 <code>pcout</code> 变量的存在。\n\n// - 明显使用 parallel::distributed::Triangulation 而不是Triangulation。\n\n// - 两个IndexSet对象的存在,表示我们在当前处理器上拥有哪些自由度集(以及解和右手向量的相关元素),以及我们需要哪些(作为幽灵元素)来使本程序中的算法工作。\n\n// - 现在所有的矩阵和向量都是分布式的。我们使用PETSc或Trilinos包装类,这样我们就可以使用Hypre(使用PETSc)或ML(使用Trilinos)提供的复杂的预处理器之一。请注意,作为这个类的一部分,我们存储的解向量不仅包含当前处理器拥有的自由度,还包括(作为鬼魂元素)所有对应于 \"本地相关 \"自由度的向量元素(即所有生活在本地拥有的单元或围绕它的鬼魂单元层的自由度)。\n\n template <int dim> \n class LaplaceProblem \n { \n public: \n LaplaceProblem(); \n\n void run(); \n\n private: \n void setup_system(); \n void assemble_system(); \n void solve(); \n void refine_grid(); \n void output_results(const unsigned int cycle) const; \n\n MPI_Comm mpi_communicator; \n\n parallel::distributed::Triangulation<dim> triangulation; \n\n FE_Q<dim> fe; \n DoFHandler<dim> dof_handler; \n\n IndexSet locally_owned_dofs; \n IndexSet locally_relevant_dofs; \n\n AffineConstraints<double> constraints; \n\n LA::MPI::SparseMatrix system_matrix; \n LA::MPI::Vector locally_relevant_solution; \n LA::MPI::Vector system_rhs; \n\n ConditionalOStream pcout; \n TimerOutput computing_timer; \n }; \n// @sect3{The <code>LaplaceProblem</code> class implementation} \n// @sect4{Constructor} \n\n// 构造函数和析构函数是相当微不足道的。除了我们在 step-6 中所做的,我们将我们想要工作的处理器集合设置为所有可用的机器(MPI_COMM_WORLD);要求三角化以确保网格保持平滑并自由精炼岛屿,例如;并初始化 <code>pcout</code> 变量,只允许处理器0输出任何东西。最后一块是初始化一个定时器,我们用它来决定程序的不同部分需要多少计算时间。\n\n template <int dim> \n LaplaceProblem<dim>::LaplaceProblem() \n : mpi_communicator(MPI_COMM_WORLD) \n , triangulation(mpi_communicator, \n typename Triangulation<dim>::MeshSmoothing( \n Triangulation<dim>::smoothing_on_refinement | \n Triangulation<dim>::smoothing_on_coarsening)) \n , fe(2) \n , dof_handler(triangulation) \n , pcout(std::cout, \n (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)) \n , computing_timer(mpi_communicator, \n pcout, \n TimerOutput::summary, \n TimerOutput::wall_times) \n {} \n\n// @sect4{LaplaceProblem::setup_system} \n\n// 下面这个函数可以说是整个程序中最有趣的一个,因为它涉及到了%并行 step-40 和顺序 step-6 的核心区别。\n\n// 在顶部我们做了我们一直在做的事情:告诉DoFHandler对象来分配自由度。由于我们在这里使用的三角测量是分布式的,DoFHandler对象足够聪明,它认识到在每个处理器上只能在它所拥有的单元上分配自由度;接下来是一个交换步骤,处理器互相告诉对方关于ghost单元的自由度。结果是DoFHandler知道本地拥有的单元和幽灵单元(即与本地拥有的单元相邻的单元)的自由度,但对更远的单元则一无所知,这与分布式计算的基本理念一致,即没有处理器可以知道所有的事情。\n\n template <int dim> \n void LaplaceProblem<dim>::setup_system() \n { \n TimerOutput::Scope t(computing_timer, \"setup\"); \n\n dof_handler.distribute_dofs(fe); \n\n// 接下来的两行提取了一些我们以后需要的信息,即两个索引集,提供了关于哪些自由度为当前处理器所拥有的信息(这些信息将被用来初始化解和右手向量以及系统矩阵,表明哪些元素要存储在当前处理器上,哪些要期望存储在其他地方);以及一个索引集,表明哪些自由度是本地相关的(即生活在当前处理器所拥有的单元上或本地所拥有的单元周围的鬼魂单元上;我们将把这些自由度存储在当前处理器上。 例如,生活在当前处理器拥有的单元上或本地拥有的单元周围的幽灵单元层上;例如,我们需要所有这些自由度来估计本地单元的误差)。)\n\n locally_owned_dofs = dof_handler.locally_owned_dofs(); \n DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n\n// 接下来,让我们初始化解和右手边的向量。如上所述,我们寻求的解向量不仅存储了我们自己的元素,还存储了幽灵条目;另一方面,右手向量只需要有当前处理器拥有的条目,因为我们所做的只是向其中写入,而不是从其中读取本地拥有的单元(当然,线性求解器会从其中读取,但它们并不关心自由度的几何位置)。\n\n locally_relevant_solution.reinit(locally_owned_dofs, \n locally_relevant_dofs, \n mpi_communicator); \n system_rhs.reinit(locally_owned_dofs, mpi_communicator); \n\n// 下一步是计算悬挂节点和边界值约束,我们将其合并为一个存储所有约束的对象。\n\n// 就像在%parallel中的所有其他事情一样,口头禅必须是:没有一个处理器可以存储整个宇宙的所有信息。因此,我们需要告诉AffineConstraints对象哪些自由度可以存储约束条件,哪些可以不期望存储任何信息。在我们的例子中,正如 @ref distributed 模块所解释的,我们需要在每个处理器上关心的自由度是本地相关的自由度,所以我们把这个传递给 AffineConstraints::reinit 函数。顺便提一下,如果你忘记传递这个参数,AffineConstraints类将分配一个长度等于它目前看到的最大自由度索引的数组。对于MPI进程数很高的处理器来说,这可能是非常大的 -- 也许是数十亿的数量级。然后,程序将为这个单一的数组分配比其他所有操作加起来还要多的内存。\n\n constraints.clear(); \n constraints.reinit(locally_relevant_dofs); \n DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n VectorTools::interpolate_boundary_values(dof_handler, \n 0, \n Functions::ZeroFunction<dim>(), \n constraints); \n constraints.close(); \n\n// 这个函数的最后一部分涉及到用伴随的稀疏模式初始化矩阵。和以前的教程程序一样,我们使用DynamicSparsityPattern作为一个中介,然后用它来初始化系统矩阵。为了做到这一点,我们必须告诉稀疏模式它的大小,但如上所述,所产生的对象不可能为每个全局自由度存储哪怕一个指针;我们最好的希望是它能存储每个局部相关自由度的信息,即所有我们在组装矩阵的过程中可能接触到的自由度( @ref distributed_paper \"分布式计算论文 \"有很长的讨论,为什么我们真的需要局部相关自由度,而不是在此背景下的小的局部活动自由度集)。\n\n// 所以我们告诉稀疏模式它的大小和要存储什么自由度,然后要求 DoFTools::make_sparsity_pattern 来填充它(这个函数忽略了所有不属于本地的单元,模仿我们下面在装配过程中的做法)。在这之后,我们调用一个函数,在处理器之间交换这些稀疏模式的条目,以便最后每个处理器真正知道它将拥有的那部分有限元矩阵中的所有条目。最后一步是用稀疏模式初始化矩阵。\n\n DynamicSparsityPattern dsp(locally_relevant_dofs); \n\n DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false); \n SparsityTools::distribute_sparsity_pattern(dsp, \n dof_handler.locally_owned_dofs(), \n mpi_communicator, \n locally_relevant_dofs); \n\n system_matrix.reinit(locally_owned_dofs, \n locally_owned_dofs, \n dsp, \n mpi_communicator); \n } \n\n// @sect4{LaplaceProblem::assemble_system} \n\n// 然后组装线性系统的函数相对来说比较无聊,几乎和我们之前看到的一模一样。需要注意的地方是。\n\n// - 装配必须只在本地拥有的单元上循环。有多种方法来测试;例如,我们可以将一个单元的subdomain_id与三角形的信息进行比较,如<code>cell->subdomain_id() == triangulation.local_owned_subdomain()</code>,或者跳过所有条件<code>cell->is_ghost() || cell->is_artificial()</code>为真的单元。然而,最简单的方法是简单地询问单元格是否为本地处理器所拥有。\n\n// - 将本地贡献复制到全局矩阵中必须包括分配约束和边界值。换句话说,我们不能(就像我们在 step-6 中所做的那样)首先将每个本地贡献复制到全局矩阵中,然后在后面的步骤中才处理悬挂节点的约束和边界值。原因是,正如在 step-17 中所讨论的那样,一旦矩阵中的任意元素被组装到矩阵中,并行矢量类就不能提供对这些元素的访问--部分原因是它们可能不再存在于当前的处理器中,而是被运到了不同的机器上。\n\n// - 我们计算右手边的方式(考虑到介绍中的公式)可能不是最优雅的,但对于重点在某个完全不同的地方的程序来说是可以的。\n\n template <int dim> \n void LaplaceProblem<dim>::assemble_system() \n { \n TimerOutput::Scope t(computing_timer, \"assembly\"); \n\n const QGauss<dim> quadrature_formula(fe.degree + 1); \n\n FEValues<dim> fe_values(fe, \n quadrature_formula, \n update_values | update_gradients | \n update_quadrature_points | update_JxW_values); \n\n const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n const unsigned int n_q_points = quadrature_formula.size(); \n\n FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n Vector<double> cell_rhs(dofs_per_cell); \n\n std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n for (const auto &cell : dof_handler.active_cell_iterators()) \n if (cell->is_locally_owned()) \n { \n cell_matrix = 0.; \n cell_rhs = 0.; \n\n fe_values.reinit(cell); \n\n for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n { \n const double rhs_value = \n (fe_values.quadrature_point(q_point)[1] > \n 0.5 + \n 0.25 * std::sin(4.0 * numbers::PI * \n fe_values.quadrature_point(q_point)[0]) ? \n 1. : \n -1.); \n\n for (unsigned int i = 0; i < dofs_per_cell; ++i) \n { \n for (unsigned int j = 0; j < dofs_per_cell; ++j) \n cell_matrix(i, j) += fe_values.shape_grad(i, q_point) * \n fe_values.shape_grad(j, q_point) * \n fe_values.JxW(q_point); \n\n cell_rhs(i) += rhs_value * // \n fe_values.shape_value(i, q_point) * // \n fe_values.JxW(q_point); \n } \n } \n\n cell->get_dof_indices(local_dof_indices); \n constraints.distribute_local_to_global(cell_matrix, \n cell_rhs, \n local_dof_indices, \n system_matrix, \n system_rhs); \n } \n\n// 注意,上面的装配只是一个局部操作。因此,为了形成 \"全局 \"线性系统,需要在所有处理器之间进行同步。这可以通过调用函数compress()来实现。参见 @ref GlossCompress \"压缩分布式对象\",以了解更多关于compress()的设计目的的信息。\n\n system_matrix.compress(VectorOperation::add); \n system_rhs.compress(VectorOperation::add); \n } \n\n// @sect4{LaplaceProblem::solve} \n\n// 尽管在可能是数以万计的处理器上求解线性系统到目前为止并不是一项微不足道的工作,但完成这项工作的函数--至少在外表上--相对简单。大部分的部分你都见过了。真正值得一提的只有两件事。\n\n// - 解算器和预处理器是建立在PETSc和Trilinos功能的deal.II包装上的。众所周知,大规模并行线性求解器的主要瓶颈实际上不是处理器之间的通信,而是很难产生能够很好地扩展到大量处理器的预处理程序。在21世纪前十年的后半段,代数多网格(AMG)方法在这种情况下显然是非常有效的,我们将使用其中的一种方法--要么是可以通过PETSc接口的Hypre软件包的BoomerAMG实现,要么是由ML提供的预处理程序,它是Trilinos的一部分--用于当前的程序。解算器本身的其余部分是模板,之前已经展示过了。由于线性系统是对称和正定的,我们可以使用CG方法作为外解器。\n\n// - 最终,我们想要一个向量,它不仅存储了当前处理器拥有的自由度的解的元素,而且还存储了所有其他本地相关的自由度。另一方面,求解器本身需要一个在处理器之间唯一分割的向量,没有任何重叠。因此,我们在这个函数的开头创建一个具有这些特性的向量,用它来求解线性系统,并在最后才把它分配给我们想要的向量。这最后一步确保所有的鬼魂元素也在必要时被复制。\n\n template <int dim> \n void LaplaceProblem<dim>::solve() \n { \n TimerOutput::Scope t(computing_timer, \"solve\"); \n LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, \n mpi_communicator); \n\n SolverControl solver_control(dof_handler.n_dofs(), 1e-12); \n\n#ifdef USE_PETSC_LA \n LA::SolverCG solver(solver_control, mpi_communicator); \n#else \n LA::SolverCG solver(solver_control); \n#endif \n\n LA::MPI::PreconditionAMG preconditioner; \n\n LA::MPI::PreconditionAMG::AdditionalData data; \n\n#ifdef USE_PETSC_LA \n data.symmetric_operator = true; \n#else \n/* Trilinos的默认值是好的 */ \n#endif \n preconditioner.initialize(system_matrix, data); \n\n solver.solve(system_matrix, \n completely_distributed_solution, \n system_rhs, \n preconditioner); \n\n pcout << \" Solved in \" << solver_control.last_step() << \" iterations.\" \n << std::endl; \n\n constraints.distribute(completely_distributed_solution); \n\n locally_relevant_solution = completely_distributed_solution; \n } \n\n// @sect4{LaplaceProblem::refine_grid} \n\n// 估计误差和细化网格的函数又与 step-6 中的函数几乎完全一样。唯一不同的是,标志着要细化的单元格的函数现在在命名空间 parallel::distributed::GridRefinement 中 -- 这个命名空间的函数可以在所有参与的处理器之间进行通信,并确定全局阈值,用于决定哪些单元格要细化,哪些要粗化。\n\n// 注意,我们不需要对KellyErrorEstimator类做任何特殊处理:我们只是给它一个向量,其元素数量与本地三角形的单元(本地拥有的单元、幽灵单元和人工单元)一样多,但它只填入那些对应于本地拥有的单元的条目。\n\n template <int dim> \n void LaplaceProblem<dim>::refine_grid() \n { \n TimerOutput::Scope t(computing_timer, \"refine\"); \n\n Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n KellyErrorEstimator<dim>::estimate( \n dof_handler, \n QGauss<dim - 1>(fe.degree + 1), \n std::map<types::boundary_id, const Function<dim> *>(), \n locally_relevant_solution, \n estimated_error_per_cell); \n parallel::distributed::GridRefinement::refine_and_coarsen_fixed_number( \n triangulation, estimated_error_per_cell, 0.3, 0.03); \n triangulation.execute_coarsening_and_refinement(); \n } \n\n// @sect4{LaplaceProblem::output_results} \n\n// 与 step-6 中的相应函数相比,这里的函数要复杂一点。有两个原因:第一个原因是,我们不只是想输出解决方案,还想输出每个单元的处理器(即它在哪个 \"子域\")。其次,正如在 step-17 和 step-18 中详细讨论的那样,生成图形数据可能是并行化的一个瓶颈。在 step-18 中,我们将这一步骤从实际计算中移出,而是将其转移到一个单独的程序中,随后将各个处理器的输出合并到一个文件中。但这并不具规模:如果处理器的数量很大,这可能意味着在单个处理器上合并数据的步骤后来成为程序中运行时间最长的部分,或者它可能产生一个大到无法再可视化的文件。我们在这里遵循一个更合理的方法,即为每个MPI进程创建单独的文件,并将其留给可视化程序来理解。\n\n// 首先,函数的顶部看起来和平时一样。除了附加解决方案向量(包含所有本地相关元素的条目,而不仅仅是本地拥有的元素)外,我们还附加一个数据向量,为每个单元存储该单元所属的子域。这稍微有点棘手,因为当然不是每个处理器都知道每个单元。因此,我们附加的向量有一个当前处理器在其网格中拥有的每个单元的条目(本地拥有的单元、幽灵单元和人造单元),但DataOut类将忽略所有对应于不属于当前处理器的单元的条目。因此,我们在这些向量条目中写入什么值实际上并不重要:我们只需用当前MPI进程的编号(即当前进程的子域_id)来填充整个向量;这就正确地设置了我们关心的值,即对应于本地拥有的单元的条目,而为所有其他元素提供了错误的值--但无论如何这些都会被忽略。\n\n template <int dim> \n void LaplaceProblem<dim>::output_results(const unsigned int cycle) const \n { \n DataOut<dim> data_out; \n data_out.attach_dof_handler(dof_handler); \n data_out.add_data_vector(locally_relevant_solution, \"u\"); \n\n Vector<float> subdomain(triangulation.n_active_cells()); \n for (unsigned int i = 0; i < subdomain.size(); ++i) \n subdomain(i) = triangulation.locally_owned_subdomain(); \n data_out.add_data_vector(subdomain, \"subdomain\"); \n\n data_out.build_patches(); \n\n// 下一步是把这些数据写到磁盘上。在MPI-IO的帮助下,我们最多可以并行写入8个VTU文件。此外,还产生了一个PVTU记录,它将写入的VTU文件分组。\n\n data_out.write_vtu_with_pvtu_record( \n \"./\", \"solution\", cycle, mpi_communicator, 2, 8); \n } \n\n// @sect4{LaplaceProblem::run} \n\n// 控制程序整体行为的函数又和 step-6 中的一样。小的区别是使用 <code>pcout</code> instead of <code>std::cout</code> 来输出到控制台(也见 step-17 ),而且我们只在最多涉及32个处理器的情况下产生图形输出。如果没有这个限制,人们很容易在没有阅读这个程序的情况下粗心大意地运行这个程序,从而导致集群互连中断,并填满任何可用的文件系统 :-)\n\n// 与 step-6 的一个功能上的区别是使用了一个正方形域,并且我们从一个稍细的网格开始(5个全局细化周期)--在4个单元上开始显示一个大规模的%并行程序没有什么意义(尽管承认在1024单元上开始显示的意义只是稍强)。\n\n template <int dim> \n void LaplaceProblem<dim>::run() \n { \n pcout << \"Running with \" \n#ifdef USE_PETSC_LA \n << \"PETSc\" \n#else \n << \"Trilinos\" \n#endif \n << \" on \" << Utilities::MPI::n_mpi_processes(mpi_communicator) \n << \" MPI rank(s)...\" << std::endl; \n\n const unsigned int n_cycles = 8; \n for (unsigned int cycle = 0; cycle < n_cycles; ++cycle) \n { \n pcout << \"Cycle \" << cycle << ':' << std::endl; \n\n if (cycle == 0) \n { \n GridGenerator::hyper_cube(triangulation); \n triangulation.refine_global(5); \n } \n else \n refine_grid(); \n\n setup_system(); \n\n pcout << \" Number of active cells: \" \n << triangulation.n_global_active_cells() << std::endl \n << \" Number of degrees of freedom: \" << dof_handler.n_dofs() \n << std::endl; \n\n assemble_system(); \n solve(); \n\n if (Utilities::MPI::n_mpi_processes(mpi_communicator) <= 32) \n { \n TimerOutput::Scope t(computing_timer, \"output\"); \n output_results(cycle); \n } \n\n computing_timer.print_summary(); \n computing_timer.reset(); \n\n pcout << std::endl; \n } \n } \n} // namespace Step40 \n\n// @sect4{main()} \n\n// 最后一个函数, <code>main()</code> ,同样具有与所有其他程序相同的结构,特别是 step-6 。像其他使用MPI的程序一样,我们必须初始化和最终确定MPI,这是用辅助对象 Utilities::MPI::MPI_InitFinalize. 完成的。该类的构造函数也初始化了依赖MPI的库,如p4est、PETSc、SLEPc和Zoltan(尽管最后两个在本教程中没有使用)。这里的顺序很重要:在这些库被初始化之前,我们不能使用它们,所以在创建 Utilities::MPI::MPI_InitFinalize. 的实例之前做任何事情都没有意义。\n\n// 在求解器完成后,LaplaceProblem解构器将运行,然后是 Utilities::MPI::MPI_InitFinalize::~MPI_InitFinalize(). 这个顺序也很重要: Utilities::MPI::MPI_InitFinalize::~MPI_InitFinalize() 调用 <code>PetscFinalize</code> (以及其他库的最终确定函数),这将删除任何正在使用的PETSc对象。这必须在我们解构拉普拉斯求解器之后进行,以避免双重删除错误。幸运的是,由于C++的析构器调用顺序规则,我们不需要担心这些:一切都以正确的顺序发生(即,与构造顺序相反)。由 Utilities::MPI::MPI_InitFinalize::~MPI_InitFinalize() 调用的最后一个函数是 <code>MPI_Finalize</code> :也就是说,一旦这个对象被析构,程序应该退出,因为MPI将不再可用。\n\nint main(int argc, char *argv[]) \n{ \n try \n { \n using namespace dealii; \n using namespace Step40; \n\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n LaplaceProblem<2> laplace_problem_2d; \n laplace_problem_2d.run(); \n } \n catch (std::exception &exc) \n { \n std::cerr << std::endl \n << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n std::cerr << \"Exception on processing: \" << std::endl \n << exc.what() << std::endl \n << \"Aborting!\" << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n\n return 1; \n } \n catch (...) \n { \n std::cerr << std::endl \n << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n std::cerr << \"Unknown exception!\" << std::endl \n << \"Aborting!\" << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n return 1; \n } \n\n return 0; \n} \n\n", "meta": {"hexsha": "8a092d585907c50062f3308e84fd9c7eb042ae4a", "size": 20081, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-40/step-40.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-40/step-40.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-40/step-40.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4044265594, "max_line_length": 458, "alphanum_fraction": 0.6705841343, "num_tokens": 8844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.09291882242470713}}
{"text": "/* $Id: step-15.cc 27656 2012-11-21 13:12:20Z bangerth $ */\n/* Author: Sven Wetterauer, University of Heidelberg, 2012 */\n\n/* $Id: step-15.cc 27656 2012-11-21 13:12:20Z bangerth $ */\n/* */\n/* Copyright (C) 2012 by the deal.II authors */\n/* */\n/* This file is subject to QPL and may not be distributed */\n/* without copyright and license information. Please refer */\n/* to the file deal.II/doc/license.html for the text and */\n/* further information on this license. */\n\n// @sect3{Include files}\n\n// The first few files have already been covered in previous examples and will\n// thus not be further commented on.\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/compressed_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/grid/grid_refinement.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_q.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n\n\n#include <fstream>\n#include <iostream>\n\n// We will use adaptive mesh refinement between Newton interations. To do so,\n// we need to be able to work with a solution on the new mesh, although it was\n// computed on the old one. The SolutionTransfer class transfers the solution\n// from the old to the new mesh:\n\n#include <deal.II/numerics/solution_transfer.h>\n\n// We then open a namepsace for this program and import everything from the\n// dealii namespace into it, as in previous programs:\nnamespace Step15\n{\n using namespace dealii;\n\n\n // @sect3{The <code>MinimalSurfaceProblem</code> class template}\n\n // The class template is basically the same as in step-6. Three additions\n // are made:\n // - There are two solution vectors, one for the Newton update\n // $\\delta u^n$, and one for the current iterate $u^n$.\n // - The <code>setup_system</code> function takes an argument that denotes whether\n // this is the first time it is called or not. The difference is that the\n // first time around we need to distributed degrees of freedom and set the\n // solution vector for $u^n$ to the correct size. The following times, the\n // function is called after we have already done these steps as part of\n // refining the mesh in <code>refine_mesh</code>.\n // - We then also need new functions: <code>set_boundary_values()</code>\n // takes care of setting the boundary values on the solution vector\n // correctly, as discussed at the end of the\n // introduction. <code>compute_residual()</code> is a function that computes\n // the norm of the nonlinear (discrete) residual. We use this function to\n // monitor convergence of the Newton iteration. The function takes a step\n // length $\\alpha^n$ as argument to compute the residual of $u^n + \\alpha^n\n // \\; \\delta u^n$. This is something one typically needs for step length\n // control, although we will not use this feature here. Finally,\n // <code>determine_step_length()</code> computes the step length $\\alpha^n$\n // in each Newton iteration. As discussed in the introduction, we here use a\n // fixed step length and leave implementing a better strategy as an\n // exercise.\n\n template <int dim>\n class MinimalSurfaceProblem\n {\n public:\n MinimalSurfaceProblem ();\n ~MinimalSurfaceProblem ();\n\n void run ();\n\n private:\n void setup_system (const bool initial_step);\n void assemble_system ();\n void solve ();\n void refine_mesh ();\n void set_boundary_values ();\n double compute_residual (const double alpha) const;\n double determine_step_length () const;\n\n Triangulation<dim> triangulation;\n\n DoFHandler<dim> dof_handler;\n FE_Q<dim> fe;\n\n ConstraintMatrix hanging_node_constraints;\n\n SparsityPattern sparsity_pattern;\n SparseMatrix<double> system_matrix;\n\n Vector<double> present_solution;\n Vector<double> newton_update;\n Vector<double> system_rhs;\n };\n\n // @sect3{Boundary condition}\n\n // The boundary condition is implemented just like in step-4. It is chosen\n // as $g(x,y)=\\sin(2 \\pi (x+y))$:\n\n template <int dim>\n class BoundaryValues : public Function<dim>\n {\n public:\n BoundaryValues () : Function<dim>() {}\n\n virtual double value (const Point<dim> &p,\n const unsigned int component = 0) const;\n };\n\n\n template <int dim>\n double BoundaryValues<dim>::value (const Point<dim> &p,\n const unsigned int /*component*/) const\n {\n return std::sin(2 * numbers::PI * (p[0]+p[1]));\n }\n\n // @sect3{The <code>MinimalSurfaceProblem</code> class implementation}\n\n // @sect4{MinimalSurfaceProblem::MinimalSurfaceProblem}\n\n // The constructor and destructor of the class are the same as in the first\n // few tutorials.\n\n template <int dim>\n MinimalSurfaceProblem<dim>::MinimalSurfaceProblem ()\n :\n dof_handler (triangulation),\n fe (2)\n {}\n\n\n\n template <int dim>\n MinimalSurfaceProblem<dim>::~MinimalSurfaceProblem ()\n {\n dof_handler.clear ();\n }\n\n // @sect4{MinimalSurfaceProblem::setup_system}\n\n // As always in the setup-system function, we setup the variables of the\n // finite element method. There are same differences to step-6, because\n // there we start solving the PDE from scratch in every refinement cycle\n // whereas here we need to take the solution from the previous mesh onto the\n // current mesh. Consequently, we can't just reset solution vectors. The\n // argument passed to this function thus indicates whether we can\n // distributed degrees of freedom (plus compute constraints) and set the\n // solution vector to zero or whether this has happened elsewhere already\n // (specifically, in <code>refine_mesh()</code>).\n\n template <int dim>\n void MinimalSurfaceProblem<dim>::setup_system (const bool initial_step)\n {\n if (initial_step)\n {\n dof_handler.distribute_dofs (fe);\n present_solution.reinit (dof_handler.n_dofs());\n\n hanging_node_constraints.clear ();\n DoFTools::make_hanging_node_constraints (dof_handler,\n hanging_node_constraints);\n hanging_node_constraints.close ();\n }\n\n\n // The remaining parts of the function are the same as in step-6.\n\n newton_update.reinit (dof_handler.n_dofs());\n system_rhs.reinit (dof_handler.n_dofs());\n\n CompressedSparsityPattern c_sparsity(dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern (dof_handler, c_sparsity);\n\n hanging_node_constraints.condense (c_sparsity);\n\n sparsity_pattern.copy_from(c_sparsity);\n system_matrix.reinit (sparsity_pattern);\n }\n\n // @sect4{MinimalSurfaceProblem::assemble_system}\n\n // This function does the same as in the previous tutorials except that now,\n // of course, the matrix and right hand side functions depend on the\n // previous iteration's solution. As discussed in the introduction, we need\n // to use zero boundary values for the Newton updates; we compute them at\n // the end of this function.\n //\n // The top of the function contains the usual boilerplate code, setting up\n // the objects that allow us to evaluate shape functions at quadrature\n // points and temporary storage locations for the local matrices and\n // vectors, as well as for the gradients of the previous solution at the\n // quadrature points. We then start the loop over all cells:\n template <int dim>\n void MinimalSurfaceProblem<dim>::assemble_system ()\n {\n const QGauss<dim> quadrature_formula(3);\n\n system_matrix = 0;\n system_rhs = 0;\n\n FEValues<dim> fe_values (fe, quadrature_formula,\n update_gradients |\n update_quadrature_points |\n update_JxW_values);\n\n const unsigned int dofs_per_cell = fe.dofs_per_cell;\n const unsigned int n_q_points = quadrature_formula.size();\n\n FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell);\n Vector<double> cell_rhs (dofs_per_cell);\n\n std::vector<Tensor<1, dim> > old_solution_gradients(n_q_points);\n\n std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n typename DoFHandler<dim>::active_cell_iterator\n cell = dof_handler.begin_active(),\n endc = dof_handler.end();\n for (; cell!=endc; ++cell)\n {\n cell_matrix = 0;\n cell_rhs = 0;\n\n fe_values.reinit (cell);\n\n // For the assembly of the linear system, we have to obtain the values\n // of the previous solution's gradients at the quadrature\n // points. There is a standard way of doing this: the\n // FEValues::get_function function takes a vector that represents a\n // finite element field defined on a DoFHandler, and evaluates the\n // gradients of this field at the quadrature points of the cell with\n // which the FEValues object has last been reinitialized. The values\n // of the gradients at all quadrature points are then written into the\n // second argument:\n fe_values.get_function_gradients(present_solution,\n old_solution_gradients);\n\n // With this, we can then do the integration loop over all quadrature\n // points and shape functions. Having just computed the gradients of\n // the old solution in the quadrature points, we are able to compute\n // the coefficients $a_{n}$ in these points. The assembly of the\n // system itself then looks similar to what we always do with the\n // exception of the nonlinear terms, as does copying the results from\n // the local objects into the global ones:\n for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n {\n const double coeff\n = 1.0 / std::sqrt(1 +\n old_solution_gradients[q_point] *\n old_solution_gradients[q_point]);\n\n for (unsigned int i=0; i<dofs_per_cell; ++i)\n {\n for (unsigned int j=0; j<dofs_per_cell; ++j)\n {\n cell_matrix(i, j) += (fe_values.shape_grad(i, q_point)\n * coeff\n * (fe_values.shape_grad(j, q_point)\n -\n coeff * coeff\n * (fe_values.shape_grad(j, q_point)\n *\n old_solution_gradients[q_point])\n * old_solution_gradients[q_point]\n )\n * fe_values.JxW(q_point));\n }\n\n cell_rhs(i) -= (fe_values.shape_grad(i, q_point)\n * coeff\n * old_solution_gradients[q_point]\n * fe_values.JxW(q_point));\n }\n }\n\n cell->get_dof_indices (local_dof_indices);\n for (unsigned int i=0; i<dofs_per_cell; ++i)\n {\n for (unsigned int j=0; j<dofs_per_cell; ++j)\n system_matrix.add (local_dof_indices[i],\n local_dof_indices[j],\n cell_matrix(i,j));\n\n system_rhs(local_dof_indices[i]) += cell_rhs(i);\n }\n }\n\n // Finally, we remove hanging nodes from the system and apply zero\n // boundary values to the linear system that defines the Newton updates\n // $\\delta u^n$:\n hanging_node_constraints.condense (system_matrix);\n hanging_node_constraints.condense (system_rhs);\n\n std::map<unsigned int,double> boundary_values;\n VectorTools::interpolate_boundary_values (dof_handler,\n 0,\n ZeroFunction<dim>(),\n boundary_values);\n MatrixTools::apply_boundary_values (boundary_values,\n system_matrix,\n newton_update,\n system_rhs);\n }\n\n\n\n // @sect4{MinimalSurfaceProblem::solve}\n\n // The solve function is the same as always. At the end of the solution\n // process we update the current solution by setting\n // $u^{n+1}=u^n+\\alpha^n\\;\\delta u^n$.\n template <int dim>\n void MinimalSurfaceProblem<dim>::solve ()\n {\n SolverControl solver_control (system_rhs.size(),\n system_rhs.l2_norm()*1e-6);\n SolverCG<> solver (solver_control);\n\n PreconditionSSOR<> preconditioner;\n preconditioner.initialize(system_matrix, 1.2);\n\n solver.solve (system_matrix, newton_update, system_rhs,\n preconditioner);\n\n hanging_node_constraints.distribute (newton_update);\n\n const double alpha = determine_step_length();\n present_solution.add (alpha, newton_update);\n }\n\n\n // @sect4{MinimalSurfaceProblem::refine_mesh}\n\n // The first part of this function is the same as in step-6... However,\n // after refining the mesh we have to transfer the old solution to the new\n // one which we do with the help of the SolutionTransfer class. The process\n // is slightly convoluted, so let us describe it in detail:\n template <int dim>\n void MinimalSurfaceProblem<dim>::refine_mesh ()\n {\n Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n\n KellyErrorEstimator<dim>::estimate (dof_handler,\n QGauss<dim-1>(3),\n typename FunctionMap<dim>::type(),\n present_solution,\n estimated_error_per_cell);\n\n GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n estimated_error_per_cell,\n 0.3, 0.03);\n\n // Then we need an additional step: if, for example, you flag a cell that\n // is once more refined than its neighbor, and that neighbor is not\n // flagged for refinement, we would end up with a jump of two refinement\n // levels across a cell interface. To avoid these situations, the library\n // will silently also have to refine the neighbor cell once. It does so by\n // calling the Triangulation::prepare_coarsening_and_refinement function\n // before actually doing the refinement and coarsening. This function\n // flags a set of additional cells for refinement or coarsening, to\n // enforce rules like the one-hanging-node rule. The cells that are\n // flagged for refinement and coarsening after calling this function are\n // exactly the ones that will actually be refined or coarsened. Usually,\n // you don't have to do this by hand\n // (Triangulation::execute_coarsening_and_refinement does this for\n // you). However, we need to initialize the SolutionTransfer class and it\n // needs to know the final set of cells that will be coarsened or refined\n // in order to store the data from the old mesh and transfer to the new\n // one. Thus, we call the function by hand:\n triangulation.prepare_coarsening_and_refinement ();\n\n // With this out of the way, we initialize a SolutionTransfer object with\n // the present DoFHandler and attach the solution vector to it, followed\n // by doing the actual refinement and distribution of degrees of freedom\n // on the new mesh\n SolutionTransfer<dim> solution_transfer(dof_handler);\n solution_transfer.prepare_for_coarsening_and_refinement(present_solution);\n\n triangulation.execute_coarsening_and_refinement();\n\n dof_handler.distribute_dofs(fe);\n\n // Finally, we retrieve the old solution interpolated to the new\n // mesh. Since the SolutionTransfer function does not actually store the\n // values of the old solution, but rather indices, we need to preserve the\n // old solution vector until we have gotten the new interpolated\n // values. Thus, we have the new values written into a temporary vector,\n // and only afterwards write them into the solution vector object. Once we\n // have this solution we have to make sure that the $u^n$ we now have\n // actually has the correct boundary values. As explained at the end of\n // the introduction, this is not automatically the case even if the\n // solution before refinement had the correct boundary values, and so we\n // have to explicitly make sure that it now has:\n Vector<double> tmp(dof_handler.n_dofs());\n solution_transfer.interpolate(present_solution, tmp);\n present_solution = tmp;\n\n set_boundary_values ();\n\n // On the new mesh, there are different hanging nodes, which we have to\n // compute again. To ensure there are no hanging nodes of the old mesh in\n // the object, it's first cleared. To be on the safe side, we then also\n // make sure that the current solution's vector entries satisfy the\n // hanging node constraints:\n\n hanging_node_constraints.clear();\n\n DoFTools::make_hanging_node_constraints(dof_handler,\n hanging_node_constraints);\n hanging_node_constraints.close();\n\n hanging_node_constraints.distribute (present_solution);\n\n // We end the function by updating all the remaining data structures,\n // indicating to <code>setup_dofs()</code> that this is not the first\n // go-around and that it needs to preserve the content of the solution\n // vector:\n setup_system (false);\n }\n\n\n\n // @sect4{MinimalSurfaceProblem::set_boundary_values}\n\n // The next function ensures that the solution vector's entries respect the\n // boundary values for our problem. Having refined the mesh (or just\n // started computations), there might be new nodal points on the\n // boundary. These have values that are simply interpolated from the\n // previous mesh (or are just zero), instead of the correct boundary\n // values. This is fixed up by setting all boundary nodes explicit to the\n // right value:\n template <int dim>\n void MinimalSurfaceProblem<dim>::set_boundary_values ()\n {\n std::map<unsigned int, double> boundary_values;\n VectorTools::interpolate_boundary_values (dof_handler,\n 0,\n BoundaryValues<dim>(),\n boundary_values);\n for (std::map<unsigned int, double>::const_iterator\n p = boundary_values.begin();\n p != boundary_values.end(); ++p)\n present_solution(p->first) = p->second;\n }\n\n\n // @sect4{MinimalSurfaceProblem::compute_residual}\n\n // In order to monitor convergence, we need a way to compute the norm of the\n // (discrete) residual, i.e., the norm of the vector\n // $\\left<F(u^n),\\varphi_i\\right>$ with $F(u)=-\\nabla \\cdot \\left(\n // \\frac{1}{\\sqrt{1+|\\nabla u|^{2}}}\\nabla u \\right)$ as discussed in the\n // introduction. It turns out that (although we don't use this feature in\n // the current version of the program) one needs to compute the residual\n // $\\left<F(u^n+\\alpha^n\\;\\delta u^n),\\varphi_i\\right>$ when determining\n // optimal step lengths, and so this is what we implement here: the function\n // takes the step length $\\alpha^n$ as an argument. The original\n // functionality is of course obtained by passing a zero as argument.\n //\n // In the function below, we first set up a vector for the residual, and\n // then a vector for the evaluation point $u^n+\\alpha^n\\;\\delta u^n$. This\n // is followed by the same boilerplate code we use for all integration\n // operations:\n template <int dim>\n double MinimalSurfaceProblem<dim>::compute_residual (const double alpha) const\n {\n Vector<double> residual (dof_handler.n_dofs());\n\n Vector<double> evaluation_point (dof_handler.n_dofs());\n evaluation_point = present_solution;\n evaluation_point.add (alpha, newton_update);\n\n const QGauss<dim> quadrature_formula(3);\n FEValues<dim> fe_values (fe, quadrature_formula,\n update_gradients |\n update_quadrature_points |\n update_JxW_values);\n\n const unsigned int dofs_per_cell = fe.dofs_per_cell;\n const unsigned int n_q_points = quadrature_formula.size();\n\n Vector<double> cell_rhs (dofs_per_cell);\n std::vector<Tensor<1, dim> > gradients(n_q_points);\n\n std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n typename DoFHandler<dim>::active_cell_iterator\n cell = dof_handler.begin_active(),\n endc = dof_handler.end();\n for (; cell!=endc; ++cell)\n {\n cell_rhs = 0;\n fe_values.reinit (cell);\n\n // The actual computation is much as in\n // <code>assemble_system()</code>. We first evaluate the gradients of\n // $u^n+\\alpha^n\\,\\delta u^n$ at the quadrature points, then compute\n // the coefficient $a_n$, and then plug it all into the formula for\n // the residual:\n fe_values.get_function_gradients (evaluation_point,\n gradients);\n\n\n for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n {\n const double coeff = 1/std::sqrt(1 +\n gradients[q_point] *\n gradients[q_point]);\n\n for (unsigned int i = 0; i < dofs_per_cell; ++i)\n cell_rhs(i) -= (fe_values.shape_grad(i, q_point)\n * coeff\n * gradients[q_point]\n * fe_values.JxW(q_point));\n }\n\n cell->get_dof_indices (local_dof_indices);\n for (unsigned int i=0; i<dofs_per_cell; ++i)\n residual(local_dof_indices[i]) += cell_rhs(i);\n }\n\n // At the end of this function we also have to deal with the hanging node\n // constraints and with the issue of boundary values. With regard to the\n // latter, we have to set to zero the elements of the residual vector for\n // all entries that correspond to degrees of freedom that sit at the\n // boundary. The reason is that because the value of the solution there is\n // fixed, they are of course no \"real\" degrees of freedom and so, strictly\n // speaking, we shouldn't have assembled entries in the residual vector\n // for them. However, as we always do, we want to do exactly the same\n // thing on every cell and so we didn't not want to deal with the question\n // of whether a particular degree of freedom sits at the boundary in the\n // integration above. Rather, we will simply set to zero these entries\n // after the fact. To this end, we first need to determine which degrees\n // of freedom do in fact belong to the boundary and then loop over all of\n // those and set the residual entry to zero. This happens in the following\n // lines which we have already seen used in step-11:\n hanging_node_constraints.condense (residual);\n\n std::vector<bool> boundary_dofs (dof_handler.n_dofs());\n DoFTools::extract_boundary_dofs (dof_handler,\n ComponentMask(),\n boundary_dofs);\n for (unsigned int i=0; i<dof_handler.n_dofs(); ++i)\n if (boundary_dofs[i] == true)\n residual(i) = 0;\n\n // At the end of the function, we return the norm of the residual:\n return residual.l2_norm();\n }\n\n\n\n // @sect4{MinimalSurfaceProblem::determine_step_length}\n\n // As discussed in the introduction, Newton's method frequently does not\n // converge if we always take full steps, i.e., compute $u^{n+1}=u^n+\\delta\n // u^n$. Rather, one needs a damping parameter (step length) $\\alpha^n$ and\n // set $u^{n+1}=u^n+\\alpha^n\\; delta u^n$. This function is the one called\n // to compute $\\alpha^n$.\n //\n // Here, we simply always return 0.1. This is of course a sub-optimal\n // choice: ideally, what one wants is that the step size goes to one as we\n // get closer to the solution, so that we get to enjoy the rapid quadratic\n // convergence of Newton's method. We will discuss better strategies below\n // in the results section.\n template <int dim>\n double MinimalSurfaceProblem<dim>::determine_step_length() const\n {\n return 0.1;\n }\n\n\n\n // @sect4{MinimalSurfaceProblem::run}\n\n // In the run function, we build the first grid and then have the top-level\n // logic for the Newton iteration. The function has two variables, one that\n // indicates whether this is the first time we solve for a Newton update and\n // one that indicates the refinement level of the mesh:\n template <int dim>\n void MinimalSurfaceProblem<dim>::run ()\n {\n unsigned int refinement = 0;\n bool first_step = true;\n\n // As described in the introduction, the domain is the unit disk around\n // the origin, created in the same way as shown in step-6. The mesh is\n // globally refined twice followed later on by several adaptive cycles:\n GridGenerator::hyper_ball (triangulation);\n static const HyperBallBoundary<dim> boundary;\n triangulation.set_boundary (0, boundary);\n triangulation.refine_global(2);\n\n // The Newton iteration starts next. During the first step we do not have\n // information about the residual prior to this step and so we continue\n // the Newton iteration until we have reached at least one iteration and\n // until residual is less than $10^{-3}$.\n //\n // At the beginning of the loop, we do a bit of setup work. In the first\n // go around, we compute the solution on the twice globally refined mesh\n // after setting up the basic data structures. In all following mesh\n // refinement loops, the mesh will be refined adaptively.\n double previous_res = 0;\n while (first_step || (previous_res>1e-3))\n {\n if (first_step == true)\n {\n std::cout << \"******** Initial mesh \"\n << \" ********\"\n << std::endl;\n\n setup_system (true);\n set_boundary_values ();\n }\n else\n {\n ++refinement;\n std::cout << \"******** Refined mesh \" << refinement\n << \" ********\"\n << std::endl;\n\n refine_mesh();\n }\n\n // On every mesh we do exactly five Newton steps. We print the initial\n // residual here and then start the iterations on this mesh.\n //\n // In every Newton step the system matrix and the right hand side have\n // to be computed first, after which we store the norm of the right\n // hand side as the residual to check against when deciding whether to\n // stop the iterations. We then solve the linear system (the function\n // also updates $u^{n+1}=u^n+\\alpha^n\\;\\delta u^n$) and output the\n // residual at the end of this Newton step:\n std::cout << \" Initial residual: \"\n << compute_residual(0)\n << std::endl;\n\n for (unsigned int inner_iteration=0; inner_iteration<5; ++inner_iteration)\n {\n assemble_system ();\n previous_res = system_rhs.l2_norm();\n\n solve ();\n\n first_step = false;\n std::cout << \" Residual: \"\n << compute_residual(0)\n << std::endl;\n }\n\n // Every fifth iteration, i.e., just before we refine the mesh again,\n // we output the solution as well as the Newton update. This happens\n // as in all programs before:\n DataOut<dim> data_out;\n\n data_out.attach_dof_handler (dof_handler);\n data_out.add_data_vector (present_solution, \"solution\");\n data_out.add_data_vector (newton_update, \"update\");\n data_out.build_patches ();\n const std::string filename = \"solution-\" +\n Utilities::int_to_string (refinement, 2) +\n \".vtk\";\n std::ofstream output (filename.c_str());\n data_out.write_vtk (output);\n\n }\n }\n}\n\n// @sect4{The main function}\n\n// Finally the main function. This follows the scheme of all other main\n// functions:\nint main ()\n{\n try\n {\n using namespace dealii;\n using namespace Step15;\n\n deallog.depth_console (0);\n\n MinimalSurfaceProblem<2> laplace_problem_2d;\n laplace_problem_2d.run ();\n }\n catch (std::exception &exc)\n {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n << exc.what() << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n\n return 1;\n }\n catch (...)\n {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n return 0;\n}\n", "meta": {"hexsha": "611921edad071675986aafeb10817561907b7ffc", "size": 30413, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-15/step-15.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-15/step-15.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-15/step-15.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 40.877688172, "max_line_length": 84, "alphanum_fraction": 0.6241081117, "num_tokens": 6719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.1732882016598637, "lm_q1q2_score": 0.08664410082993185}}
{"text": "// Copyright John Maddock 2007.\r\n// Copyright Paul A. Bristow 2010\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0. (See accompanying file\r\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Note that this file contains quickbook mark-up as well as code\r\n// and comments, don't change any of the special comment mark-ups!\r\n\r\n#include <iostream>\r\nusing std::cout; using std::endl;\r\n#include <cerrno> // for ::errno\r\n\r\n//[policy_eg_4\r\n\r\n/*`\r\nSuppose we want `C::foo()` to behave in a C-compatible way and set\r\n`::errno` on error rather than throwing any exceptions.\r\n\r\nWe'll begin by including the needed header for our function:\r\n*/\r\n\r\n#include <boost/math/special_functions.hpp>\r\n//using boost::math::tgamma; // Not needed because using C::tgamma.\r\n\r\n/*`\r\nOpen up the \"C\" namespace that we'll use for our functions, and\r\ndefine the policy type we want: in this case a C-style one that sets\r\n::errno and returns a standard value, rather than throwing exceptions.\r\n\r\nAny policies we don't specify here will inherit the defaults.\r\n*/\r\n\r\nnamespace C\r\n{ // To hold our C-style policy.\r\n //using namespace boost::math::policies; or explicitly:\r\n using boost::math::policies::policy;\r\n\r\n using boost::math::policies::domain_error;\r\n using boost::math::policies::pole_error;\r\n using boost::math::policies::overflow_error;\r\n using boost::math::policies::evaluation_error;\r\n using boost::math::policies::errno_on_error;\r\n\r\n typedef policy<\r\n domain_error<errno_on_error>,\r\n pole_error<errno_on_error>,\r\n overflow_error<errno_on_error>,\r\n evaluation_error<errno_on_error>\r\n > c_policy;\r\n\r\n/*`\r\nAll we need do now is invoke the BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS\r\nmacro passing our policy type c_policy as the single argument:\r\n*/\r\n\r\nBOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(c_policy)\r\n\r\n} // close namespace C\r\n\r\n/*`\r\nWe now have a set of forwarding functions defined in namespace C\r\nthat all look something like this:\r\n\r\n``\r\ntemplate <class RealType>\r\ninline typename boost::math::tools::promote_args<RT>::type\r\n tgamma(RT z)\r\n{\r\n return boost::math::tgamma(z, c_policy());\r\n}\r\n``\r\n\r\nSo that when we call `C::tgamma(z)`, we really end up calling\r\n`boost::math::tgamma(z, C::c_policy())`:\r\n*/\r\n\r\nint main()\r\n{\r\n errno = 0;\r\n cout << \"Result of tgamma(30000) is: \"\r\n << C::tgamma(30000) << endl; // Note using C::tgamma\r\n cout << \"errno = \" << errno << endl; // errno = 34\r\n cout << \"Result of tgamma(-10) is: \"\r\n << C::tgamma(-10) << endl;\r\n cout << \"errno = \" << errno << endl; // errno = 33, overwriting previous value of 34.\r\n}\r\n\r\n/*`\r\n\r\nWhich outputs:\r\n\r\n[pre\r\nResult of C::tgamma(30000) is: 1.#INF\r\nerrno = 34\r\nResult of C::tgamma(-10) is: 1.#QNAN\r\nerrno = 33\r\n]\r\n\r\nThis mechanism is particularly useful when we want to define a project-wide policy,\r\nand don't want to modify the Boost source,\r\nor to set project wide build macros (possibly fragile and easy to forget).\r\n\r\n*/\r\n//] //[/policy_eg_4]\r\n\r\n", "meta": {"hexsha": "1bb316e4bfdca896d8d9918defda16f893cd2b55", "size": 3023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/policy_eg_4.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/math/example/policy_eg_4.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/example/policy_eg_4.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 27.9907407407, "max_line_length": 89, "alphanum_fraction": 0.6834270592, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.18713269122913015, "lm_q1q2_score": 0.08554522407957789}}
{"text": "// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Copyright Paul A. Bristow 2015.\r\n// Copyright Christopher Kormanyos 2015.\r\n// Copyright Nikhar Agrawal 2015.\r\n\r\n// This file is written to be included from a Quickbook .qbk document.\r\n// It can be compiled by the C++ compiler, and run. Any output can\r\n// also be added here as comment or included or pasted in elsewhere.\r\n// Caution: this file contains Quickbook markup as well as code\r\n// and comments: don't change any of the special comment markups!\r\n\r\n// This file also includes Doxygen-style documentation about the function of the code.\r\n// See http://www.doxygen.org for details.\r\n\r\n//! \\file\r\n\r\n// Below are snippets of code that can be included into a Quickbook file.\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <exception>\r\n#include <typeinfo>\r\n#include <limits>\r\n\r\n#include <boost/cstdint.hpp>\r\n\r\n//[fixed_point_include_1\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n//] [/fixed_point_include_1]\r\n\r\n/*\r\n! Show numeric_limits values for a type.\r\n\\tparam T floating-point, fixed-point type.\r\n\\param os std::ostream, default @c std::cout\r\n*/\r\n\r\n// static int Functions to access template parameters for fixed_point \r\n// that are missing for fundamental integral and floating-point types.\r\n// Version selected on whether is not arithmetic, is floating_point or is integral.\r\n\r\ntemplate <typename NumericalType,\r\n typename EnableType = void>\r\nstruct numerical_details\r\n{\r\n static int get_range () { return 0; }\r\n static int get_resolution() { return 0; }\r\n};\r\n\r\n/*! Deduce fixed-point if @c std::is_class (so exclude @c bool, @c int...) and not arithmetic (exclude @c float, @c double...).\r\n*/\r\ntemplate <typename NumericalType>\r\nstruct numerical_details<NumericalType,\r\n typename std::enable_if< (std::is_arithmetic<NumericalType>::value == false)\r\n && (std::is_class<NumericalType>::value == true)>::type>\r\n{\r\n static int get_range () { return NumericalType::range; }\r\n static int get_resolution() { return NumericalType::resolution; }\r\n};\r\n\r\n/*! Deduce fundamental floating-point type @c float, @c double or @c long double. \r\n*/\r\n\r\ntemplate <typename NumericalType>\r\nstruct numerical_details<NumericalType,\r\n typename std::enable_if<std::is_floating_point<NumericalType>::value>::type>\r\n{\r\n static int get_range () { return 0; }\r\n static int get_resolution() { return std::numeric_limits<NumericalType>::digits; }\r\n};\r\n\r\n/*! Deduce fundamental integral type.\r\n*/\r\ntemplate <typename NumericalType>\r\nstruct numerical_details<NumericalType,\r\n typename std::enable_if<std::is_integral<NumericalType>::value>::type>\r\n{\r\n static int get_range () { return std::numeric_limits<NumericalType>::digits; }\r\n static int get_resolution() { return 0; }\r\n};\r\n\r\ntemplate <typename T>\r\nvoid show_fixed_point(std::ostream& os = std::cout)\r\n{\r\n using boost::fixed_point::negatable;\r\n\r\n os.precision(std::numeric_limits<T>::max_digits10);\r\n\r\n os << \"Numeric_limits of type: \"\r\n << typeid(T).name()\r\n << \"\\n range = \" << numerical_details<T>::get_range() // \r\n << \"\\n resolution = \" << numerical_details<T>::get_resolution()\r\n << \"\\n radix = \" << std::numeric_limits<T>::radix // Always 2 for fixed-point.\r\n << \"\\n digits = \" << std::numeric_limits<T>::digits; // Does not include any sign bit.\r\n\r\n if (std::is_signed<T>::value == true)\r\n {\r\n os << \"\\n signed \"\r\n << \"\\n total bits = \" << std::numeric_limits<T>::digits + 1; // DOES include sign bit.\r\n }\r\n\r\n if (std::numeric_limits<T>::is_exact == false)\r\n { // epsilon has meaning.\r\n os << \"\\n epsilon = \" << std::numeric_limits<T>::epsilon();\r\n }\r\n else\r\n {\r\n os << \"\\n exact = \" << std::numeric_limits<T>::is_exact;\r\n }\r\n\r\n // Avoid char values showing as a character or squiggle.\r\n BOOST_CONSTEXPR_OR_CONST bool is_any_character_type = ( std::is_same<T, signed char>::value \r\n || std::is_same<T, unsigned char>::value\r\n || std::is_same<T, char16_t>::value\r\n || std::is_same<T, char32_t>::value);\r\n\r\n os << \"\\n lowest = \";\r\n if(is_any_character_type)\r\n {\r\n os << static_cast<boost::int32_t>(std::numeric_limits<T>::lowest());\r\n }\r\n else\r\n {\r\n os << std::numeric_limits<T>::lowest();\r\n }\r\n\r\n BOOST_CONSTEXPR_OR_CONST bool is_8bit_character_type = ( std::is_same<T, signed char>::value\r\n || std::is_same<T, unsigned char>::value);\r\n\r\n os << \"\\n min = \";\r\n if(is_8bit_character_type)\r\n {\r\n os << static_cast<boost::int32_t>((std::numeric_limits<T>::min)());\r\n }\r\n else\r\n {\r\n os << (std::numeric_limits<T>::min)();\r\n }\r\n\r\n os << \"\\n max = \";\r\n if(is_8bit_character_type)\r\n {\r\n os << static_cast<boost::int32_t>((std::numeric_limits<T>::max)());\r\n }\r\n else\r\n {\r\n os << (std::numeric_limits<T>::max)();\r\n }\r\n\r\n os << \"\\n max_exponent = \" << std::numeric_limits<T>::max_exponent\r\n << \"\\n min_exponent = \" << std::numeric_limits<T>::min_exponent\r\n << \"\\n digits10 = \" << std::numeric_limits<T>::digits10\r\n << \"\\n max_digits10 = \" << std::numeric_limits<T>::max_digits10\r\n << \"\\n\"\r\n << std::endl;\r\n} // template <typename T> void show_fixed_point\r\n\r\nint main()\r\n{\r\n using boost::fixed_point::negatable;\r\n\r\n typedef negatable<15, -16> fixed_point_type_15m16;\r\n typedef negatable<11, -20> fixed_point_type_11m20;\r\n typedef negatable< 0, -31> fixed_point_type_0m31;\r\n typedef negatable<29, -2> fixed_point_type_29m2;\r\n typedef negatable<0, -168> fixed_point_type_0m168;\r\n typedef negatable<20, -148> fixed_point_type_20m148;\r\n\r\n try\r\n {\r\n std::cout.setf(std::ios_base::boolalpha | std::ios_base::showpoint); // Show any trailing zeros.\r\n std::cout << std::endl;\r\n\r\n//[fixed_example_1\r\n\r\n\r\n // Show all the significant digits for this particular type.\r\n\r\n // Fundamental (built-in) integral types.\r\n show_fixed_point<bool> ();\r\n show_fixed_point<signed char> ();\r\n show_fixed_point<unsigned char> ();\r\n show_fixed_point<char16_t> (); // Shows as type unsigned short.\r\n show_fixed_point<char32_t> (); // Shows as type unsigned int.\r\n show_fixed_point<short int> ();\r\n show_fixed_point<unsigned short int>();\r\n show_fixed_point<int> ();\r\n show_fixed_point<unsigned int> ();\r\n\r\n // Fundamental (built-in) floating-point types.\r\n show_fixed_point<float>();\r\n // digits 24 (leaving 8 for decimal exponent).\r\n // epsilon 1.2e-7.\r\n\r\n show_fixed_point<double>();\r\n // digits 53 (leaving 10 for decimal exponent).\r\n // epsilon 2.2e-16.\r\n show_fixed_point<long double>();\r\n // Varies with compiler\r\n // Using MSVC double == long double\r\n\r\n//] [/fixed_example_1]\r\n\r\n\r\n// Some fixed_point types using only a single 8-bit byte (signed char).\r\n\r\n//[fixed_point_15m16\r\n\r\n // Some fixed_point types using 32 bits, and more.\r\n show_fixed_point<fixed_point_type_15m16> (); // Even split bits between range and resolution. \r\n show_fixed_point<fixed_point_type_11m20> (); // More resolution than range.\r\n show_fixed_point<fixed_point_type_0m31> (); // All bits used for resolution.\r\n show_fixed_point<fixed_point_type_29m2> (); // Most bits used for range.\r\n show_fixed_point<fixed_point_type_0m168> ();\r\n show_fixed_point<fixed_point_type_20m148>();\r\n\r\n //std::cout << \"fixed_point_type(123) / 100 = \"\r\n // << x // 1.22999573 is the nearest representation of decimal digit string 1.23.\r\n // << std::endl;\r\n }\r\n catch (std::exception ex)\r\n {\r\n std::cout << ex.what() << std::endl;\r\n }\r\n}\r\n\r\n/*\r\n//[fixed_point_type_examples_output_1\r\n\r\n\r\n//] [/fixed_point_type_examples_output_1]\r\n*/\r\n", "meta": {"hexsha": "4cdd8c26b8b9e7df1b417f89b3c3c3fbb6e37006", "size": 8163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_type_examples.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/fixed_point_type_examples.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/fixed_point_type_examples.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5889830508, "max_line_length": 128, "alphanum_fraction": 0.6241577851, "num_tokens": 2010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938145706678, "lm_q2_score": 0.16451645880021026, "lm_q1q2_score": 0.08161559760585442}}
{"text": "/* Author: Wolfgang Bangerth, University of Texas at Austin, 2000, 2004 */\n\n/* $Id: step-17.cc 28351 2013-02-12 23:23:18Z heister $ */\n/* */\n/* Copyright (C) 2000, 2004-2009, 2011-2012 by the deal.II authors */\n/* */\n/* This file is subject to QPL and may not be distributed */\n/* without copyright and license information. Please refer */\n/* to the file deal.II/doc/license.html for the text and */\n/* further information on this license. */\n\n\n// First the usual assortment of header files we have already used in previous\n// example programs:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n\n// And here come the things that we need particularly for this example program\n// and that weren't in step-8. First, we replace the standard output\n// <code>std::cout</code> by a new stream <code>pcout</code> which is used in\n// %parallel computations for generating output only on one of the MPI\n// processes.\n#include <deal.II/base/conditional_ostream.h>\n// We are going to query the number of processes and the number of the present\n// process by calling the respective functions in the Utilities::MPI\n// namespace.\n#include <deal.II/base/utilities.h>\n// Then, we are going to replace all linear algebra components that involve\n// the (global) linear system by classes that wrap interfaces similar to our\n// own linear algebra classes around what PETSc offers (PETSc is a library\n// written in C, and deal.II comes with wrapper classes that provide the PETSc\n// functionality with an interface that is similar to the interface we already\n// had for our own linear algebra classes). In particular, we need vectors and\n// matrices that are distributed across several processes in MPI programs (and\n// simply map to sequential, local vectors and matrices if there is only a\n// single process, i.e. if you are running on only one machine, and without\n// MPI support):\n#include <deal.II/lac/petsc_vector.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n// Then we also need interfaces for solvers and preconditioners that PETSc\n// provides:\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n// And in addition, we need some algorithms for partitioning our meshes so\n// that they can be efficiently distributed across an MPI network. The\n// partitioning algorithm is implemented in the <code>GridTools</code> class,\n// and we need an additional include file for a function in\n// <code>DoFRenumbering</code> that allows to sort the indices associated with\n// degrees of freedom so that they are numbered according to the subdomain\n// they are associated with:\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/dofs/dof_renumbering.h>\n\n// And this is simply C++ again:\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\n// The last step is as in all previous programs:\nnamespace Step17\n{\n using namespace dealii;\n\n // Now, here comes the declaration of the main class and of various other\n // things below it. As mentioned in the introduction, almost all of this has\n // been copied verbatim from step-8, so we only comment on the few things\n // that are different. There is one (cosmetic) change in that we let\n // <code>solve</code> return a value, namely the number of iterations it\n // took to converge, so that we can output this to the screen at the\n // appropriate place. In addition, we introduce a stream-like variable\n // <code>pcout</code>, explained below:\n template <int dim>\n class ElasticProblem\n {\n public:\n ElasticProblem ();\n ~ElasticProblem ();\n void run ();\n\n private:\n void setup_system ();\n void assemble_system ();\n unsigned int solve ();\n void refine_grid ();\n void output_results (const unsigned int cycle) const;\n\n // The first variable is basically only for convenience: in %parallel\n // program, if each process outputs status information, then there quickly\n // is a lot of clutter. Rather, we would want to only have one process\n // output everything once, for example the one with process number\n // zero. <code>ConditionalOStream</code> does exactly this: it acts as if\n // it were a stream, but only forwards to a real, underlying stream if a\n // flag is set. By setting this condition to\n // <code>this_mpi_process==0</code>, we make sure that output is only\n // generated from the first process and that we don't get the same lines\n // of output over and over again, once per process.\n //\n // With this simple trick, we make sure that we don't have to guard each\n // and every write to <code>std::cout</code> by a prefixed\n // <code>if(this_mpi_process==0)</code>.\n ConditionalOStream pcout;\n\n // The next few variables are taken verbatim from step-8:\n Triangulation<dim> triangulation;\n DoFHandler<dim> dof_handler;\n\n FESystem<dim> fe;\n\n ConstraintMatrix hanging_node_constraints;\n\n // In step-8, this would have been the place where we would have declared\n // the member variables for the sparsity pattern, the system matrix, right\n // hand, and solution vector. We change these declarations to use\n // %parallel PETSc objects instead (note that the fact that we use the\n // %parallel versions is denoted the fact that we use the classes from the\n // <code>PETScWrappers::MPI</code> namespace; sequential versions of these\n // classes are in the <code>PETScWrappers</code> namespace, i.e. without\n // the <code>MPI</code> part). Note also that we do not use a separate\n // sparsity pattern, since PETSc manages that as part of its matrix data\n // structures.\n PETScWrappers::MPI::SparseMatrix system_matrix;\n\n PETScWrappers::MPI::Vector solution;\n PETScWrappers::MPI::Vector system_rhs;\n\n // The next change is that we have to declare a variable that indicates\n // the MPI communicator over which we are supposed to distribute our\n // computations. Note that if this is a sequential job without support by\n // MPI, then PETSc provides some dummy type for <code>MPI_Comm</code>, so\n // we do not have to care here whether the job is really a %parallel one:\n MPI_Comm mpi_communicator;\n\n // Then we have two variables that tell us where in the %parallel world we\n // are. The first of the following variables, <code>n_mpi_processes</code>\n // tells us how many MPI processes there exist in total, while the second\n // one, <code>this_mpi_process</code>, indicates which is the number of\n // the present process within this space of processes. The latter variable\n // will have a unique value for each process between zero and (less than)\n // <code>n_mpi_processes</code>. If this program is run on a single\n // machine without MPI support, then their values are <code>1</code> and\n // <code>0</code>, respectively.\n const unsigned int n_mpi_processes;\n const unsigned int this_mpi_process;\n };\n\n\n // The following is again taken from step-8 without change:\n template <int dim>\n class RightHandSide : public Function<dim>\n {\n public:\n RightHandSide ();\n\n virtual void vector_value (const Point<dim> &p,\n Vector<double> &values) const;\n\n virtual void vector_value_list (const std::vector<Point<dim> > &points,\n std::vector<Vector<double> > &value_list) const;\n };\n\n\n template <int dim>\n RightHandSide<dim>::RightHandSide () :\n Function<dim> (dim)\n {}\n\n\n template <int dim>\n inline\n void RightHandSide<dim>::vector_value (const Point<dim> &p,\n Vector<double> &values) const\n {\n Assert (values.size() == dim,\n ExcDimensionMismatch (values.size(), dim));\n Assert (dim >= 2, ExcInternalError());\n\n Point<dim> point_1, point_2;\n point_1(0) = 0.5;\n point_2(0) = -0.5;\n\n if (((p-point_1).square() < 0.2*0.2) ||\n ((p-point_2).square() < 0.2*0.2))\n values(0) = 1;\n else\n values(0) = 0;\n\n if (p.square() < 0.2*0.2)\n values(1) = 1;\n else\n values(1) = 0;\n }\n\n\n\n template <int dim>\n void RightHandSide<dim>::vector_value_list (const std::vector<Point<dim> > &points,\n std::vector<Vector<double> > &value_list) const\n {\n const unsigned int n_points = points.size();\n\n Assert (value_list.size() == n_points,\n ExcDimensionMismatch (value_list.size(), n_points));\n\n for (unsigned int p=0; p<n_points; ++p)\n RightHandSide<dim>::vector_value (points[p],\n value_list[p]);\n }\n\n\n // The first step in the actual implementation of things is the constructor\n // of the main class. Apart from initializing the same member variables that\n // we already had in step-8, we here initialize the MPI communicator\n // variable we shall use with the global MPI communicator linking all\n // processes together (in more complex applications, one could here use a\n // communicator object that only links a subset of all processes), and call\n // the Utilities helper functions to determine the number of processes and\n // where the present one fits into this picture. In addition, we make sure\n // that output is only generated by the (globally) first process. As,\n // this_mpi_process is determined after creation of pcout, we cannot set the\n // condition through the constructor, i.e. by pcout(std::cout,\n // this_mpi_process==0), but set the condition separately.\n template <int dim>\n ElasticProblem<dim>::ElasticProblem ()\n :\n pcout (std::cout),\n dof_handler (triangulation),\n fe (FE_Q<dim>(1), dim),\n mpi_communicator (MPI_COMM_WORLD),\n n_mpi_processes (Utilities::MPI::n_mpi_processes(mpi_communicator)),\n this_mpi_process (Utilities::MPI::this_mpi_process(mpi_communicator))\n {\n pcout.set_condition(this_mpi_process == 0);\n }\n\n\n\n template <int dim>\n ElasticProblem<dim>::~ElasticProblem ()\n {\n dof_handler.clear ();\n }\n\n\n // The second step is the function in which we set up the various variables\n // for the global linear system to be solved.\n template <int dim>\n void ElasticProblem<dim>::setup_system ()\n {\n // Before we even start out setting up the system, there is one thing to\n // do for a %parallel program: we need to assign cells to each of the\n // processes. We do this by splitting (<code>partitioning</code>) the mesh\n // cells into as many chunks (<code>subdomains</code>) as there are\n // processes in this MPI job (if this is a sequential job, then there is\n // only one job and all cells will get a zero as subdomain\n // indicator). This is done using an interface to the METIS library that\n // does this in a very efficient way, trying to minimize the number of\n // nodes on the interfaces between subdomains. All this is hidden behind\n // the following call to a deal.II library function:\n GridTools::partition_triangulation (n_mpi_processes, triangulation);\n\n // As for the linear system: First, we need to generate an enumeration for\n // the degrees of freedom in our problem. Further below, we will show how\n // we assign each cell to one of the MPI processes before we even get\n // here. What we then need to do is to enumerate the degrees of freedom in\n // a way so that all degrees of freedom associated with cells in subdomain\n // zero (which resides on process zero) come before all DoFs associated\n // with cells on subdomain one, before those on cells on process two, and\n // so on. We need this since we have to split the global vectors for right\n // hand side and solution, as well as the matrix into contiguous chunks of\n // rows that live on each of the processors, and we will want to do this\n // in a way that requires minimal communication. This is done using the\n // following two functions, which first generates an initial ordering of\n // all degrees of freedom, and then re-sort them according to above\n // criterion:\n dof_handler.distribute_dofs (fe);\n DoFRenumbering::subdomain_wise (dof_handler);\n\n // While we're at it, let us also count how many degrees of freedom there\n // exist on the present process:\n const unsigned int n_local_dofs\n = DoFTools::count_dofs_with_subdomain_association (dof_handler,\n this_mpi_process);\n\n // Then we initialize the system matrix, solution, and right hand side\n // vectors. Since they all need to work in %parallel, we have to pass them\n // an MPI communication object, as well as their global sizes (both\n // dimensions are equal to the number of degrees of freedom), and also how\n // many rows out of this global size are to be stored locally\n // (<code>n_local_dofs</code>). In addition, PETSc needs to know how to\n // partition the columns in the chunk of the matrix that is stored\n // locally; for square matrices, the columns should be partitioned in the\n // same way as the rows (indicated by the second <code>n_local_dofs</code>\n // in the call) but in the case of rectangular matrices one has to\n // partition the columns in the same way as vectors are partitioned with\n // which the matrix is multiplied, while rows have to partitioned in the\n // same way as destination vectors of matrix-vector multiplications:\n system_matrix.reinit (mpi_communicator,\n dof_handler.n_dofs(),\n dof_handler.n_dofs(),\n n_local_dofs,\n n_local_dofs,\n dof_handler.max_couplings_between_dofs());\n\n solution.reinit (mpi_communicator, dof_handler.n_dofs(), n_local_dofs);\n system_rhs.reinit (mpi_communicator, dof_handler.n_dofs(), n_local_dofs);\n\n // Finally, we need to initialize the objects denoting hanging node\n // constraints for the present grid. Note that since PETSc handles the\n // sparsity pattern internally to the matrix, there is no need to set up\n // an independent sparsity pattern here, and to condense it for\n // constraints, as we have done in all other example programs.\n hanging_node_constraints.clear ();\n DoFTools::make_hanging_node_constraints (dof_handler,\n hanging_node_constraints);\n hanging_node_constraints.close ();\n }\n\n\n // The third step is to actually assemble the matrix and right hand side of\n // the problem. There are some things worth mentioning before we go into\n // detail. First, we will be assembling the system in %parallel, i.e. each\n // process will be responsible for assembling on cells that belong to this\n // particular processor. Note that the degrees of freedom are split in a way\n // such that all DoFs in the interior of cells and between cells belonging\n // to the same subdomain belong to the process that <code>owns</code> the\n // cell. However, even then we sometimes need to assemble on a cell with a\n // neighbor that belongs to a different process, and in these cases when we\n // write the local contributions into the global matrix or right hand side\n // vector, we actually have to transfer these entries to the other\n // process. Fortunately, we don't have to do this by hand, PETSc does all\n // this for us by caching these elements locally, and sending them to the\n // other processes as necessary when we call the <code>compress()</code>\n // functions on the matrix and vector at the end of this function.\n //\n // The second point is that once we have handed over matrix and vector\n // contributions to PETSc, it is a) hard, and b) very inefficient to get\n // them back for modifications. This is not only the fault of PETSc, it is\n // also a consequence of the distributed nature of this program: if an entry\n // resides on another processor, then it is necessarily expensive to get\n // it. The consequence of this is that where we previously first assembled\n // the matrix and right hand side as if there were no hanging node\n // constraints and boundary values, and then eliminated these in a second\n // step, we should now try to do that while still assembling the local\n // systems, and before handing these entries over to PETSc. At least as far\n // as eliminating hanging nodes is concerned, this is actually possible,\n // though removing boundary nodes isn't that simple. deal.II provides\n // functions to do this first part: instead of copying elements by hand into\n // the global matrix, we use the <code>distribute_local_to_global</code>\n // functions below to take care of hanging nodes at the same time. The\n // second step, elimination of boundary nodes, is then done in exactly the\n // same way as in all previous example programs.\n //\n // So, here is the actual implementation:\n template <int dim>\n void ElasticProblem<dim>::assemble_system ()\n {\n // The infrastructure to assemble linear systems is the same as in all the\n // other programs, and in particular unchanged from step-8. Note that we\n // still use the deal.II full matrix and vector types for the local\n // systems.\n QGauss<dim> quadrature_formula(2);\n FEValues<dim> fe_values (fe, quadrature_formula,\n update_values | update_gradients |\n update_quadrature_points | update_JxW_values);\n\n const unsigned int dofs_per_cell = fe.dofs_per_cell;\n const unsigned int n_q_points = quadrature_formula.size();\n\n FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell);\n Vector<double> cell_rhs (dofs_per_cell);\n\n std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n std::vector<double> lambda_values (n_q_points);\n std::vector<double> mu_values (n_q_points);\n\n ConstantFunction<dim> lambda(1.), mu(1.);\n\n RightHandSide<dim> right_hand_side;\n std::vector<Vector<double> > rhs_values (n_q_points,\n Vector<double>(dim));\n\n\n // The next thing is the loop over all elements. Note that we do not have\n // to do all the work: our job here is only to assemble the system on\n // cells that actually belong to this MPI process, all other cells will be\n // taken care of by other processes. This is what the if-clause\n // immediately after the for-loop takes care of: it queries the subdomain\n // identifier of each cell, which is a number associated with each cell\n // that tells which process handles it. In more generality, the subdomain\n // id is used to split a domain into several parts (we do this above, at\n // the beginning of <code>setup_system</code>), and which allows to\n // identify which subdomain a cell is living on. In this application, we\n // have each process handle exactly one subdomain, so we identify the\n // terms <code>subdomain</code> and <code>MPI process</code> with each\n // other.\n //\n // Apart from this, assembling the local system is relatively uneventful\n // if you have understood how this is done in step-8, and only becomes\n // interesting again once we start distributing it into the global matrix\n // and right hand sides.\n typename DoFHandler<dim>::active_cell_iterator\n cell = dof_handler.begin_active(),\n endc = dof_handler.end();\n for (; cell!=endc; ++cell)\n if (cell->subdomain_id() == this_mpi_process)\n {\n cell_matrix = 0;\n cell_rhs = 0;\n\n fe_values.reinit (cell);\n\n lambda.value_list (fe_values.get_quadrature_points(), lambda_values);\n mu.value_list (fe_values.get_quadrature_points(), mu_values);\n\n for (unsigned int i=0; i<dofs_per_cell; ++i)\n {\n const unsigned int\n component_i = fe.system_to_component_index(i).first;\n\n for (unsigned int j=0; j<dofs_per_cell; ++j)\n {\n const unsigned int\n component_j = fe.system_to_component_index(j).first;\n\n for (unsigned int q_point=0; q_point<n_q_points;\n ++q_point)\n {\n//TODO investigate really small values here\n cell_matrix(i,j)\n +=\n (\n (fe_values.shape_grad(i,q_point)[component_i] *\n fe_values.shape_grad(j,q_point)[component_j] *\n lambda_values[q_point])\n +\n (fe_values.shape_grad(i,q_point)[component_j] *\n fe_values.shape_grad(j,q_point)[component_i] *\n mu_values[q_point])\n +\n ((component_i == component_j) ?\n (fe_values.shape_grad(i,q_point) *\n fe_values.shape_grad(j,q_point) *\n mu_values[q_point]) :\n 0)\n )\n *\n fe_values.JxW(q_point);\n }\n }\n }\n\n right_hand_side.vector_value_list (fe_values.get_quadrature_points(),\n rhs_values);\n for (unsigned int i=0; i<dofs_per_cell; ++i)\n {\n const unsigned int\n component_i = fe.system_to_component_index(i).first;\n\n for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n cell_rhs(i) += fe_values.shape_value(i,q_point) *\n rhs_values[q_point](component_i) *\n fe_values.JxW(q_point);\n }\n\n // Now we have the local system, and need to transfer it into the\n // global objects. However, as described in the introduction to this\n // function, we want to avoid any operations to matrix and vector\n // entries after handing them off to PETSc (i.e. after distributing\n // to the global objects). Therefore, we will take care of hanging\n // node constraints already here. This is not quite trivial since\n // the rows and columns of constrained nodes have to be distributed\n // to the rows and columns of those nodes to which they are\n // constrained. This can't be done on a purely local basis (because\n // the degrees of freedom to which hanging nodes are constrained may\n // not be associated with the cell we are presently treating, and\n // are therefore not represented in the local matrix and vector),\n // but it can be done while distributing the local system to the\n // global one. This is what the following call does, i.e. we\n // distribute to the global objects and at the same time make sure\n // that hanging node constraints are taken care of:\n cell->get_dof_indices (local_dof_indices);\n hanging_node_constraints\n .distribute_local_to_global(cell_matrix, cell_rhs,\n local_dof_indices,\n system_matrix, system_rhs);\n }\n\n // Now compress the vector and the system matrix:\n system_matrix.compress();\n system_rhs.compress(VectorOperation::add);\n\n // The global matrix and right hand side vectors have now been\n // formed. Note that since we took care of this already above, we do not\n // have to condense away hanging node constraints any more.\n //\n // However, we still have to apply boundary values, in the same way as we\n // always do:\n std::map<unsigned int,double> boundary_values;\n VectorTools::interpolate_boundary_values (dof_handler,\n 0,\n ZeroFunction<dim>(dim),\n boundary_values);\n MatrixTools::apply_boundary_values (boundary_values,\n system_matrix, solution,\n system_rhs, false);\n // The last argument to the call just performed allows for some\n // optimizations. It controls whether we should also delete the column\n // corresponding to a boundary node, or keep it (and passing\n // <code>true</code> as above means: yes, do eliminate the column). If we\n // do, then the resulting matrix will be symmetric again if it was before;\n // if we don't, then it won't. The solution of the resulting system should\n // be the same, though. The only reason why we may want to make the system\n // symmetric again is that we would like to use the CG method, which only\n // works with symmetric matrices. Experience tells that CG also works\n // (and works almost as well) if we don't remove the columns associated\n // with boundary nodes, which can be easily explained by the special\n // structure of the non-symmetry. Since eliminating columns from dense\n // matrices is not expensive, though, we let the function do it; not doing\n // so is more important if the linear system is either non-symmetric\n // anyway, or we are using the non-local version of this function (as in\n // all the other example programs before) and want to save a few cycles\n // during this operation.\n }\n\n\n\n // The fourth step is to solve the linear system, with its distributed\n // matrix and vector objects. Fortunately, PETSc offers a variety of\n // sequential and %parallel solvers, for which we have written wrappers that\n // have almost the same interface as is used for the deal.II solvers used in\n // all previous example programs.\n template <int dim>\n unsigned int ElasticProblem<dim>::solve ()\n {\n // First, we have to set up a convergence monitor, and assign it the\n // accuracy to which we would like to solve the linear system. Next, an\n // actual solver object using PETSc's CG solver which also works with\n // %parallel (distributed) vectors and matrices. And finally a\n // preconditioner; we choose to use a block Jacobi preconditioner which\n // works by computing an incomplete LU decomposition on each block\n // (i.e. the chunk of matrix that is stored on each MPI process). That\n // means that if you run the program with only one process, then you will\n // use an ILU(0) as a preconditioner, while if it is run on many\n // processes, then we will have a number of blocks on the diagonal and the\n // preconditioner is the ILU(0) of each of these blocks.\n SolverControl solver_control (solution.size(),\n 1e-8*system_rhs.l2_norm());\n PETScWrappers::SolverCG cg (solver_control,\n mpi_communicator);\n\n PETScWrappers::PreconditionBlockJacobi preconditioner(system_matrix);\n\n // Then solve the system:\n cg.solve (system_matrix, solution, system_rhs,\n preconditioner);\n\n // The next step is to distribute hanging node constraints. This is a\n // little tricky, since to fill in the value of a constrained node you\n // need access to the values of the nodes to which it is constrained (for\n // example, for a Q1 element in 2d, we need access to the two nodes on the\n // big side of a hanging node face, to compute the value of the\n // constrained node in the middle). Since PETSc (and, for that matter, the\n // MPI model on which it is built) does not allow to query the value of\n // another node in a simple way if we should need it, what we do here is\n // to get a copy of the distributed vector where we keep all elements\n // locally. This is simple, since the deal.II wrappers have a conversion\n // constructor for the non-MPI vector class:\n PETScWrappers::Vector localized_solution (solution);\n\n // Then we distribute hanging node constraints on this local copy, i.e. we\n // compute the values of all constrained nodes:\n hanging_node_constraints.distribute (localized_solution);\n\n // Then transfer everything back into the global vector. The following\n // operation copies those elements of the localized solution that we store\n // locally in the distributed solution, and does not touch the other\n // ones. Since we do the same operation on all processors, we end up with\n // a distributed vector that has all the constrained nodes fixed.\n solution = localized_solution;\n\n // Finally return the number of iterations it took to converge, to allow\n // for some output:\n return solver_control.last_step();\n }\n\n\n\n // Step five is to output the results we computed in this iteration. This is\n // actually the same as done in step-8 before, with two small\n // differences. First, all processes call this function, but not all of them\n // need to do the work associated with generating output. In fact, they\n // shouldn't, since we would try to write to the same file multiple times at\n // once. So we let only the first job do this, and all the other ones idle\n // around during this time (or start their work for the next iteration, or\n // simply yield their CPUs to other jobs that happen to run at the same\n // time). The second thing is that we not only output the solution vector,\n // but also a vector that indicates which subdomain each cell belongs\n // to. This will make for some nice pictures of partitioned domains.\n //\n // In practice, the present implementation of the output function is a major\n // bottleneck of this program, since generating graphical output is\n // expensive and doing so only on one process does, of course, not scale if\n // we significantly increase the number of processes. In effect, this\n // function will consume most of the run-time if you go to very large\n // numbers of unknowns and processes, and real applications should limit the\n // number of times they generate output through this function.\n //\n // The solution to this is to have each process generate output data only\n // for it's own local cells, and write them to separate files, one file per\n // process. This would distribute the work of generating the output to all\n // processes equally. In a second step, separate from running this program,\n // we would then take all the output files for a given cycle and merge these\n // parts into one single output file. This has to be done sequentially, but\n // can be done on a different machine, and should be relatively\n // cheap. However, the necessary functionality for this is not yet\n // implemented in the library, and since we are too close to the next\n // release, we do not want to do such major destabilizing changes any\n // more. This has been fixed in the meantime, though, and a better way to do\n // things is explained in the step-18 example program.\n template <int dim>\n void ElasticProblem<dim>::output_results (const unsigned int cycle) const\n {\n // One point to realize is that when we want to generate output on process\n // zero only, we need to have access to all elements of the solution\n // vector. So we need to get a local copy of the distributed vector, which\n // is in fact simple:\n const PETScWrappers::Vector localized_solution (solution);\n // The thing to notice, however, is that we do this localization operation\n // on all processes, not only the one that actually needs the data. This\n // can't be avoided, however, with the communication model of MPI: MPI\n // does not have a way to query data on another process, both sides have\n // to initiate a communication at the same time. So even though most of\n // the processes do not need the localized solution, we have to place the\n // call here so that all processes execute it.\n //\n // (In reality, part of this work can in fact be avoided. What we do is\n // send the local parts of all processes to all other processes. What we\n // would really need to do is to initiate an operation on all processes\n // where each process simply sends its local chunk of data to process\n // zero, since this is the only one that actually needs it, i.e. we need\n // something like a gather operation. PETSc can do this, but for\n // simplicity's sake we don't attempt to make use of this here. We don't,\n // since what we do is not very expensive in the grand scheme of things:\n // it is one vector communication among all processes , which has to be\n // compared to the number of communications we have to do when solving the\n // linear system, setting up the block-ILU for the preconditioner, and\n // other operations.)\n\n // This being done, process zero goes ahead with setting up the output\n // file as in step-8, and attaching the (localized) solution vector to the\n // output object:. (The code to generate the output file name is stolen\n // and slightly modified from step-5, since we expect that we can do a\n // number of cycles greater than 10, which is the maximum of what the code\n // in step-8 could handle.)\n if (this_mpi_process == 0)\n {\n std::ostringstream filename;\n filename << \"solution-\" << cycle << \".gmv\";\n\n std::ofstream output (filename.str().c_str());\n\n DataOut<dim> data_out;\n data_out.attach_dof_handler (dof_handler);\n\n std::vector<std::string> solution_names;\n switch (dim)\n {\n case 1:\n solution_names.push_back (\"displacement\");\n break;\n case 2:\n solution_names.push_back (\"x_displacement\");\n solution_names.push_back (\"y_displacement\");\n break;\n case 3:\n solution_names.push_back (\"x_displacement\");\n solution_names.push_back (\"y_displacement\");\n solution_names.push_back (\"z_displacement\");\n break;\n default:\n Assert (false, ExcInternalError());\n }\n\n data_out.add_data_vector (localized_solution, solution_names);\n\n // The only thing we do here additionally is that we also output one\n // value per cell indicating which subdomain (i.e. MPI process) it\n // belongs to. This requires some conversion work, since the data the\n // library provides us with is not the one the output class expects,\n // but this is not difficult. First, set up a vector of integers, one\n // per cell, that is then filled by the number of subdomain each cell\n // is in:\n std::vector<unsigned int> partition_int (triangulation.n_active_cells());\n GridTools::get_subdomain_association (triangulation, partition_int);\n\n // Then convert this integer vector into a floating point vector just\n // as the output functions want to see:\n const Vector<double> partitioning(partition_int.begin(),\n partition_int.end());\n\n // And finally add this vector as well:\n data_out.add_data_vector (partitioning, \"partitioning\");\n\n // This all being done, generate the intermediate format and write it\n // out in GMV output format:\n data_out.build_patches ();\n data_out.write_gmv (output);\n }\n }\n\n\n\n // The sixth step is to take the solution just computed, and evaluate some\n // kind of refinement indicator to refine the mesh. The problem is basically\n // the same as with distributing hanging node constraints: in order to\n // compute the error indicator, we need access to all elements of the\n // solution vector. We then compute the indicators for the cells that belong\n // to the present process, but then we need to distribute the refinement\n // indicators into a distributed vector so that all processes have the\n // values of the refinement indicator for all cells. But then, in order for\n // each process to refine its copy of the mesh, they need to have acces to\n // all refinement indicators locally, so they have to copy the global vector\n // back into a local one. That's a little convoluted, but thinking about it\n // quite straightforward nevertheless. So here's how we do it:\n template <int dim>\n void ElasticProblem<dim>::refine_grid ()\n {\n // So, first part: get a local copy of the distributed solution\n // vector. This is necessary since the error estimator needs to get at the\n // value of neighboring cells even if they do not belong to the subdomain\n // associated with the present MPI process:\n const PETScWrappers::Vector localized_solution (solution);\n\n // Second part: set up a vector of error indicators for all cells and let\n // the Kelly class compute refinement indicators for all cells belonging\n // to the present subdomain/process. Note that the last argument of the\n // call indicates which subdomain we are interested in. The three\n // arguments before it are various other default arguments that one\n // usually doesn't need (and doesn't state values for, but rather uses the\n // defaults), but which we have to state here explicitly since we want to\n // modify the value of a following argument (i.e. the one indicating the\n // subdomain):\n Vector<float> local_error_per_cell (triangulation.n_active_cells());\n KellyErrorEstimator<dim>::estimate (dof_handler,\n QGauss<dim-1>(2),\n typename FunctionMap<dim>::type(),\n localized_solution,\n local_error_per_cell,\n ComponentMask(),\n 0,\n multithread_info.n_default_threads,\n this_mpi_process);\n\n // Now all processes have computed error indicators for their own cells\n // and stored them in the respective elements of the\n // <code>local_error_per_cell</code> vector. The elements of this vector\n // for cells not on the present process are zero. However, since all\n // processes have a copy of a copy of the entire triangulation and need to\n // keep these copies in synch, they need the values of refinement\n // indicators for all cells of the triangulation. Thus, we need to\n // distribute our results. We do this by creating a distributed vector\n // where each process has its share, and sets the elements it has\n // computed. We will then later generate a local sequential copy of this\n // distributed vector to allow each process to access all elements of this\n // vector.\n //\n // So in the first step, we need to set up a %parallel vector. For\n // simplicity, every process will own a chunk with as many elements as\n // this process owns cells, so that the first chunk of elements is stored\n // with process zero, the next chunk with process one, and so on. It is\n // important to remark, however, that these elements are not necessarily\n // the ones we will write to. This is so, since the order in which cells\n // are arranged, i.e. the order in which the elements of the vector\n // correspond to cells, is not ordered according to the subdomain these\n // cells belong to. In other words, if on this process we compute\n // indicators for cells of a certain subdomain, we may write the results\n // to more or less random elements if the distributed vector, that do not\n // necessarily lie within the chunk of vector we own on the present\n // process. They will subsequently have to be copied into another\n // process's memory space then, an operation that PETSc does for us when\n // we call the <code>compress</code> function. This inefficiency could be\n // avoided with some more code, but we refrain from it since it is not a\n // major factor in the program's total runtime.\n //\n // So here's how we do it: count how many cells belong to this process,\n // set up a distributed vector with that many elements to be stored\n // locally, and copy over the elements we computed locally, then compress\n // the result. In fact, we really only copy the elements that are nonzero,\n // so we may miss a few that we computed to zero, but this won't hurt\n // since the original values of the vector is zero anyway.\n const unsigned int n_local_cells\n = GridTools::count_cells_with_subdomain_association (triangulation,\n this_mpi_process);\n PETScWrappers::MPI::Vector\n distributed_all_errors (mpi_communicator,\n triangulation.n_active_cells(),\n n_local_cells);\n\n for (unsigned int i=0; i<local_error_per_cell.size(); ++i)\n if (local_error_per_cell(i) != 0)\n distributed_all_errors(i) = local_error_per_cell(i);\n distributed_all_errors.compress (VectorOperation::insert);\n\n\n // So now we have this distributed vector out there that contains the\n // refinement indicators for all cells. To use it, we need to obtain a\n // local copy...\n const Vector<float> localized_all_errors (distributed_all_errors);\n\n // ...which we can the subsequently use to finally refine the grid:\n GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n localized_all_errors,\n 0.3, 0.03);\n triangulation.execute_coarsening_and_refinement ();\n }\n\n\n\n // Lastly, here is the driver function. It is almost unchanged from step-8,\n // with the exception that we replace <code>std::cout</code> by the\n // <code>pcout</code> stream. Apart from this, the only other cosmetic\n // change is that we output how many degrees of freedom there are per\n // process, and how many iterations it took for the linear solver to\n // converge:\n template <int dim>\n void ElasticProblem<dim>::run ()\n {\n for (unsigned int cycle=0; cycle<10; ++cycle)\n {\n pcout << \"Cycle \" << cycle << ':' << std::endl;\n\n if (cycle == 0)\n {\n GridGenerator::hyper_cube (triangulation, -1, 1);\n triangulation.refine_global (3);\n }\n else\n refine_grid ();\n\n pcout << \" Number of active cells: \"\n << triangulation.n_active_cells()\n << std::endl;\n\n setup_system ();\n\n pcout << \" Number of degrees of freedom: \"\n << dof_handler.n_dofs()\n << \" (by partition:\";\n for (unsigned int p=0; p<n_mpi_processes; ++p)\n pcout << (p==0 ? ' ' : '+')\n << (DoFTools::\n count_dofs_with_subdomain_association (dof_handler,\n p));\n pcout << \")\" << std::endl;\n\n assemble_system ();\n const unsigned int n_iterations = solve ();\n\n pcout << \" Solver converged in \" << n_iterations\n << \" iterations.\" << std::endl;\n\n output_results (cycle);\n }\n }\n}\n\n\n// So that's it, almost. <code>main()</code> works the same way as most of the\n// main functions in the other example programs, i.e. it delegates work to the\n// <code>run</code> function of a master object, and only wraps everything\n// into some code to catch exceptions:\nint main (int argc, char **argv)\n{\n try\n {\n using namespace dealii;\n using namespace Step17;\n\n // Here is the only real difference: PETSc requires that we initialize\n // it at the beginning of the program, and un-initialize it at the\n // end. The class MPI_InitFinalize takes care of that. The original code\n // sits in between, enclosed in braces to make sure that the\n // <code>elastic_problem</code> variable goes out of scope (and is\n // destroyed) before PETSc is closed with\n // <code>PetscFinalize</code>. (If we wouldn't use braces, the\n // destructor of <code>elastic_problem</code> would run after\n // <code>PetscFinalize</code>; since the destructor involves calls to\n // PETSc functions, we would get strange error messages from PETSc.)\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv);\n\n {\n deallog.depth_console (0);\n\n ElasticProblem<2> elastic_problem;\n elastic_problem.run ();\n }\n }\n catch (std::exception &exc)\n {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n << exc.what() << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n\n return 1;\n }\n catch (...)\n {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "8c3cb2605c9f62fa2aa7f7c14ad21c732dd18716", "size": 46208, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-17/step-17.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-17/step-17.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-17/step-17.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 48.7940865892, "max_line_length": 95, "alphanum_fraction": 0.660037223, "num_tokens": 10323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.14608724890715238, "lm_q1q2_score": 0.07076175393743926}}
{"text": "/**\n * @file Format.cc\n * @brief Implementation of double formatting strings\n * @author [Yi-Mu \"Enoch\" Chen](https://github.com/yimuchen)\n */\n\n#ifdef CMSSW_GIT_HASH\n#include \"UserUtils/Common/interface/Format.hpp\"\n#include \"UserUtils/Common/interface/Maths.hpp\"\n#include \"UserUtils/Common/interface/STLUtils/StringUtils.hpp\"\n#else\n#include \"UserUtils/Common/Format.hpp\"\n#include \"UserUtils/Common/Maths.hpp\"\n#include \"UserUtils/Common/STLUtils/StringUtils.hpp\"\n#endif\n\n#include <boost/algorithm/string.hpp>\n#include <cmath>\n#include <regex>\n#include <string>\n\nnamespace usr {\n\nnamespace fmt {\n\nnamespace base {\n\n/*-----------------------------------------------------------------------------\n * Default settings control variables\n --------------------------------------------------------------------------*/\n\n/**\n * @details default precision is set such that loss of precision due to IO would\n * not be of too much concern, while avoiding artifacts in decimal--binary\n * conversions (ex. 1.7=1.6999999999999999556 )\n */\nint precision_default = 8;\n\n/**\n * @details spacing between digits should be universal (i.e. three digits), but\n * can be changed if publishing to journal using another number system.\n */\nunsigned spacesep_default = 3;\n\n/**\n * @details Defaults to none, as it is easier on the eyes when testing code with\n * screen I/O, but you might want to set it to the latex \"\\,\" string when\n * mass producing numbers for publication.\n */\nstd::string spacestr_default = \"\";\n\n/**\n * @details library specifically doesn't allow more digits then 27 to be\n * printed after the decimal point. This is pretty close to the recommended\n * precision limit of doubles anyway.\n */\nconst unsigned max_precision = 27;\n\n/**\n * @brief generating string to represent double as a string in decimal.\n */\nstd::string\ndecimal::str() const\n{\n const unsigned op_precision = std::min( abs( _precision ), abs( max_precision ) );\n std::string retstr = usr::fstr( usr::fstr( \"%%.%df\", op_precision ), _input );\n\n // stripping trailing zero after decimal point\n if( _precision < 0 && retstr.find( '.' ) != std::string::npos ){\n boost::trim_right_if( retstr, boost::is_any_of( \"0\" ) );\n boost::trim_right_if( retstr, boost::is_any_of( \".\" ) );\n }\n\n // Adding spacing string every _spacesep digits away from decimal point\n // Largest double is around e308\n if( _spacesep != 0 && _spacestr != \"\" ){\n int space = ( ( (int)( retstr.length()/_spacesep ) ) + 1 ) * _spacesep;\n\n while( space > 0 ){\n if( retstr.find( '.' ) != std::string::npos ){\n // If decimal point exists, expand around decimal point\n const std::regex before( usr::fstr( \"(.*\\\\d)(\\\\d{%d}\\\\..*)\", space ) );\n const std::regex after( usr::fstr( \"(.*\\\\.\\\\d{%d})(\\\\d.*)\", space ) );\n retstr = std::regex_replace( retstr, before, \"$1\"+_spacestr+\"$2\" );\n retstr = std::regex_replace( retstr, after, \"$1\"+_spacestr+\"$2\" );\n } else {\n // If decimal point doesn't exist, expand around right most side\n const std::regex beforedec( usr::fstr( \"(.*\\\\d)(\\\\d{%d})\", space ) );\n retstr = std::regex_replace( retstr, beforedec, \"$1\"+_spacestr+\"$2\" );\n }\n space -= _spacesep;\n }\n }\n return retstr;\n}\n\n\n/**\n * @brief Requires explicit specification of precision (cannot be negative)\n */\nscientific::scientific( const double x, const unsigned p )\n{\n precision( p );\n _mant = x;\n _exp = ReduceToMant( _mant );\n}\n\n/**\n * @brief Generating string to represent double as string in scientific\n * notations.\n */\nstd::string\nscientific::str() const\n{\n const std::string base = decimal( _mant, _precision ).dupsetting( *this ).str();\n // largest exponent should be around ~300\n // no need of additional formatting.\n const std::string ans\n = ( _exp == 0 ) ? base : usr::fstr( \"%s \\\\times 10^{%d}\", base, _exp );\n return ans;\n}\n\n}/* base */\n\n}/* fmt */\n\n}/* usr */\n", "meta": {"hexsha": "6c83d0e924ad5e48b8c27c3321fb6aa16a25fc99", "size": 3915, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Common/src/Format.cc", "max_stars_repo_name": "yimuchen/UserUtils", "max_stars_repo_head_hexsha": "1a5c55d286f325424f4cfd23f22da63cfa6fb6a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Common/src/Format.cc", "max_issues_repo_name": "yimuchen/UserUtils", "max_issues_repo_head_hexsha": "1a5c55d286f325424f4cfd23f22da63cfa6fb6a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-10T15:04:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T18:56:53.000Z", "max_forks_repo_path": "Common/src/Format.cc", "max_forks_repo_name": "yimuchen/UserUtils", "max_forks_repo_head_hexsha": "1a5c55d286f325424f4cfd23f22da63cfa6fb6a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T14:08:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-05T14:08:08.000Z", "avg_line_length": 30.5859375, "max_line_length": 89, "alphanum_fraction": 0.6314176245, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.14033624229926062, "lm_q1q2_score": 0.07016812114963031}}
{"text": "// (C) Copyright 2007-2009 Andrew Sutton\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GRAPH_CLIQUE_HPP\n#define BOOST_GRAPH_CLIQUE_HPP\n\n#include <vector>\n#include <deque>\n#include <boost/config.hpp>\n\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/lookup_edge.hpp>\n\n#include <boost/concept/detail/concept_def.hpp>\nnamespace boost {\n namespace concepts {\n BOOST_concept(CliqueVisitor,(Visitor)(Clique)(Graph))\n {\n BOOST_CONCEPT_USAGE(CliqueVisitor)\n {\n vis.clique(k, g);\n }\n private:\n Visitor vis;\n Graph g;\n Clique k;\n };\n } /* namespace concepts */\nusing concepts::CliqueVisitorConcept;\n} /* namespace boost */\n#include <boost/concept/detail/concept_undef.hpp>\n\nnamespace boost\n{\n// The algorithm implemented in this paper is based on the so-called\n// Algorithm 457, published as:\n//\n// @article{362367,\n// author = {Coen Bron and Joep Kerbosch},\n// title = {Algorithm 457: finding all cliques of an undirected graph},\n// journal = {Communications of the ACM},\n// volume = {16},\n// number = {9},\n// year = {1973},\n// issn = {0001-0782},\n// pages = {575--577},\n// doi = {http://doi.acm.org/10.1145/362342.362367},\n// publisher = {ACM Press},\n// address = {New York, NY, USA},\n// }\n//\n// Sort of. This implementation is adapted from the 1st version of the\n// algorithm and does not implement the candidate selection optimization\n// described as published - it could, it just doesn't yet.\n//\n// The algorithm is given as proportional to (3.14)^(n/3) power. This is\n// not the same as O(...), but based on time measures and approximation.\n//\n// Unfortunately, this implementation may be less efficient on non-\n// AdjacencyMatrix modeled graphs due to the non-constant implementation\n// of the edge(u,v,g) functions.\n//\n// TODO: It might be worthwhile to provide functionality for passing\n// a connectivity matrix to improve the efficiency of those lookups\n// when needed. This could simply be passed as a BooleanMatrix\n// s.t. edge(u,v,B) returns true or false. This could easily be\n// abstracted for adjacency matricies.\n//\n// The following paper is interesting for a number of reasons. First,\n// it lists a number of other such algorithms and second, it describes\n// a new algorithm (that does not appear to require the edge(u,v,g)\n// function and appears fairly efficient. It is probably worth investigating.\n//\n// @article{DBLP:journals/tcs/TomitaTT06,\n// author = {Etsuji Tomita and Akira Tanaka and Haruhisa Takahashi},\n// title = {The worst-case time complexity for generating all maximal cliques and computational experiments},\n// journal = {Theor. Comput. Sci.},\n// volume = {363},\n// number = {1},\n// year = {2006},\n// pages = {28-42}\n// ee = {http://dx.doi.org/10.1016/j.tcs.2006.06.015}\n// }\n\n/**\n * The default clique_visitor supplies an empty visitation function.\n */\nstruct clique_visitor\n{\n template <typename VertexSet, typename Graph>\n void clique(const VertexSet&, Graph&)\n { }\n};\n\n/**\n * The max_clique_visitor records the size of the maximum clique (but not the\n * clique itself).\n */\nstruct max_clique_visitor\n{\n max_clique_visitor(std::size_t& max)\n : maximum(max)\n { }\n\n template <typename Clique, typename Graph>\n inline void clique(const Clique& p, const Graph& g)\n {\n BOOST_USING_STD_MAX();\n maximum = max BOOST_PREVENT_MACRO_SUBSTITUTION (maximum, p.size());\n }\n std::size_t& maximum;\n};\n\ninline max_clique_visitor find_max_clique(std::size_t& max)\n{ return max_clique_visitor(max); }\n\nnamespace detail\n{\n template <typename Graph>\n inline bool\n is_connected_to_clique(const Graph& g,\n typename graph_traits<Graph>::vertex_descriptor u,\n typename graph_traits<Graph>::vertex_descriptor v,\n typename graph_traits<Graph>::undirected_category)\n {\n return lookup_edge(u, v, g).second;\n }\n\n template <typename Graph>\n inline bool\n is_connected_to_clique(const Graph& g,\n typename graph_traits<Graph>::vertex_descriptor u,\n typename graph_traits<Graph>::vertex_descriptor v,\n typename graph_traits<Graph>::directed_category)\n {\n // Note that this could alternate between using an || to determine\n // full connectivity. I believe that this should produce strongly\n // connected components. Note that using && instead of || will\n // change the results to a fully connected subgraph (i.e., symmetric\n // edges between all vertices s.t., if a->b, then b->a.\n return lookup_edge(u, v, g).second && lookup_edge(v, u, g).second;\n }\n\n template <typename Graph, typename Container>\n inline void\n filter_unconnected_vertices(const Graph& g,\n typename graph_traits<Graph>::vertex_descriptor v,\n const Container& in,\n Container& out)\n {\n function_requires< GraphConcept<Graph> >();\n\n typename graph_traits<Graph>::directed_category cat;\n typename Container::const_iterator i, end = in.end();\n for(i = in.begin(); i != end; ++i) {\n if(is_connected_to_clique(g, v, *i, cat)) {\n out.push_back(*i);\n }\n }\n }\n\n template <\n typename Graph,\n typename Clique, // compsub type\n typename Container, // candidates/not type\n typename Visitor>\n void extend_clique(const Graph& g,\n Clique& clique,\n Container& cands,\n Container& nots,\n Visitor vis,\n std::size_t min)\n {\n function_requires< GraphConcept<Graph> >();\n function_requires< CliqueVisitorConcept<Visitor,Clique,Graph> >();\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n\n // Is there vertex in nots that is connected to all vertices\n // in the candidate set? If so, no clique can ever be found.\n // This could be broken out into a separate function.\n {\n typename Container::iterator ni, nend = nots.end();\n typename Container::iterator ci, cend = cands.end();\n for(ni = nots.begin(); ni != nend; ++ni) {\n for(ci = cands.begin(); ci != cend; ++ci) {\n // if we don't find an edge, then we're okay.\n if(!lookup_edge(*ni, *ci, g).second) break;\n }\n // if we iterated all the way to the end, then *ni\n // is connected to all *ci\n if(ci == cend) break;\n }\n // if we broke early, we found *ni connected to all *ci\n if(ni != nend) return;\n }\n\n // TODO: the original algorithm 457 describes an alternative\n // (albeit really complicated) mechanism for selecting candidates.\n // The given optimizaiton seeks to bring about the above\n // condition sooner (i.e., there is a vertex in the not set\n // that is connected to all candidates). unfortunately, the\n // method they give for doing this is fairly unclear.\n\n // basically, for every vertex in not, we should know how many\n // vertices it is disconnected from in the candidate set. if\n // we fix some vertex in the not set, then we want to keep\n // choosing vertices that are not connected to that fixed vertex.\n // apparently, by selecting fix point with the minimum number\n // of disconnections (i.e., the maximum number of connections\n // within the candidate set), then the previous condition wil\n // be reached sooner.\n\n // there's some other stuff about using the number of disconnects\n // as a counter, but i'm jot really sure i followed it.\n\n // TODO: If we min-sized cliques to visit, then theoretically, we\n // should be able to stop recursing if the clique falls below that\n // size - maybe?\n\n // otherwise, iterate over candidates and and test\n // for maxmimal cliquiness.\n typename Container::iterator i, j, end = cands.end();\n for(i = cands.begin(); i != cands.end(); ) {\n Vertex candidate = *i;\n\n // add the candidate to the clique (keeping the iterator!)\n // typename Clique::iterator ci = clique.insert(clique.end(), candidate);\n clique.push_back(candidate);\n\n // remove it from the candidate set\n i = cands.erase(i);\n\n // build new candidate and not sets by removing all vertices\n // that are not connected to the current candidate vertex.\n // these actually invert the operation, adding them to the new\n // sets if the vertices are connected. its semantically the same.\n Container new_cands, new_nots;\n filter_unconnected_vertices(g, candidate, cands, new_cands);\n filter_unconnected_vertices(g, candidate, nots, new_nots);\n\n if(new_cands.empty() && new_nots.empty()) {\n // our current clique is maximal since there's nothing\n // that's connected that we haven't already visited. If\n // the clique is below our radar, then we won't visit it.\n if(clique.size() >= min) {\n vis.clique(clique, g);\n }\n }\n else {\n // recurse to explore the new candidates\n extend_clique(g, clique, new_cands, new_nots, vis, min);\n }\n\n // we're done with this vertex, so we need to move it\n // to the nots, and remove the candidate from the clique.\n nots.push_back(candidate);\n clique.pop_back();\n }\n }\n} /* namespace detail */\n\ntemplate <typename Graph, typename Visitor>\ninline void\nbron_kerbosch_all_cliques(const Graph& g, Visitor vis, std::size_t min)\n{\n function_requires< IncidenceGraphConcept<Graph> >();\n function_requires< VertexListGraphConcept<Graph> >();\n function_requires< VertexIndexGraphConcept<Graph> >();\n function_requires< AdjacencyMatrixConcept<Graph> >(); // Structural requirement only\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;\n typedef std::vector<Vertex> VertexSet;\n typedef std::deque<Vertex> Clique;\n function_requires< CliqueVisitorConcept<Visitor,Clique,Graph> >();\n\n // NOTE: We're using a deque to implement the clique, because it provides\n // constant inserts and removals at the end and also a constant size.\n\n VertexIterator i, end;\n tie(i, end) = vertices(g);\n VertexSet cands(i, end); // start with all vertices as candidates\n VertexSet nots; // start with no vertices visited\n\n Clique clique; // the first clique is an empty vertex set\n detail::extend_clique(g, clique, cands, nots, vis, min);\n}\n\n// NOTE: By default the minimum number of vertices per clique is set at 2\n// because singleton cliques aren't really very interesting.\ntemplate <typename Graph, typename Visitor>\ninline void\nbron_kerbosch_all_cliques(const Graph& g, Visitor vis)\n{ bron_kerbosch_all_cliques(g, vis, 2); }\n\ntemplate <typename Graph>\ninline std::size_t\nbron_kerbosch_clique_number(const Graph& g)\n{\n std::size_t ret = 0;\n bron_kerbosch_all_cliques(g, find_max_clique(ret));\n return ret;\n}\n\n} /* namespace boost */\n\n#endif\n", "meta": {"hexsha": "f6d253b1a26684d685ed5953e65da541cabc7baf", "size": 11997, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/bron_kerbosch_all_cliques.hpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T10:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-08T10:44:28.000Z", "max_issues_repo_path": "boost/graph/bron_kerbosch_all_cliques.hpp", "max_issues_repo_name": "jonstewart/boost-svn", "max_issues_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/bron_kerbosch_all_cliques.hpp", "max_forks_repo_name": "jonstewart/boost-svn", "max_forks_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7, "max_line_length": 118, "alphanum_fraction": 0.6229057264, "num_tokens": 2672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.13117321187415154, "lm_q1q2_score": 0.06507422100264813}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2013 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Timo Heister, Texas A&M University, 2013 \n */ \n\n\n\n// 这个教程程序很奇怪,与其他大多数步骤不同,介绍中已经提供了关于如何使用各种策略来生成网格的大部分信息。因此,这里没有什么需要评论的,我们在代码中穿插了相对较少的文字。从本质上讲,这里的代码只是提供了一个在介绍中已经描述过的内容的参考实现。\n\n// @sect3{Include files} \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/grid/manifold_lib.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/grid/grid_in.h> \n\n#include <iostream> \n#include <fstream> \n\n#include <map> \n\nusing namespace dealii; \n// @sect3{Generating output for a given mesh} \n\n// 下面的函数为我们将在本程序的剩余部分中生成的任何网格生成一些输出。特别是,它生成了以下信息。\n\n\n\n// - 一些关于这个网格所处的空间维数和它的单元数的一般信息。\n\n// - 使用每个边界指标的边界面的数量,这样就可以和我们预期的情况进行比较。\n\n// 最后,该函数将网格输出为VTU格式,可以方便地在Paraview或VisIt中进行可视化。\n\ntemplate <int dim> \nvoid print_mesh_info(const Triangulation<dim> &triangulation, \n const std::string & filename) \n{ \n std::cout << \"Mesh info:\" << std::endl \n << \" dimension: \" << dim << std::endl \n << \" no. of cells: \" << triangulation.n_active_cells() << std::endl; \n\n// 接下来循环所有单元格的所有面,找出每个边界指标的使用频率(请记住,如果你访问一个不存在的 std::map 对象的元素,它将被隐式创建并默认初始化--在当前情况下为零--然后我们再将其增加)。\n\n { \n std::map<types::boundary_id, unsigned int> boundary_count; \n for (const auto &face : triangulation.active_face_iterators()) \n if (face->at_boundary()) \n boundary_count[face->boundary_id()]++; \n\n std::cout << \" boundary indicators: \"; \n for (const std::pair<const types::boundary_id, unsigned int> &pair : \n boundary_count) \n { \n std::cout << pair.first << \"(\" << pair.second << \" times) \"; \n } \n std::cout << std::endl; \n } \n\n// 最后,产生一个网格的图形表示到一个输出文件。\n\n std::ofstream out(filename); \n GridOut grid_out; \n grid_out.write_vtu(triangulation, out); \n std::cout << \" written to \" << filename << std::endl << std::endl; \n} \n// @sect3{Main routines} \n// @sect4{grid_1: Loading a mesh generated by gmsh} \n\n// 在这第一个例子中,我们展示了如何加载我们在介绍中讨论过的如何生成的网格。这与 step-5 中加载网格的模式相同,尽管那里是以不同的文件格式(UCD而不是MSH)编写。\n\nvoid grid_1() \n{ \n Triangulation<2> triangulation; \n\n GridIn<2> gridin; \n gridin.attach_triangulation(triangulation); \n std::ifstream f(\"example.msh\"); \n gridin.read_msh(f); \n\n print_mesh_info(triangulation, \"grid-1.vtu\"); \n} \n// @sect4{grid_2: Merging triangulations} \n\n// 在这里,我们首先创建两个三角形,然后将它们合并成一个。 正如介绍中所讨论的,必须确保共同界面的顶点位于相同的坐标上。\n\nvoid grid_2() \n{ \n Triangulation<2> tria1; \n GridGenerator::hyper_cube_with_cylindrical_hole(tria1, 0.25, 1.0); \n\n Triangulation<2> tria2; \n std::vector<unsigned int> repetitions(2); \n repetitions[0] = 3; \n repetitions[1] = 2; \n GridGenerator::subdivided_hyper_rectangle(tria2, \n repetitions, \n Point<2>(1.0, -1.0), \n Point<2>(4.0, 1.0)); \n\n Triangulation<2> triangulation; \n GridGenerator::merge_triangulations(tria1, tria2, triangulation); \n\n print_mesh_info(triangulation, \"grid-2.vtu\"); \n} \n// @sect4{grid_3: Moving vertices} \n\n// 在这个函数中,我们移动一个网格的顶点。这比人们通常想象的要简单:如果你用 <code>cell-@>vertex(i)</code> 询问一个单元格的 <code>i</code> 的顶点的坐标,它不只是提供这个顶点的位置,实际上是对存储这些坐标的位置的引用。然后我们可以修改存储在那里的值。\n\n// 所以这就是我们在这个函数的第一部分所做的。我们创建一个几何形状为 $[-1,1]^2$ 的正方形,在原点处有一个半径为0.25的圆孔。然后我们在所有单元格和所有顶点上循环,如果一个顶点的 $y$ 坐标等于1,我们就把它向上移动0.5。\n\n// 注意,这种程序通常不是这样工作的,因为通常会多次遇到相同的顶点,并且可能会多次移动它们。它在这里起作用是因为我们根据顶点的几何位置来选择要使用的顶点,而移动过一次的顶点在未来将无法通过这个测试。解决这个问题的一个更普遍的方法是保留一个 std::set ,即那些我们已经移动过的顶点索引(我们可以用 <code>cell-@>vertex_index(i)</code> 获得,并且只移动那些索引还不在这个集合中的顶点。\n\nvoid grid_3() \n{ \n Triangulation<2> triangulation; \n GridGenerator::hyper_cube_with_cylindrical_hole(triangulation, 0.25, 1.0); \n\n for (const auto &cell : triangulation.active_cell_iterators()) \n { \n for (const auto i : cell->vertex_indices()) \n { \n Point<2> &v = cell->vertex(i); \n if (std::abs(v(1) - 1.0) < 1e-5) \n v(1) += 0.5; \n } \n } \n\n// 在第二步,我们将对网格进行两次细化。为了正确做到这一点,我们应该沿着以原点为中心的圆的表面在内部边界上放置新的点。幸运的是, GridGenerator::hyper_cube_with_cylindrical_hole 已经在内部边界上附加了一个Manifold对象,所以我们不需要做任何事情,只需要细化网格(参见<a href=\"#Results\">results section</a>中一个完全可行的例子,我们 <em> 做 </em> 附加一个Manifold对象)。\n\n triangulation.refine_global(2); \n print_mesh_info(triangulation, \"grid-3.vtu\"); \n} \n\n// 如上图所示,做事有一个障碍。如果像这里所示的那样移动边界上的节点,由于内部的节点没有被移动,所以经常会出现内部的单元被严重扭曲的情况。在目前的情况下,这并不是一个很大的问题,因为当节点被移动时,网格并不包含任何内部节点--它是粗略的网格,而且恰好所有的顶点都在边界上。还有一种情况是,我们在这里的移动,与平均单元的大小相比,并没有太大影响。然而,有时我们确实想把顶点移动一段距离,在这种情况下,我们也需要移动内部节点。一个自动完成的方法是调用函数 GridTools::laplace_transform ,该函数接收一组转换后的顶点坐标并移动所有其他的顶点,使产生的网格在某种意义上有一个小的变形。\n\n// @sect4{grid_4: Demonstrating extrude_triangulation} \n\n// 这个例子从前面的函数中获取初始网格,并简单地将其挤压到第三空间维度。\n\nvoid grid_4() \n{ \n Triangulation<2> triangulation; \n Triangulation<3> out; \n GridGenerator::hyper_cube_with_cylindrical_hole(triangulation, 0.25, 1.0); \n\n GridGenerator::extrude_triangulation(triangulation, 3, 2.0, out); \n print_mesh_info(out, \"grid-4.vtu\"); \n} \n// @sect4{grid_5: Demonstrating GridTools::transform, part 1} \n\n// 这个例子和下一个例子首先创建一个网格,然后根据一个函数移动网格的每个节点,这个函数接收一个点并返回一个映射的点。在这个例子中,我们转换 $(x,y) \\mapsto (x,y+\\sin(\\pi x/5))$ 。\n\n// GridTools::transform() 需要一个三角形和一个参数,这个参数可以像一个函数一样被调用,接收一个点并返回一个点。有不同的方式来提供这样一个参数。它可以是一个函数的指针;它可以是一个具有`operator()`的类的对象;它可以是一个lambda函数;或者它可以是任何通过 <code>std::function@<Point@<2@>(const Point@<2@>)@></code> 对象描述的东西。\n\n// 更现代的方法是使用一个接受一个点并返回一个点的lambda函数,这就是我们在下面所做的。\n\nvoid grid_5() \n{ \n Triangulation<2> triangulation; \n std::vector<unsigned int> repetitions(2); \n repetitions[0] = 14; \n repetitions[1] = 2; \n GridGenerator::subdivided_hyper_rectangle(triangulation, \n repetitions, \n Point<2>(0.0, 0.0), \n Point<2>(10.0, 1.0)); \n\n GridTools::transform( \n [](const Point<2> &in) { \n return Point<2>(in[0], in[1] + std::sin(numbers::PI * in[0] / 5.0)); \n }, \n triangulation); \n print_mesh_info(triangulation, \"grid-5.vtu\"); \n} \n\n// @sect4{grid_6: Demonstrating GridTools::transform, part 2} \n\n// 在第二个例子中,我们将使用映射 $(x,y) \\mapsto (x,\\tanh(2y)/\\tanh(2))$ 将原始网格中的点转换为新的网格。为了使事情更有趣,而不是像前面的例子那样在一个单一的函数中完成,我们在这里创建一个具有 <code>operator()</code> 的对象,这个对象将被 GridTools::transform. 所调用。当然,这个对象实际上可能要复杂得多:这个对象可能有成员变量,在计算顶点的新位置时起作用。\n\nstruct Grid6Func \n{ \n double trans(const double y) const \n { \n return std::tanh(2 * y) / tanh(2); \n } \n\n Point<2> operator()(const Point<2> &in) const \n { \n return {in(0), trans(in(1))}; \n } \n}; \n\nvoid grid_6() \n{ \n Triangulation<2> triangulation; \n std::vector<unsigned int> repetitions(2); \n repetitions[0] = repetitions[1] = 40; \n GridGenerator::subdivided_hyper_rectangle(triangulation, \n repetitions, \n Point<2>(0.0, 0.0), \n Point<2>(1.0, 1.0)); \n\n GridTools::transform(Grid6Func(), triangulation); \n print_mesh_info(triangulation, \"grid-6.vtu\"); \n} \n// @sect4{grid_7: Demonstrating distort_random} \n\n// 在这最后一个例子中,我们创建了一个网格,然后通过随机扰动使其(内部)顶点变形。这不是你想在生产计算中做的事情(因为在具有 \"良好形状 \"单元的网格上的结果通常比在 GridTools::distort_random()), 产生的变形单元上的结果要好,但这是一个有用的工具,可以测试离散化和代码,确保它们不会因为网格恰好是均匀结构和支持超级收敛特性而意外地工作。\n\nvoid grid_7() \n{ \n Triangulation<2> triangulation; \n std::vector<unsigned int> repetitions(2); \n repetitions[0] = repetitions[1] = 16; \n GridGenerator::subdivided_hyper_rectangle(triangulation, \n repetitions, \n Point<2>(0.0, 0.0), \n Point<2>(1.0, 1.0)); \n\n GridTools::distort_random(0.3, triangulation, true); \n print_mesh_info(triangulation, \"grid-7.vtu\"); \n} \n// @sect3{The main function} \n\n// 最后是主函数。这里没有什么可做的,只是调用我们上面写的所有各种函数。\n\nint main() \n{ \n try \n { \n grid_1(); \n grid_2(); \n grid_3(); \n grid_4(); \n grid_5(); \n grid_6(); \n grid_7(); \n } \n catch (std::exception &exc) \n { \n std::cerr << std::endl \n << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n std::cerr << \"Exception on processing: \" << std::endl \n << exc.what() << std::endl \n << \"Aborting!\" << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n\n return 1; \n } \n catch (...) \n { \n std::cerr << std::endl \n << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n std::cerr << \"Unknown exception!\" << std::endl \n << \"Aborting!\" << std::endl \n << \"----------------------------------------------------\" \n << std::endl; \n return 1; \n } \n} \n\n\n", "meta": {"hexsha": "71d2645522b7afd85f445d695bf1bf653b8a5bea", "size": 9548, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-49/step-49.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-49/step-49.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-49/step-49.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.501754386, "max_line_length": 303, "alphanum_fraction": 0.6045245078, "num_tokens": 3974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.1623800386934589, "lm_q1q2_score": 0.06492142969342321}}
{"text": "/**\n * \\file dcs/disjoint_sets.hpp\n *\n * \\brief Implementation of the disjoint-sets (union-find) data structure.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_DISJOINT_SETS_HPP\n#define DCS_DISJOINT_SETS_HPP\n\n\n#include <boost/function.hpp>\n#include <cstddef>\n#include <map>\n#include <vector>\n\n\nnamespace dcs {\n\nnamespace detail { namespace /*<unnamed>*/ {\n\ntemplate <typename T,typename ValueT>\nstruct identity_hasher\n{\n\tValueT operator()(T const& t) { return t; }\n}; // identity\n\n\ntemplate <class ParentPA, class Vertex>\nVertex find_representative_with_path_halving(ParentPA p, Vertex v)\n{\n Vertex parent = p[v];\n Vertex grandparent = p[parent];\n while (parent != grandparent) {\n p[v] = grandparent;\n v = grandparent;\n parent = p[v];\n grandparent = p[parent];\n }\n return parent;\n}\n\n\ntemplate <class ParentPA, class Vertex>\nVertex find_representative_with_full_compression(ParentPA parent, Vertex v)\n{\n Vertex old = v;\n Vertex ancestor = parent[v];\n while (ancestor != v) {\n v = ancestor;\n ancestor = parent[v];\n }\n v = parent[old];\n while (ancestor != v) {\n parent[old] = ancestor;\n old = v;\n v = parent[old];\n }\n return ancestor;\n}\n\n}} // Namespace detail::<unnamed>\n\n\nstruct find_with_path_halving\n{\n\ttemplate <class ParentPA, class Vertex>\n\tVertex operator()(ParentPA p, Vertex v) const\n\t{\n\t\treturn detail::find_representative_with_path_halving(p, v);\n\t}\n};\n\nstruct find_with_full_path_compression\n{\n\ttemplate <class ParentPA, class Vertex>\n\tVertex operator()(ParentPA p, Vertex v) const\n\t{\n\t\treturn detail::find_representative_with_full_compression(p, v);\n\t}\n};\n\n\ntemplate <typename ElementT, typename FinderT = find_with_full_path_compression>\nclass disjoint_sets\n{\n\tpublic: typedef ElementT element_type;\n\tpublic: typedef ::std::size_t size_type;\n\tpublic: typedef size_type (*hash_function_type)(element_type const&);\n\tpublic: typedef FinderT finder_type;\n\n\n\tpublic: disjoint_sets()\n\t: hash_(detail::identity_hasher<element_type,size_type>())\n\t{\n\t}\n\n\tpublic: void make_set(element_type const& e)\n\t{\n\t\tsize_type sid(id_map_.size());\n\t\tid_map_[hash_(e)] = sid;\n\t\tinv_id_map_[sid] = e;\n\t\tranks_.push_back(0);\n\t\tparents_.push_back(sid);\n\n\t}\n\n\tpublic: size_type find_set(element_type const& e) const\n\t{\n\t\treturn finder_(parents_, id_map_.at(hash_(e)));\n\t}\n\n\tpublic: void link_sets(element_type const& e1, element_type const& e2)\n\t{\n\t\tsize_type sid1 = find_set(e1);\n\t\tsize_type sid2 = find_set(e2);\n\t\tif (sid1 == sid2)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t// e1 and e1 are not already in same set. Merge them.\n\t\tif (ranks_[sid1] > ranks_[sid2])\n\t\t{\n\t\t\tparents_[sid2] = sid1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tparents_[sid1] = sid2;\n\t\t\tif (ranks_[sid1] == ranks_[sid2])\n\t\t\t{\n\t\t\t\tranks_[sid2] += 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic: void union_sets(element_type const& e1, element_type const& e2)\n\t{\n\t\tlink_sets(find_set(e1), find_set(e2));\n\t}\n\n\n\tprivate: ::std::vector<size_type> ranks_;\n\tprivate: ::std::vector<size_type> parents_;\n\tprivate: ::std::map<size_type,size_type> id_map_;\n\tprivate: ::std::map<size_type,element_type> inv_id_map_;\n\tprivate: ::boost::function<size_type(element_type const&)> hash_;\n\tprivate: finder_type finder_;\n}; // disjoint_sets\n\n} // Namespace dcs\n\n#endif // DCS_DISJOINT_SETS_HPP\n", "meta": {"hexsha": "19d6719e8c776974c04ba8306814c27e45e44efe", "size": 3870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/disjoint_sets.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/disjoint_sets.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/disjoint_sets.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6315789474, "max_line_length": 80, "alphanum_fraction": 0.7062015504, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.12765261702501562, "lm_q1q2_score": 0.06382630851250781}}
{"text": "// (C) Copyright 2007-2009 Andrew Sutton\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GRAPH_CYCLE_HPP\r\n#define BOOST_GRAPH_CYCLE_HPP\r\n\r\n#include <vector>\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/properties.hpp>\r\n\r\n#include <boost/concept/detail/concept_def.hpp>\r\nnamespace boost {\r\n namespace concepts {\r\n BOOST_concept(CycleVisitor,(Visitor)(Path)(Graph))\r\n {\r\n BOOST_CONCEPT_USAGE(CycleVisitor)\r\n {\r\n vis.cycle(p, g);\r\n }\r\n private:\r\n Visitor vis;\r\n Graph g;\r\n Path p;\r\n };\r\n } /* namespace concepts */\r\nusing concepts::CycleVisitorConcept;\r\n} /* namespace boost */\r\n#include <boost/concept/detail/concept_undef.hpp>\r\n\r\n\r\nnamespace boost\r\n{\r\n\r\n// The implementation of this algorithm is a reproduction of the Teirnan\r\n// approach for directed graphs: bibtex follows\r\n//\r\n// @article{362819,\r\n// author = {James C. Tiernan},\r\n// title = {An efficient search algorithm to find the elementary circuits of a graph},\r\n// journal = {Commun. ACM},\r\n// volume = {13},\r\n// number = {12},\r\n// year = {1970},\r\n// issn = {0001-0782},\r\n// pages = {722--726},\r\n// doi = {http://doi.acm.org/10.1145/362814.362819},\r\n// publisher = {ACM Press},\r\n// address = {New York, NY, USA},\r\n// }\r\n//\r\n// It should be pointed out that the author does not provide a complete analysis for\r\n// either time or space. This is in part, due to the fact that it's a fairly input\r\n// sensitive problem related to the density and construction of the graph, not just\r\n// its size.\r\n//\r\n// I've also taken some liberties with the interpretation of the algorithm - I've\r\n// basically modernized it to use real data structures (no more arrays and matrices).\r\n// Oh... and there's explicit control structures - not just gotos.\r\n//\r\n// The problem is definitely NP-complete, an an unbounded implementation of this\r\n// will probably run for quite a while on a large graph. The conclusions\r\n// of this paper also reference a Paton algorithm for undirected graphs as being\r\n// much more efficient (apparently based on spanning trees). Although not implemented,\r\n// it can be found here:\r\n//\r\n// @article{363232,\r\n// author = {Keith Paton},\r\n// title = {An algorithm for finding a fundamental set of cycles of a graph},\r\n// journal = {Commun. ACM},\r\n// volume = {12},\r\n// number = {9},\r\n// year = {1969},\r\n// issn = {0001-0782},\r\n// pages = {514--518},\r\n// doi = {http://doi.acm.org/10.1145/363219.363232},\r\n// publisher = {ACM Press},\r\n// address = {New York, NY, USA},\r\n// }\r\n\r\n/**\r\n * The default cycle visitor providse an empty visit function for cycle\r\n * visitors.\r\n */\r\nstruct cycle_visitor\r\n{\r\n template <typename Path, typename Graph>\r\n inline void cycle(const Path& p, const Graph& g)\r\n { }\r\n};\r\n\r\n/**\r\n * The min_max_cycle_visitor simultaneously records the minimum and maximum\r\n * cycles in a graph.\r\n */\r\nstruct min_max_cycle_visitor\r\n{\r\n min_max_cycle_visitor(std::size_t& min_, std::size_t& max_)\r\n : minimum(min_), maximum(max_)\r\n { }\r\n\r\n template <typename Path, typename Graph>\r\n inline void cycle(const Path& p, const Graph& g)\r\n {\r\n BOOST_USING_STD_MIN();\r\n BOOST_USING_STD_MAX();\r\n std::size_t len = p.size();\r\n minimum = min BOOST_PREVENT_MACRO_SUBSTITUTION (minimum, len);\r\n maximum = max BOOST_PREVENT_MACRO_SUBSTITUTION (maximum, len);\r\n }\r\n std::size_t& minimum;\r\n std::size_t& maximum;\r\n};\r\n\r\ninline min_max_cycle_visitor\r\nfind_min_max_cycle(std::size_t& min_, std::size_t& max_)\r\n{ return min_max_cycle_visitor(min_, max_); }\r\n\r\nnamespace detail\r\n{\r\n template <typename Graph, typename Path>\r\n inline bool\r\n is_vertex_in_path(const Graph&,\r\n typename graph_traits<Graph>::vertex_descriptor v,\r\n const Path& p)\r\n {\r\n return (std::find(p.begin(), p.end(), v) != p.end());\r\n }\r\n\r\n template <typename Graph, typename ClosedMatrix>\r\n inline bool\r\n is_path_closed(const Graph& g,\r\n typename graph_traits<Graph>::vertex_descriptor u,\r\n typename graph_traits<Graph>::vertex_descriptor v,\r\n const ClosedMatrix& closed)\r\n {\r\n // the path from u to v is closed if v can be found in the list\r\n // of closed vertices associated with u.\r\n typedef typename ClosedMatrix::const_reference Row;\r\n Row r = closed[get(vertex_index, g, u)];\r\n if(find(r.begin(), r.end(), v) != r.end()) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n template <typename Graph, typename Path, typename ClosedMatrix>\r\n inline bool\r\n can_extend_path(const Graph& g,\r\n typename graph_traits<Graph>::edge_descriptor e,\r\n const Path& p,\r\n const ClosedMatrix& m)\r\n {\r\n function_requires< IncidenceGraphConcept<Graph> >();\r\n function_requires< VertexIndexGraphConcept<Graph> >();\r\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n\r\n // get the vertices in question\r\n Vertex\r\n u = source(e, g),\r\n v = target(e, g);\r\n\r\n // conditions for allowing a traversal along this edge are:\r\n // 1. the index of v must be greater than that at which the\r\n // the path is rooted (p.front()).\r\n // 2. the vertex v cannot already be in the path\r\n // 3. the vertex v cannot be closed to the vertex u\r\n\r\n bool indices = get(vertex_index, g, p.front()) < get(vertex_index, g, v);\r\n bool path = !is_vertex_in_path(g, v, p);\r\n bool closed = !is_path_closed(g, u, v, m);\r\n return indices && path && closed;\r\n }\r\n\r\n template <typename Graph, typename Path>\r\n inline bool\r\n can_wrap_path(const Graph& g, const Path& p)\r\n {\r\n function_requires< IncidenceGraphConcept<Graph> >();\r\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n typedef typename graph_traits<Graph>::out_edge_iterator OutIterator;\r\n\r\n // iterate over the out-edges of the back, looking for the\r\n // front of the path. also, we can't travel along the same\r\n // edge that we did on the way here, but we don't quite have the\r\n // stringent requirements that we do in can_extend_path().\r\n Vertex\r\n u = p.back(),\r\n v = p.front();\r\n OutIterator i, end;\r\n for(boost::tie(i, end) = out_edges(u, g); i != end; ++i) {\r\n if((target(*i, g) == v)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n template <typename Graph,\r\n typename Path,\r\n typename ClosedMatrix>\r\n inline typename graph_traits<Graph>::vertex_descriptor\r\n extend_path(const Graph& g,\r\n Path& p,\r\n ClosedMatrix& closed)\r\n {\r\n function_requires< IncidenceGraphConcept<Graph> >();\r\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n typedef typename graph_traits<Graph>::edge_descriptor Edge;\r\n typedef typename graph_traits<Graph>::out_edge_iterator OutIterator;\r\n\r\n // get the current vertex\r\n Vertex u = p.back();\r\n Vertex ret = graph_traits<Graph>::null_vertex();\r\n\r\n // AdjacencyIterator i, end;\r\n OutIterator i, end;\r\n for(boost::tie(i, end) = out_edges(u, g); i != end; ++i) {\r\n Vertex v = target(*i, g);\r\n\r\n // if we can actually extend along this edge,\r\n // then that's what we want to do\r\n if(can_extend_path(g, *i, p, closed)) {\r\n p.push_back(v); // add the vertex to the path\r\n ret = v;\r\n break;\r\n }\r\n }\r\n return ret;\r\n }\r\n\r\n template <typename Graph, typename Path, typename ClosedMatrix>\r\n inline bool\r\n exhaust_paths(const Graph& g, Path& p, ClosedMatrix& closed)\r\n {\r\n function_requires< GraphConcept<Graph> >();\r\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n\r\n // if there's more than one vertex in the path, this closes\r\n // of some possible routes and returns true. otherwise, if there's\r\n // only one vertex left, the vertex has been used up\r\n if(p.size() > 1) {\r\n // get the last and second to last vertices, popping the last\r\n // vertex off the path\r\n Vertex last, prev;\r\n last = p.back();\r\n p.pop_back();\r\n prev = p.back();\r\n\r\n // reset the closure for the last vertex of the path and\r\n // indicate that the last vertex in p is now closed to\r\n // the next-to-last vertex in p\r\n closed[get(vertex_index, g, last)].clear();\r\n closed[get(vertex_index, g, prev)].push_back(last);\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n\r\n template <typename Graph, typename Visitor>\r\n inline void\r\n all_cycles_from_vertex(const Graph& g,\r\n typename graph_traits<Graph>::vertex_descriptor v,\r\n Visitor vis,\r\n std::size_t minlen,\r\n std::size_t maxlen)\r\n {\r\n function_requires< VertexListGraphConcept<Graph> >();\r\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n typedef std::vector<Vertex> Path;\r\n function_requires< CycleVisitorConcept<Visitor,Path,Graph> >();\r\n typedef std::vector<Vertex> VertexList;\r\n typedef std::vector<VertexList> ClosedMatrix;\r\n\r\n Path p;\r\n ClosedMatrix closed(num_vertices(g), VertexList());\r\n Vertex null = graph_traits<Graph>::null_vertex();\r\n\r\n // each path investigation starts at the ith vertex\r\n p.push_back(v);\r\n\r\n while(1) {\r\n // extend the path until we've reached the end or the\r\n // maxlen-sized cycle\r\n Vertex j = null;\r\n while(((j = detail::extend_path(g, p, closed)) != null)\r\n && (p.size() < maxlen))\r\n ; // empty loop\r\n\r\n // if we're done extending the path and there's an edge\r\n // connecting the back to the front, then we should have\r\n // a cycle.\r\n if(detail::can_wrap_path(g, p) && p.size() >= minlen) {\r\n vis.cycle(p, g);\r\n }\r\n\r\n if(!detail::exhaust_paths(g, p, closed)) {\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // Select the minimum allowable length of a cycle based on the directedness\r\n // of the graph - 2 for directed, 3 for undirected.\r\n template <typename D> struct min_cycles { enum { value = 2 }; };\r\n template <> struct min_cycles<undirected_tag> { enum { value = 3 }; };\r\n} /* namespace detail */\r\n\r\ntemplate <typename Graph, typename Visitor>\r\ninline void\r\ntiernan_all_cycles(const Graph& g,\r\n Visitor vis,\r\n std::size_t minlen,\r\n std::size_t maxlen)\r\n{\r\n function_requires< VertexListGraphConcept<Graph> >();\r\n typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;\r\n\r\n VertexIterator i, end;\r\n for(boost::tie(i, end) = vertices(g); i != end; ++i) {\r\n detail::all_cycles_from_vertex(g, *i, vis, minlen, maxlen);\r\n }\r\n}\r\n\r\ntemplate <typename Graph, typename Visitor>\r\ninline void\r\ntiernan_all_cycles(const Graph& g, Visitor vis, std::size_t maxlen)\r\n{\r\n typedef typename graph_traits<Graph>::directed_category Dir;\r\n tiernan_all_cycles(g, vis, detail::min_cycles<Dir>::value, maxlen);\r\n}\r\n\r\ntemplate <typename Graph, typename Visitor>\r\ninline void\r\ntiernan_all_cycles(const Graph& g, Visitor vis)\r\n{\r\n typedef typename graph_traits<Graph>::directed_category Dir;\r\n tiernan_all_cycles(g, vis, detail::min_cycles<Dir>::value,\r\n (std::numeric_limits<std::size_t>::max)());\r\n}\r\n\r\ntemplate <typename Graph>\r\ninline std::pair<std::size_t, std::size_t>\r\ntiernan_girth_and_circumference(const Graph& g)\r\n{\r\n std::size_t\r\n min_ = (std::numeric_limits<std::size_t>::max)(),\r\n max_ = 0;\r\n tiernan_all_cycles(g, find_min_max_cycle(min_, max_));\r\n\r\n // if this is the case, the graph is acyclic...\r\n if(max_ == 0) max_ = min_;\r\n\r\n return std::make_pair(min_, max_);\r\n}\r\n\r\ntemplate <typename Graph>\r\ninline std::size_t\r\ntiernan_girth(const Graph& g)\r\n{ return tiernan_girth_and_circumference(g).first; }\r\n\r\ntemplate <typename Graph>\r\ninline std::size_t\r\ntiernan_circumference(const Graph& g)\r\n{ return tiernan_girth_and_circumference(g).second; }\r\n\r\n} /* namespace boost */\r\n\r\n#endif\r\n", "meta": {"hexsha": "a80d547195525ed4ae789bf5dcd35b3f743c25c1", "size": 13202, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/tiernan_all_cycles.hpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-30T18:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T18:41:39.000Z", "max_issues_repo_path": "boost/graph/tiernan_all_cycles.hpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/tiernan_all_cycles.hpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0185676393, "max_line_length": 95, "alphanum_fraction": 0.590971065, "num_tokens": 2946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.13660838651113866, "lm_q1q2_score": 0.06350945152621872}}
{"text": "// Copyright John Maddock 2006.\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0. (See accompanying file\r\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// distributions.hpp provides definitions of the concept of a distribution\r\n// and non-member accessor functions that must be implemented by all distributions.\r\n// This is used to verify that\r\n// all the features of a distributions have been fully implemented.\r\n\r\n#ifndef BOOST_MATH_DISTRIBUTION_CONCEPT_HPP\r\n#define BOOST_MATH_DISTRIBUTION_CONCEPT_HPP\r\n\r\n#include <boost/math/distributions/complement.hpp>\r\n#ifdef BOOST_MSVC\r\n#pragma warning(push)\r\n#pragma warning(disable: 4100)\r\n#pragma warning(disable: 4510)\r\n#pragma warning(disable: 4610)\r\n#endif\r\n#include <boost/concept_check.hpp>\r\n#ifdef BOOST_MSVC\r\n#pragma warning(pop)\r\n#endif\r\n#include <utility>\r\n\r\nnamespace boost{\r\nnamespace math{\r\n\r\nnamespace concepts\r\n{\r\n// Begin by defining a concept archetype\r\n// for a distribution class:\r\n//\r\ntemplate <class RealType>\r\nclass distribution_archetype\r\n{\r\npublic:\r\n typedef RealType value_type;\r\n\r\n distribution_archetype(const distribution_archetype&); // Copy constructible.\r\n distribution_archetype& operator=(const distribution_archetype&); // Assignable.\r\n\r\n // There is no default constructor,\r\n // but we need a way to instantiate the archetype:\r\n static distribution_archetype& get_object()\r\n {\r\n // will never get caled:\r\n return *reinterpret_cast<distribution_archetype*>(0);\r\n }\r\n}; // template <class RealType>class distribution_archetype\r\n\r\n// Non-member accessor functions:\r\n// (This list defines the functions that must be implemented by all distributions).\r\n\r\ntemplate <class RealType>\r\nRealType pdf(const distribution_archetype<RealType>& dist, const RealType& x);\r\n\r\ntemplate <class RealType>\r\nRealType cdf(const distribution_archetype<RealType>& dist, const RealType& x);\r\n\r\ntemplate <class RealType>\r\nRealType quantile(const distribution_archetype<RealType>& dist, const RealType& p);\r\n\r\ntemplate <class RealType>\r\nRealType cdf(const complemented2_type<distribution_archetype<RealType>, RealType>& c);\r\n\r\ntemplate <class RealType>\r\nRealType quantile(const complemented2_type<distribution_archetype<RealType>, RealType>& c);\r\n\r\ntemplate <class RealType>\r\nRealType mean(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType standard_deviation(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType variance(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType hazard(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType chf(const distribution_archetype<RealType>& dist);\r\n// http://en.wikipedia.org/wiki/Characteristic_function_%28probability_theory%29\r\n\r\ntemplate <class RealType>\r\nRealType coefficient_of_variation(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType mode(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType skewness(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType kurtosis_excess(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType kurtosis(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nRealType median(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nstd::pair<RealType, RealType> range(const distribution_archetype<RealType>& dist);\r\n\r\ntemplate <class RealType>\r\nstd::pair<RealType, RealType> support(const distribution_archetype<RealType>& dist);\r\n\r\n//\r\n// Next comes the concept checks for verifying that a class\r\n// fullfils the requirements of a Distribution:\r\n//\r\ntemplate <class Distribution>\r\nstruct DistributionConcept\r\n{\r\n void constraints()\r\n {\r\n function_requires<CopyConstructibleConcept<Distribution> >();\r\n function_requires<AssignableConcept<Distribution> >();\r\n\r\n typedef typename Distribution::value_type value_type;\r\n\r\n const Distribution& dist = DistributionConcept<Distribution>::get_object();\r\n\r\n value_type x = 0;\r\n // The result values are ignored in all these checks.\r\n value_type v = cdf(dist, x);\r\n v = cdf(complement(dist, x));\r\n v = pdf(dist, x);\r\n v = quantile(dist, x);\r\n v = quantile(complement(dist, x));\r\n v = mean(dist);\r\n v = mode(dist);\r\n v = standard_deviation(dist);\r\n v = variance(dist);\r\n v = hazard(dist, x);\r\n v = chf(dist, x);\r\n v = coefficient_of_variation(dist);\r\n v = skewness(dist);\r\n v = kurtosis(dist);\r\n v = kurtosis_excess(dist);\r\n v = median(dist);\r\n std::pair<value_type, value_type> pv;\r\n pv = range(dist);\r\n pv = support(dist);\r\n\r\n float f = 1;\r\n v = cdf(dist, f);\r\n v = cdf(complement(dist, f));\r\n v = pdf(dist, f);\r\n v = quantile(dist, f);\r\n v = quantile(complement(dist, f));\r\n v = hazard(dist, f);\r\n v = chf(dist, f);\r\n double d = 1;\r\n v = cdf(dist, d);\r\n v = cdf(complement(dist, d));\r\n v = pdf(dist, d);\r\n v = quantile(dist, d);\r\n v = quantile(complement(dist, d));\r\n v = hazard(dist, d);\r\n v = chf(dist, d);\r\n#ifndef TEST_MPFR\r\n long double ld = 1;\r\n v = cdf(dist, ld);\r\n v = cdf(complement(dist, ld));\r\n v = pdf(dist, ld);\r\n v = quantile(dist, ld);\r\n v = quantile(complement(dist, ld));\r\n v = hazard(dist, ld);\r\n v = chf(dist, ld);\r\n#endif\r\n int i = 1;\r\n v = cdf(dist, i);\r\n v = cdf(complement(dist, i));\r\n v = pdf(dist, i);\r\n v = quantile(dist, i);\r\n v = quantile(complement(dist, i));\r\n v = hazard(dist, i);\r\n v = chf(dist, i);\r\n unsigned long li = 1;\r\n v = cdf(dist, li);\r\n v = cdf(complement(dist, li));\r\n v = pdf(dist, li);\r\n v = quantile(dist, li);\r\n v = quantile(complement(dist, li));\r\n v = hazard(dist, li);\r\n v = chf(dist, li);\r\n }\r\nprivate:\r\n static Distribution& get_object()\r\n {\r\n // will never get called:\r\n static char buf[sizeof(Distribution)];\r\n return * reinterpret_cast<Distribution*>(buf);\r\n }\r\n}; // struct DistributionConcept\r\n\r\n} // namespace concepts\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_DISTRIBUTION_CONCEPT_HPP\r\n\r\n", "meta": {"hexsha": "610c9d58de21e7ee815acbc4d776eda120eb8bde", "size": 6411, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/math/concepts/distributions.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T01:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-26T07:38:43.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/math/concepts/distributions.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T01:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T01:56:28.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/math/concepts/distributions.hpp", "max_forks_repo_name": "benkaraban/anima-games-engine", "max_forks_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9710144928, "max_line_length": 92, "alphanum_fraction": 0.6788332553, "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.12085323090725615, "lm_q1q2_score": 0.05995454212471399}}
{"text": "/*\n//@HEADER\n// ************************************************************************\n//\n// tutorial1.cc\n// \t\t Pressio\n// Copyright 2019\n// National Technology & Engineering Solutions of Sandia, LLC (NTESS)\n//\n// Under the terms of Contract DE-NA0003525 with NTESS, the\n// U.S. Government retains certain rights in this software.\n//\n// Pressio is licensed under BSD-3-Clause terms of use:\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)\n//\n// ************************************************************************\n//@HEADER\n*/\n\n#include \"pressio_containers.hpp\"\n#include <Eigen/Core>\n\nint main(int argc, char *argv[])\n{\n std::cout << \"Running tutorial 1\\n\";\n\n /*\n Pressio makes use of container wrappers to wrap arbitrary data types.\n These wrappers are thin layers.\n\n Pressio has predefined knowledge about data structures\n from specific libraries, e.g. Trilinos, Eigen, Kokkos.\n Over time, this support will be extended.\n If your application uses vector/matrix/multivector classes of one\n of these libraries, you can easily use pressio as follows.\n\n Suppose that you have an application that is based on Eigen.\n Therefore, a (dynamic) vector object \"a\" in your application looks like:\n\n Eigen::VectorXd a;\n\n Now, suppose now that you need to use some functionality in pressio.\n To do so, you need to wrap your object with a pressio container.\n e.g. ::pressio::containers::Vector<Eigen::VectorXd> aW(a);\n\n If the type you are wrapping is one of the already supported by pressio,\n then you have seamless access to all pressio functionalities, since pressio\n behind the scenes knows how to do algebra with these objects and in fact\n leverages the native algebra functionalities of the target library.\n If the type you are wrapping is NOT already known to pressio,\n then you can still wrap it, but in order to instantiate and use pressio\n functionalities you need to provide functionalities to tell pressio\n how to do operations with your data types.\n See tutorials{3,5} for examples showing using arbitrary types.\n */\n\n // this is dynamic double array in Eigen\n Eigen::VectorXd a(5);\n a.setConstant(2.2);\n\n // the corresponding pressio wrapper can be created as follows\n // Note that here pressio makes a deep copy of the object.\n // This is because the target ROM algorithms are all implemented\n // such that pressio owns the data and queries the full-order application\n // to computed things.\n ::pressio::containers::Vector<Eigen::VectorXd> aW(a);\n\n // we can verify that a deep copy is made\n for (auto i=0; i<aW.extent(0); ++i)\n std::cout << \"aW(i) = \" << aW(i)\n\t << \" expected = \" << 2.2\n\t << std::endl;\n\n // note that above we used the \"extent\" method\n // extent(k) works for all pressio container wrappers\n // - extent(k1) for 1d objects,\n // - extent(k1,k2) for 2d objects\n\n return 0;\n}\n", "meta": {"hexsha": "2ae7167a00e77e7bc836a224b0355f4e68c79e54", "size": 4470, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tutorials/wip/tutorial1.cc", "max_stars_repo_name": "Pressio/pressio-tutorials", "max_stars_repo_head_hexsha": "5762d17a8cd2990d84ccc80e1f5ba9759b55b5b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-06T12:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T12:06:19.000Z", "max_issues_repo_path": "tutorials/wip/tutorial1.cc", "max_issues_repo_name": "Pressio/pressio-tutorials", "max_issues_repo_head_hexsha": "5762d17a8cd2990d84ccc80e1f5ba9759b55b5b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2019-09-30T11:34:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T20:58:46.000Z", "max_forks_repo_path": "tutorials/wip/tutorial1.cc", "max_forks_repo_name": "Pressio/pressio-tutorials", "max_forks_repo_head_hexsha": "5762d17a8cd2990d84ccc80e1f5ba9759b55b5b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6363636364, "max_line_length": 79, "alphanum_fraction": 0.6995525727, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.15002883004302128, "lm_q1q2_score": 0.05554448250333409}}
{"text": "/* Daniel R. Reynolds\n SMU Mathematics\n 6 August 2020 */\n\n// Inclusions\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <armadillo>\nusing namespace std;\n\n// prototypes of other functions\nint GramSchmidt(arma::mat& X);\n\n\n// Example routine to test the Mat class\nint main(int argc, char* argv[]) {\n\n // create a row vector of length 5\n arma::rowvec a(5);\n a.fill(0.0);\n\n // create a row vec with an existing data array\n double dat1[5] = {0.1, 0.2, 0.3, 0.4, 0.5};\n arma::rowvec b(dat1, 5);\n\n // create a column vec with an existing vector\n double dat2[5] = {0.1, 0.2, 0.3, 0.4, 0.5};\n arma::vec b2(dat2, 5);\n\n // create a row vector using linspace\n arma::rowvec c = arma::linspace<arma::rowvec>(1.0, 5.0, 5);\n\n // create a column vector using the single integer constructor\n arma::vec h(7);\n\n // output vectors above to screen\n cout << \"writing array of zeros:\\n\";\n cout << a << endl;\n cout << \"writing array of 0.1,0.2,0.3,0.4,0.5:\\n\";\n cout << b << endl;\n cout << \"writing (column) array of 0.1,0.2,0.3,0.4,0.5:\\n\";\n cout << b2 << endl;\n cout << \"writing array of 1,2,3,4,5:\\n\";\n cout << c << endl;\n cout << \"writing a column vector of 7 zeros:\\n\";\n cout << h << endl;\n\n // verify that b has size 5\n if (b.n_elem != 5)\n cerr << \"error: incorrect matrix size\\n\";\n if (b.n_cols != 5)\n cerr << \"error: incorrect matrix columns\\n\";\n if (b.n_rows != 1)\n cerr << \"error: incorrect matrix rows\\n\";\n\n // edit entries of a in both matrix forms, and write each entry of a to screen\n a(0) = 10.0;\n a(1) = 15.0;\n a[2] = 20.0;\n a(0,3) = 25.0;\n a.at(4) = 30.0;\n cout << \"entries of a, one at a time: should give 10, 15, 20, 25, 30\\n\";\n for (size_t i=0; i<a.n_elem; i++)\n cout << \" \" << a[i] << endl;\n\n // write the values to file\n cout << \"writing this same vector to the file 'a_data':\\n\";\n a.save(\"a_data\", arma::raw_ascii);\n\n // Testing MatrixRead() constructor\n double tol = 2.0e-15;\n arma::mat read_test1a = arma::randu(3,4);\n read_test1a.save(\"tmp.txt\", arma::raw_ascii);\n arma::mat read_test1b;\n read_test1b.load(\"tmp.txt\");\n arma::mat read_test1_error = read_test1a - read_test1b;\n if (norm(read_test1_error,\"inf\") < tol)\n cout << \"save/load test 1 passed\\n\";\n else {\n cout << \"save/load test 1 failed, ||error|| = \" << norm(read_test1_error,\"inf\") << endl;\n cout << \" read_test1a = \\n\" << read_test1a << endl;\n cout << \" read_test1b = \\n\" << read_test1b << endl;\n }\n\n arma::mat read_test2a = arma::randu(12,1);\n read_test2a.save(\"tmp.txt\", arma::raw_ascii);\n arma::mat read_test2b;\n read_test2b.load(\"tmp.txt\");\n arma::mat read_test2_error = read_test2a - read_test2b;\n if (norm(read_test2_error,\"inf\") < tol)\n cout << \"save/load test 2 passed\\n\";\n else {\n cout << \"save/load test 2 failed, ||error|| = \" << norm(read_test2_error,\"inf\") << endl;\n cout << \" read_test2a = \\n\" << read_test2a << endl;\n cout << \" read_test2b = \\n\" << read_test2b << endl;\n }\n\n arma::mat read_test3a = arma::randu(1,7);\n read_test3a.save(\"tmp.txt\", arma::raw_ascii);\n arma::mat read_test3b;\n read_test3b.load(\"tmp.txt\");\n arma::mat read_test3_error = read_test3a - read_test3b;\n if (norm(read_test3_error,\"inf\") < tol)\n cout << \"save/load test 3 passed\\n\";\n else {\n cout << \"save/load test 3 failed, ||error|| = \" << norm(read_test3_error,\"inf\") << endl;\n cout << \" read_test3a = \\n\" << read_test3a << endl;\n cout << \" read_test3b = \\n\" << read_test3b << endl;\n }\n\n // Testing copy constructor\n arma::mat B = a;\n cout << \"arma::mat B = a uses copy constructor, should give 10, 15, 20, 25, 30\\n\";\n cout << B << endl;\n // update one entry of a\n cout << \"updating the 5th entry of a to be 31:\\n\";\n a(4) = 31.0;\n cout << \" a = \" << a << endl;\n\n cout << \"B should not have changed\" << endl;\n cout << \" B = \" << B << endl;\n a(4) = 30.0; // reset to original\n\n // Testing submatrix copy constructor\n arma::mat B2 = a.submat(0,1,0,3); // B2 = a(0:0,1:3)\n cout << \"arma::mat B2 = a.submat(0,1,0,3) uses submatrix copy constructor\" << endl;\n cout << B2 << endl;\n // update entries of B2\n B2(0) = 4.0;\n B2(1) = 3.0;\n B2(2) = 2.0;\n // copy B2 back into a using submatrix copy\n a(0,arma::span(1,3)) = B2; // a(0,1:3) = B2\n cout << \"span copy back into a, should have entries 10 4 3 2 30\" << endl;\n cout << a << endl;\n a(1) = 15.0; // reset to original\n a(2) = 20.0;\n a(3) = 25.0;\n\n // Test arithmetic operators\n cout << \"Testing vector add, should give 1.1, 2.2, 3.3, 4.4, 5.5\\n\";\n b += c; // b = b + c\n cout << b << endl;\n\n cout << \"Testing scalar add, should give 2, 3, 4, 5, 6\\n\";\n c += 1.0; // c = c + 1\n cout << c << endl;\n\n cout << \"Testing vector subtract, should be 8, 12, 16, 20, 24\\n\";\n a -= c; // a = a - c\n cout << a << endl;\n\n cout << \"Testing scalar subtract, should be 0, 1, 2, 3, 4\\n\";\n c -= 2.0; // c = c - 2\n cout << c << endl;\n\n cout << \"Testing vector fill, should all be -1\\n\";\n b.fill(-1.0); // b = -1*ones(size(b))\n cout << b << endl;\n\n cout << \"Testing vector copy, should be 0, 1, 2, 3, 4\\n\";\n a = c;\n cout << a << endl;\n\n cout << \"Testing scalar multiply, should be 0, 5, 10, 15, 20\\n\";\n c *= 5.0; // c = c * 5\n cout << c << endl;\n\n cout << \"Testing deep copy, should be 0, 1, 2, 3, 4\\n\";\n cout << a << endl;\n\n cout << \"Testing vector multiply, should be 0, -1, -2, -3, -4\\n\";\n b %= a; // b = b.*a\n cout << b << endl;\n\n cout << \"Testing vector divide, should be 0, -2.5, -3.3333, -3.75, -4\\n\";\n arma::mat j(c); // j = c\n b += -1.0;\n j /= b; // j = j ./ b\n b += 1.0;\n cout << j << endl;\n\n cout << \"Testing vector +=, should be 0, 4, 8, 12, 16\\n\";\n b += c;\n cout << b << endl;\n\n cout << \"Testing scalar +=, should be 1, 6, 11, 16, 21\\n\";\n c += 1.0;\n cout << c << endl;\n\n cout << \"Testing vector -=, should be 1, 2, 3, 4, 5\\n\";\n c -= b;\n cout << c << endl;\n\n cout << \"Testing scalar -=, should be -2, -1, 0, 1, 2\\n\";\n a -= 2.0;\n cout << a << endl;\n\n cout << \"Testing vector %=, should be 0, -4, 0, 12, 32\\n\";\n a %= b;\n cout << a << endl;\n\n cout << \"Testing scalar *=, should be 2, 4, 6, 8, 10\\n\";\n c *= 2.0;\n cout << c << endl;\n\n cout << \"Testing vector /=, should be 0, -1, 0, 1.5, 3.2\\n\";\n j = a;\n j /= c;\n cout << j << endl;\n\n cout << \"Testing scalar /=, should be 1, 2, 3, 4, 5\\n\";\n j = c;\n j /= 2.0;\n cout << j << endl;\n\n cout << \"Testing vector =, should be 2, 4, 6, 8, 10\\n\";\n b = c;\n cout << b << endl;\n\n cout << \"Testing scalar fill, should be 3, 3, 3, 3, 3\\n\";\n a.fill(3.0);\n cout << a << endl;\n\n cout << \"Testing vector norm, should be 14.8324\\n\";\n cout << \" \" << arma::norm(b) << endl;\n\n cout << \"Testing vector infinity norm, should be 10\\n\";\n cout << \" \" << arma::norm(b,\"inf\") << endl;\n\n cout << \"Testing vector one norm, should be 30\\n\";\n cout << \" \" << arma::norm(b,1) << endl;\n\n cout << \"Testing vector min, should be 2\\n\";\n cout << \" \" << b.min() << endl;\n\n cout << \"Testing vector max, should be 10\\n\";\n cout << \" \" << b.max() << endl;\n\n B = arma::mat(2,5);\n B(0,arma::span(0,4)) = c; // B(0,:) = c\n B(1,arma::span(0,4)) = a; // B(1,:) = a\n B += 2.0;\n\n cout << \"Testing matrix infinity norm, should be 40\\n\";\n cout << \" \" << arma::norm(B,\"inf\") << endl;\n\n cout << \"Testing matrix one norm, should be 17\\n\";\n cout << \" \" << arma::norm(B,1) << endl;\n\n cout << \"Testing matrix two norm, should be 21.7821\\n\";\n cout << \" \" << arma::norm(B,2) << endl;\n\n cout << \"Testing matrix min, should be 4\\n\";\n cout << \" \" << B.min() << endl;\n\n cout << \"Testing matrix max, should be 12\\n\";\n cout << \" \" << B.max() << endl;\n\n cout << \"Testing dot, should be 90\\n\";\n cout << \" \" << dot(a, c) << endl;\n\n cout << \"Testing logspace, should be 0.01 0.1 1 10 100\\n\";\n arma::mat e = arma::logspace<arma::rowvec>(-2.0, 2.0, 5);\n cout << e << endl;\n\n ofstream out;\n out.open(\"e.txt\");\n if(out.is_open())\n {\n out << e;\n cout << \"Wrote to file e.txt:\\n\" << e;\n }\n out.close();\n\n cout << \"Testing randu\\n\";\n arma::mat f = arma::randu(3,3);\n cout << \"f = \" << f << endl;\n cout << \"Testing write with a temporary result\" << endl;\n cout << (f*f+f) << endl;\n cout << \"f should be unchanged from above\" << endl;\n cout << \"f = \" << f << endl;\n cout << \"Testing f==f, should be 3x3 matrix of ones\\n\" << (f==f) << endl;\n b.fill(1.0);\n cout << \"Testing e==b, should be 0 0 1 0 0\\n \" << (e==b) << endl;\n\n // create and fill in a 10x5 matrix\n arma::mat Y(10,5);\n for (size_t i=0; i<10; i++) {\n Y(i,0) = 1.0*i;\n Y(i,1) = -5.0 + 1.0*i;\n Y(i,2) = 2.0 + 2.0*i;\n Y(i,3) = 20.0 - 1.0*i;\n Y(i,4) = -20.0 + 1.0*i;\n }\n\n // extract columns from matrix (both ways)\n arma::vec Y0 = Y.col(0);\n arma::mat Y1(Y.col(1));\n arma::vec Y2(Y(arma::span(0,9),2));\n arma::vec Y3 = Y.col(3);\n arma::vec Y4 = Y(arma::span(0,9),4);\n\n // check the LinearSum routine\n Y4 += Y3;\n cout << \"Testing column extraction, should be all zeros:\\n\";\n cout << Y4 << endl;\n\n // check linear sum \n arma::mat d = arma::linspace<arma::rowvec>(0.0, 4.0, 5);\n cout << \"Testing LinearSum, should be 0.02 1.2 4 23 204:\\n\";\n arma::mat g = 1.0*d + 2.0*e;\n cout << g << endl;\n\n // check the pow routine\n d = arma::pow(d,2.0); // d = d.^2\n cout << \"Testing pow, should be 0 1 4 9 16:\\n\";\n cout << d << endl;\n d = arma::pow(d,0.5); // d = sqrt(d)\n cout << \"Testing pow, should be 0 1 2 3 4:\\n\";\n cout << d << endl;\n\n // check the abs routine\n Y1 = arma::abs(Y1);\n cout << \"Testing abs, should be the column 5 4 3 2 1 0 1 2 3 4:\\n\";\n cout << Y1 << endl;\n\n // check the inplace_trans routine\n cout << \"Testing inplace_trans, should be the row 5 4 3 2 1 0 1 2 3 4:\\n\";\n inplace_trans(Y1);\n cout << Y1 << endl;\n\n // check the copy-based transpose routine\n cout << \"Testing copy-based transpose, should be the column 5 4 3 2 1 0 1 2 3 4:\\n\";\n Y2 = Y1.t();\n cout << Y2 << endl;\n\n cout << \"Testing GramSchmidt, should work\\n\";\n arma::mat X = arma::randu(20,3);\n int iret = GramSchmidt(X);\n cout << \" GramSchmidt returned \" << iret << \", dot-products are:\\n\";\n cout << \" <X0,X0> = \" << arma::dot(X.col(0),X.col(0)) << endl;\n cout << \" <X0,X1> = \" << arma::dot(X.col(0),X.col(1)) << endl;\n cout << \" <X0,X2> = \" << arma::dot(X.col(0),X.col(2)) << endl;\n cout << \" <X1,X1> = \" << arma::dot(X.col(1),X.col(1)) << endl;\n cout << \" <X1,X2> = \" << arma::dot(X.col(1),X.col(2)) << endl;\n cout << \" <X2,X2> = \" << arma::dot(X.col(2),X.col(2)) << endl << endl;\n\n cout << \"Testing GramSchmidt, should fail\\n\";\n arma::mat V = arma::randu(20,3);\n V.col(2) = 2.0*V.col(1);\n iret = GramSchmidt(V);\n cout << \" GramSchmidt returned \" << iret << \", dot-products are:\\n\";\n cout << \" <V0,V0> = \" << arma::dot(V.col(0),V.col(0)) << endl;\n cout << \" <V0,V1> = \" << arma::dot(V.col(0),V.col(1)) << endl;\n cout << \" <V0,V2> = \" << arma::dot(V.col(0),V.col(2)) << endl;\n cout << \" <V1,V1> = \" << arma::dot(V.col(1),V.col(1)) << endl;\n cout << \" <V1,V2> = \" << arma::dot(V.col(1),V.col(2)) << endl;\n cout << \" <V2,V2> = \" << arma::dot(V.col(2),V.col(2)) << endl << endl;\n\n cout << \"Testing matrix product, should be: 9 -1 9 -8 11 6\\n\";\n arma::mat A_ = arma::eye(6,6);\n A_(0,3) = 2.0;\n A_(1,2) = -1.0;\n A_(2,5) = 1.0;\n A_(3,5) = -2.0;\n A_(4,5) = 1.0;\n arma::mat xtrue_ = arma::linspace(1.0, 6.0, 6);\n arma::mat b_ = A_*xtrue_;\n cout << b_ << endl;\n\n cout << \"Testing backwards substitution solve with provided solution array:\\n\";\n arma::vec x_(6);\n if (arma::solve(x_, A_, b_)) {\n cout << \" solve succeeded\\n\";\n } else {\n cout << \" solve failed\\n\";\n }\n cout << \" ||x - xtrue|| = \" << arma::norm(x_ - xtrue_, \"inf\") << \"\\n\\n\";\n\n cout << \"Testing forwards substitution with provided solution array:\\n\";\n A_.eye();\n A_(3,0) = 2.0;\n A_(2,1) = -1.0;\n A_(5,2) = 1.0;\n A_(5,3) = -2.0;\n A_(5,4) = 1.0;\n b_ = A_*xtrue_;\n x_ = 0.0;\n if (arma::solve(x_, A_, b_)) {\n cout << \" solve succeeded\\n\";\n } else {\n cout << \" solve failed\\n\";\n }\n cout << \" ||x - xtrue|| = \" << arma::norm(x_ - xtrue_, \"inf\") << \"\\n\\n\";\n\n cout << \"Testing general solver:\\n\";\n arma::mat C_ = 100.0*arma::eye(9,9) + arma::randu(9,9);\n arma::vec z_ = arma::logspace(-4.0, 4.0, 9);\n arma::mat f_ = C_*z_;\n arma::mat g_ = arma::solve(C_, f_);\n cout << \" ||x - xtrue|| = \" << arma::norm(g_ - z_, \"inf\") << \"\\n\\n\";\n\n cout << \"Testing copy-into-col, should be: \\n\";\n cout << \" 0.01 0.02 0.04 0.08\\n\";\n cout << \" 0.1 0.2 0.4 0.8\\n\";\n cout << \" 1 2 4 8\\n\";\n cout << \" 10 20 40 80\\n\";\n cout << \" Actually is:\\n\";\n arma::mat z2_ = arma::logspace(-2.0, 1.0, 4);\n arma::mat B_(4,4);\n B_.col(0) = z2_;\n z2_ *= 2.0;\n B_.col(1) = z2_;\n z2_ *= 2.0;\n B_.col(2) = z2_;\n z2_ *= 2.0;\n B_.col(3) = z2_;\n cout << B_ << endl;\n\n cout << \"Testing general solver with matrix-valued rhs:\\n\";\n arma::mat E_ = 100.0*arma::eye(4,4) + arma::randu(4,4);\n arma::mat F_ = E_*B_;\n arma::mat X_ = arma::solve(E_, F_);\n cout << \" ||X - Xtrue|| = \" << arma::norm(X_ - B_,\"inf\") << \"\\n\\n\";\n\n cout << \"Testing matrix inverse:\\n\";\n arma::mat D_ = 10.0*arma::eye(8,8) + arma::randu(8,8);\n arma::mat DDinv_(D_);\n arma::mat Dinv_ = D_.i();\n DDinv_ = D_*Dinv_;\n cout << \" ||I - D*Dinv|| = \" << arma::norm(arma::eye(8,8) - DDinv_,\"inf\") << endl;\n DDinv_ = Dinv_*D_;\n cout << \" ||I - Dinv*D|| = \" << arma::norm(arma::eye(8,8) - DDinv_,\"inf\") << endl;\n\n return 0;\n} // end main\n", "meta": {"hexsha": "b55d4e166b1e35326114dfa4c9305eff7a33d3a0", "size": 13500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armadillo/armadillo_test.cpp", "max_stars_repo_name": "drreynolds/Math6321-codes", "max_stars_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armadillo/armadillo_test.cpp", "max_issues_repo_name": "drreynolds/Math6321-codes", "max_issues_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armadillo/armadillo_test.cpp", "max_forks_repo_name": "drreynolds/Math6321-codes", "max_forks_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-31T18:04:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T18:04:07.000Z", "avg_line_length": 30.612244898, "max_line_length": 92, "alphanum_fraction": 0.5384444444, "num_tokens": 5329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11279541373888333, "lm_q1q2_score": 0.053316528312935506}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/* */\n/* This file is part of the library KASKADE 7 */\n/* see http://www.zib.de/projects/kaskade7-finite-element-toolbox */\n/* */\n/* Copyright (C) 2002-2016 Zuse Institute Berlin */\n/* */\n/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */\n/* see $KASKADE/academic.txt */\n/* */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <iostream>\n\n#ifndef GRIDTYPE\n#define GRIDTYPE 1 // UGGrid\n#endif\n\n#if ( GRIDTYPE < 1 ) || ( GRIDTYPE > 4 )\n#error \"GRIDTYPE must be 1 (UGGrid), 2 (ALUSImplexGrid), 3 (ALUConformGrid) or 4 (AlbertaGrid)\"\n#endif\n\n#if GRIDTYPE==1\n#define CHARGRIDTYPE \"UGGrid\"\n#elif GRIDTYPE==2\n#define CHARGRIDTYPE \"ALUSimplexGrid\"\n#elif GRIDTYPE==3\n#define CHARGRIDTYPE \"ALUConformGrid\"\n#elif GRIDTYPE==4\n#define CHARGRIDTYPE \"AlbertaGrid\"\n#endif\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n\n#ifndef SPACEDIM\n#define SPACEDIM 2\n#endif\n\n#if ( SPACEDIM < 2 ) || ( SPACEDIM > 3 )\n#error 'Dimension SPACEDIM must be 2 or 3'\n#endif\n\n#if ( GRIDTYPE==2 ) || ( GRIDTYPE==3 )\n#define HAVE_DUNE_ALUGRID 1\n#define ENABLE_DUNE_ALUGRID 1\n#if SPACEDIM==2\n#include \"dune/alugrid/2d/alu2dinclude.hh\"\n#include \"dune/alugrid/2d/alugrid.hh\"\n#include \"dune/alugrid/2d/gridfactory.hh\"\n#else\n#include \"dune/alugrid/3d/alu3dinclude.hh\"\n#include \"dune/alugrid/3d/alugrid.hh\"\n#include \"dune/alugrid/3d/gridfactory.hh\"\n#endif\n#endif\n\n#if GRIDTYPE==4\n#define ENABLE_ALBERTA 1\n#define ALBERTA_DIM SPACEDIM\n#include \"dune/grid/albertagrid/agrid.hh\"\n#include \"dune/grid/albertagrid/gridfactory.hh\"\n#endif\n\n#include \"utilities/enums.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/norms.hh\"\n#include \"fem/lagrangespace.hh\"\n//#include \"fem/hierarchicspace.hh\" // ContinuousHierarchicMapper\n#include \"linalg/direct.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n//#include \"linalg/partialDirectPreconditioner.hh\"\n#include \"linalg/additiveschwarz.hh\"\n#include \"linalg/iluprecond.hh\" // ILUT, ILUK, ARMS\n#include \"linalg/iccprecond.hh\"\n#include \"linalg/icc0precond.hh\"\n#include \"linalg/hyprecond.hh\" // BoomerAMG, Euclid\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/cg.hh\"\n#include \"mg/hb.hh\"\n#include \"io/vtk.hh\"\n//#include \"io/amira.hh\"\n#include \"utilities/kaskopt.hh\"\n\nusing namespace Kaskade;\n#include \"ht.hh\"\n\n#if SPACEDIM==3\n#include \"cubus.hh\"\n#endif\n\n#if GRIDTYPE==4\n#define DEFAULT_REFINEMENTS 14\n#else\n#if GRIDTYPE==3\n#define DEFAULT_REFINEMENTS 7\n#else\n#if SPACEDIM==2\n#define DEFAULT_REFINEMENTS 5\n#endif\n#if SPACEDIM==3\n#define DEFAULT_REFINEMENTS 3\n#endif\n#endif\n#endif\n\nint main(int argc, char *argv[])\n{\n using namespace boost::fusion;\n\n std::cout << \"Start heat transfer tutorial program (with GridType=\" << CHARGRIDTYPE <<\n \" and SpaceDimension=\" << SPACEDIM << \")\" << std::endl;\n\n boost::timer::cpu_timer totalTimer;\n\n int verbosityOpt = 1;\n bool dump = true; \n std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);\n\n int refinements = getParameter(pt, \"refinements\", DEFAULT_REFINEMENTS),\n order = getParameter(pt, \"order\", 2),\n verbosity = getParameter(pt, \"verbosity\", 1);\n std::cout << \"original mesh shall be refined : \" << refinements << \" times\" << std::endl;\n std::cout << \"discretization order : \" << order << std::endl;\n std::cout << \"output level (verbosity) : \" << verbosity << std::endl;\n\n int direct, onlyLowerTriangle = false;\n \n DirectType directType;\n// IterateType iterateType = IterateType::CG;\n MatrixProperties property = MatrixProperties::SYMMETRIC;\n PrecondType precondType = PrecondType::NONE;\n std::string empty;\n\n std::string s(\"names.type.\");\n s += getParameter(pt, \"solver.type\", empty);\n direct = getParameter(pt, s, 0);\n \n s = \"names.direct.\" + getParameter(pt, \"solver.direct\", empty);\n directType = static_cast<DirectType>(getParameter(pt, s, 0));\n\n// s = \"names.iterate.\" + getParameter(pt, \"solver.iterate\", empty);\n// iterateType = static_cast<IterateType>(getParameter(pt, s, 0));\n s = \"names.preconditioner.\" + getParameter(pt, \"solver.preconditioner\", empty);\n precondType = static_cast<PrecondType>(getParameter(pt, s, 0));\n \n int blocks = getParameter(pt,\"blocks\",40);\n int nthreads = getParameter(pt,\"threads\",4);\n double rowBlockFactor = getParameter(pt,\"rowBlockFactor\",2.0);\n\n property = MatrixProperties::SYMMETRIC;\n\n if ( (directType == DirectType::MUMPS)||(directType == DirectType::PARDISO) || ( (precondType == PrecondType::ICC) && !direct ) )\n {\n onlyLowerTriangle = true;\n std::cout << \n \"Note: direct solver MUMPS/PARADISO or PrecondType::ICC preconditioner ===> onlyLowerTriangle is set to true!\" \n << std::endl;\n }\n\n boost::timer::cpu_timer gridTimer;\n#if SPACEDIM==2\n // two-dimensional space: dim=2\n constexpr int dim=2; \n#if GRIDTYPE==1\n using Grid = Dune::UGGrid<dim>;\n#endif\n // There are alternatives to UGGrid: ALUSimplexGrid (red refinement), ALUConformGrid (bisection)\n // and AlbertaGrid\n#if GRIDTYPE==2\n using Grid = Dune::ALUGrid<dim,dim,Dune::ALUGridElementType::simplex,Dune::ALUGridRefinementType::nonconforming>;\n#endif\n#if GRIDTYPE==3\n using Grid = Dune::ALUGrid<dim,dim,Dune::ALUGridElementType::simplex,Dune::ALUGridRefinementType::conforming>;\n#endif\n#if GRIDTYPE==4\n using Grid = Dune::AlbertaGrid<dim,dim>;\n#endif\n Dune::GridFactory<Grid> factory;\n\n // vertex coordinates v[0], v[1]\n Dune::FieldVector<double,dim> v; \n v[0]=0; v[1]=0; factory.insertVertex(v);\n v[0]=1; v[1]=0; factory.insertVertex(v);\n v[0]=1; v[1]=1; factory.insertVertex(v);\n v[0]=0; v[1]=1; factory.insertVertex(v);\n // triangle defined by 3 vertex indices\n std::vector<unsigned int> vid(3);\n Dune::GeometryType gt(Dune::GeometryType::simplex,2);\n vid[0]=0; vid[1]=1; vid[2]=2; factory.insertElement(gt,vid);\n vid[0]=0; vid[1]=2; vid[2]=3; factory.insertElement(gt,vid);\n std::unique_ptr<Grid> grid( factory.createGrid() ) ;\n // the coarse grid will be refined three times\n grid->globalRefine(refinements);\n // some information on the refined mesh\n std::cout << std::endl << \"Grid: \" << grid->size(0) << \" triangles, \" << std::endl;\n std::cout << \" \" << grid->size(1) << \" edges, \" << std::endl;\n std::cout << \" \" << grid->size(2) << \" points\" << std::endl;\n\n // a gridmanager is constructed \n // as connector between geometric and algebraic information\n GridManager<Grid> gridManager(std::move(grid));\n#else\n // three-dimensional space: dim=3\n // we offer 2 geometries:\n // - very simple: 1 tetrahedron defined by 4 vertices\n // - more complex: 1 cube defined by 48 tetrahedra, provided in cubus.hh\n constexpr int dim=3;\n \n // \n //definition of 1 tetrahedron by 4 vertices\n#if GRIDTYPE==4\n using Grid = Dune::AlbertaGrid<dim,dim>;\n Dune::GridFactory<Grid> factory;\n // vertex coordinates v[0], v[1]\n Dune::FieldVector<double,dim> v; \n v[0]=0; v[1]=0; v[2]=0; factory.insertVertex(v);\n v[0]=1; v[1]=0; v[2]=0; factory.insertVertex(v);\n v[0]=0; v[1]=1; v[2]=0; factory.insertVertex(v);\n v[0]=0; v[1]=0; v[2]=1; factory.insertVertex(v);\n // tetrahedron defined by 4 vertex indices\n std::vector<unsigned int> vid(4);\n Dune::GeometryType gt(Dune::GeometryType::simplex,dim);\n vid[0]=0; vid[1]=1; vid[2]=2; vid[3]=3; factory.insertElement(gt,vid);\n std::unique_ptr<Grid> grid( factory.createGrid() ) ;\n // the coarse grid will be refined three times\n grid->globalRefine(refinements);\n //\n#else \n // definition of a more complex mesh using cubus.hh\n // note: trying to use the following code with AlbertaGrid will lead to a crash\n // during runtime due to a bug in the AlbertaGrid refinement routine\n int heapSize=1024;\n#if GRIDTYPE==1\n using Grid = Dune::UGGrid<dim>;\n#endif\n // There are alternatives to UGGrid: ALUSimplexGrid (red refinement)\n#if GRIDTYPE==2\n using Grid = Dune::ALUGrid<dim,dim,Dune::ALUGridElementType::simplex,Dune::ALUGridRefinementType::nonconforming>;\n#endif\n#if GRIDTYPE==3\n#error ALUCONFORM GridType not supported by DUNE for Dimension=3\n#endif\n std::unique_ptr<Grid> grid( RefineGrid<Grid>(refinements, heapSize) );\n#endif\n\n // some information on the refined mesh\n std::cout << std::endl << \"Grid: \" << grid->size(0) << \" tetrahedra, \" << std::endl;\n std::cout << \" \" << grid->size(1) << \" triangles, \" << std::endl;\n std::cout << \" \" << grid->size(dim-1) << \" edges, \" << std::endl;\n std::cout << \" \" << grid->size(dim) << \" points\" << std::endl;\n // a gridmanager is constructed \n // as connector between geometric and algebraic information\n GridManager<Grid> gridManager(std::move(grid));\n#endif\n std::cout << \"computing time for generation of initial mesh: \" << boost::timer::format(gridTimer.elapsed()) << \"\\n\";\n \n using LeafView = Grid::LeafGridView;\n \n // construction of finite element space for the scalar solution T.\n using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> >;\n // using H1Space = FEFunctionSpace<ContinuousHierarchicMapper<double,LeafView> >;\n using Spaces = boost::fusion::vector<H1Space const*>;\n using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>,VariableId<0> > >;\n using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n using Functional = HeatFunctional<double,VariableSet>;\n using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n constexpr int neq = Functional::TestVars::noOfVariables;\n using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n using LinearSpace = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n // avoid collision of reference to the Kaskade CG with an equal named enum value in the Alberta headers\n using CG = Kaskade::CG<LinearSpace,LinearSpace>;\n \n // construction of finite element space for the scalar solution T.\n H1Space temperatureSpace(gridManager,gridManager.grid().leafGridView(),order);\n \n Spaces spaces(&temperatureSpace);\n \n // construct variable list.\n // VariableDescription<int spaceId, int components, int Id>\n // spaceId: number of associated FEFunctionSpace\n // components: number of components in this variable\n // Id: number of this variable\n \n std::string varNames[1] = { \"u\" };\n \n VariableSet variableSet(spaces,varNames);\n\n // construct variational functional\n \n double kappa = 1.0;\n double q = 1.0;\n Functional F(kappa,q);\n constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n std::cout << std::endl << \"no of variables = \" << nvars << std::endl;\n std::cout << \"no of equations = \" << neq << std::endl;\n size_t dofs = variableSet.degreesOfFreedom(0,nvars);\n std::cout << \"number of degrees of freedom = \" << dofs << std::endl;\n\n //construct Galerkin representation\n Assembler assembler(gridManager,spaces);\n VariableSet::VariableSet u(variableSet);\n VariableSet::VariableSet du(variableSet);\n\n size_t nnz = assembler.nnz(0,neq,0,nvars,onlyLowerTriangle);\n std::cout << \"number of nonzero elements in the stiffness matrix: \" << nnz << std::endl << std::endl;\n \n boost::timer::cpu_timer assembTimer;\n CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<0,neq>::init(spaces));\n solution = 0;\n \n // UG seems to admit concurrent reads while claiming not to be thread safe. In this case we enforce multithreading during assembly.\n gridManager.enforceConcurrentReads(std::is_same<Grid,Dune::UGGrid<dim> >::value);\n assembler.setNSimultaneousBlocks(blocks);\n assembler.setRowBlockFactor(rowBlockFactor);\n assembler.assemble(linearization(F,u),assembler.MATRIX|assembler.RHS|assembler.VALUE,nthreads,verbosity);\n std::cout << \"computing time for assemble: \" << boost::timer::format(assembTimer.elapsed()) << \"\\n\";\n \n CoefficientVectors rhs(assembler.rhs());\n AssembledGalerkinOperator<Assembler,0,neq,0,nvars> A(assembler, onlyLowerTriangle);\n \n // matrix may be used in triplet format, e.g.,\n // MatrixAsTriplet<double> tri = A.get<MatrixAsTriplet<double> >();\n // for (k=0; k< nnz; k++)\n // {\n // printf(\"%3d %3d %e\\n\", tri.ridx[k], tri.cidx[k], tri.data[k]);\n // }\n\n if (direct)\n {\n boost::timer::cpu_timer directTimer;\n directInverseOperator(A,directType,property).applyscaleadd(-1.0,rhs,solution);\n u.data = solution.data;\n std::cout << \"computing time for direct solve: \" << boost::timer::format(directTimer.elapsed()) << \"\\n\";\n }\n else\n {\n boost::timer::cpu_timer iteTimer;\n Dune::InverseOperatorResult res;\n const DefaultDualPairing<LinearSpace,LinearSpace> defaultScalarProduct{};\n int iteSteps = getParameter(pt, \"solver.iteMax\", 2000);\n double iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-10);\n StrakosTichyPTerminationCriterion<double> termination(iteEps,iteSteps);\n int lookAhead;\n switch (precondType)\n {\n case PrecondType::NONE:\n case PrecondType::HB: lookAhead=50; break;\n default: lookAhead=3; break;\n }\n lookAhead = getParameter(pt, \"solver.lookAhead\", lookAhead);\n termination.setLookAhead(lookAhead);\n\n switch (precondType)\n {\n case PrecondType::NONE:\n {\n std::cout << \"selected preconditioner: NONE\" << std::endl;\n TrivialPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > trivial;\n CG cg(A,trivial,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::ADDITIVESCHWARZ:\n {\n std::cout << \"selected preconditioner: ADDITIVESCHWARZ\" << std::endl;\n std::pair<size_t,size_t> idx = temperatureSpace.mapper().globalIndexRange(gridManager.grid().leafIndexSet().geomTypes(dim)[0]);\n AdditiveSchwarzPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > addschwarz(A,idx.first,idx.second,verbosity);\n CG cg(A,addschwarz,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::ILUT:\n {\n std::cout << \"selected preconditioner: ILUT\" << std::endl;\n// std::cout << \"Note that this preconditioner combined with the BICGSTAB solver\" << std::endl;\n std::cout << \"needs matrix.property = GENERAL\" << std::endl;\n int lfil = getParameter(pt, \"solver.ILUT.lfil\", 140);\n double dropTol = getParameter(pt, \"solver.ILUT.dropTol\", 0.01);\n ILUTPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > ilut(A,lfil,dropTol,verbosity);\n CG cg(A,ilut,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n// Dune::BiCGSTABSolver<LinearSpace> cg(A,ilut,iteEps,iteSteps,verbosity);\n// cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::ILUK:\n {\n std::cout << \"selected preconditioner: ILUK\" << std::endl;\n// std::cout << \"Note that this preconditioner combined with the BICGSTAB solver\" << std::endl;\n std::cout << \"needs matrix.property = GENERAL\" << std::endl;\n int fill_lev = getParameter(pt, \"solver.ILUK.fill_lev\", 3);\n ILUKPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > iluk(A,fill_lev,verbosity);\n CG cg(A,iluk,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n// Dune::BiCGSTABSolver<LinearSpace> cg(A,iluk,iteEps,iteSteps,verbosity);\n// cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::ARMS:\n {\n int lfil = getParameter(pt, \"solver.ARMS.lfil\", 140);\n int lev_reord = getParameter(pt, \"solver.ARMS.lev_reord\", 1);\n double dropTol = getParameter(pt, \"solver.ARMS.dropTol\", 0.01);\n double tolind = getParameter(pt, \"solver.ARMS.tolind\", 0.2);\n ARMSPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > iluk(A,lfil,dropTol,lev_reord,tolind,verbosity);\n CG cg(A,iluk,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::ICC:\n {\n std::cout << \"selected preconditioner: ICC\" << std::endl;\n if (property != MatrixProperties::SYMMETRIC) \n {\n std::cout << \"PrecondType::ICC preconditioner of TAUCS lib has to be used with matrix.property==MatrixProperties::SYMMETRIC\\n\";\n std::cout << \"i.e., call the executable with option --solver.property MatrixProperties::SYMMETRIC\\n\\n\";\n }\n double dropTol = getParameter(pt, \"solver.ICC.dropTol\", 0.01);;\n ICCPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > icc(A,dropTol);\n CG cg(A,icc,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::ICC0:\n {\n std::cout << \"selected preconditioner: ICC0\" << std::endl;\n ICC_0Preconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > icc0(A);\n CG cg(A,icc0,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::HB:\n {\n std::cout << \"selected preconditioner: HB\" << std::endl;\n HierarchicalBasisPreconditioner<Grid,AssembledGalerkinOperator<Assembler,0,neq,0,nvars>::range_type, AssembledGalerkinOperator<Assembler,0,neq,0,nvars>::range_type > hb(gridManager.grid());\n CG cg(A,hb,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::BOOMERAMG:\n {\n int steps = getParameter(pt, \"solver.BOOMERAMG.steps\", iteSteps);\n int coarsentype = getParameter(pt, \"solver.BOOMERAMG.coarsentype\", 21);\n int interpoltype = getParameter(pt, \"solver.BOOMERAMG.interpoltype\", 0);\n int cycleType = getParameter(pt, \"solver.BOOMERAMG.cycleType\", 1);\n int relaxType = getParameter(pt, \"solver.BOOMERAMG.relaxType\", 3);\n int variant = getParameter(pt, \"solver.BOOMERAMG.variant\", 0);\n int overlap = getParameter(pt, \"solver.BOOMERAMG.overlap\", 1);\n double tol = getParameter(pt, \"solver.BOOMERAMG.tol\", iteEps);\n double strongThreshold = getParameter(pt, \"solver.BOOMERAMG.strongThreshold\", (dim==2)?0.25:0.6);\n BoomerAMG<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> >\n boomerAMGPrecon(A,steps,coarsentype,interpoltype,tol,cycleType,relaxType,\n strongThreshold,variant,overlap,1,verbosity);\n CG cg(A,boomerAMGPrecon,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n// Dune::LoopSolver<LinearSpace> cg(A,boomerAMGPrecon,iteEps,iteSteps,verbosity);\n// cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::EUCLID:\n {\n std::cout << \"selected preconditioner: EUCLID\" << std::endl;\n int level = getParameter(pt, \"solver.EUCLID.level\",1);\n double droptol = getParameter(pt, \"solver.EUCLID.droptol\",0.01);\n int printlevel = 0;\n if (verbosity>2) printlevel=verbosity-2;\n printlevel = getParameter(pt,\"solver.EUCLID.printlevel\",printlevel);\n int bj = getParameter(pt, \"solver.EUCLID.bj\",0);\n Euclid<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > EuclidPrecon(A,level,droptol,printlevel,bj,verbosity);\n CG cg(A,EuclidPrecon,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n case PrecondType::JACOBI:\n default:\n {\n std::cout << \"selected preconditioner: JACOBI\" << std::endl;\n JacobiPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > jacobi(A,1.0);\n CG cg(A,jacobi,defaultScalarProduct,termination,verbosity);\n cg.apply(solution,rhs,res);\n }\n break;\n }\n solution *= -1.0;\n u.data = solution.data;\n \n std::cout << \"iterative solve eps= \" << iteEps << \": \" \n << (res.converged?\"converged\":\"failed\") << \" after \"\n << res.iterations << \" steps, rate=\"\n << res.conv_rate << \", computing time=\" << (double)(iteTimer.elapsed().user)/1e9 << \"s\\n\";\n }\n \n \n \n // compute L2 norm of the solution\n boost::timer::cpu_timer outputTimer;\n L2Norm l2Norm;\n std::cout << \"L2norm(solution) = \" << l2Norm(boost::fusion::at_c<0>(u.data)) << std::endl;\n \n \n\n // output of solution in VTK format for visualization,\n // the data are written as ascii stream into file temperature.vtu,\n // possible is also binary\n writeVTKFile(u,\"temperature\",IoOptions().setOrder(order).setPrecision(7));\n\n std::cout << \"graphical output finished, data in VTK format is written into file temperature.vtu \\n\";\n \n // output of solution for Amira visualization,\n // the data are written in binary format into file temperature.am,\n // possible is also ascii\n // IoOptions options;\n // options.outputType = IoOptions::ascii;\n // LeafView leafGridView = gridManager.grid().leafGridView();\n // writeAMIRAFile(leafGridView,variableSet,u,\"temperature\",options);\n\n std::cout << \"computing time for output: \" << boost::timer::format(outputTimer.elapsed()) << \"\\n\";\n\n std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n std::cout << \"End heat transfer tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "8ca051c18ac60345374192e966d512bc332859c9", "size": 21825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/stationary_heattransfer/ht_advanced.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/stationary_heattransfer/ht_advanced.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/stationary_heattransfer/ht_advanced.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 41.4923954373, "max_line_length": 197, "alphanum_fraction": 0.6629553265, "num_tokens": 6201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.10521053950871516, "lm_q1q2_score": 0.05260526975435758}}
{"text": "/*!\n * @file right_hand_side.hpp\n * @brief Contains implementation of right-hand side.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_RIGHT_HAND_SIDE_HPP_\n#define INCLUDE_RIGHT_HAND_SIDE_HPP_\n\n// Deal.ii\n#include <deal.II/base/function.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n\n// My Headers\n#include \"coefficients.h\"\n\nnamespace Coefficients\n{\nusing namespace dealii;\n\n/*!\n * @class RightHandSide\n * @brief Class implements scalar right-hand side function.\n *\n * The right-hand side represents some external forcing parameter.\n */\ntemplate <int dim>\nclass RightHandSide : public Function<dim>\n{\npublic:\n\tRightHandSide() : Function<dim>() {}\n\n\tvirtual double value(const Point<dim> &p,\n\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\tvirtual void value_list(const std::vector<Point<dim>> &points,\n\t\t\t\t\t\t\tstd::vector<double> &values,\n\t\t\t\t\t\t\tconst unsigned int component = 0) const override;\n};\n\n\ntemplate <int dim>\ndouble\nRightHandSide<dim>::value(const Point<dim>& /*p*/,\n\t\t\t\t\t\t\t const unsigned int /*component*/) const\n{\n\tdouble return_value = 2.0;\n\n\treturn return_value;\n}\n\ntemplate <int dim>\nvoid\nRightHandSide<dim>::value_list(const std::vector<Point<dim>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double> &values,\n\t\t\t\t\t\t\t\tconst unsigned int /*component = 0*/) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\n\tfor ( unsigned int p=0; p<points.size(); ++p)\n\t{\n\t\tvalues[p] = 2.0;\n\t} // end ++p\n}\n\n} // end namespace Coefficients\n\n#endif /* INCLUDE_RIGHT_HAND_SIDE_HPP_ */\n", "meta": {"hexsha": "04f6622a489a4b17324b1415cc47532f18dfd4b1", "size": 1559, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/right_hand_side.hpp", "max_stars_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_stars_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/right_hand_side.hpp", "max_issues_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_issues_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/right_hand_side.hpp", "max_forks_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_forks_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T15:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T15:42:43.000Z", "avg_line_length": 21.3561643836, "max_line_length": 69, "alphanum_fraction": 0.6946760744, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.11124120650754304, "lm_q1q2_score": 0.052581880235436966}}
{"text": "/**\n * @file laxwendroffscheme_main.cc\n * @brief NPDE homework \"LaxWendroffScheme\" code\n * @author Oliver Rietmann\n * @date 29.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <fstream>\n#include <iostream>\n\n#include \"laxwendroffscheme.h\"\n\nusing namespace LaxWendroffScheme;\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n Eigen::VectorXi M(6);\n M << 20, 40, 80, 160, 320, 640;\n\n Eigen::VectorXd error_LaxWendroffRP = numexpLaxWendroffRP(M);\n Eigen::VectorXd error_LaxWendroffSmoothU0 = numexpLaxWendroffSmoothU0(M);\n Eigen::VectorXd error_GodunovSmoothU0 = numexpGodunovSmoothU0(M);\n\n std::ofstream file;\n file.open(\"convergence.csv\");\n file << M.transpose().format(CSVFormat) << std::endl;\n file << error_LaxWendroffRP.transpose().format(CSVFormat) << std::endl;\n file << error_LaxWendroffSmoothU0.transpose().format(CSVFormat) << std::endl;\n file << error_GodunovSmoothU0.transpose().format(CSVFormat) << std::endl;\n file.close();\n std::cout << \"Generated \" CURRENT_BINARY_DIR \"/convergence.csv\" << std::endl;\n\n // To plot from convergence.csv uncomment this:\n // std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n // \"/convergence.csv \" CURRENT_BINARY_DIR \"/convergence.eps\");\n\n return 0;\n}\n", "meta": {"hexsha": "fffd78b9b74de4e598f56016a1069deed192ca2c", "size": 1370, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LaxWendroffScheme/templates/laxwendroffscheme_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/LaxWendroffScheme/templates/laxwendroffscheme_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/LaxWendroffScheme/templates/laxwendroffscheme_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 31.8604651163, "max_line_length": 79, "alphanum_fraction": 0.702919708, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.152032235859071, "lm_q1q2_score": 0.051931549081896934}}
{"text": "//C++ implementation code of finding the product of large numbers using Boost Lib.\n//The Boost.Multiprecision library can be used for computations requiring precision exceeding that of standard built-in types such as float, double and long double.\n//For extended-precision calculations, Boost.Multiprecision supplies a template data type called cpp_dec_float.\n\n#include <boost/multiprecision/cpp_int.hpp> \nusing namespace boost::multiprecision; //here we are using boost as namespace that includes boost libarary\nusing namespace std; \n \n//the below line is the function where the product of two numbers will take place. \nint128_t boost_product(long long A, long long B) \n{ \n int128_t ans = (int128_t) A * B; \n return ans; \n} \n \n//in main function we tooked two long data type numbers and then called our boost_product() function.\nint main() \n{ \n long long first = 98745636214564698; \n long long second=7459874565236544789; \n cout << \"Product of \"<< first << \" * \"\n << second << \" = \\n\"\n << boost_product(first,second) ; \n return 0; \n} \n", "meta": {"hexsha": "f9319a76ee31d29597b3e6a24d7332b52a20b7da", "size": 1071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++boost/LarNumBoost.cpp", "max_stars_repo_name": "soumilk/Inheritance-", "max_stars_repo_head_hexsha": "8aa19aef0f4d739db71124af1616ec8f6ddd8375", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-07-04T19:35:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T15:10:19.000Z", "max_issues_repo_path": "C++boost/LarNumBoost.cpp", "max_issues_repo_name": "soumilk/Inheritance-", "max_issues_repo_head_hexsha": "8aa19aef0f4d739db71124af1616ec8f6ddd8375", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-07-16T17:15:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T09:07:12.000Z", "max_forks_repo_path": "C++boost/LarNumBoost.cpp", "max_forks_repo_name": "soumilk/Inheritance-", "max_forks_repo_head_hexsha": "8aa19aef0f4d739db71124af1616ec8f6ddd8375", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2019-08-16T00:52:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T15:03:32.000Z", "avg_line_length": 41.1923076923, "max_line_length": 164, "alphanum_fraction": 0.7264239029, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.10669058471438035, "lm_q1q2_score": 0.05043087650546012}}