Keep last record of each model number in data, in ascending order.
KEPLER appends records on restart from an earlier dump, so a file can hold overlapping model ranges w/ model number and time jumping back ("Models and time", docs/cnvfiles.md). Band tracer, strip edges and bisection need strictly increasing model numbers.
subroutine sort_models() !! Keep last record of each model number in `data`, in ascending order. !! !! KEPLER appends records on restart from an earlier dump, so a file can hold overlapping model !! ranges w/ model number and time jumping back ("Models and time", docs/cnvfiles.md). Band !! tracer, strip edges and bisection need strictly increasing model numbers. use convdata, only: & convtype, data implicit none type(convtype), dimension(:), allocatable :: & data1 integer(kind=int32), dimension(:), allocatable :: & idx, tmp integer(kind=int32) :: & n, i, k, m, w, l, r, la, lb n = int(size(data), int32) if (n <= 1) return ! fast path: model numbers already strictly increasing do i = 2, n if (data(i)%ncyc <= data(i-1)%ncyc) exit enddo if (i > n) return ! stable bottom-up merge sort of record indices by model number, so ! records sharing a ncyc stay in file order and the last one wins allocate(idx(n), tmp(n)) do i = 1, n idx(i) = i enddo w = 1 do while (w < n) do l = 1, n - w, 2 * w m = l + w - 1 r = min(l + 2 * w - 1, n) tmp(l:r) = idx(l:r) la = l lb = m + 1 do k = l, r if (lb > r) then idx(k) = tmp(la); la = la + 1 else if (la > m) then idx(k) = tmp(lb); lb = lb + 1 else if (data(tmp(lb))%ncyc < data(tmp(la))%ncyc) then idx(k) = tmp(lb); lb = lb + 1 else idx(k) = tmp(la); la = la + 1 endif enddo enddo w = 2 * w enddo ! keep the last record of each run of equal model numbers m = 0 do i = 1, n if (i < n) then if (data(idx(i))%ncyc == data(idx(i+1))%ncyc) cycle endif m = m + 1 idx(m) = idx(i) enddo if (m < n) & print*, '[loadconv] Removed', n - m, & 'superseded model(s) (restart overlap)' allocate(data1(m)) do i = 1, m data1(i) = data(idx(i)) enddo deallocate(data) call move_alloc(data1, data) deallocate(idx, tmp) end subroutine sort_models