Example #1
0
def print_bufr_data_category(input_bufr_file):
    #  #[
    """
    an example routine to demonstrate how to retrieve
    some meta datafrom the BUFR messages in a BUFR file
    """
    # get an instance of the RawBUFRFile class
    rbf = RawBUFRFile()

    # open the file for reading, count nr of BUFR messages in it
    # and store its content in memory, together with
    # an array of pointers to the start and end of each BUFR message
    rbf.open(input_bufr_file, 'rb')

    # extract the number of BUFR messages from the file
    num_msgs = rbf.get_num_bufr_msgs()

    for msg_nr in range(1, num_msgs + 1):
        raw_msg = rbf.get_raw_bufr_msg(msg_nr)[0]
        bufr_obj = BUFRInterfaceECMWF(encoded_message=raw_msg)
        bufr_obj.decode_sections_012()
        data_category = bufr_obj.ksec1[11 - 1]
        print('BUFR msg %i has data category %i' % (msg_nr, data_category))

    # close the file
    rbf.close()
def print_bufr_edition_number(input_bufr_file):
    #  #[
    """
    an example routine to demonstrate how to retrieve
    some meta data from the BUFR messages in a BUFR file
    """
    # get an instance of the RawBUFRFile class
    rbf = RawBUFRFile()

    # open the file for reading, count nr of BUFR messages in it
    # and store its content in memory, together with
    # an array of pointers to the start and end of each BUFR message
    rbf.open(input_bufr_file, 'rb')

    # extract the number of BUFR messages from the file
    num_msgs = rbf.get_num_bufr_msgs()

    for msg_nr in range(1, num_msgs+1):
        raw_msg = rbf.get_raw_bufr_msg(msg_nr)[0]
        bufr_obj = BUFRInterfaceECMWF(encoded_message=raw_msg)
        bufr_obj.decode_sections_012()
        bufr_edition = bufr_obj.ksec0[3-1]
        print('BUFR msg %i has version %i' % (msg_nr, bufr_edition))

    # close the file
    rbf.close()
    def test_get_exp_bufr_table_names(self):
        #  #[
        """
        test the get_expected_ecmwf_bufr_table_names method
        """

        center = 210 # = ksec1( 3)
        subcenter = 0 # = ksec1(16)
        local_version = 1 # = ksec1( 8)
        master_table_version = 0 # = ksec1(15)
        edition_number = 3 # =  ksec0( 3)
        master_table_number = 0 # = ksec1(14)
        bufrobj = BUFRInterfaceECMWF()

        # inspect the location of the ecmwfbufr*.so file, and derive
        # from this the location of the BUFR tables that are delivered
        # with the ECMWF BUFR library software
        ecmwfbufr_path = os.path.split(ecmwfbufr.__file__)[0]
        path1 = os.path.join(ecmwfbufr_path, "ecmwf_bufrtables")
        path2 = os.path.join(ecmwfbufr_path, '..', "ecmwf_bufrtables")

        if os.path.exists(path1):
            ecmwf_bufr_tables_dir = path1
        elif os.path.exists(path2):
            ecmwf_bufr_tables_dir = path2
        else:
            print("Error: could not find BUFR tables directory")
            raise IOError

        # make sure the path is absolute, otherwise the ECMWF library
        # might fail when it attempts to use it ...
        bufrobj.ecmwf_bufr_tables_dir = os.path.abspath(ecmwf_bufr_tables_dir)

        (btable, ctable, dtable) = \
                 bufrobj.get_expected_ecmwf_bufr_table_names(\
                             center,
                             subcenter,
                             local_version,
                             master_table_version,
                             edition_number,
                             master_table_number)

        # print("tabel name B: ", btable)
        # print("tabel name D: ", dtable)
        self.assertEqual(btable, 'B0000000000210000001.TXT')
        self.assertEqual(ctable, 'C0000000000210000001.TXT')
        self.assertEqual(dtable, 'D0000000000210000001.TXT')
def decoding_example(input_bufr_file, custom_bufr_tables=None):
    #  #[
    """
    wrap the example in a function to circumvent the pylint
    convention of requiring capitals for constants in the global
    scope (since most of these variables are not constants at all))
    """

    # read the binary data using the BUFRFile class
    print('loading testfile: ', input_bufr_file)
    rbf = RawBUFRFile(verbose=False)
    rbf.open(input_bufr_file, 'rb')
    (words, section_sizes, section_start_locations) = \
            rbf.get_next_raw_bufr_msg()
    rbf.close()

    if words is None:
        print('No valid BUFR messages found')
        sys.exit(0)

    print('------------------------------')
    bufr = BUFRInterfaceECMWF(encoded_message=words,
                              section_sizes=section_sizes,
                              section_start_locations=section_start_locations,
                              verbose=True)

    print("calling: decode_sections_012():")
    bufr.decode_sections_012()

    print("Metadata for decoded BUFR message:")
    bufr.print_sections_012_metadata()

    print("calling: setup_tables()")
    if custom_bufr_tables:
        bufr.setup_tables(table_b_to_use=custom_bufr_tables[0],
                          table_c_to_use=custom_bufr_tables[1],
                          table_d_to_use=custom_bufr_tables[2])
    else:
        bufr.setup_tables()

    print("calling: print_sections_012():")
    bufr.print_sections_012()

    # seems not to work correctly now ...
    #bufr.fill_descriptor_list()
    #bufr.print_descriptors()

    print('------------------------------')
    print("calling: bufr.decode_data():")
    bufr.decode_data()

    bufr.decode_sections_0123()
    bufr.fill_descriptor_list_subset(subset=1)

    return bufr
