Пример #1
0
    def test_12(self):
        """
        Defining Grids

        Grids can be defined from
        * a record in a FSTD file or
        * directly by providing parameters.
        These grids parameters can be used to geolocate the data points and
        for interpolation operations (see below).

        See also:
        """
        import os
        import rpnpy.librmn.all as rmn

        ATM_MODEL_DFILES = os.getenv('ATM_MODEL_DFILES')
        fileName = os.path.join(ATM_MODEL_DFILES.strip(),
                                'bcmk/2009042700_012')

        # Define a grid from parameters, a cylindrical equidistant (LatLon) grid with 0.5 deg spacing.
        paramsL = {
            'grtyp': 'L',  # Cylindrical equidistant projection
            'ni': 90,  # Grid dimension: 90 by 45 points
            'nj': 45,
            'lat0':
            0.,  # Grid lower-left (south-west) corner (point 1,1) is located at 0N, 180E
            'lon0': 180.,
            'dlat':
            0.5,  # The grid has a resolution (grid spacing) of 0.5 deg. on both axes
            'dlon': 0.5
        }
        try:
            gridL = rmn.encodeGrid(paramsL)
        except:
            raise rmn.FSTDError(
                "Problem defining a grid with provided parameters: %s " %
                str(paramsL))

        # Get a grid definition from a record in a FSTD file
        try:
            fileId = rmn.fstopenall(fileName, rmn.FST_RO)
            prKey = rmn.fstinf(fileId, nomvar='PR')['key']
            prMeta = rmn.fstprm(
                prKey)  # Get the record metadata along with partial grid info
            prMeta['iunit'] = fileId
            prGrid0 = rmn.ezqkdef(
                prMeta)  # use ezscint to retreive full grid info
            prGrid = rmn.decodeGrid(
                prGrid0)  # Decode all the grid parameters values
            rmn.fstcloseall(fileId)
        except:
            raise rmn.FSTDError(
                "Problem getting PR record grid meta from file: %s" % fileName)
Пример #2
0
def defineZPSGrid(txtRec, verbose=False):
    """
    Define a North polar sterographic grid, ezscint encoded

    See: https://wiki.cmc.ec.gc.ca/wiki/Python-RPN/2.1/rpnpy/librmn/grids#defGrid_PS
    """
    if txtRec['Projection'] != 'PolarStereographic':
        raise ValueError('Unknown projection: {}'.format(txtRec['Projection']))
    if int(float(txtRec['TrueLatitude'])) != 60:
        raise ValueError('Cannot encode TrueLatitude of: {}'.format(txtRec['TrueLatitude']))

    if verbose:
        sys.stdout.write('Defining a North PS grid: {}\n'.format(filename))
    ni, nj = txtRec['Data'].shape
 
    ## First define a base projection as a grid centered on the N-pole
    pi, pj = float(ni)/2., float(nj)/2.
    gp = {
        'grtyp' : 'N',
        'north' : True,
        'ni'    : ni,
        'nj'    : nj,
        'pi'    : pi,
        'pj'    : pj,
        'd60'   : float(txtRec['Scale']) * 1000.,
        'dgrw'  : float(txtRec['ReferenceLongitude']),
     }
    g = rmn.encodeGrid(gp)

    ## Second correct the base grid position
    lon0 = float(txtRec['LonCentre'])
    lat0 = float(txtRec['LatCentre'])
    xy = rmn.gdxyfll(g['id'], lat0, lon0)
    gp['pi'] = float(ni) - xy['x'][0]
    gp['pj'] = float(nj) - xy['y'][0]
    g = rmn.encodeGrid(gp)
    return g
