Exemplo n.º 1
0
def test_gdal_calculations_py_10():
    ''' Test snap dataset '''
    try:
        from gdal_calculations import Dataset, Env

        f = 'data/tgc_geo.tif'
        ds1 = Dataset(f)
        f = 'data/tgc_geo_shifted.vrt'
        ds2 = Dataset(f)
        f = 'data/tgc_geo_shifted_2.vrt'
        snap_ds = Dataset(f)

        Env.snap = ds2
        out = ds1 + ds2
        assert approx_equal(
            [out.gt[0], out.gt[3]],
            [ds2.gt[0], ds2.gt[3]]), 'out geotransform doesnae match ds2'

        Env.snap = snap_ds
        out = ds2 + ds1
        assert approx_equal([out.gt[0], out.gt[3]],
                            [snap_ds.gt[0], snap_ds.gt[3]
                             ]), 'out geotransform doesnae match snap_ds'

        ds1, ds2, snap_ds, out = None, None, None, None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
Exemplo n.º 2
0
def test_gdal_calculations_py_14():
    ''' Test some numpy methods '''
    try:
        from gdal_calculations import Dataset, Env
        Env.reproject = True

        #Regular raster
        f = 'data/tgc_geo.tif'
        dsf = Dataset(f)
        #Warped raster
        f = 'data/tgc_alb.vrt'
        dsw = Dataset(f)

        out = np.sum([dsf, dsw])
        out = np.mean([dsf, dsw])

        #None of these will work - invalid __array_struct__
        #out=np.multiply(dsf,dsw)
        #out=np.divide(dsf,dsw)
        #out=np.logaddexp(dsf,dsw)
        #out=np.power(dsf,2)
        #out=np.mod(dsf,2)

        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
def test_gdal_calculations_py_7():
    '''Test on-the-fly reprojection'''
    try:
        from gdal_calculations import Dataset, Env

        #Regular raster
        f='data/tgc_geo.tif'
        dsf=Dataset(f)
        #Warped raster
        f='data/tgc_alb.vrt'
        dsw=Dataset(f)

        try:out_alb=dsw+dsf
        except:pass
        else:raise Exception('operation succeeded when coordinate systems differ and Env.reproject is False')

        Env.reproject=True
        out_alb=dsw+dsf
        assert out_alb._srs==dsw._srs, "out_alb._srs!=dsw._srs"

        out_geo=dsf+dsw
        assert out_geo._srs==dsf._srs, "out_geo._srs==dsf._srs"

        dsf,dsw,out_alb,out_geo=None,None,None,None
        return 'success'
    except ImportError:
        return 'skip'
    except Exception as e:
        gdaltest.post_reason(e.message)
        return 'fail'
    finally:cleanup()
Exemplo n.º 4
0
def test_gdal_calculations_py_3():
    ''' Test dataset open from filepath and gdal.Dataset object '''
    try:
        from gdal_calculations import Dataset
        from gdal_calculations.gdal_dataset import Band

        f = 'data/tgc_geo.tif'
        d = gdal.Open(f)
        dsf = Dataset(f)
        assert isinstance(dsf,
                          Dataset), "isinstance(%s,Dataset)!=True" % repr(dsf)
        assert isinstance(dsf[0],
                          Band), "isinstance(%s,Band)!=True" % repr(dsf[0])
        dsd = Dataset(d)
        assert isinstance(dsf,
                          Dataset), "isinstance(%s,Dataset)!=True" % repr(dsf)
        assert isinstance(dsf[0],
                          Band), "isinstance(%s,Band)!=True" % repr(dsf[0])
        dsf = None
        dsd = None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