def encoding_example(output_bufr_file):
    #  #[
    """
    wrap the example in a function to circumvent the pylint
    convention of requiring capitals for constants in the global
    scope (since most of these variables are not constants at all))
    """

    bufr = BUFRInterfaceECMWF(verbose=True)

    # fill sections 0, 1, 2 and 3
    num_subsets = 4
    bufr.fill_sections_0123(bufr_code_centre=98, # ECMWF
                            bufr_obstype=3, # sounding
                            bufr_subtype=251, # L1B
                            bufr_table_local_version=1,
                            bufr_table_master=0,
                            bufr_table_master_version=15,
                            bufr_code_subcentre=0, # L2B processing facility
                            num_subsets=num_subsets,
                            bufr_compression_flag=0)
    # 64=compression/0=no compression

    # determine information from sections 0123 to construct the BUFR table
    # names expected by the ECMWF BUFR library and create symlinks to the
    # default tables if needed
    # NOTE: these custom BUFR tables have been created by the
    #       create_bufr_tables.py example script
    bufr.setup_tables(table_b_to_use='B_my_test_BUFR_table.txt',
                      table_c_to_use='C_my_test_BUFR_table.txt',
                      table_d_to_use='D_my_test_BUFR_table.txt')

    # define a descriptor list
    template = BufrTemplate(verbose=True)

    template.add_descriptors(DD_B_048001,        # 0
                             DD_B_048002,        # 1
                             DD_D_348001)        # 2

    bufr.register_and_expand_descriptors(template)

    # activate this one if the encoding crashes without clear cause:
    # bufr.estimated_num_bytes_for_encoding = 25000

    # retrieve the length of the expanded descriptor list
    exp_descr_list_length = bufr.ktdexl
    print("exp_descr_list_length = ", exp_descr_list_length)

    # fill the values array with some dummy varying data
    num_values = exp_descr_list_length*num_subsets
    values = np.zeros(num_values, dtype=np.float64) # this is the default

    # note: these two must be identical for now, otherwise the
    # python to fortran interface breaks down. This also ofcourse is the
    # cause of the huge memory use of cvals in case num_values is large.
    num_cvalues = num_values
    cvals = np.zeros((num_cvalues, 80), dtype=np.character)

    for subset in range(num_subsets):
        # note that python starts counting with 0, unlike fortran,
        # so there is no need to take (subset-1)
        i = subset*exp_descr_list_length

        # fill the message with some dummy data
        values[i] = 1.2515 + 0.0011*subset
        i = i+1
        values[i] = (3.4562 + 0.0012*subset)*1.e-9
        i = i+1
        values[i] = 1.2625 + 0.0003*subset
        i = i+1
        values[i] = (3.4561 + 0.0014*subset)*1.e-9

    # do the encoding to binary format
    bufr.encode_data(values, cvals)

    # get an instance of the RawBUFRFile class
    bf1 = RawBUFRFile()
    # open the file for writing
    bf1.open(output_bufr_file, 'wb')
    # write the encoded BUFR message
    bf1.write_raw_bufr_msg(bufr.encoded_message)
    # close the file
    bf1.close()
# define the table name without preceding 'B' or 'D' character
# (which will be prepended by the below write method)
table_name = '_test_table.txt'
bufr_table_set.write_tables(table_name)

# now use these definitions to create a BUFR template
max_nr_of_repeats = 5
num_subsets = 2
num_repetitions = [3, 5] # actual number to be used

template = BufrTemplate(verbose=True)
template.add_descriptor(D_363192) # 1 item
template.del_repl_max_nr_of_repeats_list = [max_nr_of_repeats,]*num_subsets

# and use this BUFR template to create a test BUFR message
bufr = BUFRInterfaceECMWF(verbose=True)

# fill sections 0, 1, 2 and 3
bufr.fill_sections_0123(bufr_code_centre=0,
                        bufr_obstype=0,
                        bufr_subtype=0,
                        bufr_table_local_version=0,
                        bufr_table_master=0,
                        bufr_table_master_version=0,
                        bufr_code_subcentre=0,
                        num_subsets=num_subsets,
                        bufr_compression_flag=0)
                        # 64=compression/0=no compression

# determine information from sections 0123 to construct the BUFR table
# names expected by the ECMWF BUFR library and create symlinks to the
def encoding_example(output_bufr_file):
    #  #[
    """
    wrap the example in a function to circumvent the pylint
    convention of requiring capitals for constants in the global
    scope (since most of these variables are not constants at all))
    """

    bufr = BUFRInterfaceECMWF(verbose=True)

    # fill sections 0, 1, 2 and 3
    num_subsets = 4
    bufr.fill_sections_0123(bufr_code_centre=98, # ECMWF
                            bufr_obstype=3, # sounding
                            bufr_subtype=251, # L1B
                            bufr_table_local_version=1,
                            bufr_table_master=0,
                            bufr_table_master_version=15,
                            bufr_code_subcentre=0, # L2B processing facility
                            num_subsets=num_subsets,
                            bufr_compression_flag=0)
    # 64=compression/0=no compression

    # determine information from sections 0123 to construct the BUFR table
    # names expected by the ECMWF BUFR library and create symlinks to the
    # default tables if needed
    bufr.setup_tables()

    # define a descriptor list
    template = BufrTemplate()

    template.add_descriptors(DD_D_DATE_YYYYMMDD, # 0
                             DD_D_TIME_HHMM)     # 1

    # delay replication for the next 2 descriptors
    # allow at most 2 delayed replications
    template.add_delayed_replic_descriptors(2,
                                            DD_PRESSURE,
                                            DD_TEMPERATURE)

    # replicate the next 2 descriptors 3 times
    template.add_replicated_descriptors(3,
                                        DD_LATITUDE_HIGH_ACCURACY,
                                        DD_LONGITUDE_HIGH_ACCURACY)

    bufr.register_and_expand_descriptors(template)

    # activate this one if the encoding crashes without clear cause:
    # bufr.estimated_num_bytes_for_encoding = 25000

    # retrieve the length of the expanded descriptor list
    exp_descr_list_length = bufr.ktdexl
    print "exp_descr_list_length = ", exp_descr_list_length

    # fill the values array with some dummy varying data
    num_values = exp_descr_list_length*num_subsets
    values = np.zeros(num_values, dtype=np.float64) # this is the default

    # note: these two must be identical for now, otherwise the
    # python to fortran interface breaks down. This also ofcourse is the
    # cause of the huge memory use of cvals in case num_values is large.
    num_cvalues = num_values
    cvals = np.zeros((num_cvalues, 80), dtype=np.character)

    for subset in range(num_subsets):
        # note that python starts counting with 0, unlike fortran,
        # so there is no need to take (subset-1)
        i = subset*exp_descr_list_length

        values[i] = 1999 # year
        i = i+1
        values[i] = 12 # month
        i = i+1
        values[i] = 31 # day
        i = i+1
        values[i] = 23 # hour
        i = i+1
        values[i] = 59 - subset # minute
        i = i+1
        values[i] = 2 # delayed replication factor
        # this delayed replication factor determines the actual number
        # of values to be stored for this particular subset
        # even if it is less then the number given in kdata above !
        for repl in range(2):
            i = i+1
            values[i] = 1013.e2 - 100.e2*subset+i+repl # pressure [pa]
            i = i+1
            values[i] = 273.15 - 10.*subset+i+repl # temperature [K]
        for repl in range(3):
            i = i+1
            values[i] = 51.82 + 0.05*subset+i+repl # latitude
            i = i+1
            values[i] = 5.25 + 0.1*subset+i+repl # longitude

    # do the encoding to binary format
    bufr.encode_data(values, cvals)

    # get an instance of the RawBUFRFile class
    bf1 = RawBUFRFile()
    # open the file for writing
    bf1.open(output_bufr_file, 'wb')
    # write the encoded BUFR message
    bf1.write_raw_bufr_msg(bufr.encoded_message)
    # close the file
    bf1.close()