Пример #3
0
    def test_12(self):
        """
        Defining Grids

        Grids can be defined from
        * a record in a FSTD file or
        * directly by providing parameters.
        These grids parameters can be used to geolocate the data points and
        for interpolation operations (see below).

        See also:
        """
        import os
        import rpnpy.librmn.all as rmn
 
        ATM_MODEL_DFILES = os.getenv('ATM_MODEL_DFILES')
        fileName = os.path.join(ATM_MODEL_DFILES.strip(), 'bcmk/2009042700_012')
 
        # Define a grid from parameters, a cylindrical equidistant (LatLon) grid with 0.5 deg spacing.
        paramsL = {
            'grtyp' : 'L', # Cylindrical equidistant projection
            'ni'   :  90,  # Grid dimension: 90 by 45 points
            'nj'   :  45,
            'lat0' :   0., # Grid lower-left (south-west) corner (point 1,1) is located at 0N, 180E
            'lon0' : 180.,
            'dlat' :   0.5,# The grid has a resolution (grid spacing) of 0.5 deg. on both axes
            'dlon' :   0.5
            }
        try:
            gridL = rmn.encodeGrid(paramsL)
        except:
            raise rmn.FSTDError("Problem defining a grid with provided parameters: %s " % str(paramsL))
 
        # Get a grid definition from a record in a FSTD file
        try:
            fileId = rmn.fstopenall(fileName, rmn.FST_RO)
            prKey  = rmn.fstinf(fileId, nomvar='PR')['key']
            prMeta = rmn.fstprm(prKey)              # Get the record metadata along with partial grid info
            prMeta['iunit'] = fileId
            prGrid0 = rmn.ezqkdef(prMeta)           # use ezscint to retreive full grid info
            prGrid  = rmn.decodeGrid(prGrid0)       # Decode all the grid parameters values
            rmn.fstcloseall(fileId)
        except:
            raise rmn.FSTDError("Problem getting PR record grid meta from file: %s" % fileName)
Пример #4
0
def build_fst(params, y_int, m_int):
    '''
    (dict) -> (int, dict)
    builds the file as per the parameters defined in the params dict
    
    returns the file_id
    '''

    # makes an empty .fst file
    day = time.gmtime()
    temp = ''
    for x in day:
        temp += str(x)
    #new_nc = '/home/ords/aq/alh002/pyscripts/workdir/pv_files/TEST5.fst'
    new_nc = '/home/ords/aq/alh002/pyscripts/workdir/pv_files/SHIFTED_POTVOR_file_{0}_{1}.fst'.format(
        y_int + 2008, m_int + 1)
    tmp = open(new_nc, 'w+')
    tmp.close()
    output_file = new_nc

    try:
        file_id = rmn.fnom(output_file)
        open_fst = rmn.fstouv(file_id, rmn.FST_RW)
        print(file_id, open_fst)

        MACC_grid = rmn.encodeGrid(params)
        print("Grids created.")
        print 'Grid Shape:' + str(MACC_grid['shape'])

        rmn.writeGrid(file_id, MACC_grid)
        toc_record = vgd.vgd_new_pres(const_pressure,
                                      ip1=MACC_grid['ig1'],
                                      ip2=MACC_grid['ig2'])
        vgd.vgd_write(toc_record, file_id)

        return file_id, MACC_grid

    except:
        rmn.fstfrm(file_id)
        rmn.fclos(file_id)
        raise
