Skip to content
Permalink
Browse files
Improvements in R Connection (more or less working now)
added R toolbox actions


git-svn-id: http://sextante.googlecode.com/svn/trunk/soft/bindings/qgis-plugin@31 881b9c09-3ef8-f3c2-ec3d-21d735c97f4d
  • Loading branch information
volayaf@gmail.com committed Mar 8, 2012
1 parent 1b68f20 commit 7e93081
Show file tree
Hide file tree
Showing 10 changed files with 226 additions and 33 deletions.
@@ -0,0 +1,77 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
import os.path
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from sextante.parameters.ParameterVector import ParameterVector
from sextante.core.QGisLayers import QGisLayers
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from sextante.outputs.OutputVector import OutputVector

class LayerFromExtent(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/icons/layer_extent.png")

def processAlgorithm(self, progress):
settings = QSettings()
systemEncoding = settings.value( "/UI/encoding", "System" ).toString()
output = self.getOutputValue(LayerFromExtent.OUTPUT)
vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(LayerFromExtent.INPUT))
fields = {
0 : QgsField( "MINX", QVariant.Double ),
1 : QgsField( "MINY", QVariant.Double ),
2 : QgsField( "MAXX", QVariant.Double ),
3 : QgsField( "MAXY", QVariant.Double ),
4 : QgsField( "CNTX", QVariant.Double ),
5 : QgsField( "CNTY", QVariant.Double ),
6 : QgsField( "AREA", QVariant.Double ),
7 : QgsField( "PERIM", QVariant.Double ),
8 : QgsField( "HEIGHT", QVariant.Double ),
9 : QgsField( "WIDTH", QVariant.Double ) }

writer = QgsVectorFileWriter( output, systemEncoding, fields, QGis.WKBPolygon, self.vlayer.crs() )
rect = vlayer.extent()
minx = rect.xMinimum()
miny = rect.yMinimum()
maxx = rect.xMaximum()
maxy = rect.yMaximum()
height = rect.height()
width = rect.width()
cntx = minx + ( width / 2.0 )
cnty = miny + ( height / 2.0 )
area = width * height
perim = ( 2 * width ) + (2 * height )
rect = [
QgsPoint( minx, miny ),
QgsPoint( minx, maxy ),
QgsPoint( maxx, maxy ),
QgsPoint( maxx, miny ),
QgsPoint( minx, miny ) ]
geometry = QgsGeometry().fromPolygon( [ rect ] )
feat = QgsFeature()
feat.setGeometry( geometry )
feat.setAttributeMap( {
0 : QVariant( minx ),
1 : QVariant( miny ),
2 : QVariant( maxx ),
3 : QVariant( maxy ),
4 : QVariant( cntx ),
5 : QVariant( cnty ),
6 : QVariant( area ),
7 : QVariant( perim ),
8 : QVariant( height ),
9 : QVariant( width ) } )
writer.addFeature( feat )
del writer

