eccodes/examples/python/grib_set_bitmap.py

72 lines
2.0 KiB
Python
Raw Normal View History

2019-04-15 13:44:45 +00:00
# Copyright 2005-2019 ECMWF.
2013-06-07 15:47:47 +00:00
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
2016-01-05 14:32:24 +00:00
# In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
# virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
2013-06-07 15:47:47 +00:00
from __future__ import print_function
import traceback
import sys
from eccodes import *
2013-06-07 15:47:47 +00:00
2015-11-11 18:20:31 +00:00
INPUT = '../../data/regular_latlon_surface.grib1'
2016-01-05 14:32:24 +00:00
OUTPUT = 'out.set_bitmap_p.grib'
2013-06-07 15:47:47 +00:00
MISSING = 9999
2015-11-11 18:20:31 +00:00
VERBOSE = 1 # verbose error reporting
2013-06-07 15:47:47 +00:00
def example():
fin = open(INPUT, 'rb')
fout = open(OUTPUT, 'wb')
2015-03-04 17:11:18 +00:00
gid = codes_grib_new_from_file(fin)
2013-06-07 15:47:47 +00:00
2016-06-03 10:28:00 +00:00
# The missingValue is not coded in the message.
# It is a value we define as a placeholder for a missing value
# at a point in the grid.
# It should be chosen so that it cannot be confused
# with a valid field value
2015-11-11 18:20:31 +00:00
codes_set(gid, 'missingValue', MISSING)
2016-06-03 10:28:00 +00:00
values = codes_get_values(gid)
2016-06-03 10:28:00 +00:00
# Enable bitmap
codes_set(gid, 'bitmapPresent', 1)
2016-06-03 10:28:00 +00:00
2013-06-07 15:47:47 +00:00
# Change some data values to be missing
num_missing = 0
for i in range(100):
2016-06-03 10:28:00 +00:00
# Set every other value to a missing value
2013-06-07 15:47:47 +00:00
if i % 2 == 0:
values[i] = MISSING
num_missing += 1
codes_set_values(gid, values)
2015-11-11 18:20:31 +00:00
2013-06-07 15:47:47 +00:00
# Check counts of missing and non-missing values
2015-11-11 18:20:31 +00:00
num_data = codes_get(gid, 'numberOfDataPoints', int)
2016-06-03 10:28:00 +00:00
assert num_data == len(values)
assert codes_get(gid, 'numberOfCodedValues', int) == num_data - num_missing
assert codes_get(gid, 'numberOfMissing', int) == num_missing
2013-06-07 15:47:47 +00:00
2015-11-11 18:20:31 +00:00
codes_write(gid, fout)
codes_release(gid)
2013-06-07 15:47:47 +00:00
fin.close()
fout.close()
2015-11-11 18:20:31 +00:00
2013-06-07 15:47:47 +00:00
def main():
try:
example()
except CodesInternalError as err:
2013-06-07 15:47:47 +00:00
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
print(err.msg, file=sys.stderr)
2013-06-07 15:47:47 +00:00
return 1
2013-06-07 15:47:47 +00:00
if __name__ == "__main__":
sys.exit(main())