Skip to content

Commit 772e8e7

Browse files
author
volayaf
committed
started grass algorithm provider
git-svn-id: http://sextante.googlecode.com/svn/trunk/soft/bindings/qgis-plugin@48 881b9c09-3ef8-f3c2-ec3d-21d735c97f4d
1 parent b7d940e commit 772e8e7

File tree

198 files changed

+2610
-214
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

198 files changed

+2610
-214
lines changed

src/sextante/SextantePlugin.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
from PyQt4.QtCore import *
22
from PyQt4.QtGui import *
33
from qgis.core import *
4-
5-
64
import os, sys
75
import inspect
86
from sextante.core.Sextante import Sextante
@@ -26,7 +24,7 @@ def __init__(self, iface):
2624
self.iface = iface
2725
QGisLayers.setInterface(iface)
2826
Sextante.initialize()
29-
Sextante .setInterface(iface)
27+
Sextante.setInterface(iface)
3028

3129
def initGui(self):
3230
self.toolbox = SextanteToolbox(self.iface)
@@ -77,9 +75,6 @@ def initGui(self):
7775
QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.openAbout)
7876
self.menu.addAction(self.aboutAction)
7977

80-
81-
82-
8378
menuBar = self.iface.mainWindow().menuBar()
8479
menuBar.insertMenu(menuBar.actions()[-1], self.menu)
8580

src/sextante/core/GeoAlgorithm.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
from PyQt4 import QtGui
77
import os.path
88
from sextante.core.SextanteUtils import SextanteUtils
9-
from sextante.parameters.ParameterNumber import ParameterNumber
10-
from sextante.parameters.ParameterBoolean import ParameterBoolean
119

1210

1311
class GeoAlgorithm:
@@ -20,6 +18,7 @@ def __init__(self):
2018
self.defineCharacteristics()
2119
self.providerName = ""
2220
self.crs = None
21+
self.helpfile = None
2322

2423
#methods to overwrite when creating a custom geoalgorithm
2524
#=========================================================

src/sextante/core/QGisLayers.py

+25-10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from PyQt4.QtGui import *
44
from PyQt4 import QtCore, QtGui
55
from os import path
6+
from sextante.core.SextanteConfig import SextanteConfig
67

78
class QGisLayers:
89

@@ -15,7 +16,7 @@ def getRasterLayers():
1516
raster = list()
1617

1718
for layer in layers:
18-
if layer.type() == layer.RasterLayer :
19+
if layer.type() == layer.RasterLayer and not layer.usesProvider():
1920
raster.append(layer)
2021
return raster
2122

@@ -24,7 +25,7 @@ def getVectorLayers(shapetype=-1):
2425
layers = QGisLayers.iface.legendInterface().layers()
2526
vector = list()
2627
for layer in layers:
27-
if layer.type() == layer.VectorLayer:
28+
if layer.type() == layer.VectorLayer and not layer.usesProvider():
2829
if shapetype == QGisLayers.ALL_TYPES or layer.geometryType() == shapetype:
2930
vector.append(layer)
3031
return vector
@@ -62,18 +63,32 @@ def load(layer, name = None, crs = None):
6263
settings.setValue("/Projections/defaultBehaviour", QVariant(""))
6364
if name == None:
6465
name = path.split(layer)[1]
65-
if layer.endswith("shp"):
66-
qgslayer = QgsVectorLayer(layer, name, 'ogr')
66+
qgslayer = QgsVectorLayer(layer, name , 'ogr')
67+
if qgslayer.isValid():
6768
if crs != None:
68-
qgslayer.setCrs(crs, False)
69+
qgslayer.setCrs(crs,False)
70+
if qgslayer.geometryType == 0:
71+
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_POINT_STYLE)
72+
elif qgslayer.geometryType == 1:
73+
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_LINE_STYLE)
74+
else:
75+
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_POLYGON_STYLE)
76+
qgslayer.loadNamedStyle(style)
6977
QgsMapLayerRegistry.instance().addMapLayer(qgslayer)
7078
else:
7179
qgslayer = QgsRasterLayer(layer, name)
72-
if crs != None:
73-
qgslayer.setCrs(crs,False)
74-
QgsMapLayerRegistry.instance().addMapLayer(qgslayer)
75-
except Exception:
76-
QtGui.QMessageBox(None, "Error", "Could not load layer: " + str(layer))
80+
if qgslayer.isValid():
81+
if crs != None:
82+
qgslayer.setCrs(crs,False)
83+
84+
style = SextanteConfig.getSetting(SextanteConfig.RASTER_STYLE)
85+
qgslayer.loadNamedStyle(style)
86+
QgsMapLayerRegistry.instance().addMapLayer(qgslayer)
87+
QGisLayers.iface.legendInterface().refreshLayerSymbology(qgslayer)
88+
else:
89+
QtGui.QMessageBox.critical(None, "Error", "Could not load layer: " + str(layer))
90+
except Exception, e:
91+
QtGui.QMessageBox.critical(None, "Error", "Could not load layer: " + str(layer))
7792
finally:
7893
if prjSetting:
7994
settings.setValue("/Projections/defaultBehaviour", prjSetting)

