Debian Codegraph @

src/atlas/output/detail/GmshIO.cc

raw
1 /*
2 * (C) Copyright 2013 ECMWF.
3 *
4 * This software is licensed under the terms of the Apache Licence Version 2.0
5 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
6 * In applying this licence, ECMWF does not waive the privileges and immunities
7 * granted to it by virtue of its status as an intergovernmental organisation
8 * nor does it submit to any jurisdiction.
9 */
10
11 // file deepcode ignore MissingOpenCheckOnFile: False positive
12
13 #include <cmath>
14 #include <fstream>
15 #include <iostream>
16 #include <limits>
17 #include <stdexcept>
18
19 #include "eckit/filesystem/PathName.h"
20 #include "eckit/config/Resource.h"
21
22 #include "atlas/array.h"
23 #include "atlas/array/ArrayView.h"
24 #include "atlas/array/IndexView.h"
25 #include "atlas/array/MakeView.h"
26 #include "atlas/field/Field.h"
27 #include "atlas/field/FieldSet.h"
28 #include "atlas/field/MissingValue.h"
29 #include "atlas/functionspace/FunctionSpace.h"
30 #include "atlas/mesh/ElementType.h"
31 #include "atlas/mesh/Elements.h"
32 #include "atlas/mesh/HybridElements.h"
33 #include "atlas/mesh/Mesh.h"
34 #include "atlas/mesh/Nodes.h"
35 #include "atlas/output/detail/GmshIO.h"
36 #include "atlas/parallel/GatherScatter.h"
37 #include "atlas/parallel/mpi/mpi.h"
38 #include "atlas/runtime/Exception.h"
39 #include "atlas/runtime/Log.h"
40 #include "atlas/util/Constants.h"
41 #include "atlas/util/CoordinateEnums.h"
42
43 using atlas::functionspace::NodeColumns;
44 using atlas::util::Metadata;
45 using atlas::util::Topology;
46 using eckit::PathName;
47
48 namespace atlas {
49 namespace output {
50 namespace detail {
51
52 namespace {
53
54 class GmshFile : public std::ofstream {
55 public:
56 GmshFile(const PathName& file_path, std::ios_base::openmode mode, int part = static_cast<int>(mpi::rank())) {
57 PathName par_path(file_path);
58 int mpi_size = static_cast<int>(mpi::size());
59 if (mpi::size() == 1 || part == -1) {
60 std::ofstream::open(par_path.localPath(), mode);
61 }
62 else {
63 if (mpi::rank() == 0) {
64 PathName par_path(file_path);
65 std::ofstream par_file(par_path.localPath(), std::ios_base::out);
66 for (int p = 0; p < mpi_size; ++p) {
67 PathName loc_path(file_path);
68 // loc_path = loc_path.baseName(false) + "_p" + to_str(p) + ".msh";
69 loc_path = loc_path.baseName(false) + ".msh.p" + std::to_string(p);
70 par_file << "Merge \"" << loc_path << "\";" << std::endl;
71 }
72 par_file.close();
73 }
74 PathName path(file_path);
75 // path = path.dirName() + "/" + path.baseName(false) + "_p" +
76 // to_str(part) + ".msh";
77 path = path.dirName() + "/" + path.baseName(false) + ".msh.p" + std::to_string(part);
78 std::ofstream::open(path.localPath(), mode);
79 }
80 }
81 };
82
83 enum GmshElementTypes
84 {
85 LINE = 1,
86 TRIAG = 2,
87 QUAD = 3,
88 POINT = 15
89 };
90
91 // ----------------------------------------------------------------------------
92 void write_header_ascii(std::ostream& out) {
93 out << "$MeshFormat\n";
94 out << "2.2 0 " << sizeof(double) << "\n";
95 out << "$EndMeshFormat\n";
96 }
97 // ----------------------------------------------------------------------------
98
99 // ----------------------------------------------------------------------------
100 void write_header_binary(std::ostream& out) {
101 out << "$MeshFormat\n";
102 out << "2.2 1 " << sizeof(double) << "\n";
103 int one = 1;
104 out.write(reinterpret_cast<const char*>(&one), sizeof(int));
105 out << "\n$EndMeshFormat\n";
106 }
107 // ----------------------------------------------------------------------------
108
109 namespace { // anonymous
110
111 template <typename T>
112 array::LocalView<const T, 2> make_level_view(const Field& field, int ndata, int jlev) {
113 using namespace array;
114 if (field.levels()) {
115 if (field.variables()) {
116 return make_view<const T, 3>(field).slice(Range::to(ndata), jlev, Range::all());
117 }
118 else {
119 return make_view<const T, 2>(field).slice(Range::to(ndata), jlev, Range::dummy());
120 }
121 }
122 else {
123 if (field.variables()) {
124 return make_view<const T, 2>(field).slice(Range::to(ndata), Range::all());
125 }
126 else {
127 return make_view<const T, 1>(field).slice(Range::to(ndata), Range::dummy());
128 }
129 }
130 }
131
132 template <typename Value, typename GlobalIndex, typename IncludeIndex>
133 void write_level(std::ostream& out, GlobalIndex gidx, const array::LocalView<Value, 2>& data, IncludeIndex include) {
134 using value_type = typename std::remove_const<Value>::type;
135 int ndata = data.shape(0);
136 int nvars = data.shape(1);
137 if (nvars == 1) {
138 for (idx_t n = 0; n < ndata; ++n) {
139 if (include(n)) {
140 out << gidx(n) << " " << data(n, 0) << "\n";
141 }
142 }
143 }
144 else if (nvars <= 3) {
145 std::array<value_type, 3> data_vec;
146 data_vec.fill(static_cast<value_type>(0));
147 for (idx_t n = 0; n < ndata; ++n) {
148 if (include(n)) {
149 for (idx_t v = 0; v < nvars; ++v) {
150 data_vec[v] = data(n, v);
151 }
152 out << gidx(n);
153 for (int v = 0; v < 3; ++v) {
154 out << " " << data_vec[v];
155 }
156 out << "\n";
157 }
158 }
159 }
160 else if (nvars <= 9) {
161 std::array<value_type, 9> data_vec;
162 data_vec.fill(static_cast<value_type>(0));
163 if (nvars == 4) {
164 for (int n = 0; n < ndata; ++n) {
165 if (include(n)) {
166 for (int i = 0; i < 2; ++i) {
167 for (int j = 0; j < 2; ++j) {
168 data_vec[i * 3 + j] = data(n, i * 2 + j);
169 }
170 }
171 out << gidx(n);
172 for (int v = 0; v < 9; ++v) {
173 out << " " << data_vec[v];
174 }
175 out << "\n";
176 }
177 }
178 }
179 else if (nvars == 9) {
180 for (int n = 0; n < ndata; ++n) {
181 if (include(n)) {
182 for (int i = 0; i < 3; ++i) {
183 for (int j = 0; j < 3; ++j) {
184 data_vec[i * 3 + j] = data(n, i * 2 + j);
185 }
186 }
187 out << gidx(n);
188 for (int v = 0; v < 9; ++v) {
189 out << " " << data_vec[v];
190 }
191 out << "\n";
192 }
193 }
194 }
195 else {
196 ATLAS_NOTIMPLEMENTED;
197 }
198 }
199 else {
200 ATLAS_NOTIMPLEMENTED;
201 }
202 }
203 template <typename Value, typename GlobalIndex>
204 void write_level(std::ostream& out, GlobalIndex gidx, const array::LocalView<Value, 2>& data) {
205 write_level(out, gidx, data, [](idx_t) { return true; });
206 }
207
208 std::vector<int> get_levels(int nlev, const Metadata& gmsh_options) {
209 std::vector<int> lev;
210 std::vector<int> gmsh_levels;
211 gmsh_options.get("levels", gmsh_levels);
212 if (gmsh_levels.empty() || nlev == 1) {
213 lev.resize(nlev);
214 for (int ilev = 0; ilev < nlev; ++ilev) {
215 lev[ilev] = ilev;
216 }
217 }
218 else {
219 lev = gmsh_levels;
220 }
221 return lev;
222 }
223
224 std::string field_lev(const Field& field, int jlev) {
225 if (field.levels()) {
226 char str[6] = {0, 0, 0, 0, 0, 0};
227 auto str_len = std::snprintf(str, sizeof(str), "[%03d]", jlev);
228 ATLAS_ASSERT(str_len == 5);
229 return std::string(str);
230 }
231 else {
232 return std::string();
233 }
234 }
235
236 double field_time(const Field& field) {
237 return field.metadata().has("time") ? field.metadata().get<double>("time") : 0.;
238 }
239
240 int field_step(const Field& field) {
241 return field.metadata().has("step") ? field.metadata().get<size_t>("step") : 0;
242 }
243
244 int field_vars(int nvars) {
245 if (nvars == 1) {
246 return nvars;
247 }
248 else if (nvars <= 3) {
249 return 3;
250 }
251 else if (nvars <= 9) {
252 return 9;
253 }
254 else {
255 return nvars;
256 }
257 }
258
259 } // namespace
260
261 // ----------------------------------------------------------------------------
262 template <typename Value>
263 void write_field_nodes(const Metadata& gmsh_options, const functionspace::NodeColumns& function_space,
264 const Field& field, std::ostream& out) {
265 Log::debug() << "writing NodeColumns field " << field.name() << " defined in NodeColumns..." << std::endl;
266
267 bool gather(gmsh_options.get<bool>("gather") && mpi::size() > 1);
268 // unused: bool binary( !gmsh_options.get<bool>( "ascii" ) );
269 idx_t nlev = std::max<idx_t>(1, field.levels());
270 idx_t ndata = std::min<idx_t>(function_space.nb_nodes(), field.shape(0));
271 idx_t nvars = std::max<idx_t>(1, field.variables());
272 auto gidx = array::make_view<gidx_t, 1>(function_space.nodes().global_index());
273 Field gidx_glb;
274 Field field_glb;
275 if (gather) {
276 gidx_glb =
277 function_space.createField<gidx_t>(option::name("gidx_glb") | option::levels(false) | option::global());
278 function_space.gather(function_space.nodes().global_index(), gidx_glb);
279 gidx = array::make_view<gidx_t, 1>(gidx_glb);
280
281 field_glb = function_space.createField(field, option::global());
282 function_space.gather(field, field_glb);
283 ndata = std::min<idx_t>(function_space.nb_nodes_global(), field_glb.shape(0));
284 }
285 auto missing = field::MissingValue(field);
286
287 std::vector<int> lev = get_levels(nlev, gmsh_options);
288 for (size_t ilev = 0; ilev < lev.size(); ++ilev) {
289 int jlev = lev[ilev];
290 if ((gather && mpi::rank() == 0) || !gather) {
291 auto data =
292 gather ? make_level_view<Value>(field_glb, ndata, jlev) : make_level_view<Value>(field, ndata, jlev);
293 auto include_idx = [&](idx_t n) {
294 for (idx_t v = 0; v < nvars; ++v) {
295 if (missing(data(n, v))) {
296 return false;
297 }
298 }
299 return true;
300 };
301 idx_t ndata_nonmissing = [&] {
302 if (missing) {
303 idx_t c = 0;
304 for (idx_t n = 0; n < ndata; ++n) {
305 c += include_idx(n);
306 }
307 return c;
308 }
309 return ndata;
310 }();
311
312 out << "$NodeData\n";
313 out << "1\n";
314 out << "\"" << field.name() << field_lev(field, jlev) << "\"\n";
315 out << "1\n";
316 out << field_time(field) << "\n";
317 out << "4\n";
318 out << field_step(field) << "\n";
319 out << field_vars(nvars) << "\n";
320 out << ndata_nonmissing << "\n";
321 out << mpi::rank() << "\n";
322 if (missing) {
323 write_level(out, gidx, data, include_idx);
324 }
325 else {
326 write_level(out, gidx, data);
327 }
328 out << "$EndNodeData\n";
329 }
330 }
331 }
332
333 // ----------------------------------------------------------------------------
334 template <typename Value>
335 void write_field_nodes(const Metadata& gmsh_options, const functionspace::NoFunctionSpace& function_space,
336 const Field& field, std::ostream& out) {
337 Log::debug() << "writing field " << field.name() << " defined without functionspace..." << std::endl;
338
339 // unused: bool binary( !gmsh_options.get<bool>( "ascii" ) );
340 idx_t nlev = std::max<idx_t>(1, field.levels());
341 idx_t ndata = field.shape(0);
342 idx_t nvars = std::max<idx_t>(1, field.variables());
343 auto gidx = [](idx_t inode) { return inode + 1; };
344
345 auto missing = field::MissingValue(field);
346
347 std::vector<int> lev = get_levels(nlev, gmsh_options);
348 for (size_t ilev = 0; ilev < lev.size(); ++ilev) {
349 int jlev = lev[ilev];
350
351 auto data = make_level_view<Value>(field, ndata, jlev);
352 auto include_idx = [&](idx_t n) {
353 for (idx_t v = 0; v < nvars; ++v) {
354 if (missing(data(n, v))) {
355 return false;
356 }
357 }
358 return true;
359 };
360 idx_t ndata_nonmissing = [&] {
361 if (missing) {
362 idx_t c = 0;
363 for (idx_t n = 0; n < ndata; ++n) {
364 c += include_idx(n);
365 }
366 return c;
367 }
368 return ndata;
369 }();
370
371 out << "$NodeData\n";
372 out << "1\n";
373 out << "\"" << field.name() << field_lev(field, jlev) << "\"\n";
374 out << "1\n";
375 out << field_time(field) << "\n";
376 out << "4\n";
377 out << field_step(field) << "\n";
378 out << field_vars(nvars) << "\n";
379 out << ndata_nonmissing << "\n";
380 out << mpi::rank() << "\n";
381 if (missing) {
382 write_level(out, gidx, data, include_idx);
383 }
384 else {
385 write_level(out, gidx, data);
386 }
387 out << "$EndNodeData\n";
388 }
389 }
390 // ----------------------------------------------------------------------------
391
392
393 // ----------------------------------------------------------------------------
394
395 void print_field_lev(char field_lev[], size_t size, int jlev) {
396 ATLAS_ASSERT(size > 5);
397 std::snprintf(field_lev, size, "[%03d]", jlev);
398 }
399
400 /* unused
401 void print_field_lev( char field_lev[], long jlev ) {
402 std::sprintf( field_lev, "[%03ld]", jlev );
403 }
404
405 void print_field_lev( char field_lev[], unsigned long jlev ) {
406 std::sprintf( field_lev, "[%03lu]", jlev );
407 }
408 **/
409
410 // ----------------------------------------------------------------------------
411 template <typename DATATYPE>
412 void write_field_nodes(const Metadata& gmsh_options, const functionspace::StructuredColumns& function_space,
413 const Field& field, std::ostream& out) {
414 Log::debug() << "writing StructuredColumns field " << field.name() << "..." << std::endl;
415
416 bool gather(gmsh_options.get<bool>("gather") && mpi::size() > 1);
417 // unused: bool binary( !gmsh_options.get<bool>( "ascii" ) );
418 idx_t nlev = std::max<idx_t>(1, field.levels());
419 idx_t ndata = std::min<idx_t>(function_space.sizeOwned(), field.shape(0));
420 idx_t nvars = std::max<idx_t>(1, field.variables());
421 auto gidx = array::make_view<gidx_t, 1>(function_space.global_index());
422 Field gidx_glb;
423 Field field_glb;
424 if (gather) {
425 gidx_glb =
426 function_space.createField(function_space.global_index(), option::name("gidx_glb") | option::global());
427 function_space.gather(function_space.global_index(), gidx_glb);
428 gidx = array::make_view<gidx_t, 1>(gidx_glb);
429
430 field_glb = function_space.createField(field, option::global());
431 function_space.gather(field, field_glb);
432 ndata = field_glb.shape(0);
433 }
434
435 auto missing = field::MissingValue(field);
436
437 std::vector<int> lev = get_levels(nlev, gmsh_options);
438 for (size_t ilev = 0; ilev < lev.size(); ++ilev) {
439 int jlev = lev[ilev];
440 char field_lev[6] = {0, 0, 0, 0, 0, 0};
441
442 if (field.levels()) {
443 print_field_lev(field_lev, sizeof(field_lev), jlev);
444 }
445
446 auto data =
447 gather ? make_level_view<DATATYPE>(field_glb, ndata, jlev) : make_level_view<DATATYPE>(field, ndata, jlev);
448
449 auto include_idx = [&](idx_t n) {
450 for (idx_t v = 0; v < nvars; ++v) {
451 if (missing(data(n, v))) {
452 return false;
453 }
454 }
455 return true;
456 };
457 idx_t ndata_nonmissing = [&] {
458 if (missing) {
459 idx_t c = 0;
460 for (idx_t n = 0; n < ndata; ++n) {
461 c += include_idx(n);
462 }
463 return c;
464 }
465 return ndata;
466 }();
467
468
469 out << "$NodeData\n";
470 out << "1\n";
471 out << "\"" << field.name() << field_lev << "\"\n";
472 out << "1\n";
473 out << field_time(field) << "\n";
474 out << "4\n";
475 out << field_step(field) << "\n";
476 out << field_vars(nvars) << "\n";
477 out << ndata_nonmissing << "\n";
478 out << mpi::rank() << "\n";
479 if (missing) {
480 write_level(out, gidx, data, include_idx);
481 }
482 else {
483 write_level(out, gidx, data);
484 }
485 out << "$EndNodeData\n";
486 }
487 }
488 // ----------------------------------------------------------------------------
489
490 template <typename DATATYPE>
491 void write_field_elems(const Metadata& gmsh_options, const functionspace::CellColumns& function_space,
492 const Field& field, std::ostream& out) {
493 #if 1
494 Log::debug() << "writing CellColumns field " << field.name() << "..." << std::endl;
495
496 bool gather(gmsh_options.get<bool>("gather") && mpi::size() > 1);
497 // unused: bool binary( !gmsh_options.get<bool>( "ascii" ) );
498 idx_t nlev = std::max<idx_t>(1, field.levels());
499 idx_t ndata = std::min<idx_t>(function_space.nb_cells(), field.shape(0));
500 idx_t nvars = std::max<idx_t>(1, field.variables());
501 auto gidx = array::make_view<gidx_t, 1>(function_space.cells().global_index());
502 Field gidx_glb;
503 Field field_glb;
504 if (gather) {
505 gidx_glb =
506 function_space.createField<gidx_t>(option::name("gidx_glb") | option::levels(false) | option::global());
507 function_space.gather(function_space.cells().global_index(), gidx_glb);
508 gidx = array::make_view<gidx_t, 1>(gidx_glb);
509
510 field_glb = function_space.createField(field, option::global());
511 function_space.gather(field, field_glb);
512 ndata = std::min<idx_t>(function_space.nb_cells_global(), field_glb.shape(0));
513 }
514
515 auto missing = field::MissingValue(field);
516
517 std::vector<int> lev = get_levels(nlev, gmsh_options);
518 for (size_t ilev = 0; ilev < lev.size(); ++ilev) {
519 int jlev = lev[ilev];
520
521 auto data = gather ? make_level_view<DATATYPE>(field_glb, ndata, jlev)
522 : make_level_view<DATATYPE>(field, ndata, jlev);
523
524 auto include_idx = [&](idx_t n) {
525 for (idx_t v = 0; v < nvars; ++v) {
526 if (missing(data(n, v))) {
527 return false;
528 }
529 }
530 return true;
531 };
532 idx_t ndata_nonmissing = [&] {
533 if (missing) {
534 idx_t c = 0;
535 for (idx_t n = 0; n < ndata; ++n) {
536 c += include_idx(n);
537 }
538 return c;
539 }
540 return ndata;
541 }();
542
543
544 if ((gather && mpi::rank() == 0) || !gather) {
545 out << "$ElementData\n";
546 out << "1\n";
547 out << "\"" << field.name() << field_lev(field, jlev) << "\"\n";
548 out << "1\n";
549 out << field_time(field) << "\n";
550 out << "4\n";
551 out << field_step(field) << "\n";
552 out << field_vars(nvars) << "\n";
553 out << ndata_nonmissing << "\n";
554 out << mpi::rank() << "\n";
555 if (missing) {
556 write_level(out, gidx, data, include_idx);
557 }
558 else {
559 write_level(out, gidx, data);
560 }
561 out << "$EndElementData\n";
562 }
563 }
564 #endif
565 }
566
567 // ----------------------------------------------------------------------------
568 #if 0
569 template< typename DATA_TYPE >
570 void write_field_elems(const Metadata& gmsh_options, const FunctionSpace& function_space, const Field& field, std::ostream& out)
571 {
572 Log::info() << "writing field " << field.name() << "..." << std::endl;
573 bool gather( gmsh_options.get<bool>("gather") );
574 bool binary( !gmsh_options.get<bool>("ascii") );
575 int nlev = field.metadata().has("nb_levels") ? field.metadata().get<size_t>("nb_levels") : 1;
576 int ndata = field.shape(0);
577 int nvars = field.shape(1)/nlev;
578 array::ArrayView<gidx_t,1 > gidx ( function_space.field( "glb_idx" ) );
579 array::ArrayView<DATA_TYPE> data ( field );
580 array::ArrayT<DATA_TYPE> field_glb_arr;
581 array::ArrayT<gidx_t > gidx_glb_arr;
582 if( gather )
583 {
584 mpl::GatherScatter& fullgather = function_space.fullgather();
585 ndata = fullgather.glb_dof();
586 field_glb_arr.resize(ndata,field.shape(1));
587 gidx_glb_arr.resize(ndata);
588 array::ArrayView<DATA_TYPE> data_glb( field_glb_arr );
589 array::ArrayView<gidx_t,1> gidx_glb( gidx_glb_arr );
590 fullgather.gather( gidx, gidx_glb );
591 fullgather.gather( data, data_glb );
592 gidx = array::ArrayView<gidx_t,1>( gidx_glb_arr );
593 data = data_glb;
594 }
595
596 double time = field.metadata().has("time") ? field.metadata().get<double>("time") : 0.;
597 size_t step = field.metadata().has("step") ? field.metadata().get<size_t>("step") : 0 ;
598
599 int nnodes = IndexView<int,2>( function_space.field("nodes") ).shape(1);
600
601 for (int jlev=0; jlev<nlev; ++jlev)
602 {
603 char field_lev[6] = {0, 0, 0, 0, 0, 0};
604 if( field.metadata().has("nb_levels") )
605 std::sprintf(field_lev, "[%03d]",jlev);
606
607 out << "$ElementNodeData\n";
608 out << "1\n";
609 out << "\"" << field.name() << field_lev << "\"\n";
610 out << "1\n";
611 out << time << "\n";
612 out << "4\n";
613 out << step << "\n";
614 if ( nvars == 1 ) out << nvars << "\n";
615 else if( nvars <= 3 ) out << 3 << "\n";
616 out << ndata << "\n";
617 out << mpi::rank() << "\n";
618
619 if( binary )
620 {
621 if( nvars == 1)
622 {
623 double value;
624 for (size_t jelem=0; jelem<ndata; ++jelem)
625 {
626 out.write(reinterpret_cast<const char*>(&gidx(jelem)),sizeof(int));
627 out.write(reinterpret_cast<const char*>(&nnodes),sizeof(int));
628 for (size_t n=0; n<nnodes; ++n)
629 {
630 value = data(jelem,jlev);
631 out.write(reinterpret_cast<const char*>(&value),sizeof(double));
632 }
633 }
634 }
635 else if( nvars <= 3 )
636 {
637 double value[3] = {0,0,0};
638 for (size_t jelem=0; jelem<ndata; ++jelem)
639 {
640 out << gidx(jelem) << " " << nnodes;
641 for (size_t n=0; n<nnodes; ++n)
642 {
643 for( int v=0; v<nvars; ++v)
644 value[v] = data(jelem,jlev*nvars+v);
645 out.write(reinterpret_cast<const char*>(&value),sizeof(double)*3);
646 }
647 }
648 }
649 out <<"\n";
650 }
651 else
652 {
653 if( nvars == 1)
654 {
655 for (size_t jelem=0; jelem<ndata; ++jelem)
656 {
657 out << gidx(jelem) << " " << nnodes;
658 for (size_t n=0; n<nnodes; ++n)
659 out << " " << data(jelem,jlev);
660 out <<"\n";
661 }
662 }
663 else if( nvars <= 3 )
664 {
665 std::vector<DATA_TYPE> data_vec(3,0.);
666 for (size_t jelem=0; jelem<ndata; ++jelem)
667 {
668 out << gidx(jelem) << " " << nnodes;
669 for (size_t n=0; n<nnodes; ++n)
670 {
671 for( int v=0; v<nvars; ++v)
672 data_vec[v] = data(jelem,jlev*nvars+v);
673 for( int v=0; v<3; ++v)
674 out << " " << data_vec[v];
675 }
676 out <<"\n";
677 }
678 }
679 }
680 out << "$EndElementNodeData\n";
681 }
682 }
683 #endif
684
685 // ----------------------------------------------------------------------------
686
687 } // end anonymous namespace
688
689 // ----------------------------------------------------------------------------
690 GmshIO::GmshIO() {
691 // which field holds the Nodes
692 options.set<std::string>("nodes", "xy");
693
694 // Gather fields to one proc before writing
695 options.set<bool>("gather", false);
696
697 // Output of ghost nodes / elements
698 options.set<bool>("ghost", false);
699
700 // ASCII format (true) or binary (false)
701 options.set<bool>("ascii", true);
702
703 // Output of elements
704 options.set<bool>("elements", true);
705
706 // Output of edges
707 options.set<bool>("edges", true);
708
709 // Levels of fields to use
710 options.set<std::vector<long>>("levels", std::vector<long>());
711 }
712
713 GmshIO::~GmshIO() = default;
714
715 Mesh GmshIO::read(const PathName& file_path) const {
716 Mesh mesh;
717 GmshIO::read(file_path, mesh);
718 return mesh;
719 }
720
721 namespace {
722 mesh::ElementType* make_element_type(int type) {
723 if (type == QUAD) {
724 return mesh::ElementType::create("Quadrilateral");
725 }
726 if (type == TRIAG) {
727 return mesh::ElementType::create("Triangle");
728 }
729 if (type == LINE) {
730 return mesh::ElementType::create("Line");
731 }
732 throw_Exception("Element type not supported", Here());
733 }
734 } // namespace
735
736 void GmshIO::read(const PathName& file_path, Mesh& mesh) const {
737 std::ifstream file;
738 file.open(file_path.localPath(), std::ios::in | std::ios::binary);
739 if (!file.is_open()) {
740 throw_CantOpenFile(file_path);
741 }
742
743 std::string line;
744
745 while (line != "$MeshFormat") {
746 std::getline(file, line);
747 }
748 double version;
749 int binary;
750 int size_of_real;
751 file >> version >> binary >> size_of_real;
752
753 while (line != "$Nodes") {
754 std::getline(file, line);
755 }
756
757 // Create nodes
758 idx_t nb_nodes;
759 file >> nb_nodes;
760
761 mesh.nodes().resize(nb_nodes);
762
763 mesh::Nodes& nodes = mesh.nodes();
764
765 //nodes.add( Field( "xyz", array::make_datatype<double>(), array::make_shape( nb_nodes, 3 ) ) );
766
767 // array::ArrayView<double, 2> coords = array::make_view<double, 2>( nodes.field( "xyz" ) );
768 array::ArrayView<double, 2> xy = array::make_view<double, 2>(nodes.xy());
769 array::ArrayView<double, 2> lonlat = array::make_view<double, 2>(nodes.lonlat());
770 array::ArrayView<gidx_t, 1> glb_idx = array::make_view<gidx_t, 1>(nodes.global_index());
771 array::ArrayView<int, 1> part = array::make_view<int, 1>(nodes.partition());
772 array::ArrayView<int, 1> ghost = array::make_view<int, 1>(nodes.ghost());
773
774 std::map<int, int> glb_to_loc;
775 int g;
776 double x, y, z;
777 double xyz[3];
778 double xmax = -std::numeric_limits<double>::max();
779 double zmax = -std::numeric_limits<double>::max();
780 gidx_t max_glb_idx = 0;
781 while (binary && file.peek() == '\n') {
782 file.get();
783 }
784 for (idx_t n = 0; n < nb_nodes; ++n) {
785 if (binary) {
786 file.read(reinterpret_cast<char*>(&g), sizeof(int));
787 file.read(reinterpret_cast<char*>(&xyz), sizeof(double) * 3);
788 x = xyz[XX];
789 y = xyz[YY];
790 z = xyz[ZZ];
791 }
792 else {
793 file >> g >> x >> y >> z;
794 }
795 glb_idx(n) = g;
796 xy(n, XX) = x;
797 xy(n, YY) = y;
798 lonlat(n, LON) = x;
799 lonlat(n, LAT) = y;
800 glb_to_loc[g] = n;
801 part(n) = 0;
802 ghost(n) = 0;
803 max_glb_idx = std::max(max_glb_idx, static_cast<gidx_t>(g));
804 xmax = std::max(x, xmax);
805 zmax = std::max(z, zmax);
806 }
807 for (int i = 0; i < 3; ++i) {
808 std::getline(file, line);
809 }
810
811 int nb_elements = 0;
812
813 while (line != "$Elements") {
814 std::getline(file, line);
815 }
816
817 file >> nb_elements;
818
819 if (binary) {
820 while (file.peek() == '\n') {
821 file.get();
822 }
823 int accounted_elems = 0;
824 while (accounted_elems < nb_elements) {
825 int header[3];
826 int data[100];
827 file.read(reinterpret_cast<char*>(&header), sizeof(int) * 3);
828
829 int etype = header[0];
830 size_t netype = header[1];
831 size_t ntags = header[2];
832 accounted_elems += netype;
833 mesh::Elements* elements;
834 if (etype == LINE) {
835 size_t jtype = mesh.edges().add(make_element_type(etype), netype);
836 elements = &mesh.edges().elements(jtype);
837 }
838 else {
839 size_t jtype = mesh.cells().add(make_element_type(etype), netype);
840 elements = &mesh.cells().elements(jtype);
841 }
842
843 size_t nnodes_per_elem = elements->element_type().nb_nodes();
844 mesh::BlockConnectivity& conn = elements->node_connectivity();
845 array::ArrayView<gidx_t, 1> egidx = array::make_view<gidx_t, 1>(elements->global_index());
846 array::ArrayView<int, 1> epart = array::make_view<int, 1>(elements->partition());
847
848 size_t dsize = 1 + ntags + nnodes_per_elem;
849 int part;
850 for (size_t e = 0; e < netype; ++e) {
851 file.read(reinterpret_cast<char*>(&data), sizeof(int) * dsize);
852 part = 0;
853 egidx(e) = data[0];
854 epart(e) = part;
855 for (size_t n = 0; n < nnodes_per_elem; ++n) {
856 conn.set(e, n, glb_to_loc[data[1 + ntags + n]]);
857 }
858 }
859 }
860 }
861 else {
862 // Find out which element types are inside
863 int position = file.tellg();
864 std::vector<int> nb_etype(20, 0);
865 int elements_max_glb_idx(0);
866 int etype;
867 for (int e = 0; e < nb_elements; ++e) {
868 file >> g >> etype;
869 std::getline(file, line); // finish line
870 ++nb_etype[etype];
871 elements_max_glb_idx = std::max(elements_max_glb_idx, g);
872 }
873
874 // Allocate data structures for quads, triags, edges
875
876 int nb_quads = nb_etype[QUAD];
877 int nb_triags = nb_etype[TRIAG];
878 //int nb_edges = nb_etype[LINE];
879
880 mesh::Elements& quads = mesh.cells().elements(mesh.cells().add(make_element_type(QUAD), nb_quads));
881 mesh::Elements& triags = mesh.cells().elements(mesh.cells().add(make_element_type(TRIAG), nb_triags));
882 // mesh::Elements& edges = mesh.edges().elements( mesh.edges().add( make_element_type( LINE ), nb_edges ) );
883
884 mesh::BlockConnectivity& quad_nodes = quads.node_connectivity();
885 mesh::BlockConnectivity& triag_nodes = triags.node_connectivity();
886 // mesh::BlockConnectivity& edge_nodes = edges.node_connectivity();
887
888 array::ArrayView<gidx_t, 1> quad_glb_idx = array::make_view<gidx_t, 1>(quads.global_index());
889 array::ArrayView<int, 1> quad_part = array::make_view<int, 1>(quads.partition());
890
891 array::ArrayView<gidx_t, 1> triag_glb_idx = array::make_view<gidx_t, 1>(triags.global_index());
892 array::ArrayView<int, 1> triag_part = array::make_view<int, 1>(triags.partition());
893
894 // array::ArrayView<gidx_t, 1> edge_glb_idx = array::make_view<gidx_t, 1>( edges.global_index() );
895 // array::ArrayView<int, 1> edge_part = array::make_view<int, 1>( edges.partition() );
896
897 // Now read all elements
898 file.seekg(position, std::ios::beg);
899 int gn0, gn1, gn2, gn3;
900 int quad = 0, triag = 0;
901 int ntags, tags[100];
902 for (int e = 0; e < nb_elements; ++e) {
903 file >> g >> etype >> ntags;
904 for (int t = 0; t < ntags; ++t) {
905 file >> tags[t];
906 }
907 int part = 0;
908 if (ntags > 3) {
909 part = std::max(part, *std::max_element(tags + 3, tags + ntags - 1)); // one positive, others negative
910 }
911
912 idx_t enodes[4] = {-1, -1, -1, -1};
913
914 switch (etype) {
915 case (QUAD):
916 file >> gn0 >> gn1 >> gn2 >> gn3;
917 quad_glb_idx(quad) = g;
918 quad_part(quad) = part;
919 enodes[0] = glb_to_loc[gn0];
920 enodes[1] = glb_to_loc[gn1];
921 enodes[2] = glb_to_loc[gn2];
922 enodes[3] = glb_to_loc[gn3];
923 quad_nodes.set(quad, enodes);
924 ++quad;
925 break;
926 case (TRIAG):
927 file >> gn0 >> gn1 >> gn2;
928 triag_glb_idx(triag) = g;
929 triag_part(triag) = part;
930 enodes[0] = glb_to_loc[gn0];
931 enodes[1] = glb_to_loc[gn1];
932 enodes[2] = glb_to_loc[gn2];
933 triag_nodes.set(triag, enodes);
934 ++triag;
935 break;
936 case (LINE):
937 file >> gn0 >> gn1;
938 // edge_glb_idx( edge ) = g;
939 // edge_part( edge ) = part;
940 // enodes[0] = glb_to_loc[gn0];
941 // enodes[1] = glb_to_loc[gn1];
942 // edge_nodes.set( edge, enodes );
943 // ++edge;
944 break;
945 case (POINT):
946 file >> gn0;
947 break;
948 default:
949 std::cout << "etype " << etype << std::endl;
950 throw_Exception("ERROR: element type not supported", Here());
951 }
952 }
953 }
954
955 file.close();
956 }
957
958 void GmshIO::write(const Mesh& mesh, const PathName& file_path) const {
959 mpi::Scope scope(mesh.mpi_comm());
960 int part = mesh.metadata().has("part") ? mesh.metadata().get<size_t>("part") : mpi::rank();
961 bool include_ghost = options.get<bool>("ghost") && options.get<bool>("elements");
962
963 bool land_water_flag = options.has("water") || options.has("land");
964 bool include_water = options.getBool("water", false);
965 bool include_land = options.getBool("land", false);
966
967 std::string nodes_field = options.get<std::string>("nodes");
968 const mesh::Nodes& nodes = mesh.nodes();
969
970 const Field coords_field = nodes.field(nodes_field);
971 array::ArrayT<double> dummy_double(1, 1);
972 array::ArrayT<idx_t> dummy_idx(1, 1);
973 bool coords_is_idx = coords_field.datatype().kind() == array::make_datatype<idx_t>().kind();
974 auto coords = array::make_view<const double, 2>(coords_is_idx ? dummy_double : coords_field.array());
975 auto coords_idx = array::make_view<const idx_t, 2>(coords_is_idx ? coords_field.array() : dummy_idx);
976 bool coords_is_lonlat = coords_field.name() == "lonlat";
977
978 double filter_edge_ratio = eckit::Resource<double>("$ATLAS_GMSH_FILTER_EDGE_RATIO",0.);
979
980 auto glb_idx = array::make_view<gidx_t, 1>(nodes.global_index());
981
982 const idx_t surfdim = nodes.field(nodes_field).shape(1); // nb of variables in coords
983
984 bool include_patch = (surfdim == 3);
985
986
987 ATLAS_ASSERT(surfdim == 2 || surfdim == 3);
988
989 Log::debug() << "writing mesh to gmsh file " << file_path << std::endl;
990
991 bool binary = !options.get<bool>("ascii");
992
993 openmode mode = std::ios::out;
994 if (binary) {
995 mode = std::ios::out | std::ios::binary;
996 }
997 GmshFile file(file_path, mode, part);
998
999 // Header
1000 if (binary) {
1001 write_header_binary(file);
1002 }
1003 else {
1004 write_header_ascii(file);
1005 }
1006
1007 // Nodes
1008 const idx_t nb_nodes = nodes.size();
1009 file << "$Nodes\n";
1010 file << nb_nodes << "\n";
1011 double xyz[3] = {0., 0., 0.};
1012 for (idx_t n = 0; n < nb_nodes; ++n) {
1013 gidx_t g = glb_idx(n);
1014
1015 if (coords_is_idx) {
1016 for (idx_t d = 0; d < surfdim; ++d) {
1017 xyz[d] = coords_idx(n, d);
1018 }
1019 }
1020 else {
1021 for (idx_t d = 0; d < surfdim; ++d) {
1022 xyz[d] = coords(n, d);
1023 }
1024 }
1025
1026 if (binary) {
1027 file.write(reinterpret_cast<const char*>(&g), sizeof(gidx_t));
1028 file.write(reinterpret_cast<const char*>(&xyz), sizeof(double) * 3);
1029 }
1030 else {
1031 file << g << " " << xyz[XX] << " " << xyz[YY] << " " << xyz[ZZ] << "\n";
1032 }
1033 }
1034 if (binary) {
1035 file << "\n";
1036 }
1037 file << "$EndNodes\n";
1038
1039 // Elements
1040 file << "$Elements\n";
1041 {
1042 std::vector<const mesh::HybridElements*> grouped_elements;
1043 if (options.get<bool>("elements")) {
1044 grouped_elements.push_back(&mesh.cells());
1045 }
1046 if (options.get<bool>("edges")) {
1047 grouped_elements.push_back(&mesh.edges());
1048 }
1049
1050 idx_t nb_elements(0);
1051 for (const mesh::HybridElements* hybrid : grouped_elements) {
1052 nb_elements += hybrid->size();
1053 const auto hybrid_halo = array::make_view<int, 1>(hybrid->halo());
1054 const auto hybrid_flags = array::make_view<int, 1>(hybrid->flags());
1055 const auto& node_connectivity = hybrid->node_connectivity();
1056
1057 auto include = [&](idx_t e) {
1058 auto topology = Topology::view(hybrid_flags(e));
1059 if (land_water_flag && not(include_water && include_land)) {
1060 if (include_water && !topology.check(Topology::WATER)) {
1061 return false;
1062 }
1063 if (include_land && !topology.check(Topology::LAND)) {
1064 return false;
1065 }
1066 }
1067 if (not include_ghost) {
1068 if (topology.check(Topology::GHOST) || hybrid_halo(e)) {
1069 return false;
1070 }
1071 }
1072 if (not include_patch) {
1073 if (topology.check(Topology::PATCH)) {
1074 return false;
1075 }
1076 }
1077 if (topology.check(Topology::INVALID)) {
1078 return false;
1079 }
1080
1081 if (coords_is_lonlat) {
1082 if (node_connectivity.cols(e) == 3) {
1083 auto x0 = [&]() { return coords(node_connectivity(e,0),LON); };
1084 auto x1 = [&]() { return coords(node_connectivity(e,1),LON); };
1085 auto x2 = [&]() { return coords(node_connectivity(e,2),LON); };
1086 auto y0 = [&]() { return coords(node_connectivity(e,0),LAT); };
1087 auto y1 = [&]() { return coords(node_connectivity(e,1),LAT); };
1088 auto y2 = [&]() { return coords(node_connectivity(e,2),LAT); };
1089 auto triangle_area = (x0() * (y1() - y2()) + x1() * (y2() - y0()) + x2() * (y0() - y1())) * 0.5;
1090 if (triangle_area <= 0 ) {
1091 return false;
1092 }
1093 // edge length comparison
1094 if (filter_edge_ratio > 0.) {
1095 auto dx10 = (x1()-x0());
1096 auto dx21 = (x2()-x1());
1097 auto dx02 = (x0()-x2());
1098 auto dy10 = (y1()-y0());
1099 auto dy21 = (y2()-y1());
1100 auto dy02 = (y0()-y2());
1101 auto d10 = dx10*dx10 + dy10*dy10;
1102 auto d21 = dx21*dx21 + dy21*dy21;
1103 auto d02 = dx02*dx02 + dy02*dy02;
1104 auto dmin = std::min(d10, std::min(d21, d02));
1105 auto dmax = std::max(d10, std::max(d21, d02));
1106 if (dmax > filter_edge_ratio * dmin) {
1107 return false;
1108 }
1109 }
1110 }
1111 }
1112 return true;
1113 };
1114
1115 for (idx_t e = 0; e < hybrid->size(); ++e) {
1116 if (not include(e)) {
1117 --nb_elements;
1118 }
1119 }
1120 }
1121
1122 file << nb_elements << "\n";
1123
1124 for (const mesh::HybridElements* hybrid : grouped_elements) {
1125 for (idx_t etype = 0; etype < hybrid->nb_types(); ++etype) {
1126 const mesh::Elements& elements = hybrid->elements(etype);
1127 const mesh::ElementType& element_type = elements.element_type();
1128 const mesh::BlockConnectivity& node_connectivity = elements.node_connectivity();
1129 size_t nb_nodes = node_connectivity.cols();
1130
1131 int gmsh_elem_type;
1132 if (element_type.name() == "Line") {
1133 gmsh_elem_type = 1;
1134 }
1135 else if (element_type.name() == "Triangle") {
1136 gmsh_elem_type = 2;
1137 }
1138 else if (element_type.name() == "Quadrilateral") {
1139 gmsh_elem_type = 3;
1140 }
1141 else if (element_type.name() == "Pentagon") {
1142 // Hack: treat as quadrilateral and ignore 5th point
1143 gmsh_elem_type = 3;
1144 nb_nodes = 4;
1145 }
1146 else {
1147 ATLAS_NOTIMPLEMENTED;
1148 }
1149
1150
1151 auto elems_glb_idx = elements.view<gidx_t, 1>(elements.global_index());
1152 auto elems_partition = elements.view<int, 1>(elements.partition());
1153
1154 auto elems_halo = elements.view<int, 1>(elements.halo());
1155 auto elems_flags = elements.view<int, 1>(elements.flags());
1156
1157 auto include = [&](idx_t e) {
1158 auto topology = Topology::view(elems_flags(e));
1159 if (land_water_flag && not(include_water && include_land)) {
1160 if (include_water && !topology.check(Topology::WATER)) {
1161 return false;
1162 }
1163 if (include_land && !topology.check(Topology::LAND)) {
1164 return false;
1165 }
1166 }
1167 if (not include_ghost) {
1168 if (topology.check(Topology::GHOST) || elems_halo(e)) {
1169 return false;
1170 }
1171 }
1172 if (not include_patch) {
1173 if (topology.check(Topology::PATCH)) {
1174 return false;
1175 }
1176 }
1177 if (topology.check(Topology::INVALID)) {
1178 return false;
1179 }
1180 if (coords_is_lonlat) {
1181 if (nb_nodes == 3) {
1182 auto x0 = [&]() { return coords(node_connectivity(e,0),LON); };
1183 auto x1 = [&]() { return coords(node_connectivity(e,1),LON); };
1184 auto x2 = [&]() { return coords(node_connectivity(e,2),LON); };
1185 auto y0 = [&]() { return coords(node_connectivity(e,0),LAT); };
1186 auto y1 = [&]() { return coords(node_connectivity(e,1),LAT); };
1187 auto y2 = [&]() { return coords(node_connectivity(e,2),LAT); };
1188 auto triangle_area = (x0() * (y1() - y2()) + x1() * (y2() - y0()) + x2() * (y0() - y1())) * 0.5;
1189 if (triangle_area <= 0 ) {
1190 return false;
1191 }
1192 // edge length comparison
1193 if (filter_edge_ratio > 0.) {
1194 auto dx10 = (x1()-x0());
1195 auto dx21 = (x2()-x1());
1196 auto dx02 = (x0()-x2());
1197 auto dy10 = (y1()-y0());
1198 auto dy21 = (y2()-y1());
1199 auto dy02 = (y0()-y2());
1200 auto d10 = dx10*dx10 + dy10*dy10;
1201 auto d21 = dx21*dx21 + dy21*dy21;
1202 auto d02 = dx02*dx02 + dy02*dy02;
1203 auto dmin = std::min(d10, std::min(d21, d02));
1204 auto dmax = std::max(d10, std::max(d21, d02));
1205 if (dmax > filter_edge_ratio * dmin) {
1206 return false;
1207 }
1208 }
1209 }
1210 }
1211 return true;
1212 };
1213 if (binary) {
1214 idx_t nb_elems = elements.size();
1215 if (!include_ghost) {
1216 for (idx_t elem = 0; elem < elements.size(); ++elem) {
1217 if (elems_halo(elem)) {
1218 --nb_elems;
1219 }
1220 }
1221 }
1222
1223 int header[3];
1224 int data[9];
1225 header[0] = gmsh_elem_type;
1226 header[1] = nb_elems;
1227 header[2] = 4; // nb_tags
1228 file.write(reinterpret_cast<const char*>(&header), sizeof(int) * 3);
1229 data[1] = 1;
1230 data[2] = 1;
1231 data[3] = 1;
1232 size_t datasize = sizeof(int) * (5 + nb_nodes);
1233 for (idx_t elem = 0; elem < nb_elems; ++elem) {
1234 if (include_ghost || !elems_halo(elem)) {
1235 data[0] = elems_glb_idx(elem);
1236 data[4] = elems_partition(elem);
1237 for (idx_t n = 0; n < nb_nodes; ++n) {
1238 data[5 + n] = glb_idx(node_connectivity(elem, n));
1239 }
1240 file.write(reinterpret_cast<const char*>(&data), datasize);
1241 }
1242 }
1243 }
1244 else {
1245 std::stringstream ss_elem_info;
1246 ss_elem_info << " " << gmsh_elem_type << " 4 1 1 1 ";
1247 std::string elem_info = ss_elem_info.str();
1248 for (idx_t elem = 0; elem < elements.size(); ++elem) {
1249 if (include(elem)) {
1250 file << elems_glb_idx(elem) << elem_info << elems_partition(elem);
1251 for (idx_t n = 0; n < nb_nodes; ++n) {
1252 file << " " << glb_idx(node_connectivity(elem, n));
1253 }
1254 file << "\n";
1255 }
1256 }
1257 }
1258 }
1259 }
1260 }
1261 if (binary) {
1262 file << "\n";
1263 }
1264 file << "$EndElements\n";
1265 file << std::flush;
1266
1267 // Optional mesh information file
1268 if (options.has("info") && options.get<bool>("info")) {
1269 PathName mesh_info(file_path);
1270 mesh_info = mesh_info.dirName() + "/" + mesh_info.baseName(false) + "_info.msh";
1271
1272 //[next] make NodesFunctionSpace accept const mesh
1273 functionspace::NodeColumns function_space(const_cast<Mesh&>(mesh));
1274
1275 FieldSet fieldset;
1276 auto lat =
1277 array::make_view<double, 1>(fieldset.add(Field("lat", array::make_datatype<double>(), {nodes.size()})));
1278 auto lon =
1279 array::make_view<double, 1>(fieldset.add(Field("lon", array::make_datatype<double>(), {nodes.size()})));
1280
1281 auto lonlat = array::make_view<double, 2>(nodes.lonlat());
1282 for (idx_t n = 0; n < nodes.size(); ++n) {
1283 lon(n) = lonlat(n, 0);
1284 lat(n) = lonlat(n, 1);
1285 }
1286 write(fieldset, function_space, mesh_info, std::ios_base::out);
1287 std::vector<std::string> extra_fields = {"partition", "water", "dual_volumes", "dual_delta_sph",
1288 "ghost", "halo", "remote_index"};
1289 for (auto& f : extra_fields) {
1290 if (nodes.has_field(f)) {
1291 write(nodes.field(f), function_space, mesh_info, std::ios_base::app);
1292 }
1293 }
1294
1295
1296 //[next] if( mesh.has_function_space("edges") )
1297 //[next] {
1298 //[next] FunctionSpace& edges = mesh.function_space( "edges" );
1299
1300 //[next] if (edges.has_field("dual_normals"))
1301 //[next] {
1302 //[next] write(edges.field("dual_normals"),mesh_info,std::ios_base::app);
1303 //[next] }
1304
1305 //[next] if (edges.has_field("skewness"))
1306 //[next] {
1307 //[next] write(edges.field("skewness"),mesh_info,std::ios_base::app);
1308 //[next] }
1309
1310 //[next] if (edges.has_field("arc_length"))
1311 //[next] {
1312 //[next] write(edges.field("arc_length"),mesh_info,std::ios_base::app);
1313 //[next] }
1314 //[next] }
1315 }
1316 file.close();
1317 }
1318
1319 // ----------------------------------------------------------------------------
1320 void GmshIO::write(const Field& field, const PathName& file_path, openmode mode) const {
1321 if (!field.functionspace()) {
1322 FieldSet fieldset;
1323 fieldset.add(field);
1324 write(fieldset, field.functionspace(), file_path, mode);
1325 }
1326
1327 else if (functionspace::NodeColumns(field.functionspace())) {
1328 FieldSet fieldset;
1329 fieldset.add(field);
1330 write(fieldset, field.functionspace(), file_path, mode);
1331 }
1332 else if (functionspace::StructuredColumns(field.functionspace())) {
1333 FieldSet fieldset;
1334 fieldset.add(field);
1335 write(fieldset, field.functionspace(), file_path, mode);
1336 }
1337 else if (functionspace::CellColumns(field.functionspace())) {
1338 FieldSet fieldset;
1339 fieldset.add(field);
1340 write(fieldset, field.functionspace(), file_path, mode);
1341 }
1342 else {
1343 std::stringstream msg;
1344 msg << "Field [" << field.name() << "] has functionspace [" << field.functionspace().type()
1345 << "] but requires a [functionspace::NodeColumns "
1346 << "or functionspace::StructuredColumns]";
1347
1348 throw_AssertionFailed(msg.str(), Here());
1349 }
1350 }
1351 // ----------------------------------------------------------------------------
1352
1353 // ----------------------------------------------------------------------------
1354 void GmshIO::write_delegate(const Field& field, const functionspace::NodeColumns& functionspace,
1355 const PathName& file_path, openmode mode) const {
1356 FieldSet fieldset;
1357 fieldset.add(field);
1358 write_delegate(fieldset, functionspace, file_path, mode);
1359 }
1360
1361 // ----------------------------------------------------------------------------
1362
1363 void GmshIO::write_delegate(const Field& field, const functionspace::NoFunctionSpace& functionspace,
1364 const eckit::PathName& file_path, GmshIO::openmode mode) const {
1365 FieldSet fieldset;
1366 fieldset.add(field);
1367 write_delegate(fieldset, functionspace, file_path, mode);
1368 }
1369
1370 // ----------------------------------------------------------------------------
1371
1372 void GmshIO::write_delegate(const Field& field, const functionspace::CellColumns& functionspace,
1373 const eckit::PathName& file_path, GmshIO::openmode mode) const {
1374 FieldSet fieldset;
1375 fieldset.add(field);
1376 write_delegate(fieldset, functionspace, file_path, mode);
1377 }
1378
1379 // ----------------------------------------------------------------------------
1380 void GmshIO::write_delegate(const Field& field, const functionspace::StructuredColumns& functionspace,
1381 const PathName& file_path, openmode mode) const {
1382 FieldSet fieldset;
1383 fieldset.add(field);
1384 write_delegate(fieldset, functionspace, file_path, mode);
1385 }
1386 // ----------------------------------------------------------------------------
1387
1388 // ----------------------------------------------------------------------------
1389 void GmshIO::write_delegate(const FieldSet& fieldset, const functionspace::NodeColumns& functionspace,
1390 const PathName& file_path, openmode mode) const {
1391 bool is_new_file = (mode != std::ios_base::app || !file_path.exists());
1392 bool binary(!options.get<bool>("ascii"));
1393 if (binary) {
1394 mode |= std::ios_base::binary;
1395 }
1396 bool gather = options.has("gather") ? options.get<bool>("gather") : false;
1397 GmshFile file(file_path, mode, gather ? -1 : int(mpi::rank()));
1398
1399 // Header
1400 if (is_new_file) {
1401 write_header_ascii(file);
1402 }
1403
1404 // field::Fields
1405 for (idx_t field_idx = 0; field_idx < fieldset.size(); ++field_idx) {
1406 const Field& field = fieldset[field_idx];
1407 Log::debug() << "writing field " << field.name() << " to gmsh file " << file_path << std::endl;
1408
1409 if (field.datatype() == array::DataType::int32()) {
1410 write_field_nodes<int>(options, functionspace, field, file);
1411 }
1412 else if (field.datatype() == array::DataType::int64()) {
1413 write_field_nodes<long>(options, functionspace, field, file);
1414 }
1415 else if (field.datatype() == array::DataType::real32()) {
1416 write_field_nodes<float>(options, functionspace, field, file);
1417 }
1418 else if (field.datatype() == array::DataType::real64()) {
1419 write_field_nodes<double>(options, functionspace, field, file);
1420 }
1421
1422 file << std::flush;
1423 }
1424 file.close();
1425 }
1426
1427 void GmshIO::write_delegate(const FieldSet& fieldset, const functionspace::NoFunctionSpace& functionspace,
1428 const eckit::PathName& file_path, GmshIO::openmode mode) const {
1429 bool is_new_file = (mode != std::ios_base::app || !file_path.exists());
1430 bool binary(!options.get<bool>("ascii"));
1431 if (binary) {
1432 mode |= std::ios_base::binary;
1433 }
1434 bool gather = options.has("gather") ? options.get<bool>("gather") : false;
1435 GmshFile file(file_path, mode, gather ? -1 : int(mpi::rank()));
1436
1437 // Header
1438 if (is_new_file) {
1439 write_header_ascii(file);
1440 }
1441
1442 // field::Fields
1443 for (idx_t field_idx = 0; field_idx < fieldset.size(); ++field_idx) {
1444 const Field& field = fieldset[field_idx];
1445 Log::debug() << "writing field " << field.name() << " to gmsh file " << file_path << std::endl;
1446
1447 if (field.datatype() == array::DataType::int32()) {
1448 write_field_nodes<int>(options, functionspace, field, file);
1449 }
1450 else if (field.datatype() == array::DataType::int64()) {
1451 write_field_nodes<long>(options, functionspace, field, file);
1452 }
1453 else if (field.datatype() == array::DataType::real32()) {
1454 write_field_nodes<float>(options, functionspace, field, file);
1455 }
1456 else if (field.datatype() == array::DataType::real64()) {
1457 write_field_nodes<double>(options, functionspace, field, file);
1458 }
1459
1460 file << std::flush;
1461 }
1462 file.close();
1463 }
1464
1465 void GmshIO::write_delegate(const FieldSet& fieldset, const functionspace::CellColumns& functionspace,
1466 const eckit::PathName& file_path, GmshIO::openmode mode) const {
1467 bool is_new_file = (mode != std::ios_base::app || !file_path.exists());
1468 bool binary(!options.get<bool>("ascii"));
1469 if (binary) {
1470 mode |= std::ios_base::binary;
1471 }
1472 bool gather = options.has("gather") ? options.get<bool>("gather") : false;
1473 GmshFile file(file_path, mode, gather ? -1 : int(mpi::rank()));
1474
1475 // Header
1476 if (is_new_file) {
1477 write_header_ascii(file);
1478 }
1479
1480 // field::Fields
1481 for (idx_t field_idx = 0; field_idx < fieldset.size(); ++field_idx) {
1482 const Field& field = fieldset[field_idx];
1483 Log::debug() << "writing field " << field.name() << " to gmsh file " << file_path << std::endl;
1484
1485 if (field.datatype() == array::DataType::int32()) {
1486 write_field_elems<int>(options, functionspace, field, file);
1487 }
1488 else if (field.datatype() == array::DataType::int64()) {
1489 write_field_elems<long>(options, functionspace, field, file);
1490 }
1491 else if (field.datatype() == array::DataType::real32()) {
1492 write_field_elems<float>(options, functionspace, field, file);
1493 }
1494 else if (field.datatype() == array::DataType::real64()) {
1495 write_field_elems<double>(options, functionspace, field, file);
1496 }
1497
1498 file << std::flush;
1499 }
1500 file.close();
1501 }
1502 // ----------------------------------------------------------------------------
1503
1504 // ----------------------------------------------------------------------------
1505 void GmshIO::write_delegate(const FieldSet& fieldset, const functionspace::StructuredColumns& functionspace,
1506 const PathName& file_path, openmode mode) const {
1507 bool is_new_file = (mode != std::ios_base::app || !file_path.exists());
1508 bool binary(!options.get<bool>("ascii"));
1509
1510 if (binary) {
1511 mode |= std::ios_base::binary;
1512 }
1513
1514 bool gather = options.has("gather") ? options.get<bool>("gather") : false;
1515
1516 GmshFile file(file_path, mode, gather ? -1 : int(mpi::rank()));
1517
1518 // Header
1519 if (is_new_file) {
1520 write_header_ascii(file);
1521 }
1522
1523 // field::Fields
1524 for (idx_t field_idx = 0; field_idx < fieldset.size(); ++field_idx) {
1525 const Field& field = fieldset[field_idx];
1526 Log::debug() << "writing field " << field.name() << " to gmsh file " << file_path << std::endl;
1527
1528 if (field.datatype() == array::DataType::int32()) {
1529 write_field_nodes<int>(options, functionspace, field, file);
1530 }
1531 else if (field.datatype() == array::DataType::int64()) {
1532 write_field_nodes<long>(options, functionspace, field, file);
1533 }
1534 else if (field.datatype() == array::DataType::real32()) {
1535 write_field_nodes<float>(options, functionspace, field, file);
1536 }
1537 else if (field.datatype() == array::DataType::real64()) {
1538 write_field_nodes<double>(options, functionspace, field, file);
1539 }
1540
1541 file << std::flush;
1542 }
1543
1544 file.close();
1545 }
1546 // ----------------------------------------------------------------------------
1547
1548 // ----------------------------------------------------------------------------
1549 void GmshIO::write(const FieldSet& fieldset, const FunctionSpace& funcspace, const eckit::PathName& file_path,
1550 openmode mode) const {
1551 mpi::Scope scope(funcspace.mpi_comm());
1552 if (functionspace::NodeColumns(funcspace)) {
1553 write_delegate(fieldset, functionspace::NodeColumns(funcspace), file_path, mode);
1554 }
1555 else if (functionspace::StructuredColumns(funcspace)) {
1556 write_delegate(fieldset, functionspace::StructuredColumns(funcspace), file_path, mode);
1557 }
1558 else if (functionspace::CellColumns(funcspace)) {
1559 write_delegate(fieldset, functionspace::CellColumns(funcspace), file_path, mode);
1560 }
1561 else if (not funcspace) {
1562 write_delegate(fieldset, functionspace::NoFunctionSpace(), file_path, mode);
1563 }
1564 else {
1565 ATLAS_NOTIMPLEMENTED;
1566 }
1567 }
1568 // ----------------------------------------------------------------------------
1569
1570 // ----------------------------------------------------------------------------
1571 void GmshIO::write(const Field& field, const FunctionSpace& funcspace, const eckit::PathName& file_path,
1572 openmode mode) const {
1573 mpi::Scope scope(funcspace.mpi_comm());
1574 if (functionspace::NodeColumns(funcspace)) {
1575 write_delegate(field, functionspace::NodeColumns(funcspace), file_path, mode);
1576 }
1577 else if (functionspace::StructuredColumns(funcspace)) {
1578 write_delegate(field, functionspace::StructuredColumns(funcspace), file_path, mode);
1579 }
1580 else if (functionspace::CellColumns(funcspace)) {
1581 write_delegate(field, functionspace::CellColumns(funcspace), file_path, mode);
1582 }
1583 else {
1584 ATLAS_NOTIMPLEMENTED;
1585 }
1586 }
1587 // ----------------------------------------------------------------------------
1588
1589 class GmshFortranInterface {
1590 public:
1591 static Mesh::Implementation* atlas__Gmsh__read(GmshIO* This, char* file_path);
1592 static void atlas__Gmsh__write(GmshIO* This, Mesh::Implementation* mesh, char* file_path);
1593 static Mesh::Implementation* atlas__read_gmsh(char* file_path);
1594 static void atlas__write_gmsh_mesh(const Mesh::Implementation* mesh, char* file_path);
1595 static void atlas__write_gmsh_fieldset(const field::FieldSetImpl* fieldset,
1596 functionspace::FunctionSpaceImpl* functionspace, char* file_path, int mode);
1597 static void atlas__write_gmsh_field(const field::FieldImpl* field, functionspace::FunctionSpaceImpl* functionspace,
1598 char* file_path, int mode);
1599 };
1600
1601 Mesh::Implementation* GmshFortranInterface::atlas__Gmsh__read(GmshIO* This, char* file_path) {
1602 Mesh::Implementation* m;
1603 {
1604 Mesh mesh = This->read(PathName(file_path));
1605 mesh.get()->attach();
1606 m = mesh.get();
1607 }
1608 m->detach();
1609 return m;
1610 }
1611
1612 void GmshFortranInterface::atlas__Gmsh__write(GmshIO* This, Mesh::Implementation* mesh, char* file_path) {
1613 Mesh m(mesh);
1614 This->write(m, PathName(file_path));
1615 }
1616
1617 Mesh::Implementation* GmshFortranInterface::atlas__read_gmsh(char* file_path) {
1618 Mesh::Implementation* m;
1619 {
1620 Mesh mesh = GmshIO().read(PathName(file_path));
1621 mesh.get()->attach();
1622 m = mesh.get();
1623 }
1624 m->detach();
1625 return m;
1626 }
1627
1628 void GmshFortranInterface::atlas__write_gmsh_mesh(const Mesh::Implementation* mesh, char* file_path) {
1629 GmshIO writer;
1630 writer.write(mesh, PathName(file_path));
1631 }
1632
1633 void GmshFortranInterface::atlas__write_gmsh_fieldset(const field::FieldSetImpl* fieldset,
1634 functionspace::FunctionSpaceImpl* functionspace, char* file_path,
1635 int /*mode*/) {
1636 GmshIO writer;
1637 writer.write(fieldset, functionspace, PathName(file_path));
1638 }
1639
1640 void GmshFortranInterface::atlas__write_gmsh_field(const field::FieldImpl* field,
1641 functionspace::FunctionSpaceImpl* functionspace, char* file_path,
1642 int /*mode*/) {
1643 GmshIO writer;
1644 writer.write(field, functionspace, PathName(file_path));
1645 }
1646
1647 extern "C" {
1648
1649 // ----------------------------------------------------------------------------
1650 // C wrapper interfaces to C++ routines
1651 // ----------------------------------------------------------------------------
1652 GmshIO* atlas__Gmsh__new() {
1653 return new GmshIO();
1654 }
1655
1656 void atlas__Gmsh__delete(GmshIO* This) {
1657 delete This;
1658 }
1659
1660 Mesh::Implementation* atlas__Gmsh__read(GmshIO* This, char* file_path) {
1661 return GmshFortranInterface::atlas__Gmsh__read(This, file_path);
1662 }
1663
1664 void atlas__Gmsh__write(GmshIO* This, Mesh::Implementation* mesh, char* file_path) {
1665 GmshFortranInterface::atlas__Gmsh__write(This, mesh, file_path);
1666 }
1667
1668 Mesh::Implementation* atlas__read_gmsh(char* file_path) {
1669 return GmshFortranInterface::atlas__read_gmsh(file_path);
1670 }
1671
1672 void atlas__write_gmsh_mesh(const Mesh::Implementation* mesh, char* file_path) {
1673 GmshFortranInterface::atlas__write_gmsh_mesh(mesh, file_path);
1674 }
1675
1676 void atlas__write_gmsh_fieldset(const field::FieldSetImpl* fieldset, functionspace::FunctionSpaceImpl* functionspace,
1677 char* file_path, int mode) {
1678 GmshFortranInterface::atlas__write_gmsh_fieldset(fieldset, functionspace, file_path, mode);
1679 }
1680
1681 void atlas__write_gmsh_field(const field::FieldImpl* field, functionspace::FunctionSpaceImpl* functionspace,
1682 char* file_path, int mode) {
1683 GmshFortranInterface::atlas__write_gmsh_field(field, functionspace, file_path, mode);
1684 }
1685 }
1686 // ----------------------------------------------------------------------------
1687
1688 } // namespace detail
1689 } // namespace output
1690 } // namespace atlas