def test_BasinClass01(self): files = ["small25", "jebja30", "tunez"] for file in files: # Cargamos flow flw_path = "{}/{}_fd.tif".format(infolder, file) dem_path = "{}/{}.tif".format(infolder, file) dem = DEM(dem_path) fd = Flow(flw_path) # Obtenemos cuencas cuencas = fd.get_drainage_basins(min_area=0.0025) # Mayor, menor, y random bids, counts = np.unique(cuencas.read_array(), return_counts=True) if 0 in bids: bids = bids[1:] counts = counts[1:] idmax = bids[np.argmax(counts)] idmin = bids[np.argmin(counts)] idrdn = np.random.choice(bids) idxs = [idmax, idmin, idrdn] lbls = ["max", "min", "rdn"] for n in range(3): basin = Basin(dem, cuencas, idxs[n]) basin_path = "{}/{}_basin{}.tif".format( outfolder, file, lbls[n]) basin.save(basin_path) basin2 = Basin(basin_path) computed = np.array_equal(basin.read_array(), basin2.read_array()) self.assertEqual(computed, True)
def test_BNetwork_class04(self): """ Test que prueba cabeceras en cuenca 1 con small25 (sin utilizar id field) 474260.9;4114339.6;3 474856.9;4114711.1;2 """ # Cargamos DEM, Flow, Network fd = Flow("{}/{}_fd.tif".format(infolder, "small25")) net = Network("{}/{}_net.dat".format(infolder, "small25")) # Cargamos outlets, heads y generamos cuencas outlets = np.loadtxt("{}/{}_bnet_outlets.txt".format( infolder, "small25"), delimiter=";") heads = np.loadtxt("{}/{}_bnet_heads.txt".format(infolder, "small25"), delimiter=";") # Remove the id column heads = heads[:, :-1] outlets = net.snap_points(outlets) cuencas = fd.get_drainage_basins(outlets) bid = 1 bnet = BNetwork(net, cuencas, heads, bid) self.assertEqual(np.array_equal(bnet._heads, np.array([16171, 13494])), True)
def test_BNetwork_class01(self): """ Test00 Crea BNetwork para cuencas de prueba a partir de un objeto Basin Sin utilizar cabeceras """ files = ["small25", "jebja30", "tunez"] for file in files: # Cargamos DEM, Flow, Network fd = Flow("{}/{}_fd.tif".format(infolder, file)) dem = DEM("{}/{}.tif".format(infolder, file)) net = Network("{}/{}_net.dat".format(infolder, file)) # Cargamos outlets y generamos cuencas outlets = np.loadtxt("{}/{}_bnet_outlets.txt".format( infolder, file), delimiter=";") outlets = net.snap_points(outlets) cuencas = fd.get_drainage_basins(outlets) for bid in np.unique(cuencas.read_array()): if bid == 0: continue basin = Basin(dem, cuencas, bid) bnet = BNetwork(net, basin) # Este test solo verifica que se realice sin fallos y que # el objeto bnet tiene una única cabecera bnet = BNetwork(net, cuencas, None, bid) self.assertEqual(int(bnet._heads[0]), self.results[file][bid])
def test_drainage_basins_05(self): # Test extracting all basins files = ["small25", "morocco", "tunez", "jebja30"] for file in files: flw_path = infolder + "/{0}_fd.tif".format(file) fd = Flow(flw_path) # Extract all basin without min_area basins = fd.get_drainage_basins(min_area=0) basins.save(outfolder + "/all_basins{0}".format(file))
def test_drainage_basins_04(self): # Test extracting all basins (min_area = 10%) files = ["small25", "tunez", "jebja30"] for file in files: flw_path = infolder + "/{0}_fd.tif".format(file) fd = Flow(flw_path) # Extract all basin with min_area basins = fd.get_drainage_basins() basins.save(outfolder + "/all_basins-minarea_{0}.tif".format(file))
def test_drainage_basins_03(self): # Test extracting the biggest basin and input as a list [x, y] files = ["small25", "morocco", "tunez", "jebja30"] for file in files: flw_path = infolder + "/{0}_fd.tif".format(file) fd = Flow(flw_path) # Get coords of the highest flow accumulation fac = fd.get_flow_accumulation() maxval = fac.max() rowpos, colpos = np.where(fac.read_array() == maxval) xi, yi = fd.cell_2_xy(rowpos, colpos) # Extract basin outlets = np.array((xi, yi)).T basins = fd.get_drainage_basins(outlets) basins.save(outfolder + "/max_basin2_{0}".format(file))
def test_drainage_basins_01(self): # Test 10 random basins files = ["small25", "morocco", "tunez", "jebja30"] for file in files: flw_path = infolder + "/{0}_fd.tif".format(file) fd = Flow(flw_path) # Creamos 10 cuencas aleatorias ri = np.random.randint(0, fd._dims[0], 10) ci = np.random.randint(0, fd._dims[1], 10) xi, yi = fd.cell_2_xy(ri, ci) # Extract basins outlets = np.array((xi, yi)).T basins = fd.get_drainage_basins(outlets) basins.save(outfolder + "/rnd_basins_{0}".format(file))
def test_BNetwork_class05(self): """ Test de creado masivo de cuencas con cabeceras aleatorias """ files = ["small25", "jebja30", "tunez"] for file in files: # Cargamos DEM, Flow, Network fd = Flow("{}/{}_fd.tif".format(infolder, file)) net = Network("{}/{}_net.dat".format(infolder, file)) dem = DEM("{}/{}.tif".format(infolder, file)) # Generamos todas las cuencas cuencas = fd.get_drainage_basins(min_area=0.0025) # Generamos 50 puntos aleatorios dentro de la extensión del objeto Network # Estos 50 puntos se usaran como cabeceras xmin, xmax, ymin, ymax = net.get_extent() xi = np.random.randint(xmin, xmax, 50) yi = np.random.randint(ymin, ymax, 50) heads = np.array((xi, yi)).T # Cogemos 5 cuencas aleatorias bids = np.random.choice(np.unique(cuencas.read_array())[1:], 5) for bid in bids: try: if np.random.randint(100) < 70: bnet = BNetwork(net, cuencas, heads, bid) else: basin = Basin(dem, cuencas, bid) bnet = BNetwork(net, basin, heads) except NetworkError: print( "Network of {} file inside the basin {} has not enough pixels" .format(file, bid)) continue # Salvamos BNetwork y volvemos a cargar para comprobar que se cargan-guardan bien bnet_path = "{}/{}_{}_bnet.dat".format(outfolder, file, bid) bnet.save(bnet_path) bnet2 = BNetwork(bnet_path) computed = np.array_equal(bnet._ix, bnet2._ix) self.assertEqual(computed, True) # borramos archivo os.remove(bnet_path)
def test_drainage_basins_00(self): # Test 10 random basins files = ["small25", "tunez", "jebja30"] for file in files: flw_path = infolder + "/{0}_fd.tif".format(file) fd = Flow(flw_path) # Creamos 10 cuencas aleatorias ri = np.random.randint(0, fd.get_dims()[0], 10) ci = np.random.randint(0, fd.get_dims()[1], 10) rdn_ids = np.random.randint(100, 700, 10) xi, yi = fd.cell_2_xy(ri, ci) # Extract basins outlets = np.array((xi, yi, rdn_ids)).T threshold = int(fd.get_ncells() * 0.05) snap_outlets = fd.snap_points(outlets, threshold, kind="channel") snap = np.append(snap_outlets, rdn_ids.reshape(rdn_ids.size, 1), 1) basins = fd.get_drainage_basins(snap) basins.save(outfolder + "/rnd_snap_basins_{0}.tif".format(file))
def test_BNetwork_class00(self): """ Test00 Crea BNetwork para cuencas de prueba a partir de un Grid de cuencas Sin utilizar cabeceras """ files = ["small25", "jebja30", "tunez"] for file in files: # Cargamos DEM, Flow, Network fd = Flow("{}/{}_fd.tif".format(infolder, file)) net = Network("{}/{}_net.dat".format(infolder, file)) # Cargamos outlets y generamos cuencas outlets = np.loadtxt("{}/{}_bnet_outlets.txt".format( infolder, file), delimiter=";") outlets = net.snap_points(outlets) cuencas = fd.get_drainage_basins(outlets) for bid in np.unique(cuencas.read_array()): if bid == 0: continue bnet = BNetwork(net, cuencas, None, bid) self.assertEqual(int(bnet._heads[0]), self.results[file][bid])
from topopy import Network, DEM, Flow, Grid import matplotlib.pyplot as plt import numpy as np infolder = "../data/in" outfolder = "../data/out" dem = DEM(infolder + "/morocco.tif") fd = Flow(dem) net = Network(dem, fd, 1500) streams = net.get_streams() streams.save(outfolder + "/canales_orig.tif") outlet = np.array([579213, 504282]).reshape(1, 2) basin = fd.get_drainage_basins(net.snap_points(outlet), asgrid=False) c1 = basin.max(axis=0).argmax() r1 = basin.max(axis=1).argmax() c2 = basin.shape[1] - np.fliplr(basin).max(axis=0).argmax() r2 = basin.shape[0] - np.flipud(basin).max(axis=1).argmax() basin_cl = basin[r1:r2, c1:c2] nrow = basin_cl.shape[0] ncol = basin_cl.shape[1] outgrid = Grid() outgrid._size = (ncol, nrow) outgrid._dims = (nrow, ncol) geot = net._geot ULx = geot[0] + geot[1] * c1 ULy = geot[3] + geot[5] * r1
# -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal """ from topopy import Network, Channel, Flow, BNetwork import ogr import numpy as np import matplotlib.pyplot as plt fd = Flow("../data/in/jebja30_fd.tif") net = Network("../data/in/jebja30_net.dat") cuencas = fd.get_drainage_basins() bnet1 = BNetwork(net, cuencas, None, 3) bnet2 = BNetwork(net, cuencas, None, 10) shp_path = "../data/out/canales_basin.shp" bnet1.export_to_shp(shp_path, True) dataset = ogr.Open(shp_path) layer = dataset.GetLayer(0) canales = [] for n in range(layer.GetFeatureCount()): feat = layer.GetFeature(n) geom = feat.GetGeometryRef() head = geom.GetPoint(0) mouth = geom.GetPoint(geom.GetPointCount() - 1)