src/sextante/core/Sextante.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from PyQt4.QtCore import *
22
from PyQt4.QtGui import *
3-
from PyQt4 import QtCore, QtGui
43
from sextante.saga.SagaAlgorithmProvider import SagaAlgorithmProvider
54
from sextante.script.ScriptAlgorithmProvider import ScriptAlgorithmProvider
65
import copy
@@ -16,12 +15,14 @@
1615
from sextante.modeler.ProviderIcons import ProviderIcons
1716
from sextante.r.RAlgorithmProvider import RAlgorithmProvider
1817
from sextante.parameters.ParameterSelection import ParameterSelection
18+
from sextante.grass.GrassAlgorithmProvider import GrassAlgorithmProvider
1919

2020
class Sextante:
2121

2222
iface = None
2323
providers = [SagaAlgorithmProvider(), ScriptAlgorithmProvider(),
24-
MMQGISAlgorithmProvider(), FToolsAlgorithmProvider(), RAlgorithmProvider()]
24+
MMQGISAlgorithmProvider(), FToolsAlgorithmProvider(),
25+
RAlgorithmProvider(), GrassAlgorithmProvider()]
2526
algs = {}
2627
actions = {}
2728
contextMenuActions = []

src/sextante/core/SextanteConfig.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,21 @@
44
class SextanteConfig():
55

66
OUTPUT_FOLDER = "OUTPUT_FOLDER"
7+
RASTER_STYLE = "RASTER_STYLE"
8+
VECTOR_POINT_STYLE = "VECTOR_POINT_STYLE"
9+
VECTOR_LINE_STYLE = "VECTOR_LINE_STYLE"
10+
VECTOR_POLYGON_STYLE = "VECTOR_POLYGON_STYLE"
711

812
settings = {}
913

1014
@staticmethod
1115
def initialize():
1216
SextanteConfig.addSetting(Setting("General", SextanteConfig.OUTPUT_FOLDER,
1317
"Output folder", os.path.join(SextanteUtils.userFolder(),"outputs" )))
14-
18+
SextanteConfig.addSetting(Setting("General", SextanteConfig.RASTER_STYLE,"Style for raster layers",""))
19+
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_POINT_STYLE,"Style for point layers",""))
20+
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_LINE_STYLE,"Style for line layers",""))
21+
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_POLYGON_STYLE,"Style for polygon layers",""))
1522

1623
@staticmethod
1724
def addSetting(setting):

src/sextante/grass/GrassAlgorithm.py

