File: Processing.py

package info (click to toggle)
qgis 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 374,696 kB
  • ctags: 66,263
  • sloc: cpp: 396,139; ansic: 241,070; python: 130,609; xml: 14,884; perl: 1,290; sh: 1,287; sql: 500; yacc: 268; lex: 242; makefile: 168
file content (350 lines) | stat: -rw-r--r-- 13,016 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# -*- coding: utf-8 -*-

"""
***************************************************************************
    Processing.py
    ---------------------
    Date                 : August 2012
    Copyright            : (C) 2012 by Victor Olaya
    Email                : volayaf at gmail dot com
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import processing
from qgis.utils import iface
from processing.core.ProcessingConfig import ProcessingConfig
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.ProcessingLog import ProcessingLog
from processing.core.SilentProgress import SilentProgress
from processing.gui.AlgorithmClassification import AlgorithmDecorator
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.RenderingStyles import RenderingStyles
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.gui.UnthreadedAlgorithmExecutor import \
        UnthreadedAlgorithmExecutor
from processing.modeler.Providers import Providers
from processing.modeler.ModelerAlgorithmProvider import \
        ModelerAlgorithmProvider
from processing.modeler.ModelerOnlyAlgorithmProvider import \
        ModelerOnlyAlgorithmProvider
from processing.algs.qgis.QGISAlgorithmProvider import QGISAlgorithmProvider
from processing.algs.grass.GrassAlgorithmProvider import GrassAlgorithmProvider
from processing.algs.grass7.Grass7AlgorithmProvider import Grass7AlgorithmProvider
from processing.algs.lidar.LidarToolsAlgorithmProvider import \
        LidarToolsAlgorithmProvider
from processing.algs.gdal.GdalOgrAlgorithmProvider import GdalOgrAlgorithmProvider
from processing.algs.otb.OTBAlgorithmProvider import OTBAlgorithmProvider
from processing.algs.r.RAlgorithmProvider import RAlgorithmProvider
from processing.algs.saga.SagaAlgorithmProvider import SagaAlgorithmProvider
from processing.script.ScriptAlgorithmProvider import ScriptAlgorithmProvider
from processing.algs.taudem.TauDEMAlgorithmProvider import TauDEMAlgorithmProvider
from processing.tools import dataobjects


class Processing:

    listeners = []
    providers = []

    # A dictionary of algorithms. Keys are names of providers
    # and values are list with all algorithms from that provider
    algs = {}

    # Same structure as algs
    actions = {}

    # All the registered context menu actions for the toolbox
    contextMenuActions = []

    modeler = ModelerAlgorithmProvider()

    @staticmethod
    def addProvider(provider, updateList=False):
        """Use this method to add algorithms from external providers.
        """

        # Note: this might slow down the initialization process if
        # there are many new providers added. Should think of a
        # different solution
        try:
            provider.initializeSettings()
            Processing.providers.append(provider)
            ProcessingConfig.readSettings()
            if updateList:
                Processing.updateAlgsList()
        except:
            ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                   'Could not load provider:'
                                   + provider.getDescription() + '\n'
                                   + unicode(sys.exc_info()[1]))
            Processing.removeProvider(provider)

    @staticmethod
    def removeProvider(provider):
        """Use this method to remove a provider.

        This method should be called when unloading a plugin that
        contributes a provider.
        """
        try:
            provider.unload()
            Processing.providers.remove(provider)
            ProcessingConfig.readSettings()
            Processing.updateAlgsList()
        except:
            # This try catch block is here to avoid problems if the
            # plugin with a provider is unloaded after the Processing
            # framework itself has been unloaded. It is a quick fix
            # before I found out how to properly avoid that.
            pass

    @staticmethod
    def getProviderFromName(name):
        """Returns the provider with the given name.
        """
        for provider in Processing.providers:
            if provider.getName() == name:
                return provider
        return Processing.modeler


    @staticmethod
    def initialize():
        # Add the basic providers
        Processing.addProvider(QGISAlgorithmProvider())
        Processing.addProvider(ModelerOnlyAlgorithmProvider())
        Processing.addProvider(GdalOgrAlgorithmProvider())
        Processing.addProvider(LidarToolsAlgorithmProvider())
        Processing.addProvider(OTBAlgorithmProvider())
        Processing.addProvider(RAlgorithmProvider())
        Processing.addProvider(SagaAlgorithmProvider())
        Processing.addProvider(GrassAlgorithmProvider())
        Processing.addProvider(Grass7AlgorithmProvider())
        Processing.addProvider(ScriptAlgorithmProvider())
        Processing.addProvider(TauDEMAlgorithmProvider())
        Processing.modeler.initializeSettings()

        # And initialize
        AlgorithmDecorator.loadClassification()
        ProcessingLog.startLogging()
        ProcessingConfig.initialize()
        ProcessingConfig.readSettings()
        RenderingStyles.loadStyles()
        Processing.loadFromProviders()

    @staticmethod
    def updateAlgsList():
        """Call this method when there has been any change that
        requires the list of algorithms to be created again from
        algorithm providers.
        """
        Processing.loadFromProviders()
        Processing.fireAlgsListHasChanged()

    @staticmethod
    def loadFromProviders():
        Processing.loadAlgorithms()
        Processing.loadActions()
        Processing.loadContextMenuActions()

    @staticmethod
    def updateProviders():
        for provider in Processing.providers:
            provider.loadAlgorithms()

    @staticmethod
    def addAlgListListener(listener):
        """Listener should implement a algsListHasChanged() method.

        Whenever the list of algorithms changes, that method will be
        called for all registered listeners.
        """
        Processing.listeners.append(listener)

    @staticmethod
    def fireAlgsListHasChanged():
        for listener in Processing.listeners:
            listener.algsListHasChanged()

    @staticmethod
    def loadAlgorithms():
        Processing.algs = {}
        Processing.updateProviders()
        for provider in Processing.providers:
            providerAlgs = provider.algs
            algs = {}
            for alg in providerAlgs:
                algs[alg.commandLineName()] = alg
            Processing.algs[provider.getName()] = algs

        # This is a special provider, since it depends on others.
        # TODO: Fix circular imports, so this provider can be
        # incorporated as a normal one.
        provider = Processing.modeler
        provider.setAlgsList(Processing.algs)
        provider.loadAlgorithms()
        providerAlgs = provider.algs
        algs = {}
        for alg in providerAlgs:
            algs[alg.commandLineName()] = alg
        Processing.algs[provider.getName()] = algs

        # And we do it again, in case there are models containing
        # models.
        # TODO: Improve this
        provider.setAlgsList(Processing.algs)
        provider.loadAlgorithms()
        providerAlgs = provider.algs
        algs = {}
        for alg in providerAlgs:
            algs[alg.commandLineName()] = alg
        Processing.algs[provider.getName()] = algs
        provs = {}
        for provider in Processing.providers:
            provs[provider.getName()] = provider
        provs[Processing.modeler.getName()] = Processing.modeler
        Providers.providers = provs

    @staticmethod
    def loadActions():
        for provider in Processing.providers:
            providerActions = provider.actions
            actions = list()
            for action in providerActions:
                actions.append(action)
            Processing.actions[provider.getName()] = actions

        provider = Processing.modeler
        actions = list()
        for action in provider.actions:
            actions.append(action)
        Processing.actions[provider.getName()] = actions

    @staticmethod
    def loadContextMenuActions():
        Processing.contextMenuActions = []
        for provider in Processing.providers:
            providerActions = provider.contextMenuActions
            for action in providerActions:
                Processing.contextMenuActions.append(action)

        provider = Processing.modeler
        providerActions = provider.contextMenuActions
        for action in providerActions:
            Processing.contextMenuActions.append(action)

    @staticmethod
    def getAlgorithm(name):
        for provider in Processing.algs.values():
            if name in provider:
                return provider[name]
        return None

    @staticmethod
    def getAlgorithmFromFullName(name):
        for provider in Processing.algs.values():
            for alg in provider.values():
                if alg.name == name:
                    return alg
        return None

    @staticmethod
    def getObject(uri):
        """Returns the QGIS object identified by the given URI.
        """
        return dataobjects.getObjectFromUri(uri)

    @staticmethod
    def runandload(name, *args):
        Processing.runAlgorithm(name, handleAlgorithmResults, *args)

    @staticmethod
    def runAlgorithm(algOrName, onFinish, *args):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = Processing.getAlgorithm(algOrName)
        if alg is None:
            print 'Error: Algorithm not found\n'
            return
        if len(args) != alg.getVisibleParametersCount() \
                    + alg.getVisibleOutputsCount():
            print 'Error: Wrong number of parameters'
            processing.alghelp(algOrName)
            return

        alg = alg.getCopy()
        if isinstance(args, dict):
            # Set params by name
            for (name, value) in args.items():
                if alg.getParameterFromName(name).setValue(value):
                    continue
                if alg.getOutputFromName(name).setValue(value):
                    continue
                print 'Error: Wrong parameter value %s for parameter %s.' \
                    % (value, name)
                return
        else:
            i = 0
            for param in alg.parameters:
                if not param.hidden:
                    if not param.setValue(args[i]):
                        print 'Error: Wrong parameter value: ' \
                            + unicode(args[i])
                        return
                    i = i + 1

            for output in alg.outputs:
                if not output.hidden:
                    if not output.setValue(args[i]):
                        print 'Error: Wrong output value: ' + unicode(args[i])
                        return
                    i = i + 1

        msg = alg.checkParameterValuesBeforeExecuting()
        if msg:
            print 'Unable to execute algorithm\n' + msg
            return

        if not alg.checkInputCRS():
            print 'Warning: Not all input layers use the same CRS.\n' \
                + 'This can cause unexpected results.'

        ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, alg.getAsCommand())

        # Don't set the wait cursor twice, because then when you
        # restore it, it will still be a wait cursor.
        cursor = QApplication.overrideCursor()
        if cursor is None or cursor == 0:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        elif cursor.shape() != Qt.WaitCursor:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        progress = SilentProgress()
        if iface is not None :
            progress = MessageBarProgress()
        ret = UnthreadedAlgorithmExecutor.runalg(alg, progress)
        if onFinish is not None and ret:
            onFinish(alg, progress)
        QApplication.restoreOverrideCursor()
        progress.close()
        return alg