Debian Codegraph @

src/atlas/grid/StructuredPartitionPolygon.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 "atlas/grid/StructuredPartitionPolygon.h"
14
15 #include <fstream>
16 #include <iomanip>
17 #include <sstream>
18 #include <string>
19
20 #include "atlas/array/MakeView.h"
21 #include "atlas/functionspace/StructuredColumns.h"
22 #include "atlas/parallel/mpi/mpi.h"
23 #include "atlas/runtime/Trace.h"
24 #include "atlas/util/CoordinateEnums.h"
25
26 namespace atlas {
27 namespace grid {
28
29 void compute(const functionspace::FunctionSpaceImpl& _fs, idx_t _halo, std::vector<Point2>& points,
30 std::vector<Point2>& bb) {
31 if (not dynamic_cast<const functionspace::detail::StructuredColumns*>(&_fs)) {
32 throw_Exception("Could not cast functionspace to StructuredColumns", Here());
33 }
34 const auto& fs = dynamic_cast<const functionspace::detail::StructuredColumns&>(_fs);
35 const auto grid = fs.grid();
36 const auto dom = RectangularDomain(grid.domain());
37
38 if (_halo > 0 && _halo != fs.halo()) {
39 throw_Exception("halo must zero or matching the one of the StructuredColumns", Here());
40 }
41
42 const int y_numbering = (grid.y().front() < grid.y().back()) ? +1 : -1;
43 bool jfirst_at_pole = y_numbering * 90. + grid.y(0) == 0.;
44 bool jlast_at_pole = y_numbering * 90. - grid.y(grid.ny() - 1) == 0;
45
46 auto compute_j = [&](const idx_t j) {
47 if (j < 0) {
48 return -j - 1 + jfirst_at_pole;
49 }
50 else if (j >= grid.ny()) {
51 return 2 * grid.ny() - j - 1 - jlast_at_pole;
52 }
53 return j;
54 };
55
56 auto compute_y = [&](const idx_t j) {
57 return fs.compute_xy(0,j).y();
58 };
59
60 auto compute_x = [&](const idx_t i, const idx_t j) {
61 return fs.compute_xy(i,j).x();
62 };
63
64 auto equal = [](const double& a, const double& b) { return std::abs(a - b) < 1.e-12; };
65
66 auto last_edge_horizontal = [&]() {
67 if (points.size() < 2) {
68 return false;
69 }
70 size_t size = points.size();
71 return equal(points.at(size - 1)[YY], points.at(size - 2)[YY]);
72 };
73 auto last_edge_vertical = [&]() {
74 if (points.size() < 2) {
75 return false;
76 }
77 size_t size = points.size();
78 return equal(points.at(size - 1)[XX], points.at(size - 2)[XX]);
79 };
80
81 PointXY p;
82 idx_t c{0};
83
84 auto add_point = [&](const Point2& point) {
85 points.emplace_back(point);
86 // Log::info() << "add point (" << points.size() - 1 << ") " << point << std::endl;
87 };
88
89 auto add_vertical_edge = [&](const Point2& point) {
90 if (last_edge_vertical()) {
91 points.back()[YY] = point[YY];
92 // Log::info() << "mod point (" << points.size() - 1 << ") " << point << std::endl;
93 }
94 else {
95 add_point(point);
96 c++;
97 }
98 };
99 auto add_horizontal_edge = [&](const Point2& point) {
100 if (last_edge_horizontal()) {
101 points.back()[XX] = point[XX];
102 // Log::info() << "mod point (" << points.size() - 1 << ") " << point << std::endl;
103 }
104 else {
105 add_point(point);
106 c++;
107 }
108 };
109
110 double ymax, ymin, xmax, xmin;
111 if (fs.j_begin() >= fs.j_end()) {
112 return;
113 }
114
115 // Top
116 // Top left point
117 {
118 idx_t j = _halo ? fs.j_begin_halo() : fs.j_begin();
119 idx_t i = _halo ? fs.i_begin_halo(j) : fs.i_begin(j);
120 if (j == 0 && _halo == 0) {
121 p[YY] = y_numbering < 0 ? dom.ymax() : dom.ymin();
122 }
123 else {
124 p[YY] = 0.5 * (compute_y(j - 1) + compute_y(j));
125 }
126 if (i == 0 && _halo == 0) {
127 p[XX] = dom.xmin();
128 }
129 else {
130 p[XX] = 0.5 * (compute_x(i - 1, j) + compute_x(i, j));
131 }
132 add_point(p);
133 }
134
135 // Top right point
136 {
137 idx_t j = _halo ? fs.j_begin_halo() : fs.j_begin();
138 idx_t i = _halo ? fs.i_end_halo(j) - 1 : fs.i_end(j) - 1;
139 if (j == 0 && _halo == 0) {
140 p[YY] = y_numbering < 0 ? dom.ymax() : dom.ymin();
141 }
142 else {
143 p[YY] = 0.5 * (compute_y(j - 1) + compute_y(j));
144 }
145 if (i == grid.nx(compute_j(j)) - 1 && _halo == 0) {
146 p[XX] = dom.xmax();
147 }
148 else {
149 p[XX] = 0.5 * (compute_x(i, j) + compute_x(i + 1, j));
150 }
151 add_horizontal_edge(p);
152
153 ymax = p[YY];
154 xmax = p[XX];
155 }
156 // Right side
157 {
158 idx_t j_begin = _halo ? fs.j_begin_halo() : fs.j_begin();
159 idx_t j_end = _halo ? fs.j_end_halo() : fs.j_end();
160 for (idx_t j = j_begin; j < j_end - 1 ; ++j) {
161 p[YY] = compute_y(j);
162 idx_t i = _halo ? fs.i_end_halo(j) - 1 : fs.i_end(j) - 1;
163 if (i == grid.nx(compute_j(j)) - 1 && _halo == 0) {
164 p[XX] = dom.xmax();
165 }
166 else {
167 p[XX] = 0.5 * (compute_x(i, j) + compute_x(i + 1, j));
168 }
169 if (p == points.back()) {
170 continue;
171 }
172 if (not equal(p[XX], points.back()[XX])) {
173 // Make a corner plus horizontal edge
174
175 PointXY ptmp = p;
176
177 // vertical edge
178 p[XX] = points.back()[XX];
179 p[YY] = 0.5 * (points.back()[YY] + p[YY]);
180 add_vertical_edge(p);
181 p = ptmp;
182
183 // horizontal edge
184 ptmp = p;
185 p[YY] = points.back()[YY];
186 add_horizontal_edge(p);
187 p = ptmp;
188 }
189 add_vertical_edge(p);
190
191 xmax = std::min(xmax, p[XX]);
192 }
193 }
194 // Bottom
195 // Bottom right point(s)
196 {
197 idx_t j = _halo ? fs.j_end_halo() - 1 : fs.j_end() - 1;
198 idx_t i = _halo ? fs.i_end_halo(j) - 1 : fs.i_end(j) - 1;
199
200 if (j == grid.ny() - 1 && _halo == 0) {
201 p[YY] = y_numbering < 0 ? dom.ymin() : dom.ymax();
202 }
203 else {
204 p[YY] = 0.5 * (compute_y(j) + compute_y(j + 1));
205 }
206 if (i == grid.nx(compute_j(j)) - 1 && _halo == 0) {
207 p[XX] = dom.xmax();
208 }
209 else {
210 p[XX] = 0.5 * (compute_x(i, j) + compute_x(i + 1, j));
211 }
212
213 ymin = p[YY];
214
215 PointXY pmin = p;
216
217 if (not equal(p[XX], points.back()[XX])) {
218 PointXY ptmp;
219 ptmp = p;
220 p[XX] = points.back()[XX];
221 p[YY] = 0.5 * (points.back()[YY] + compute_y(j));
222 add_vertical_edge(p);
223
224 pmin = p;
225 xmax = std::min(xmax, p[XX]);
226
227 p = ptmp;
228
229
230 ptmp = p;
231 p[YY] = points.back()[YY];
232
233 add_horizontal_edge(p);
234 p = ptmp;
235 }
236 if (xmax - grid.xspace().dx()[compute_j(j)] < compute_x(i, j)) {
237 xmax = std::min(xmax, 0.5 * (compute_x(i + 1, j) + compute_x(i, j)));
238 }
239 else {
240 ymin = pmin[YY];
241 }
242 add_vertical_edge(p);
243 }
244
245 // Bottom left point
246 {
247 idx_t j = _halo ? fs.j_end_halo() - 1 : fs.j_end() - 1;
248 idx_t i = _halo ? fs.i_begin_halo(j) : fs.i_begin(j);
249 if (j == grid.ny() - 1 && _halo == 0) {
250 p[YY] = y_numbering < 0 ? dom.ymin() : dom.ymax();
251 }
252 else {
253 p[YY] = 0.5 * (compute_y(j) + compute_y(j + 1));
254 }
255 if (i == 0 && _halo == 0) {
256 p[XX] = dom.xmin();
257 }
258 else {
259 p[XX] = 0.5 * (compute_x(i - 1, j) + compute_x(i, j));
260 }
261 add_horizontal_edge(p);
262 xmin = p[XX];
263 }
264 // Left side
265 {
266 idx_t j_end = _halo ? fs.j_end_halo() : fs.j_end();
267 idx_t j_begin = _halo ? fs.j_begin_halo() : fs.j_begin();
268 for (idx_t j = j_end - 1; j >= j_begin; --j) {
269 p[YY] = compute_y(j);
270 idx_t i = _halo ? fs.i_begin_halo(j) : fs.i_begin(j);
271 if (i == 0 && _halo == 0) {
272 p[XX] = dom.xmin();
273 }
274 else {
275 p[XX] = 0.5 * (compute_x(i - 1, j) + compute_x(i, j));
276 }
277
278 if (j > j_begin) {
279 xmin = std::max(xmin, p[XX]);
280 }
281 if (j == j_begin && xmin < points[0][XX]) {
282 idx_t jtop = j_begin;
283 idx_t itop = _halo ? fs.i_begin_halo(jtop) : fs.i_begin(jtop);
284 if (xmin + grid.xspace().dx()[compute_j(jtop)] > compute_x(itop, jtop)) {
285 xmin = std::max(xmin, 0.5 * (compute_x(itop - 1, jtop) + compute_x(itop, jtop)));
286 }
287 else {
288 ymax = 0.5 * (p[YY] + compute_y(jtop+1));
289 }
290 }
291
292 if (p == points.back()) {
293 continue;
294 }
295
296 if (not equal(p[XX], points.back()[XX])) {
297 PointXY ptmp;
298 ptmp = p;
299
300 // vertical edge
301 p[XX] = points.back()[XX];
302 p[YY] = 0.5 * (points.back()[YY] + compute_y(j));
303 add_vertical_edge(p);
304 p = ptmp;
305
306 // horizontal edge
307 ptmp = p;
308 p[YY] = points.back()[YY];
309 add_horizontal_edge(p);
310 p = ptmp;
311 }
312
313 add_vertical_edge(p);
314 }
315 }
316 // Connect to top
317 if (last_edge_vertical()) {
318 points.pop_back();
319 c--;
320 }
321 add_point(points.front());
322
323 bb = std::vector<Point2>{{xmin, ymax}, {xmin, ymin}, {xmax, ymin}, {xmax, ymax}, {xmin, ymax}};
324 }
325
326 StructuredPartitionPolygon::StructuredPartitionPolygon(const functionspace::FunctionSpaceImpl& fs, idx_t halo):
327 fs_(fs), halo_(halo) {
328 ATLAS_TRACE("StructuredPartitionPolygon");
329 compute(fs, halo, points_, inner_bounding_box_);
330 auto min = Point2(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
331 auto max = Point2(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest());
332 for (int i = 0; i < static_cast<int>(inner_bounding_box_.size()) - 1; ++i) {
333 min = Point2::componentsMin(min, inner_bounding_box_[i]);
334 max = Point2::componentsMax(max, inner_bounding_box_[i]);
335 }
336 inscribed_domain_ = {{min[XX], max[XX]}, {min[YY], max[YY]}};
337 }
338
339 size_t StructuredPartitionPolygon::footprint() const {
340 size_t size = sizeof(*this);
341 size += capacity() * sizeof(idx_t);
342 return size;
343 }
344
345 void StructuredPartitionPolygon::outputPythonScript(const eckit::PathName& filepath,
346 const eckit::Configuration& config) const {
347 ATLAS_TRACE("Output PartitionPolygon");
348 const auto& comm = atlas::mpi::comm(fs_.mpi_comm());
349 int mpi_rank = int(comm.rank());
350 int mpi_size = int(comm.size());
351
352 auto xy = array::make_view<double, 2>(dynamic_cast<const functionspace::detail::StructuredColumns&>(fs_).xy());
353
354 const std::vector<Point2>& points = config.getBool("inner_bounding_box", false) ? inner_bounding_box_ : points_;
355
356 double xmin = std::numeric_limits<double>::max();
357 double xmax = -std::numeric_limits<double>::max();
358 for (size_t i = 0; i < points.size(); ++i) {
359 xmin = std::min(xmin, points[i][XX]);
360 xmax = std::max(xmax, points[i][XX]);
361 }
362 comm.allReduceInPlace(xmin, eckit::mpi::min());
363 comm.allReduceInPlace(xmax, eckit::mpi::max());
364
365 idx_t count = dynamic_cast<const functionspace::detail::StructuredColumns&>(fs_).sizeOwned();
366 idx_t count_all = count;
367 comm.allReduceInPlace(count_all, eckit::mpi::sum());
368
369 bool plot_nodes = config.getBool("nodes", false);
370 for (int r = 0; r < mpi_size; ++r) {
371 // clang-format off
372 if ( mpi_rank == r ) {
373 std::ofstream f( filepath.asString().c_str(), mpi_rank == 0 ? std::ios::trunc : std::ios::app );
374 ATLAS_ASSERT( f.is_open() );
375 if ( mpi_rank == 0 ) {
376 f << "\n" "import sys"
377 "\n"
378 "\n" "# Configuration option to plot nodes"
379 "\n" "plot_nodes = False"
380 "\n" "for argv in sys.argv[1:] :"
381 "\n" " if argv == \"--nodes\" :"
382 "\n" " plot_nodes = " + std::string( plot_nodes ? "True" : "False" ) +
383 "\n"
384 "\n" "import matplotlib.pyplot as plt"
385 "\n" "from matplotlib.path import Path"
386 "\n" "import matplotlib.patches as patches"
387 "\n"
388 "\n" "from itertools import cycle"
389 "\n" "import matplotlib.cm as cm"
390 "\n" "import numpy as np"
391 "\n" "colours = cycle([cm.Paired(i) for i in np.linspace(0,1,12,endpoint=True)])"
392 "\n"
393 "\n" "fig = plt.figure()"
394 "\n" "ax = fig.add_subplot(111,aspect='equal')"
395 "\n";
396 }
397 if (points.size() > 0) {
398 f << "\n" "verts_" << r << " = [";
399 for ( size_t i=0; i<points.size(); ++i ) {
400 f << "\n (" << points[i][XX] << ", " << points[i][YY] << "), ";
401 }
402 f << "\n]"
403 "\n"
404 "\n" "codes_" << r << " = [Path.MOVETO]"
405 "\n" "codes_" << r << ".extend([Path.LINETO] * " << ( points.size() - 2 ) << ")"
406 "\n" "codes_" << r << ".extend([Path.CLOSEPOLY])"
407 "\n"
408 "\n" "count_" << r << " = " << count <<
409 "\n" "count_all_" << r << " = " << count_all <<
410 "\n";
411 if ( plot_nodes ) {
412 f << "\n" "x_" << r << " = [";
413 for ( idx_t i = 0; i < count; ++i ) {
414 f << xy( i, XX ) << ", ";
415 }
416 f << "]"
417 "\n" "y_" << r << " = [";
418 for ( idx_t i = 0; i < count; ++i ) {
419 f << xy( i, YY ) << ", ";
420 }
421 f << "]";
422 }
423 f << "\n"
424 "\n" "c = next(colours)"
425 "\n" "ax.add_patch(patches.PathPatch(Path(verts_" << r << ", codes_" << r << "), edgecolor=c, facecolor=c, alpha=0.3, lw=1))";
426 if ( plot_nodes ) {
427 f << "\n" "if plot_nodes:"
428 "\n" " ax.scatter(x_" << r << ", y_" << r << ", color=c, marker='o')";
429 }
430 f << "\n";
431 }
432 if ( mpi_rank == mpi_size - 1 ) {
433 if (fs_.projection().units() == "degrees") {
434 f << "\n" "ax.set_xlim( " << xmin << "-5, " << xmax << "+5)"
435 "\n" "ax.set_ylim(-90-5, 90+5)"
436 "\n" "ax.set_xticks([0,45,90,135,180,225,270,315,360])"
437 "\n" "ax.set_yticks([-90,-45,0,45,90])";
438 }
439 else {
440 f << "\n" "ax.autoscale()";
441 }
442 f << "\n" "plt.grid()"
443 "\n" "plt.show()";
444 }
445 }
446 // clang-format on
447 comm.barrier();
448 }
449 }
450
451 util::PartitionPolygon::PointsXY StructuredPartitionPolygon::xy() const {
452 return points_;
453 }
454
455 util::PartitionPolygon::PointsXY StructuredPartitionPolygon::lonlat() const {
456 return points_;
457 }
458
459 void StructuredPartitionPolygon::allGather(util::PartitionPolygons& polygons_) const {
460 ATLAS_TRACE();
461
462 const auto& comm = mpi::comm(fs_.mpi_comm());
463 const int mpi_size = int(comm.size());
464
465 polygons_.clear();
466 polygons_.reserve(mpi_size);
467
468 auto& poly = *this;
469
470 std::vector<double> mypolygon;
471 mypolygon.reserve(poly.size() * 2);
472
473 for (auto& p : poly.xy()) {
474 mypolygon.push_back(p[XX]);
475 mypolygon.push_back(p[YY]);
476 }
477
478 eckit::mpi::Buffer<double> recv_polygons(mpi_size);
479
480 comm.allGatherv(mypolygon.begin(), mypolygon.end(), recv_polygons);
481
482 for (idx_t p = 0; p < mpi_size; ++p) {
483 PointsXY recv_points;
484 recv_points.reserve(recv_polygons.counts[p]);
485 for (idx_t j = 0; j < recv_polygons.counts[p] / 2; ++j) {
486 PointXY pxy(*(recv_polygons.begin() + recv_polygons.displs[p] + 2 * j + XX),
487 *(recv_polygons.begin() + recv_polygons.displs[p] + 2 * j + YY));
488 recv_points.push_back(pxy);
489 }
490 polygons_.emplace_back(new util::ExplicitPartitionPolygon(std::move(recv_points)));
491 }
492 }
493
494 // void StructuredPartitionPolygon::print( std::ostream& out ) const {
495 // out << "polygon:{"
496 // << "halo:" << halo_ << ",size:" << polygon_.size() << ",nodes:" << static_cast<const util::Polygon&>( polygon_ )
497 // << "}";
498 // }
499
500 // ----------------------------------------------------------------------------
501
502 } // namespace grid
503 } // namespace atlas