def defineCharacteristics(self):
self.name = "Layer from layer extent"
self.group = "Geometry tools"
self.addParameter(ParameterVector(LayerFromExtent.INPUT, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addOutput(OutputVector(LayerFromExtent.OUTPUT, "Output layer"))
#=========================================================
@@ -89,7 +89,6 @@ def executeAlgorithm(self):
alg = copy.deepcopy(alg)
dlg = ParametersDialog(alg)
dlg.exec_()

if isinstance(item, TreeActionItem):
action = item.action
action.setData(self)
@@ -0,0 +1,20 @@
from sextante.script.EditScriptDialog import EditScriptDialog
from sextante.gui.ToolboxAction import ToolboxAction
import os
from PyQt4 import QtGui
from sextante.r.EditRScriptDialog import EditRScriptDialog

class CreateNewRScriptAction(ToolboxAction):

def __init__(self):
self.name="Create new R script"
self.group="Tools"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/r.png")

def execute(self):
dlg = EditRScriptDialog(None)
dlg.exec_()
if dlg.update:
self.toolbox.updateTree()
@@ -0,0 +1,17 @@
from sextante.gui.ContextAction import ContextAction
from sextante.r.RAlgorithm import RAlgorithm
from sextante.r.EditRScriptDialog import EditRScriptDialog

class EditRScriptAction(ContextAction):

def __init__(self):
self.name="Edit R script"

def isEnabled(self):
return isinstance(self.alg, RAlgorithm)

def execute(self):
dlg = EditRScriptDialog(self.alg)
dlg.exec_()
if dlg.update:
self.toolbox.updateTree()
@@ -0,0 +1,51 @@
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.r.RUtils import RUtils

class EditRScriptDialog(QtGui.QDialog):
def __init__(self, alg):
self.alg = alg
QtGui.QDialog.__init__(self)
self.setModal(True)
self.setupUi()
self.update = False

def setupUi(self):
self.setObjectName("Dialog")
self.resize(655, 360)
self.setWindowTitle("Edit script")
self.text = QtGui.QTextEdit(self)
self.text.setGeometry(QtCore.QRect(5, 5, 550, 350))
self.text.setObjectName("text")
self.text.setEnabled(True)
if self.alg != None:
self.text.setText(self.alg.script)
self.saveButton = QtGui.QPushButton(self)
self.saveButton.setGeometry(QtCore.QRect(570, 300, 80, 23))
self.saveButton.setObjectName("saveButton")
self.saveButton.setText("Save")
self.cancelButton = QtGui.QPushButton(self)
self.cancelButton.setGeometry(QtCore.QRect(570, 327, 80, 23))
self.cancelButton.setObjectName("cancelButton")
self.cancelButton.setText("Cancel")
QObject.connect(self.saveButton, QtCore.SIGNAL("clicked()"), self.saveAlgorithm)
QObject.connect(self.cancelButton, QtCore.SIGNAL("clicked()"), self.cancel)
QtCore.QMetaObject.connectSlotsByName(self)

def saveAlgorithm(self):
if self.alg!=None:
filename = self.alg.descriptionFile
else:
filename = QtGui.QFileDialog.getSaveFileName(self, "Save Script", RUtils.RScriptsFolder(), "R-SEXTANTE scripts (*.rsx)")
if filename:
text = self.text.toPlainText()
fout = open(filename, "w")
fout.write(text)
fout.close()
self.update = True
self.close()

def cancel(self):
self.update = False
self.close()
@@ -32,7 +32,8 @@ def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/script.png")

def defineCharacteristicsFromFile(self):
self.commands=""
self.script = ""
self.commands=[]
self.showPlots = False
self.showConsoleOutput = False
self.verboseCommands = []
@@ -45,13 +46,14 @@ def defineCharacteristicsFromFile(self):
if line.startswith("##"):
self.processParameterLine(line)
elif line.startswith(">"):
self.commands += line[1:]
self.commands.append(line[1:])
self.verboseCommands.append(line[1:])
if not self.showConsoleOutput:
self.addOutput(OutputHTML(RAlgorithm.R_CONSOLE_OUTPUT, "R Console Output"))
self.showConsoleOutput = True
else:
self.commands += line
self.commands.append(line)
self.script += line + "\n"
line = lines.readline().strip("\n")
lines.close()

@@ -146,8 +148,8 @@ def getFullSetOfRCommands(self):

commands = []
commands += self.getImportCommands()
commands += self.getExportCommands()
commands += self.getRCommands()
commands += self.getExportCommands()

return commands

@@ -168,7 +170,7 @@ def getExportCommands(self):
value = value + ".shp"
value = value.replace("\\", "/")
filename = os.path.basename(value)
filename = filename[-4]
filename = filename[:-4]
commands.append("writeOGR(" + out.name + ",\"" + value + "\",\""
+ filename + "\", driver=\"ESRI Shapefile\")");

@@ -178,8 +180,6 @@ def getExportCommands(self):
return commands




def getImportCommands(self):

commands = []
@@ -197,7 +197,7 @@ def getImportCommands(self):
raise GeoAlgorithmExecutionException("Unsupported input file format.\n" + value)
value = value.replace("\\", "/")
filename = os.path.basename(value)
filename = filename[-4]
filename = filename[:-4]
commands.append(param.name + " = " + "readOGR(\"" + value + "\",layer=\"" + filename + "\")")
if isinstance(param, (ParameterTableField, ParameterString)):
commands.append(param.name + "=\"" + param.value + "\"")
@@ -225,7 +225,7 @@ def getImportCommands(self):
raise GeoAlgorithmExecutionException("Unsupported input file format.\n" + layer)
layer = layer.replace("\\", "/")
filename = os.path.basename(layer)
filename = filename[-4]
filename = filename[:-4]
commands.append("tempvar" + str(iLayer) + " = " + "readOGR(\"" + layer + "\",layer=\"" + filename + "\")")
iLayer+=1
s = ""
@@ -8,16 +8,18 @@
from PyQt4 import QtGui
from sextante.r.RUtils import RUtils
from sextante.r.RAlgorithm import RAlgorithm
from sextante.r.CreateNewRScriptAction import CreateNewRScriptAction
from sextante.r.EditRScriptAction import EditRScriptAction

class RAlgorithmProvider(AlgorithmProvider):

def __init__(self):
AlgorithmProvider.__init__(self)
SextanteConfig.addSetting(Setting("R", RUtils.RSCRIPTS_FOLDER, "R Scripts folder", RUtils.RScriptsFolder()))
SextanteConfig.addSetting(Setting("R", RUtils.R_FOLDER, "R folder", RUtils.RFolder()))
#self.actions = []
#self.actions.append(CreateNewScriptAction())
self.contextMenuActions = []#EditScriptAction(), DeleteScriptAction()]
self.actions = []
self.actions.append(CreateNewRScriptAction())
self.contextMenuActions = [EditRScriptAction()]

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/r.png")
@@ -49,22 +49,23 @@ def executeRAlgorithm(alg):
RUtils.verboseCommands = alg.getVerboseCommands();
RUtils.createRScriptFromRCommands(alg.getFullSetOfRCommands())
if SextanteUtils.isWindows():
command = ["\"" + RUtils.RFolder() + os.sep + "bin" + os.sep + "R.exe\"", "CMD", "BATCH", "--vanilla",
"\"" + RUtils.getRScriptFilename() + "\""]
command = [RUtils.RFolder() + os.sep + "bin" + os.sep + "R.exe", "CMD", "BATCH", "--vanilla", RUtils.getRScriptFilename()]
else:#TODO***********
pass

proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True).stdout
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True)