def test_gdal_calculations_py_9():
    ''' Test on-the-fly resampling '''
    try:
        from gdal_calculations import Dataset, Env

        #Smaller raster
        f='data/tgc_geo.tif'
        ds1=Dataset(f)
        #Larger pixel raster
        f='data/tgc_geo_resize_warp.vrt'
        ds2=Dataset(f)

        #Default cellsize = left dataset
        out=ds1+ds2
        assert approx_equal([out._gt[1],out._gt[5]],[ds1._gt[1],ds1._gt[5]]),'out cellsize!=ds1 cellsize'
        out=ds2+ds1
        assert approx_equal([out._gt[1],out._gt[5]],[ds2._gt[1],ds2._gt[5]]),'out cellsize!=ds2 cellsize'

        #MINOF cellsize
        Env.cellsize='MINOF'
        out=ds1+ds2
        assert approx_equal([out._gt[1],out._gt[5]],[ds1._gt[1],ds1._gt[5]]),'Env.cellsize=MINOF and out cellsize!=ds1 cellsize'
        out=ds2+ds1
        assert approx_equal([out._gt[1],out._gt[5]],[ds1._gt[1],ds1._gt[5]]),'Env.cellsize=MINOF and out cellsize!=ds1 cellsize'

        #MAXOF cellsize
        Env.cellsize='MAXOF'
        out=ds1+ds2
        assert approx_equal([out._gt[1],out._gt[5]],[ds2._gt[1],ds2._gt[5]]),'Env.cellsize=MAXOF and out cellsize!=ds2 cellsize'
        out=ds2+ds1
        assert approx_equal([out._gt[1],out._gt[5]],[ds2._gt[1],ds2._gt[5]]),'Env.cellsize=MAXOF and out cellsize!=ds2 cellsize'

        #specific cellsize
        Env.cellsize=0.015
        out=ds1+ds2
        assert approx_equal([out._gt[1],out._gt[5]],[0.015,-0.015]),'Env.cellsize=0.015 and out cellsize==(%s,%s)'%(out._gt[1],abs(out._gt[5]))
        out=ds2+ds1
        assert approx_equal([out._gt[1],out._gt[5]],[0.015,-0.015]),'Env.cellsize=0.015 and out cellsize==(%s,%s)'%(out._gt[1],abs(out._gt[5]))
        Env.cellsize=(0.019,0.018)
        out=ds1+ds2
        assert approx_equal([out._gt[1],out._gt[5]],[0.019,-0.018]),'Env.cellsize=(0.019,0.018) and out cellsize==(%s,%s)'%(out._gt[1],abs(out._gt[5]))
        out=ds2+ds1
        assert approx_equal([out._gt[1],out._gt[5]],[0.019,-0.018]),'Env.cellsize=(0.019,0.018) and out cellsize==(%s,%s)'%(out._gt[1],abs(out._gt[5]))

        #Inappropriate cellsize
        Env.cellsize=25
        out=ds1+1 #Environment settings don't get applied with a single raster in the expression
        assert not approx_equal([out._gt[1],out._gt[5]],[25,-25]),'Env.cellsize=25 and out cellsize==%s'%(out._gt[1])
        try:out=ds1+ds1
        except:pass
        else:raise Exception('Inappropriate cellsize ds1+ds1')

        ds1,ds2,out=None,None,None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:cleanup()
Exemplo n.º 6
0
def test_gdal_calculations_py_8():
    ''' Test on-the-fly clipping '''
    try:
        from gdal_calculations import Dataset, Env

        #Smaller raster
        f = 'data/tgc_geo.tif'
        ds1 = Dataset(f)
        #Larger raster
        f = 'data/tgc_geo_resize.vrt'
        ds2 = Dataset(f)
        #Even larger raster
        f = 'data/tgc_geo_resize_2.vrt'
        ds3 = Dataset(f)
        #Larger raster (warped)
        f = 'data/tgc_geo_resize_warp.vrt'
        ds4 = Dataset(f)

        #Default extent = Min extent
        out = ds1 + ds2
        assert approx_equal(out.extent, ds1.extent), 'out.extent!=ds1.extent'
        out = ds2 + ds1
        assert approx_equal(out.extent, ds1.extent), 'out.extent!=ds1.extent'
        out = ds3 + ds2 + ds1
        assert approx_equal(out.extent, ds1.extent), 'out.extent!=ds1.extent'

        #Max extent
        Env.extent = 'MAXOF'
        out = ds1 + ds2
        assert approx_equal(
            out.extent,
            ds2.extent), 'Env.extent="MAXOF" and out.extent!=ds2.extent'
        out = ds1 + ds2 + ds3
        assert approx_equal(
            out.extent,
            ds3.extent), 'Env.extent="MAXOF" and out.extent!=ds3.extent'

        #specified extent
        Env.extent = [147.55, -35.45, 148.45, -34.55]
        out = ds1 + ds2
        assert approx_equal(
            out.extent,
            Env.extent), 'Env.extent=%s and out.extent==%s' % (Env.extent,
                                                               out.extent)
        out = ds1 + ds2 + ds4
        assert approx_equal(
            out.extent,
            Env.extent), 'Env.extent=%s and out.extent==%s' % (Env.extent,
                                                               out.extent)

        ds1, ds2, ds3, ds4, out = None, None, None, None, None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