+227
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
import os
2+
from qgis.core import *
3+
from PyQt4.QtCore import *
4+
from PyQt4.QtGui import *
5+
from sextante.core.GeoAlgorithm import GeoAlgorithm
6+
from sextante.parameters.ParameterTable import ParameterTable
7+
from sextante.parameters.ParameterMultipleInput import ParameterMultipleInput
8+
from sextante.parameters.ParameterRaster import ParameterRaster
9+
from sextante.outputs.OutputRaster import OutputRaster
10+
from sextante.parameters.ParameterVector import ParameterVector
11+
from sextante.parameters.ParameterBoolean import ParameterBoolean
12+
from sextante.outputs.OutputVector import OutputVector
13+
from sextante.saga.SagaUtils import SagaUtils
14+
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
15+
from sextante.core.SextanteLog import SextanteLog
16+
from sextante.parameters.ParameterFactory import ParameterFactory
17+
from sextante.outputs.OutputFactory import OutputFactory
18+
from sextante.core.SextanteConfig import SextanteConfig
19+
from sextante.core.QGisLayers import QGisLayers
20+
from sextante.grass.GrassUtils import GrassUtils
21+
import time
22+
from sextante.core.SextanteUtils import SextanteUtils
23+
24+
class GrassAlgorithm(GeoAlgorithm):
25+
26+
def __init__(self, descriptionfile):
27+
GeoAlgorithm.__init__(self)
28+
self._descriptionFile = descriptionfile
29+
self.defineCharacteristicsFromFile()
30+
self.numExportedLayers = 0
31+
self.needsregion = False
32+
33+
def getIcon(self):
34+
return QIcon(os.path.dirname(__file__) + "/../images/grass.png")
35+
36+
def defineCharacteristicsFromFile(self):
37+
lines = open(self._descriptionFile)
38+
line = lines.readline().strip("\n").strip()
39+
self.name = line
40+
line = lines.readline().strip("\n").strip()
41+
self.group = line
42+
while line != "":
43+
try:
44+
line = line.strip("\n").strip()
45+
if line.startswith("Parameter"):
46+
self.addParameter(ParameterFactory.getFromString(line))
47+
elif line.startswith("Region"):
48+
self.needsregion = True
49+
else:
50+
self.addOutput(OutputFactory.getFromString(line))
51+
line = lines.readline().strip("\n").strip()
52+
except Exception,e:
53+
SextanteLog.addToLog(SextanteLog.LOG_ERROR, "Could not open GRASS algorithm: " + self._descriptionFile + "\n" + line)
54+
raise e
55+
lines.close()
56+
57+
def calculateResamplingExtent(self):
58+
auto = SextanteConfig.getSetting(GrassUtils.GRASS_AUTO_REGION)
59+
if auto:
60+
first = True;
61+
for param in self.parameters:
62+
if isinstance(param, ParameterRaster):
63+
if isinstance(param.value, QgsRasterLayer):
64+
value = param.value
65+
else:
66+
value = QGisLayers.getObjectFromUri(param.value)
67+
if first:
68+
self.xmin = value.extent().xMinimum()
69+
self.xmax = value.extent().xMaximum()
70+
self.ymin = value.extent().yMinimum()
71+
self.ymax = value.extent().yMaximum()
72+
self.cellsize = (value.extent().xMaximum() - value.extent().xMinimum())/value.getRasterXDim()
73+
first = False
74+
else:
75+
self.xmin = min(self.xmin, value.extent().xMinimum())
76+
self.xmax = max(self.xmax, value.extent().xMaximum())
77+
self.ymin = min(self.ymin, value.extent().yMinimum())
78+
self.ymax = max(self.ymax, value.extent().yMaximum())
79+
self.cellsize = max(self.cellsize, (value.extent().xMaximum() - value.extent().xMinimum())/value.getRasterXDim())
80+
else:
81+
self.xmin = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMIN)
82+
self.xmax = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMAX)
83+
self.ymin = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMIN)
84+
self.ymax = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMAX)
85+
self.cellsize = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_CELLSIZE)
86+
87+
88+
def processAlgorithm(self, progress):
89+
path = GrassUtils.grassPath()
90+
if path == "":
91+
raise GeoAlgorithmExecutionException("GRASS folder is not configured.\nPlease configure it before running GRASS algorithms.")
92+
useSelection = SextanteConfig.getSetting(SagaUtils.SAGA_USE_SELECTED)
93+
94+
commands = []
95+
self.exportedLayers = {}
96+
self.numExportedLayers = 0;
97+
98+
if self.needsregion:
99+
self.calculateResamplingExtent()
100+
GrassUtils.createTempMapset();
101+
102+
if self.needsregion:
103+
command = "g.region"
104+
command += " n=" + str(self.ymax)
105+
command +=" s=" + str(self.ymin)
106+
command +=" e=" + str(self.xmax)
107+
command +=" w=" + str(self.xmin)
108+
command +=" res=" + str(self.cellsize);
109+
commands.append(command)
110+
111+
#1: Export layer to grass mapset
112+
for param in self.parameters:
113+
if isinstance(param, ParameterRaster):
114+
if param.value == None:
115+
continue
116+
value = param.value
117+
commands.append(self.exportRasterLayer(value))
118+
if isinstance(param, ParameterVector):
119+
if param.value == None:
120+
continue
121+
value = param.value
122+
self.exportVectorLayer(value)
123+
if isinstance(param, ParameterTable):
124+
pass
125+
if isinstance(param, ParameterMultipleInput):
126+
if param.value == None:
127+
continue
128+
layers = param.value.split(";")
129+
if layers == None or len(layers) == 0:
130+
continue
131+
if param.datatype == ParameterMultipleInput.TYPE_RASTER:
132+
for layer in layers:
133+
commands.append(self.exportRasterLayer(layer))
134+
elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
135+
for layer in layers:
136+
if (not value.endswith("shp")) or useSelection:
137+
commands.append(self.exportRasterLayer(layer))
138+
139+
#2: set parameters and outputs
140+
command = self.name
141+
for param in self.parameters:
142+
if param.value == None:
143+
continue
144+
if isinstance(param, (ParameterRaster, ParameterVector)):
145+
value = param.value
146+
if value in self.exportedLayers.keys():
147+
command+=(" " + param.name + "=" + self.exportedLayers[value])
148+
else:
149+
command+=(" " + param.name + "=" + value)
150+
elif isinstance(param, ParameterMultipleInput):
151+
s = param.value
152+
for layer in self.exportedLayers.keys():
153+
s = s.replace(layer, self.exportedLayers[layer])
154+
s = s.replace(";",",")
155+
command+=(" " + param.name + "=" + s);
156+
elif isinstance(param, ParameterBoolean):
157+
if param.value:
158+
command += param.name
159+
else:
160+
command+=(" " + param.name + "=" + str(param.value));
161+
162+
for out in self.outputs:
163+
command+=(" " + out.name + "=" + out.name);
164+
165+
command += " --overwrite"
166+
commands.append(command)
167+
168+
#3:Export resulting layers to a format that qgis can read
169+
for out in self.outputs:
170+
if isinstance(out, OutputRaster):
171+
filename = out.value
172+
#Raster layer output: adjust region to layer before exporting
173+
commands.append("g.region rast=" + out.name)
174+
command = "r.out.gdal -c createopt=\"TFW=YES,COMPRESS=LZW\""
175+
command += " input="
176+
command += out.name
177+
command += " output=\"" + filename + "\""
178+
commands.append(command)
179+
if isinstance(out, OutputVector):
180+
command = "v.out.ogr -e -z input=" + out.name
181+
command += " dsn=\"" + os.path.dirname(out.value) + "\""
182+
command += " format=ESRI_Shapefile"
183+
command += " olayer=" + os.path.basename(out.value)
184+
command += " type=auto"
185+
commands.append(command)
186+
187+
#4 Run GRASS
188+
GrassUtils.createGrassScript(commands)
189+
loglines = []
190+
loglines.append("GRASS execution commands")
191+
for line in commands:
192+
loglines.append(line)
193+
SextanteLog.addToLog(SextanteLog.LOG_INFO, loglines)
194+
GrassUtils.executeGrass(progress);
195+
196+
197+
def exportVectorLayer(self, filename):
198+
destFilename = self.getTempFilename()
199+
self.exportedLayers[filename]= destFilename
200+
command = "v.in.ogr"
201+
command += " min_area=-1"
202+
command +=" dsn=\"" + os.path.dirname(filename) + "\""
203+
command +=" layer=" + os.path.basename(filename)
204+
command +=" output=" + destFilename;
205+
command +=" --overwrite -o"
206+
return command
207+
208+
209+
def exportRasterLayer(self, layer):
210+
destFilename = self.getTempFilename()
211+
self.exportedLayers[layer]= destFilename
212+
command = "r.in.gdal"
213+
command +=" input=\"" + layer + "\""
214+
command +=" band=0"
215+
command +=" out=" + destFilename;
216+
command +=" --overwrite -o"
217+
return command
218+
219+
220+
def getTempFilename(self):
221+
self.numExportedLayers+=1
222+
filename = str(time.time()) + str(SextanteUtils.NUM_EXPORTED)
223+
SextanteUtils.NUM_EXPORTED +=1
224+
225+
return filename
226+
227+

0 commit comments

Comments
 (0)