From b1681bb035838f408c448222bb1d45ec9f4f939e Mon Sep 17 00:00:00 2001 From: Weiyuan Jiang Date: Tue, 10 Nov 2026 07:18:35 -0500 Subject: [PATCH 1/3] Add 2d (NX-by-NY) domain decomposition for GEOSldas - preprocess_ldas_routines.F90: new optimize_latlon_2d() that cuts the domain into NX i stripes and NY j stripes (each >= 2 grid cells) and minimizes the max no. of tiles per process: * exact min-max (painter's partition) of one direction given the other, generalized to per-process (block) loads and min stripe width * cube-sphere: same IMS on all faces (MAPL), no process across faces, optimal no. of j stripes per face, NY must be a multiple of 6 * local search on i/j stripe boundaries and reproducible random restarts * writes IMS.rc/JMS.rc (EASE) or GEOSldas.IMS and JMS.rc (cube-sphere) - preprocess_ldas.F90: new option "optimize_2d" - ldas.py, setup_utils.py: optional batinp inputs NX and NY (ntasks_model = NX*NY); 1d layouts still use "optimize" - lenkf_j_template.py: re-optimize the decomposition when NX/NY in LDAS.rc differ from the stored layout, and update LDAS.rc, IMS.rc, JMS.rc --- GEOSldas_App/ldas.py | 1 + GEOSldas_App/ldas_config.py | 9 + GEOSldas_App/ldas_rc.py | 37 +- GEOSldas_App/lenkf_j_template.py | 73 +- GEOSldas_App/preprocess_ldas.F90 | 9 +- GEOSldas_App/preprocess_ldas_routines.F90 | 992 ++++++++++++++++++++++ GEOSldas_App/setup_utils.py | 7 +- 7 files changed, 1096 insertions(+), 32 deletions(-) diff --git a/GEOSldas_App/ldas.py b/GEOSldas_App/ldas.py index d620a9d1..ef45e248 100644 --- a/GEOSldas_App/ldas.py +++ b/GEOSldas_App/ldas.py @@ -155,6 +155,7 @@ def _rc_out_txt(kind): MY_ENSEMBLE_FORCING= self.ExeInputs.get('ENSEMBLE_FORCING', 'NO').upper(), MY_ADAS_EXPDIR = self.adas_expdir, MY_EXPDIR = self.expdir, + MY_TILE_TYPES = '_'.join(self.tile_types), DETECTED_MPI_STACK = "@MPI_STACK@", ) diff --git a/GEOSldas_App/ldas_config.py b/GEOSldas_App/ldas_config.py index 45017669..f2668b1c 100644 --- a/GEOSldas_App/ldas_config.py +++ b/GEOSldas_App/ldas_config.py @@ -443,6 +443,15 @@ def _read_resource_inputs(self, cmdLineArgs): self._verifyResourceInputs() + # optional 2d processor layout: ntasks_model = NX*NY + if 'NX' in self.RmInputs or 'NY' in self.RmInputs: + require('NX' in self.RmInputs and 'NY' in self.RmInputs, 'NX and NY must be specified together') + npes_nx = int(self.RmInputs['NX']) + npes_ny = int(self.RmInputs['NY']) + require(npes_nx >= 1 and npes_ny >= 1, 'NX and NY must be >= 1') + require(npes_nx*npes_ny == int(self.RmInputs['ntasks_model']), + 'ntasks_model (%s) must equal NX*NY (%d*%d)' % (self.RmInputs['ntasks_model'], npes_nx, npes_ny)) + # print rm inputs if self.verbose: print ('\n\nInputs for resource manager:') diff --git a/GEOSldas_App/ldas_rc.py b/GEOSldas_App/ldas_rc.py index 90dd5997..af572423 100644 --- a/GEOSldas_App/ldas_rc.py +++ b/GEOSldas_App/ldas_rc.py @@ -77,24 +77,41 @@ def _copy_nml(self, etcdir): # ----------------------------------------------------------------------------------- def _optimize_layout(self): """ - Run preprocess_ldas.x optimize: writes IMS.rc/JMS.rc to rundir and returns the - NX/NY layout (dict). For cube-sphere tile space, ntasks_model may be adjusted. + Run preprocess_ldas.x optimize (1d) or optimize_2d (NX-by-NY): writes IMS.rc and/or + JMS.rc to rundir and returns the NX/NY layout (dict). ntasks_model may be adjusted. """ + # 2d decomposition (NX-by-NY) unless NX and NY are not specified or the requested layout is + # the 1d layout (cube-sphere: NX=1; lat-lon/EASE: NY=1) + decomp_2d = False + if 'NX' in self.RmInputs: + is_cs = '-CF' in self.ExeInputs['GRIDNAME'] + npes_nx = int(self.RmInputs['NX']) + npes_ny = int(self.RmInputs['NY']) + decomp_2d = not ((is_cs and npes_nx == 1) or (not is_cs and npes_ny == 1)) + if is_cs: + require(npes_ny % 6 == 0, 'NY (%d) must be a multiple of 6 for cube-sphere grid' % npes_ny) + tmp_ = tempfile.NamedTemporaryFile(delete=False) tmp_.close() try: print ("Optimizing... decomposition of processes.... \n") - print ("IMS.rc or JMS.rc would be generated on " + self.rundir) - run_cmd(self.bindir + '/preprocess_ldas.x optimize '+ self.inpdir+'/tile.data ' - + str(self.RmInputs['ntasks_model']) + ' ' + tmp_.name + ' ' + self.rundir + ' ' - + '_'.join(self.tile_types)) + print ("IMS.rc and/or JMS.rc would be generated on " + self.rundir) + if decomp_2d: + run_cmd(self.bindir + '/preprocess_ldas.x optimize_2d '+ self.inpdir+'/tile.data ' + + str(npes_nx) + ' ' + str(npes_ny) + ' ' + tmp_.name + ' ' + self.rundir + ' ' + + '_'.join(self.tile_types)) + else: + run_cmd(self.bindir + '/preprocess_ldas.x optimize '+ self.inpdir+'/tile.data ' + + str(self.RmInputs['ntasks_model']) + ' ' + tmp_.name + ' ' + self.rundir + ' ' + + '_'.join(self.tile_types)) optinxny = parseInputFile(tmp_.name) finally: os.remove(tmp_.name) - if (int(optinxny['NX']) == 1): - if int(optinxny['NY']) != int(self.RmInputs['ntasks_model']): - self.RmInputs['ntasks_model']=optinxny['NY'] - print ('adjust ntasks_model %d for cubed-sphere grid' % int(self.RmInputs['ntasks_model'])) + require('NX' in optinxny and 'NY' in optinxny, 'Optimization of domain decomposition failed') + ntasks_opt = int(optinxny['NX'])*int(optinxny['NY']) + if ntasks_opt != int(self.RmInputs['ntasks_model']): + self.RmInputs['ntasks_model'] = ntasks_opt + print ('adjust ntasks_model %d for cubed-sphere grid' % int(self.RmInputs['ntasks_model'])) return optinxny # ----------------------------------------------------------------------------------- diff --git a/GEOSldas_App/lenkf_j_template.py b/GEOSldas_App/lenkf_j_template.py index 3746dce2..f5fb6c71 100644 --- a/GEOSldas_App/lenkf_j_template.py +++ b/GEOSldas_App/lenkf_j_template.py @@ -228,32 +228,65 @@ ####################################################################### # Domain Decomposition ####################################################################### -set npes_nx = `grep NX: LDAS.rc | cut -d':' -f2 ` -set npes_ny = `grep NY: LDAS.rc | cut -d':' -f2 ` -@ numprocs = $npes_nx * $npes_ny -if( -e IMS.rc ) then - set oldtasks = `head -n 1 IMS.rc` - if($numprocs != $oldtasks) then - $GEOSBIN/preprocess_ldas.x optimize ../input/tile.data $numprocs nothing nothing nothing +# Re-optimize the domain decomposition if NX or NY in LDAS.rc do not match the layout +# stored in IMS.rc/JMS.rc (lat-lon/EASE) or in JMS.rc/GEOSldas.IMS (cube-sphere). +# 1d layout (cube-sphere: NX=1; lat-lon/EASE: NY=1) uses "optimize", otherwise "optimize_2d". + +set npes_nx = `grep '^NX:' LDAS.rc | cut -d':' -f2 ` +set npes_ny = `grep '^NY:' LDAS.rc | cut -d':' -f2 ` + +set gridname = `grep GEOSldas.GRIDNAME LDAS.rc | cut -d':' -f2 | cut -d'-' -f2 | awk '{{print $1}}'` + +set old_nx = 1 +set old_ny = 1 +if ( -e IMS.rc ) set old_nx = `head -n 1 IMS.rc | awk '{{print $1}}'` +if ( -e JMS.rc ) set old_ny = `head -n 1 JMS.rc | awk '{{print $1}}'` +set ims_list = `grep '^GEOSldas.IMS:' LDAS.rc | cut -d':' -f2` +if ( $#ims_list > 0 ) set old_nx = $#ims_list + +if ( $npes_nx != $old_nx || $npes_ny != $old_ny ) then + + echo "re-optimizing domain decomposition for NX = $npes_nx, NY = $npes_ny" + + /bin/rm -f IMS.rc JMS.rc optimized_distribution.rc + + set is_1d = 0 + if ( "$gridname" == "CF" && $npes_nx == 1 ) set is_1d = 1 + if ( "$gridname" != "CF" && $npes_ny == 1 ) set is_1d = 1 + + if ( $is_1d == 1 ) then + @ numprocs = $npes_nx * $npes_ny + $GEOSBIN/preprocess_ldas.x optimize ../input/tile.data $numprocs optimized_distribution.rc . {MY_TILE_TYPES} + else + $GEOSBIN/preprocess_ldas.x optimize_2d ../input/tile.data $npes_nx $npes_ny optimized_distribution.rc . {MY_TILE_TYPES} endif -endif -if( -e JMS.rc ) then - set oldtasks = `head -n 1 JMS.rc | cut -c1-5` - if($numprocs != $oldtasks) then - $GEOSBIN/preprocess_ldas.x optimize ../input/tile.data $numprocs nothing nothing nothing + if ( ! -e optimized_distribution.rc ) then + echo "ERROR: optimization of domain decomposition failed" + exit endif -endif -set gridname = `grep GEOSldas.GRIDNAME LDAS.rc | cut -d':' -f2 | cut -d'-' -f2 | awk '{{print $1}}'` -if ( "$gridname" == "CF" ) then - set new_ny = `echo "NY: "$numprocs` - sed -i "/NY:/c\\\\$new_ny" LDAS.rc -else - set new_nx = `echo "NX: "$numprocs` - sed -i "/NX:/c\\\\$new_nx" LDAS.rc + # replace domain decomposition entries in LDAS.rc + sed -i -e '/^GEOSldas.IMS:/d' -e '/^GEOSldas.IMS_FILE:/d' -e '/^GEOSldas.JMS_FILE:/d' LDAS.rc + foreach line ( "`cat optimized_distribution.rc`" ) + set key = `echo "$line" | awk '{{print $1}}'` + sed -i "/^${{key}}/d" LDAS.rc + echo "$line" >> LDAS.rc + end + /bin/rm -f optimized_distribution.rc + + # keep run directory consistent + /bin/rm -f $HOMDIR/IMS.rc $HOMDIR/JMS.rc + /bin/cp -f LDAS.rc $HOMDIR/ + if ( -e IMS.rc ) /bin/cp -f IMS.rc $HOMDIR/ + if ( -e JMS.rc ) /bin/cp -f JMS.rc $HOMDIR/ + + set npes_nx = `grep '^NX:' LDAS.rc | cut -d':' -f2 ` + set npes_ny = `grep '^NY:' LDAS.rc | cut -d':' -f2 ` endif +@ numprocs = $npes_nx * $npes_ny + ####################################################################### # Create Strip Utility to Remove Multiple Blank Spaces ####################################################################### diff --git a/GEOSldas_App/preprocess_ldas.F90 b/GEOSldas_App/preprocess_ldas.F90 index 6abffea3..efd24321 100644 --- a/GEOSldas_App/preprocess_ldas.F90 +++ b/GEOSldas_App/preprocess_ldas.F90 @@ -12,7 +12,8 @@ program main createZoominRestart, & correctEase, & convert_pert_rst, & - optimize_latlon + optimize_latlon, & + optimize_latlon_2d implicit none @@ -152,6 +153,12 @@ program main call get_tile_types(trim(arg5), int_types) call optimize_latlon(arg1,arg2, arg3, arg4, int_types) + else if (trim(option) == "optimize_2d") then + + ! arg1: tile file, arg2: NX, arg3: NY, arg4: optimized_file, arg5: run_dir, arg6: tile types + call get_tile_types(trim(arg6), int_types) + call optimize_latlon_2d(arg1, arg2, arg3, arg4, arg5, int_types) + else print*, " wrong preprocess option:",option diff --git a/GEOSldas_App/preprocess_ldas_routines.F90 b/GEOSldas_App/preprocess_ldas_routines.F90 index ae46007e..1d811909 100644 --- a/GEOSldas_App/preprocess_ldas_routines.F90 +++ b/GEOSldas_App/preprocess_ldas_routines.F90 @@ -110,6 +110,7 @@ module preprocess_ldas_routines public :: createZoominVegRestart public :: correctEase public :: optimize_latlon + public :: optimize_latlon_2d public :: convert_pert_rst character(10), private :: tmpstring10 @@ -2564,6 +2565,997 @@ end subroutine equal_partition end subroutine optimize_latlon + ! ******************************************************************** + ! + ! subroutine to optimize the 2d domain decomposition (processor layout NX-by-NY) + ! + ! Extends optimize_latlon() from a 1d layout (N_proc-by-1 or 1-by-N_proc) to a 2d layout + ! with N_proc = NX*NY processors (or tasks), excl. OSERVER tasks: + ! - the domain is cut into NX stripes in the i (longitude) direction and + ! NY stripes in the j (latitude) direction + ! - each stripe must be at least two grid cells thick + ! - the stripes are chosen such that the maximum number of land *tiles* per process + ! is minimized (load balance): + ! * for given i stripes, the optimal j stripes (and, for cube-sphere, the optimal + ! no. of j stripes per face) are computed exactly, and vice versa + ! * local search on the i and j stripe boundaries, starting from several initial + ! guesses and random perturbations (iterated local search, reproducible) + ! - NOTE: The decomposition is a tensor product of the i and j stripes (MAPL/ESMF + ! convention; for cube-sphere, the i stripes are also the same on all faces). + ! Because land tiles are distributed very unevenly, the load balance of a 2d + ! decomposition is typically worse than that of a 1d decomposition with the same + ! number of processes. + ! + ! For lat-lon and EASE grid tile spaces: + ! - IMS(k), k=1:NX, IMS(k)>=2, is written into file IMS.rc + ! - JMS(k), k=1:NY, JMS(k)>=2, is written into file JMS.rc + ! For cube-sphere grid tile spaces: + ! - NY must be a multiple of 6 (MAPL convention) + ! - the NY stripes are distributed among the 6 faces (at least 1 stripe per face), and + ! a process never has grid cells from more than one face + ! - IMS(k), k=1:NX, IMS(k)>=2, is the same for all faces (MAPL convention) and is + ! written as GEOSldas.IMS into optimized_file + ! - JMS(k), k=1:NY, JMS(k)>=2, is written face by face into file JMS.rc + ! + ! cube-sphere lat-lon/EASE + ! --------------------------------------------------- + ! NX: NX NX + ! NY: NY NY + ! IMS (rc), JMS.rc IMS.rc, JMS.rc + + subroutine optimize_latlon_2d(fname_tilefile, NX_string, NY_string, optimized_file, run_dir, types) + + character(*), intent(in) :: fname_tilefile ! file name (with path) of tile file (*.til) + character(*), intent(in) :: NX_string ! *string* w/ no. of processors in i direction + character(*), intent(in) :: NY_string ! *string* w/ no. of processors in j direction + character(*), intent(in) :: optimized_file + character(*), intent(in) :: run_dir + integer, optional, intent(in) :: types(:) + + ! local variables + integer, parameter :: min_width = 2 ! min no. of grid cells per process in each direction + integer, parameter :: max_iter = 20 ! max iterations of local search + integer, parameter :: max_perturb = 50 ! max no. of random perturbations + integer, parameter :: max_fail = 10 ! stop after max_fail perturbations w/o improvement + + integer :: NX, NY, N_lon, N_lat, ni, nj, i0, n_zones, L, max_rows + integer :: n, i, j, k, z, s1, istart, b, best, maxload, total_tile, lower_bound, amp, d, n_fail + integer(kind=8) :: seed + integer, allocatable :: typs(:), II(:), JJ(:), ti(:), tj(:), tile_types(:) + integer, allocatable :: colW(:,:), rowW(:,:), xb(:), yb(:), Pi(:,:), Pj(:,:) + integer, allocatable :: IMS(:), JMS(:), best_IMS(:), best_JMS(:) + integer, allocatable :: zone_rows(:), best_zone_rows(:), zone_land(:) + integer, allocatable :: local_tile(:,:) + logical :: isCS, isEASE, use_prefix + character(len=128) :: gridname + character(len=:), allocatable :: IMS_file, JMS_file + character(len=*), parameter :: Iam = 'optimize_latlon_2d' + character(len=400) :: err_msg + + ! ----------------------------- + + read (NX_string,*) NX + read (NY_string,*) NY + + if (present(types)) then + tile_types = types + else + tile_types = [MAPL_LAND] + endif + + call read_tile_types_ij(fname_tilefile, gridname, N_lon, N_lat, typs, II, JJ) + + isCS = (index(gridname,"CF") /= 0) + isEASE = (index(gridname,"EASE") /= 0) + + ni = N_lon + nj = N_lat + + if (isCS) then + ! cube-sphere: e.g., N_lon=180, N_lat=1080 for c180 + if (nj/6 /= ni) then + err_msg = 'wrong im, jm' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + end if + n_zones = 6 ! a "zone" is a cube face + L = ni ! no. of grid cells in j direction per zone + else + n_zones = 1 + L = nj + endif + + ! EASE grid indices are 0-based + i0 = 1 + if (isEASE) i0 = 0 + + ! keep only tiles of requested types; convert to 1-based grid indices + + total_tile = count([(any(tile_types == typs(n)), n=1,size(typs))]) + allocate(ti(total_tile), tj(total_tile)) + k = 0 + do n = 1, size(typs) + if (any(tile_types == typs(n))) then + k = k + 1 + ti(k) = II(n) - i0 + 1 + tj(k) = JJ(n) - i0 + 1 + endif + enddo + deallocate(typs, II, JJ) + + if (any(ti < 1) .or. any(ti > ni) .or. any(tj < 1) .or. any(tj > nj)) then + err_msg = 'tile (i,j) index outside of grid' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + + print*, "total tiles: ", total_tile + + ! check processor layout + + ! MAPL currently assumes that NY is a multiple of 6 for cube-sphere grids + if (isCS .and. mod(NY,6) /= 0) then + err_msg = 'NY must be a multiple of 6 for cube-sphere grid' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + + max_rows = L/min_width + + if (NX < 1 .or. NY < n_zones) then + err_msg = 'NX or NY too small' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + if (NX*min_width > ni) then + err_msg = 'Each processor must have at least 2 cells in i direction. Request smaller NX.' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + if (NY > n_zones*max_rows) then + err_msg = 'Each processor must have at least 2 cells in j direction. Request smaller NY.' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + + print*, "NX, NY: ", NX, NY + + allocate(zone_rows(n_zones), zone_land(n_zones)) + do z = 1, n_zones + zone_land(z) = count( tj > (z-1)*L .and. tj <= z*L ) + enddo + + allocate(IMS(NX), JMS(NY), xb(ni), yb(nj)) + allocate(rowW(nj, NX), colW(ni, NY)) + + ! prefix sums of the no. of tiles along i for each j line (Pi) and along j for each + ! i line (Pj), used to quickly compute the no. of tiles of each j (i) line within each + ! i (j) stripe (skipped if too large) + + use_prefix = (real(ni+1)*real(nj+1) <= 1.25e8) + if (use_prefix) then + allocate(Pi(nj, 0:ni), source=0) + allocate(Pj(ni, 0:nj), source=0) + do n = 1, total_tile + Pi(tj(n), ti(n)) = Pi(tj(n), ti(n)) + 1 + Pj(ti(n), tj(n)) = Pj(ti(n), tj(n)) + 1 + enddo + do i = 1, ni + Pi(:,i) = Pi(:,i) + Pi(:,i-1) + enddo + do j = 1, nj + Pj(:,j) = Pj(:,j) + Pj(:,j-1) + enddo + endif + + ! lower bound for the max no. of tiles per process: + ! average no. of tiles per process, and for cube-sphere each face must have at least + ! one j stripe, i.e., each face has at most NY-5 j stripes + lower_bound = ceiling(real(total_tile)/real(NX*NY)) + if (n_zones > 1) then + do z = 1, n_zones + lower_bound = max(lower_bound, ceiling(real(zone_land(z))/real(NX*min(max_rows,NY-n_zones+1)))) + enddo + endif + + ! minimize the maximum no. of tiles per process (load balance) + ! + ! starting from different initial i stripes: + ! 1: i stripes with balanced no. of tiles (as in 1d decomposition) + ! 2: i stripes of equal width + ! followed by random perturbations of the best i stripes found so far + ! (iterated local search) + + best = huge(1) + n_fail = 0 + seed = 20240101_8 + + do istart = 1, 2+max_perturb + + if (best <= lower_bound) exit + + select case (istart) + case (1) + colW(:,1) = 0 + do n = 1, total_tile + colW(ti(n),1) = colW(ti(n),1) + 1 + enddo + call minmax_partition(colW(:,1:1), IMS, min_width, b) + case (2) + IMS = ni/NX + IMS(1:mod(ni,NX)) = IMS(1:mod(ni,NX)) + 1 + case default + IMS = best_IMS + do k = 1, NX-1 + ! shift boundary between i stripes k and k+1 by a random no. of cells + amp = max(1, (IMS(k)+IMS(k+1))/4) + d = random_int(-amp, amp) + d = max(d, min_width - IMS(k)) + d = min(d, IMS(k+1) - min_width) + IMS(k) = IMS(k) + d + IMS(k+1) = IMS(k+1) - d + enddo + end select + + call improve_decomposition(IMS, JMS, zone_rows, maxload) + + if (maxload < best) then + if (istart > 2) print*, "perturbation, max tiles per process: ", istart-2, maxload + best = maxload + best_IMS = IMS + best_JMS = JMS + best_zone_rows = zone_rows + n_fail = 0 + else if (istart > 2) then + n_fail = n_fail + 1 + if (n_fail >= max_fail) exit + endif + + if (istart <= 2) print*, "initial guess, max tiles per process: ", istart, maxload + + enddo + + IMS = best_IMS + JMS = best_JMS + zone_rows = best_zone_rows + + ! verify the decomposition + + if (sum(IMS) /= ni .or. any(IMS < min_width)) then + err_msg = 'wrong domain distribution in i direction' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + if (any(JMS < min_width)) then + err_msg = 'wrong domain distribution in j direction' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + ! each zone (cube face) must be covered exactly by its j stripes + s1 = 0 + do z = 1, n_zones + if (sum(JMS(s1+1:s1+zone_rows(z))) /= L) then + err_msg = 'one or more processes may have tiles from two or more faces' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + s1 = s1 + zone_rows(z) + enddo + + call widths_to_blocks(IMS, xb) + call widths_to_blocks(JMS, yb) + allocate(local_tile(NX,NY), source=0) + do n = 1, total_tile + local_tile(xb(ti(n)), yb(tj(n))) = local_tile(xb(ti(n)), yb(tj(n))) + 1 + enddo + + if (sum(local_tile) /= total_tile) then + err_msg = 'wrong distribution' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + + print*, "Average tiles per process: ", real(total_tile)/real(NX*NY) + print*, "Max tiles per process: ", maxval(local_tile) + print*, "Min tiles per process: ", minval(local_tile) + print*, "Lower bound of max tiles : ", lower_bound + print*, "Load balance (avg/max) : ", real(total_tile)/real(NX*NY)/real(max(maxval(local_tile),1)) + print*, "IMS: ", IMS + print*, "JMS: ", JMS + if (isCS) print*, "j stripes per face: ", zone_rows + + ! write output + + if (isCS) then + + open(10,file=optimized_file,action='write') + write(10,'(A)') "GEOSldas.GRIDNAME: " // trim(gridname) + write(10,'(A)') "GEOSldas.GRID_TYPE: Cubed-Sphere" + write(10,'(A)') "GEOSldas.NF: 6" + write(10,'(A,I6)') "GEOSldas.IM_WORLD: ", ni + write(10,'(A)') "GEOSldas.LM: 1" + write(10,'(A,I5)') "NX: ", NX + write(10,'(A,I5)') "NY: ", NY + write(10,'(A,*(I6))') "GEOSldas.IMS: ", IMS + write(10,'(A)') "GEOSldas.JMS_FILE: JMS.rc" + close(10) + + JMS_file = trim(run_dir)//"/JMS.rc" + open(10,file=JMS_file ,action='write') + write(10,'(I5,I5)') NY, maxval(zone_rows) + do n = 1, NY + write(10,'(I8)') JMS(n) + enddo + close(10) + + else + + if (index(gridname, 'SMAP') /=0 ) then + gridname = trim(adjustl(gridname)) + gridname = gridname(6:) + gridname(7:7) = '_' ! replace '-' with '_' + endif + + open(10,file=optimized_file, action='write') + write(10,'(A)') "GEOSldas.GRID_TYPE: EASE" + write(10,'(A)') "GEOSldas.GRIDNAME: "//trim(gridname) + write(10,'(A)') "GEOSldas.LM: 1" + write(10,'(A)') "GEOSldas.POLE: XY" + write(10,'(A)') "GEOSldas.DATELINE: DE" + write(10,'(A,I6)') "GEOSldas.IM_WORLD: ", N_lon + write(10,'(A,I6)') "GEOSldas.JM_WORLD: ", N_lat + write(10,'(A,I5)') "NX: ", NX + write(10,'(A,I5)') "NY: ", NY + write(10,'(A)') "GEOSldas.IMS_FILE: IMS.rc" + write(10,'(A)') "GEOSldas.JMS_FILE: JMS.rc" + close(10) + + IMS_file = trim(run_dir)//"/IMS.rc" + open(10,file=IMS_file,action='write') + write(10,'(I5)') NX + do n = 1, NX + write(10,'(I8)') IMS(n) + enddo + close(10) + + JMS_file = trim(run_dir)//"/JMS.rc" + open(10,file=JMS_file,action='write') + write(10,'(I5)') NY + do n = 1, NY + write(10,'(I8)') JMS(n) + enddo + close(10) + + endif + + contains + + ! --------------------------------------------------- + + integer function random_int(lo, hi) + + ! reproducible pseudo-random integer in [lo,hi] (linear congruential generator) + + integer, intent(in) :: lo, hi + + seed = mod(1103515245_8*seed + 12345_8, 2147483648_8) + random_int = lo + int(mod(seed/65536_8, int(hi-lo+1,8))) + + end function random_int + + ! --------------------------------------------------- + + subroutine improve_decomposition(IMS, JMS, zr, F) + + ! starting from i stripes IMS, minimize the max no. of tiles per process F by + ! alternating optimization of i and j stripes and local search on the i stripes + + integer, intent(inout) :: IMS(:) + integer, intent(out) :: JMS(:), zr(:), F + + integer :: trial_IMS(size(IMS)), trial_JMS(size(JMS)), trial_zr(size(zr)) + integer :: Ft, b, t, d, sgn, iter, z, s + logical :: improved + + call rows_given_cols(IMS, JMS, zr, F) + + do iter = 1, max_iter + + if (F <= lower_bound) exit + + improved = .false. + + ! i stripes given j stripes + + call cols_given_rows(JMS, trial_IMS, b, F-1) + if (b < F) then + call rows_given_cols(trial_IMS, trial_JMS, trial_zr, Ft, F-1) + if (Ft < F) then + IMS = trial_IMS ; JMS = trial_JMS ; zr = trial_zr ; F = Ft + improved = .true. + endif + endif + + ! local search: shift the boundary between i stripes t and t+1 by +/-1, 2, 4, ... + ! cells, with optimal j stripes for each trial + + do t = 1, size(IMS)-1 + d = 1 + do while (d < max(IMS(t), IMS(t+1))) + do sgn = -1, 1, 2 + trial_IMS = IMS + trial_IMS(t) = IMS(t) + sgn*d + trial_IMS(t+1) = IMS(t+1) - sgn*d + if (min(trial_IMS(t), trial_IMS(t+1)) < min_width) cycle + call rows_given_cols(trial_IMS, trial_JMS, trial_zr, Ft, F-1) + if (Ft < F) then + IMS = trial_IMS ; JMS = trial_JMS ; zr = trial_zr ; F = Ft + improved = .true. + endif + enddo + d = 2*d + enddo + enddo + + ! local search: shift the boundary between j stripes t and t+1 (of the same face) by + ! +/-1, 2, 4, ... cells, with optimal i stripes for each trial + + z = 1 + s = zr(1) ! last j stripe of face z + do t = 1, size(JMS)-1 + if (t == s) then + ! j stripes t and t+1 are on different faces + z = z + 1 + s = s + zr(z) + cycle + endif + d = 1 + do while (d < max(JMS(t), JMS(t+1))) + do sgn = -1, 1, 2 + trial_JMS = JMS + trial_JMS(t) = JMS(t) + sgn*d + trial_JMS(t+1) = JMS(t+1) - sgn*d + if (min(trial_JMS(t), trial_JMS(t+1)) < min_width) cycle + call cols_given_rows(trial_JMS, trial_IMS, Ft, F-1) + if (Ft < F) then + IMS = trial_IMS ; JMS = trial_JMS ; F = Ft + improved = .true. + endif + enddo + d = 2*d + enddo + enddo + + if (.not. improved) exit + + enddo + + end subroutine improve_decomposition + + ! --------------------------------------------------- + + subroutine rows_given_cols(IMS, JMS, zr, F, upper) + + ! optimal j stripes JMS (and, for cube-sphere, optimal no. of j stripes per face zr) + ! for given i stripes IMS; F is the resulting max no. of tiles per process + ! + ! If upper is present, only decompositions with F <= upper are of interest; if there + ! is none, F=upper+1 is returned and JMS, zr are undefined. + + integer, intent(in) :: IMS(:) + integer, intent(out) :: JMS(:), zr(:), F + integer, intent(in), optional :: upper + + integer :: z, s, j, lo, hi, mid, b + integer :: fmin(n_zones), fmax(n_zones) + integer, allocatable :: Pz(:,:,:) + + call build_rowW(IMS) + + if (n_zones == 1) then + zr(1) = size(JMS) + call minmax_partition(rowW, JMS, min_width, F, upper) + return + endif + + ! prefix sums along j for each face + allocate(Pz(size(IMS), 0:L, n_zones)) + do z = 1, n_zones + Pz(:,0,z) = 0 + do j = 1, L + Pz(:,j,z) = Pz(:,j-1,z) + rowW((z-1)*L+j,:) + enddo + enddo + + ! bisection on the max load: the smallest load for which the NY j stripes can be + ! distributed among the faces, i.e., sum(fmin) <= NY <= sum(fmax), where fmin/fmax is + ! the min/max no. of j stripes of a face for the given max load + + lo = 0 + hi = maxval(Pz(:,L,:)) + + if (present(upper)) then + if (upper < hi) then + if (.not. faces_feasible(Pz, upper, min_width, NY)) then + F = upper + 1 + return + endif + hi = upper + endif + endif + + do while (lo < hi) + mid = lo + (hi-lo)/2 + if (faces_feasible(Pz, mid, min_width, NY)) then + hi = mid + else + lo = mid + 1 + endif + enddo + + do z = 1, n_zones + call count_segments(Pz(:,:,z), lo, min_width, fmin(z), fmax(z)) + enddo + zr = fmin + + ! remaining j stripes go to the faces with the most tiles per stripe + do while (sum(zr) < NY) + z = maxloc(real(zone_land)/real(zr), DIM=1, MASK = zr < fmax) + zr(z) = zr(z) + 1 + enddo + + F = 0 + s = 0 + do z = 1, n_zones + call minmax_partition(rowW((z-1)*L+1:z*L,:), JMS(s+1:s+zr(z)), min_width, b) + F = max(F, b) + s = s + zr(z) + enddo + + end subroutine rows_given_cols + + + ! --------------------------------------------------- + + subroutine cols_given_rows(JMS, IMS, F, upper) + + ! optimal i stripes IMS (same for all faces) for given j stripes JMS + ! (see minmax_partition for upper) + + integer, intent(in) :: JMS(:) + integer, intent(out) :: IMS(:), F + integer, intent(in), optional :: upper + + integer :: n, y, s + + if (use_prefix) then + s = 0 + do y = 1, size(JMS) + colW(:,y) = Pj(:,s+JMS(y)) - Pj(:,s) + s = s + JMS(y) + enddo + else + call widths_to_blocks(JMS, yb) + colW = 0 + do n = 1, total_tile + colW(ti(n), yb(tj(n))) = colW(ti(n), yb(tj(n))) + 1 + enddo + endif + call minmax_partition(colW, IMS, min_width, F, upper) + + end subroutine cols_given_rows + + ! --------------------------------------------------- + + subroutine build_rowW(IMS) + + ! rowW(j,x): no. of tiles of j line within i stripe x + + integer, intent(in) :: IMS(:) + + integer :: n, x, s + + if (use_prefix) then + s = 0 + do x = 1, size(IMS) + rowW(:,x) = Pi(:,s+IMS(x)) - Pi(:,s) + s = s + IMS(x) + enddo + else + call widths_to_blocks(IMS, xb) + rowW = 0 + do n = 1, total_tile + rowW(tj(n), xb(ti(n))) = rowW(tj(n), xb(ti(n))) + 1 + enddo + endif + + end subroutine build_rowW + + ! --------------------------------------------------- + + subroutine widths_to_blocks(widths, blk) + + ! map each grid index to the stripe (block) that contains it + + integer, intent(in) :: widths(:) + integer, intent(out) :: blk(:) + + integer :: m, s + + s = 0 + do m = 1, size(widths) + blk(s+1:s+widths(m)) = m + s = s + widths(m) + enddo + + end subroutine widths_to_blocks + + end subroutine optimize_latlon_2d + + ! ******************************************************************** + + subroutine minmax_partition(W, widths, min_width, bottleneck, upper) + + ! Partition the n=size(W,1) lines of W into k=size(widths) contiguous segments, each at + ! least min_width lines wide, such that the maximum (across segments and across the + ! m=size(W,2) blocks) of the segment sums of W(:,block) is minimized. + ! + ! Exact. Requires W>=0. Bisection on the bottleneck value; for a given value, the range + ! of feasible no. of segments is computed with dynamic programming (count_segments), and + ! the partition with exactly k segments is obtained with partition_k. + ! + ! If upper is present, only partitions with bottleneck <= upper are of interest; if there + ! is none, bottleneck=upper+1 is returned and widths is undefined. + + integer, intent(in) :: W(:,:) + integer, intent(out) :: widths(:) + integer, intent(in) :: min_width + integer, intent(out) :: bottleneck + integer, intent(in), optional :: upper + + integer, allocatable :: P(:,:) + integer :: n, m, k, j, lo, hi, mid + logical :: ok + character(len=*), parameter :: Iam = 'minmax_partition' + character(len=400) :: err_msg + + n = size(W,1) + m = size(W,2) + k = size(widths) + + if (k < 1 .or. n < k*min_width) then + err_msg = 'too many partitions for the number of grid cells' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + + ! prefix sums, P(:,j) = sum of lines 1:j + allocate(P(m,0:n)) + P(:,0) = 0 + do j = 1, n + P(:,j) = P(:,j-1) + W(j,:) + enddo + + lo = 0 + hi = maxval(P(:,n)) + + if (present(upper)) then + if (upper < hi) then + if (.not. k_in_range(upper)) then + bottleneck = upper + 1 + return + endif + hi = upper + endif + endif + + do while (lo < hi) + mid = lo + (hi-lo)/2 + if (k_in_range(mid)) then + hi = mid + else + lo = mid + 1 + endif + enddo + + call partition_k(P, lo, min_width, widths, ok) + + if (.not. ok) then + ! not all no. of segments between the min and max no. of segments are feasible (rare); + ! continue bisection with exact test for k segments + hi = maxval(P(:,n)) + if (present(upper)) hi = min(hi, upper) + lo = lo + 1 + do while (lo < hi) + mid = lo + (hi-lo)/2 + call partition_k(P, mid, min_width, widths, ok) + if (ok) then + hi = mid + else + lo = mid + 1 + endif + enddo + call partition_k(P, lo, min_width, widths, ok) + if (.not. ok) then + if (present(upper)) then + bottleneck = upper + 1 + return + endif + err_msg = 'partition failed' + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + endif + endif + + bottleneck = lo + + contains + + logical function k_in_range(B) + integer, intent(in) :: B + integer :: fmin, fmax + call count_segments(P, B, min_width, fmin, fmax) + k_in_range = (fmin <= k .and. k <= fmax) + end function k_in_range + + end subroutine minmax_partition + + ! ******************************************************************** + + logical function faces_feasible(Pz, B, min_width, NY) + + ! cube-sphere: NY j stripes can be distributed among the faces with max load B, i.e., + ! sum(fmin) <= NY <= sum(fmax), where fmin/fmax is the min/max no. of j stripes of + ! a face for max load B + + integer, intent(in) :: Pz(:,0:,:) ! prefix sums along j for each face, Pz(1:m,0:L,1:6) + integer, intent(in) :: B + integer, intent(in) :: min_width + integer, intent(in) :: NY + + integer :: z, smin, smax, fmin, fmax + + smin = 0 + smax = 0 + do z = 1, size(Pz,3) + call count_segments(Pz(:,:,z), B, min_width, fmin, fmax) + smin = smin + fmin + smax = smax + max(fmax,0) + if (fmax < 0 .or. smin > NY) then + faces_feasible = .false. + return + endif + enddo + faces_feasible = (smin <= NY .and. NY <= smax) + + end function faces_feasible + + ! ******************************************************************** + + subroutine max_reach(P, B, g) + + ! g(s): last line e such that the segment s:e does not exceed B in any block + ! (g(s)=s-1 if line s alone exceeds B); g is non-decreasing + + integer, intent(in) :: P(:,0:) ! prefix sums, P(1:m,0:n) + integer, intent(in) :: B + integer, intent(out) :: g(:) + + integer :: n, s, e + + n = size(P,2) - 1 + e = 0 + do s = 1, n + e = max(e, s-1) + do while (e < n) + if (any(P(:,e+1) - P(:,s-1) > B)) exit + e = e + 1 + enddo + g(s) = e + enddo + + end subroutine max_reach + + ! ******************************************************************** + + subroutine count_segments(P, B, min_width, fmin, fmax) + + ! Minimum (fmin) and maximum (fmax) no. of contiguous segments, each at least min_width + ! lines wide, of the n lines with prefix sums P such that no segment exceeds B in any + ! block. fmin=n+1 and fmax=-1 if impossible. + ! + ! Dynamic programming over the end line e of segments; segment s:e is valid if + ! s0(e) <= s <= e-min_width+1, where s0(e) is the first s with g(s)>=e. The window + ! minimum/maximum is computed with monotone queues, i.e., O(n) operations. + + integer, intent(in) :: P(:,0:) ! prefix sums, P(1:m,0:n) + integer, intent(in) :: B + integer, intent(in) :: min_width + integer, intent(out) :: fmin, fmax + + integer, allocatable :: g(:), lmin(:), lmax(:), qmin(:), qmax(:) + integer :: n, e, q, s0, hmin, tmin, hmax, tmax + + n = size(P,2) - 1 + + allocate(g(n), lmin(0:n), lmax(0:n), qmin(n+1), qmax(n+1)) + call max_reach(P, B, g) + + lmin = n + 1 ! unreachable + lmax = -1 ! unreachable + lmin(0) = 0 + lmax(0) = 0 + + hmin = 1 ; tmin = 0 + hmax = 1 ; tmax = 0 + s0 = 1 + + do e = min_width, n + + ! candidate end of previous segment q=s-1 with s=e-min_width+1 + q = e - min_width + if (lmin(q) <= n) then + do while (tmin >= hmin) + if (lmin(qmin(tmin)) < lmin(q)) exit + tmin = tmin - 1 + enddo + tmin = tmin + 1 ; qmin(tmin) = q + endif + if (lmax(q) >= 0) then + do while (tmax >= hmax) + if (lmax(qmax(tmax)) > lmax(q)) exit + tmax = tmax - 1 + enddo + tmax = tmax + 1 ; qmax(tmax) = q + endif + + do while (s0 <= n) + if (g(s0) >= e) exit + s0 = s0 + 1 + enddo + + ! remove q < s0-1 + do while (hmin <= tmin) + if (qmin(hmin) >= s0-1) exit + hmin = hmin + 1 + enddo + do while (hmax <= tmax) + if (qmax(hmax) >= s0-1) exit + hmax = hmax + 1 + enddo + + if (hmin <= tmin) lmin(e) = lmin(qmin(hmin)) + 1 + if (hmax <= tmax) lmax(e) = lmax(qmax(hmax)) + 1 + + enddo + + fmin = lmin(n) + fmax = lmax(n) + + end subroutine count_segments + + ! ******************************************************************** + + subroutine partition_k(P, B, min_width, widths, ok) + + ! Partition of the n lines with prefix sums P into exactly k=size(widths) contiguous + ! segments, each at least min_width lines wide, such that no segment exceeds B in + ! any block. ok=.false. if impossible. Dynamic programming, O(k*n) operations. + + integer, intent(in) :: P(:,0:) ! prefix sums, P(1:m,0:n) + integer, intent(in) :: B + integer, intent(in) :: min_width + integer, intent(out) :: widths(:) + logical, intent(out) :: ok + + integer, allocatable :: g(:), s0(:), C(:) + logical, allocatable :: reach(:,:) + integer :: n, k, e, ip, q, s, lo, hi + + n = size(P,2) - 1 + k = size(widths) + + allocate(g(n), s0(n), C(-1:n), reach(0:n,0:k)) + call max_reach(P, B, g) + + ! s0(e): first s with g(s) >= e (n+1 if none) + s = 1 + do e = 1, n + do while (s <= n) + if (g(s) >= e) exit + s = s + 1 + enddo + s0(e) = s + enddo + + ! reach(e,ip): lines 1:e can be partitioned into ip valid segments + reach = .false. + reach(0,0) = .true. + do ip = 1, k + C(-1) = 0 + do q = 0, n + C(q) = C(q-1) + if (reach(q,ip-1)) C(q) = C(q) + 1 + enddo + do e = min_width, n + lo = s0(e) - 1 + hi = e - min_width + if (lo <= hi) reach(e,ip) = (C(hi) - C(lo-1) > 0) + enddo + enddo + + ok = reach(n,k) + if (.not. ok) return + + ! trace back + e = n + do ip = k, 1, -1 + do q = e - min_width, s0(e) - 1, -1 + if (reach(q,ip-1)) exit + enddo + widths(ip) = e - q + e = q + enddo + + end subroutine partition_k + + ! ******************************************************************** + + subroutine read_tile_types_ij(fname_tilefile, gridname, N_lon, N_lat, typs, II, JJ) + + ! read tile type and (i,j) grid indices of all tiles from tile file (ASCII or nc4) + + character(*), intent(in) :: fname_tilefile + character(*), intent(out) :: gridname + integer, intent(out) :: N_lon, N_lat + integer, allocatable, intent(out) :: typs(:), II(:), JJ(:) + + integer :: n_tiles, n_grids, file_type, status, n, IM(2), JM(2) + integer, allocatable :: iTable(:,:) + character(len=128) :: GNames(2) + character(len=256) :: tmpLine + real :: tmpreal + logical :: file_exist + character(len=*), parameter :: Iam = 'read_tile_types_ij' + character(len=400) :: err_msg + + inquire(file=trim(fname_tilefile),exist=file_exist) + if( .not. file_exist) then + err_msg = 'tile file does not exist: ' //trim(fname_tilefile) + call ldas_abort(LDAS_GENERIC_ERROR, Iam, err_msg) + end if + + call MAPL_NCIOGetFileType(trim(fname_tilefile), file_type, rc=status) + + if (file_type == MAPL_FILETYPE_NC4) then + + call MAPL_ReadTilingNC4(trim(fname_tilefile), GridName=GNames, im=IM, jm=JM, n_Grids=n_grids, n_tiles=n_tiles, & + iTable=iTable, rc=status) + gridname = GNames(1) + N_lon = IM(1) + N_lat = JM(1) + typs = iTable(:,0) + II = iTable(:,2) + JJ = iTable(:,3) + + else + + open (10, file=trim(fname_tilefile), form='formatted', action='read') + read (10,*) n_tiles + read (10,*) n_grids + read (10,*) gridname + read (10,*) N_lon + read (10,*) N_lat + + allocate(typs(n_tiles), II(n_tiles), JJ(n_tiles)) + + ! skip info of second (ocean) grid; some EASE *.til files state "n_grids=1" but + ! still include the three header lines of the second grid (see correctEase()) + read (10,'(A)') tmpLine + if (n_grids == 2 .or. index(tmpLine,'OCEAN') /= 0) then + read (10,*) + read (10,*) + read (10,'(A)') tmpLine + endif + + read (tmpLine,*) typs(1), tmpreal, tmpreal, tmpreal, II(1), JJ(1) + do n = 2, n_tiles + read (10,*) typs(n), tmpreal, tmpreal, tmpreal, II(n), JJ(n) + enddo + close(10) + + endif + + end subroutine read_tile_types_ij + ! ******************************************************************** subroutine convert_pert_rst(pfile_name,pfile_nc4,in_path,exp_id) diff --git a/GEOSldas_App/setup_utils.py b/GEOSldas_App/setup_utils.py index a007f947..1e1130ce 100644 --- a/GEOSldas_App/setup_utils.py +++ b/GEOSldas_App/setup_utils.py @@ -362,7 +362,7 @@ def getResourceKeys(option): # Required resource manager input fields # ------ RmInpKeys ={'required' : ['account', 'walltime', 'ntasks_model'], - 'optional' : ['job_name', 'qos', 'oserver_nodes', 'writers-per-node', 'ntasks-per-node', 'constraint'] + 'optional' : ['job_name', 'qos', 'oserver_nodes', 'writers-per-node', 'ntasks-per-node', 'constraint', 'NX', 'NY'] } require(option in RmInpKeys, ' "%s" option is not supported' % option) @@ -401,6 +401,11 @@ def printResourceInputSampleFile(): print ('# - ntasks-per-node = requesting fewer ntasks-per-node than total number of cores per node increases allocated memory;') print ('# ntasks_model should be a multiple of ntasks-per-node') print ('# - constraint = name of chip set(s) (NCCS default is "[mil|cas]", NAS default is "cas_ait")') + print ('# - NX, NY = 2d processor layout (NX-by-NY) for domain decomposition; must be specified together,') + print ('# and ntasks_model must equal NX*NY;') + print ('# default is a 1d layout (cube-sphere: 1-by-ntasks_model; lat-lon/EASE: ntasks_model-by-1);') + print ('# each process must have at least 2 grid cells in each direction;') + print ('# for cube-sphere grids, NY must be a multiple of 6') print ('#') for key in optionalKeys: print ('#'+key + ':') From 9dcbfcb8d4142b5789e4c2d0f064f8471d8ff700 Mon Sep 17 00:00:00 2001 From: Weiyuan Jiang Date: Tue, 10 Nov 2026 10:54:48 -0500 Subject: [PATCH 2/3] Allow ldas_setup and mock regression to run on macOS - ldas_setup: set the stack limit to the hard limit (unlimited at NCCS/NAS) instead of RLIM_INFINITY; if python cannot change the stack limit (macOS), print a warning to stderr and keep the current limit - mock_regression.py: * patch the legacy setrlimit call in ref installs the same way * normalize temporary file names under $TMPDIR (macOS), not only /tmp * compare 'ldas_setup sample' stdout only (stderr has python warnings with install-specific paths) * set PERTURBATIONS=1 for offline ensemble cases (required for NUM_LDAS_ENSEMBLE>1 since 27d63bc) --- GEOSldas_App/ldas_setup | 8 +++++++- GEOSldas_App/tests/mock_regression.py | 29 ++++++++++++++++++++------- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/GEOSldas_App/ldas_setup b/GEOSldas_App/ldas_setup index 84242e91..07cd7a3d 100755 --- a/GEOSldas_App/ldas_setup +++ b/GEOSldas_App/ldas_setup @@ -143,7 +143,13 @@ def parseCmdLine(): def main(): - resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY)) + # raise the stack limit to the hard limit (unlimited at NCCS, NAS); macOS rejects + # changes of the stack limit from within python, in which case keep the default + _, stack_hard = resource.getrlimit(resource.RLIMIT_STACK) + try: + resource.setrlimit(resource.RLIMIT_STACK, (stack_hard, stack_hard)) + except (ValueError, OSError): + print('WARNING: cannot raise stack limit; using current limit', file=sys.stderr) #convert command line to dictionary args = vars(parseCmdLine()) diff --git a/GEOSldas_App/tests/mock_regression.py b/GEOSldas_App/tests/mock_regression.py index 53bf7994..14813d17 100644 --- a/GEOSldas_App/tests/mock_regression.py +++ b/GEOSldas_App/tests/mock_regression.py @@ -151,6 +151,13 @@ def list_py_modules(commit): return [os.path.basename(l) for l in out.split() if l.endswith('.py')] +LEGACY_SETRLIMIT = b"resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))" +PORTABLE_SETRLIMIT = b"""_, stack_hard = resource.getrlimit(resource.RLIMIT_STACK) + try: + resource.setrlimit(resource.RLIMIT_STACK, (stack_hard, stack_hard)) + except (ValueError, OSError): + print('WARNING: cannot raise stack limit; using current limit', file=sys.stderr)""" + DISCOVER_BCS = b"/discover/nobackup/projects/gmao/bcs_shared/fvInput/ExtData/esm/tiles" DISCOVER_MWRTM = b"/discover/nobackup/projects/gmao/smap/LDAS_inputs_for_LADAS/RTM_params/RTMParam_SMAP_L4SM_v006/" @@ -169,6 +176,8 @@ def make_install(dest, commit, site='NCCS', data_root=None): data = git_show(commit, f) # emulate cmake configure_file(@ONLY) for all files (only ldas.py has placeholders) data = data.replace(b'@GEOS_SITE@', site.encode()).replace(b'@MPI_STACK@', b'openmpi') + # older ldas_setup (ref commits) requests an unlimited hard stack limit, which fails on macOS + data = data.replace(LEGACY_SETRLIMIT, PORTABLE_SETRLIMIT) if data_root: data = data.replace(DISCOVER_BCS, os.path.join(data_root, 'bcs').encode()) data = data.replace(DISCOVER_MWRTM, os.path.join(data_root, 'mwrtm').encode() + b'/') @@ -304,7 +313,7 @@ def add(name, upd=(), drop=(), batinp=None, expect='same', site='NCCS', cpl=None 'MWRTM_PATH': os.path.join(D['root'], 'mwrtm'), 'ENSEMBLE_FORCING': 'YES', 'MET_PATH': os.path.join(D['root'], 'met', 'ensmet')}) - add('r1_zoom_ens_assim', {'NUM_LDAS_ENSEMBLE': '2', 'LAND_ASSIM': 'YES', + add('r1_zoom_ens_assim', {'NUM_LDAS_ENSEMBLE': '2', 'LAND_ASSIM': 'YES', 'PERTURBATIONS': '1', 'MWRTM_PATH': os.path.join(D['root'], 'mwrtm'), 'MINLAT': '20.', 'MAXLAT': '50.'}) add('r3_catchcn', {'RESTART': '3', 'LSM_CHOICE': '2'}) @@ -321,10 +330,10 @@ def add(name, upd=(), drop=(), batinp=None, expect='same', site='NCCS', cpl=None 'oserver_nodes': '1', 'writers-per-node': '3'}) add('tile_txt', {'TILE_FILE_FORMAT': 'TXT'}) # restart staging edge cases (phase 4) - add('r3_ens3_fallback', {'RESTART': '3', 'NUM_LDAS_ENSEMBLE': '3'}) # no ens0002 -> member-0 files - add('r1_ens2_all_types', {'NUM_LDAS_ENSEMBLE': '2', 'TILE_TYPES': '100 19 20', 'DO_ISSM': '1', + add('r3_ens3_fallback', {'RESTART': '3', 'NUM_LDAS_ENSEMBLE': '3', 'PERTURBATIONS': '1'}) # no ens0002 -> member-0 files + add('r1_ens2_all_types', {'NUM_LDAS_ENSEMBLE': '2', 'PERTURBATIONS': '1', 'TILE_TYPES': '100 19 20', 'DO_ISSM': '1', 'RUN_ROUTE': '1'}) - add('r2_ens2_all_types', {'RESTART': '2', 'NUM_LDAS_ENSEMBLE': '2', 'TILE_TYPES': '100 19 20', + add('r2_ens2_all_types', {'RESTART': '2', 'NUM_LDAS_ENSEMBLE': '2', 'PERTURBATIONS': '1', 'TILE_TYPES': '100 19 20', 'DO_ISSM': '1', 'RUN_ROUTE': '1'}) add('r1_lake_only_zoom', {'TILE_TYPES': '19', 'MINLAT': '20.'}) add('rM_lake', {'RESTART': 'M', 'TILE_TYPES': '100 19'}) @@ -363,6 +372,11 @@ def _last_error(exphome): return (errs or log or [''])[-1] +# temporary file names: /tmp on Linux, $TMPDIR (/var/folders/...) on macOS +_TMP_DIRS = sorted({'/tmp', tempfile.gettempdir(), os.path.realpath(tempfile.gettempdir())}, key=len, reverse=True) +TMP_RE = r'(?:/private)?(?:%s)/+tmp[^\s/]*' % '|'.join(re.escape(d.rstrip('/')) for d in _TMP_DIRS) + + def compare_logs(ref_log, new_log, same=(), out=sys.stdout): """Compare setup output, ignoring per-run roots and temporary file names.""" pairs = [(os.path.abspath(ref), os.path.abspath(new)) for ref, new in same] @@ -370,7 +384,7 @@ def compare_logs(ref_log, new_log, same=(), out=sys.stdout): def normalize(log, which): for i, (ref, new) in enumerate(pairs): log = log.replace((ref, new)[which], '' % i) - return re.sub(r'/tmp/tmp[^\s/]*', '', log).splitlines() + return re.sub(TMP_RE, '', log).splitlines() with open(ref_log, errors='replace') as f: ref_lines = normalize(f.read(), 0) @@ -433,10 +447,11 @@ def expdir(which, name): return os.path.join(work, which, name, 'testexp') names = o.case or list(C) if not o.case: - # 'ldas_setup sample' output must be identical + # 'ldas_setup sample' output must be identical (stdout only: stderr has python + # warnings with install-specific paths) for opt in ['--exeinp', '--batinp']: outs = [sp.run([sys.executable, os.path.join(inst(w, 'NCCS'), 'ldas_setup'), 'sample', opt], - stdout=sp.PIPE, stderr=sp.STDOUT).stdout for w in ['ref', 'new']] + stdout=sp.PIPE, stderr=sp.DEVNULL).stdout for w in ['ref', 'new']] same = outs[0] == outs[1] and len(outs[0]) > 1000 if opt == '--exeinp' else outs[0] == outs[1] print('== %-24s %s' % ('sample ' + opt, 'IDENTICAL' if same else 'DIFFERS')) ok = ok and same From 1dfe05cb47dc2d37474e504253f5db2868501e4a Mon Sep 17 00:00:00 2001 From: Weiyuan Jiang Date: Mon, 30 Nov 2026 14:25:25 -0500 Subject: [PATCH 3/3] zero diff for 2d layout --- .../clsm_ensupd_enkf_update.F90 | 149 +++++++++--------- .../clsm_ensupd_upd_routines.F90 | 8 +- 2 files changed, 82 insertions(+), 75 deletions(-) diff --git a/GEOSlandassim_GridComp/clsm_ensupd_enkf_update.F90 b/GEOSlandassim_GridComp/clsm_ensupd_enkf_update.F90 index c82c7533..be07ee4d 100644 --- a/GEOSlandassim_GridComp/clsm_ensupd_enkf_update.F90 +++ b/GEOSlandassim_GridComp/clsm_ensupd_enkf_update.F90 @@ -316,6 +316,7 @@ subroutine get_enkf_increments( & integer :: N_obsf_assim, N_obsl_assim integer :: N_obsl_assim_vec(numprocs) integer, dimension(:), allocatable :: indObs_ana + integer*8, dimension(:), allocatable :: obs_sort_key integer, dimension(:), allocatable, target :: ind_obsl_assim integer, dimension(:), pointer :: ptr2indx => null() type(varLenIntArr) :: indObsAna_vec(numprocs) @@ -793,8 +794,21 @@ subroutine get_enkf_increments( & end do if (allocated(tmp_ind_obs)) deallocate(tmp_ind_obs) if (allocated(select_species)) deallocate(select_species) - ! sort obs indices (for layout independence) - if (nObs_ana>1) call MAPL_Sort(indObs_ana(1:nObs_ana)) + ! sort obs (for layout independence) by global tile_id and species; the order + ! of Obs_f_assim follows the processor layout (rank by rank) and matches + ! the global tile order only for 1d layouts; index in Obs_f_assim breaks ties + if (nObs_ana>1) then + allocate(obs_sort_key(nObs_ana)) + do i=1,nObs_ana + ctr = indObs_ana(i) + obs_sort_key(i) = & + ( int(tile_coord_f(Obs_f_assim(ctr)%tilenum)%tile_id,8) & + * int(N_obs_param+1,8) + int(Obs_f_assim(ctr)%species,8) ) & + * int(N_obsf_assim+1,8) + int(ctr,8) + end do + call MAPL_Sort(obs_sort_key, indObs_ana(1:nObs_ana)) + deallocate(obs_sort_key) + end if ! Step 3b: nObs_ana -> nObsAna_vec (on root) call MPI_Gather(nObs_ana,1,MPI_INTEGER, & @@ -1563,11 +1577,10 @@ subroutine output_ObsFcstAna(date_time, exp_id, & #ifdef LDAS_MPI - integer :: this_species, ind_tmp, j + integer :: max_tilenum - integer, dimension(N_obs_param) :: N_per_species - integer, dimension(N_obs_param) :: species_low_ind - integer, dimension(N_obs_param) :: ind_within_species + integer*8, dimension(:), allocatable :: obs_sort_key + integer, dimension(:), allocatable :: obs_sort_ind #endif @@ -1628,78 +1641,47 @@ subroutine output_ObsFcstAna(date_time, exp_id, & if (root_proc) then -#ifdef LDAS_MPI - - ! sort observations according to species so that the ObsFcstAna - ! file looks the same regardless of the MPI configuration - ! - ! NOTE: within each species, observations should already be sorted according - ! to tilenum because of the loop through species in collect_obs() - - ! first loop: count how many obs there are per species - - N_per_species(1:N_obs_param) = 0 - - do n=1,N_obsf - - this_species = Observations_f(n)%species - - N_per_species(this_species) = N_per_species(this_species) + 1 - - end do - - ! get starting index of each species in sorted vector Observations_f - - species_low_ind(1) = 1 - - do j=1,N_obs_param-1 - - species_low_ind(j+1) = species_low_ind(j) + N_per_species(j) - - end do - - ! second loop: re-order Observations_f into Observations_tmp - - allocate(Observations_tmp(N_obsf)) - - ind_within_species(1:N_obs_param) = 0 - - do n=1,N_obsf - - this_species = Observations_f(n)%species - - ind_tmp = species_low_ind(this_species) + ind_within_species(this_species) + ! reorder tilenum, so it is consistent with the order in tile_coord.bin file + if(present(rf2f)) then + allocate(rf_tilenums(N_obsf), tilenums(N_obsf)) + rf_tilenums = Observations_f(:)%tilenum + tilenums = rf2f(rf_tilenums) + Observations_f(:)%tilenum =tilenums + deallocate(rf_tilenums, tilenums) + endif - Observations_tmp(ind_tmp) = Observations_f(n) +#ifdef LDAS_MPI - ! NOTE: ind_within_species is "zero-based" + ! sort observations according to species and tilenum so that the ObsFcstAna + ! file looks the same regardless of the MPI configuration (the gathered obs + ! are in tilenum order within each species only for 1d layouts); + ! index in gathered vector breaks ties - ind_within_species(this_species) = ind_within_species(this_species) + 1 + if (N_obsf>1) then - end do + allocate(obs_sort_key(N_obsf), obs_sort_ind(N_obsf)) - ! copy back into Observations_f + max_tilenum = maxval(Observations_f(:)%tilenum) - do n=1,N_obsf + do n=1,N_obsf + obs_sort_key(n) = & + ( int(Observations_f(n)%species,8) * int(max_tilenum+1,8) & + + int(Observations_f(n)%tilenum,8) ) * int(N_obsf+1,8) + int(n,8) + obs_sort_ind(n) = n + end do - Observations_f(n) = Observations_tmp(n) + call MAPL_Sort(obs_sort_key, obs_sort_ind) - end do + allocate(Observations_tmp(N_obsf)) + Observations_tmp = Observations_f(obs_sort_ind) + Observations_f = Observations_tmp + deallocate(Observations_tmp, obs_sort_key, obs_sort_ind) - deallocate(Observations_tmp) + end if #endif ! LDAS_MPI - ! reorder tilenum, so it is consistent with the order in tile_coord.bin file - if(present(rf2f)) then - allocate(rf_tilenums(N_obsf), tilenums(N_obsf)) - rf_tilenums = Observations_f(:)%tilenum - tilenums = rf2f(rf_tilenums) - Observations_f(:)%tilenum =tilenums - deallocate(rf_tilenums, tilenums) - endif - ! write to file if (out_ObsFcstAna == 1 .or. out_ObsFcstAna == 3) then @@ -2401,6 +2383,9 @@ subroutine write_smapL4SMaup( option, date_time, exp_id, N_ens, & real, dimension(:), allocatable :: tile_data_f + integer, dimension(:), allocatable :: f2rf_out + integer*8, dimension(:), allocatable :: tile_id_8 + real, dimension( N_catl) :: srfexc, rzexc, catdef real, dimension( N_catl) :: ar1, ar2, ar4 @@ -2449,6 +2434,22 @@ subroutine write_smapL4SMaup( option, date_time, exp_id, N_ens, & open(unitnum, file=fname, form='unformatted', action='write', & position=position) + ! tile_coord_f and the gathered tile data are in the "re-ordered full" (rf) order, + ! which follows the processor layout; write tile data in the order of tile_coord.bin + ! (ascending tile_id), so the file is the same regardless of the processor layout + + allocate(f2rf_out(N_catf), tile_id_8(N_catf)) + + tile_id_8 = int(tile_coord_f(1:N_catf)%tile_id,8) + + do n=1,N_catf + f2rf_out(n) = n + end do + + call MAPL_Sort(tile_id_8, f2rf_out) + + deallocate(tile_id_8) + end if ! -------------------------------------------------------------- @@ -3061,8 +3062,8 @@ subroutine write_smapL4SMaup( option, date_time, exp_id, N_ens, & ! write into file - write (unitnum) ( data_h_9km_tile_8(n) , n=1,N_catf) - write (unitnum) ( data_v_9km_tile_8(n) , n=1,N_catf) + write (unitnum) ( data_h_9km_tile_8(f2rf_out(n)) , n=1,N_catf) + write (unitnum) ( data_v_9km_tile_8(f2rf_out(n)) , n=1,N_catf) else @@ -3081,13 +3082,13 @@ subroutine write_smapL4SMaup( option, date_time, exp_id, N_ens, & ! convert to integer before writing to file - write (unitnum) (nint(data_h_9km_tile(n)), n=1,N_catf) - write (unitnum) (nint(data_v_9km_tile(n)), n=1,N_catf) + write (unitnum) (nint(data_h_9km_tile(f2rf_out(n))), n=1,N_catf) + write (unitnum) (nint(data_v_9km_tile(f2rf_out(n))), n=1,N_catf) else - write (unitnum) ( data_h_9km_tile(n) , n=1,N_catf) - write (unitnum) ( data_v_9km_tile(n) , n=1,N_catf) + write (unitnum) ( data_h_9km_tile(f2rf_out(n)) , n=1,N_catf) + write (unitnum) ( data_v_9km_tile(f2rf_out(n)) , n=1,N_catf) end if @@ -3204,7 +3205,7 @@ subroutine write_smapL4SMaup( option, date_time, exp_id, N_ens, & call l2f_real( N_catl, N_catf, N_catl_vec, low_ind, & tile_mean_l(:,k), tile_data_f) - if (root_proc) write(unitnum) (tile_data_f(n), n=1,N_catf) + if (root_proc) write(unitnum) (tile_data_f(f2rf_out(n)), n=1,N_catf) end do @@ -3225,7 +3226,7 @@ subroutine write_smapL4SMaup( option, date_time, exp_id, N_ens, & call l2f_real( N_catl, N_catf, N_catl_vec, low_ind, & tile_std_l(:,k), tile_data_f) - if (root_proc) write(unitnum) (tile_data_f(n), n=1,N_catf) + if (root_proc) write(unitnum) (tile_data_f(f2rf_out(n)), n=1,N_catf) end do @@ -3241,6 +3242,8 @@ subroutine write_smapL4SMaup( option, date_time, exp_id, N_ens, & if (root_proc) close(unitnum,status='keep') + if (allocated(f2rf_out)) deallocate(f2rf_out) + end subroutine write_smapL4SMaup ! ----------------------------------------------------------------- diff --git a/GEOSlandassim_GridComp/clsm_ensupd_upd_routines.F90 b/GEOSlandassim_GridComp/clsm_ensupd_upd_routines.F90 index edeb2387..70a111af 100644 --- a/GEOSlandassim_GridComp/clsm_ensupd_upd_routines.F90 +++ b/GEOSlandassim_GridComp/clsm_ensupd_upd_routines.F90 @@ -3154,9 +3154,13 @@ subroutine get_tiles_in_halo( N_catl, N_fields, N_ens, tile_data_l, tile_coord_l ! processor i needs tile_data_l from processor j ! if bounding box around tile_data_l(j) overlaps ! with bounding box plus halo of processor i + ! + ! use ">=" because the bounding box of processor j has zero width if all + ! of its tiles are in a single row or column (e.g., coastal blocks of + ! a 2d layout on EASE grids) - if ( (min(ur_lon,maxlon) - max(ll_lon,minlon))>0. .and. & - (min(ur_lat,maxlat) - max(ll_lat,minlat))>0. ) & + if ( (min(ur_lon,maxlon) - max(ll_lon,minlon))>=0. .and. & + (min(ur_lat,maxlat) - max(ll_lat,minlat))>=0. ) & need_catl(i,j) = .true. need_catl(j,i) = need_catl(i,j)