def add_rasters(self, path, indexdict=None, qv=None): """ Add any raster bands from raster-file as Raster Parameters ---------- path : str Path to raster-file indexdict : dict, optional Contains names for raster-indices, where key is GDAL-Band index and value is the key for the Raster in Collection.rasters qv : int, optional Quantification value """ # open GDAL-Dataset dataset = gdal.Open(path) ct = transformation_from_dataset(dataset) if indexdict == None: # add all rasters to indexdict keys = range(1, dataset.RasterCount + 1) rc = len(self.rasters) names = range(len(self.rasters), len(self.rasters) + dataset.RasterCount) indexdict = dict(zip(keys, names)) for index, name in indexdict.items(): # add raster-band as Raster to Collection.rasters self.rasters[name] = Raster(dataset, index, qv, ct) self._datasets.append(dataset)
def propagateFromRidges(self, valleyDepthsFile, dirRaster, accRaster): """ Propagate relative heights of nearest ridge points along flow paths, starting from points with accumulation 1. Heights are put into ridgeHeightsRaster. Distances from ridge are put into ridgeDistancesRaster If a point already has a height, but the new path is shorter, the new height overwrites the old. """ time1 = time.process_time() self.valleyDepthsRaster = Raster(valleyDepthsFile, self._gv, canWrite=False, isInt=False) res = self.valleyDepthsRaster.open(self.chunkCount) if not res: return reportFailure = True pathLength = 0 # path length counted in pixels (horizontal and vertical assumed same, so 1) diag = math.sqrt(2) for row in range(self.numRows): for col in range(self.numCols): if accRaster.read(row, col) == 1: elevation, pathLength = self.getRidgeElevation( row, col, reportFailure) if pathLength < 0: if reportFailure: reportFailure = False elevation = self.demRaster.read(row, col) pathLength = 0 nextRow, nextCol = row, col while True: nextElev = self.demRaster.read(nextRow, nextCol) if nextElev == self.demNoData: break currentPathLength = self.ridgeDistancesRaster.read( nextRow, nextCol) if currentPathLength >= 0: # have a previously stored value if pathLength < currentPathLength: # new path length from ridge is shorter: update heights raster self.ridgeHeightsRaster.write( nextRow, nextCol, elevation - nextElev) self.ridgeDistancesRaster.write( nextRow, nextCol, pathLength) else: # already had shorter path from ridge - no point in continuing down flow path break else: # no value stored yet self.ridgeHeightsRaster.write( nextRow, nextCol, elevation - nextElev) self.ridgeDistancesRaster.write( nextRow, nextCol, pathLength) pt, isDiag = self.alongDirPoint( nextRow, nextCol, dirRaster) if pt is None: break pathLength += diag if isDiag else 1 nextRow, nextCol = pt time2 = time.process_time() QSWATUtils.loginfo('Propagating ridge points took {0} seconds'.format( int(time2 - time1)))
def start(self): laser_width = self.args.kerf[0] border_size = self.args.border[0] output_file = self.args.output[0] if self.args.output else None layer_height = self.args.height[0] back_and_forth = self.args.alternate_raster if self.args.file: raster = Raster(laser_width, border_size, output_file, layer_height, back_and_forth=back_and_forth) raster.process_file(self.args.file[0]) else: raster = Raster(laser_width, border_size, output_file, layer_height, back_and_forth=back_and_forth) raster.process_folder(self.args.directory[0])
def read_layer(filename): """Read spatial layer from file. This can be either raster or vector data. """ _, ext = os.path.splitext(filename) if ext in ['.asc', '.tif', '.nc']: return Raster(filename) elif ext in ['.shp', '.sqlite']: return Vector(filename) else: msg = ('Could not read %s. ' 'Extension "%s" has not been implemented' % (filename, ext)) raise ReadLayerError(msg)
def make_tiles(r_analytic, images_path, output_filepath, window_size, idx, overlap, dtype, scaling_type): """Create tiles from satellite image, save to file and return number of tiles created.""" meta_data_filename = get_meta_data_filename(images_path, r_analytic.name) r_visual_rgb_filename = get_rgb_filename(images_path, r_analytic.name) # instantiate raster class raster = Raster(r_analytic, r_visual_rgb_filename, meta_data_filename) # ** create tiles ** num_tiles = raster.to_tiles(output_path=output_filepath, window_size=window_size, idx=idx, overlap=overlap, dtype=dtype, scaling_type=scaling_type) return num_tiles
def raster_test(): doc = Document("Untitled-1") width = 100 height = 100 image = Image.new("L", (width, height)) draw = ImageDraw.Draw(image) draw_circle(draw, width / 2, height / 2, width / 2 - 10, 255) draw_circle(draw, width * 3 / 4, height / 4, width / 5, 0) image.save("prntest.png") raster = Raster(image, 100, 100, 100, 100) doc.addRaster(raster) return doc
def __init__(self, year_list, data_dir): ''' year_list: a numeric list of years which are took into account when calculating climatic covariates ''' def GetRefRaster(data_dir): for (subdirpath, subdirname, filenames) in walk(data_dir): for f in filenames: if f.split('.')[-1].lower()[:3] == 'tif': return join(subdirpath, f) self.years = year_list self.dir = data_dir self.raster = Raster() self.ref_raster = GetRefRaster(self.dir) self.ref_array = self.raster.getRasterArray(self.ref_raster) self.no_data = self.raster.getNoDataValue(self.ref_raster)
def write_raster_data(data, projection, geotransform, filename, keywords=None): """Write array to raster file with specified metadata and one data layer Input: data: Numpy array containing grid data projection: WKT projection information geotransform: 6 digit vector (top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution). See e.g. http://www.gdal.org/gdal_tutorial.html filename: Output filename keywords: Optional dictionary Note: The only format implemented is GTiff and the extension must be .tif """ R = Raster(data, projection, geotransform, keywords=keywords) R.write_to_file(filename)
def makeRidgeRaster(self): """Make raster to show ridges.""" ridgeFile = QSWATUtils.join(self._gv.demDir, 'ridge' + str(self.branchThresh) + '.tif') ridgeRaster = Raster(ridgeFile, self._gv, canWrite=True, isInt=True) res = ridgeRaster.open(self.chunkCount, numRows=self.numRows, numCols=self.numCols, transform=self.demTransform, projection=self.demProjection, noData=self.noData) if not res: return for row in range(self.numRows): for col in range(self.numCols): if self.demRaster.read(row, col) != self.demNoData: val, _ = self.ridgePoints.get((row, col), (-1, -1)) ridgeRaster.write(row, col, 0 if val == -1 else 1) ridgeRaster.close()
def add_event_series(self, am_Model, road_width, deposition_pattern, power, layer_break): self.write('#EVENT SERIES\n') part = am_Model.get_part() amModel_name = am_Model.get_amModel_name() AM_model_name = 'mdb.customData.am.amModels["' + amModel_name + '"]' add_element = part.get_features()['add_element'] base_element = part.get_features()['base_element'] #depth of add_element depth = add_element.get_depth() #thickness of each layer thickness = add_element.get_layer_thickness() #road_width am_Model.set_road_width(road_width) #corner coordinate point1 = add_element.get_point1() corner_x = point1[0] corner_y = point1[1] corner_z = base_element.get_depth() #x and y length of add_element point2 = add_element.get_point2() x_length = abs(point1[0] - point2[0]) y_length = abs(point1[1] - point2[1]) if deposition_pattern.lower() == 'raster': #__init__(self, z_length, thickness, x_length, y_length, corner_x, corner_y, corner_z, road_width,P): dp_object = Raster(depth, thickness, x_length, y_length, corner_x, corner_y, corner_z, road_width, power, layer_break) elif deposition_pattern.lower() == 'zigzag': #__init__(self, z_length, thickness, x_length, y_length, corner_x, corner_y, corner_z, road_width,P): dp_object = Zigzag(depth, thickness, x_length, y_length, corner_x, corner_y, corner_z, road_width, power, layer_break) else: raise NotImplementedError( 'This deposition pattern is not implemented') dp_object.generate_heat_path() dp_object.generate_material_path() material_path = pathlib.Path('material_path.txt') material_path = material_path.resolve() heat_path = pathlib.Path('heat_path.txt') heat_path = heat_path.resolve() self.write( AM_model_name + '.addEventSeries(eventSeriesName="material_path", eventSeriesTypeName=' + "'" + '"ABQ_AM.MaterialDeposition"' + "'" + ', timeSpan="TOTAL TIME", fileName="' + str(material_path) + '", isFile=ON)\n') self.write( AM_model_name + '.addEventSeries(eventSeriesName="heat_path", eventSeriesTypeName=' + "'" + '"ABQ_AM.PowerMagnitude"' + "'" + ', timeSpan="TOTAL TIME", fileName="' + str(heat_path) + '", isFile=ON)\n') self.seperate_sec()
def create_climate_covariates(self, climate_dir, start_year, end_year, key_min, key_max, key_pcp, out_dir): abstemp = 273.15 year_list = cc.getYearList(start_year, end_year) climate_covariate = cc.ClimaticCovariates(year_list, climate_dir) ref_raster = climate_covariate.ref_raster out_raster = Raster() crops_id = [] crops = [] with self.conn as cur: rows = cur.execute("select * from crop").fetchall() if rows: print('Start to generate climate covariates...') for row in rows: crops_id.append(row['id']) crops.append(row['crop']) for crop_id, crop in zip(crops_id, crops): print(crop) with self.conn as cur: covariates = cur.execute( "select * from covariate_threshold where crop_id=?", (crop_id, )).fetchall() if covariates: for covariate in covariates: with self.conn as cur: covariate_name = cur.execute( "select covariate from Covariate where id=?", (covariate['covariate_id'], )).fetchone()['covariate'] print('Generate {} at {} ...'.format( covariate_name, dt.datetime.now())) if covariate['t_below'] is not None: try: t_below = float(covariate['t_below']) + abstemp except ValueError: t_below = None else: t_below = None if covariate['t_above'] is not None: try: t_above = float(covariate['t_above']) + abstemp except ValueError: t_above = None else: t_above = None if covariate['pcp_above'] is not None: try: pcp_above = float(covariate['pcp_above']) except ValueError: pcp_above = None else: pcp_above = None if covariate['pcp_below'] is not None: try: pcp_below = float(covariate['pcp_below']) except ValueError: pcp_below = None else: pcp_below = None out_sub_dir = join(out_dir, crop) if not os.path.exists(out_sub_dir): os.makedirs(out_sub_dir, exist_ok=True) covariate_array = cc.generate( covariate['covariate_id'], year_list, climate_dir, covariate['start_date'], covariate['end_date'], key_min, key_max, key_pcp, t_below, t_above, pcp_above, pcp_below, out_sub_dir, crop_id, covariate['covariate_id'], ref_raster) try: if covariate_array is not None: out_raster_file = join( out_sub_dir, '{}_{}_{}_{}.tif'.format( crop_id, covariate['covariate_id'], start_year, end_year)) out_raster.array2Raster( covariate_array, ref_raster, out_raster_file) except: pass
# -*- coding: utf-8 -*- """ Created on Mon Jul 2 15:53:48 2018 @author: guoj """ from osgeo import gdal, ogr, osr from os.path import join import numpy as np from raster import Raster rst = Raster() class GeoProcessing(object): def __init__(self, no_data): self.no_data = no_data def strip_end(self, text, suffix): if not text.endswith(suffix): return text return text[:len(text)-len(suffix)] def strip_start(self, text, suffix): if not text.startswith(suffix): return text return text[len(suffix):] def reproject_raster2(self, dataset, refdataset, outrst): g = gdal.Open(dataset)
timeSteps = [] Helios = helios.DAC() try: """ stats = { 'frameNum': 0, 'startTime': time.time(), 'lastTime': time.time(), 'curTime': time.time(), 'timeStep': 0.01, ' """ clem = Raster('clementine.png') clock = Clock() frameNum = 0 startTime = time.time() lastTime = startTime while True: curTime = time.time() timeStep = curTime - lastTime timeSteps.append(timeStep) elapsed = curTime - startTime frameNum += 1 fps = 1 / timeStep if frameNum % msgOutputInterval == 0: print "\rFrame", frameNum, "Elapsed", elapsed, \ "Time Step", timeStep, "Fps", fps, \
def calcRidgeHeightsByInversion(self, ridgep, ridges, root, mustRun): """ Create the ridgeHeightsRaster with differences between the elevation at the point and the elevation of the nearest ridge cell. ridgep is the D8 flow directions and ridges the flow accumulation raster , both calculated from an inverted DEM. """ self.ridgeHeightsFile = QSWATUtils.join(self._gv.demDir, 'invheights.tif') if mustRun or not QSWATUtils.isUpToDate( ridgep, self.ridgeHeightsFile) or not QSWATUtils.isUpToDate( ridges, self.ridgeHeightsFile): self._gv.clearOpenRasters() completed = False while not completed: try: completed = True # only gets set on MemoryError exception if os.path.exists(self.ridgeHeightsFile): QSWATUtils.tryRemoveLayerAndFiles( self.ridgeHeightsFile, root) self.ridgeHeightsRaster = Raster(self.ridgeHeightsFile, self._gv, canWrite=True, isInt=False) res = self.ridgeHeightsRaster.open( self.chunkCount, numRows=self.numRows, numCols=self.numCols, transform=self.demTransform, projection=self.demProjection, noData=self.noData) if not res: return False # ridgep obtained by inversion has float values, although these are in the range 1 to 8 ridgepRaster = Raster(ridgep, self._gv, canWrite=False, isInt=False) res = ridgepRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return False ridgesRaster = Raster(ridges, self._gv, canWrite=False, isInt=True) res = ridgesRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return False for row in range(self.numRows): for col in range(self.numCols): if self.demRaster.read(row, col) != self.demNoData: (val, path) = self.valueAtNearest( row, col, ridgepRaster, ridgesRaster, self.ridgeThresh) if path is not None: self.propagate(val, path) ridgepRaster.close() ridgesRaster.close() self.ridgeHeightsRaster.close() return True except MemoryError: QSWATUtils.loginfo( 'Out of memory for ridge heights by inversion with chunk count {0}' .format(self.chunkCount)) self._gv.closeOpenRasters() completed = False self.chunkCount += 1 if not self.demRaster.open(self.chunkCount): return False else: return True
from shapely.geometry import Point from raster import Raster """ USAGE: ./reachID_grid_to_vector_points.py <flows_grid_IDs raster file> <flows_points vector file> <reachID or featureID> """ path = sys.argv[1] outputFileName = sys.argv[2] writeOption = sys.argv[3] #r = gdal.Open(path) #band = r.GetRasterBand(1) boolean=Raster(path) #(upper_left_x, x_size, x_rotation, upper_left_y, y_rotation, y_size) = r.GetGeoTransform() (upper_left_x, x_size, x_rotation, upper_left_y, y_rotation, y_size) = boolean.gt #a = band.ReadAsArray().astype(np.float) # indices = np.nonzero(a != band.GetNoDataValue()) indices = np.nonzero(boolean.array >= 1) # Init the shapefile stuff.. #srs = osgeo.osr.SpatialReference() #srs.ImportFromWkt(r.GetProjection()) #driver = osgeo.ogr.GetDriverByName('GPKG') #shapeData = driver.CreateDataSource(outputFileName)
def mapping(self, crop_id, covariate_rasters, conn, covariate_root_dir, suit_root_dir): raster = Raster() self.no_data = raster.getNoDataValue(covariate_rasters[-1]) ref_rst = covariate_rasters[-1] covariate_id_list = [] suit_array_stack = [] filepath = strip_end(ref_rst, ref_rst.split('\\')[-1]) out_dir = join( suit_root_dir, strip_start(filepath, covariate_root_dir)[1:] ) # the [1:] is for removing the first and the last '\' of string if not os.path.exists(out_dir): os.makedirs(out_dir, exist_ok=True) for rst in covariate_rasters: filename = rst.split('\\')[-1].split('.')[0] if len(filename.split('_')) == 1: covariate_id = filename covariate_id_list.append(covariate_id) out_raster = join( out_dir, 'suitability_{}_{}.tif'.format(crop_id, covariate_id)) else: covariate_id = filename.split('_')[1] covariate_id_list.append(covariate_id) time_span = '{}_{}'.format( filename.split('_')[-2], filename.split('_')[-1]) out_raster = join( out_dir, 'suitability_{}_{}_{}.tif'.format(crop_id, covariate_id, time_span)) with conn as cur: rows = cur.execute( "select * from suitability_rule where crop_id=? and covariate_id=? order by suitability_level", ( crop_id, covariate_id, )).fetchall() is_continual = cur.execute( "select * from Covariate where id=?", (covariate_id, )).fetchone()['iscontinual'] # If the query returns none then move to the next covariate if rows: covariate_array = raster.getRasterArray( rst) # array of the covariate if is_continual == 1: suit_array = self.__reclassify_contianual__( covariate_array, rows) else: suit_array = self.__reclassify_catorgorical__( covariate_array, rows) suit_array[np.where( covariate_array == self.no_data)] = self.no_data raster.array2Raster(suit_array, ref_rst, out_raster) suit_array_stack.append(suit_array) else: print( 'Warning! Suitability ruleset for {}, {} not found! Please check the database.' .format(crop_id, covariate_id)) if len(suit_array_stack) > 0: crop_suit_array = ExtractMaxValueOfStack(suit_array_stack) ref_array = homogenize_nodata_area(suit_array_stack, self.no_data) crop_suit_array[np.where(ref_array == self.no_data)] = self.no_data crop_suit_raster = join(out_dir, '{}_suitability.tif'.format(crop_id)) raster.array2Raster(crop_suit_array, ref_rst, crop_suit_raster) print('create dominant worst covariate raster at {}...'.format( dt.datetime.now())) worst_dominant_array, worst_count_array, worst_dominant_legend_list = ExtractMaxValueIndexBinaryOfStack( suit_array_stack, covariate_id_list, 4) worst_dominant_array[np.where( ref_array == self.no_data)] = self.no_data worst_dominant_raster_file = join( out_dir, '{}_worst_dominant.tif'.format(crop_id)) raster.array2Raster(worst_dominant_array, ref_rst, worst_dominant_raster_file) worst_count_array[np.where( ref_array == self.no_data)] = self.no_data worst_count_raster_file = join( out_dir, '{}_worst_count.tif'.format(crop_id)) raster.array2Raster(worst_count_array, ref_rst, worst_count_raster_file) worst_dominant_legend_csv = join( out_dir, '{}_worst_dominant_legend.csv'.format(crop_id)) csvw = CSVOperation.CSVWriting() headers = ['raster value', 'number of restriction', 'covariates'] csvw.WriteLines(worst_dominant_legend_csv, headers, worst_dominant_legend_list) else: print('Warning! No suitability map for {} was created!'.format( crop_id))
avg_foss_si = (foss_sinuosity['arc_lengths'] / foss_sinuosity['straight_lengths']).mean() print(avg_esri_si, avg_foss_si, avg_esri_si / avg_foss_si) # SRCS's with open(esri_src_fileName, 'r') as f: esri_src = json.load(f) with open(foss_src_fileName, 'r') as f: foss_src = json.load(f) esri_cw = pd.read_csv(esri_cw_fileName, dtype=int) foss_cw = pd.read_csv(foss_cw_fileName, dtype=int) esri_rem = Raster(esri_rem_fileName) foss_rem = Raster(foss_rem_fileName) esri_src_table = pd.read_csv(esri_src_table_fileName, dtype={ 'A': float, 'B': float, 'H': float, 'Length_m': float, 'P': float, 'R': float, 'HydroID': int, 'Q': float }) foss_src_table = pd.read_csv(foss_src_table_fileName, dtype={
def writeFloodPlain(self, valleyDepthsFile, mustRun): """Calculate slope positions from valleyDepths and ridgeHeights, and write floodplain raster .""" method = 'inv' if self.useInversion else 'branch' thresh = '{0:.2F}'.format(self.floodThresh).replace('.', '_') flood = QSWATUtils.join(self._gv.floodDir, method + 'flood' + thresh + '.tif') root = QgsProject.instance().layerTreeRoot() if mustRun or \ not QSWATUtils.isUpToDate(valleyDepthsFile, flood) or \ not QSWATUtils.isUpToDate(self.ridgeHeightsFile, flood): if os.path.exists(flood): QSWATUtils.tryRemoveLayerAndFiles(flood, root) self._gv.clearOpenRasters() completed = False while not completed: try: completed = True # only gets set on MemoryError exception self.ridgeHeightsRaster = Raster(self.ridgeHeightsFile, self._gv, canWrite=False, isInt=False) res = self.ridgeHeightsRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return if self.valleyDepthsRaster is None: # may have been opened when calculating ridge heights by branch length self.valleyDepthsRaster = Raster(valleyDepthsFile, self._gv, canWrite=False, isInt=False) res = self.valleyDepthsRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return self._progress('Flood plain...') self.floodplainRaster = Raster(flood, self._gv, canWrite=True, isInt=True) OK = self.floodplainRaster.open( self.chunkCount, numRows=self.numRows, numCols=self.numCols, transform=self.demTransform, projection=self.demProjection, noData=self.noData) if OK: self.calcFloodPlain1() self.floodplainRaster.close() ## fixing aux.xml file seems unnecessary in QGIS 2.16 # # now fix maximum value to 1 instead of zero in aux.xml file # # else if loaded has legend 0 to nan and display is all black # xmlFile = self.floodplainRaster.fileName + '.aux.xml' # ok, err = QSWATUtils.setXMLValue(xmlFile, u'MDI', u'key', u'STATISTICS_MAXIMUM', u'1') # if not ok: # QSWATUtils.error(err, self._gv.isBatch) QSWATUtils.copyPrj(self.demRaster.fileName, self.floodplainRaster.fileName) # load flood above DEM layers = root.findLayers() demLayer = QSWATUtils.getLayerByLegend( FileTypes.legend(FileTypes._DEM), layers) ft = FileTypes._INVFLOOD if self.useInversion else FileTypes._BRANCHFLOOD floodLayer, _ = QSWATUtils.getLayerByFilename( layers, self.floodplainRaster.fileName, ft, self._gv, demLayer, QSWATUtils._WATERSHED_GROUP_NAME) if floodLayer is None: QSWATUtils.error('Failed to load floodplain raster {0}' \ .format(self.floodplainRaster.fileName), self._gv.isBatch) self.valleyDepthsRaster.close() self.ridgeHeightsRaster.close() self._progress('Flood plain done') except MemoryError: QSWATUtils.loginfo( 'Out of memory for flood plain with chunk count {0}'. format(self.chunkCount)) self._gv.closeOpenRasters() completed = False self.chunkCount += 1 else: # already have uptodate flood file: make sure it is loaded # load flood above DEM layers = root.findLayers() demLayer = QSWATUtils.getLayerByLegend( FileTypes.legend(FileTypes._DEM), layers) ft = FileTypes._INVFLOOD if self.useInversion else FileTypes._BRANCHFLOOD floodLayer, _ = QSWATUtils.getLayerByFilename( layers, flood, ft, self._gv, demLayer, QSWATUtils._WATERSHED_GROUP_NAME) if floodLayer is None: QSWATUtils.error('Failed to load floodplain raster {0}' \ .format(self.floodplainRaster.fileName), self._gv.isBatch)
def calRidgeHeghtsByBranchLength(self, subbasins, distances, slopeDir, flowAcc, valleyDepthsFile, root, mustRun): """ Create the ridgeHeightsRaster with differences between the elevation at the point and the elevation of the nearest ridge cell. subbasins is the subbasins raster, distances is the distances to outlet raster, slopeDir is the D8 slope directions raster, flowAcc the flow accumulation raster, all four clipped the same as the DEM. valleyDepthsFile is the existing raster giving the depth of the valley flow below each point (as a positive number of metres). """ self.ridgeHeightsFile = QSWATUtils.join(self._gv.demDir, 'branchheights.tif') distancesFile = QSWATUtils.join(self._gv.demDir, 'branchdistancess.tif') if mustRun or not QSWATUtils.isUpToDate(subbasins, self.ridgeHeightsFile) \ or not QSWATUtils.isUpToDate(distances, self.ridgeHeightsFile) \ or not QSWATUtils.isUpToDate(slopeDir, self.ridgeHeightsFile) \ or not QSWATUtils.isUpToDate(flowAcc, self.ridgeHeightsFile): self._gv.clearOpenRasters() completed = False while not completed: try: completed = True # only gets set on MemoryError exception if os.path.exists(self.ridgeHeightsFile): QSWATUtils.tryRemoveLayerAndFiles( self.ridgeHeightsFile, root) if os.path.exists(distancesFile): QSWATUtils.tryRemoveLayerAndFiles(distancesFile, root) self.ridgeHeightsRaster = Raster(self.ridgeHeightsFile, self._gv, canWrite=True, isInt=False) res = self.ridgeHeightsRaster.open( self.chunkCount, numRows=self.numRows, numCols=self.numCols, transform=self.demTransform, projection=self.demProjection, noData=self.noData) if not res: return False self.ridgeDistancesRaster = Raster(distancesFile, self._gv, canWrite=True, isInt=False) res = self.ridgeDistancesRaster.open( self.chunkCount, numRows=self.numRows, numCols=self.numCols, transform=self.demTransform, projection=self.demProjection, noData=self.noData) if not res: self._gv.closeOpenRasters() return False subbasinsRaster = Raster(subbasins, self._gv, canWrite=False, isInt=True) res = subbasinsRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return False distRaster = Raster(distances, self._gv, canWrite=False, isInt=False) res = distRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return False self.findRidges(subbasinsRaster, distRaster, root) subbasinsRaster.close() distRaster.close() accRaster = Raster(flowAcc, self._gv, canWrite=False, isInt=True) res = accRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return False dirRaster = Raster(slopeDir, self._gv, canWrite=False, isInt=True) res = dirRaster.open(self.chunkCount) if not res: self._gv.closeOpenRasters() return False self.propagateFromRidges(valleyDepthsFile, dirRaster, accRaster) dirRaster.close() accRaster.close() self.ridgeHeightsRaster.close() self.ridgeDistancesRaster.close() return True except MemoryError: QSWATUtils.loginfo( 'Out of memory for ridge heights by branch length with chunk count {0}' .format(self.chunkCount)) self._gv.closeOpenRasters() completed = False self.chunkCount += 1 if not self.demRaster.open(self.chunkCount): return False else: return True