Project

General

Profile

RE: Sort Grid Cell Values From Greatest to Smallest (Rank) ยป sortCdo.py

Ralf Mueller, 2019-10-22 18:04

 
from cdo import Cdo
import sys

cdo = Cdo()
cdo.debug = True

inputfile = sys.argv[1]
print('inputfile='+inputfile)
outputfile = 'sortedInput.nc'

# create a mask for application of the 'reducegrid' operator. it's some sort of
# misuse, because it was develop to reduce data. Here I use it the create an
# unstructured CF-conform grid representation of the input by using a mask
# entirely being 1. So that nothing will be removed from the original data

# compute the lower boundary
LowerBoundary = float(cdo.outputkey('value,nohead', input='-fldmin '+inputfile)[0])
# mask being 1 at all points
mask = cdo.gtc(LowerBoundary-1,input=inputfile)
# transorm the input input unstructured grid in netcdf format
unstructuredInput = cdo.reducegrid(mask,input=inputfile,options='-f nc')

# create an orderes list of location indices
indexList = cdo.outputkey('value,xind,nohead', input=unstructuredInput)
print(indexList)

# create numbers from the strings so that the sorting of the data values works correctly
nestedList = [(_[1], float(_[0])) for _ in [x.split() for x in indexList]]
print(nestedList)

# select the sorted indicees
sortedList = sorted(nestedList, key=lambda x: x[1])
sortedIndexList = [x[0] for x in sortedList]
print(sortedIndexList)

# selecta (all) grid locations in the order of the data values
cdo.selgridcell(','.join(sortedIndexList),input=unstructuredInput,output=outputfile)
    (1-1/1)