def main(): args = setArguments() esriGrid = ASC() try: esriGrid.loadFromFile(args.inputFile) except (ValueError, IOError) as ex: print("Error loading the raster %s: %s" % (args.inputFile, ex)) sys.exit() esriArea = math.pow(esriGrid.size, 2) hexArea = 0 # Preserve spatial resolution: increase cell area. if (args.resolution): hexArea = esriArea * RES_FACTOR # Use area provided. elif (args.area > 0): hexArea = args.area # Preserve cell area: used the same as the original raster. else: hexArea = esriArea # Compute hexagonal cell geometry as function of area hexSide = math.sqrt(2 * hexArea / (3 * math.sqrt(3))) hexRaster = HASC() hexRaster.initWithExtent(hexSide, esriGrid.xll, esriGrid.yll, esriGrid.xll + esriGrid.ncols * esriGrid.size, esriGrid.yll + esriGrid.nrows * esriGrid.size) print("Geometries:" + "\n Input square cell area : " + str(esriArea) + "\n Hexagon cell area : " + str(hexArea) + "\n Hexagon side length : " + str(hexSide) + "\n Hexagon perpendicular : " + str(hexRaster.hexPerp) + "\n Number of rows in mesh : " + str(hexRaster.nrows) + "\n Number of columns in mesh : " + str(hexRaster.ncols)) if (args.method == Method.MULTIQUADRATIC.value[0]): interpol = esriGrid.interpolMultiquadratic print("\nConverting with Multi-quadratic interpolation ...") else: interpol = esriGrid.getNearestNeighbour print("\nConverting with Nearest Neighbour interpolation ...") for j in range(hexRaster.nrows): for i in range(hexRaster.ncols): x, y = hexRaster.getCellCentroidCoords(i, j) hexRaster.set(i, j, interpol(x, y)) try: hexRaster.save(args.outputFile) except (ValueError, IOError) as ex: print("Error saving output file %s: %s" % (args.outputFile, ex)) print("Finished successfully.")
def createChoropleth(self, layer, min, max, num_classes=10): myTargetField = HASC().valueField myRangeList = [] myOpacity = 1 step = (max - min) / num_classes col_step = 256 / (num_classes - 1) for i in range(num_classes): label = str(min + step * i) + " - " + str(min + step * (i + 1)) hex_level = hex(int(col_step * i)).split('x')[1] if (len(hex_level) < 2): hex_level = "0" + hex_level colour = "#" + hex_level + hex_level + hex_level symbol = QgsFillSymbolV2.createSimple({ 'color': colour, 'color_border': colour, 'width_border': '0' }) symbol.setAlpha(myOpacity) myRangeList.append( QgsRendererRangeV2(min + step * i, min + step * (i + 1), symbol, label)) renderer = QgsGraduatedSymbolRendererV2('', myRangeList) renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) renderer.setClassAttribute(myTargetField) layer.setRendererV2(renderer)
def main(): args = setArguments() esriGrid = ASC() try: esriGrid.loadFromFile(args.inputFile) except (ValueError, IOError) as ex: print("Error loading the raster %s: %s" % (args.inputFile, ex)) sys.exit() esriArea = math.pow(esriGrid.size, 2) hexArea = 0 # Preserve spatial resolution: increase cell area. if (args.resolution): hexArea = esriArea * RES_FACTOR # Use area provided. elif (args.area > 0): hexArea = args.area # Preserve cell area: used the same as the original raster. else: hexArea = esriArea # Compute hexagonal cell geometry as function of area hexSide = math.sqrt(2 * hexArea / (3 * math.sqrt(3))) hexRaster = HASC() hexRaster.initWithExtent(hexSide, esriGrid.xll, esriGrid.yll, esriGrid.ncols * esriGrid.size, esriGrid.nrows * esriGrid.size) print("Geometries:" + "\n Input square cell area : " + str(esriArea) + "\n Hexagon cell area : " + str(hexArea) + "\n Hexagon side length : " + str(hexSide) + "\n Hexagon perpendicular : " + str(hexRaster.hexPerp) + "\n Number of rows in mesh : " + str(hexRaster.nrows) + "\n Number of columns in mesh : " + str(hexRaster.ncols)) print("\nConverting ...") if(args.method == Method.MULTIQUADRATIC): interpol = esriGrid.interpolMultiquadratic else: interpol = esriGrid.getNearestNeighbour for j in range(hexRaster.nrows): for i in range(hexRaster.ncols): x, y = hexRaster.getCellCentroidCoords(i, j) hexRaster.set(i, j, interpol(x, y)) try: hexRaster.save(args.outputFile) except (ValueError, IOError) as ex: print ("Error saving output file %s: %s" % (args.outputFile, ex)) print ("Finished successfully.")
def main(): processArguments(sys.argv) hexRaster = HASC() try: hexRaster.loadFromFile(inputFile) except (ValueError, IOError) as ex: print("Error loading the raster %s: %s" % (inputFile, ex)) sys.exit() print ("Loaded input HASC, converting...") try: hexRaster.saveAsGML(outputFile) except (ImportError, IOError) as ex: print("Error saving the raster %s: %s" % (inputFile, ex)) sys.exit() print ("Conversion successfully completed.")
def main(): options, flags = gscript.parser() input = options['input'] output = options['output'] if (output is None or output == ""): gscript.error(_("[h.in] ERROR: output is a mandatory parameter.")) exit() # Load HexASCII raster into memory hexASCII = HASC() try: hexASCII.loadFromFile(input) except (ValueError, IOError) as ex: gscript.error( _("[h.in] ERROR: Failed to load raster %s: %s" % (input, ex))) exit() # Set region (note that it is tricking GRASS to think it is a squared raster) gscript.run_command('g.region', rows=hexASCII.nrows, cols=hexASCII.ncols, res=hexASCII.side) # Create RasterRow object and iterate trough rows newRast = raster.RasterRow(output) newRast.open('w', 'FCELL') for row in range(0, hexASCII.nrows): newRow = Buffer(shape=(1, hexASCII.ncols)) #, dtype=float, order='F') for col in range(0, hexASCII.ncols): newRow[0, col] = hexASCII.get(col, row) gscript.message(_("[h.in] DEBUG: Importing row: %s" % newRow)) newRast.put_row(newRow) gscript.message(_("[h.in] DEBUG: Imported raster: %s" % (newRast))) # Close RasterRow to force its creation newRast.close() gscript.message(_("[h.in] SUCCESS: HexASCII raster imported."))
def main(): options, flags = gscript.parser() input = options['input'] output = options['output'] if (input is None or input == ""): gscript.error(_("[h.out] ERROR: input is a mandatory parameter.")) exit() exists = False maps_list = utils.findmaps(type='raster') for map in maps_list: if input == map[0]: exists = True break if (not exists): gscript.error(_("[h.out] ERROR: could not find input map.")) exit() if (output is None or output == ""): gscript.error(_("[h.out] ERROR: output is a mandatory parameter.")) exit() rast = raster.RasterRow(input) # Set region (note that it is tricking GRASS to think it is a squared raster) info = gscript.read_command('r.info', map=input, flags='g') info = info.split("\n") print(info[6]) hexASCII = HASC() # This can probably be set from the RasterRow object hexASCII.init( int(info[7].split("=")[1]), #ncols, int(info[6].split("=")[1]), #nrows, int(info[3].split("=")[1]), #xll, int(info[1].split("=")[1]), #yll, "NA") #nodata) r = 0 rast.open() for row in rast: for c in range(0, rast.info.cols): hexASCII.set(c, r, row[c]) gscript.message(_("[h.in] DEBUG: Exporting row: %s" % newRow)) r = r + 1 gscript.message(_("[h.out] SUCCESS: HexASCII raster exported."))
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. fileName = self.dlg.lineEdit.text() # Load the HexASCII file hexASCII = HASC() try: hexASCII.loadFromFile(fileName) hexASCII.saveAsGML(fileName + ".gml") except (ValueError, IOError) as ex: self.iface.messageBar().pushMessage( "Error", "Failed to load the raster %s: %s" % (fileName, ex), level=QgsMessageBar.CRITICAL) # Add HexASCII to the layer heap vector = fileName.split("/") layerName = vector[len(vector) - 1] layerName = layerName.split(".")[0] layer = self.iface.addVectorLayer(fileName + ".gml", layerName, "ogr") if not layer: self.iface.messageBar().pushMessage( "Error", "Failed to add raster to the layer heap", level=QgsMessageBar.CRITICAL) self.createChoropleth(layer, hexASCII.min, hexASCII.max)
def main(): neighbours = 5 tolerance = 0.1 epsilon = 100 coords_list = [] values_list = [] args = getArguments() with open(args.input, 'rt') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: raw = str(row[0]).split(',') coords_list.append([float(raw[0]), float(raw[1])]) values_list.append(float(raw[2])) coords = numpy.array(coords_list) values = numpy.array(values_list) tree = spatial.KDTree(coords) # Set maximum and minimum admissable values max_value = values.max() + (values.max() - values.min()) * tolerance min_value = values.min() - (values.max() - values.min()) * tolerance hexRaster = HASC() hexRaster.initWithExtent(args.side, args.xmin, args.ymin, args.xmax, args.ymax) print("Geometries:" + "\n Hexagon cell area : " + str(hexRaster.cellArea()) + "\n Hexagon side length : " + str(hexRaster.side) + "\n Hexagon perpendicular : " + str(hexRaster.hexPerp) + "\n Number of rows in mesh : " + str(hexRaster.nrows) + "\n Number of columns in mesh : " + str(hexRaster.ncols)) for j in range(hexRaster.nrows): for i in range(hexRaster.ncols): xx = [] yy = [] vals = [] x, y = hexRaster.getCellCentroidCoords(i, j) d, ind = tree.query(numpy.array([x, y]),neighbours) for n in range(neighbours): xx.append(tree.data[ind[n]][0]) yy.append(tree.data[ind[n]][1]) vals.append(values[ind[n]]) f = interpolate.Rbf(xx, yy, vals, epsilon=epsilon) new_value = f(x,y) if new_value < min_value: hexRaster.set(i, j, min_value) elif new_value > max_value: hexRaster.set(i, j, max_value) else: hexRaster.set(i, j, new_value) hexRaster.save(args.output) hexRaster.saveAsGeoJSON(args.output + ".json") hexRaster.saveAsGML(args.output + ".gml") print("\nSuccessfully created new HexASCII raster.")
def main(): args = getArguments() raster = HASC() raster.initWithExtent(args.side, args.xmin, args.ymin, args.xmax, args.ymax) print("Geometries:" + "\n Hexagon cell area : " + str(raster.cellArea()) + "\n Hexagon side length : " + str(raster.side) + "\n Hexagon perpendicular : " + str(raster.hexPerp) + "\n Number of rows in mesh : " + str(raster.nrows) + "\n Number of columns in mesh : " + str(raster.ncols)) moduleName = args.module.rsplit('/', 1)[1].rsplit('.py', 1)[0] # Dynamically import surface function try: # Pyhton 2 runtime if sys.version_info[0] < 3: import imp module = imp.load_source(moduleName, args.module) else: # Python 3 runtime import importlib.util spec = importlib.util.spec_from_file_location(moduleName, args.module) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) function = getattr(module, args.function) except(Exception) as ex: print("Failed to import module or function: %s" % (ex)) sys.exit() for i in range(raster.ncols): for j in range(raster.nrows): x, y = raster.getCellCentroidCoords(i, j) raster.set(i, j, function(x, y)) try: raster.save(args.output) raster.saveAsGML(args.output + ".gml") except (ImportError, IOError) as ex: print("Error saving the raster %s: %s" % (args.output, ex)) sys.exit() print("Created new raster successfully")
def main(): args = getArguments() raster = HASC() raster.initWithExtent(args.side, args.xmin, args.ymin, args.xmax, args.ymax) print("Geometries:" + "\n Hexagon cell area : " + str(raster.cellArea()) + "\n Hexagon side length : " + str(raster.side) + "\n Hexagon perpendicular : " + str(raster.hexPerp) + "\n Number of rows in mesh : " + str(raster.nrows) + "\n Number of columns in mesh : " + str(raster.ncols)) moduleName = args.module.rsplit('/', 1)[1].rsplit('.py', 1)[0] # Dynamically import surface function try: # Pyhton 2 runtime if sys.version_info[0] < 3: import imp module = imp.load_source(moduleName, args.module) else: # Python 3 runtime import importlib.util spec = importlib.util.spec_from_file_location( moduleName, args.module) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) function = getattr(module, args.function) except (Exception) as ex: print("Failed to import module or function: %s" % (ex)) sys.exit() for i in range(raster.ncols): for j in range(raster.nrows): x, y = raster.getCellCentroidCoords(i, j) raster.set(i, j, function(x, y)) try: raster.save(args.output) raster.saveAsGML(args.output + ".gml") except (ImportError, IOError) as ex: print("Error saving the raster %s: %s" % (args.output, ex)) sys.exit() print("Created new raster successfully")
def main(): neighbours = 5 tolerance = 0.1 epsilon = 100 coords_list = [] values_list = [] args = getArguments() with open(args.input, 'rt') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: raw = str(row[0]).split(',') coords_list.append([float(raw[0]), float(raw[1])]) values_list.append(float(raw[2])) coords = numpy.array(coords_list) values = numpy.array(values_list) tree = spatial.KDTree(coords) # Set maximum and minimum admissable values max_value = values.max() + (values.max() - values.min()) * tolerance min_value = values.min() - (values.max() - values.min()) * tolerance hexRaster = HASC() hexRaster.initWithExtent(args.side, args.xmin, args.ymin, args.xmax, args.ymax) print("Geometries:" + "\n Hexagon cell area : " + str(hexRaster.cellArea()) + "\n Hexagon side length : " + str(hexRaster.side) + "\n Hexagon perpendicular : " + str(hexRaster.hexPerp) + "\n Number of rows in mesh : " + str(hexRaster.nrows) + "\n Number of columns in mesh : " + str(hexRaster.ncols)) # Supress warnings from numpy with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'scipy.linalg.solve') for j in range(hexRaster.nrows): for i in range(hexRaster.ncols): xx = [] yy = [] vals = [] x, y = hexRaster.getCellCentroidCoords(i, j) d, ind = tree.query(numpy.array([x, y]), neighbours) for n in range(neighbours): xx.append(tree.data[ind[n]][0]) yy.append(tree.data[ind[n]][1]) vals.append(values[ind[n]]) try: f = interpolate.Rbf(xx, yy, vals, epsilon=epsilon) new_value = f(x, y) except (Exception) as ex: new_value = sum(vals) / len(vals) else: if new_value < min_value: hexRaster.set(i, j, min_value) elif new_value > max_value: hexRaster.set(i, j, max_value) else: hexRaster.set(i, j, new_value) hexRaster.save(args.output) hexRaster.saveAsGeoJSON(args.output + ".json") hexRaster.saveAsGML(args.output + ".gml") print("\nSuccessfully created new HexASCII raster.")