Example #8
0
def create_bufr_file(output_bufr_file, template):
    #  #[ create bufr file
    '''
    and use this BUFR template to create a test BUFR message
    '''
    from pybufr_ecmwf.bufr_interface_ecmwf import BUFRInterfaceECMWF
    bufr = BUFRInterfaceECMWF(verbose=True)

    # fill sections 0, 1, 2 and 3
    num_subsets = 2
    bufr.fill_sections_0123(bufr_code_centre=98, # ECMWF
                            bufr_obstype=3, # sounding
                            bufr_subtype=253, # L2B
                            bufr_table_local_version=1,
                            bufr_table_master=0,
                            bufr_table_master_version=15,
                            bufr_code_subcentre=0, # L2B processing facility
                            num_subsets=num_subsets,
                            bufr_compression_flag=0)
                            # 64=compression/0=no compression

    # determine information from sections 0123 to construct the BUFR table
    # names expected by the ECMWF BUFR library and create symlinks to the
    # default tables if needed
    bufr.setup_tables(table_b_to_use='B'+TABLE_NAME,
                      table_d_to_use='D'+TABLE_NAME)
    bufr.register_and_expand_descriptors(template)

    # activate this one if the encoding crashes without clear cause:
    # bufr.estimated_num_bytes_for_encoding = 25000

    # retrieve the length of the expanded descriptor list
    exp_descr_list_length = bufr.ktdexl
    print "exp_descr_list_length = ", exp_descr_list_length

    # fill the values array with some dummy varying data
    num_values = num_subsets*bufr.max_nr_expanded_descriptors
    values = numpy.zeros(num_values, dtype=numpy.float64) # this is the default

    # note: these two must be identical for now, otherwise the
    # python to fortran interface breaks down. This also ofcourse is the
    # cause of the huge memory use of cvals in case num_values is large.
    num_cvalues = num_values
    cvals = numpy.zeros((num_cvalues, 80), dtype=numpy.character)
    cvals_index = 0

    repl_counts = []

    for subset in range(num_subsets):
        # note that python starts counting with 0, unlike fortran,
        # so there is no need to take (subset-1)

        print 'subset,exp_descr_list_length = ', subset, exp_descr_list_length
        i = subset*exp_descr_list_length

        # fill the message with some dummy data

        # fill year, month, day
        for val in [2014, 3, 19]: # fill the header
            values[i] = val+subset
            i += 1

        # fill prod_name
        # this is not python2.6 compatible
        #txt = 'filename{}.txt'.format(subset)
        txt = 'filename'+str(subset)+'.txt'
        cvals[cvals_index, :] = ' '
        for icval, cval in enumerate(txt):
            cvals[cvals_index, icval] = cval

        # values[i] = cvals_index * 1000 + 64 # len(txt)
        values[i] = (cvals_index+1) * 1000 + len(txt)
        i += 1
        cvals_index = cvals_index + 1

        for val in [5.1+0.1*subset, 55.2-0.01*subset, 23., 45., 73., 82.]:
            bufr.verify_in_range(i, val)
            values[i] = val
            i += 1

        if USE_DELAYED_REPLICATION:
            # set actual delayed replication repeats
            num_repl = 3 + 2*subset
            print 'num_repl = ', num_repl
            values[i] = num_repl
            i += 1
            repl_counts.append(num_repl)

            # fill the replicated variable
            for irepl in range(num_repl):
                val = 12.+subset*0.1 + irepl*0.01
                bufr.verify_in_range(i, val)
                values[i] = val
                i += 1

    # do the encoding to binary format
    bufr.kdata = numpy.array(repl_counts)
    print 'bufr.kdata = ', bufr.kdata
    bufr.encode_data(values, cvals)

    print 'DEBUG: values = ', values

    from pybufr_ecmwf.raw_bufr_file import RawBUFRFile
    # get an instance of the RawBUFRFile class
    bf1 = RawBUFRFile()

    # open the file for writing
    bf1.open(output_bufr_file, 'wb')
    # write the encoded BUFR message
    bf1.write_raw_bufr_msg(bufr.encoded_message)
    # close the file
    bf1.close()
Example #9
0
num_replications1 = [1, 2, 3]
num_replications2 = [[
    1,
], [
    2,
    2,
], [3, 3, 3]]

template = BufrTemplate(verbose=True)
template.add_descriptor(D_363192)  # 1 item
template.del_repl_max_nr_of_repeats_list = ([
    max_nr_of_replications,
] * max_nr_of_replications * num_subsets)

# and use this BUFR template to create a test BUFR message
bufr = BUFRInterfaceECMWF(verbose=True)

# fill sections 0, 1, 2 and 3
bufr.fill_sections_0123(bufr_code_centre=0,
                        bufr_obstype=0,
                        bufr_subtype=0,
                        bufr_table_local_version=0,
                        bufr_table_master=0,
                        bufr_table_master_version=0,
                        bufr_code_subcentre=0,
                        num_subsets=num_subsets,
                        bufr_compression_flag=0)
# 64=compression/0=no compression

