Note: this is documentation for an old release. View the latest documentation at docs.fenicsproject.org/dolfinx/v0.9.0/cpp/doxygen/df/d34/ADIOS2Writers_8h_source.html
DOLFINx 0.7.3
DOLFINx C++ interface
Loading...
Searching...
No Matches
ADIOS2Writers.h
Go to the documentation of this file.
1// Copyright (C) 2021-2023 Jørgen S. Dokken and Garth N. Wells
2//
3// This file is part of DOLFINX (https://www.fenicsproject.org)
4//
5// SPDX-License-Identifier: LGPL-3.0-or-later
6
7#pragma once
8
9#ifdef HAS_ADIOS2
10
11#include "vtk_utils.h"
12#include <adios2.h>
13#include <basix/mdspan.hpp>
14#include <cassert>
15#include <complex>
16#include <concepts>
17#include <dolfinx/common/IndexMap.h>
18#include <dolfinx/fem/DofMap.h>
19#include <dolfinx/fem/FiniteElement.h>
20#include <dolfinx/fem/Function.h>
21#include <dolfinx/mesh/Geometry.h>
22#include <dolfinx/mesh/Mesh.h>
23#include <filesystem>
24#include <memory>
25#include <mpi.h>
26#include <string>
27#include <type_traits>
28#include <variant>
29#include <vector>
30
33
34namespace dolfinx::fem
35{
36template <dolfinx::scalar T, std::floating_point U>
37class Function;
38}
39
40namespace dolfinx::io
41{
42namespace adios2_writer
43{
45template <std::floating_point T>
46using U = std::vector<std::variant<
47 std::shared_ptr<const fem::Function<float, T>>,
48 std::shared_ptr<const fem::Function<double, T>>,
49 std::shared_ptr<const fem::Function<std::complex<float>, T>>,
50 std::shared_ptr<const fem::Function<std::complex<double>, T>>>>;
51} // namespace adios2_writer
52
55{
56protected:
63 ADIOS2Writer(MPI_Comm comm, const std::filesystem::path& filename,
64 std::string tag, std::string engine);
65
67 ADIOS2Writer(ADIOS2Writer&& writer) = default;
68
70 ADIOS2Writer(const ADIOS2Writer&) = delete;
71
74
76 ADIOS2Writer& operator=(ADIOS2Writer&& writer) = default;
77
78 // Copy assignment
79 ADIOS2Writer& operator=(const ADIOS2Writer&) = delete;
80
81public:
83 void close();
84
85protected:
86 std::unique_ptr<adios2::ADIOS> _adios;
87 std::unique_ptr<adios2::IO> _io;
88 std::unique_ptr<adios2::Engine> _engine;
89};
90
92namespace impl_adios2
93{
96constexpr std::array field_ext = {"_real", "_imag"};
97
100template <class T>
101adios2::Attribute<T> define_attribute(adios2::IO& io, std::string name,
102 const T& value, std::string var_name = "",
103 std::string separator = "/")
104{
105 if (adios2::Attribute<T> attr = io.InquireAttribute<T>(name); attr)
106 return attr;
107 else
108 return io.DefineAttribute<T>(name, value, var_name, separator);
109}
110
113template <class T>
114adios2::Variable<T> define_variable(adios2::IO& io, std::string name,
115 const adios2::Dims& shape = adios2::Dims(),
116 const adios2::Dims& start = adios2::Dims(),
117 const adios2::Dims& count = adios2::Dims())
118{
119 if (adios2::Variable v = io.InquireVariable<T>(name); v)
120 {
121 if (v.Count() != count and v.ShapeID() == adios2::ShapeID::LocalArray)
122 v.SetSelection({start, count});
123 return v;
124 }
125 else
126 return io.DefineVariable<T>(name, shape, start, count);
127}
128
130template <std::floating_point T>
131std::shared_ptr<const mesh::Mesh<T>>
132extract_common_mesh(const typename adios2_writer::U<T>& u)
133{
134 // Extract mesh from first function
135 assert(!u.empty());
136 auto mesh = std::visit([](auto&& u) { return u->function_space()->mesh(); },
137 u.front());
138 assert(mesh);
139
140 // Check that all functions share the same mesh
141 for (auto& v : u)
142 {
143 std::visit(
144 [&mesh](auto&& u)
145 {
146 if (mesh != u->function_space()->mesh())
147 {
148 throw std::runtime_error(
149 "ADIOS2Writer only supports functions sharing the same mesh");
150 }
151 },
152 v);
153 }
154
155 return mesh;
156}
157
158} // namespace impl_adios2
159
161namespace impl_fides
162{
167void initialize_mesh_attributes(adios2::IO& io, mesh::CellType type);
168
173template <std::floating_point T>
175 const typename adios2_writer::U<T>& u)
176{
177 // Array of function (name, cell association types) for each function
178 // added to the file
179 std::vector<std::array<std::string, 2>> u_data;
180 for (auto& v : u)
181 {
182 std::visit(
183 [&u_data](auto&& u)
184 {
185 using U = std::decay_t<decltype(u)>;
186 using X = typename U::element_type;
187 if constexpr (std::is_floating_point_v<typename X::value_type>)
188 u_data.push_back({u->name, "points"});
189 else
190 {
191 u_data.push_back({u->name + impl_adios2::field_ext[0], "points"});
192 u_data.push_back({u->name + impl_adios2::field_ext[1], "points"});
193 }
194 },
195 v);
196 }
197
198 // Write field associations to file
199 if (adios2::Attribute<std::string> assc
200 = io.InquireAttribute<std::string>("Fides_Variable_Associations");
201 !assc)
202 {
203 std::vector<std::string> u_type;
204 std::transform(u_data.cbegin(), u_data.cend(), std::back_inserter(u_type),
205 [](auto& f) { return f[1]; });
206 io.DefineAttribute<std::string>("Fides_Variable_Associations",
207 u_type.data(), u_type.size());
208 }
209
210 // Write field pointers to file
211 if (adios2::Attribute<std::string> fields
212 = io.InquireAttribute<std::string>("Fides_Variable_List");
213 !fields)
214 {
215 std::vector<std::string> names;
216 std::transform(u_data.cbegin(), u_data.cend(), std::back_inserter(names),
217 [](auto& f) { return f[0]; });
218 io.DefineAttribute<std::string>("Fides_Variable_List", names.data(),
219 names.size());
220 }
221}
222
225template <typename T, std::floating_point U>
227{
228 auto V = u.function_space();
229 assert(V);
230 auto dofmap = V->dofmap();
231 assert(dofmap);
232 auto mesh = V->mesh();
233 assert(mesh);
234 const mesh::Geometry<U>& geometry = mesh->geometry();
235 auto topology = mesh->topology();
236 assert(topology);
237
238 // The Function and the mesh must have identical element_dof_layouts
239 // (up to the block size)
240 assert(dofmap->element_dof_layout()
241 == geometry.cmaps()[0].create_dof_layout());
242
243 int tdim = topology->dim();
244 auto cell_map = topology->index_map(tdim);
245 assert(cell_map);
246 std::int32_t num_cells = cell_map->size_local() + cell_map->num_ghosts();
247
248 auto vertex_map = topology->index_map(0);
249 assert(vertex_map);
250 std::uint32_t num_vertices
251 = vertex_map->size_local() + vertex_map->num_ghosts();
252
253 int rank = V->element()->value_shape().size();
254 std::uint32_t num_components = std::pow(3, rank);
255
256 // Get dof array and pack into array (padded where appropriate)
257 auto dofmap_x = geometry.dofmap();
258 const int bs = dofmap->bs();
259 std::span<const T> u_data = u.x()->array();
260 std::vector<T> data(num_vertices * num_components, 0);
261 for (std::int32_t c = 0; c < num_cells; ++c)
262 {
263 auto dofs = dofmap->cell_dofs(c);
264 auto dofs_x
265 = MDSPAN_IMPL_STANDARD_NAMESPACE::MDSPAN_IMPL_PROPOSED_NAMESPACE::
266 submdspan(dofmap_x, c, MDSPAN_IMPL_STANDARD_NAMESPACE::full_extent);
267 assert(dofs.size() == dofs_x.size());
268 for (std::size_t i = 0; i < dofs.size(); ++i)
269 for (int j = 0; j < bs; ++j)
270 data[num_components * dofs_x[i] + j] = u_data[bs * dofs[i] + j];
271 }
272
273 return data;
274}
275
282template <typename T, std::floating_point U>
283void write_data(adios2::IO& io, adios2::Engine& engine,
284 const fem::Function<T, U>& u)
285{
286 // FIXME: There is an implicit assumptions that u and the mesh have
287 // the same ElementDoflayout
288 auto V = u.function_space();
289 assert(V);
290 auto dofmap = V->dofmap();
291 assert(dofmap);
292 auto mesh = V->mesh();
293 assert(mesh);
294 const int gdim = mesh->geometry().dim();
295
296 // Vectors and tensor need padding in gdim < 3
297 int rank = V->element()->value_shape().size();
298 bool need_padding = rank > 0 and gdim != 3 ? true : false;
299
300 // Get vertex data. If the mesh and function dofmaps are the same we
301 // can work directly with the dof array.
302 std::span<const T> data;
303 std::vector<T> _data;
304 auto eq_check = [](auto x, auto y) -> bool
305 {
306 return x.extents() == y.extents()
307 and std::equal(x.data_handle(), x.data_handle() + x.size(),
308 y.data_handle());
309 };
310
311 if (!need_padding and eq_check(mesh->geometry().dofmap(), dofmap->map()))
312 data = u.x()->array();
313 else
314 {
315 _data = impl_fides::pack_function_data(u);
316 data = std::span<const T>(_data);
317 }
318
319 auto vertex_map = mesh->topology()->index_map(0);
320 assert(vertex_map);
321 std::uint32_t num_vertices
322 = vertex_map->size_local() + vertex_map->num_ghosts();
323
324 // Write each real and imaginary part of the function
325 std::uint32_t num_components = std::pow(3, rank);
326 assert(data.size() % num_components == 0);
327 if constexpr (std::is_scalar_v<T>)
328 {
329 // ---- Real
330 adios2::Variable local_output = impl_adios2::define_variable<T>(
331 io, u.name, {}, {}, {num_vertices, num_components});
332
333 // To reuse out_data, we use sync mode here
334 engine.Put(local_output, data.data());
335 engine.PerformPuts();
336 }
337 else
338 {
339 // ---- Complex
340 using X = typename T::value_type;
341
342 std::vector<X> data_real(data.size()), data_imag(data.size());
343
344 adios2::Variable local_output_r = impl_adios2::define_variable<X>(
345 io, u.name + impl_adios2::field_ext[0], {}, {},
346 {num_vertices, num_components});
347 std::transform(data.begin(), data.end(), data_real.begin(),
348 [](auto x) -> X { return std::real(x); });
349 engine.Put(local_output_r, data_real.data());
350
351 adios2::Variable local_output_c = impl_adios2::define_variable<X>(
352 io, u.name + impl_adios2::field_ext[1], {}, {},
353 {num_vertices, num_components});
354 std::transform(data.begin(), data.end(), data_imag.begin(),
355 [](auto x) -> X { return std::imag(x); });
356 engine.Put(local_output_c, data_imag.data());
357 engine.PerformPuts();
358 }
359}
360
365template <std::floating_point T>
366void write_mesh(adios2::IO& io, adios2::Engine& engine,
367 const mesh::Mesh<T>& mesh)
368{
369 const mesh::Geometry<T>& geometry = mesh.geometry();
370 auto topology = mesh.topology();
371 assert(topology);
372
373 // "Put" geometry data
374 auto x_map = geometry.index_map();
375 std::uint32_t num_vertices = x_map->size_local() + x_map->num_ghosts();
376 adios2::Variable local_geometry = impl_adios2::define_variable<T>(
377 io, "points", {}, {}, {num_vertices, 3});
378 engine.Put(local_geometry, geometry.x().data());
379
380 // TODO: The DOLFINx and VTK topology are the same for some cell types
381 // - no need to repack via extract_vtk_connectivity in these cases
382
383 // Get topological dimension, number of cells and number of 'nodes' per
384 // cell, and compute 'VTK' connectivity
385 int tdim = topology->dim();
386 std::int32_t num_cells = topology->index_map(tdim)->size_local();
387 int num_nodes = geometry.cmaps()[0].dim();
388 auto [cells, shape] = io::extract_vtk_connectivity(mesh.geometry().dofmap(),
389 topology->cell_types()[0]);
390
391 // "Put" topology data in the result in the ADIOS2 file
392 adios2::Variable local_topology = impl_adios2::define_variable<std::int64_t>(
393 io, "connectivity", {}, {}, {std::size_t(num_cells * num_nodes)});
394 engine.Put(local_topology, cells.data());
395 engine.PerformPuts();
396}
397
398} // namespace impl_fides
399
401enum class FidesMeshPolicy
402{
403 update,
404 reuse
406};
407
411template <std::floating_point T>
412class FidesWriter : public ADIOS2Writer
413{
414public:
423 FidesWriter(MPI_Comm comm, const std::filesystem::path& filename,
424 std::shared_ptr<const mesh::Mesh<T>> mesh,
425 std::string engine = "BPFile")
426 : ADIOS2Writer(comm, filename, "Fides mesh writer", engine),
427 _mesh_reuse_policy(FidesMeshPolicy::update), _mesh(mesh)
428 {
429 assert(_io);
430 assert(mesh);
431 auto topology = mesh->topology();
432 assert(topology);
433 mesh::CellType type = topology->cell_types()[0];
434 if (mesh->geometry().cmaps()[0].dim() != mesh::cell_num_entities(type, 0))
435 throw std::runtime_error("Fides only supports lowest-order meshes.");
436 impl_fides::initialize_mesh_attributes(*_io, type);
437 }
438
450 FidesWriter(MPI_Comm comm, const std::filesystem::path& filename,
451 const typename adios2_writer::U<T>& u, std::string engine,
452 const FidesMeshPolicy mesh_policy = FidesMeshPolicy::update)
453 : ADIOS2Writer(comm, filename, "Fides function writer", engine),
454 _mesh_reuse_policy(mesh_policy),
455 _mesh(impl_adios2::extract_common_mesh<T>(u)), _u(u)
456 {
457 if (u.empty())
458 throw std::runtime_error("FidesWriter fem::Function list is empty");
459
460 // Extract Mesh from first function
461 auto mesh = std::visit([](auto& u) { return u->function_space()->mesh(); },
462 u.front());
463 assert(mesh);
464
465 // Extract element from first function
466 auto element0 = std::visit([](auto& e)
467 { return e->function_space()->element().get(); },
468 u.front());
469 assert(element0);
470
471 // Check if function is mixed
472 if (element0->is_mixed())
473 {
474 throw std::runtime_error(
475 "Mixed functions are not supported by FidesWriter");
476 }
477
478 // FIXME: is the below check adequate for detecting a
479 // Lagrange element? Check that element is Lagrange
480 if (!element0->interpolation_ident())
481 {
482 throw std::runtime_error("Only Lagrange functions are supported. "
483 "Interpolate Functions before output.");
484 }
485
486 // Check if function is DG 0
487 if (element0->space_dimension() / element0->block_size() == 1)
488 {
489 throw std::runtime_error(
490 "Piecewise constants are not (yet) supported by FidesWriter");
491 }
492
493 // Check that all functions are first order Lagrange
494 auto cell_types = mesh->topology()->cell_types();
495 if (cell_types.size() > 1)
496 throw std::runtime_error("Multiple cell types in IO.");
497 int num_vertices_per_cell = mesh::cell_num_entities(cell_types.back(), 0);
498 for (auto& v : _u)
499 {
500 std::visit(
501 [num_vertices_per_cell, element0](auto&& u)
502 {
503 auto element = u->function_space()->element();
504 assert(element);
505 if (*element != *element0)
506 {
507 throw std::runtime_error("All functions in FidesWriter must have "
508 "the same element type");
509 }
510 auto dof_layout
511 = u->function_space()->dofmap()->element_dof_layout();
512 int num_vertex_dofs = dof_layout.num_entity_dofs(0);
513 int num_dofs = element->space_dimension() / element->block_size();
514 if (num_dofs != num_vertices_per_cell or num_vertex_dofs != 1)
515 {
516 throw std::runtime_error("Only first order Lagrange spaces are "
517 "supported by FidesWriter");
518 }
519 },
520 v);
521 }
522
523 auto topology = mesh->topology();
524 assert(topology);
525 mesh::CellType type = topology->cell_types()[0];
526 if (mesh->geometry().cmaps()[0].dim() != mesh::cell_num_entities(type, 0))
527 throw std::runtime_error("Fides only supports lowest-order meshes.");
528 impl_fides::initialize_mesh_attributes(*_io, type);
529 impl_fides::initialize_function_attributes<T>(*_io, u);
530 }
531
542 FidesWriter(MPI_Comm comm, const std::filesystem::path& filename,
543 const typename adios2_writer::U<T>& u,
544 const FidesMeshPolicy mesh_policy = FidesMeshPolicy::update)
545 : FidesWriter(comm, filename, u, "BPFile", mesh_policy)
546 {
547 }
548
549 // Copy constructor
550 FidesWriter(const FidesWriter&) = delete;
551
553 FidesWriter(FidesWriter&& file) = default;
554
556 ~FidesWriter() = default;
557
559 FidesWriter& operator=(FidesWriter&&) = default;
560
561 // Copy assignment
562 FidesWriter& operator=(const FidesWriter&) = delete;
563
566 void write(double t)
567 {
568 assert(_io);
569 assert(_engine);
570 _engine->BeginStep();
571 adios2::Variable var_step
572 = impl_adios2::define_variable<double>(*_io, "step");
573 _engine->template Put<double>(var_step, t);
574 if (auto v = _io->template InquireVariable<std::int64_t>("connectivity");
575 !v or _mesh_reuse_policy == FidesMeshPolicy::update)
576 {
577 impl_fides::write_mesh(*_io, *_engine, *_mesh);
578 }
579
580 for (auto& v : _u)
581 {
582 std::visit(
583 [this](auto&& u) { impl_fides::write_data(*_io, *_engine, *u); }, v);
584 }
585
586 _engine->EndStep();
587 }
588
589private:
590 // Control whether the mesh is written to file once or at every time
591 // step
592 FidesMeshPolicy _mesh_reuse_policy;
593
594 std::shared_ptr<const mesh::Mesh<T>> _mesh;
595 adios2_writer::U<T> _u;
596};
597
599namespace impl_vtx
600{
603std::stringstream create_vtk_schema(const std::vector<std::string>& point_data,
604 const std::vector<std::string>& cell_data);
605
607template <std::floating_point T>
608std::vector<std::string>
609extract_function_names(const typename adios2_writer::U<T>& u)
610{
611 std::vector<std::string> names;
612 for (auto& v : u)
613 {
614 std::visit(
615 [&names](auto&& u)
616 {
617 using U = std::decay_t<decltype(u)>;
618 using X = typename U::element_type;
619 if constexpr (std::is_floating_point_v<typename X::value_type>)
620 names.push_back(u->name);
621 else
622 {
623 names.push_back(u->name + impl_adios2::field_ext[0]);
624 names.push_back(u->name + impl_adios2::field_ext[1]);
625 }
626 },
627 v);
628 }
629
630 return names;
631}
632
642template <typename T, std::floating_point X>
643void vtx_write_data(adios2::IO& io, adios2::Engine& engine,
644 const fem::Function<T, X>& u)
645{
646 // Get function data array and information about layout
647 assert(u.x());
648 std::span<const T> u_vector = u.x()->array();
649 int rank = u.function_space()->element()->value_shape().size();
650 std::uint32_t num_comp = std::pow(3, rank);
651 std::shared_ptr<const fem::DofMap> dofmap = u.function_space()->dofmap();
652 assert(dofmap);
653 std::shared_ptr<const common::IndexMap> index_map = dofmap->index_map;
654 assert(index_map);
655 int index_map_bs = dofmap->index_map_bs();
656 int dofmap_bs = dofmap->bs();
657 std::uint32_t num_dofs = index_map_bs
658 * (index_map->size_local() + index_map->num_ghosts())
659 / dofmap_bs;
660 if constexpr (std::is_scalar_v<T>)
661 {
662 // ---- Real
663 std::vector<T> data(num_dofs * num_comp, 0);
664 for (std::size_t i = 0; i < num_dofs; ++i)
665 for (int j = 0; j < index_map_bs; ++j)
666 data[i * num_comp + j] = u_vector[i * index_map_bs + j];
667
668 adios2::Variable output = impl_adios2::define_variable<T>(
669 io, u.name, {}, {}, {num_dofs, num_comp});
670 engine.Put(output, data.data(), adios2::Mode::Sync);
671 }
672 else
673 {
674 // ---- Complex
675 using U = typename T::value_type;
676
677 std::vector<U> data(num_dofs * num_comp, 0);
678 for (std::size_t i = 0; i < num_dofs; ++i)
679 for (int j = 0; j < index_map_bs; ++j)
680 data[i * num_comp + j] = std::real(u_vector[i * index_map_bs + j]);
681
682 adios2::Variable output_real = impl_adios2::define_variable<U>(
683 io, u.name + impl_adios2::field_ext[0], {}, {}, {num_dofs, num_comp});
684 engine.Put(output_real, data.data(), adios2::Mode::Sync);
685
686 std::fill(data.begin(), data.end(), 0);
687 for (std::size_t i = 0; i < num_dofs; ++i)
688 for (int j = 0; j < index_map_bs; ++j)
689 data[i * num_comp + j] = std::imag(u_vector[i * index_map_bs + j]);
690 adios2::Variable output_imag = impl_adios2::define_variable<U>(
691 io, u.name + impl_adios2::field_ext[1], {}, {}, {num_dofs, num_comp});
692 engine.Put(output_imag, data.data(), adios2::Mode::Sync);
693 }
694}
695
700template <std::floating_point T>
701void vtx_write_mesh(adios2::IO& io, adios2::Engine& engine,
702 const mesh::Mesh<T>& mesh)
703{
704 const mesh::Geometry<T>& geometry = mesh.geometry();
705 auto topology = mesh.topology();
706 assert(topology);
707
708 // "Put" geometry
709 std::shared_ptr<const common::IndexMap> x_map = geometry.index_map();
710 std::uint32_t num_vertices = x_map->size_local() + x_map->num_ghosts();
711 adios2::Variable local_geometry = impl_adios2::define_variable<T>(
712 io, "geometry", {}, {}, {num_vertices, 3});
713 engine.Put(local_geometry, geometry.x().data());
714
715 // Put number of nodes. The mesh data is written with local indices,
716 // therefore we need the ghost vertices.
717 adios2::Variable vertices = impl_adios2::define_variable<std::uint32_t>(
718 io, "NumberOfNodes", {adios2::LocalValueDim});
719 engine.Put<std::uint32_t>(vertices, num_vertices);
720
721 auto [vtkcells, shape] = io::extract_vtk_connectivity(
722 geometry.dofmap(), topology->cell_types()[0]);
723
724 // Add cell metadata
725 int tdim = topology->dim();
726 adios2::Variable cell_var = impl_adios2::define_variable<std::uint32_t>(
727 io, "NumberOfCells", {adios2::LocalValueDim});
728 engine.Put<std::uint32_t>(cell_var, shape[0]);
729 adios2::Variable celltype_var
730 = impl_adios2::define_variable<std::uint32_t>(io, "types");
731 engine.Put<std::uint32_t>(
732 celltype_var, cells::get_vtk_cell_type(topology->cell_types()[0], tdim));
733
734 // Pack mesh 'nodes'. Output is written as [N0, v0_0,...., v0_N0, N1,
735 // v1_0,...., v1_N1,....], where N is the number of cell nodes and v0,
736 // etc, is the node index
737 std::vector<std::int64_t> cells(shape[0] * (shape[1] + 1), shape[1]);
738 for (std::size_t c = 0; c < shape[0]; ++c)
739 {
740 std::span vtkcell(vtkcells.data() + c * shape[1], shape[1]);
741 std::span cell(cells.data() + c * (shape[1] + 1), shape[1] + 1);
742 std::copy(vtkcell.begin(), vtkcell.end(), std::next(cell.begin()));
743 }
744
745 // Put topology (nodes)
746 adios2::Variable local_topology = impl_adios2::define_variable<std::int64_t>(
747 io, "connectivity", {}, {}, {shape[0], shape[1] + 1});
748 engine.Put(local_topology, cells.data());
749
750 // Vertex global ids and ghost markers
751 adios2::Variable orig_id = impl_adios2::define_variable<std::int64_t>(
752 io, "vtkOriginalPointIds", {}, {}, {num_vertices});
753 engine.Put(orig_id, geometry.input_global_indices().data());
754
755 std::vector<std::uint8_t> x_ghost(num_vertices, 0);
756 std::fill(std::next(x_ghost.begin(), x_map->size_local()), x_ghost.end(), 1);
757 adios2::Variable ghost = impl_adios2::define_variable<std::uint8_t>(
758 io, "vtkGhostType", {}, {}, {x_ghost.size()});
759 engine.Put(ghost, x_ghost.data());
760 engine.PerformPuts();
761}
762
770template <std::floating_point T>
771void vtx_write_mesh_from_space(adios2::IO& io, adios2::Engine& engine,
772 const fem::FunctionSpace<T>& V)
773{
774 auto mesh = V.mesh();
775 assert(mesh);
776 auto topology = mesh->topology();
777 assert(topology);
778 int tdim = topology->dim();
779
780 // Get a VTK mesh with points at the 'nodes'
781 auto [x, xshape, x_id, x_ghost, vtk, vtkshape] = io::vtk_mesh_from_space(V);
782
783 std::uint32_t num_dofs = xshape[0];
784
785 // -- Pack mesh 'nodes'. Output is written as [N0, v0_0,...., v0_N0, N1,
786 // v1_0,...., v1_N1,....], where N is the number of cell nodes and v0,
787 // etc, is the node index.
788
789 // Create vector, setting all entries to nodes per cell (vtk.shape(1))
790 std::vector<std::int64_t> cells(vtkshape[0] * (vtkshape[1] + 1), vtkshape[1]);
791
792 // Set the [v0_0,...., v0_N0, v1_0,...., v1_N1,....] data
793 for (std::size_t c = 0; c < vtkshape[0]; ++c)
794 {
795 std::span vtkcell(vtk.data() + c * vtkshape[1], vtkshape[1]);
796 std::span cell(cells.data() + c * (vtkshape[1] + 1), vtkshape[1] + 1);
797 std::copy(vtkcell.begin(), vtkcell.end(), std::next(cell.begin()));
798 }
799
800 // Define ADIOS2 variables for geometry, topology, celltypes and
801 // corresponding VTK data
802 adios2::Variable local_geometry
803 = impl_adios2::define_variable<T>(io, "geometry", {}, {}, {num_dofs, 3});
804 adios2::Variable local_topology = impl_adios2::define_variable<std::int64_t>(
805 io, "connectivity", {}, {}, {vtkshape[0], vtkshape[1] + 1});
806 adios2::Variable cell_type
807 = impl_adios2::define_variable<std::uint32_t>(io, "types");
808 adios2::Variable vertices = impl_adios2::define_variable<std::uint32_t>(
809 io, "NumberOfNodes", {adios2::LocalValueDim});
810 adios2::Variable elements = impl_adios2::define_variable<std::uint32_t>(
811 io, "NumberOfEntities", {adios2::LocalValueDim});
812
813 // Write mesh information to file
814 engine.Put<std::uint32_t>(vertices, num_dofs);
815 engine.Put<std::uint32_t>(elements, vtkshape[0]);
816 engine.Put<std::uint32_t>(
817 cell_type, cells::get_vtk_cell_type(topology->cell_types()[0], tdim));
818 engine.Put(local_geometry, x.data());
819 engine.Put(local_topology, cells.data());
820
821 // Node global ids
822 adios2::Variable orig_id = impl_adios2::define_variable<std::int64_t>(
823 io, "vtkOriginalPointIds", {}, {}, {x_id.size()});
824 engine.Put(orig_id, x_id.data());
825 adios2::Variable ghost = impl_adios2::define_variable<std::uint8_t>(
826 io, "vtkGhostType", {}, {}, {x_ghost.size()});
827 engine.Put(ghost, x_ghost.data());
828
829 engine.PerformPuts();
830}
831} // namespace impl_vtx
832
838template <std::floating_point T>
839class VTXWriter : public ADIOS2Writer
840{
841public:
853 VTXWriter(MPI_Comm comm, const std::filesystem::path& filename,
854 std::shared_ptr<const mesh::Mesh<T>> mesh,
855 std::string engine = "BPFile")
856 : ADIOS2Writer(comm, filename, "VTX mesh writer", engine), _mesh(mesh)
857 {
858 // Define VTK scheme attribute for mesh
859 std::string vtk_scheme = impl_vtx::create_vtk_schema({}, {}).str();
860 impl_adios2::define_attribute<std::string>(*_io, "vtk.xml", vtk_scheme);
861 }
862
874 VTXWriter(MPI_Comm comm, const std::filesystem::path& filename,
875 const typename adios2_writer::U<T>& u,
876 std::string engine = "BPFile")
877 : ADIOS2Writer(comm, filename, "VTX function writer", engine),
878 _mesh(impl_adios2::extract_common_mesh<T>(u)), _u(u)
879 {
880 if (u.empty())
881 throw std::runtime_error("VTXWriter fem::Function list is empty.");
882
883 // Extract element from first function
884 auto element0 = std::visit([](auto& u)
885 { return u->function_space()->element().get(); },
886 u.front());
887 assert(element0);
888
889 // Check if function is mixed
890 if (element0->is_mixed())
891 {
892 throw std::runtime_error(
893 "Mixed functions are not supported by VTXWriter.");
894 }
895
896 // FIXME: is the below check adequate for detecting a Lagrange
897 // element?
898 // Check that element is Lagrange
899 if (!element0->interpolation_ident())
900 {
901 throw std::runtime_error(
902 "Only (discontinuous) Lagrange functions are "
903 "supported. Interpolate Functions before output.");
904 }
905
906 // Check if function is DG 0
907 if (element0->space_dimension() / element0->block_size() == 1)
908 {
909 throw std::runtime_error(
910 "VTK does not support cell-wise fields. See "
911 "https://gitlab.kitware.com/vtk/vtk/-/issues/18458.");
912 }
913
914 // Check that all functions come from same element type
915 for (auto& v : _u)
916 {
917 std::visit(
918 [element0](auto& u)
919 {
920 auto element = u->function_space()->element();
921 assert(element);
922 if (*element != *element0)
923 {
924 throw std::runtime_error("All functions in VTXWriter must have "
925 "the same element type.");
926 }
927 },
928 v);
929 }
930
931 // Define VTK scheme attribute for set of functions
932 std::vector<std::string> names = impl_vtx::extract_function_names<T>(u);
933 std::string vtk_scheme = impl_vtx::create_vtk_schema(names, {}).str();
934 impl_adios2::define_attribute<std::string>(*_io, "vtk.xml", vtk_scheme);
935 }
936
937 // Copy constructor
938 VTXWriter(const VTXWriter&) = delete;
939
941 VTXWriter(VTXWriter&& file) = default;
942
944 ~VTXWriter() = default;
945
947 VTXWriter& operator=(VTXWriter&&) = default;
948
949 // Copy assignment
950 VTXWriter& operator=(const VTXWriter&) = delete;
951
954 void write(double t)
955 {
956 assert(_io);
957 assert(_engine);
958 adios2::Variable var_step
959 = impl_adios2::define_variable<double>(*_io, "step");
960 _engine->BeginStep();
961 _engine->template Put<double>(var_step, t);
962
963 // If we have no functions write the mesh to file
964 if (_u.empty())
965 impl_vtx::vtx_write_mesh(*_io, *_engine, *_mesh);
966 else
967 {
968 // Write a single mesh for functions as they share finite element
969 std::visit(
970 [&](auto& u) {
971 impl_vtx::vtx_write_mesh_from_space(*_io, *_engine,
972 *u->function_space());
973 },
974 _u[0]);
975
976 // Write function data for each function to file
977 for (auto& v : _u)
978 std::visit(
979 [&](auto& u) { impl_vtx::vtx_write_data(*_io, *_engine, *u); }, v);
980 }
981
982 _engine->EndStep();
983 }
984
985private:
986 std::shared_ptr<const mesh::Mesh<T>> _mesh;
987 adios2_writer::U<T> _u;
988};
989
991template <typename U, typename T>
992VTXWriter(MPI_Comm comm, U filename, T mesh)
993 -> VTXWriter<typename std::remove_cvref<
994 typename T::element_type>::type::geometry_type::value_type>;
995
997template <typename U, typename T>
998FidesWriter(MPI_Comm comm, U filename, T mesh)
999 -> FidesWriter<typename std::remove_cvref<
1000 typename T::element_type>::type::geometry_type::value_type>;
1001
1002} // namespace dolfinx::io
1003
1004#endif
std::shared_ptr< const mesh::Mesh< T > > extract_common_mesh(const typename adios2_writer::U< T > &u)
Extract common mesh from list of Functions.
Definition ADIOS2Writers.h:132
adios2::Variable< T > define_variable(adios2::IO &io, std::string name, const adios2::Dims &shape=adios2::Dims(), const adios2::Dims &start=adios2::Dims(), const adios2::Dims &count=adios2::Dims())
Safe definition of a variable. First check if it has already been defined and return it....
Definition ADIOS2Writers.h:114
adios2::Attribute< T > define_attribute(adios2::IO &io, std::string name, const T &value, std::string var_name="", std::string separator="/")
Safe definition of an attribute. First check if it has already been defined and return it....
Definition ADIOS2Writers.h:101
constexpr std::array field_ext
String suffix for real and complex components of a vector-valued field.
Definition ADIOS2Writers.h:96
void write_data(adios2::IO &io, adios2::Engine &engine, const fem::Function< T, U > &u)
Write a first order Lagrange function (real or complex) using ADIOS2 in Fides format....
Definition ADIOS2Writers.h:283
void write_mesh(adios2::IO &io, adios2::Engine &engine, const mesh::Mesh< T > &mesh)
Write mesh geometry and connectivity (topology) for Fides.
Definition ADIOS2Writers.h:366
std::vector< T > pack_function_data(const fem::Function< T, U > &u)
Pack Function data at vertices. The mesh and the function must both be 'P1'.
Definition ADIOS2Writers.h:226
void initialize_function_attributes(adios2::IO &io, const typename adios2_writer::U< T > &u)
Initialize function related attributes for the ADIOS2 file used in Fides.
Definition ADIOS2Writers.h:174
Degree-of-freedom map representations and tools.
This class represents a function in a finite element function space , given by.
Definition Function.h:45
std::string name
Name.
Definition Function.h:657
std::shared_ptr< const FunctionSpace< U > > function_space() const
Access the function space.
Definition Function.h:140
std::shared_ptr< const la::Vector< T > > x() const
Underlying vector.
Definition Function.h:146
Base class for ADIOS2-based writers.
Definition ADIOS2Writers.h:55
ADIOS2Writer & operator=(ADIOS2Writer &&writer)=default
Move assignment.
void close()
Close the file.
Definition ADIOS2Writers.cpp:64
ADIOS2Writer(const ADIOS2Writer &)=delete
Copy constructor.
ADIOS2Writer(ADIOS2Writer &&writer)=default
Move constructor.
~ADIOS2Writer()
Destructor.
Definition ADIOS2Writers.cpp:62
Geometry stores the geometry imposed on a mesh.
Definition Geometry.h:33
std::shared_ptr< const common::IndexMap > index_map() const
Index map.
Definition Geometry.h:104
MDSPAN_IMPL_STANDARD_NAMESPACE::mdspan< const std::int32_t, MDSPAN_IMPL_STANDARD_NAMESPACE::dextents< std::size_t, 2 > > dofmap() const
DOF map.
Definition Geometry.h:94
std::span< const value_type > x() const
Access geometry degrees-of-freedom data (const version).
Definition Geometry.h:113
const std::vector< fem::CoordinateElement< value_type > > & cmaps() const
The elements that describes the geometry maps.
Definition Geometry.h:125
A Mesh consists of a set of connected and numbered mesh topological entities, and geometry data.
Definition Mesh.h:23
std::shared_ptr< Topology > topology()
Get mesh topology.
Definition Mesh.h:64
Geometry< T > & geometry()
Get mesh geometry.
Definition Mesh.h:76
int rank(MPI_Comm comm)
Return process rank for the communicator.
Definition MPI.cpp:64
void cells(la::SparsityPattern &pattern, std::span< const std::int32_t > cells, std::array< std::reference_wrapper< const DofMap >, 2 > dofmaps)
Iterate over cells and insert entries into sparsity pattern.
Definition sparsitybuild.cpp:18
Finite element method functionality.
Definition assemble_matrix_impl.h:25
Support for file IO.
Definition ADIOS2Writers.h:41
CellType
Cell type identifier.
Definition cell_types.h:22