YAC 3.12.0
Yet Another Coupler
Loading...
Searching...
No Matches
core.pyx
Go to the documentation of this file.
1# Copyright (c) 2024 The YAC Authors
2#
3# SPDX-License-Identifier: BSD-3-Clause
4
5import cython
6import numpy as _np
7from libc.stdint cimport SIZE_MAX
8from cython cimport view
9from libc.stdlib cimport malloc, free
10from warnings import warn
11from collections import namedtuple
12from types import coroutine
13import logging
14
15logger = logging.getLogger("yac.core")
16logger.addHandler(logging.NullHandler())
17
18cdef extern from "Python.h":
19 int Py_AtExit(void (*)())
20
21cdef extern from "<mpi.h>" nogil:
22 ctypedef void* MPI_Comm
23 MPI_Comm MPI_Comm_f2c(int)
24 MPI_Comm MPI_COMM_WORLD
25 MPI_Comm MPI_COMM_NULL
26
27cdef extern from "yac_types.h":
28 ctypedef int yac_int;
29 ctypedef double(*yac_coordinate_pointer)[3];
30
31cdef extern from "location.h":
32 cpdef enum yac_location:
33 YAC_LOC_CELL
34 YAC_LOC_CORNER
35 YAC_LOC_EDGE
36 YAC_LOC_UNDEFINED
37
38cdef extern from "interpolation/methods/interp_method_avg.h":
39 cpdef enum yac_interp_avg_weight_type:
40 YAC_INTERP_AVG_ARITHMETIC
41 YAC_INTERP_AVG_DIST
42 YAC_INTERP_AVG_BARY
43 cdef yac_interp_avg_weight_type YAC_INTERP_AVG_WEIGHT_TYPE_DEFAULT
44 cdef int YAC_INTERP_AVG_PARTIAL_COVERAGE_DEFAULT
45
46cdef extern from "interpolation/methods/interp_method_ncc.h":
47 cpdef enum yac_interp_ncc_weight_type:
48 YAC_INTERP_NCC_AVG
49 YAC_INTERP_NCC_DIST
50 cdef yac_interp_ncc_weight_type YAC_INTERP_NCC_WEIGHT_TYPE_DEFAULT
51 cdef int YAC_INTERP_NCC_PARTIAL_COVERAGE_DEFAULT
52
53cdef extern from "interpolation/methods/interp_method_conserv.h":
54 cpdef enum yac_interp_method_conserv_normalisation:
55 YAC_INTERP_CONSERV_DESTAREA
56 YAC_INTERP_CONSERV_FRACAREA
57 cdef int YAC_INTERP_CONSERV_ORDER_DEFAULT
58 cdef int YAC_INTERP_CONSERV_ENFORCED_CONSERV_DEFAULT
59 cdef int YAC_INTERP_CONSERV_PARTIAL_COVERAGE_DEFAULT
60 cdef yac_interp_method_conserv_normalisation YAC_INTERP_CONSERV_NORMALISATION_DEFAULT
61
62cdef extern from "interpolation/methods/interp_method_spmap.h":
63 cpdef enum yac_interp_spmap_weight_type:
64 YAC_INTERP_SPMAP_AVG
65 YAC_INTERP_SPMAP_DIST
66 cpdef enum yac_interp_spmap_scale_type:
67 YAC_INTERP_SPMAP_NONE
68 YAC_INTERP_SPMAP_SRCAREA
69 YAC_INTERP_SPMAP_INVTGTAREA
70 YAC_INTERP_SPMAP_FRACAREA
71 cpdef enum yac_interp_spmap_cell_area_provider:
72 YAC_INTERP_SPMAP_CELL_AREA_FILE
73 YAC_INTERP_SPMAP_CELL_AREA_YAC
74 cdef double YAC_INTERP_SPMAP_SPREAD_DISTANCE_DEFAULT
75 cdef double YAC_INTERP_SPMAP_MAX_SEARCH_DISTANCE_DEFAULT
76 cdef yac_interp_spmap_weight_type YAC_INTERP_SPMAP_WEIGHTED_DEFAULT
77 cdef yac_interp_spmap_scale_type YAC_INTERP_SPMAP_SCALE_TYPE_DEFAULT
78 cdef double YAC_INTERP_SPMAP_SPHERE_RADIUS_DEFAULT
79 cdef const char* YAC_INTERP_SPMAP_FILENAME_DEFAULT
80 cdef const char* YAC_INTERP_SPMAP_VARNAME_DEFAULT
81 cdef int YAC_INTERP_SPMAP_MIN_GLOBAL_ID_DEFAULT
82
83cdef extern from "interpolation/methods/interp_method_nnn.h":
84 cpdef enum yac_interp_nnn_weight_type:
85 YAC_INTERP_NNN_AVG #< average of n source points
86 YAC_INTERP_NNN_DIST #< distance weighted average of n source points
87 YAC_INTERP_NNN_GAUSS #< distance with Gauss weights of n source points
88 YAC_INTERP_NNN_RBF #< radial basis functions
89 YAC_INTERP_NNN_ZERO #< all weights are set to zero
90 cdef yac_interp_nnn_weight_type YAC_INTERP_NNN_WEIGHTED_DEFAULT
91 cdef int YAC_INTERP_NNN_N_DEFAULT
92 cdef double YAC_INTERP_NNN_MAX_SEARCH_DISTANCE_DEFAULT
93 cdef double YAC_INTERP_NNN_GAUSS_SCALE_DEFAULT
94 cdef int YAC_INTERP_RBF_N_DEFAULT
95 cdef double YAC_INTERP_RBF_MAX_SEARCH_DISTANCE_DEFAULT
96 cdef double YAC_INTERP_RBF_SCALE_DEFAULT
97 cdef int YAC_INTERP_RBF_KERNEL_DEFAULT
98
99cdef extern from "interpolation/methods/interp_method_file.h":
100 cpdef enum yac_interp_file_on_missing_file:
101 YAC_INTERP_FILE_MISSING_ERROR
102 YAC_INTERP_FILE_MISSING_CONT
103 cpdef enum yac_interp_file_on_success:
104 YAC_INTERP_FILE_SUCCESS_STOP
105 YAC_INTERP_FILE_SUCCESS_CONT
106 cdef yac_interp_file_on_missing_file YAC_INTERP_FILE_ON_MISSING_FILE_DEFAULT
107 cdef yac_interp_file_on_success YAC_INTERP_FILE_ON_SUCCESS_DEFAULT
108
109cdef extern from "interpolation/methods/interp_method_check.h":
110 cdef const char* YAC_INTERP_CHECK_CONSTRUCTOR_KEY_DEFAULT
111 cdef const char* YAC_INTERP_CHECK_DO_SEARCH_KEY_DEFAULT
112
113cdef extern from "interpolation/methods/interp_method_creep.h":
114 cdef int YAC_INTERP_CREEP_DISTANCE_DEFAULT
115
116cdef extern from "grids/basic_grid_data.h":
117 struct yac_basic_grid_data:
118 yac_int * cell_ids;
119 yac_int * vertex_ids;
120 yac_int * edge_ids;
121 int * core_cell_mask;
122 int * core_vertex_mask;
123 int * core_edge_mask;
124cdef extern from "grids/basic_grid.h" nogil:
125 struct yac_basic_grid:
126 pass
127 yac_basic_grid_data * yac_basic_grid_get_data(
128 yac_basic_grid * grid);
129 struct yac_interp_field:
130 yac_location location
131 size_t coordinates_idx
132 size_t masks_idx
134 yac_basic_grid * grid,
135 const char * filename,
136 MPI_Comm comm)
137 const char * yac_basic_grid_get_name(yac_basic_grid * grid);
138 size_t yac_basic_grid_get_data_size(yac_basic_grid * grid, yac_location location);
139 void yac_basic_grid_delete(yac_basic_grid * grid);
141 yac_basic_grid * grid, yac_location location,
142 yac_coordinate_pointer coordinates, size_t count);
144 yac_basic_grid * grid, yac_location location,
145 const int * mask, size_t count, const char * mask_name);
146 yac_basic_grid * yac_basic_grid_reg_2d_new(
147 const char * name, size_t nbr_vertices[2], int cyclic[2],
148 double *lon_vertices, double *lat_vertices)
149 yac_basic_grid * yac_basic_grid_empty_new(const char* name)
150 yac_basic_grid * yac_basic_grid_unstruct_new(
151 const char * name, size_t nbr_vertices, size_t nbr_cells,
152 int *num_vertices_per_cell, double *x_vertices, double *y_vertices,
153 int *cell_to_vertex);
154 yac_basic_grid * yac_basic_grid_unstruct_ll_new(
155 const char * name, size_t nbr_vertices, size_t nbr_cells,
156 int *num_vertices_per_cell, double *x_vertices, double *y_vertices,
157 int *cell_to_vertex);
158 yac_basic_grid * yac_basic_grid_unstruct_edge_new(
159 const char * name, size_t nbr_vertices, size_t nbr_cells, size_t nbr_edges,
160 int *num_edges_per_cell, double *x_vertices, double *y_vertices,
161 int *cell_to_edge, int *edge_to_vertex);
163 const char * name, size_t nbr_vertices, size_t nbr_cells, size_t nbr_edges,
164 int *num_edges_per_cell, double *x_vertices, double *y_vertices,
165 int *cell_to_edge, int *edge_to_vertex);
166
167cdef extern from "read_icon_grid.h" nogil:
169 const char * filename, const char * gridname, MPI_Comm comm,
170 yac_basic_grid ** basic_grid, size_t * cell_coordinate_idx,
171 int ** cell_mask)
172
173cdef extern from "read_scrip_grid.h" nogil:
174 yac_basic_grid * yac_read_scrip_basic_grid(
175 const char * grid_filename, const char * mask_filename,
176 const char * grid_name, int valid_mask_value, const char * name,
177 int use_ll_edges, size_t * cell_coord_idx,
178 size_t ** duplicated_cell_idx, yac_int ** orig_cell_global_ids,
179 size_t * nbr_duplicated_cells);
180
181cdef extern from "grids/dist_grid.h":
182 struct yac_dist_grid_pair:
183 pass
184 yac_dist_grid_pair * yac_dist_grid_pair_new(
185 yac_basic_grid * grid_a, yac_basic_grid * grid_b,
186 MPI_Comm comm);
187 void yac_dist_grid_pair_delete(yac_dist_grid_pair * grid_pair);
188
189cdef extern from "interpolation/interp_grid.h":
190 struct yac_interp_grid:
191 pass
192 yac_interp_grid * yac_interp_grid_new(
193 yac_dist_grid_pair * grid_pair,
194 const char * src_grid_name, const char * tgt_grid_name,
195 size_t num_src_fields, const yac_interp_field * src_fields,
196 const yac_interp_field tgt_field);
197 void yac_interp_grid_delete(yac_interp_grid * interp_grid);
198
199cdef extern from "interpolation/methods/interp_method.h" nogil:
200 struct interp_method:
201 pass
202 yac_interp_weights * yac_interp_method_do_search(
203 interp_method ** method, yac_interp_grid * grid);
204 void yac_interp_method_delete(interp_method ** method);
205
206cdef extern from "interpolation/interp_stack_config.h":
207 struct yac_interp_stack_config:
208 pass
209 struct yac_interp_method:
210 pass
211 yac_interp_stack_config * yac_interp_stack_config_new();
213 yac_interp_stack_config * interp_stack_config);
214 interp_method ** yac_interp_stack_config_generate(
215 yac_interp_stack_config * interp_stack);
216
218 yac_interp_stack_config * interp_stack_config,
219 yac_interp_avg_weight_type reduction_type, int partial_coverage);
221 yac_interp_stack_config * interp_stack_config,
222 yac_interp_ncc_weight_type type, int partial_coverage);
224 yac_interp_stack_config * interp_stack_config,
225 yac_interp_nnn_weight_type type, size_t n,
226 double max_search_distance, double scale);
228 yac_interp_stack_config * interp_stack_config,
229 int order, int enforced_conserv, int partial_coverage,
230 yac_interp_method_conserv_normalisation normalisation);
232 yac_interp_stack_config * interp_stack_config,
233 double spread_distance, double max_search_distance,
234 yac_interp_spmap_weight_type weight_type,
235 yac_interp_spmap_scale_type scale_type,
236 double src_sphere_radius, const char * src_filename,
237 const char * src_varname, int src_min_global_id,
238 double tgt_sphere_radius, const char * tgt_filename,
239 const char * tgt_varname, int tgt_min_global_id);
241 yac_interp_stack_config * interp_stack_config, double value);
243 yac_interp_stack_config * interp_stack_config,
244 const char * filename, yac_interp_file_on_missing_file on_missing_file,
245 yac_interp_file_on_success on_success);
247 yac_interp_stack_config * interp_stack_config,
248 const char * constructor_key, const char * do_search_key);
250 yac_interp_stack_config * interp_stack_config);
252 yac_interp_stack_config * interp_stack_config,
253 size_t n, double max_search_distance, double scale);
255 yac_interp_stack_config * interp_stack_config, int creep_distance);
256
257cdef extern from "interpolation/interpolation.h" nogil:
258 struct yac_interpolation:
259 pass
261 yac_interpolation * interp, double *** src_fields,
262 double *** src_frac_masks, double ** tgt_field);
264 yac_interpolation * interp, double *** src_fields, double *** src_frac_masks);
265 int yac_interpolation_execute_put_test(yac_interpolation * interp);
267 yac_interpolation * interp, double ** tgt_field);
268 int yac_interpolation_execute_get_test(yac_interpolation * interp);
269
270cdef extern from "collection_selection.h":
271 struct yac_collection_selection:
272 pass
273 yac_collection_selection * yac_collection_selection_new(
274 size_t collection_size, const size_t * selection_indices);
276 yac_collection_selection * collection_selection);
277
278cdef extern from "interpolation/interpolation_gen_config.h":
279 cpdef enum yac_interp_weights_reorder_type:
280 YAC_MAPPING_ON_SRC
281 YAC_MAPPING_ON_TGT
282 struct yac_interpolation_gen_config:
283 pass
284 yac_interpolation_gen_config * yac_interpolation_gen_config_new();
285 void yac_interpolation_gen_config_delete(yac_interpolation_gen_config * config);
286 void yac_interpolation_gen_config_set_reorder(yac_interpolation_gen_config * config, yac_interp_weights_reorder_type reorder)
287 void yac_interpolation_gen_config_set_collection_size(yac_interpolation_gen_config * config, size_t collection_size);
289 yac_interpolation_gen_config * config,
290 const yac_collection_selection * collection_selection);
292 yac_interpolation_gen_config * config,
293 double frac_mask_fallback_value);
295 yac_interpolation_gen_config * config, double scaling_factor);
297 yac_interpolation_gen_config * config, double scaling_summand);
299 yac_interpolation_gen_config * config, const char * name);
300
301cdef extern from "interpolation/interp_weights.h" nogil:
302 struct yac_interp_weights:
303 pass
304 cpdef enum yac_weight_file_on_existing:
305 YAC_WEIGHT_FILE_ERROR
306 YAC_WEIGHT_FILE_KEEP
307 YAC_WEIGHT_FILE_OVERWRITE
308 YAC_WEIGHT_FILE_UNDEFINED
310 yac_interp_weights * weights, const char * filename,
311 const char * src_grid_name, const char * tgt_grid_name,
312 size_t src_grid_size, size_t tgt_grid_size,
313 yac_weight_file_on_existing on_existing);
315 const yac_interp_weights * weights,
316 const yac_interpolation_gen_config * interp_gen_config,
317 int is_source, int is_target);
318
319cdef extern from "yac_mpi.h":
320 void yac_yaxt_init(MPI_Comm comm);
321 void yac_mpi_init();
322 void yac_mpi_finalize();
323
324cdef extern from "io_utils.h" nogil:
325 void yac_get_io_ranks(
326 MPI_Comm comm, int * local_is_io, int ** io_ranks, int * num_io_ranks);
327
328def lonlat2xyz(lon, lat):
329 clat = _np.cos(lat)
330 slat = _np.sin(lat)
331 return clat * _np.cos(lon), clat * _np.sin(lon), slat
332
333cdef _decode(const char* c_str):
334 if c_str == NULL:
335 return None
336 return bytes.decode(c_str)
337
338cdef int get_c_comm(comm, MPI_Comm* c_comm) except -1:
339 """
340 Convert comm into an MPI_Comm.
341 Comm can be given as an fortran comm (int) or as an mpi4py.Comm
342 """
343 try:
344 from mpi4py import MPI
345 if isinstance(comm, MPI.Comm):
346 comm = comm.py2f()
347 except:
348 pass
349 if comm is None:
350 c_comm[0] = MPI_COMM_WORLD
351 elif isinstance(comm, int):
352 c_comm[0] = MPI_Comm_f2c(comm)
353 else:
354 raise ValueError("Invalid communicator")
355
356 return 0
357
359 cdef yac_int tmp;
360 dtype = _np.asarray(<yac_int[:1]>&tmp).dtype
361 assert dtype.itemsize == sizeof(yac_int), "dtype detected did not work"
362 info = _np.iinfo(dtype)
363 assert _np.min(arr) >= info.min and _np.max(arr) <= info.max, \
364 f"Indices must be within the valid range for yac_int ({info.min:_} to {info.max:_})"
365 return _np.ascontiguousarray(arr, dtype=dtype)
366
367
368logger.info("Initializing MPI")
370logger.info("Initializing yaxt")
371yac_yaxt_init(MPI_COMM_WORLD);
372
373Coordinates = namedtuple("Coordinates", ["basic_grid", "location", "coord_idx"])
374Mask = namedtuple("Mask", ["basic_grid", "location", "mask_idx"])
375
376cdef class BasicGrid:
377 cdef yac_basic_grid* _ptr;
378
379 def __init__(self, yac_basic_grid_ptr):
380 raise TypeError("This class cannot be instantiated directly.")
381
382 def __del__(self):
383 logger.info("calling yac_basic_grid_delete")
385
386 @staticmethod
387 cdef BasicGrid from_ptr(yac_basic_grid* basic_grid_ptr):
388 cdef BasicGrid basic_grid = BasicGrid.__new__(BasicGrid)
389 basic_grid._ptr = basic_grid_ptr
390 return basic_grid
391
392 def to_file(self, filename, comm=None):
393 filename_bytes = filename.encode()
394 cdef const char* _filename = filename_bytes
395 cdef MPI_Comm c_comm = MPI_COMM_NULL
396 get_c_comm(comm, &c_comm)
397 logger.info("calling yac_basic_grid_to_file_parallel")
398 with nogil:
400 _filename,
401 c_comm);
402
403 @property
404 def name(self):
405 cdef const char * _name = yac_basic_grid_get_name(self._ptr);
406 return _decode(_name)
407
408 def __str__(self):
409 return f"yac_basic_grid(name={self.name})"
410
411 def get_data_size(self, location : yac_location):
412 logger.info("calling yac_basic_grid_get_data_size")
413 return yac_basic_grid_get_data_size(self._ptr, location);
414
416 location : yac_location,
417 indices):
418 cdef yac_basic_grid_data* data
419 cdef yac_int** grid_global_ids;
420 cdef size_t count = self.get_data_size(location)
421 indices = _to_yac_int_np_array(indices)
422 data = yac_basic_grid_get_data(self._ptr)
423 assert indices.shape == (count,), "Wrong indices shape"
424 if location == YAC_LOC_CELL:
425 grid_global_ids = &(data.cell_ids)
426 elif location == YAC_LOC_CORNER:
427 grid_global_ids = &(data.vertex_ids)
428 elif location == YAC_LOC_EDGE:
429 grid_global_ids = &(data.edge_ids)
430 else:
431 raise RuntimeError("Invalid location")
432 if grid_global_ids[0] == NULL:
433 grid_global_ids[0] = <yac_int*>malloc(count * sizeof(yac_int));
434 logger.info("setting global index")
435 (<yac_int[:count]>(grid_global_ids[0]))[:] = indices
436
437 def set_core_mask(self, location :yac_location, mask):
438 cdef yac_basic_grid_data* data
439 cdef int** grid_core_mask;
440 cdef int count = self.get_data_size(location)
441 data = yac_basic_grid_get_data(self._ptr)
442 mask = _np.ascontiguousarray(mask, dtype=_np.intc)
443 assert mask.shape == (count,), "Wrong mask shape"
444 if location == YAC_LOC_CELL:
445 grid_core_mask = &(data.core_cell_mask)
446 elif location == YAC_LOC_CORNER:
447 grid_core_mask = &(data.core_vertex_mask)
448 elif location == YAC_LOC_EDGE:
449 grid_core_mask = &(data.core_edge_mask)
450 else:
451 raise RuntimeError("Invalid location")
452 if grid_core_mask[0] == NULL:
453 grid_core_mask[0] = <int*>malloc(count * sizeof(int));
454 logger.info("setting core mask")
455 (<int[:count]>(grid_core_mask[0]))[:] = mask
456
458 location : yac_location,
459 lon = None,
460 lat = None):
461 assert (lon is None) == (lat is None), "lon and lat must both be either set or unset."
462 cdef double[:,::1] coords_view
463 cdef size_t coords_len = 0
464 cdef yac_coordinate_pointer coords_ptr = NULL
465 cdef size_t idx = SIZE_MAX
466 if lon is not None:
467 coords_xyz = _np.stack(lonlat2xyz(lon, lat), axis=-1)
468 coords_view = _np.ascontiguousarray(coords_xyz, dtype=_np.double)
469 coords_ptr = <yac_coordinate_pointer>&coords_view[0,0]
470 coords_len = len(coords_view)
471 logger.info("calling yac_basic_grid_add_coordinates")
473 self._ptr,
474 location,
475 coords_ptr,
476 coords_len)
477 return Coordinates(basic_grid=self, location=location, coord_idx=idx)
478
479 def add_mask(self,
480 location : yac_location,
481 mask,
482 mask_name : str | None = None
483 ):
484 cdef int[:] mask_view = _np.ascontiguousarray(_np.asarray(mask), dtype=_np.intc)
485 cdef const char* _mask_name = NULL
486 if mask_name is not None:
487 mask_name_bytes = mask_name.encode()
488 _mask_name = mask_name_bytes
489 logger.info("calling yac_basic_grid_add_mask")
490 cdef size_t idx = yac_basic_grid_add_mask(
491 self._ptr,
492 location,
493 <int*>&mask_view[0], len(mask), _mask_name)
494 return Mask(basic_grid=self, location=location, mask_idx=idx)
495
496 @classmethod
497 def read_icon(cls,
498 filename :str,
499 gridname :str,
500 comm = None,
501 mask_valid_values=None):
502
503 filename_bytes = filename.encode()
504 cdef const char* _filename = filename_bytes
505 gridname_bytes = gridname.encode()
506 cdef const char* _gridname = gridname_bytes
507 cdef MPI_Comm c_comm = MPI_COMM_NULL
508 get_c_comm(comm, &c_comm)
509 cdef yac_basic_grid * _yac_basic_grid
510 cdef size_t cell_coordinate_idx
511 cdef int * cell_mask;
512
513 logger.info("calling yac_read_icon_basic_grid_parallel_2")
515 _filename, _gridname, c_comm,
516 &_yac_basic_grid,
517 &cell_coordinate_idx, &cell_mask)
518
519 basic_grid = BasicGrid.from_ptr(_yac_basic_grid)
520 cell_coords = Coordinates(basic_grid=basic_grid,
521 location=YAC_LOC_CELL,
522 coord_idx=cell_coordinate_idx)
523
524 _cell_mask = None
525 if cell_mask != NULL and mask_valid_values is not None:
526 num_cells = basic_grid.get_data_size(YAC_LOC_CELL)
527 _cell_mask = basic_grid.add_mask(YAC_LOC_CELL,
528 _np.isin(<int[:num_cells]>cell_mask, mask_valid_values))
529
530 return basic_grid, InterpField(cell_coords, _cell_mask)
531
532 @classmethod
533 def read_scrip(cls,
534 grid_filename,
535 mask_filename,
536 grid_name,
537 name,
538 valid_mask_value = 1,
539 use_ll_edges = False,
540 ):
541 cdef size_t cell_coord_idx;
542 cdef size_t* duplicated_cell_idx;
543 cdef yac_int* orig_cell_global_ids;
544 cdef size_t nbr_duplicated_cells;
545 cdef yac_basic_grid * yac_basic_grid;
546 grid_filename_bytes = grid_filename.encode()
547 cdef const char* _grid_filename = grid_filename_bytes
548 mask_filename_bytes = mask_filename.encode()
549 cdef const char* _mask_filename = mask_filename_bytes
550 grid_name_bytes = grid_name.encode()
551 cdef const char* _grid_name = grid_name_bytes
552 name_bytes = name.encode()
553 cdef const char* _name = name_bytes
554 cdef int _valid_mask_value = valid_mask_value
555 cdef int _use_ll_edges = use_ll_edges
556 logger.info("calling yac_read_scrip_basic_grid")
557 with nogil:
558 yac_basic_grid = yac_read_scrip_basic_grid(
559 _grid_filename,
560 _mask_filename,
561 _grid_name,
562 _valid_mask_value,
563 _name,
564 _use_ll_edges,
565 &cell_coord_idx,
566 &duplicated_cell_idx,
567 &orig_cell_global_ids,
568 &nbr_duplicated_cells);
569 basic_grid = BasicGrid.from_ptr(yac_basic_grid)
570 return (basic_grid,
571 InterpField(Coordinates(basic_grid=basic_grid,
572 location=YAC_LOC_CELL,
573 coord_idx=cell_coord_idx)),
574 )
575
576 @classmethod
577 @cython.boundscheck(False)
578 def reg_2d_new(cls, name, lon_vertices, lat_vertices, cyclic = [False, False]):
579 cdef const double[::1] x = _np.ascontiguousarray(lon_vertices, dtype=_np.double)
580 cdef const double[::1] y = _np.ascontiguousarray(lat_vertices, dtype=_np.double)
581 cdef int[2] cyclic_view = cyclic
582 name_bytes = name.encode()
583 cdef const char* _name = name_bytes
584 cdef size_t[2] _len = [len(x), len(y)]
585 cdef int[2] _cyclic = cyclic
586 logger.info("calling yac_basic_grid_reg_2d_new")
587 with nogil:
588 yac_basic_grid = yac_basic_grid_reg_2d_new(
589 _name, _len, _cyclic,
590 <double*>&x[0], <double*>&y[0])
591 return BasicGrid.from_ptr(yac_basic_grid)
592
593 @classmethod
594 @cython.boundscheck(False)
596 name : str,
597 num_vertices_per_cell,
598 x_vertices,
599 y_vertices,
600 cell_to_vertex,
601 lonlat_edges = False):
602 assert len(x_vertices) == len(y_vertices)
603 cdef int[:] _num_vertices_per_cell = _np.ascontiguousarray(num_vertices_per_cell, dtype=_np.intc)
604 cdef double[:] _x_vertices = _np.ascontiguousarray(x_vertices, dtype=_np.double)
605 cdef double[:] _y_vertices = _np.ascontiguousarray(y_vertices, dtype=_np.double)
606 cdef int[:] _cell_to_vertex = _np.ascontiguousarray(cell_to_vertex, dtype=_np.intc)
607 cdef int[:] _num_edges_per_cell
608 cdef int[:] _edge_to_vertex
609 cdef yac_basic_grid * ptr
610 name_bytes = name.encode()
611 cdef const char* _name = name_bytes
612 cdef size_t nbr_vertices = len(x_vertices)
613 cdef size_t nbr_cells = len(num_vertices_per_cell)
614 if lonlat_edges:
615 logger.info("calling yac_basic_grid_unstruct_ll_new")
616 with nogil:
618 _name,
619 nbr_vertices,
620 nbr_cells,
621 <int*>&_num_vertices_per_cell[0],
622 <double *>&_x_vertices[0],
623 <double *>&_y_vertices[0],
624 <int *>&_cell_to_vertex[0]);
625 else:
626 logger.info("calling yac_basic_grid_unstruct_new")
627 with nogil:
629 _name,
630 nbr_vertices,
631 nbr_cells,
632 <int*>&_num_vertices_per_cell[0],
633 <double *>&_x_vertices[0],
634 <double *>&_y_vertices[0],
635 <int *>&_cell_to_vertex[0]);
636 return BasicGrid.from_ptr(ptr)
637
638 @classmethod
639 @cython.boundscheck(False)
641 name : str,
642 num_edges_per_cell,
643 x_vertices,
644 y_vertices,
645 cell_to_edge,
646 edge_to_vertex,
647 lonlat_edges : bool = False):
648 assert len(x_vertices) == len(y_vertices)
649 cdef int[:] _num_edges_per_cell = _np.ascontiguousarray(num_edges_per_cell, dtype=_np.intc)
650 cdef double[:] _x_vertices = _np.ascontiguousarray(x_vertices, dtype=_np.double)
651 cdef double[:] _y_vertices = _np.ascontiguousarray(y_vertices, dtype=_np.double)
652 cdef int[:] _cell_to_edge = _np.ascontiguousarray(cell_to_edge, dtype=_np.intc)
653 cdef int[:] _edge_to_vertex = _np.ascontiguousarray(edge_to_vertex, dtype=_np.intc)
654 name_bytes = name.encode()
655 cdef const char* _name = name_bytes
656 cdef size_t nbr_vertices = len(x_vertices)
657 cdef size_t nbr_cells = len(num_edges_per_cell)
658 cdef size_t nbr_edges = _np.max(_cell_to_edge)+1
659 if lonlat_edges:
660 logger.info("calling yac_basic_grid_unstruct_edge_ll_new")
661 with nogil:
663 _name,
664 nbr_vertices,
665 nbr_cells,
666 nbr_edges,
667 <int*>&_num_edges_per_cell[0],
668 <double*>&_x_vertices[0],
669 <double*>&_y_vertices[0],
670 <int*>&_cell_to_edge[0],
671 <int*>&_edge_to_vertex[0]);
672 else:
673 logger.info("calling yac_basic_grid_unstruct_edge_new")
674 with nogil:
676 _name,
677 nbr_vertices,
678 nbr_cells,
679 nbr_edges,
680 <int*>&_num_edges_per_cell[0],
681 <double*>&_x_vertices[0],
682 <double*>&_y_vertices[0],
683 <int*>&_cell_to_edge[0],
684 <int*>&_edge_to_vertex[0]);
685
686 return BasicGrid.from_ptr(ptr)
687
688 @classmethod
689 def empty(cls, name : str):
690 logger.info("calling yac_basic_grid_empty_new")
691 cdef yac_basic_grid * ptr = yac_basic_grid_empty_new(name.encode())
692 return BasicGrid.from_ptr(ptr)
693
694 @classmethod
695 def from_uxgrid(cls,
696 name : str,
697 uxgrid,
698 def_edges : bool = False,
699 lonlat_edges : bool = False):
700 from uxarray import INT_FILL_VALUE
701 if def_edges:
702 cell_to_edge = _np.asarray(uxgrid.face_edge_connectivity).reshape((-1,), order="C")
703 cell_to_edge = cell_to_edge[cell_to_edge!=INT_FILL_VALUE]
704 edge_to_vertex = _np.asarray(uxgrid.edge_node_connectivity).reshape((-1,), order="C")
705 edge_to_vertex = edge_to_vertex[edge_to_vertex!=INT_FILL_VALUE]
706 grid = cls.unstruct_edge_new(
707 name,
708 uxgrid.n_nodes_per_face, # n_nodes_per_face == n_edges_per_face (2D)
709 _np.deg2rad(uxgrid.node_lon),
710 _np.deg2rad(uxgrid.node_lat),
711 cell_to_edge,
712 edge_to_vertex,
713 lonlat_edges = lonlat_edges)
714 else:
715 cell_to_vertex = _np.asarray(uxgrid.face_node_connectivity).reshape((-1,), order="C")
716 cell_to_vertex = cell_to_vertex[cell_to_vertex!=INT_FILL_VALUE]
717 grid = cls.unstruct_new(
718 name,
719 uxgrid.n_nodes_per_face, # n_nodes_per_face == n_edges_per_face (2D)
720 _np.deg2rad(uxgrid.node_lon),
721 _np.deg2rad(uxgrid.node_lat),
722 cell_to_vertex,
723 lonlat_edges = lonlat_edges)
724 grid.set_global_index(YAC_LOC_CELL,
725 range(uxgrid.n_face))
726 grid.set_global_index(YAC_LOC_EDGE,
727 range(uxgrid.n_edge))
728 grid.set_global_index(YAC_LOC_CORNER,
729 range(uxgrid.n_node))
730 return grid
731
732
733cdef class InterpField:
734 cdef yac_interp_field _interp_field
735 cdef BasicGrid _basic_grid
736
737 def __init__(self,
738 coordinates : Coordinates,
739 mask : Mask = None):
740 self._basic_grid = coordinates.basic_grid
741 self._interp_field.location = coordinates.location
742 self._interp_field.coordinates_idx = coordinates.coord_idx
743 cdef masks_idx = SIZE_MAX
744 if mask is not None:
745 assert mask.location == coordinates.location, \
746 "coordinates and mask have different location"
747 masks_idx = mask.mask_idx
748 self._interp_field.masks_idx = masks_idx
749
750 def __str__(self):
751 return f"yac_interp_field(grid={self._basic_grid}, location={self.location}, coord_idx={self._interp_field.coordinates_idx}, mask_idx={self._interp_field.masks_idx})"
752
753 @property
754 def location(self):
755 return self._interp_field.location
756
757 @property
758 def basic_grid(self):
759 return self._basic_grid
760
761cdef class DistGridPair:
762 cdef yac_dist_grid_pair* _ptr
763 _str :str
764
765 def __init__(self, grid_a : BasicGrid,
766 grid_b : BasicGrid,
767 comm = None):
768 cdef MPI_Comm c_comm = MPI_COMM_NULL
769 get_c_comm(comm, &c_comm)
770 logger.info("calling yac_dist_grid_pair_new")
772 grid_a._ptr, grid_b._ptr,
773 c_comm);
774 self._str = f"yac_dist_grid_pair(grid_a={grid_a}, grid_b={grid_b}"
775
776 def __str__(self):
777 return self._str
778
779 def __del__(self):
780 logger.info("calling yac_dist_grid_pair_delete")
782
783cdef class InterpGrid:
784 cdef yac_interp_grid* _ptr
785 cdef InterpField _src_field
786 cdef InterpField _tgt_field
787
788 def __init__(self,
789 grid_pair : DistGridPair,
790 src_field : InterpField, # TODO: support multiple src_fields
791 tgt_field : InterpField):
792 src_grid_name = src_field._basic_grid.name
793 tgt_grid_name = tgt_field._basic_grid.name
794 logger.info("calling yac_interp_grid_new")
795 self._ptr = yac_interp_grid_new(grid_pair._ptr,
796 src_grid_name.encode(), tgt_grid_name.encode(),
797 1, &src_field._interp_field,
798 tgt_field._interp_field);
799 self._src_field = src_field
800 self._tgt_field = tgt_field
801
802 def __str__(self):
803 return f"yac_interp_grid(src_field={self._src_field}, tgt_field={self._tgt_field})"
804
805 def __del__(self):
806 logger.info("calling yac_interp_grid_delete")
808
810 cdef yac_interp_stack_config* _ptr
811 interpolation_register = {}
812
813 def __init__(self):
814 logger.info("calling yac_interp_stack_config_new")
816
817 @classmethod
818 def from_list(cls, interp_list):
819 interp_stack = InterpolationStack()
820 interp_list = [(t, {}) if type(t) is str else t for t in interp_list]
821 for name, kwargs in interp_list:
822 interp_stack.add(name, **kwargs)
823 return interp_stack
824
825 def __del__(self):
826 logger.info("calling yac_interp_stack_config_delete")
828
830 def _register(method):
831 InterpolationStack.interpolation_register[name] = method
832 return method
833 return _register
834
835 def add(self, name, *args, **kwargs):
836 self.interpolation_register[name](self, *args, **kwargs)
837
838 @register_interpolation("average")
839 def add_average(self,
840 reduction_type : yac_interp_avg_weight_type = YAC_INTERP_AVG_WEIGHT_TYPE_DEFAULT,
841 partial_coverage : bool = YAC_INTERP_AVG_PARTIAL_COVERAGE_DEFAULT):
842 logger.info("calling yac_interp_stack_config_add_average")
844 self._ptr, reduction_type, partial_coverage);
845
846 @register_interpolation("ncc")
847 def add_ncc(self,
848 weight_type : yac_interp_ncc_weight_type = YAC_INTERP_NCC_WEIGHT_TYPE_DEFAULT,
849 partial_coverage : bool = YAC_INTERP_NCC_PARTIAL_COVERAGE_DEFAULT):
850 logger.info("calling yac_interp_stack_config_add_ncc")
851 yac_interp_stack_config_add_ncc(self._ptr, weight_type, partial_coverage);
852
853 @register_interpolation("nnn")
854 def add_nnn(self,
855 nnn_type : yac_interp_nnn_weight_type = YAC_INTERP_NNN_WEIGHTED_DEFAULT,
856 n : int = YAC_INTERP_NNN_N_DEFAULT,
857 max_search_distance: float = YAC_INTERP_NNN_MAX_SEARCH_DISTANCE_DEFAULT,
858 scale : float = YAC_INTERP_NNN_GAUSS_SCALE_DEFAULT,
859 ):
860 logger.info("calling yac_interp_stack_config_add_nnn")
862 self._ptr, nnn_type, n, max_search_distance, scale);
863
864 @register_interpolation("conservative")
866 order : int = YAC_INTERP_CONSERV_ORDER_DEFAULT,
867 enforced_conserv : bool = YAC_INTERP_CONSERV_ENFORCED_CONSERV_DEFAULT,
868 partial_coverage : bool = YAC_INTERP_CONSERV_PARTIAL_COVERAGE_DEFAULT,
869 normalisation : yac_interp_method_conserv_normalisation = YAC_INTERP_CONSERV_NORMALISATION_DEFAULT
870 ):
871 assert order in {1,2}, "Invalid order"
872 logger.info("calling yac_interp_stack_config_add_conservative")
874 self._ptr, order, enforced_conserv, partial_coverage, normalisation);
875
876 @register_interpolation("source_to_target_map")
878 spread_distance : float = YAC_INTERP_SPMAP_SPREAD_DISTANCE_DEFAULT,
879 max_search_distance : float = YAC_INTERP_SPMAP_MAX_SEARCH_DISTANCE_DEFAULT,
880 weight_type : yac_interp_spmap_weight_type = YAC_INTERP_SPMAP_WEIGHTED_DEFAULT,
881 scale_type : yac_interp_spmap_scale_type = YAC_INTERP_SPMAP_SCALE_TYPE_DEFAULT,
882 src_sphere_radius : float = 0.0,
883 src_filename : str | None = None,
884 src_varname : str | None = None,
885 src_min_global_id : int = YAC_INTERP_SPMAP_MIN_GLOBAL_ID_DEFAULT,
886 tgt_sphere_radius : float = 0.0,
887 tgt_filename : str | None = None,
888 tgt_varname : str | None = None,
889 tgt_min_global_id : int = YAC_INTERP_SPMAP_MIN_GLOBAL_ID_DEFAULT,
890 ):
891 cdef const char* _src_filename = NULL
892 cdef const char* _src_varname = NULL
893 cdef const char* _tgt_filename = NULL
894 cdef const char* _tgt_varname = NULL
895 if src_filename is not None:
896 src_filename_bytes = bytes(src_filename)
897 _src_filename = src_filename_bytes
898 if src_varname is not None:
899 src_varname_bytes = bytes(src_varname)
900 _src_varname = src_varname_bytes
901 if tgt_filename is not None:
902 tgt_filename_bytes = bytes(tgt_filename)
903 _tgt_filename = tgt_filename_bytes
904 if src_varname is not None:
905 src_varname_bytes = bytes(src_varname)
906 _src_varname = src_varname_bytes
907 logger.info("calling yac_interp_stack_config_add_spmap")
909 self._ptr, spread_distance, max_search_distance, weight_type,
910 scale_type, src_sphere_radius, _src_filename, _src_varname,
911 src_min_global_id, tgt_sphere_radius, _tgt_filename, _tgt_varname,
912 tgt_min_global_id);
913
914 @register_interpolation("fixed")
915 def add_fixed(self, value : float):
916 logger.info("calling yac_interp_stack_config_add_fixed")
918 self._ptr, value);
919
920 @register_interpolation("user_file")
922 filename : str | None = None,
923 on_missing_file : yac_interp_file_on_missing_file = YAC_INTERP_FILE_ON_MISSING_FILE_DEFAULT,
924 on_success : yac_interp_file_on_success = YAC_INTERP_FILE_ON_SUCCESS_DEFAULT):
925 cdef const char* _filename = NULL
926 if filename is not None:
927 filename_bytes = filename.encode()
928 _filename = filename_bytes
929 logger.info("calling yac_interp_stack_config_add_user_file")
931 self._ptr, _filename, on_missing_file, on_success);
932
933 @register_interpolation("check")
934 def add_check(self,
935 constructor_key : str = _decode(YAC_INTERP_CHECK_CONSTRUCTOR_KEY_DEFAULT),
936 do_search_key : str = _decode(YAC_INTERP_CHECK_DO_SEARCH_KEY_DEFAULT)):
937 logger.info("calling yac_interp_stack_config_add_check")
939 constructor_key.encode(), do_search_key.encode());
940
941 @register_interpolation("bernstein_bezier")
943 logger.info("calling yac_interp_stack_config_add_hcsbb")
945
946 @register_interpolation("rbf")
947 def add_rbf(self,
948 n : int = YAC_INTERP_RBF_N_DEFAULT,
949 max_search_distance : float = YAC_INTERP_RBF_MAX_SEARCH_DISTANCE_DEFAULT,
950 scale : float = YAC_INTERP_RBF_SCALE_DEFAULT,
951 rbf_kernel : int = YAC_INTERP_RBF_KERNEL_DEFAULT
952 ):
953 logger.info("calling yac_interp_stack_config_add_rbf")
954 yac_interp_stack_config_add_rbf(self._ptr, n, max_search_distance, scale);
955
956 @register_interpolation("creep")
957 def add_creep(self,
958 creep_distance : int = YAC_INTERP_CREEP_DISTANCE_DEFAULT):
959 logger.info("calling yac_interp_stack_config_add_creep")
960 yac_interp_stack_config_add_creep(self._ptr, creep_distance);
961
962cdef class InterpWeights:
963 cdef yac_interp_weights* _ptr;
964 cdef _num_src_points, _num_tgt_points;
965
966 def __init__(self):
967 raise TypeError("This class cannot be instantiated directly.")
968
969 @staticmethod
970 cdef InterpWeights from_ptr(yac_interp_weights* interp_weights_ptr,
971 num_src_points : int,
972 num_tgt_points : int):
973 cdef InterpWeights interp_weights = InterpWeights.__new__(InterpWeights)
974 interp_weights._ptr = interp_weights_ptr
975 interp_weights._num_src_points = num_src_points
976 interp_weights._num_tgt_points = num_tgt_points
977 return interp_weights
978
980 filename : str,
981 src_grid_name : str = "src_grid",
982 tgt_grid_name : str = "tgt_grid",
983 num_global_src_points : int = 0,
984 num_global_tgt_points : int = 0,
985 on_existing = YAC_WEIGHT_FILE_ERROR,
986 ):
987 filename_bytes = filename.encode()
988 src_grid_name_bytes = src_grid_name.encode()
989 tgt_grid_name_bytes = tgt_grid_name.encode()
990 cdef const char* filename_cstr = filename_bytes
991 cdef const char* src_grid_name_cstr = src_grid_name_bytes
992 cdef const char* tgt_grid_name_cstr = tgt_grid_name_bytes
993 cdef yac_interp_weights* _ptr = self._ptr;
994 cdef int num_global_src_points_c = num_global_src_points
995 cdef int num_global_tgt_points_c = num_global_tgt_points
996 cdef yac_weight_file_on_existing on_existing_c = on_existing
997 logger.info("calling yac_interp_weights_write_to_file")
998 with nogil:
1000 _ptr,
1001 filename_cstr,
1002 src_grid_name_cstr,
1003 tgt_grid_name_cstr,
1004 num_global_src_points_c,
1005 num_global_tgt_points_c,
1006 on_existing_c);
1007
1009 reorder : yac_interp_weights_reorder_type = YAC_MAPPING_ON_SRC,
1010 collection_size : int | None = None,
1011 frac_mask_fallback_value : float | None = None,
1012 scaling_factor : float = 1.0,
1013 scaling_summand : float = 0.0,
1014 yaxt_exchanger_name : str | None = None,
1015 is_source : bool = True,
1016 is_target : bool = True,
1017 collection_selection : List[int] | None = None):
1018 assert (collection_size is not None) ^ (collection_selection is not None), \
1019 "Either collection_size or collection_selection must be provided"
1020 if collection_size is not None:
1021 collection_selection = list(range(collection_size))
1022 collection_size = len(collection_selection)
1023
1024 cdef yac_collection_selection* coll_sel;
1025 cdef yac_interpolation_gen_config * config = yac_interpolation_gen_config_new();
1026 cdef size_t[:] coll_sel_np = _np.ascontiguousarray(collection_selection, dtype=_np.uintp)
1028
1029 coll_sel = yac_collection_selection_new(collection_size, <size_t*>&coll_sel_np[0]);
1032
1033 if frac_mask_fallback_value is not None:
1034 yac_interpolation_gen_config_set_frac_mask_fallback_value(config, frac_mask_fallback_value);
1036 yac_interpolation_gen_config_set_scaling_summand(config, scaling_summand);
1037 if yaxt_exchanger_name is not None:
1038 yac_interpolation_gen_config_set_yaxt_exchanger_name(config, yaxt_exchanger_name.encode());
1039
1040 logger.info("calling yac_interp_weights_get_interpolation_ext")
1041 cdef yac_interpolation * interp_ptr = yac_interp_weights_get_interpolation_ext(
1042 self._ptr, config, is_source, is_target);
1043
1045 return Interpolation.from_ptr(interp_ptr,
1046 self._num_src_points,
1047 self._num_tgt_points,
1048 collection_size,
1049 )
1050
1051def do_search(interpolation_stack : InterpolationStack, interp_grid : InterpGrid):
1052 cdef interp_method** interpstack = yac_interp_stack_config_generate(interpolation_stack._ptr)
1053 cdef yac_interp_weights * w
1054 with nogil:
1056 interpstack, interp_grid._ptr);
1057 logger.info("calling yac_interp_method_delete")
1058 yac_interp_method_delete(interpstack);
1059 free(interpstack);
1060
1061 src_loc = interp_grid._src_field.location
1062 num_src_points = interp_grid._src_field._basic_grid.get_data_size(src_loc)
1063
1064 tgt_loc = interp_grid._tgt_field.location
1065 num_tgt_points = interp_grid._tgt_field._basic_grid.get_data_size(tgt_loc)
1066
1067 return InterpWeights.from_ptr(w, num_src_points, num_tgt_points)
1068
1069def compute_weights(interpolation_stack : InterpolationStack,
1070 src_field : InterpField | None,
1071 tgt_field : InterpField | None,
1072 comm = None):
1073 dgp = DistGridPair(src_field.basic_grid, tgt_field.basic_grid)
1074 ig = InterpGrid(dgp,
1075 src_field,
1076 tgt_field)
1077 return do_search(interpolation_stack,
1078 ig)
1079
1080cdef void* fill_pointer_array(array):
1081 cdef double[::1] view1d
1082 if len(array.shape) == 1:
1083 view1d = array
1084 return &view1d[0]
1085 cdef void** ptr = <void**> malloc(array.shape[0] * sizeof(ptr[0]))
1086 cdef int i
1087 for i in range(array.shape[0]):
1088 slic = array[i, ...]
1089 assert slic.base is not None
1090 ptr[i] = fill_pointer_array(slic)
1091 return ptr
1092
1093cdef void free_pointer_array(void* ptr, shape):
1094 cdef int i
1095 if len(shape) > 1:
1096 for i in range(shape[0]):
1097 free_pointer_array((<void**>ptr)[i], shape[1:])
1098 free(ptr)
1099
1100cdef class Interpolation:
1101 cdef yac_interpolation* _ptr;
1102 cdef int _collection_size;
1103 cdef _num_src_points, _num_tgt_points
1104
1105 def __init__(self):
1106 raise TypeError("This class cannot be instantiated directly.")
1107
1108 @staticmethod
1109 cdef Interpolation from_ptr(yac_interpolation* interpolation_ptr,
1110 num_src_points, num_tgt_points,
1111 collection_size):
1112 cdef Interpolation interp = Interpolation.__new__(Interpolation)
1113 interp._ptr = interpolation_ptr
1114 interp._num_src_points = num_src_points
1115 interp._num_tgt_points = num_tgt_points
1116 interp._collection_size = collection_size
1117 return interp
1118
1119 def __call__(self, src = None, *, tgt = None, frac_mask = None):
1120 cdef double*** _src = NULL
1121 cdef double*** _frac_masks = NULL
1122 cdef double** _tgt = NULL
1123 if src is not None:
1124 src = src.reshape((-1, 1, self._num_src_points))
1125 _src = <double***>fill_pointer_array(src)
1126 if frac_mask is not None:
1127 frac_mask = frac_mask.reshape((-1, 1, self._num_src_points))
1128 _frac_masks = <double***>fill_pointer_array(frac_mask)
1129
1130 if tgt is None and self._num_tgt_points > 0:
1131 tgt = _np.empty((self._collection_size, self._num_tgt_points), dtype=_np.double)
1132
1133 if tgt is not None:
1134 tgt = tgt.reshape(self._collection_size, self._num_tgt_points)
1135 _tgt = <double**>fill_pointer_array(tgt)
1136
1137 logger.info("calling yac_interpolation_execute_frac")
1138 with nogil:
1140 self._ptr, _src, _frac_masks, _tgt);
1141 if src is not None:
1142 free_pointer_array(_src, src.shape)
1143 if frac_mask is not None:
1144 free_pointer_array(_frac_masks, frac_mask.shape)
1145 if tgt is not None:
1146 free_pointer_array(_tgt, tgt.shape)
1147 return tgt
1148
1149 @coroutine
1150 def execute_async(self, src = None, *, tgt = None, frac_mask = None):
1151 cdef double*** _src = NULL
1152 cdef double*** _frac_masks = NULL
1153 cdef double** _tgt = NULL
1154 if src is not None:
1155 src = src.reshape((-1, 1, self._num_src_points))
1156 _src = <double***>fill_pointer_array(src)
1157 if frac_mask is not None:
1158 frac_mask = frac_mask.reshape((-1, 1, self._num_src_points))
1159 _frac_masks = <double***>fill_pointer_array(frac_mask)
1160
1161 if tgt is None and self._num_tgt_points > 0:
1162 tgt = _np.empty((self._collection_size, self._num_tgt_points), dtype=_np.double)
1163 if tgt is not None:
1164 tgt = tgt.reshape(self._collection_size, self._num_tgt_points)
1165 _tgt = <double**>fill_pointer_array(tgt)
1166
1167 # wait until put buffer is free
1168 while yac_interpolation_execute_put_test(self._ptr) == 0:
1169 yield
1170
1171 with nogil:
1172 yac_interpolation_execute_put_frac(self._ptr, _src, _frac_masks);
1173 yac_interpolation_execute_get_async(self._ptr, _tgt);
1174
1175 # wait for the data
1176 while yac_interpolation_execute_get_test(self._ptr) == 0:
1177 yield
1178
1179 if src is not None:
1180 free_pointer_array(_src, src.shape)
1181 if frac_mask is not None:
1182 free_pointer_array(_frac_masks, frac_mask.shape)
1183 if tgt is not None:
1184 free_pointer_array(_tgt, tgt.shape)
1185 return tgt
1186
1187def get_io_ranks(comm=None):
1188 """
1189 Returns a list of ranks designated for I/O operations in the given
1190 communicator.
1191 """
1192 cdef MPI_Comm c_comm = MPI_COMM_NULL
1193 get_c_comm(comm, &c_comm)
1194 cdef int local_is_io
1195 cdef int *io_ranks_ptr
1196 cdef int num_io_ranks
1197 logger.info("calling yac_get_io_ranks")
1198 with nogil:
1199 yac_get_io_ranks(c_comm, &local_is_io, &io_ranks_ptr, &num_io_ranks)
1200 io_ranks = [io_ranks_ptr[i] for i in range(num_io_ranks)]
1201 free(io_ranks_ptr)
1202 return bool(local_is_io), io_ranks
1203
1204if Py_AtExit(yac_mpi_finalize) < 0:
1205 warn("could not register yac_mpi_finalize with Py_AtExit()")
struct yac_basic_grid * yac_basic_grid_unstruct_edge_new(char const *name, size_t nbr_vertices, size_t nbr_cells, size_t nbr_edges, int *num_edges_per_cell, double *x_vertices, double *y_vertices, int *cell_to_edge, int *edge_to_vertex)
Definition basic_grid.c:420
struct yac_basic_grid * yac_basic_grid_unstruct_edge_ll_new(char const *name, size_t nbr_vertices, size_t nbr_cells, size_t nbr_edges, int *num_edges_per_cell, double *x_vertices, double *y_vertices, int *cell_to_edge, int *edge_to_vertex)
Definition basic_grid.c:446
void yac_basic_grid_to_file_parallel(struct yac_basic_grid *grid, char const *filename, MPI_Comm comm)
Definition basic_grid.c:768
struct yac_basic_grid * yac_basic_grid_unstruct_new(char const *name, size_t nbr_vertices, size_t nbr_cells, int *num_vertices_per_cell, double *x_vertices, double *y_vertices, int *cell_to_vertex)
Definition basic_grid.c:368
struct yac_basic_grid_data * yac_basic_grid_get_data(struct yac_basic_grid *grid)
Definition basic_grid.c:137
size_t yac_basic_grid_add_mask(struct yac_basic_grid *grid, enum yac_location location, int const *mask, size_t count, char const *mask_name)
Definition basic_grid.c:284
struct yac_basic_grid * yac_basic_grid_reg_2d_new(char const *name, size_t nbr_vertices[2], int cyclic[2], double *lon_vertices, double *lat_vertices)
Definition basic_grid.c:324
struct yac_basic_grid * yac_basic_grid_unstruct_ll_new(char const *name, size_t nbr_vertices, size_t nbr_cells, int *num_vertices_per_cell, double *x_vertices, double *y_vertices, int *cell_to_vertex)
Definition basic_grid.c:394
char const * yac_basic_grid_get_name(struct yac_basic_grid *grid)
Definition basic_grid.c:128
size_t yac_basic_grid_add_coordinates(struct yac_basic_grid *grid, enum yac_location location, yac_coordinate_pointer coordinates, size_t count)
Definition basic_grid.c:232
size_t yac_basic_grid_get_data_size(struct yac_basic_grid *grid, enum yac_location location)
Definition basic_grid.c:147
struct yac_basic_grid * yac_basic_grid_empty_new(char const *name)
Definition basic_grid.c:63
void yac_basic_grid_delete(struct yac_basic_grid *grid)
Definition basic_grid.c:70
from_uxgrid(cls, str name, uxgrid, bool def_edges=False, bool lonlat_edges=False)
Definition core.pyx:699
set_global_index(self, yac_location location, indices)
Definition core.pyx:417
__init__(self, yac_basic_grid_ptr)
Definition core.pyx:379
reg_2d_new(cls, name, lon_vertices, lat_vertices, cyclic=[False, False])
Definition core.pyx:578
unstruct_new(cls, str name, num_vertices_per_cell, x_vertices, y_vertices, cell_to_vertex, lonlat_edges=False)
Definition core.pyx:601
to_file(self, filename, comm=None)
Definition core.pyx:392
read_scrip(cls, grid_filename, mask_filename, grid_name, name, valid_mask_value=1, use_ll_edges=False)
Definition core.pyx:540
empty(cls, str name)
Definition core.pyx:689
unstruct_edge_new(cls, str name, num_edges_per_cell, x_vertices, y_vertices, cell_to_edge, edge_to_vertex, bool lonlat_edges=False)
Definition core.pyx:647
read_icon(cls, str filename, str gridname, comm=None, mask_valid_values=None)
Definition core.pyx:501
get_data_size(self, yac_location location)
Definition core.pyx:411
add_coordinates(self, yac_location location, lon=None, lat=None)
Definition core.pyx:460
add_mask(self, yac_location location, mask, str|None mask_name=None)
Definition core.pyx:483
set_core_mask(self, yac_location location, mask)
Definition core.pyx:437
__init__(self, BasicGrid grid_a, BasicGrid grid_b, comm=None)
Definition core.pyx:767
__init__(self, Coordinates coordinates, Mask mask=None)
Definition core.pyx:739
__init__(self, DistGridPair grid_pair, InterpField src_field, InterpField tgt_field)
Definition core.pyx:791
get_interpolation(self, yac_interp_weights_reorder_type reorder=YAC_MAPPING_ON_SRC, int|None collection_size=None, float|None frac_mask_fallback_value=None, float scaling_factor=1.0, float scaling_summand=0.0, str|None yaxt_exchanger_name=None, bool is_source=True, bool is_target=True, List[int]|None collection_selection=None)
Definition core.pyx:1017
write_to_file(self, str filename, str src_grid_name="src_grid", str tgt_grid_name="tgt_grid", int num_global_src_points=0, int num_global_tgt_points=0, on_existing=YAC_WEIGHT_FILE_ERROR)
Definition core.pyx:986
add_nnn(self, yac_interp_nnn_weight_type nnn_type=YAC_INTERP_NNN_WEIGHTED_DEFAULT, int n=YAC_INTERP_NNN_N_DEFAULT, float max_search_distance=YAC_INTERP_NNN_MAX_SEARCH_DISTANCE_DEFAULT, float scale=YAC_INTERP_NNN_GAUSS_SCALE_DEFAULT)
Definition core.pyx:859
add_user_file(self, str|None filename=None, yac_interp_file_on_missing_file on_missing_file=YAC_INTERP_FILE_ON_MISSING_FILE_DEFAULT, yac_interp_file_on_success on_success=YAC_INTERP_FILE_ON_SUCCESS_DEFAULT)
Definition core.pyx:924
add_check(self, str constructor_key=_decode(YAC_INTERP_CHECK_CONSTRUCTOR_KEY_DEFAULT), str do_search_key=_decode(YAC_INTERP_CHECK_DO_SEARCH_KEY_DEFAULT))
Definition core.pyx:936
add(self, name, *args, **kwargs)
Definition core.pyx:835
add_fixed(self, float value)
Definition core.pyx:915
add_rbf(self, int n=YAC_INTERP_RBF_N_DEFAULT, float max_search_distance=YAC_INTERP_RBF_MAX_SEARCH_DISTANCE_DEFAULT, float scale=YAC_INTERP_RBF_SCALE_DEFAULT, int rbf_kernel=YAC_INTERP_RBF_KERNEL_DEFAULT)
Definition core.pyx:952
add_creep(self, int creep_distance=YAC_INTERP_CREEP_DISTANCE_DEFAULT)
Definition core.pyx:958
add_source_to_target_map(self, float spread_distance=YAC_INTERP_SPMAP_SPREAD_DISTANCE_DEFAULT, float max_search_distance=YAC_INTERP_SPMAP_MAX_SEARCH_DISTANCE_DEFAULT, yac_interp_spmap_weight_type weight_type=YAC_INTERP_SPMAP_WEIGHTED_DEFAULT, yac_interp_spmap_scale_type scale_type=YAC_INTERP_SPMAP_SCALE_TYPE_DEFAULT, float src_sphere_radius=0.0, str|None src_filename=None, str|None src_varname=None, int src_min_global_id=YAC_INTERP_SPMAP_MIN_GLOBAL_ID_DEFAULT, float tgt_sphere_radius=0.0, str|None tgt_filename=None, str|None tgt_varname=None, int tgt_min_global_id=YAC_INTERP_SPMAP_MIN_GLOBAL_ID_DEFAULT)
Definition core.pyx:890
add_ncc(self, yac_interp_ncc_weight_type weight_type=YAC_INTERP_NCC_WEIGHT_TYPE_DEFAULT, bool partial_coverage=YAC_INTERP_NCC_PARTIAL_COVERAGE_DEFAULT)
Definition core.pyx:849
add_conservative(self, int order=YAC_INTERP_CONSERV_ORDER_DEFAULT, bool enforced_conserv=YAC_INTERP_CONSERV_ENFORCED_CONSERV_DEFAULT, bool partial_coverage=YAC_INTERP_CONSERV_PARTIAL_COVERAGE_DEFAULT, yac_interp_method_conserv_normalisation normalisation=YAC_INTERP_CONSERV_NORMALISATION_DEFAULT)
Definition core.pyx:870
from_list(cls, interp_list)
Definition core.pyx:818
add_average(self, yac_interp_avg_weight_type reduction_type=YAC_INTERP_AVG_WEIGHT_TYPE_DEFAULT, bool partial_coverage=YAC_INTERP_AVG_PARTIAL_COVERAGE_DEFAULT)
Definition core.pyx:841
void yac_dist_grid_pair_delete(struct yac_dist_grid_pair *grid_pair)
Definition dist_grid.c:2313
struct yac_dist_grid_pair * yac_dist_grid_pair_new(struct yac_basic_grid *grid_a, struct yac_basic_grid *grid_b, MPI_Comm comm)
Definition dist_grid.c:2061
void yac_collection_selection_delete(struct yac_collection_selection *collection_selection)
Delete a collection selection object.
struct yac_collection_selection * yac_collection_selection_new(size_t collection_size, size_t const *selection_indices)
Create a new collection selection.
void yac_interp_grid_delete(struct yac_interp_grid *interp_grid)
struct yac_interp_grid * yac_interp_grid_new(struct yac_dist_grid_pair *grid_pair, char const *src_grid_name, char const *tgt_grid_name, size_t num_src_fields, struct yac_interp_field const *src_fields, struct yac_interp_field const tgt_field)
Definition interp_grid.c:31
void yac_interp_method_delete(struct interp_method **method)
struct yac_interp_weights * yac_interp_method_do_search(struct interp_method **method, struct yac_interp_grid *interp_grid)
enum callback_type type
void yac_interp_stack_config_add_check(struct yac_interp_stack_config *interp_stack_config, char const *constructor_key, char const *do_search_key)
void yac_interp_stack_config_add_spmap(struct yac_interp_stack_config *interp_stack_config, double spread_distance, double max_search_distance, enum yac_interp_spmap_weight_type weight_type, enum yac_interp_spmap_scale_type scale_type, double src_sphere_radius, char const *src_filename, char const *src_varname, int src_min_global_id, double tgt_sphere_radius, char const *tgt_filename, char const *tgt_varname, int tgt_min_global_id)
void yac_interp_stack_config_add_fixed(struct yac_interp_stack_config *interp_stack_config, double value)
void yac_interp_stack_config_add_hcsbb(struct yac_interp_stack_config *interp_stack_config)
void yac_interp_stack_config_add_rbf(struct yac_interp_stack_config *interp_stack_config, size_t n, double max_search_distance, double scale)
void yac_interp_stack_config_add_average(struct yac_interp_stack_config *interp_stack_config, enum yac_interp_avg_weight_type reduction_type, int partial_coverage)
void yac_interp_stack_config_add_creep(struct yac_interp_stack_config *interp_stack_config, int creep_distance)
void yac_interp_stack_config_add_nnn(struct yac_interp_stack_config *interp_stack_config, enum yac_interp_nnn_weight_type type, size_t n, double max_search_distance, double scale)
void yac_interp_stack_config_delete(struct yac_interp_stack_config *interp_stack_config)
void yac_interp_stack_config_add_conservative(struct yac_interp_stack_config *interp_stack_config, int order, int enforced_conserv, int partial_coverage, enum yac_interp_method_conserv_normalisation normalisation)
struct interp_method ** yac_interp_stack_config_generate(struct yac_interp_stack_config *interp_stack)
void yac_interp_stack_config_add_ncc(struct yac_interp_stack_config *interp_stack_config, enum yac_interp_ncc_weight_type weight_type, int partial_coverage)
void yac_interp_stack_config_add_user_file(struct yac_interp_stack_config *interp_stack_config, char const *filename, enum yac_interp_file_on_missing_file on_missing_file, enum yac_interp_file_on_success on_success)
struct yac_interp_stack_config * yac_interp_stack_config_new()
struct yac_interpolation * yac_interp_weights_get_interpolation_ext(struct yac_interp_weights const *weights, struct yac_interpolation_gen_config const *config, int is_source, int is_target)
void yac_interp_weights_write_to_file(struct yac_interp_weights *weights, char const *filename, char const *src_grid_name, char const *tgt_grid_name, size_t src_grid_size, size_t tgt_grid_size, enum yac_weight_file_on_existing on_existing)
int yac_interpolation_execute_put_test(struct yac_interpolation *interp)
Test whether the asynchronous put phase has completed.
void yac_interpolation_execute_frac(struct yac_interpolation *interp, double ***src_fields, double ***src_frac_masks, double **tgt_field)
Execute interpolation with fractional masks and write results to the target field.
void yac_interpolation_execute_get_async(struct yac_interpolation *interp, double **tgt_field)
Complete interpolation asynchronously and write results to the target field (get phase).
void yac_interpolation_execute_put_frac(struct yac_interpolation *interp, double ***src_fields, double ***src_frac_masks)
Provide source field data with fractional masks and start asynchronous execution of interpolation (pu...
int yac_interpolation_execute_get_test(struct yac_interpolation *interp)
Test whether the asynchronous get phase has completed.
void yac_interpolation_gen_config_set_reorder(struct yac_interpolation_gen_config *config, enum yac_interp_weights_reorder_type reorder)
Set the reordering strategy for interpolation weights.
void yac_interpolation_gen_config_set_collection_size(struct yac_interpolation_gen_config *config, size_t collection_size)
Set the number of contiguous fields (starting at "0") in the field collection.
void yac_interpolation_gen_config_set_collection_selection(struct yac_interpolation_gen_config *config, struct yac_collection_selection const *collection_selection)
Set the collection selection of source field in the source field collection.
void yac_interpolation_gen_config_set_scaling_factor(struct yac_interpolation_gen_config *config, double scaling_factor)
Set the multiplicative scaling factor.
void yac_interpolation_gen_config_set_yaxt_exchanger_name(struct yac_interpolation_gen_config *config, char const *name)
Set the name of the Yaxt exchanger.
void yac_interpolation_gen_config_delete(struct yac_interpolation_gen_config *config)
Release a interpolation generation configuration structure allocated by yac_interpolation_gen_config_...
void yac_interpolation_gen_config_set_frac_mask_fallback_value(struct yac_interpolation_gen_config *config, double frac_mask_fallback_value)
Set the fractional mask fallback value.
struct yac_interpolation_gen_config * yac_interpolation_gen_config_new(void)
Allocate and initialise an interpolation generation configuration structure.
void yac_interpolation_gen_config_set_scaling_summand(struct yac_interpolation_gen_config *config, double scaling_summand)
Set the additive scaling summand.
void yac_get_io_ranks(MPI_Comm comm, int *local_is_io_, int **io_ranks_, int *num_io_ranks_)
Definition io_utils.c:309
execute_async(self, src=None, *, tgt=None, frac_mask=None)
Definition core.pyx:1150
_to_yac_int_np_array(arr)
Definition core.pyx:358
compute_weights(InterpolationStack interpolation_stack, InterpField|None src_field, InterpField|None tgt_field, comm=None)
Definition core.pyx:1072
get_io_ranks(comm=None)
Returns a list of ranks designated for I/O operations in the given communicator.
Definition core.pyx:1187
__init__(self)
Definition core.pyx:1105
do_search(InterpolationStack interpolation_stack, InterpGrid interp_grid)
Definition core.pyx:1051
Coordinates
Initialization.
Definition core.pyx:373
__call__(self, src=None, *, tgt=None, frac_mask=None)
Definition core.pyx:1119
lonlat2xyz(lon, lat)
using int here is ok.
Definition core.pyx:328
void yac_read_icon_basic_grid_parallel_2(char const *filename, char const *gridname, MPI_Comm comm, struct yac_basic_grid **basic_grid, size_t *cell_coordinate_idx, int **cell_mask)
struct yac_basic_grid * yac_read_scrip_basic_grid(char const *grid_filename, char const *mask_filename, char const *grid_name, int valid_mask_value, char const *name, int use_ll_edges, size_t *cell_coord_idx, size_t **duplicated_cell_idx, yac_int **orig_cell_global_ids, size_t *nbr_duplicated_cells)
int const * location
char const * name
Definition toy_scrip.c:114
void yac_mpi_finalize()
Definition yac_mpi.c:108
void yac_yaxt_init(MPI_Comm comm)
Definition yac_mpi.c:40
void yac_mpi_init()
Definition yac_mpi.c:77