Пример #5
0
def plotFSTs(season=season, spcs=spcs, spcsFiles=spcsFiles, outputName = outputName, saveDir=saveDir):
    # print minimum outputs
    rmn.fstopt(rmn.FSTOP_MSGLVL,rmn.FSTOPI_MSG_CATAST)

    mInds = []
    for m in season:
        mInds += [monthList.index(m)]

    if os.path.exists(saveDir) == False:
        nu.makeDir(saveDir)

    for spcInd, nomvar in enumerate(spcs):
        try:
            filename = os.path.join(saveDir, 'output_file_{0}_{1}.fst'.format(outputName, nomvar))
            print('Creating and saving to {}'.format(filename))
            tmp = open(filename, 'w+'); tmp.close()

            output_file = filename
            file_id = rmn.fnom(output_file)
            open_fst = rmn.fstouv(file_id, rmn.FST_RW)
            open_file = spcsFiles[spcInd]
            print "Parameter: " + nomvar
            seaSpcData = get_var(pyg.open(open_file), nomvar, mInds)
            nc_lnsp = pyg.open(lnsp_file)
            pressures = get_pressures(nc_lnsp, mInds)

            timelen, levlen, latlen, lonlen = seaSpcData.shape
            #NOTE: uncomment the following three lines to prep data for basemap use
            #lonShiftSSData = shift_lon(seaSpcData)
            #vertInterpSSData = vert_interp(pressures, lonShiftSSData)
            #meanSSData = np.mean(vertInterpSSData, axis=0)
            #NOTE: uncommment the following four liness to use for fst plotting
            vertInterpSSData = vert_interp(pressures, seaSpcData)
            meanSSData = np.mean(vertInterpSSData, axis=0)  # temp
            for lvl, ray in enumerate(meanSSData):
                meanSSData[lvl] = np.flipud(ray)
            scaleFac = scaleSpcs[allSpcs.index(nomvar)]
            scaledSSData = meanSSData*scaleFac

            #define grid for this file - note that the MACC grid in the file is
            #defined for lons -180 to 180, but the python defGrid_L can't deal
            #with that and defines the grid from 0 to 360 so will have to reorder
            #the MACC fields a bit, or they end up 180 deg out of phase
            # Also necessary to add one more longitude to wrap around
            dlatlon = 360./lonlen   # this is equal to the resolution of the grid

            params0 = {
                    'grtyp' : 'Z',
                    'grref' : 'L',
                    'nj'    : latlen,
                    'ni'    : lonlen,
                    'lat0'  : -90.,
                    'lon0'  : 0.,
                    'dlat'  : dlatlon,
                    'dlon'  : dlatlon
                    }

            MACC_grid= rmn.encodeGrid(params0)
            print("Grids created.")
            print 'Grid Shape:' + str(MACC_grid['shape'])

            # copies the default record
            new_record = rmn.FST_RDE_META_DEFAULT.copy()
            tic_record = rmn.FST_RDE_META_DEFAULT.copy()
            tac_record = rmn.FST_RDE_META_DEFAULT.copy()

            try:
                rmn.writeGrid(file_id, MACC_grid)

                tac = rmn.fstinl(file_id, nomvar='>>')[0]
                tic = rmn.fstinl(file_id, nomvar='^^')[0]

                tic_record.update(rmn.fstprm(tic))
                tac_record.update(rmn.fstprm(tac))

                tic_record.update({'datyp' : rmn.FST_DATYP_LIST['float']})
                tac_record.update({'datyp' : rmn.FST_DATYP_LIST['float']})

                rmn.fsteff(tic)
                rmn.fsteff(tac)

                tic_record.update({'d': MACC_grid['ay']})
                tac_record.update({'d': MACC_grid['ax']})
                toc_record = vgd.vgd_new_pres(const_pressure, ip1=MACC_grid['ig1'], ip2=MACC_grid['ig2'])

                rmn.fstecr(file_id, tic_record)  # write the dictionary record to the file as a new record
                rmn.fstecr(file_id, tac_record)  # write the dictionary record to the file as a new record
                vgd.vgd_write(toc_record, file_id)

            except:
                raise

            for rp1 in xrange(len(const_pressure)):  # writes a record for every level (as a different ip1)
                try:
                    # converts rp1 into a ip1 with pressure kind
                    ip1 = rmn.convertIp(rmn.CONVIP_ENCODE, const_pressure[rp1], rmn.KIND_PRESSURE)
                    new_record.update(MACC_grid)
                    new_record.update({  # Update with specific meta
                        'nomvar': nomvar,
                        'typvar': 'C',
                        'etiket': 'MACCRean',
                        'ni'    : MACC_grid['ni'],
                        'nj'    : MACC_grid['nj'],
                        'ig1'   : tic_record['ip1'],
                        'ig2'   : tic_record['ip2'],
                        'ig3'   : tic_record['ip3'],
                        'ig4'   : tic_record['ig4'],
                        'dateo' : rmn.newdate(rmn.NEWDATE_PRINT2STAMP, 20120101, 0000000),
                        'deet'  : 0,  # Timestep in sec
                        'ip1'   : ip1
                        })

                    #tmp_nparray = np.asfortranarray(monthly_mean[rp1])
                    tmp = scaledSSData[rp1]
                    tmp = np.transpose(tmp)
                    # data array is structured as tmp = monthly_mean[level] where monthly_mean is [level, lat, lon]
                    new_record.update({'d': tmp.astype(np.float32)}) # Updates with data array in the form (lon x lat)

                    print "Defined a new record with dimensions ({0}, {1})".format(new_record['ni'], new_record['nj'])
                    rmn.fstecr(file_id, new_record)  # write the dictionary record to the file as a new record

                except:
                    #rmn.closeall(file_id)
                    rmn.fstfrm(file_id)
                    rmn.fclos(file_id)
                    raise
            rmn.fstfrm(file_id)
            rmn.fclos(file_id)
            print('{} complete~'.format(filename))
        except:
            rmn.fstfrm(file_id)
            rmn.fclos(file_id)
            raise
    print('Finished plotting all FSTs. ')