Exemplo n.º 7
0
def test_gdal_calculations_py_13():
    ''' Test numexpr '''
    try:
        from gdal_calculations import Dataset, Env
        import numexpr as ne

        Env.enable_numexpr = True

        f = 'data/tgc_geo.tif'
        ds1 = Dataset(f)
        f = 'data/tgc_geo_resize.vrt'
        ds2 = Dataset(f)

        #Must not be tiled for numexpr
        try:
            ne.evaluate('ds1+1')
        except:
            pass
        else:
            raise AssertionError(
                'numexpr.evaluate succeeded and Env.tiled=True')
        Env.tiled = False
        out = ne.evaluate('ds1+1')  #returns a numpy ndarray
        assert out.shape==(ds1.RasterXSize,ds1.RasterYSize), "out.shape == %s not %s"% \
                        (repr(out.shape), repr((ds1.RasterXSize,ds1.RasterYSize)))

        #No subscripting or methods in the expression
        try:
            ne.evaluate('Float32(ds1[0])+1')
        except:
            pass
        else:
            raise AssertionError(
                'numexpr.evaluate succeeded and with subscripting / methods in the expression'
            )

        #Must be same coordinate systems and dimensions
        #The apply_environment method will reproject/resample/clip if required
        try:
            ne.evaluate('ds1+ds2')
        except:
            pass
        else:
            raise AssertionError(
                'numexpr.evaluate succeeded when ds1 and ds2 extents differ')
        ds3, ds4 = ds1.apply_environment(ds2)
        out = ne.evaluate('ds3+ds4')  #returns a numpy ndarray
        assert out.shape==(ds1.RasterXSize,ds1.RasterYSize), "out.shape == %s not %s"% \
                        (repr(out.shape), repr((ds1.RasterXSize,ds1.RasterYSize)))

        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
        cleanup('numexpr')
def test_gdal_calculations_py_17():
    try:
        from gdal_calculations import NewDataset, ArrayDataset, Dataset, Env
        Env.tempdir='/vsimem'

        #Regular raster
        f='data/tgc_geo.tif'
        dsf=Dataset(f)
        dat=dsf.ReadAsArray()

        dsn=NewDataset('/vsimem/test.tif',prototype_ds=dsf)
        dsn.write_data(dat)
        ok=(dsn.ReadAsArray())==(dsf.ReadAsArray())
        assert ok.all(), "dsn.ReadAsArray()!=dsf.ReadAsArray()"
        assert dsn.RasterXSize==dsf.RasterXSize, "dsn.RasterXSize!=dsf.RasterXSize"
        assert dsn.RasterYSize==dsf.RasterYSize, "dsn.RasterYSize!=dsf.RasterYSize"
        assert dsn.GetGeoTransform()==dsf.GetGeoTransform(), "dsn.GetGeoTransform()!=dsf.GetGeoTransform()"
        assert dsn.GetProjection()==dsf.GetProjection(), "dsn.GetProjection()!=dsf.GetProjection()"

        dsa=ArrayDataset(dat,prototype_ds=dsf)
        ok=(dsa.ReadAsArray())==(dsf.ReadAsArray())
        assert ok.all(), "dsa.ReadAsArray()!=dsf.ReadAsArray()"
        assert dsa.RasterXSize==dsf.RasterXSize, "dsa.RasterXSize!=dsf.RasterXSize"
        assert dsa.RasterYSize==dsf.RasterYSize, "dsa.RasterYSize!=dsf.RasterYSize"
        assert dsa.GetGeoTransform()==dsf.GetGeoTransform(), "dsa.GetGeoTransform()!=dsf.GetGeoTransform()"
        assert dsa.GetProjection()==dsf.GetProjection(), "dsa.GetProjection()!=dsf.GetProjection()"

        return 'success'
    except AssertionError:
        return fail()
    finally:
        cleanup()
def test_gdal_calculations_py_5():
    ''' Test type conversion functions '''
    try:
        from gdal_calculations import Dataset,Byte,Int16,UInt32,Int32,Float32,Float64

        #Regular raster
        f='data/tgc_geo.tif'
        dsf=Dataset(f)

        d=Byte(dsf)
        assert d._data_type==gdal.GDT_Byte, "data_type!=Byte (%s)"%gdal.GetDataTypeName(d._data_type)
        d=Int16(dsf)
        assert d._data_type==gdal.GDT_Int16, "data_type!=Int16 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=UInt32(dsf)
        assert d._data_type==gdal.GDT_UInt32, "data_type!=UInt32 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=Int32(dsf)
        assert d._data_type==gdal.GDT_Int32, "data_type!=Int32 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=Float32(dsf)
        assert d._data_type==gdal.GDT_Float32, "data_type!=Float32 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=Float64(dsf)
        assert d._data_type==gdal.GDT_Float64, "data_type!=Float64 (%s)"%gdal.GetDataTypeName(d._data_type)

        #Warped VRT
        f='data/tgc_alb.vrt'
        dsf=Dataset(f)

        d=Byte(dsf)
        assert d._data_type==gdal.GDT_Byte, "data_type!=Byte (%s)"%gdal.GetDataTypeName(d._data_type)
        d=None
        d=Int16(dsf)
        assert d._data_type==gdal.GDT_Int16, "data_type!=Int16 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=None
        d=UInt32(dsf)
        assert d._data_type==gdal.GDT_UInt32, "data_type!=UInt32 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=None
        d=Int32(dsf)
        assert d._data_type==gdal.GDT_Int32, "data_type!=Int32 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=None
        d=Float32(dsf)
        assert d._data_type==gdal.GDT_Float32, "data_type!=Float32 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=None
        d=Float64(dsf)
        assert d._data_type==gdal.GDT_Float64, "data_type!=Float64 (%s)"%gdal.GetDataTypeName(d._data_type)
        d=None

        dsf=None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:cleanup()