# determine information from sections 0123 to construct the BUFR table
# names expected by the ECMWF BUFR library and create symlinks to the
Example #10
0
def print_bufr_content3(input_bufr_file, output_fd, separator, max_msg_nr,
                        expand_flags):
    #  #[ implementation 3
    """
    example implementation using the BUFRInterfaceECMWF class
    """
    if expand_flags:
        print('Sorry, expand_flags is not yet implemented ' +
              'for example implementation 3')

    # get an instance of the RawBUFRFile class
    rbf = RawBUFRFile()

    # open the file for reading, count nr of BUFR messages in it
    # and store its content in memory, together with
    # an array of pointers to the start and end of each BUFR message
    rbf.open(input_bufr_file, 'rb')

    # extract the number of BUFR messages from the file
    num_msgs = rbf.get_num_bufr_msgs()

    # print('num_msgs = ',num_msgs)

    for msg_nr in range(1, num_msgs + 1):
        encoded_message, section_sizes, section_start_locations = \
                         rbf.get_raw_bufr_msg(msg_nr)
        bufr_obj = BUFRInterfaceECMWF(encoded_message, section_sizes,
                                      section_start_locations)
        #                              verbose=True)
        bufr_obj.decode_sections_012()
        bufr_obj.setup_tables()
        # print('num_subsets: ', bufr_obj.get_num_subsets())
        # print('num_elements: ',bufr_obj.get_num_elements())
        # bufr_obj.decode_sections_0123()
        # bufr_obj.print_sections_0123_metadata()

        # d = '/home/jos/werk/pybufr_ecmwf_interface/'+\
        #     'BUFR_test_files/radar/bufrtables/'
        # bufr_obj.setup_tables(table_b_to_use = d+'B0000000000085011012.TXT',
        #                      table_d_to_use = d+'D0000000000085011012.TXT')
        # bufr_obj.print_sections_012()
        # bufr_obj.fill_descriptor_list()

        # do the actual decoding
        bufr_obj.decode_data()

        # needed to have the units ready, so autoget_cval will work
        bufr_obj.decode_sections_0123()

        # Create header lines from variable names and units
        if msg_nr == 1:
            list_of_names = []
            list_of_units = []
            for (cname, cunit) in zip(bufr_obj.cnames, bufr_obj.cunits):
                # glue the ndarray of characters together to form strings
                if python3:
                    cname_str = ''.join(c.decode() for c in cname).strip()
                    cunit_str = ''.join(c.decode() for c in cunit).strip()
                else:
                    cname_str = ''.join(cname).strip()
                    cunit_str = ''.join(cunit).strip()

                # cnames is a bit over dimensioned, so check for empty values
                if cname_str.strip() == '':
                    break

                # append the strings to the head list and quote them
                list_of_names.append('"' + cname_str + '"')
                list_of_units.append('"' + cunit_str + '"')

            output_fd.write('"subset nr"' + separator)
            output_fd.write(separator.join(list_of_names) + '\n')

            output_fd.write('""' + separator)
            output_fd.write(separator.join(list_of_units) + '\n')

        nsubsets = bufr_obj.get_num_subsets()
        for subs in range(1, nsubsets + 1):

            # needed to have the units ready, so autoget_cval will work
            bufr_obj.fill_descriptor_list_subset(subs)

            nelements = bufr_obj.get_num_elements()
            data_list = []
            for descr_nr in range(nelements):
                data = bufr_obj.get_value(descr_nr, subs, autoget_cval=True)
                data_list.append(data)
            output_fd.write(
                str(subs) + separator +
                separator.join(str(val) for val in data_list) + "\n")
        print('converted BUFR msg nr. ', msg_nr)
        if (max_msg_nr > 0) and (msg_nr >= max_msg_nr):
            print('skipping remainder of this BUFR file')
            break

    # close the BUFR file
    rbf.close()
    if num_msgs == 0:
        print('no BUFR messages found, are you sure this is a BUFR file?')
Example #11
0
def print_bufr_content3(input_bufr_file, output_fd, separator,
                        max_msg_nr, expand_flags):
    #  #[ implementation 3
    """
    example implementation using the BUFRInterfaceECMWF class
    """
    if expand_flags:
        print('Sorry, expand_flags is not yet implemented '+
              'for example implementation 3')

    # get an instance of the RawBUFRFile class
    rbf = RawBUFRFile()

    # open the file for reading, count nr of BUFR messages in it
    # and store its content in memory, together with
    # an array of pointers to the start and end of each BUFR message
    rbf.open(input_bufr_file, 'rb')

    # extract the number of BUFR messages from the file
    num_msgs = rbf.get_num_bufr_msgs()

    # print('num_msgs = ',num_msgs)

    for msg_nr in range(1, num_msgs+1):
        encoded_message, section_sizes, section_start_locations = \
                         rbf.get_raw_bufr_msg(msg_nr)
        bufr_obj = BUFRInterfaceECMWF(encoded_message, section_sizes,
                                      section_start_locations)
        #                              verbose=True)
        bufr_obj.decode_sections_012()
        bufr_obj.setup_tables()
        # print('num_subsets: ', bufr_obj.get_num_subsets())
        # print('num_elements: ',bufr_obj.get_num_elements())
        # bufr_obj.decode_sections_0123()
        # bufr_obj.print_sections_0123_metadata()

        # d = '/home/jos/werk/pybufr_ecmwf_interface/'+\
        #     'BUFR_test_files/radar/bufrtables/'
        # bufr_obj.setup_tables(table_b_to_use = d+'B0000000000085011012.TXT',
         #                      table_d_to_use = d+'D0000000000085011012.TXT')
        # bufr_obj.print_sections_012()
        # bufr_obj.fill_descriptor_list()

        # do the actual decoding
        bufr_obj.decode_data()

        # needed to have the units ready, so autoget_cval will work
        bufr_obj.decode_sections_0123()

        # Create header lines from variable names and units
        if msg_nr == 1:
            list_of_names = []
            list_of_units = []
            for (cname, cunit) in zip(bufr_obj.cnames, bufr_obj.cunits):
                # glue the ndarray of characters together to form strings
                if python3:
                    cname_str = ''.join(c.decode() for c in cname).strip()
                    cunit_str = ''.join(c.decode() for c in cunit).strip()
                else:
                    cname_str = ''.join(cname).strip()
                    cunit_str = ''.join(cunit).strip()

                # cnames is a bit over dimensioned, so check for empty values
                if cname_str.strip() == '':
                    break

                # append the strings to the head list and quote them
                list_of_names.append('"'+cname_str+'"')
                list_of_units.append('"'+cunit_str+'"')

            output_fd.write('"subset nr"'+separator)
            output_fd.write(separator.join(list_of_names) + '\n')

            output_fd.write('""'+separator)
            output_fd.write(separator.join(list_of_units) + '\n')

        nsubsets = bufr_obj.get_num_subsets()
        for subs in range(1, nsubsets+1):

            # needed to have the units ready, so autoget_cval will work
            bufr_obj.fill_descriptor_list_subset(subs)

            nelements = bufr_obj.get_num_elements()
            data_list = []
            for descr_nr in range(nelements):
                data = bufr_obj.get_value(descr_nr, subs, autoget_cval=True)
                data_list.append(data)
            output_fd.write(str(subs)+separator+
                            separator.join(str(val) for val in data_list)+
                            "\n")
        print('converted BUFR msg nr. ', msg_nr)
        if (max_msg_nr > 0) and (msg_nr >= max_msg_nr):
            print('skipping remainder of this BUFR file')
            break

    # close the BUFR file
    rbf.close()
    if num_msgs == 0:
        print('no BUFR messages found, are you sure this is a BUFR file?')