Пример #6
0
    def test_41(self):
        """
        Horizontal Interpolation
        
        See also:
        """
        import os, sys, datetime
        import rpnpy.librmn.all as rmn
        fdate = datetime.date.today().strftime('%Y%m%d') + '00_048'
        CMCGRIDF = os.getenv('CMCGRIDF').strip()
        fileNameIn = os.path.join(CMCGRIDF, 'prog', 'regeta', fdate)
        fileNameOut = 'p0fstfile.fst'

        # Restrict to the minimum the number of messages printed by librmn
        rmn.fstopt(rmn.FSTOP_MSGLVL, rmn.FSTOPI_MSG_CATAST)

        try:
            # Create Destination grid
            # Note: Destination grid can also be read from a file
            gp = {
                'grtyp': 'Z',
                'grref': 'E',
                'ni': 90,
                'nj': 45,
                'lat0': 35.,
                'lon0': 250.,
                'dlat': 0.5,
                'dlon': 0.5,
                'xlat1': 0.,
                'xlon1': 180.,
                'xlat2': 1.,
                'xlon2': 270.
            }
            gOut = rmn.encodeGrid(gp)
            print("CB41: Defined a %s/%s grid of shape=%d, %d" %
                  (gOut['grtyp'], gOut['grref'], gOut['ni'], gOut['nj']))
        except:
            sys.stderr.write("Problem creating grid\n")
            sys.exit(1)

        # Open Files
        try:
            fileIdIn = rmn.fstopenall(fileNameIn)
            fileIdOut = rmn.fstopenall(fileNameOut, rmn.FST_RW)
        except:
            sys.stderr.write("Problem opening the files: %s, %s\n" %
                             (fileNameIn, fileNameOut))
            sys.exit(1)

        try:
            # Find and read record to interpolate with its grid
            r = rmn.fstlir(fileIdIn, nomvar='P0')
            gIn = rmn.readGrid(fileIdIn, r)
            print("CB41: Read P0")

            # Set interpolation options and interpolate
            rmn.ezsetopt(rmn.EZ_OPT_INTERP_DEGREE, rmn.EZ_INTERP_LINEAR)
            d = rmn.ezsint(gOut, gIn, r)
            print("CB41: Interpolate P0")

            # Create new record to write with interpolated data and
            r2 = r.copy()  # Preserve meta from original record
            r2.update(gOut)  # update grid information
            r2.update({  # attach data and update specific meta
                'etiket': 'my_etk',
                'd': d
            })

            # Write record data + meta + grid to file
            rmn.fstecr(fileIdOut, r2)
            rmn.writeGrid(fileIdOut, gOut)
            print("CB41: Wrote interpolated P0 and its grid")
        except:
            pass
        finally:
            # Properly close files even if an error occured above
            # This is important when editing to avoid corrupted files
            rmn.fstcloseall(fileIdIn)
            rmn.fstcloseall(fileIdOut)
            os.unlink(fileNameOut)  # Remove test file