RUtils.createConsoleOutput()


@staticmethod
def createConsoleOutput():
add = False
lines = open(RUtils.getConsoleOutputFilename())
line = lines.readline().strip("\n").strip(" ")
while line != "":
if line.startswith(">"):
line = line[1:]
line = line[1:].strip(" ")
if line in RUtils.verboseCommands:
add = True
else:
@@ -29,6 +29,7 @@
from sextante.parameters.ParameterFactory import ParameterFactory
from sextante.outputs.OutputFactory import OutputFactory
from sextante.core.SextanteConfig import SextanteConfig
import math

class SagaAlgorithm(GeoAlgorithm):

@@ -174,14 +175,48 @@ def defineCharacteristicsFromFileSagaFormat(self):
line = lines.readline()
lines.close()

def processAlgorithm(self, progress):

def calculateResamplingExtent(self):
auto = SextanteConfig.getSetting(SagaUtils.SAGA_AUTO_RESAMPLING)
if auto:
first = True;
for param in self.parameters:
if isinstance(param, ParameterRaster):
if isinstance(param.value, QgsRasterLayer):
value = param.value
else:
value = QGisLayers.getObjectFromUri(param.value)
if first:
self.xmin = value.extent().xMinimum()
self.xmax = value.extent().xMaximum()
self.ymin = value.extent().yMinimum()
self.ymax = value.extent().yMaximum()
self.cellsize = (value.extent().xMaximum() - value.extent().xMinimum())/value.getRasterXDim()
first = False
else:
self.xmin = min(self.xmin, value.extent().xMinimum())
self.xmax = max(self.xmax, value.extent().xMaximum())
self.ymin = min(self.ymin, value.extent().yMinimum())
self.ymax = max(self.ymax, value.extent().yMaximum())
self.cellsize = max(self.cellsize, (value.extent().xMaximum() - value.extent().xMinimum())/value.getRasterXDim())
else:
self.xmin = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMIN)
self.xmax = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMAX)
self.ymin = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMIN)
self.ymax = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMAX)
self.cellsize = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_CELLSIZE)



def processAlgorithm(self, progress):
commands = list()
self.exportedLayers = {}
self.numExportedLayers = 0;

#1: Export rasters to sgrd. only ASC and TIF are supported.
# Vector layers must be in shapefile format and tables in dbf format. We check that.
#1: Export rasters to sgrd. only ASC and TIF are supported.
# Vector layers must be in shapefile format and tables in dbf format. We check that.
if self.resample:
self.calculateResamplingExtent()
for param in self.parameters:
if isinstance(param, ParameterRaster):
if param.value == None:
@@ -305,18 +340,10 @@ def resampleRasterLayer(self,layer):
inputFilename = layer
destFilename = self.getTempFilename()
self.exportedLayers[layer]= destFilename
auto = SextanteConfig.getSetting(SagaUtils.SAGA_AUTO_RESAMPLING)
if auto:
pass
else:
xmin = auto = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMIN)
xmax = auto = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMAX)
ymin = auto = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMIN)
ymax = auto = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMAX)
cellsize = auto = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_CELLSIZE)
s = "grid_tools \"Resampling\" -INPUT " + inputFilename + "-TARGET 0 -SCALE_UP_METHOD 4 -SCALE_DOWN_METHOD 4 -USER_XMIN " +\
xmin + " -USER_XMAX " + xmax + " -USER_YMIN " + ymin + " -USER_YMAX " + ymax +\
" -USER_SIZE " + str(cellsize) + " -USER_GRID " + destFilename
s = "grid_tools \"Resampling\" -INPUT " + inputFilename + "-TARGET 0 -SCALE_UP_METHOD 4 -SCALE_DOWN_METHOD 4 -USER_XMIN " +\
self.xmin + " -USER_XMAX " + self.xmax + " -USER_YMIN " + self.ymin + " -USER_YMAX " + self.ymax +\
" -USER_SIZE " + str(self.cellsize) + " -USER_GRID " + destFilename
return s

def exportRasterLayer(self,layer):
if not layer.lower().endswith("tif") and not layer.lower().endswith("asc"):
@@ -46,7 +46,6 @@ def createDescriptiveName(self, s):
return s.replace("_", " ")

def processParameterLine(self,line):

param = None
out = None
line = line.replace("#", "");

0 comments on commit 7e93081

Please sign in to comment.