def test_gdal_calculations_py_4():
    ''' Test dataset reads and getattr calls '''
    try:
        from gdal_calculations import Env,Dataset
        Env.tiled=True

        f='data/tgc_geo.tif'
        dsf=Dataset(f)

        #ReadAsArray() (also a __getattr__ gdal.Dataset method)
        data=dsf.ReadAsArray()
        assert data.shape==(100,100), "data.shape==%s"%repr(data.shape)
        data=None

        #ReadBlocksAsArray() (gdal_calculations.Dataset method)
        for block in dsf.ReadBlocksAsArray():
            assert block.data.shape==(40,100), "data.shape==%s"%repr(block.data.shape)
            break
        del block

        #__getattr__ np attribute
        assert dsf.shape==(40,100), "dsf.shape==%s"%repr(dsf.shape)

        #ReadBlocksAsArray() (gdal_calculations.Dataset method)
        Env.ntiles=2
        for block in dsf.ReadBlocksAsArray():
            assert block.data.shape==(80,100), "data.shape==%s"%repr(block.data.shape)
            break
        del block
        Env.ntiles=1

        #__getattr__ np method that doesn't return a temp dataset
        Env.tiled=False
        s=dsf.sum()
        assert s==50005000, "dsf.sum()==%s"%repr(s)
        s=dsf.max()
        assert s==10000, "dsf.max()==%s"%repr(s)

        #__getattr__ np method that returns a temp dataset
        Env.tiled=True
        s=dsf.astype(np.int32)
        assert isinstance(s,Dataset), "isinstance(%s,Dataset)!=True"%repr(s)
        del s

        #__getattr__ gdal.Dataset method
        gt=dsf.GetGeoTransform()
        assert gt==(147.5, 0.01, 0.0, -34.5, 0.0, -0.01), "dsf.GetGeoTransform()==%s"%repr(gt)
        del gt

        Env.tiled=True
        dsf=None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:cleanup()
def test_gdal_calculations_py_13():
    ''' Test numexpr '''
    try:
        from gdal_calculations import Dataset, Env
        import numexpr as ne

        Env.enable_numexpr=True

        f='data/tgc_geo.tif'
        ds1=Dataset(f)
        f='data/tgc_geo_resize.vrt'
        ds2=Dataset(f)

        #Must not be tiled for numexpr
        try:ne.evaluate('ds1+1')
        except:pass
        else:raise AssertionError('numexpr.evaluate succeeded and Env.tiled=True')
        Env.tiled=False
        out=ne.evaluate('ds1+1') #returns a numpy ndarray
        assert out.shape==(ds1.RasterXSize,ds1.RasterYSize), "out.shape == %s not %s"% \
                        (repr(out.shape), repr((ds1.RasterXSize,ds1.RasterYSize)))

        #No subscripting or methods in the expression
        try:ne.evaluate('Float32(ds1[0])+1')
        except:pass
        else:raise AssertionError('numexpr.evaluate succeeded and with subscripting / methods in the expression')

        #Must be same coordinate systems and dimensions
        #The apply_environment method will reproject/resample/clip if required
        try:ne.evaluate('ds1+ds2')
        except:pass
        else:raise AssertionError('numexpr.evaluate succeeded when ds1 and ds2 extents differ')
        ds3,ds4=ds1.apply_environment(ds2)
        out=ne.evaluate('ds3+ds4') #returns a numpy ndarray
        assert out.shape==(ds1.RasterXSize,ds1.RasterYSize), "out.shape == %s not %s"% \
                        (repr(out.shape), repr((ds1.RasterXSize,ds1.RasterYSize)))

        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
        cleanup('numexpr')
Exemplo n.º 12
0
def test_gdal_calculations_py_12():
    ''' Test nodata handling '''
    try:
        from gdal_calculations import Dataset, Env

        f = 'data/tgc_geo_resize.vrt'
        dsf = Dataset(f, gdal.GA_ReadOnly)

        Env.nodata = True

        #1st pixel should be 0
        #tgc_geo_resize.vrt does not have a nodata value set
        val = dsf[0].ReadAsArray(0, 0, 1, 1)
        assert val == 0, "dsf[0].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)

        #Add 1.
        #Create a copy of the VRT so GDAL doesn't modify it on disk
        dsg = Dataset(gdal.GetDriverByName('VRT').CreateCopy('', dsf._dataset))
        out = dsg[0] + 1
        val = out.ReadAsArray(0, 0, 1, 1)
        assert val==1, "dsg[0] nodata not set (%s) out.ReadAsArray(0, 0, 1, 1)==%s"% \
                        (repr(dsf[0].GetNoDataValue()), repr(val))

        #Set nodata and add 1 again
        dsg[0].SetNoDataValue(0)
        out = dsg[0] + 1
        val = out.ReadAsArray(0, 0, 1, 1)
        assert val==0, "dsg[0] nodata is set (%s) out.ReadAsArray(0, 0, 1, 1)==%s"% \
                        (repr(dsf[0].GetNoDataValue()), repr(val))

        dsf, dsg, out = None, None, None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
