def write_interpolated(filename, f0, f1, fact, datasetNames):
    '''
    interpolate two hdf files f0 and f1 using factor fact, and
    write the result to filename
    '''

    hdf = SD(filename, SDC.WRITE|SDC.CREATE)
    for datasetName in datasetNames:

        try:
            info = SD(f0).select(datasetName).info()
        except:
            print >> stderr, 'Error loading %s in %s' % (datasetName, f0)
            raise

        typ  = info[3]
        shp  = info[2]
        sds_in1 = SD(f0).select(datasetName)
        met0 = sds_in1.get()
        met1 = SD(f1).select(datasetName).get()

        interp = (1-fact)*met0 + fact*met1

        interp = interp.astype({
                SDC.INT16: 'int16',
                SDC.FLOAT32: 'float32',
                SDC.FLOAT64: 'float64',
            }[typ])

        # write
        sds = hdf.create(datasetName, typ, shp)
        sds[:] = interp[:]

        # copy attributes
        attr = sds_in1.attributes()
        if len(attr) > 0:
            for name in attr.keys():
                setattr(sds, name, attr[name])
        sds.endaccess()

    hdf.end()
Example #2
0
def plot_sd(SD):
    #     TODO:
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    from matplotlib import ticker

    name = SD.info()[0]
    rank = SD.info()[1]
    dims = SD.info()[2]

    fill = SD._FillValue
    scale = SD.scale_factor
    offset = SD.add_offset
    #     unit = SD.units
    data = SD.get()
    # print data.shape, rank
    scl_data = data * scale + offset
    vrng = np.array(SD.valid_range) * scale + offset

    if rank == 3:
        nc = 3  # number of columns in figure
        nr = dims[0] / nc + 1 if dims[0] % nc > 0 else dims[0] / nc
        fig = plt.figure(figsize=(12, nr * 3))
        gs = gridspec.GridSpec(nr, nc)

        for i in range(0, dims[0]):
            if data[i, :, :].max() == fill: continue

            ax = fig.add_subplot(gs[i])
            frame = plt.gca()
            frame.axes.get_xaxis().set_ticks([])
            frame.axes.get_yaxis().set_ticks([])
            ax.set_title('{0}:{1}'.format(name, i + 1), fontsize=10)
            mdata = np.ma.masked_where(data[i, :, :] == fill,
                                       scl_data[i, :, :])
            #             print 'Reading array', i
            #             print mdata.min(), mdata.max(), mdata.ptp()
            vrng = [mdata.min(), mdata.max()]
            plt.imshow(mdata.T,
                       vmin=vrng[0],
                       vmax=vrng[1],
                       cmap=plt.cm.Spectral_r)  # @UndefinedVariable

            cb = plt.colorbar(orientation='vertical',
                              fraction=.03,
                              format='%0.2f')
            tick_locator = ticker.MaxNLocator(nbins=6)
            cb.locator = tick_locator
            cb.update_ticks()

    elif rank == 2:
        if data.max() == fill:
            # No valid sds in the selected field, skip further processing..
            raise SystemExit('** W: No valid data in {0} for '\
                             'plotting **\n'.format(name))
        else:
            # Create masked array of the selected field filtering out fill_values
            mdata = np.ma.masked_where(data == fill, scl_data)
            fig = plt.figure(figsize=(4, 3))
            ax = fig.add_subplot(111)
            ax.set_title(name)
            plt.imshow(mdata.T,
                       vmin=mdata.min(),
                       vmax=mdata.max(),
                       cmap=plt.cm.Spectral_r)  # @UndefinedVariable
            ax.set_aspect('equal')
            plt.colorbar(orientation='vertical', fraction=.03)

    fig.tight_layout()
    plt.show()