def create_bufr_file(output_bufr_file, template):
    #  #[ create bufr file
    '''
    and use this BUFR template to create a test BUFR message
    '''
    from pybufr_ecmwf.bufr_interface_ecmwf import BUFRInterfaceECMWF
    bufr = BUFRInterfaceECMWF(verbose=True)

    # fill sections 0, 1, 2 and 3
    num_subsets = 2
    bufr.fill_sections_0123(bufr_code_centre=98, # ECMWF
                            bufr_obstype=3, # sounding
                            bufr_subtype=253, # L2B
                            bufr_table_local_version=1,
                            bufr_table_master=0,
                            bufr_table_master_version=15,
                            bufr_code_subcentre=0, # L2B processing facility
                            num_subsets=num_subsets,
                            bufr_compression_flag=0)
                            # 64=compression/0=no compression

    # determine information from sections 0123 to construct the BUFR table
    # names expected by the ECMWF BUFR library and create symlinks to the
    # default tables if needed
    bufr.setup_tables(table_b_to_use='B'+TABLE_NAME,
                      table_d_to_use='D'+TABLE_NAME)
    bufr.register_and_expand_descriptors(template)

    # activate this one if the encoding crashes without clear cause:
    # bufr.estimated_num_bytes_for_encoding = 25000

    # retrieve the length of the expanded descriptor list
    exp_descr_list_length = bufr.ktdexl
    print "exp_descr_list_length = ", exp_descr_list_length

    # fill the values array with some dummy varying data
    num_values = num_subsets*bufr.max_nr_expanded_descriptors
    values = numpy.zeros(num_values, dtype=numpy.float64) # this is the default

    # note: these two must be identical for now, otherwise the
    # python to fortran interface breaks down. This also ofcourse is the
    # cause of the huge memory use of cvals in case num_values is large.
    num_cvalues = num_values
    cvals = numpy.zeros((num_cvalues, 80), dtype=numpy.character)
    cvals_index = 0

    repl_counts = []

    for subset in range(num_subsets):
        # note that python starts counting with 0, unlike fortran,
        # so there is no need to take (subset-1)

        print 'subset,exp_descr_list_length = ', subset, exp_descr_list_length
        i = subset*exp_descr_list_length

        # fill the message with some dummy data

        # fill year, month, day
        for val in [2014, 3, 19]: # fill the header
            values[i] = val+subset
            i += 1

        # fill prod_name
        txt = 'filename{}.txt'.format(subset)
        cvals[cvals_index, :] = ' '
        for icval, cval in enumerate(txt):
            cvals[cvals_index, icval] = cval

        # values[i] = cvals_index * 1000 + 64 # len(txt)
        values[i] = (cvals_index+1) * 1000 + len(txt)
        i += 1
        cvals_index = cvals_index + 1

        for val in [5.1+0.1*subset, 55.2-0.01*subset, 23., 45., 73., 82.]:
            bufr.verify_in_range(i, val)
            values[i] = val
            i += 1

        if USE_DELAYED_REPLICATION:
            # set actual delayed replication repeats
            num_repl = 3 + 2*subset
            print 'num_repl = ', num_repl
            values[i] = num_repl
            i += 1
            repl_counts.append(num_repl)

            # fill the replicated variable
            for irepl in range(num_repl):
                val = 12.+subset*0.1 + irepl*0.01
                bufr.verify_in_range(i, val)
                values[i] = val
                i += 1

    # do the encoding to binary format
    bufr.kdata = numpy.array(repl_counts)
    print 'bufr.kdata = ', bufr.kdata
    bufr.encode_data(values, cvals)

    print 'DEBUG: values = ', values

    from pybufr_ecmwf.raw_bufr_file import RawBUFRFile
    # get an instance of the RawBUFRFile class
    bf1 = RawBUFRFile()

    # open the file for writing
    bf1.open(output_bufr_file, 'wb')
    # write the encoded BUFR message
    bf1.write_raw_bufr_msg(bufr.encoded_message)
    # close the file
    bf1.close()
Example #13
0
def encoding_example(output_bufr_file):
    #  #[
    """
    wrap the example in a function to circumvent the pylint
    convention of requiring capitals for constants in the global
    scope (since most of these variables are not constants at all))
    """

    bufr = BUFRInterfaceECMWF(verbose=True)

    # fill sections 0, 1, 2 and 3
    num_subsets = 4
    bufr.fill_sections_0123(
        bufr_code_centre=98,  # ECMWF
        bufr_obstype=3,  # sounding
        bufr_subtype=251,  # L1B
        bufr_table_local_version=1,
        bufr_table_master=0,
        bufr_table_master_version=15,
        bufr_code_subcentre=0,  # L2B processing facility
        num_subsets=num_subsets,
        bufr_compression_flag=0)
    # 64=compression/0=no compression

    # determine information from sections 0123 to construct the BUFR table
    # names expected by the ECMWF BUFR library and create symlinks to the
    # default tables if needed
    bufr.setup_tables()

    # define a descriptor list
    template = BufrTemplate(verbose=True)

    template.add_descriptors(
        DD_D_DATE_YYYYMMDD,  # 0
        DD_D_TIME_HHMM)  # 1

    # delay replication for the next 2 descriptors
    # allow at most 2 delayed replications
    template.add_delayed_replic_descriptors(2, DD_PRESSURE, DD_TEMPERATURE)

    # replicate the next 2 descriptors 3 times
    template.add_replicated_descriptors(3, DD_LATITUDE_HIGH_ACCURACY,
                                        DD_LONGITUDE_HIGH_ACCURACY)

    bufr.register_and_expand_descriptors(template)

    # activate this one if the encoding crashes without clear cause:
    # bufr.estimated_num_bytes_for_encoding = 25000

    # retrieve the length of the expanded descriptor list
    exp_descr_list_length = bufr.ktdexl
    print("exp_descr_list_length = ", exp_descr_list_length)

    # fill the values array with some dummy varying data
    num_values = exp_descr_list_length * num_subsets
    values = np.zeros(num_values, dtype=np.float64)  # this is the default

    # note: these two must be identical for now, otherwise the
    # python to fortran interface breaks down. This also ofcourse is the
    # cause of the huge memory use of cvals in case num_values is large.
    num_cvalues = num_values
    cvals = np.zeros((num_cvalues, 80), dtype=np.character)

    for subset in range(num_subsets):
        # note that python starts counting with 0, unlike fortran,
        # so there is no need to take (subset-1)
        i = subset * exp_descr_list_length

        values[i] = 1999  # year
        i = i + 1
        values[i] = 12  # month
        i = i + 1
        values[i] = 31  # day
        i = i + 1
        values[i] = 23  # hour
        i = i + 1
        values[i] = 59 - subset  # minute
        i = i + 1
        values[i] = 2  # delayed replication factor
        # this delayed replication factor determines the actual number
        # of values to be stored for this particular subset
        # even if it is less then the number given in kdata above !
        for repl in range(2):
            i = i + 1
            values[i] = 1013.e2 - 100.e2 * subset + i + repl  # pressure [pa]
            i = i + 1
            values[i] = 273.15 - 10. * subset + i + repl  # temperature [K]
        for repl in range(3):
            i = i + 1
            values[i] = 51.82 + 0.05 * subset + i + repl  # latitude
            i = i + 1
            values[i] = 5.25 + 0.1 * subset + i + repl  # longitude

    # do the encoding to binary format
    bufr.encode_data(values, cvals)

    # get an instance of the RawBUFRFile class
    bf1 = RawBUFRFile()
    # open the file for writing
    bf1.open(output_bufr_file, 'wb')
    # write the encoded BUFR message
    bf1.write_raw_bufr_msg(bufr.encoded_message)
    # close the file
    bf1.close()