def test_gdal_calculations_py_11():
    ''' Test srs '''
    try:
        from gdal_calculations import Dataset, Env

        Env.srs=3112 #GDA94 / Australia Lambert

        f='data/tgc_geo.tif' #GDA94 / Geographic
        ds1=Dataset(f)
        f='data/tgc_alb.vrt' #GDA94 / Australia Albers
        ds2=Dataset(f)

        out=ds1[0]+ds2[0]
        outsrs=osr.SpatialReference(out._srs)
        assert Env.srs.IsSame(outsrs),'out srs != Env.srs'

        ds1,ds2,out=None,None,None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:cleanup()
Exemplo n.º 14
0
def test_gdal_calculations_py_18():
    try:
        from gdal_calculations import NewDataset, ArrayDataset, Dataset, Env
        Env.tempdir = '/vsimem'

        #Regular raster
        f = 'data/tgc_geo.tif'
        dsf = Dataset(f)
        dat = dsf.ReadAsArray()

        dsn = NewDataset('/vsimem/test.tif', prototype_ds=dsf)
        dsn.set_nodata_value(123)
        dsn.write_data(dat)

        del dsn
        dsn = Dataset('/vsimem/test.tif')
        assert dsn.nodata == [123], "dsn.nodata != [123]"
        assert dsn[0].GetNoDataValue() == 123, "dsn[0].GetNoDataValue() != 123"

        return 'success'
    except AssertionError:
        return fail()
    finally:
        cleanup()
Exemplo n.º 15
0
def test_gdal_calculations_py_19():
    try:
        from gdal_calculations import Dataset, Env
        Env.tempdir = '/vsimem'
        Env.tiled = False

        #Regular raster
        f = 'data/tgc_geo.tif'
        dsf = Dataset(f)
        bnd = dsf[0]
        test = bnd * 1.0

        return 'success'
    except AssertionError:
        return fail()
    finally:
        cleanup()
Exemplo n.º 16
0
def test_gdal_calculations_py_16():
    ''' Test Issue 3 - Multiband order'''
    try:
        from gdal_calculations import Dataset, Int16, Env

        #Regular raster
        f = 'data/tgc_multiband.tif'
        dsf = Dataset(f)

        val = dsf[0].ReadAsArray(0, 0, 1, 1)
        assert val == 1, "dsf[0].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dsf[1].ReadAsArray(0, 0, 1, 1)
        assert val == 2, "dsf[1].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dsf[2].ReadAsArray(0, 0, 1, 1)
        assert val == 3, "dsf[2].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dsf[3].ReadAsArray(0, 0, 1, 1)
        assert val == 4, "dsf[3].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)

        dst = Int16(dsf)
        val = dst[0].ReadAsArray(0, 0, 1, 1)
        assert val == 1, "dst[0].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dst[1].ReadAsArray(0, 0, 1, 1)
        assert val == 2, "dst[1].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dst[2].ReadAsArray(0, 0, 1, 1)
        assert val == 3, "dst[2].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dst[3].ReadAsArray(0, 0, 1, 1)
        assert val == 4, "dst[3].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)

        Env.extent = [0.0, 0.0, 5.0, 5.0]
        dst = dsf * 1
        val = dst[0].ReadAsArray(0, 0, 1, 1)
        assert val == 1, "dst[0].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dst[1].ReadAsArray(0, 0, 1, 1)
        assert val == 2, "dst[1].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dst[2].ReadAsArray(0, 0, 1, 1)
        assert val == 3, "dst[2].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = dst[3].ReadAsArray(0, 0, 1, 1)
        assert val == 4, "dst[3].ReadAsArray(0, 0, 1, 1)==%s" % repr(val)

        return 'success'
    except AssertionError:
        return fail()
    finally:
        cleanup()