Пример #7
0
    def test_24(self):
        """
        Edit: New file from scratch

        This example shows how to
        * Create a record meta and data from scratch
        * Create grid descriptors for the data
        * Create vgrid descriptor for the data
        * write the recod data + meta
        * write the grid descriptors
        * write the vgrid descriptor

        See also:
        rpnpy.librmn.fstd98.fstopt
        rpnpy.librmn.fstd98.fstopenall
        rpnpy.librmn.fstd98.fstcloseall
        rpnpy.librmn.fstd98.fsrecr
        rpnpy.librmn.fstd98.dtype_fst2numpy
        rpnpy.librmn.grids.encodeGrid
        rpnpy.librmn.grids.defGrid_ZE
        rpnpy.librmn.grids.writeGrid
        rpnpy.librmn.base.newdate
        rpnpy.vgd.base.vgd_new
        rpnpy.vgd.base.vgd_new_pres
        rpnpy.vgd.base.vgd_new_get
        rpnpy.vgd.base.vgd_write
        rpnpy.librmn.const
        rpnpy.vgd.const
        """
        import os, sys
        import numpy as np
        import rpnpy.librmn.all as rmn
        import rpnpy.vgd.all as vgd

        # Restrict to the minimum the number of messages printed by librmn
        rmn.fstopt(rmn.FSTOP_MSGLVL, rmn.FSTOPI_MSG_CATAST)

        # Create Record grid
        gp = {
            'grtyp': 'Z',
            'grref': 'E',
            'ni': 90,
            'nj': 45,
            'lat0': 35.,
            'lon0': 250.,
            'dlat': 0.5,
            'dlon': 0.5,
            'xlat1': 0.,
            'xlon1': 180.,
            'xlat2': 1.,
            'xlon2': 270.
        }
        g = rmn.encodeGrid(gp)
        print("CB24: Defined a %s/%s grid of shape=%d, %d" %
              (gp['grtyp'], gp['grref'], gp['ni'], gp['nj']))

        # Create Record vgrid
        lvls = (500., 850., 1000.)
        v = vgd.vgd_new_pres(lvls)
        ip1list = vgd.vgd_get(v, 'VIPT')
        print("CB24: Defined a Pres vgrid with lvls=%s" % str(lvls))

        # Create Record data + meta
        datyp = rmn.FST_DATYP_LIST['float_IEEE_compressed']
        npdtype = rmn.dtype_fst2numpy(datyp)
        rshape = (g['ni'], g['nj'], len(ip1list))
        r = rmn.FST_RDE_META_DEFAULT.copy()  # Copy default record meta
        r.update(g)  # Update with grid info
        r.update({  # Update with specific meta and data array
            'nomvar':
            'MASK',
            'dateo':
            rmn.newdate(rmn.NEWDATE_PRINT2STAMP, 20160302, 1800000),
            'nk':
            len(ip1list),
            'ip1':
            0,  # level, will be set later, level by level
            'ip2':
            6,  # Forecast of 6h
            'deet':
            3600,  # Timestep in sec
            'npas':
            6,  # Step number
            'etiket':
            'my_etk',
            'nbits':
            32,  # Keep full 32 bits precision for that field
            'datyp':
            datyp,  # datyp (above) float_IEEE_compressed
            'd':
            np.empty(rshape, dtype=npdtype, order='FORTRAN')
        })
        print("CB24: Defined a new record of shape=%d, %d" %
              (r['ni'], r['nj']))

        # Compute record values
        r['d'][:, :, :] = 0.
        r['d'][10:-11, 5:-6, :] = 1.

        # Open Files
        fileNameOut = 'newfromscratch.fst'
        try:
            fileIdOut = rmn.fstopenall(fileNameOut, rmn.FST_RW)
        except:
            sys.stderr.write("Problem opening the file: %s, %s\n" %
                             fileNameOut)
            sys.exit(1)

        # Write record data + meta + grid + vgrid to file
        try:
            r2d = r.copy()
            r2d['nk'] = 1
            for k in range(len(ip1list)):
                r2d['ip1'] = ip1list[k]
                r2d['d'] = np.asfortranarray(r['d'][:, :, k])
                rmn.fstecr(fileIdOut, r2d['d'], r2d)
                print("CB24: wrote %s at ip1=%d" % (r2d['nomvar'], r2d['ip1']))
            rmn.writeGrid(fileIdOut, g)
            print("CB24: wrote the grid descriptors")
            vgd.vgd_write(v, fileIdOut)
            print("CB24: wrote the vgrid descriptor")
        except:
            raise
        finally:
            # Properly close files even if an error occured above
            # This is important when editing to avoid corrupted files
            rmn.fstcloseall(fileIdOut)
            os.unlink(fileNameOut)  # Remove test file