def upgrade_bufr_file(input_bufr_file, output_bufr_file):
    #  #[
    """
    an example routine to demonstrate how to read a BUFR message,
    upgrade it's edition number, and write it to an output BUFR file
    """
    # get 2 instances of the RawBUFRFile class
    rbf_in = RawBUFRFile()
    rbf_out = RawBUFRFile()

    # open the file for reading, count nr of BUFR messages in it
    # and store its content in memory, together with
    # an array of pointers to the start and end of each BUFR message
    rbf_in.open(input_bufr_file, 'rb')

    # open the file for writing
    rbf_out.open(output_bufr_file, 'wb')

    # extract the number of BUFR messages from the file
    num_msgs = rbf_in.get_num_bufr_msgs()

    for msg_nr in range(1, num_msgs+1):
        raw_msg, section_sizes, section_start_locations = \
                 rbf_in.get_raw_bufr_msg(msg_nr)
        bufr_obj = BUFRInterfaceECMWF(raw_msg, section_sizes,
                                      section_start_locations,
                                      verbose=True)

        bufr_obj.decode_sections_012()
        bufr_obj.setup_tables()
        bufr_obj.decode_data()

        nsub = bufr_obj.get_num_subsets()
        n_exp_descr = len(bufr_obj.values)/nsub
        bufr_obj.fill_descriptor_list(nr_of_expanded_descriptors=n_exp_descr)

        bufr_obj.ksec0[3-1] = 4 # set bufr edition to 4
        bufr_obj.ktdlst = bufr_obj.get_descriptor_list()

        # extract delayed replication factors
        delayed_repl_data = bufr_obj.derive_delayed_repl_factors()

        # fill the list of replication factors
        bufr_obj.fill_delayed_repl_data(delayed_repl_data)

        # activate this one if the encoding crashes without clear cause:
        # bufr_obj.estimated_num_bytes_for_encoding = 25000

        # encode the data
        bufr_obj.encode_data(bufr_obj.values, bufr_obj.cvals)
        print 'Encode BUFR msg %i' % msg_nr

        rbf_out.write_raw_bufr_msg(bufr_obj.encoded_message)

    # close the file
    rbf_in.close()
    rbf_out.close()
def decoding_example(input_bufr_file, custom_bufr_tables=None):
    #  #[
    """
    wrap the example in a function to circumvent the pylint
    convention of requiring capitals for constants in the global
    scope (since most of these variables are not constants at all))
    """

    # read the binary data using the BUFRFile class
    print('loading testfile: ', input_bufr_file)
    rbf = RawBUFRFile(verbose=False)
    rbf.open(input_bufr_file, 'rb')
    (words, section_sizes, section_start_locations) = \
            rbf.get_next_raw_bufr_msg()
    rbf.close()

    if words is None:
        print('No valid BUFR messages found')
        sys.exit(0)

    print('------------------------------')
    bufr = BUFRInterfaceECMWF(encoded_message=words,
                              section_sizes=section_sizes,
                              section_start_locations=section_start_locations,
                              verbose=True)

    print("calling: decode_sections_012():")
    bufr.decode_sections_012()

    print("Metadata for decoded BUFR message:")
    bufr.print_sections_012_metadata()

    print("calling: setup_tables()")
    if custom_bufr_tables:
        bufr.setup_tables(table_b_to_use=custom_bufr_tables[0],
                          table_c_to_use=custom_bufr_tables[1],
                          table_d_to_use=custom_bufr_tables[2])
    else:
        bufr.setup_tables()

    print("calling: print_sections_012():")
    bufr.print_sections_012()

    # seems not to work correctly now ...
    #bufr.fill_descriptor_list()
    #bufr.print_descriptors()

    print('------------------------------')
    print("calling: bufr.decode_data():")
    bufr.decode_data()

    bufr.decode_sections_0123()
    bufr.fill_descriptor_list_subset(subset=1)

    return bufr