Exemplo n.º 17
0
def test_gdal_calculations_py_15():
    ''' Test commandline '''
    #In the unlikely event this code ever ends up _in_ GDAL, this function
    #will need modification to comply with standard GDAL script/sample paths
    try:
        from gdal_calculations import Dataset, __version__
        cd = os.path.abspath(os.curdir)

        testdir = os.path.abspath(os.path.dirname(__file__))
        datadir = os.path.join(testdir, 'data')
        tmpdir = os.path.join(testdir, 'tmp')
        topdir = os.path.abspath(os.path.join(testdir, '..', '..'))
        bindir = os.path.join(topdir, 'bin')
        libdir = os.path.join(topdir, 'lib')

        f1 = os.path.join(datadir, 'tgc_geo.tif')
        f2 = os.path.join(datadir, 'tgc_geo_resize.vrt')

        #test commandline scripts (assumes orig googlecode svn structure, not various gdal setups)
        #All the commandline gdal_calculate and gdal_calculate.cmd scripts do
        #is call python -m gdal_calculations <args>
        os.chdir(libdir)  #So script can find module
        script = os.path.join(bindir, 'gdal_calculate')
        if sys.platform == 'win32': script += '.cmd'
        #gdaltest.runexternal() doesn't read stderr
        ret = gdaltest.runexternal(script +
                                   ' --version --redirect-stderr').strip()
        assert ret == __version__, 'Script version (%s) != %s' % (ret,
                                                                  __version__)
        try:
            del ret
        except:
            pass

        #Try running something that numexpr can handle
        #if numexpr is not available, this should be handled by standard python eval
        out = os.path.join(tmpdir, 'tgc_15a.ers')
        args = '--calc="ds + 1" --ds="%s" --outfile="%s" --numexpr --of=ERS --redirect-stderr' % (
            f1, out)
        try:
            ret = gdaltest.runexternal(script + ' ' + args).strip()
            ds = Dataset(out)
            del ds
        except Exception as e:
            raise RuntimeError(ret + '\n' + e.message)
        finally:
            try:
                gdal.Unlink(out)
                gdal.Unlink(out[:-4])
            except:
                pass
        del ret

        #Try running something that numexpr can't handle,
        #this should be handled by standard python eval
        out = os.path.join(tmpdir, 'tgc_15b.ers')
        args = '--calc="ds1+ds2" --ds1="%s" --ds2="%s" --outfile="%s" --numexpr --of=ERS --redirect-stderr' % (
            f1, f2, out)
        try:
            ret = gdaltest.runexternal(script + ' ' + args).strip()
            ds = Dataset(out)
            del ds
        except Exception as e:
            raise RuntimeError(ret + '\n' + e.message)
        finally:
            try:
                gdal.Unlink(out)
                gdal.Unlink(out[:-4])
            except:
                pass
        del ret

        return 'success'
    except AssertionError:
        return fail()
    finally:
        os.chdir(cd)
        cleanup()
Exemplo n.º 18
0
def test_gdal_calculations_py_2():
    ''' Test environment getting/setting '''
    try:
        from gdal_calculations import Env, Dataset
        from osgeo import gdal

        #Get/set cellsize
        assert Env.cellsize == "DEFAULT", "Env.cellsize != 'DEFAULT' ('%s')" % Env.cellsize
        Env.cellsize = "DEFAULT"
        Env.cellsize = "MINOF"
        Env.cellsize = "MAXOF"
        Env.cellsize = 1
        Env.cellsize = [1, 1]
        try:
            Env.cellsize = "INCORRECT"
        except:
            pass
        else:
            return fail('Env.cellsize accepted an incorrect value')

        #Get/set extent
        assert Env.extent == "MINOF", "Env.extent != 'MINOF' ('%s')" % Env.extent
        Env.extent = "MINOF"
        Env.extent = "MAXOF"
        Env.extent = [1, 1, 2, 2]
        try:
            Env.extent = "INCORRECT"
        except:
            pass
        else:
            return fail('Env.extent accepted an incorrect value')

        #Get/set extent
        assert Env.nodata == False, "Env.nodata != False ('%s')" % Env.nodata
        Env.nodata = True
        Env.nodata = False

        #Get/set overwrite
        assert Env.overwrite == False, "Env.overwrite != False ('%s')" % Env.overwrite
        Env.overwrite = True
        Env.overwrite = False

        #Get/set reproject
        assert Env.reproject == False, "Env.reproject != False ('%s')" % Env.reproject
        Env.reproject = True
        Env.reproject = False

        #Get/set resampling
        assert Env.resampling == gdal.GRA_NearestNeighbour, 'Env.resampling != "NEAREST"'
        Env.resampling = "BILINEAR"
        Env.resampling = "CUBIC"
        Env.resampling = "CUBICSPLINE"
        Env.resampling = "LANCZOS"
        Env.resampling = "NEAREST"
        if int(gdal.VersionInfo("VERSION_NUM")) >= 1100000:
            Env.resampling = "AVERAGE"
            Env.resampling = "MODE"
        try:
            Env.resampling = "INCORRECT"
        except:
            pass
        else:
            return fail('Env.resampling accepted an incorrect value')

        #Get/set snap
        assert Env.snap is None, 'Env.snap should be None not %s' % repr(
            Env.snap)
        Env.snap = Dataset('data/tgc_geo.tif')
        assert isinstance(Env.snap, Dataset), 'Env.snap is not a Dataset'

        #Get/set srs
        epsg = 4283
        wkt = 'GEOGCS["GDA94",DATUM["Geocentric_Datum_of_Australia_1994",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6283"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4283"]]'
        srs = osr.SpatialReference(wkt)
        assert Env.srs is None, 'Env.srs should be None'
        Env.srs = epsg
        assert isinstance(
            Env.srs,
            osr.SpatialReference), 'Env.srs is not a SpatialReference (EPSG)'
        Env.srs = wkt
        assert isinstance(
            Env.srs,
            osr.SpatialReference), 'Env.srs is not a SpatialReference (WKT)'
        Env.srs = srs
        assert isinstance(
            Env.srs, osr.SpatialReference
        ), 'Env.srs is not a SpatialReference (SpatialReference)'
        gue = osr.GetUseExceptions()
        osr.DontUseExceptions()
        try:
            Env.srs = 1
        except:
            pass
        else:
            return fail('Env.srs accepted an invalid EPSG (1)')
        try:
            Env.srs = 'INCORRECT'
        except:
            pass
        else:
            return fail('Env.extent accepted an invalid WKT ("INCORRECT")')
        try:
            Env.srs = osr.SpatialReference('sdfsdfsdf')
        except:
            pass
        else:
            return fail('Env.extent accepted an invalid SpatialReference')
        if gue: osr.UseExceptions()
        else: osr.DontUseExceptions()

        #Get/set tempdir
        try:
            tempdir = tempfile.tempdir  #use to reset tempfile.tempdir to default
            assert Env.tempdir == tempfile.tempdir, 'Env.tempdir != %s' % tempfile.tempdir
            Env.tempdir = 'tmp'  #autotest/pyscripts/tmp
            assert tempfile.tempdir == 'tmp', 'tempfile.tempdir != tmp'
            try:
                Env.tempdir = "INCORRECT"
            except:
                pass
            else:
                gdaltest.post_reason('Env.tempdir accepted an incorrect value')
                return 'fail'
        finally:
            tempfile.tempdir = tempdir

        #Get/set tiled
        assert Env.tiled == True, "Env.tiled != True ('%s')" % Env.tiled
        Env.tiled = False
        Env.tiled = True

        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        cleanup()