Пример #8
0
    def test_24(self):
        """
        Edit: New file from scratch

        This example shows how to
        * Create a record meta and data from scratch
        * Create grid descriptors for the data
        * Create vgrid descriptor for the data
        * write the recod data + meta
        * write the grid descriptors
        * write the vgrid descriptor

        See also:
        rpnpy.librmn.fstd98.fstopt
        rpnpy.librmn.fstd98.fstopenall
        rpnpy.librmn.fstd98.fstcloseall
        rpnpy.librmn.fstd98.fsrecr
        rpnpy.librmn.fstd98.dtype_fst2numpy
        rpnpy.librmn.grids.encodeGrid
        rpnpy.librmn.grids.defGrid_ZE
        rpnpy.librmn.grids.writeGrid
        rpnpy.librmn.base.newdate
        rpnpy.vgd.base.vgd_new
        rpnpy.vgd.base.vgd_new_pres
        rpnpy.vgd.base.vgd_new_get
        rpnpy.vgd.base.vgd_write
        rpnpy.librmn.const
        rpnpy.vgd.const
        """
        import os, sys
        import numpy as np
        import rpnpy.librmn.all as rmn
        import rpnpy.vgd.all as vgd
        
        # Restrict to the minimum the number of messages printed by librmn
        rmn.fstopt(rmn.FSTOP_MSGLVL,rmn.FSTOPI_MSG_CATAST)

        # Create Record grid
        gp = {
            'grtyp' : 'Z',
            'grref' : 'E',
            'ni'    : 90,
            'nj'    : 45,
            'lat0'  : 35.,
            'lon0'  : 250.,
            'dlat'  : 0.5,
            'dlon'  : 0.5,
            'xlat1' : 0.,
            'xlon1' : 180.,
            'xlat2' : 1.,
            'xlon2' : 270.
        }
        g = rmn.encodeGrid(gp)
        print("CB24: Defined a %s/%s grid of shape=%d, %d" %
              (gp['grtyp'], gp['grref'], gp['ni'], gp['nj']))
            
        # Create Record vgrid
        lvls = (500.,850.,1000.)
        v = vgd.vgd_new_pres(lvls)
        ip1list = vgd.vgd_get(v, 'VIPT')
        print("CB24: Defined a Pres vgrid with lvls=%s" % str(lvls))
        
        # Create Record data + meta
        datyp   = rmn.FST_DATYP_LIST['float_IEEE_compressed']
        npdtype = rmn.dtype_fst2numpy(datyp)
        rshape  = (g['ni'], g['nj'], len(ip1list))
        r = rmn.FST_RDE_META_DEFAULT.copy() # Copy default record meta
        r.update(g)                         # Update with grid info
        r.update({                          # Update with specific meta and data array
            'nomvar': 'MASK',
            'dateo' : rmn.newdate(rmn.NEWDATE_PRINT2STAMP, 20160302, 1800000),
            'nk'    : len(ip1list),
            'ip1'   : 0,     # level, will be set later, level by level
            'ip2'   : 6,     # Forecast of 6h
            'deet'  : 3600,  # Timestep in sec
            'npas'  : 6,     # Step number
            'etiket': 'my_etk',
            'nbits' : 32,    # Keep full 32 bits precision for that field
            'datyp' : datyp, # datyp (above) float_IEEE_compressed
            'd'     : np.empty(rshape, dtype=npdtype, order='FORTRAN')
            })
        print("CB24: Defined a new record of shape=%d, %d" % (r['ni'], r['nj']))

        
        # Compute record values
        r['d'][:,:,:] = 0.
        r['d'][10:-11,5:-6,:] = 1.
        
        # Open Files
        fileNameOut = 'newfromscratch.fst'
        try:
            fileIdOut = rmn.fstopenall(fileNameOut, rmn.FST_RW)
        except:
            sys.stderr.write("Problem opening the file: %s, %s\n" % fileNameOut)
            sys.exit(1)

        # Write record data + meta + grid + vgrid to file
        try:
            r2d = r.copy()
            r2d['nk']  = 1
            for k in range(len(ip1list)):
                r2d['ip1'] = ip1list[k]
                r2d['d'] = np.asfortranarray(r['d'][:,:,k])
                rmn.fstecr(fileIdOut, r2d['d'], r2d)
                print("CB24: wrote %s at ip1=%d" % (r2d['nomvar'], r2d['ip1']))
            rmn.writeGrid(fileIdOut, g)
            print("CB24: wrote the grid descriptors")
            vgd.vgd_write(v, fileIdOut)
            print("CB24: wrote the vgrid descriptor")
        except:
            raise
        finally:
            # Properly close files even if an error occured above
            # This is important when editing to avoid corrupted files
            rmn.fstcloseall(fileIdOut)
            os.unlink(fileNameOut)  # Remove test file