def encode(output_bufr_file, RadarData, WMOID):

    # Get the data for the wind profilers

    WindComponentData = RadarData.getWindComponents()

    GateSpaceWidths = RadarData.getGateSpace()

    if len(GateSpaceWidths) > 1:

        MaxWidth = 0
        for Width in GateSpaceWidths:

            if Width > MaxWidth:
                MaxWidth = Width
    else:

        MaxWidth = GateSpaces[0]

    print('Using Pulse Mode ' + str(MaxWidth))

    for DateTime in WindComponentData:

        print('Processing ' + str(DateTime))

        print(MaxWidth)
        print(WindComponentData[DateTime].keys())

        if MaxWidth in WindComponentData[DateTime].keys():
            print('Processing high mode only. Pulse ' + str(MaxWidth)
                  + 'ns')

            WindComponents = WindComponentData[DateTime][MaxWidth]

            # Create tge buffer for the hour block of data.

            bufr = BUFRInterfaceECMWF(verbose=True)

            # fill sections 0, 1, 2 and 3 in the BUFR table

            num_subsets = 1
            bufr.fill_sections_0123(  # ECMWF
                                      # wind profiler . Also know as Message Type (Table A)
                                      # Message sub-type
                                      # L2B processing facility
                bufr_code_centre=59,
                bufr_obstype=2,
                bufr_subtype=7,
                bufr_table_local_version=1,
                bufr_table_master=0,
                bufr_table_master_version=3,
                bufr_code_subcentre=0,
                num_subsets=num_subsets,
                bufr_compression_flag=0,
                )

            bufr.setup_tables()

        # define a descriptor list

            template = BufrTemplate()

            print('adding {0} descriptors'.format(10))

            template.add_descriptors(
                WMO_BLOCK_NUM,
                WMO_STATION_NUM,
                DD_LATITUDE_COARSE_ACCURACY,
                DD_LONGITUDE_COARSE_ACCURACY,
                STATION_HEIGHT,
                YEAR,
                MONTH,
                MDAY,
                HOUR,
                MIN,
                TIME_SIGNIFICANCE,
                TIME_PERIOD,
                DD_WIND_SPEED,
                DD_WIND_DIR,
                DD_PRESSURE,
                DD_TEMPERATURE,
                RAINFALL_SWE,
                DD_RELATIVE_HUMD,
                HEIGHT_INCREMENT,
                WIND_PROFILER_SUB_MODE_INFO,
                HEIGHT_INCREMENT,
                HEIGHT_INCREMENT,
                HEIGHT_INCREMENT,
                )

        # delay replication for the next 10 descriptors

            template.add_replicated_descriptors(
                len(WindComponents),
                WIND_PROFILER_MODE_INFO,
                WIND_PROFILER_QC_RESULTS,
                TOTAL_NUMBER,
                WIND_U_COMPONENT,
                WIND_V_COMPONENT,
                STD_DEV_HORIZONTAL_WIND_SPEED,
                TOTAL_NUMBER,
                RADAR_BACK_SCATTER,
                WIND_W_COMPONENT,
                STD_DEV_VERTICAL_SPEED,
                )

            bufr.register_and_expand_descriptors(template)

        # activate this one if the encoding crashes without clear cause:
        # bufr.estimated_num_bytes_for_encoding = 25000

        # retrieve the length of the expanded descriptor list

            exp_descr_list_length = bufr.ktdexl

        # fill the values array with some dummy varying data

            num_values = exp_descr_list_length

            values = np.zeros(num_values, dtype=np.float64)  # this is the default

        # note: these two must be identical for now, otherwise the
        # python to fortran interface breaks down. This also ofcourse is the
        # cause of the huge memory use of cvals in case num_values is large.

            num_cvalues = num_values
            cvals = np.zeros((num_cvalues, 80), dtype=np.character)

        # note that python starts counting with 0, unlike fortran,
            # so there is no need to take (subset-1)
        #     i = subset*exp_descr_list_length

            values[0] = WMOID[0:2]  # WMO Block Number
            values[1] = WMOID[2:5]  # WMO Station #

            values[2] = RadarData.getLatitude()  # Latitude
            values[3] = RadarData.getLongitude()
            values[4] = RadarData.getElev()  # Elevation of Station (meters)
            values[5] = DateTime.timetuple().tm_year  # year
            values[6] = DateTime.timetuple().tm_mon  # month
            values[7] = DateTime.timetuple().tm_mday  # day
            values[8] = DateTime.timetuple().tm_hour  # hour
            values[9] = 0  # minute
            values[10] = 2  # Time Significance
            values[11] = -60  # Time Period
            values[12] = 1  # Wind Speed
            values[13] = 1  # Wind Dir
            values[14] = 1  # Pressure
            values[15] = 1  # Temperature
            values[16] = .2  # Rainfall
            values[17] = 1  # Realative Humidty
            GateSpace = int(MaxWidth) * 1.e-9 * 3.e+8 / 2.
            values[18] = GateSpace  # Height Increment
            values[19] = 0  # Wind Profiler Sub Mode
            values[20] = GateSpace  # Height Increment
            values[21] = GateSpace  # Height Increment
            values[22] = GateSpace  # Height Increment

            print('Number of gates ' + str(len(WindComponents)))

            for i in range(0, len(WindComponents)):

                for t in range(0, 10):

                    # Calulcate the correct index in the BUFR

                    rec = i * 10 + 23 + t

                    if WindComponents[i][0] <= 1000 \
                        and WindComponents[i][1] <= 1000:
                        WindRadians = math.radians(WindComponents[i][1])
                        VelocityU = -WindComponents[i][0] \
                            * math.sin(WindRadians)
                        VelocityV = -WindComponents[i][0] \
                            * math.cos(WindRadians)
                        TotalNumber = WindComponents[i][2]
                        SnrDB = WindComponents[i][3]
                    else:

                        VelocityU = VelocityV = TotalNumbe = SnrDB = -99
                        values[rec] = float('NaN')  # level mode
                        continue

                    if rec % 10 == 3:
                        values[rec] = 1  # level mode

                    if rec % 10 == 4:
                        values[rec] = 0  # Quality Control test

                    if rec % 10 == 5:
                        values[rec] = TotalNumber  # Total Number (with respect to accumlation or average)

                    if rec % 10 == 6:
                        values[rec] = VelocityU  # U-Component

                    if rec % 10 == 7:
                        values[rec] = VelocityV  # V-Component

                    if rec % 10 == 8:
                        values[rec] = 0.000  # Std Deviation of horizontal wind speed

                    if rec % 10 == 9:
                        values[rec] = TotalNumber  # Total Number  (with respect to accumlation or average)

                    if rec % 10 == 0:
                        values[rec] = SnrDB / 100  # Radar Back Scatter (Peak Power)  x100

                    if rec % 10 == 1:
                        values[rec] = 0.000  # W-Component  x100

                    if rec % 10 == 2:
                        values[rec] = 0.000  # Std Deviation of vertical wind

            # do the encoding to binary format

            bufr.encode_data(values, cvals)

            HeaderString = '''

287

IUAK01 PANC %02d%02d00

''' \
                % (DateTime.timetuple().tm_mday,
                   DateTime.timetuple().tm_hour)

            if not os.path.exists(OutputPath):
                os.makedirs(OutputPath)

            OutputFile = \
                '%s/IUPTO2_%s_%02d%02d00_216234297.bufr.%04d%02d%02d%02d' \
                % (
                OutputPath,
                RadarData.getSiteID().upper(),
                DateTime.timetuple().tm_mon,
                DateTime.timetuple().tm_mday,
                DateTime.timetuple().tm_year,
                DateTime.timetuple().tm_mon,
                DateTime.timetuple().tm_mday,
                DateTime.timetuple().tm_hour,
                )

             # Remove file if exsists

            if os.path.exists(OutputFile):
                os.remove(OutputFile)

            bf1 = open(OutputFile, 'ab')
            bf1.write(HeaderString)
            bf1.close()

            # get an instance of the RawBUFRFile class

            bf1 = RawBUFRFile()

            # open the file for writing

            bf1.open(OutputFile, 'ab')

            # write the encoded BUFR message

            bf1.write_raw_bufr_msg(bufr.encoded_message)

            # close the file

            bf1.close()

            #  #]

            print('succesfully written BUFR encoded data to file: ',
                  OutputFile)
