Examples: Run black formatter

This commit is contained in:
Shahram Najm 2021-09-15 20:45:34 +01:00
parent 6198f46ba2
commit 280f144111
42 changed files with 652 additions and 556 deletions

View File

@ -18,8 +18,8 @@ VERBOSE = 1 # verbose error reporting
def example():
f = open(sys.argv[1], 'rb')
fout = open(sys.argv[2], 'wb')
f = open(sys.argv[1], "rb")
fout = open(sys.argv[2], "wb")
while 1:
gid = codes_grib_new_from_file(f)
@ -45,7 +45,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -21,24 +21,18 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/syno_multi.bufr'
INPUT = "../../data/bufr/syno_multi.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
# define the attributes to be printed (see BUFR code table B)
attrs = [
'code',
'units',
'scale',
'reference',
'width'
]
attrs = ["code", "units", "scale", "reference", "width"]
# loop for the messages in the file
while 1:
@ -51,16 +45,16 @@ def example():
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# --------------------------------------------------------------
# We will read the value and all the attributes available for
# the 2m temperature.
# --------------------------------------------------------------
# get the value
key = 'airTemperatureAt2M'
key = "airTemperatureAt2M"
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -68,9 +62,9 @@ def example():
# are keys as well. Their name is constructed like:
# keyname->attributename
for attr in attrs:
key = 'airTemperatureAt2M' + "->" + attr
key = "airTemperatureAt2M" + "->" + attr
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -81,17 +75,17 @@ def example():
# ------------------------------------------------------------------
# get the value
key = 'airTemperatureAt2M->percentConfidence'
key = "airTemperatureAt2M->percentConfidence"
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
# print the values of the attributes of the key.
for attr in attrs:
key = 'airTemperatureAt2M->percentConfidence' + "->" + attr
key = "airTemperatureAt2M->percentConfidence" + "->" + attr
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -111,7 +105,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -22,17 +22,17 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/syno_1.bufr'
OUTPUT = 'bufr_clone_test_p.clone.bufr'
INPUT = "../../data/bufr/syno_1.bufr"
OUTPUT = "bufr_clone_test_p.clone.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open BUFR file
fin = open(INPUT, 'rb')
fin = open(INPUT, "rb")
# open output BUFR file
fout = open(OUTPUT, 'wb')
fout = open(OUTPUT, "wb")
# get handle for message
bufr = codes_bufr_new_from_file(fin)
@ -44,7 +44,7 @@ def example():
clone_id = codes_clone(bufr)
# this is the place where you may wish to modify the clone
codes_set(clone_id, 'bufrHeaderCentre', centre)
codes_set(clone_id, "bufrHeaderCentre", centre)
# write the cloned message to a file
codes_write(clone_id, fout)
@ -66,7 +66,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -25,27 +25,34 @@ VERBOSE = 1 # verbose error reporting
def example(input_filename, output_filename):
f = open(input_filename, 'rb')
f = open(input_filename, "rb")
ibufrin = codes_bufr_new_from_file(f)
f.close()
# Need to unpack to get delayed replications and reference values from input
codes_set(ibufrin, 'unpack', 1)
references = codes_get_array(ibufrin, 'inputOverriddenReferenceValues')
replication = codes_get_array(ibufrin, 'delayedDescriptorReplicationFactor')
codes_set(ibufrin, "unpack", 1)
references = codes_get_array(ibufrin, "inputOverriddenReferenceValues")
replication = codes_get_array(ibufrin, "delayedDescriptorReplicationFactor")
ibufrout = codes_clone(ibufrin)
# Copy over to output
codes_set_array(ibufrout, 'inputOverriddenReferenceValues', references)
codes_set_array(ibufrout, 'inputDelayedDescriptorReplicationFactor', replication)
codes_set_array(ibufrout, "inputOverriddenReferenceValues", references)
codes_set_array(ibufrout, "inputDelayedDescriptorReplicationFactor", replication)
# Keep all original descriptors and add 'meanWindDirectionForSurfaceTo1500M' (011044)
ivalues = (203014, 7030, 7031, 203255, 307080, 11044,)
codes_set_array(ibufrout, 'unexpandedDescriptors', ivalues)
ivalues = (
203014,
7030,
7031,
203255,
307080,
11044,
)
codes_set_array(ibufrout, "unexpandedDescriptors", ivalues)
codes_bufr_copy_data(ibufrin, ibufrout)
outfile = open(output_filename, 'wb')
outfile = open(output_filename, "wb")
codes_write(ibufrout, outfile)
outfile.close()
@ -55,7 +62,7 @@ def example(input_filename, output_filename):
def main():
if len(sys.argv) < 3:
print('Usage: ', sys.argv[0], ' bufr_in bufr_out', file=sys.stderr)
print("Usage: ", sys.argv[0], " bufr_in bufr_out", file=sys.stderr)
sys.exit(1)
input_filename = sys.argv[1]
@ -67,7 +74,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -26,21 +26,21 @@ WIGOS_SEQ = 301150
def example(input_filename, output_filename):
f = open(input_filename, 'rb')
f = open(input_filename, "rb")
ibufrin = codes_bufr_new_from_file(f)
f.close()
codes_set(ibufrin, 'unpack', 1)
inUE = codes_get_array(ibufrin, 'unexpandedDescriptors').tolist()
codes_set(ibufrin, "unpack", 1)
inUE = codes_get_array(ibufrin, "unexpandedDescriptors").tolist()
nsubsets = 2
ibufrout = codes_bufr_new_from_samples('BUFR4')
ibufrout = codes_bufr_new_from_samples("BUFR4")
# Update the unexpandedDescriptors to add the WIGOS data at the beginning
outUE = inUE
outUE.insert(0, WIGOS_SEQ)
codes_set(ibufrout, 'masterTablesVersionNumber', 28)
codes_set(ibufrout, 'numberOfSubsets', nsubsets)
codes_set_array(ibufrout, 'unexpandedDescriptors', outUE)
codes_set(ibufrout, "masterTablesVersionNumber", 28)
codes_set(ibufrout, "numberOfSubsets", nsubsets)
codes_set_array(ibufrout, "unexpandedDescriptors", outUE)
# Some dummy WIGOS info
for i in range(0, nsubsets):
@ -50,7 +50,7 @@ def example(input_filename, output_filename):
# Copy across other data in input
codes_bufr_copy_data(ibufrin, ibufrout)
outfile = open(output_filename, 'wb')
outfile = open(output_filename, "wb")
codes_write(ibufrout, outfile)
outfile.close()
@ -60,7 +60,7 @@ def example(input_filename, output_filename):
def main():
if len(sys.argv) < 3:
print('Usage: ', sys.argv[0], ' bufr_in bufr_out', file=sys.stderr)
print("Usage: ", sys.argv[0], " bufr_in bufr_out", file=sys.stderr)
return 1
input_filename = sys.argv[1]
@ -72,7 +72,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1
return 0

View File