Пример #9
0
    def test_41(self):
        """
        Horizontal Interpolation
        
        See also:
        """
        import os, sys, datetime
        import rpnpy.librmn.all as rmn
        fdate       = datetime.date.today().strftime('%Y%m%d') + '00_048'
        CMCGRIDF    = os.getenv('CMCGRIDF').strip()
        fileNameIn  = os.path.join(CMCGRIDF, 'prog', 'regeta', fdate)
        fileNameOut = 'p0fstfile.fst'

        # Restric to the minimum the number of messages printed by librmn
        rmn.fstopt(rmn.FSTOP_MSGLVL,rmn.FSTOPI_MSG_CATAST)

        try:
            # Create Destination grid
            # Note: Destination grid can also be read from a file
            gp = {
                'grtyp' : 'Z',
                'grref' : 'E',
                'ni'    : 90,
                'nj'    : 45,
                'lat0'  : 35.,
                'lon0'  : 250.,
                'dlat'  : 0.5,
                'dlon'  : 0.5,
                'xlat1' : 0.,
                'xlon1' : 180.,
                'xlat2' : 1.,
                'xlon2' : 270.
                }
            gOut = rmn.encodeGrid(gp)
            print("CB41: Defined a %s/%s grid of shape=%d, %d" %
                  (gOut['grtyp'], gOut['grref'], gOut['ni'], gOut['nj']))
        except:
            sys.stderr.write("Problem creating grid\n")
            sys.exit(1)

        # Open Files
        try:
            fileIdIn  = rmn.fstopenall(fileNameIn)
            fileIdOut = rmn.fstopenall(fileNameOut, rmn.FST_RW)
        except:
            sys.stderr.write("Problem opening the files: %s, %s\n" % (fileNameIn, fileNameOut))
            sys.exit(1)

        try:
            # Find and read record to interpolate with its grid 
            r = rmn.fstlir(fileIdIn, nomvar='P0')
            gIn = rmn.readGrid(fileIdIn, r)
            print("CB41: Read P0")

            # Set interpolation options and interpolate
            rmn.ezsetopt(rmn.EZ_OPT_INTERP_DEGREE, rmn.EZ_INTERP_LINEAR)
            d = rmn.ezsint(gOut, gIn, r)
            print("CB41: Interpolate P0")

            # Create new record to write with interpolated data and 
            r2 = r.copy()    # Preserve meta from original record
            r2.update(gOut)  # update grid information
            r2.update({      # attach data and update specific meta
                'etiket': 'my_etk',
                'd'     : d
                })
            
            # Write record data + meta + grid to file
            rmn.fstecr(fileIdOut, r2)
            rmn.writeGrid(fileIdOut, gOut)
            print("CB41: Wrote interpolated P0 and its grid")
        except:
            pass
        finally:
            # Properly close files even if an error occured above
            # This is important when editing to avoid corrupted files
            rmn.fstcloseall(fileIdIn)
            rmn.fstcloseall(fileIdOut)
            os.unlink(fileNameOut)  # Remove test file
Пример #10
0
xlat2 = latitudearraynp[(ni / 2) + 1, nj / 2]
xlon2 = longitudearraynp[(ni / 2) + 1, nj / 2] + 360.0

params = rmn.defGrid_ZEr(ni, nj, lat0, lon0, dlat, dlon, xlat1, xlon1, xlat2,
                         xlon2)

funit = rmn.fstopenall('test.rpn', rmn.FST_RW)

print(fieldnp)

#rmn.fstecr(funit,np.asfortranarray(fieldnp))

params0 = {
    'grtyp': 'Z',
    'grref': 'E',
    'ni': ni,
    'nj': nj,
    'lat0': lat0,
    'lon0': lon0,
    'dlat': dlat,
    'dlon': dlon,
    'xlat1': xlat1,
    'xlon1': xlon1,
    'xlat2': xlat2,
    'xlon2': xlon2,
}
params = rmn.encodeGrid(params0)
print params
rmn.writeGrid(funit, params)
rmn.fstcloseall(funit)