Example #17
0
def encode(output_bufr_file, RadarData, WMOID):

    # Get the data for the wind profilers

    WindComponentData = RadarData.getWindComponents()

    GateSpaceWidths = RadarData.getGateSpace()

    if len(GateSpaceWidths) > 1:

        MaxWidth = 0
        for Width in GateSpaceWidths:

            if Width > MaxWidth:
                MaxWidth = Width
    else:

        MaxWidth = GateSpaces[0]

    print('Using Pulse Mode ' + str(MaxWidth))

    for DateTime in WindComponentData:

        print('Processing ' + str(DateTime))

        print(MaxWidth)
        print(WindComponentData[DateTime].keys())

        if MaxWidth in WindComponentData[DateTime].keys():
            print('Processing high mode only. Pulse ' + str(MaxWidth) + 'ns')

            WindComponents = WindComponentData[DateTime][MaxWidth]

            # Create tge buffer for the hour block of data.

            bufr = BUFRInterfaceECMWF(verbose=True)

            # fill sections 0, 1, 2 and 3 in the BUFR table

            num_subsets = 1
            bufr.fill_sections_0123(  # ECMWF
                # wind profiler . Also know as Message Type (Table A)
                # Message sub-type
                # L2B processing facility
                bufr_code_centre=59,
                bufr_obstype=2,
                bufr_subtype=7,
                bufr_table_local_version=1,
                bufr_table_master=0,
                bufr_table_master_version=3,
                bufr_code_subcentre=0,
                num_subsets=num_subsets,
                bufr_compression_flag=0,
            )

            bufr.setup_tables()

            # define a descriptor list

            template = BufrTemplate()

            print('adding {0} descriptors'.format(10))

            template.add_descriptors(
                WMO_BLOCK_NUM,
                WMO_STATION_NUM,
                DD_LATITUDE_COARSE_ACCURACY,
                DD_LONGITUDE_COARSE_ACCURACY,
                STATION_HEIGHT,
                YEAR,
                MONTH,
                MDAY,
                HOUR,
                MIN,
                TIME_SIGNIFICANCE,
                TIME_PERIOD,
                DD_WIND_SPEED,
                DD_WIND_DIR,
                DD_PRESSURE,
                DD_TEMPERATURE,
                RAINFALL_SWE,
                DD_RELATIVE_HUMD,
                HEIGHT_INCREMENT,
                WIND_PROFILER_SUB_MODE_INFO,
                HEIGHT_INCREMENT,
                HEIGHT_INCREMENT,
                HEIGHT_INCREMENT,
            )

            # delay replication for the next 10 descriptors

            template.add_replicated_descriptors(
                len(WindComponents),
                WIND_PROFILER_MODE_INFO,
                WIND_PROFILER_QC_RESULTS,
                TOTAL_NUMBER,
                WIND_U_COMPONENT,
                WIND_V_COMPONENT,
                STD_DEV_HORIZONTAL_WIND_SPEED,
                TOTAL_NUMBER,
                RADAR_BACK_SCATTER,
                WIND_W_COMPONENT,
                STD_DEV_VERTICAL_SPEED,
            )

            bufr.register_and_expand_descriptors(template)

            # activate this one if the encoding crashes without clear cause:
            # bufr.estimated_num_bytes_for_encoding = 25000

            # retrieve the length of the expanded descriptor list

            exp_descr_list_length = bufr.ktdexl

            # fill the values array with some dummy varying data

            num_values = exp_descr_list_length

            values = np.zeros(num_values,
                              dtype=np.float64)  # this is the default

            # note: these two must be identical for now, otherwise the
            # python to fortran interface breaks down. This also ofcourse is the
            # cause of the huge memory use of cvals in case num_values is large.

            num_cvalues = num_values
            cvals = np.zeros((num_cvalues, 80), dtype=np.character)

            # note that python starts counting with 0, unlike fortran,
            # so there is no need to take (subset-1)
            #     i = subset*exp_descr_list_length

            values[0] = WMOID[0:2]  # WMO Block Number
            values[1] = WMOID[2:5]  # WMO Station #

            values[2] = RadarData.getLatitude()  # Latitude
            values[3] = RadarData.getLongitude()
            values[4] = RadarData.getElev()  # Elevation of Station (meters)
            values[5] = DateTime.timetuple().tm_year  # year
            values[6] = DateTime.timetuple().tm_mon  # month
            values[7] = DateTime.timetuple().tm_mday  # day
            values[8] = DateTime.timetuple().tm_hour  # hour
            values[9] = 0  # minute
            values[10] = 2  # Time Significance
            values[11] = -60  # Time Period
            values[12] = 1  # Wind Speed
            values[13] = 1  # Wind Dir
            values[14] = 1  # Pressure
            values[15] = 1  # Temperature
            values[16] = .2  # Rainfall
            values[17] = 1  # Realative Humidty
            GateSpace = int(MaxWidth) * 1.e-9 * 3.e+8 / 2.
            values[18] = GateSpace  # Height Increment
            values[19] = 0  # Wind Profiler Sub Mode
            values[20] = GateSpace  # Height Increment
            values[21] = GateSpace  # Height Increment
            values[22] = GateSpace  # Height Increment

            print('Number of gates ' + str(len(WindComponents)))

            for i in range(0, len(WindComponents)):

                for t in range(0, 10):

                    # Calulcate the correct index in the BUFR

                    rec = i * 10 + 23 + t

                    if WindComponents[i][0] <= 1000 \
                        and WindComponents[i][1] <= 1000:
                        WindRadians = math.radians(WindComponents[i][1])
                        VelocityU = -WindComponents[i][0] \
                            * math.sin(WindRadians)
                        VelocityV = -WindComponents[i][0] \
                            * math.cos(WindRadians)
                        TotalNumber = WindComponents[i][2]
                        SnrDB = WindComponents[i][3]
                    else:

                        VelocityU = VelocityV = TotalNumbe = SnrDB = -99
                        values[rec] = float('NaN')  # level mode
                        continue

                    if rec % 10 == 3:
                        values[rec] = 1  # level mode

                    if rec % 10 == 4:
                        values[rec] = 0  # Quality Control test

                    if rec % 10 == 5:
                        values[
                            rec] = TotalNumber  # Total Number (with respect to accumlation or average)

                    if rec % 10 == 6:
                        values[rec] = VelocityU  # U-Component

                    if rec % 10 == 7:
                        values[rec] = VelocityV  # V-Component

                    if rec % 10 == 8:
                        values[
                            rec] = 0.000  # Std Deviation of horizontal wind speed

                    if rec % 10 == 9:
                        values[
                            rec] = TotalNumber  # Total Number  (with respect to accumlation or average)

                    if rec % 10 == 0:
                        values[
                            rec] = SnrDB / 100  # Radar Back Scatter (Peak Power)  x100

                    if rec % 10 == 1:
                        values[rec] = 0.000  # W-Component  x100

                    if rec % 10 == 2:
                        values[rec] = 0.000  # Std Deviation of vertical wind

            # do the encoding to binary format

            bufr.encode_data(values, cvals)

            HeaderString = '''

287

IUAK01 PANC %02d%02d00

''' \
                % (DateTime.timetuple().tm_mday,
                   DateTime.timetuple().tm_hour)

            if not os.path.exists(OutputPath):
                os.makedirs(OutputPath)

            OutputFile = \
                '%s/IUPTO2_%s_%02d%02d00_216234297.bufr.%04d%02d%02d%02d' \
                % (
                OutputPath,
                RadarData.getSiteID().upper(),
                DateTime.timetuple().tm_mon,
                DateTime.timetuple().tm_mday,
                DateTime.timetuple().tm_year,
                DateTime.timetuple().tm_mon,
                DateTime.timetuple().tm_mday,
                DateTime.timetuple().tm_hour,
                )

            # Remove file if exsists

            if os.path.exists(OutputFile):
                os.remove(OutputFile)

            bf1 = open(OutputFile, 'ab')
            bf1.write(HeaderString)
            bf1.close()

            # get an instance of the RawBUFRFile class

            bf1 = RawBUFRFile()

            # open the file for writing

            bf1.open(OutputFile, 'ab')

            # write the encoded BUFR message

            bf1.write_raw_bufr_msg(bufr.encoded_message)

            # close the file

            bf1.close()

            #  #]

            print('succesfully written BUFR encoded data to file: ',
                  OutputFile)