@ -14,13 +14,13 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/syno_1.bufr'
INPUT = "../../data/bufr/syno_1.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -38,7 +38,7 @@ def example():
the_message = codes_get_message(bufr)
newbufr = codes_new_from_message(the_message)
codes_set(newbufr, 'unpack', 1)
codes_set(newbufr, "unpack", 1)
# get BUFR key iterator
iterid = codes_bufr_keys_iterator_new(newbufr)
@ -68,7 +68,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -9,118 +9,125 @@ import traceback
from eccodes import *
OUTPUT_FILENAME = 'outfile_ecc_869_test.bufr'
OUTPUT_FILENAME = "outfile_ecc_869_test.bufr"
VERBOSE = 1 # verbose error reporting
def bufr_encode():
ibufr = codes_bufr_new_from_samples('BUFR3_local')
ivalues = (0, 0, 0, 0,)
codes_set_array(ibufr, 'inputShortDelayedDescriptorReplicationFactor', ivalues)
ibufr = codes_bufr_new_from_samples("BUFR3_local")
ivalues = (
0,
0,
0,
0,
)
codes_set_array(ibufr, "inputShortDelayedDescriptorReplicationFactor", ivalues)
SIZE_OF_BMP = 41
bitMask = [1] * SIZE_OF_BMP
bitMask[0] = 0 # marineObservingPlatformIdentifier
bitMask[37] = 0 # pressureReducedToMeanSeaLevel
codes_set_array(ibufr, 'inputDataPresentIndicator', bitMask)
codes_set_array(ibufr, "inputDataPresentIndicator", bitMask)
codes_set(ibufr, 'edition', 3)
codes_set(ibufr, 'masterTableNumber', 0)
codes_set(ibufr, 'bufrHeaderSubCentre', 0)
codes_set(ibufr, 'bufrHeaderCentre', 98)
codes_set(ibufr, 'updateSequenceNumber', 0)
codes_set(ibufr, 'dataCategory', 1)
codes_set(ibufr, 'dataSubCategory', 182)
codes_set(ibufr, 'masterTablesVersionNumber', 22)
codes_set(ibufr, 'localTablesVersionNumber', 0)
codes_set(ibufr, 'typicalYearOfCentury', 18)
codes_set(ibufr, 'typicalMonth', 11)
codes_set(ibufr, 'typicalDay', 21)
codes_set(ibufr, 'typicalHour', 21)
codes_set(ibufr, 'typicalMinute', 4)
codes_set(ibufr, 'rdbType', 1)
codes_set(ibufr, 'oldSubtype', 182)
codes_set(ibufr, 'localYear', 2018)
codes_set(ibufr, 'localMonth', 11)
codes_set(ibufr, 'localDay', 21)
codes_set(ibufr, 'localHour', 21)
codes_set(ibufr, 'localMinute', 4)
codes_set(ibufr, 'localSecond', 0)
codes_set(ibufr, 'ident', ' 3101544')
codes_set(ibufr, 'rdbtimeDay', 21)
codes_set(ibufr, 'rdbtimeHour', 21)
codes_set(ibufr, 'rdbtimeMinute', 26)
codes_set(ibufr, 'rdbtimeSecond', 59)
codes_set(ibufr, 'rectimeDay', 10)
codes_set(ibufr, 'rectimeHour', 10)
codes_set(ibufr, 'rectimeMinute', 0)
codes_set(ibufr, 'rectimeSecond', 0)
codes_set(ibufr, 'correction1', 0)
codes_set(ibufr, 'correction1Part', 0)
codes_set(ibufr, 'correction2', 0)
codes_set(ibufr, 'correction2Part', 0)
codes_set(ibufr, 'correction3', 0)
codes_set(ibufr, 'correction3Part', 0)
codes_set(ibufr, 'correction4', 0)
codes_set(ibufr, 'correction4Part', 0)
codes_set(ibufr, 'qualityControl', 70)
codes_set(ibufr, 'newSubtype', 0)
codes_set(ibufr, 'numberOfSubsets', 1)
codes_set(ibufr, 'localLatitude', -3.598198000000000008e+01)
codes_set(ibufr, 'localLongitude', -4.484317000000000064e+01)
codes_set(ibufr, 'observedData', 1)
codes_set(ibufr, 'compressedData', 0)
codes_set(ibufr, "edition", 3)
codes_set(ibufr, "masterTableNumber", 0)
codes_set(ibufr, "bufrHeaderSubCentre", 0)
codes_set(ibufr, "bufrHeaderCentre", 98)
codes_set(ibufr, "updateSequenceNumber", 0)
codes_set(ibufr, "dataCategory", 1)
codes_set(ibufr, "dataSubCategory", 182)
codes_set(ibufr, "masterTablesVersionNumber", 22)
codes_set(ibufr, "localTablesVersionNumber", 0)
codes_set(ibufr, "typicalYearOfCentury", 18)
codes_set(ibufr, "typicalMonth", 11)
codes_set(ibufr, "typicalDay", 21)
codes_set(ibufr, "typicalHour", 21)
codes_set(ibufr, "typicalMinute", 4)
codes_set(ibufr, "rdbType", 1)
codes_set(ibufr, "oldSubtype", 182)
codes_set(ibufr, "localYear", 2018)
codes_set(ibufr, "localMonth", 11)
codes_set(ibufr, "localDay", 21)
codes_set(ibufr, "localHour", 21)
codes_set(ibufr, "localMinute", 4)
codes_set(ibufr, "localSecond", 0)
codes_set(ibufr, "ident", " 3101544")
codes_set(ibufr, "rdbtimeDay", 21)
codes_set(ibufr, "rdbtimeHour", 21)
codes_set(ibufr, "rdbtimeMinute", 26)
codes_set(ibufr, "rdbtimeSecond", 59)
codes_set(ibufr, "rectimeDay", 10)
codes_set(ibufr, "rectimeHour", 10)
codes_set(ibufr, "rectimeMinute", 0)
codes_set(ibufr, "rectimeSecond", 0)
codes_set(ibufr, "correction1", 0)
codes_set(ibufr, "correction1Part", 0)
codes_set(ibufr, "correction2", 0)
codes_set(ibufr, "correction2Part", 0)
codes_set(ibufr, "correction3", 0)
codes_set(ibufr, "correction3Part", 0)
codes_set(ibufr, "correction4", 0)
codes_set(ibufr, "correction4Part", 0)
codes_set(ibufr, "qualityControl", 70)
codes_set(ibufr, "newSubtype", 0)
codes_set(ibufr, "numberOfSubsets", 1)
codes_set(ibufr, "localLatitude", -3.598198000000000008e01)
codes_set(ibufr, "localLongitude", -4.484317000000000064e01)
codes_set(ibufr, "observedData", 1)
codes_set(ibufr, "compressedData", 0)
# Create the structure of the data section
codes_set_array(ibufr, 'unexpandedDescriptors',
(315009, 222000, 236000, 101000 + SIZE_OF_BMP, 31031, 33007, 33007)
codes_set_array(
ibufr,
"unexpandedDescriptors",
(315009, 222000, 236000, 101000 + SIZE_OF_BMP, 31031, 33007, 33007),
)
codes_set(ibufr, 'marineObservingPlatformIdentifier', 3101544)
codes_set(ibufr, 'marineObservingPlatformIdentifier->percentConfidence', 44)
codes_set(ibufr, 'longStationName', 'SIO Lagrangian Drifter Lab')
codes_set(ibufr, 'dataBuoyType', 1)
codes_set(ibufr, '#1#timeSignificance', 26)
codes_set(ibufr, '#1#year', 2018)
codes_set(ibufr, '#1#month', 11)
codes_set(ibufr, '#1#day', 21)
codes_set(ibufr, '#1#hour', 21)
codes_set(ibufr, '#1#minute', 4)
codes_set(ibufr, 'latitude', -3.598198000000000008e+01)
codes_set(ibufr, 'longitude', -4.484317000000000064e+01)
codes_set(ibufr, 'platformTransmitterIdNumber', ' 300234065315740')
codes_set(ibufr, 'dataCollectionLocationSystem', 8)
codes_set(ibufr, 'directionOfMotionOfMovingObservingPlatform', CODES_MISSING_LONG)
codes_set(ibufr, 'platformDriftSpeed', CODES_MISSING_DOUBLE)
codes_set(ibufr, 'qualityOfBuoySatelliteTransmission', 0)
codes_set(ibufr, 'qualityOfBuoyLocation', 0)
codes_set(ibufr, 'locationQualityClassRangeOfRadiusOf66Confidence', 3)
codes_set(ibufr, 'batteryVoltageLargeRange', 1.020000000000000107e+01)
codes_set(ibufr, 'drogueType', 1)
codes_set(ibufr, 'lagrangianDrifterDrogueStatus', 2)
codes_set(ibufr, 'drogueDepth', 15)
codes_set(ibufr, 'lagrangianDrifterSubmergenceTimeSubmerged', 30)
codes_set(ibufr, '#2#timeSignificance', 25)
codes_set(ibufr, '#2#year', 2018)
codes_set(ibufr, '#2#month', 11)
codes_set(ibufr, '#2#day', 21)
codes_set(ibufr, '#2#hour', 21)
codes_set(ibufr, '#2#minute', 4)
codes_set_missing(ibufr, 'temperatureObservationPrecision')
codes_set(ibufr, 'oceanographicWaterTemperature', 2.914499999999999886e+02)
codes_set_missing(ibufr, 'methodOfSalinityOrDepthMeasurement')
codes_set(ibufr, 'seaSurfaceSalinity', CODES_MISSING_DOUBLE)
codes_set(ibufr, 'surfaceType', CODES_MISSING_LONG)
codes_set(ibufr, 'iceThickness', CODES_MISSING_DOUBLE)
codes_set(ibufr, 'nonCoordinatePressure', CODES_MISSING_DOUBLE)
codes_set(ibufr, 'pressureReducedToMeanSeaLevel', 1.021700000000000000e+05)
codes_set(ibufr, 'pressureReducedToMeanSeaLevel->percentConfidence', 45)
codes_set(ibufr, "marineObservingPlatformIdentifier", 3101544)
codes_set(ibufr, "marineObservingPlatformIdentifier->percentConfidence", 44)
codes_set(ibufr, "longStationName", "SIO Lagrangian Drifter Lab")
codes_set(ibufr, "dataBuoyType", 1)
codes_set(ibufr, "#1#timeSignificance", 26)
codes_set(ibufr, "#1#year", 2018)
codes_set(ibufr, "#1#month", 11)
codes_set(ibufr, "#1#day", 21)
codes_set(ibufr, "#1#hour", 21)
codes_set(ibufr, "#1#minute", 4)
codes_set(ibufr, "latitude", -3.598198000000000008e01)
codes_set(ibufr, "longitude", -4.484317000000000064e01)
codes_set(ibufr, "platformTransmitterIdNumber", " 300234065315740")
codes_set(ibufr, "dataCollectionLocationSystem", 8)
codes_set(ibufr, "directionOfMotionOfMovingObservingPlatform", CODES_MISSING_LONG)
codes_set(ibufr, "platformDriftSpeed", CODES_MISSING_DOUBLE)
codes_set(ibufr, "qualityOfBuoySatelliteTransmission", 0)
codes_set(ibufr, "qualityOfBuoyLocation", 0)
codes_set(ibufr, "locationQualityClassRangeOfRadiusOf66Confidence", 3)
codes_set(ibufr, "batteryVoltageLargeRange", 1.020000000000000107e01)
codes_set(ibufr, "drogueType", 1)
codes_set(ibufr, "lagrangianDrifterDrogueStatus", 2)
codes_set(ibufr, "drogueDepth", 15)
codes_set(ibufr, "lagrangianDrifterSubmergenceTimeSubmerged", 30)
codes_set(ibufr, "#2#timeSignificance", 25)
codes_set(ibufr, "#2#year", 2018)
codes_set(ibufr, "#2#month", 11)
codes_set(ibufr, "#2#day", 21)
codes_set(ibufr, "#2#hour", 21)
codes_set(ibufr, "#2#minute", 4)
codes_set_missing(ibufr, "temperatureObservationPrecision")
codes_set(ibufr, "oceanographicWaterTemperature", 2.914499999999999886e02)
codes_set_missing(ibufr, "methodOfSalinityOrDepthMeasurement")
codes_set(ibufr, "seaSurfaceSalinity", CODES_MISSING_DOUBLE)
codes_set(ibufr, "surfaceType", CODES_MISSING_LONG)
codes_set(ibufr, "iceThickness", CODES_MISSING_DOUBLE)
codes_set(ibufr, "nonCoordinatePressure", CODES_MISSING_DOUBLE)
codes_set(ibufr, "pressureReducedToMeanSeaLevel", 1.021700000000000000e05)
codes_set(ibufr, "pressureReducedToMeanSeaLevel->percentConfidence", 45)
# Encode the keys back in the data section
codes_set(ibufr, 'pack', 1)
codes_set(ibufr, "pack", 1)
outfile = open(OUTPUT_FILENAME, 'wb')
outfile = open(OUTPUT_FILENAME, "wb")
codes_write(ibufr, outfile)
print("Created output BUFR file ", OUTPUT_FILENAME)
codes_release(ibufr)
@ -133,7 +140,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -23,49 +23,54 @@ VERBOSE = 1 # verbose error reporting
def parse_date(x):
return datetime.strptime(x.decode('ascii'), '%Y%m%d')
return datetime.strptime(x.decode("ascii"), "%Y%m%d")
def parse_time(x):
return datetime.strptime(x.decode('ascii'), '%H:%M:%S')
return datetime.strptime(x.decode("ascii"), "%H:%M:%S")
def example(csvfile, input_filename, output_filename):
fbufrin = open(input_filename, 'rb')
fbufrout = open(output_filename, 'wb')
fbufrin = open(input_filename, "rb")
fbufrout = open(output_filename, "wb")
print('Using ecCodes version: ', codes_get_api_version())
print("Using ecCodes version: ", codes_get_api_version())
# The first line in the CSV has the column names
print('Reading input CSV file: ', csvfile)
data = np.genfromtxt(csvfile, delimiter=',', dtype=None, names=True,
converters={0: parse_date, 1: parse_time})
print("Reading input CSV file: ", csvfile)
data = np.genfromtxt(
csvfile,
delimiter=",",
dtype=None,
names=True,
converters={0: parse_date, 1: parse_time},
)
ymd_column = data['ymd']
ymd_column = data["ymd"]
years = np.array([x.year for x in ymd_column])
months = np.array([x.month for x in ymd_column])
days = np.array([x.day for x in ymd_column])
time_column = data['time']
time_column = data["time"]
hours = np.array([x.hour for x in time_column])
minutes = np.array([x.minute for x in time_column])
seconds = np.array([x.second for x in time_column])
latitudes = data['latitude']
longitudes = data['longitude']
altitudes = data['altitude']
pressures = data['pressure']
windSpeeds = data['windSpeed']
windDirections = data['windDirection']
temperatures = data['temperature']
latitudes = data["latitude"]
longitudes = data["longitude"]
altitudes = data["altitude"]
pressures = data["pressure"]
windSpeeds = data["windSpeed"]
windDirections = data["windDirection"]
temperatures = data["temperature"]
print('Reading input BUFR file: ', input_filename)
print("Reading input BUFR file: ", input_filename)
bufr = codes_bufr_new_from_file(fbufrin)
codes_set(bufr, 'masterTablesVersionNumber', 24)
codes_set(bufr, 'localTablesVersionNumber', 0)
codes_set(bufr, 'compressedData', 1)
codes_set(bufr, 'numberOfSubsets', len(years))
codes_set(bufr, "masterTablesVersionNumber", 24)
codes_set(bufr, "localTablesVersionNumber", 0)
codes_set(bufr, "compressedData", 1)
codes_set(bufr, "numberOfSubsets", len(years))
# unexpandedDescriptors and BufrTemplate can be set alternatively
# to choose the template for the BUFR message
@ -73,26 +78,26 @@ def example(csvfile, input_filename, output_filename):
# unexpandedDescriptors = [301051,4006,7002,10004,12001,11001,11002,11031,11032,11033,20041]
# codes_set_array(bufr, 'unexpandedDescriptors', unexpandedDescriptors)
codes_set(bufr, 'BufrTemplate', 'aircraftReportWithSecondsAndPressure')
codes_set(bufr, "BufrTemplate", "aircraftReportWithSecondsAndPressure")
codes_set_array(bufr, 'year', years)
codes_set_array(bufr, 'month', months)
codes_set_array(bufr, 'day', days)
codes_set_array(bufr, 'hour', hours)
codes_set_array(bufr, 'minute', minutes)
codes_set_array(bufr, 'second', seconds)
codes_set_array(bufr, 'latitude', latitudes)
codes_set_array(bufr, 'longitude', longitudes)
codes_set_array(bufr, 'height', altitudes)
codes_set_array(bufr, 'nonCoordinatePressure', pressures)
codes_set_array(bufr, 'windSpeed', windSpeeds)
codes_set_array(bufr, 'windDirection', windDirections)
codes_set_array(bufr, 'airTemperature', temperatures)
codes_set_array(bufr, "year", years)
codes_set_array(bufr, "month", months)
codes_set_array(bufr, "day", days)
codes_set_array(bufr, "hour", hours)
codes_set_array(bufr, "minute", minutes)
codes_set_array(bufr, "second", seconds)
codes_set_array(bufr, "latitude", latitudes)
codes_set_array(bufr, "longitude", longitudes)
codes_set_array(bufr, "height", altitudes)
codes_set_array(bufr, "nonCoordinatePressure", pressures)
codes_set_array(bufr, "windSpeed", windSpeeds)
codes_set_array(bufr, "windDirection", windDirections)
codes_set_array(bufr, "airTemperature", temperatures)
codes_set(bufr, 'pack', 1)
codes_set(bufr, "pack", 1)
codes_write(bufr, fbufrout)
print('Created output BUFR file: ', output_filename)
print("Created output BUFR file: ", output_filename)
fbufrin.close()
fbufrout.close()
@ -100,7 +105,7 @@ def example(csvfile, input_filename, output_filename):
def main():
if len(sys.argv) < 4:
print('Usage: ', sys.argv[0], ' csv bufr_in bufr_out', file=sys.stderr)
print("Usage: ", sys.argv[0], " csv bufr_in bufr_out", file=sys.stderr)
sys.exit(1)
csv_filename = sys.argv[1]
@ -113,7 +118,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -20,13 +20,13 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/syno_1.bufr'
INPUT = "../../data/bufr/syno_1.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -41,16 +41,16 @@ def example():
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# ----------------------------------
# get all the expanded data values
# ----------------------------------
key = 'numericValues'
key = "numericValues"
# get size
num = codes_get_size(bufr, key)
print(' size of %s is: %s' % (key, num))
print(" size of %s is: %s" % (key, num))
# get values
values = codes_get_array(bufr, key)
@ -73,7 +73,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -21,13 +21,13 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/syno_multi.bufr'
INPUT = "../../data/bufr/syno_multi.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -42,54 +42,54 @@ def example():
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# ---------------------------------------------
# get values for keys holding a single value
# ---------------------------------------------
# Native type integer
key = 'blockNumber'
key = "blockNumber"
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
# Native type integer
key = 'stationNumber'
key = "stationNumber"
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
assert codes_is_missing(bufr, key) == 0
# Native type float
key = 'airTemperatureAt2M'
key = "airTemperatureAt2M"
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
assert codes_is_missing(bufr, key) == 0
# Native type string
key = 'typicalDate'
key = "typicalDate"
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
assert codes_is_missing(bufr, 'relativeHumidity') == 1
assert codes_is_missing(bufr, '#5#cloudAmount') == 1
assert codes_is_missing(bufr, "relativeHumidity") == 1
assert codes_is_missing(bufr, "#5#cloudAmount") == 1
# --------------------------------
# get values for an array
# --------------------------------
# Native type integer
key = 'bufrdcExpandedDescriptors'
key = "bufrdcExpandedDescriptors"
# get size
num = codes_get_size(bufr, key)
print(' size of %s is: %s' % (key, num))
print(" size of %s is: %s" % (key, num))
# get values
values = codes_get_array(bufr, key)
@ -97,11 +97,11 @@ def example():
print(" %d %06d" % (i + 1, values[i]))
# Native type float
key = 'numericValues'
key = "numericValues"
# get size
num = codes_get_size(bufr, key)
print(' size of %s is: %s' % (key, num))
print(" size of %s is: %s" % (key, num))
# get values
values = codes_get_array(bufr, key)
@ -124,7 +124,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -27,7 +27,7 @@ VERBOSE = 1 # verbose error reporting
def example(INPUT):
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -42,7 +42,7 @@ def example(INPUT):
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# get BUFR key iterator
iterid = codes_bufr_keys_iterator_new(bufr)
@ -72,7 +72,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -27,18 +27,18 @@ VERBOSE = 1 # verbose error reporting
def example(INPUT):
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
# define the keys to be printed
keys = [
'dataCategory',
'dataSubCategory',
'typicalDate',
'bufrHeaderCentre',
'bufrHeaderSubCentre',
'masterTablesVersionNumber',
'localTablesVersionNumber',
'numberOfSubsets',
"dataCategory",
"dataSubCategory",
"typicalDate",
"bufrHeaderCentre",
"bufrHeaderSubCentre",
"masterTablesVersionNumber",
"localTablesVersionNumber",
"numberOfSubsets",
]
cnt = 0
@ -55,7 +55,7 @@ def example(INPUT):
# print the values for the selected keys from the message
for key in keys:
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -75,7 +75,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -26,30 +26,30 @@ VERBOSE = 1 # verbose error reporting
def get_key_value(msgid, key):
v = codes_get(msgid, key)
if v == CODES_MISSING_DOUBLE or v == CODES_MISSING_LONG:
v = 'MISSING'
v = "MISSING"
return v
def example(INPUT):
# open BUFR file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
# These keys should be in the sample files
keys = [
'editionNumber',
'unexpandedDescriptors',
'blockNumber',
'stationNumber',
'verticalSignificanceSurfaceObservations',
'latitude',
'longitude',
'24HourPressureChange',
'horizontalVisibility',
'#1#cloudAmount', # cloud amount (low and mid level)
'#1#heightOfBaseOfCloud',
'#1#cloudType', # cloud type (low clouds)
'#2#cloudType', # cloud type (middle clouds)
'#3#cloudType' # cloud type (highclouds)
"editionNumber",
"unexpandedDescriptors",
"blockNumber",
"stationNumber",
"verticalSignificanceSurfaceObservations",
"latitude",
"longitude",
"24HourPressureChange",
"horizontalVisibility",
"#1#cloudAmount", # cloud amount (low and mid level)
"#1#heightOfBaseOfCloud",
"#1#cloudType", # cloud type (low clouds)
"#2#cloudType", # cloud type (middle clouds)
"#3#cloudType", # cloud type (highclouds)
]
cnt = 0
@ -62,10 +62,10 @@ def example(INPUT):
print("message: %s" % cnt)
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
for key in keys:
print(' %s=%s' % (key, get_key_value(bufr, key)))
print(" %s=%s" % (key, get_key_value(bufr, key)))
cnt += 1
@ -81,7 +81,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -26,13 +26,13 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/asca_139.bufr'
INPUT = "../../data/bufr/asca_139.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -47,7 +47,7 @@ def example():
# We need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# The BUFR file contains a single message with 2016 subsets in a
# compressed form. It means each subset has exactly the same structure:
@ -60,7 +60,7 @@ def example():
# Get the total number of subsets.
numObs = codes_get(bufr, "numberOfSubsets")
print(' Number of values: %ld' % numObs)
print(" Number of values: %ld" % numObs)
# Get latitude (for all the subsets)
lat = codes_get_array(bufr, "latitude")
@ -74,7 +74,7 @@ def example():
# Check that all arrays are same size
if len(lat) != numObs or len(lon) != numObs or len(bscat) != numObs:
print('inconsistent array dimension')
print("inconsistent array dimension")
return 1
# Print the values
@ -100,7 +100,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -25,29 +25,29 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/syno_multi.bufr'
INPUT = "../../data/bufr/syno_multi.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open bufr file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
# define the keys to be printed
keys = [
'blockNumber',
'stationNumber',
'latitude',
'longitude',
'airTemperatureAt2M',
'dewpointTemperatureAt2M',
'windSpeedAt10M',
'windDirectionAt10M',
'#1#cloudAmount', # cloud amount (low and mid level)
'#1#heightOfBaseOfCloud',
'#1#cloudType', # cloud type (low clouds)
'#2#cloudType', # cloud type (middle clouds)
'#3#cloudType' # cloud type (highclouds)
"blockNumber",
"stationNumber",
"latitude",
"longitude",
"airTemperatureAt2M",
"dewpointTemperatureAt2M",
"windSpeedAt10M",
"windDirectionAt10M",
"#1#cloudAmount", # cloud amount (low and mid level)
"#1#heightOfBaseOfCloud",
"#1#cloudType", # cloud type (low clouds)
"#2#cloudType", # cloud type (middle clouds)
"#3#cloudType", # cloud type (highclouds)
]
# The cloud information is stored in several blocks in the
@ -72,12 +72,12 @@ def example():
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# print the values for the selected keys from the message
for key in keys:
try:
print(' %s: %s' % (key, codes_get(bufr, key)))
print(" %s: %s" % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -97,7 +97,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -26,13 +26,13 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/PraticaTemp.bufr'
INPUT = "../../data/bufr/PraticaTemp.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open BUFR file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
# loop over the messages in the file
while 1:
@ -43,11 +43,13 @@ def example():
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data section
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# get all the timePeriods
timePeriod = codes_get_array(bufr, "timePeriod")
pressure = codes_get_array(bufr, "pressure")
extendedVerticalSoundingSignificance = codes_get_array(bufr, "extendedVerticalSoundingSignificance")
extendedVerticalSoundingSignificance = codes_get_array(
bufr, "extendedVerticalSoundingSignificance"
)
geopotentialHeight = codes_get_array(bufr, "nonCoordinateGeopotentialHeight")
latitudeDisplacement = codes_get_array(bufr, "latitudeDisplacement")
longitudeDisplacement = codes_get_array(bufr, "longitudeDisplacement")
@ -57,12 +59,22 @@ def example():
windSpeed = codes_get_array(bufr, "windSpeed")
blockNumber = codes_get(bufr, "blockNumber")
stationNumber = codes_get(bufr, "stationNumber")
print('station %d%d' % (blockNumber, stationNumber))
print("station %d%d" % (blockNumber, stationNumber))
print(
'timePeriod pressure geopotentialHeight latitudeDisplacement longitudeDisplacement airTemperature windDirection windSpeed significance')
"timePeriod pressure geopotentialHeight latitudeDisplacement longitudeDisplacement airTemperature windDirection windSpeed significance"
)
for i in range(0, len(windSpeed) - 1):
print(timePeriod[i], pressure[i], geopotentialHeight[i], latitudeDisplacement[i], longitudeDisplacement[i],
airTemperature[i], windDirection[i], windSpeed[i], extendedVerticalSoundingSignificance[i])
print(
timePeriod[i],
pressure[i],
geopotentialHeight[i],
latitudeDisplacement[i],
longitudeDisplacement[i],
airTemperature[i],
windDirection[i],
windSpeed[i],
extendedVerticalSoundingSignificance[i],
)
cnt += 1
# delete handle
codes_release(bufr)
@ -77,7 +89,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -24,7 +24,7 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/tropical_cyclone.bufr'
INPUT = "../../data/bufr/tropical_cyclone.bufr"
VERBOSE = 1 # verbose error reporting
data = collections.defaultdict(dict)
@ -32,7 +32,7 @@ data = collections.defaultdict(dict)
def example():
# open BUFR file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -43,11 +43,11 @@ def example():
if bufr is None:
break
print('**************** MESSAGE: ', cnt + 1, ' *****************')
print("**************** MESSAGE: ", cnt + 1, " *****************")
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
numObs = codes_get(bufr, "numberOfSubsets")
year = codes_get(bufr, "year")
@ -56,10 +56,10 @@ def example():
hour = codes_get(bufr, "hour")
minute = codes_get(bufr, "minute")
print('Date and time: ', day, '.', month, '.', year, ' ', hour, ':', minute)
print("Date and time: ", day, ".", month, ".", year, " ", hour, ":", minute)
stormIdentifier = codes_get(bufr, "stormIdentifier")
print('Storm identifier: ', stormIdentifier)
print("Storm identifier: ", stormIdentifier)
# How many different timePeriod in the data structure?
numberOfPeriods = 0
@ -76,50 +76,74 @@ def example():
memberNumberLen = len(memberNumber)
# Observed Storm Centre
significance = codes_get(bufr, '#1#meteorologicalAttributeSignificance')
latitudeCentre = codes_get(bufr, '#1#latitude')
longitudeCentre = codes_get(bufr, '#1#longitude')
significance = codes_get(bufr, "#1#meteorologicalAttributeSignificance")
latitudeCentre = codes_get(bufr, "#1#latitude")
longitudeCentre = codes_get(bufr, "#1#longitude")
if significance != 1:
print('ERROR: unexpected #1#meteorologicalAttributeSignificance')
print("ERROR: unexpected #1#meteorologicalAttributeSignificance")
return 1
if (latitudeCentre == CODES_MISSING_DOUBLE) and (longitudeCentre == CODES_MISSING_DOUBLE):
print('Observed storm centre position missing')
if (latitudeCentre == CODES_MISSING_DOUBLE) and (
longitudeCentre == CODES_MISSING_DOUBLE
):
print("Observed storm centre position missing")
else:
print('Observed storm centre: latitude=', latitudeCentre, ' longitude=', longitudeCentre)
print(
"Observed storm centre: latitude=",
latitudeCentre,
" longitude=",
longitudeCentre,
)
# Location of storm in perturbed analysis
significance = codes_get(bufr, '#2#meteorologicalAttributeSignificance')
significance = codes_get(bufr, "#2#meteorologicalAttributeSignificance")
if significance != 4:
print('ERROR: unexpected #2#meteorologicalAttributeSignificance')
print("ERROR: unexpected #2#meteorologicalAttributeSignificance")
return 1
latitudeAnalysis = codes_get_array(bufr, '#2#latitude')
longitudeAnalysis = codes_get_array(bufr, '#2#longitude')
pressureAnalysis = codes_get_array(bufr, '#1#pressureReducedToMeanSeaLevel')
latitudeAnalysis = codes_get_array(bufr, "#2#latitude")
longitudeAnalysis = codes_get_array(bufr, "#2#longitude")
pressureAnalysis = codes_get_array(bufr, "#1#pressureReducedToMeanSeaLevel")
# Location of Maximum Wind
significance = codes_get(bufr, '#3#meteorologicalAttributeSignificance')
significance = codes_get(bufr, "#3#meteorologicalAttributeSignificance")
if significance != 3:
print('ERROR: unexpected #3#meteorologicalAttributeSignificance=', significance)
print(
"ERROR: unexpected #3#meteorologicalAttributeSignificance=",
significance,
)
return 1
latitudeMaxWind0 = codes_get_array(bufr, '#3#latitude')
longitudeMaxWind0 = codes_get_array(bufr, '#3#longitude')
windMaxWind0 = codes_get_array(bufr, '#1#windSpeedAt10M')
latitudeMaxWind0 = codes_get_array(bufr, "#3#latitude")
longitudeMaxWind0 = codes_get_array(bufr, "#3#longitude")
windMaxWind0 = codes_get_array(bufr, "#1#windSpeedAt10M")
if len(latitudeAnalysis) == len(memberNumber) and len(latitudeMaxWind0) == len(memberNumber):
if len(latitudeAnalysis) == len(memberNumber) and len(latitudeMaxWind0) == len(
memberNumber
):
for k in range(len(memberNumber)):
data[k][0] = [latitudeAnalysis[k], longitudeAnalysis[k], pressureAnalysis[k], latitudeMaxWind0[k],
longitudeMaxWind0[k], windMaxWind0[k]]
data[k][0] = [
latitudeAnalysis[k],
longitudeAnalysis[k],
pressureAnalysis[k],
latitudeMaxWind0[k],
longitudeMaxWind0[k],
windMaxWind0[k],
]
else:
for k in range(len(memberNumber)):
data[k][0] = [latitudeAnalysis[0], longitudeAnalysis[0], pressureAnalysis[k], latitudeMaxWind0[0],
longitudeMaxWind0[0], windMaxWind0[k]]
data[k][0] = [
latitudeAnalysis[0],
longitudeAnalysis[0],
pressureAnalysis[k],
latitudeMaxWind0[0],
longitudeMaxWind0[0],
windMaxWind0[k],
]
timePeriod = [0 for x in range(numberOfPeriods)]
for i in range(1, numberOfPeriods):
@ -137,7 +161,9 @@ def example():
break
# Location of the storm
values = codes_get_array(bufr, "#%d#meteorologicalAttributeSignificance" % rank1)
values = codes_get_array(
bufr, "#%d#meteorologicalAttributeSignificance" % rank1
)
if len(values) == 1:
significance = values[0]
else:
@ -149,12 +175,19 @@ def example():
if significance == 1:
lat = codes_get_array(bufr, "#%d#latitude" % rank1)
lon = codes_get_array(bufr, "#%d#longitude" % rank1)
press = codes_get_array(bufr, "#%d#pressureReducedToMeanSeaLevel" % (i + 1))
press = codes_get_array(
bufr, "#%d#pressureReducedToMeanSeaLevel" % (i + 1)
)
else:
print('ERROR: unexpected meteorologicalAttributeSignificance=', significance)
print(
"ERROR: unexpected meteorologicalAttributeSignificance=",
significance,
)
# Location of maximum wind
values = codes_get_array(bufr, "#%d#meteorologicalAttributeSignificance" % rank3)
values = codes_get_array(
bufr, "#%d#meteorologicalAttributeSignificance" % rank3
)
if len(values) == 1:
significanceWind = values[0]
else:
@ -168,20 +201,47 @@ def example():
lonWind = codes_get_array(bufr, "#%d#longitude" % rank3)
wind10m = codes_get_array(bufr, "#%d#windSpeedAt10M" % (i + 1))
else:
print('ERROR: unexpected meteorologicalAttributeSignificance=', significanceWind)
print(
"ERROR: unexpected meteorologicalAttributeSignificance=",
significanceWind,
)
for k in range(len(memberNumber)):
data[k][i] = [lat[k], lon[k], press[k], latWind[k], lonWind[k], wind10m[k]]
data[k][i] = [
lat[k],
lon[k],
press[k],
latWind[k],
lonWind[k],
wind10m[k],
]
# ---------------------------------------- Print the values -------------
for m in range(len(memberNumber)):
print("== Member %d" % memberNumber[m])
print("step latitude longitude pressure latitude longitude wind")
for s in range(len(timePeriod)):
if data[m][s][0] != CODES_MISSING_DOUBLE and data[m][s][1] != CODES_MISSING_DOUBLE:
print(" {0:>3d}{1}{2:>6.1f}{3}{4:>6.1f}{5}{6:>8.1f}{7}{8:>6.1f}{9}{10:>6.1f}{11}{12:>6.1f}".format(
timePeriod[s], ' ', data[m][s][0], ' ', data[m][s][1], ' ', data[m][s][2], ' ',
data[m][s][3], ' ', data[m][s][4], ' ', data[m][s][5]))
if (
data[m][s][0] != CODES_MISSING_DOUBLE
and data[m][s][1] != CODES_MISSING_DOUBLE
):
print(
" {0:>3d}{1}{2:>6.1f}{3}{4:>6.1f}{5}{6:>8.1f}{7}{8:>6.1f}{9}{10:>6.1f}{11}{12:>6.1f}".format(
timePeriod[s],
" ",
data[m][s][0],
" ",
data[m][s][1],
" ",
data[m][s][2],
" ",
data[m][s][3],
" ",
data[m][s][4],
" ",
data[m][s][5],
)
)
# -----------------------------------------------------------------------
cnt += 1
@ -200,7 +260,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -21,17 +21,17 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/syno_multi.bufr'
OUTPUT = 'bufr_set_keys_test_p.tmp.bufr'
INPUT = "../../data/bufr/syno_multi.bufr"
OUTPUT = "bufr_set_keys_test_p.tmp.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open BUFR file
fin = open(INPUT, 'rb')
fin = open(INPUT, "rb")
# open output BUFR file
fout = open(OUTPUT, 'wb')
fout = open(OUTPUT, "wb")
cnt = 0
@ -54,16 +54,16 @@ def example():
# set centre
val = 222
print(' set bufrHeaderCentre to: %d' % val)
print(" set bufrHeaderCentre to: %d" % val)
key = 'bufrHeaderCentre'
key = "bufrHeaderCentre"
try:
print(' %s: %s' % (key, codes_set(bufr, key, val)))
print(" %s: %s" % (key, codes_set(bufr, key, val)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
# check bufrHeaderCentre's value
print(' %s''s new value is: %d' % (key, codes_get(bufr, key)))
print(" %s" "s new value is: %d" % (key, codes_get(bufr, key)))
# write modified message to output
codes_write(bufr, fout)
@ -84,7 +84,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -21,13 +21,13 @@ import traceback
from eccodes import *
INPUT = '../../data/bufr/synop_multi_subset.bufr'
INPUT = "../../data/bufr/synop_multi_subset.bufr"
VERBOSE = 1 # verbose error reporting
def example():
# open BUFR file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -42,25 +42,25 @@ def example():
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
codes_set(bufr, 'unpack', 1)
codes_set(bufr, "unpack", 1)
# find out the number of subsets
key = 'numberOfSubsets'
numberOfSubsets = codes_get(bufr, 'numberOfSubsets')
print(' %s: %d' % (key, numberOfSubsets))
key = "numberOfSubsets"
numberOfSubsets = codes_get(bufr, "numberOfSubsets")
print(" %s: %d" % (key, numberOfSubsets))
# loop over the subsets
for i in range(1, numberOfSubsets + 1):
# read and print some data values
key = '/subsetNumber=%d/blockNumber' % i
key = "/subsetNumber=%d/blockNumber" % i
print(key)
val = codes_get_long(bufr, key)
print(' %s= %d' % (key, val))
print(" %s= %d" % (key, val))
key = '/subsetNumber=%d/stationNumber' % i
key = "/subsetNumber=%d/stationNumber" % i
val = codes_get_long(bufr, key)
print(' %s: %d' % (key, val))
print(" %s: %d" % (key, val))
cnt += 1
@ -78,7 +78,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -26,16 +26,16 @@ VERBOSE = 1 # verbose error reporting
def example():
if len(sys.argv) < 2:
print('Usage: ', sys.argv[0], ' file', file=sys.stderr)
print("Usage: ", sys.argv[0], " file", file=sys.stderr)
sys.exit(1)
f = open(sys.argv[1], 'rb')
f = open(sys.argv[1], "rb")
while 1:
ident = codes_new_from_file(f, CODES_PRODUCT_ANY)
if ident is None:
break
print('product: ', codes_get(ident, 'kindOfProduct', str))
print("product: ", codes_get(ident, "kindOfProduct", str))
codes_release(ident)
@ -49,7 +49,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -14,17 +14,17 @@ import traceback
from eccodes import *
INPUT = '../../data/ccsds.grib2'
INPUT = "../../data/ccsds.grib2"
VERBOSE = 1 # verbose error reporting
def example():
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
keys = [
'ccsdsFlags',
'ccsdsBlockSize',
'bitsPerValue',
"ccsdsFlags",
"ccsdsBlockSize",
"bitsPerValue",
]
while 1:
@ -34,7 +34,7 @@ def example():
for key in keys:
try:
print(' %s: %s' % (key, codes_get(gid, key)))
print(" %s: %s" % (key, codes_get(gid, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -50,7 +50,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -15,25 +15,25 @@ import traceback
from eccodes import *
INPUT = '../../data/constant_field.grib1'
OUTPUT = 'out.clone.grib'
INPUT = "../../data/constant_field.grib1"
OUTPUT = "out.clone.grib"
VERBOSE = 1 # verbose error reporting
def example():
fin = open(INPUT, 'rb')
fout = open(OUTPUT, 'wb')
fin = open(INPUT, "rb")
fout = open(OUTPUT, "wb")
gid = codes_grib_new_from_file(fin)
assert not codes_is_missing(gid, 'Ni')
assert not codes_is_missing(gid, 'Nj')
nx = codes_get(gid, 'Ni')
ny = codes_get(gid, 'Nj')
assert not codes_is_missing(gid, "Ni")
assert not codes_is_missing(gid, "Nj")
nx = codes_get(gid, "Ni")
ny = codes_get(gid, "Nj")
for step in range(0, 24, 6):
clone_id = codes_clone(gid)
codes_set(clone_id, 'step', step)
codes_set(clone_id, "step", step)
values = [random.random() for i in range(nx * ny)]
@ -55,7 +55,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -16,12 +16,12 @@ import traceback
from eccodes import *
INPUT = '../../data/tigge_pf_ecmwf.grib2'
INPUT = "../../data/tigge_pf_ecmwf.grib2"
VERBOSE = 1 # verbose error reporting
def example():
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
mcount = codes_count_in_file(f)
gid_list = [codes_grib_new_from_file(f) for i in range(mcount)]
@ -29,14 +29,14 @@ def example():
f.close()
keys = [
'Ni',
'Nj',
'latitudeOfFirstGridPointInDegrees',
'longitudeOfFirstGridPointInDegrees',
'latitudeOfLastGridPointInDegrees',
'longitudeOfLastGridPointInDegrees',
'jDirectionIncrementInDegrees',
'iDirectionIncrementInDegrees',
"Ni",
"Nj",
"latitudeOfFirstGridPointInDegrees",
"longitudeOfFirstGridPointInDegrees",
"latitudeOfLastGridPointInDegrees",
"longitudeOfLastGridPointInDegrees",
"jDirectionIncrementInDegrees",
"iDirectionIncrementInDegrees",
]
for i in range(mcount):
@ -45,16 +45,19 @@ def example():
print("processing message number", i + 1)
for key in keys:
print('%s=%g' % (key, codes_get(gid, key)))
print("%s=%g" % (key, codes_get(gid, key)))
print('There are %d, average is %g, min is %g, max is %g' % (
codes_get_size(gid, 'values'),
codes_get(gid, 'average'),
codes_get(gid, 'min'),
codes_get(gid, 'max')
))
print(
"There are %d, average is %g, min is %g, max is %g"
% (
codes_get_size(gid, "values"),
codes_get(gid, "average"),
codes_get(gid, "min"),
codes_get(gid, "max"),
)
)
print('-' * 100)
print("-" * 100)
codes_release(gid)
@ -66,7 +69,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -19,20 +19,20 @@ import traceback
from eccodes import *
INPUT = '../../data/reduced_latlon_surface.grib1'
INPUT = "../../data/reduced_latlon_surface.grib1"
VERBOSE = 1 # verbose error reporting
def example():
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
keys = [
'Ni',
'Nj',
'latitudeOfFirstGridPointInDegrees',
'longitudeOfFirstGridPointInDegrees',
'latitudeOfLastGridPointInDegrees',
'longitudeOfLastGridPointInDegrees',
"Ni",
"Nj",
"latitudeOfFirstGridPointInDegrees",
"longitudeOfFirstGridPointInDegrees",
"latitudeOfLastGridPointInDegrees",
"longitudeOfLastGridPointInDegrees",
]
while 1:
@ -42,7 +42,7 @@ def example():
for key in keys:
try:
print(' %s: %s' % (key, codes_get(gid, key)))
print(" %s: %s" % (key, codes_get(gid, key)))
except KeyValueNotFoundError as err:
# Full list of exceptions here:
# https://confluence.ecmwf.int/display/ECC/Python+exception+classes
@ -50,12 +50,15 @@ def example():
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
print('There are %d values, average is %f, min is %f, max is %f' % (
codes_get_size(gid, 'values'),
codes_get(gid, 'average'),
codes_get(gid, 'min'),
codes_get(gid, 'max')
))
print(
"There are %d values, average is %f, min is %f, max is %f"
% (
codes_get_size(gid, "values"),
codes_get(gid, "average"),
codes_get(gid, "min"),
codes_get(gid, "max"),
)
)
codes_release(gid)
@ -69,7 +72,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -26,10 +26,10 @@ VERBOSE = 1 # verbose error reporting
def example():
if len(sys.argv) < 2:
print('Usage: ', sys.argv[0], ' file', file=sys.stderr)
print("Usage: ", sys.argv[0], " file", file=sys.stderr)
sys.exit(1)
f = open(sys.argv[1], 'rb')
f = open(sys.argv[1], "rb")
while 1:
ident = codes_grib_new_from_file(f)
if ident is None:
@ -49,7 +49,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -20,14 +20,14 @@ import traceback
from eccodes import *
INPUT = '../../data/index.grib'
INPUT = "../../data/index.grib"
VERBOSE = 1 # verbose error reporting
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = list(map(tuple, args)) * kwds.get('repeat', 1)
pools = list(map(tuple, args)) * kwds.get("repeat", 1)
result = [[]]
for pool in pools:
result = [x + [y] for x in result for y in pool]
@ -54,10 +54,7 @@ def example():
index_vals = []
for key in index_keys:
print("%sSize=%d" % (
key,
codes_index_get_size(iid, key)
))
print("%sSize=%d" % (key, codes_index_get_size(iid, key)))
key_vals = codes_index_get(iid, key)
print(" ".join(key_vals))
@ -72,8 +69,9 @@ def example():
gid = codes_new_from_index(iid)
if gid is None:
break
print(" ".join(["%s=%s" % (key, codes_get(gid, key))
for key in index_keys]))
print(
" ".join(["%s=%s" % (key, codes_get(gid, key)) for key in index_keys])
)
codes_release(gid)
codes_index_release(iid)
@ -86,7 +84,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -16,7 +16,7 @@ import traceback
from eccodes import *
VERBOSE = 1 # verbose error reporting
missingValue = 1e+20 # A value out of range
missingValue = 1e20 # A value out of range
def example(INPUT):
@ -66,7 +66,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -23,7 +23,7 @@ VERBOSE = 1 # verbose error reporting
def example(INPUT):
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
while 1:
gid = codes_grib_new_from_file(f)
@ -32,13 +32,13 @@ def example(INPUT):
iterid = codes_grib_iterator_new(gid, 0)
bitmapPresent = codes_get(gid, 'bitmapPresent')
bitmapPresent = codes_get(gid, "bitmapPresent")
if bitmapPresent:
# Get the bitmap array which contains 0s and 1s
bitmap = codes_get_array(gid, 'bitmap', int)
bitmap = codes_get_array(gid, "bitmap", int)
# Do some sanity checking
assert len(bitmap) == codes_get_size(gid, 'values')
assert len(bitmap) == codes_get(gid, 'numberOfDataPoints')
assert len(bitmap) == codes_get_size(gid, "values")
assert len(bitmap) == codes_get(gid, "numberOfDataPoints")
i = 0
while 1:
@ -71,7 +71,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -16,19 +16,19 @@ import traceback
from eccodes import *
INPUT = '../../data/reduced_latlon_surface.grib1'
INPUT = "../../data/reduced_latlon_surface.grib1"
VERBOSE = 1 # verbose error reporting
def example():
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
while 1:
gid = codes_grib_new_from_file(f)
if gid is None:
break
iterid = codes_keys_iterator_new(gid, 'ls')
iterid = codes_keys_iterator_new(gid, "ls")
# Different types of keys can be skipped
# codes_skip_computed(iterid)
@ -56,7 +56,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -21,14 +21,14 @@ import traceback
from eccodes import *
VERBOSE = 1 # verbose error reporting
default_namespace = 'ls'
default_namespace = "ls"
def do_print(namespace, INPUT):
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
first_time = True
print('{')
print("{")
print(' "messages" : [')
while 1:
gid = codes_grib_new_from_file(f)
@ -36,9 +36,9 @@ def do_print(namespace, INPUT):
break
if not first_time:
print(' ,{')
print(" ,{")
else:
print(' {')
print(" {")
first_time = False
iterid = codes_keys_iterator_new(gid, namespace)
@ -48,30 +48,30 @@ def do_print(namespace, INPUT):
keyname = codes_keys_iterator_get_name(iterid)
keyval = codes_get_string(gid, keyname)
if not f1:
print(',')
print(",")
else:
print('')
print("")
f1 = False
print(" \"%s\" : \"%s\"" % (keyname, keyval), end=' ')
print(' "%s" : "%s"' % (keyname, keyval), end=" ")
print('')
print(' }')
print("")
print(" }")
codes_keys_iterator_delete(iterid)
codes_release(gid)
print(' ]')
print('}')
print(" ]")
print("}")
f.close()
def usage():
progname = os.path.basename(sys.argv[0])
print("Usage: ", progname, "[options] grib_file1 grib_file2 ...")
print('Options:')
print('\t-n namespace')
print('\t\tAll the keys belonging to namespace are printed.')
print('\t-m Mars keys are printed.')
print('')
print("Options:")
print("\t-n namespace")
print("\t\tAll the keys belonging to namespace are printed.")
print("\t-m Mars keys are printed.")
print("")
def main():
@ -83,12 +83,12 @@ def main():
namespace = default_namespace
opts, args = getopt.getopt(sys.argv[1:], options)
for o, a in opts:
if o == '-m':
namespace = 'mars'
elif o == '-n':
if o == "-m":
namespace = "mars"
elif o == "-n":
namespace = a or default_namespace
else:
assert False, 'Invalid option'
assert False, "Invalid option"
# Check we have some GRIB files to process
if not args:
@ -97,7 +97,7 @@ def main():
for arg in args:
do_print(namespace, arg)
except getopt.GetoptError as err:
print('Error: ', err)
print("Error: ", err)
usage()
return 1
except GribInternalError as err:

View File

@ -14,14 +14,14 @@ import traceback
from eccodes import *
INPUT = '../../data/sample.grib2'
OUTPUT = 'out.mw.grib'
INPUT = "../../data/sample.grib2"
OUTPUT = "out.mw.grib"
VERBOSE = 1 # verbose error reporting
def example():
fin = open(INPUT, 'rb')
fout = open(OUTPUT, 'wb')
fin = open(INPUT, "rb")
fout = open(OUTPUT, "wb")
gid = codes_grib_new_from_file(fin)
@ -46,7 +46,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -16,21 +16,20 @@ import traceback
from eccodes import *
INPUT = '../../data/reduced_gaussian_lsm.grib1'
INPUT = "../../data/reduced_gaussian_lsm.grib1"
VERBOSE = 1 # verbose error reporting
def example():
points = ((30, -20), (13, 234))
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
gid = codes_grib_new_from_file(f)
for lat, lon in points:
nearest = codes_grib_find_nearest(gid, lat, lon)[0]
print(lat, lon)
print(nearest.lat, nearest.lon, nearest.value, nearest.distance,
nearest.index)
print(nearest.lat, nearest.lon, nearest.value, nearest.distance, nearest.index)
four = codes_grib_find_nearest(gid, lat, lon, is_lsm=False, npoints=4)
for i in range(len(four)):
@ -50,7 +49,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -16,12 +16,12 @@ import traceback
from eccodes import *
INPUT = '../../data/regular_latlon_surface.grib1'
INPUT = "../../data/regular_latlon_surface.grib1"
VERBOSE = 1 # verbose error reporting
def example():
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
gid = codes_grib_new_from_file(f)
values = codes_get_values(gid)
@ -29,15 +29,15 @@ def example():
for i in range(num_vals):
print("%d %.10e" % (i + 1, values[i]))
print('%d values found in %s' % (num_vals, INPUT))
print("%d values found in %s" % (num_vals, INPUT))
for key in ('max', 'min', 'average'):
print('%s=%.10e' % (key, codes_get(gid, key)))
for key in ("max", "min", "average"):
print("%s=%.10e" % (key, codes_get(gid, key)))
# Example of accessing specific elements from data values
# Get first, middle and last elements
indexes = [0, int(num_vals / 2), num_vals - 1]
elems = codes_get_double_elements(gid, 'values', indexes)
elems = codes_get_double_elements(gid, "values", indexes)
codes_release(gid)
f.close()
@ -50,7 +50,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -25,19 +25,19 @@ VERBOSE = 1 # verbose error reporting
def example(INPUT):
# open GRIB file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
# These keys should be in the sample files
keys = [
'identifier',
'editionNumber',
'year',
'month',
'latitudeOfFirstGridPointInDegrees',
'longitudeOfFirstGridPointInDegrees',
'bitsPerValue',
'stepType',
'packingType'
"identifier",
"editionNumber",
"year",
"month",
"latitudeOfFirstGridPointInDegrees",
"longitudeOfFirstGridPointInDegrees",
"bitsPerValue",
"stepType",
"packingType",
]
cnt = 0
@ -51,7 +51,7 @@ def example(INPUT):
print("message: %s" % cnt)
for key in keys:
print(' %s=%s' % (key, codes_get(gid, key)))
print(" %s=%s" % (key, codes_get(gid, key)))
cnt += 1
@ -67,7 +67,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -14,24 +14,24 @@ import traceback
from eccodes import *
INPUT = '../../data/tp_ecmwf.grib'
OUTPUT = 'p_out.grib_samples.grib'
INPUT = "../../data/tp_ecmwf.grib"
OUTPUT = "p_out.grib_samples.grib"
VERBOSE = 1 # verbose error reporting
def example():
sample_id = codes_grib_new_from_samples("regular_ll_sfc_grib1")
fin = open(INPUT, 'rb')
fout = open(OUTPUT, 'wb')
fin = open(INPUT, "rb")
fout = open(OUTPUT, "wb")
keys = {
'dataDate': 20080104,
'startStep': 0,
'endStep': 12,
'stepType': 'accum',
'table2Version': 2,
'indicatorOfParameter': 61,
'decimalPrecision': 2,
"dataDate": 20080104,
"startStep": 0,
"endStep": 12,
"stepType": "accum",
"table2Version": 2,
"indicatorOfParameter": 61,
"decimalPrecision": 2,
}
prev_vals = None
@ -54,8 +54,8 @@ def example():
result[i] -= prev_vals[i]
prev_vals = curr_vals
keys['startStep'] += 12
keys['endStep'] += 12
keys["startStep"] += 12
keys["endStep"] += 12
clone_id = codes_clone(sample_id)
@ -79,7 +79,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -13,15 +13,15 @@ import traceback
from eccodes import *
INPUT = '../../data/regular_latlon_surface.grib1'
OUTPUT = 'out.set_bitmap_p.grib'
INPUT = "../../data/regular_latlon_surface.grib1"
OUTPUT = "out.set_bitmap_p.grib"
MISSING = 9999
VERBOSE = 1 # verbose error reporting
def example():
fin = open(INPUT, 'rb')
fout = open(OUTPUT, 'wb')
fin = open(INPUT, "rb")
fout = open(OUTPUT, "wb")
gid = codes_grib_new_from_file(fin)
# The missingValue is not coded in the message.
@ -29,12 +29,12 @@ def example():
# at a point in the grid.
# It should be chosen so that it cannot be confused
# with a valid field value
codes_set(gid, 'missingValue', MISSING)
codes_set(gid, "missingValue", MISSING)
values = codes_get_values(gid)
# Enable bitmap
codes_set(gid, 'bitmapPresent', 1)
codes_set(gid, "bitmapPresent", 1)
# Change some data values to be missing
num_missing = 0
@ -46,10 +46,10 @@ def example():
codes_set_values(gid, values)
# Check counts of missing and non-missing values
num_data = codes_get(gid, 'numberOfDataPoints', int)
num_data = codes_get(gid, "numberOfDataPoints", int)
assert num_data == len(values)
assert codes_get(gid, 'numberOfCodedValues', int) == num_data - num_missing
assert codes_get(gid, 'numberOfMissing', int) == num_missing
assert codes_get(gid, "numberOfCodedValues", int) == num_data - num_missing
assert codes_get(gid, "numberOfMissing", int) == num_missing
codes_write(gid, fout)
codes_release(gid)

View File

@ -21,51 +21,51 @@ from datetime import date
from eccodes import *
INPUT = '../../data/regular_latlon_surface_constant.grib1'
OUTPUT = 'out.set.grib'
INPUT = "../../data/regular_latlon_surface_constant.grib1"
OUTPUT = "out.set.grib"
VERBOSE = 1 # verbose error reporting
def example():
fin = open(INPUT, 'rb')
fout = open(OUTPUT, 'wb')
fin = open(INPUT, "rb")
fout = open(OUTPUT, "wb")
gid = codes_grib_new_from_file(fin)
dt = date.today()
today = "%d%02d%02d" % (dt.year, dt.month, dt.day)
codes_set(gid, 'dataDate', int(today))
codes_set(gid, 'centre', 80)
codes_set(gid, "dataDate", int(today))
codes_set(gid, "centre", 80)
centreIntVal = codes_get_array(gid, 'centre', int)
centreStrVal = codes_get_array(gid, 'centre', str)
dateStrVal = codes_get_array(gid, 'dataDate', str)
assert (centreIntVal[0] == 80)
assert (centreStrVal[0] == 'cnmc')
assert (dateStrVal[0] == today)
print('get centre as an integer - centre = %d' % centreIntVal[0])
print('get centre as a string - centre = %s' % centreStrVal[0])
print('get date as a string - date = %s' % dateStrVal[0])
centreIntVal = codes_get_array(gid, "centre", int)
centreStrVal = codes_get_array(gid, "centre", str)
dateStrVal = codes_get_array(gid, "dataDate", str)
assert centreIntVal[0] == 80
assert centreStrVal[0] == "cnmc"
assert dateStrVal[0] == today
print("get centre as an integer - centre = %d" % centreIntVal[0])
print("get centre as a string - centre = %s" % centreStrVal[0])
print("get date as a string - date = %s" % dateStrVal[0])
# Now do the same but using set_key_vals, setting keys all at once
print('set keys using one long comma-separated string...')
codes_set_key_vals(gid, 'level=1,centre=98')
assert (codes_get(gid, 'centre', str) == 'ecmf')
assert (codes_get(gid, 'level', int) == 1)
print("set keys using one long comma-separated string...")
codes_set_key_vals(gid, "level=1,centre=98")
assert codes_get(gid, "centre", str) == "ecmf"
assert codes_get(gid, "level", int) == 1
print('set keys using a list of strings...')
codes_set_key_vals(gid, ['level=2', 'centre=kwbc'])
assert (codes_get(gid, 'centre', int) == 7)
assert (codes_get(gid, 'level', int) == 2)
print("set keys using a list of strings...")
codes_set_key_vals(gid, ["level=2", "centre=kwbc"])
assert codes_get(gid, "centre", int) == 7
assert codes_get(gid, "level", int) == 2
print('set keys using a dictionary (order not as specified!)...')
codes_set_key_vals(gid, {'level': 3, 'centre': 84})
assert (codes_get(gid, 'centre', str) == 'lfpw')
assert (codes_get(gid, 'level', int) == 3)
print("set keys using a dictionary (order not as specified!)...")
codes_set_key_vals(gid, {"level": 3, "centre": 84})
assert codes_get(gid, "centre", str) == "lfpw"
assert codes_get(gid, "level", int) == 3
print('set keys using an ordered dictionary...')
codes_set_key_vals(gid, OrderedDict([('level', 3), ('centre', 84)]))
assert (codes_get(gid, 'centre', str) == 'lfpw')
assert (codes_get(gid, 'level', int) == 3)
print("set keys using an ordered dictionary...")
codes_set_key_vals(gid, OrderedDict([("level", 3), ("centre", 84)]))
assert codes_get(gid, "centre", str) == "lfpw"
assert codes_get(gid, "level", int) == 3
codes_gts_header(True)
codes_gts_header(False)
@ -83,7 +83,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -14,26 +14,26 @@ import traceback
from eccodes import *
INPUT = '../../data/tigge/tigge_ecmf_pl_t.grib'
OUTPUT = 'out.p_set_missing.grib'
INPUT = "../../data/tigge/tigge_ecmf_pl_t.grib"
OUTPUT = "out.p_set_missing.grib"
VERBOSE = 1 # verbose error reporting
def example():
fin = open(INPUT, 'rb')
fout = open(OUTPUT, 'wb')
fin = open(INPUT, "rb")
fout = open(OUTPUT, "wb")
gid = codes_grib_new_from_file(fin)
codes_set_long(gid, "scaledValueOfFirstFixedSurface", 15)
codes_set_long(gid, "scaleFactorOfFirstFixedSurface", 1)
level = codes_get_double(gid, "level")
assert (level == 1.5)
assert level == 1.5
# set type of level to surface
codes_set(gid, 'typeOfFirstFixedSurface', 'sfc')
codes_set_missing(gid, 'scaleFactorOfFirstFixedSurface')
codes_set_missing(gid, 'scaledValueOfFirstFixedSurface')
codes_set(gid, "typeOfFirstFixedSurface", "sfc")
codes_set_missing(gid, "scaleFactorOfFirstFixedSurface")
codes_set_missing(gid, "scaledValueOfFirstFixedSurface")
codes_write(gid, fout)
@ -49,7 +49,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -23,20 +23,20 @@ def example():
"""
# read the coefficients from file
pv = []
for line in open('../../data/60_model_levels'):
pv.extend([float(x) for x in line.strip().split('\t')])
for line in open("../../data/60_model_levels"):
pv.extend([float(x) for x in line.strip().split("\t")])
numberOfLevels = 60
numberOfCoefficients = 2 * (numberOfLevels + 1)
assert (len(pv) == numberOfCoefficients)
assert len(pv) == numberOfCoefficients
fout = open('grib_set_pv.py.temp.grib', 'wb')
gid = codes_grib_new_from_samples('reduced_gg_sfc_grib1')
fout = open("grib_set_pv.py.temp.grib", "wb")
gid = codes_grib_new_from_samples("reduced_gg_sfc_grib1")
codes_set(gid, 'typeOfLevel', 'hybrid')
codes_set(gid, 'level', 2)
codes_set(gid, 'PVPresent', 1)
codes_set_array(gid, 'pv', pv)
codes_set(gid, "typeOfLevel", "hybrid")
codes_set(gid, "level", 2)
codes_set(gid, "PVPresent", 1)
codes_set_array(gid, "pv", pv)
codes_write(gid, fout)
@ -51,10 +51,10 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1
if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())

View File

@ -20,13 +20,13 @@ import traceback
from eccodes import *
INPUT = '../../data/gts/EGRR20150317121020_00493212.DAT'
INPUT = "../../data/gts/EGRR20150317121020_00493212.DAT"
VERBOSE = 1 # verbose error reporting
def example():
# open GTS file
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
cnt = 0
@ -43,11 +43,11 @@ def example():
# ---------------------------------------------
# get values for keys holding a single value
# ---------------------------------------------
keys = ['TT', 'AA', 'II', 'CCCC', 'YY', 'GG', 'gg', 'BBB']
keys = ["TT", "AA", "II", "CCCC", "YY", "GG", "gg", "BBB"]
for key in keys:
try:
print(' %s: %s' % (key, codes_get(gid, key)))
print(" %s: %s" % (key, codes_get(gid, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -65,7 +65,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1

View File

@ -16,12 +16,12 @@ import traceback
from eccodes import *
INPUT = '../../data/gts.bufr'
INPUT = "../../data/gts.bufr"
VERBOSE = 1 # verbose error reporting
def example():
f = open(INPUT, 'rb')
f = open(INPUT, "rb")
while 1:
gid = gts_new_from_file(f)

View File

@ -21,17 +21,25 @@ import traceback
from eccodes import *
INPUT = '../../data/metar/metar.txt'
INPUT = "../../data/metar/metar.txt"
VERBOSE = 1 # verbose error reporting
def print_keys(msg_id):
keys = ['CCCC', 'latitude', 'longitude', 'dateTime',
'elevation', 'temperature', 'dewPointTemperature', 'qnh']
keys = [
"CCCC",
"latitude",
"longitude",
"dateTime",
"elevation",
"temperature",
"dewPointTemperature",
"qnh",
]
for key in keys:
try:
if codes_is_defined(msg_id, key):
print(' %s: %s' % (key, codes_get(msg_id, key)))
print(" %s: %s" % (key, codes_get(msg_id, key)))
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
@ -62,7 +70,7 @@ def example1():
def example2():
# This time read from a string rather than a file.
metar_str = 'METAR LQMO 022350Z 09003KT 6000 FEW010 SCT035 BKN060 08/08 Q1003='
metar_str = "METAR LQMO 022350Z 09003KT 6000 FEW010 SCT035 BKN060 08/08 Q1003="
# get handle for message
msg_id = codes_new_from_message(metar_str)
@ -81,7 +89,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write(err.msg + '\n')
sys.stderr.write(err.msg + "\n")
return 1