Exemplo n.º 19
0
def test_gdal_calculations_py_6():
    ''' Test some arithmetic '''
    try:
        from gdal_calculations import Dataset, Int16
        olderr = np.seterr(**{'all': 'ignore'})

        #Regular raster
        f = 'data/tgc_geo.tif'
        dsf = Dataset(f)

        #original values
        assert dsf.ReadAsArray(0, 0, 1,
                               1) == 1, "dsf.ReadAsArray(0, 0, 1, 1)!=1"
        assert dsf.ReadAsArray(1, 0, 1,
                               1) == 2, "dsf.ReadAsArray(1, 0, 1, 1)!=2"
        assert dsf.ReadAsArray(55, 2, 1,
                               1) == 256, "dsf.ReadAsArray(55,2,1,1)!=256"

        #===========================================================================
        #Arithmetic operations
        #===========================================================================
        #__add__
        val = (dsf + 1).ReadAsArray(0, 0, 1, 1)
        assert val == 2, "(dsf+1).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        #__sub__ and __rsub__
        val = (dsf - 1).ReadAsArray(0, 0, 1, 1)
        assert val == 0, "(dsf-1).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = (10 - dsf).ReadAsArray(0, 0, 1, 1)
        assert val == 9, "(10-dsf).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        #__mul__
        val = (dsf * 2).ReadAsArray(0, 0, 1, 1)
        assert val == 2, "(dsf*2).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        #__div__ and __rdiv__
        val = (dsf / 2).ReadAsArray(0, 0, 1, 1)
        assert val == 0, "(dsf/2).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = (2 / dsf).ReadAsArray(0, 0, 1, 1)
        assert val == 2, "(2/dsf).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        #__truediv__
        ##Can't do `from __future__ import division` except at the top of the script
        import __future__
        expr = compile('(dsf/2).ReadAsArray(0, 0, 1, 1)', '', 'eval',
                       __future__.CO_FUTURE_DIVISION)
        val = eval(expr)
        assert val == 0.5, "(dsf/2).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        expr = compile('(2/dsf).ReadAsArray(0, 0, 1, 1)', '', 'eval',
                       __future__.CO_FUTURE_DIVISION)
        val = eval(expr)
        assert val == 2, "(2/dsf).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        #__floordiv__ and __rfloordiv__
        val = (dsf // 2).ReadAsArray(0, 0, 1, 1)
        assert val == 0, "(dsf//2).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = (2 // dsf).ReadAsArray(0, 0, 1, 1)
        assert val == 2, "(2//dsf).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        #__mod__ and __rmod__
        val = (dsf % 1.5).ReadAsArray(1, 0, 1, 1)
        assert val == 0.5, "(dsf % 1.5).ReadAsArray(1, 0, 1, 1)==%s" % repr(
            val)
        val = (1.5 % dsf).ReadAsArray(1, 0, 1, 1)
        assert val == 1.5, "(dsf % 1.5).ReadAsArray(1, 0, 1, 1)==%s" % repr(
            val)
        #__pow__ and __rpow__
        val = (dsf**2).ReadAsArray(2, 0, 1, 1)
        assert val == 9, "(dsf ** 2).ReadAsArray(2, 0, 1, 1)==%s" % repr(val)
        val = (2**dsf).ReadAsArray(2, 0, 1, 1)
        assert val == 8, "(2 ** dsf).ReadAsArray(2, 0, 1, 1)==%s" % repr(val)
        #__neg__
        val = -dsf.ReadAsArray(0, 0, 1, 1)
        assert val == 65535, "-dsf.ReadAsArray(0, 0, 1, 1)==%s" % repr(val)
        val = -Int16(dsf).ReadAsArray(0, 0, 1, 1)
        assert val == -1, "-Int16(dsf).ReadAsArray(0, 0, 1, 1)==%s" % repr(val)

        #===========================================================================
        #Bitwise operations
        #===========================================================================
        #__and__ and __rand__
        val = (dsf & 3).ReadAsArray(4, 0, 1, 1)
        assert val == 1, "(dsf&3).ReadAsArray(4,0,1,1)==%s" % repr(val)
        val = (3 & dsf).ReadAsArray(4, 0, 1, 1)
        assert val == 1, "(3&dsf).ReadAsArray(4,0,1,1)==%s" % repr(val)
        #__or__ and __ror__
        val = (dsf & 3).ReadAsArray(4, 0, 1, 1)
        assert val == 1, "(dsf&3).ReadAsArray(4,0,1,1)==%s" % repr(val)
        val = (3 & dsf).ReadAsArray(4, 0, 1, 1)
        assert val == 1, "(3&dsf).ReadAsArray(4,0,1,1)==%s" % repr(val)
        #__lshift__ and __rlshift__
        val = (dsf << 2).ReadAsArray(2, 0, 1, 1)
        assert val == 12, "(dsf<<2).ReadAsArray(2, 0, 1, 1)==%s" % repr(val)
        val = (2 << dsf).ReadAsArray(2, 0, 1, 1)
        assert val == 16, "(dsf<<2).ReadAsArray(2, 0, 1, 1)==%s" % repr(val)
        #__rshift__ and __rrshift__
        val = (dsf >> 2).ReadAsArray(55, 2, 1, 1)
        assert val == 64, "(dsf>>2).ReadAsArray(55,2,1,1)==%s" % repr(val)
        val = (256 >> dsf).ReadAsArray(1, 0, 1, 1)
        assert val == 64, "(dsf>>2).ReadAsArray(1,0,1,1)==%s" % repr(val)
        #__xor__ and __rxor__
        val = (dsf ^ 3).ReadAsArray(4, 0, 1, 1)
        assert val == 6, "(dsf^3).ReadAsArray(4,0,1,1)==%s" % repr(val)
        val = (3 ^ dsf).ReadAsArray(4, 0, 1, 1)
        assert val == 6, "(3^dsf).ReadAsArray(4,0,1,1)==%s" % repr(val)

        #===========================================================================
        #Boolean operations
        #===========================================================================
        #__lt__
        val = (dsf < 2).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            1, 0), "(dsf<2).ReadAsArray(0,0,2,1)==%s" % repr(val)
        val = (1 < dsf).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            0, 1), "(1<dsf).ReadAsArray(0,0,2,1)==%s" % repr(val)
        #__le__
        val = (dsf <= 1).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            1, 0), "(dsf<=1).ReadAsArray(0,0,2,1)==%s" % repr(val)
        val = (2 <= dsf).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            0, 1), "(2<=dsf).ReadAsArray(0,0,2,1)==%s" % repr(val)
        #__eq__
        val = (dsf == 1).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            1, 0), "(dsf==1).ReadAsArray(0,0,2,1)==%s" % repr(val)
        val = (1 == dsf).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            1, 0), "(1==dsf).ReadAsArray(0,0,2,1)==%s" % repr(val)
        #__ne__
        val = (dsf != 1).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            0, 1), "(dsf==1).ReadAsArray(0,0,2,1)==%s" % repr(val)
        val = (1 != dsf).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            0, 1), "(1==dsf).ReadAsArray(0,0,2,1)==%s" % repr(val)
        #__gt__
        val = (dsf > 1).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            0, 1), "(dsf>1).ReadAsArray(0,0,2,1)==%s" % repr(val)
        val = (2 > dsf).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            1, 0), "(2>dsf).ReadAsArray(0,0,2,1)==%s" % repr(val)
        #__ge__
        val = (dsf >= 2).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            0, 1), "(dsf>=2).ReadAsArray(0,0,2,1)==%s" % repr(val)
        val = (1 >= dsf).ReadAsArray(0, 0, 2, 1)
        assert (val[0][0], val[0][1]) == (
            1, 0), "(1>=dsf).ReadAsArray(0,0,2,1)==%s" % repr(val)

        dsf = None
        return 'success'
    except ImportError:
        return 'skip'
    except AssertionError:
        return fail()
    finally:
        try:
            np.seterr(**olderr)
        except:
            pass
        cleanup()
        cleanup('__future__')