Statistics
| Revision:

gvsig-scripting / org.gvsig.scripting / trunk / org.gvsig.scripting / org.gvsig.scripting.app / org.gvsig.scripting.app.mainplugin / src / main / resources-plugin / scripting / lib / gvsig / libs / gvpy.py @ 946

History | View | Annotate | Download (33.8 KB)

1

    
2
# File: gvpy.py
3
# Version: v0.5
4
# 2016/02/10
5

    
6
__author__ = """Oscar Martinez Olmos <masquesig@gmail.com>"""
7

    
8
import gvsig
9
from gvsig import geom
10
import gvsig_raster
11
from org.gvsig.app import ApplicationLocator
12
from org.gvsig.fmap.dal import DALLocator
13
import os.path
14
from org.gvsig.andami import PluginsLocator
15
from org.gvsig.fmap.mapcontext import MapContextLocator
16
import java.awt
17
import java.awt.event
18
import java.awt.geom
19
from java.io import File
20
from java.util import ArrayList
21

    
22
from gvsig import uselib
23
uselib.use_plugin("org.gvsig.geoprocess.app.mainplugin")
24
uselib.use_plugin("org.gvsig.gdal.app.ogr.mainplugin")
25

    
26
from es.unex.sextante.core import Sextante, OutputFactory, AnalysisExtent
27
from es.unex.sextante.outputs import FileOutputChannel
28
from es.unex.sextante.gui.core import SextanteGUI
29
from es.unex.sextante.dataObjects import IRasterLayer
30
from es.unex.sextante.parameters import RasterLayerAndBand
31

    
32
from org.gvsig.geoprocess.lib.sextante.dataObjects import FlyrVectIVectorLayer, FLyrRasterIRasterLayer, TableDocumentITable
33
from org.gvsig.fmap.mapcontext.layers import FLayer
34
from java.awt.geom import RectangularShape, Rectangle2D
35
from org.gvsig.fmap.mapcontext.layers.vectorial import FLyrVect
36
from org.gvsig.raster.fmap.layers import DefaultFLyrRaster
37
from org.gvsig.app.project.documents.view import DefaultViewDocument
38
from org.gvsig.fmap.dal import DALLocator
39
from org.gvsig.fmap.mapcontext import MapContextLocator
40

    
41
#Constant
42
TYPE_POLYGON = 0
43
TYPE_LINE = 1
44
TYPE_POINT = 2
45

    
46
#With True will appear a lot of extra info about all steps through the process
47
DEV_INFO = False
48

    
49
class Geoprocess:
50
    def __init__(self):
51
      self.__FlyrVectIVectorLayer = None
52
      self.__outputFactory = SextanteGUI.getOutputFactory()
53
      self.__algorithms = dict()
54
      self.__defaultAE = None #default AExtension
55

    
56
      keySetIterator = Sextante.getAlgorithms().keySet().iterator()
57
      while(keySetIterator.hasNext()):
58
        key = keySetIterator.next()
59
        algorithms = Sextante.getAlgorithms().get(str(key))
60
        for name in algorithms.keySet():
61
          self.__algorithms[str(name)] = algorithms.get(name)
62

    
63
    def __createSextanteLayer(self, layer):
64
        """ gvsig layer -> SEXTANTE """
65
        slayer = FlyrVectIVectorLayer()
66
        slayer.create(layer)
67
        return slayer
68

    
69
    def __createSextanteRaster(self, layer):
70
        """ gvsig raster -> SEXTANTE """
71
        rlayer = FLyrRasterIRasterLayer()
72
        rlayer.create(layer)
73
        return rlayer
74

    
75
    def __createSextanteTable(self, layer):
76
        """ gvsig table -> SEXTANTE """
77
        table = TableDocumentITable()
78
        table.create(layer)
79
        return table
80

    
81
    def getAlgorithms(self):
82
        return self.__algorithms
83

    
84
    def __defineParameters_str2value(self, i, param, kwparams):
85
        if param.getParameterName() in kwparams:
86
            paramValue = kwparams[param.getParameterName()]
87
        else:
88
            paramValue = kwparams[i]
89

    
90
        #Input params: Tranform STRING to NUMERIC
91
        cond1 = (str(param) == "Numerical Value")
92
        cond2 = (str(param) == "Selection")
93
        isstr = isinstance(paramValue, str)
94
        cond4 = (str(param) == "Boolean")
95
        cond5 = (str(param) == "Table Field")
96
        if "Multi" in (str(param)):
97
            cond6 = True
98
        else:
99
            cond6 = False
100
        cond7 = (str(param) == "Point")
101

    
102
        if isstr:
103
            if cond1:
104
                paramValue = float(paramValue)
105
            elif cond2:
106
                paramValue = int(paramValue)
107
            elif cond4:
108
                paramValue = eval(paramValue.capitalize())
109
            elif cond5:
110
                paramValue = int(paramValue)
111
            elif cond6:
112
                #  <type 'java.util.ArrayList'>
113
                paramValue = list(paramValue)
114
            elif cond7: #Point
115
                paramValue = paramValue.split(',')
116
                x = float(paramValue[0])
117
                y = float(paramValue[1])
118
                paramValue = java.awt.geom.Point2D.Double(x, y)
119
            else: #is str
120
                pass
121
        else:
122
            if cond7: #punto de gvsig. agregar condicion punto
123
                x = paramValue.getX()
124
                y = paramValue.getY()
125
                paramValue = java.awt.geom.Point2D.Double(x, y)
126
        if DEV_INFO:
127
            print "Param Name: ", param.getParameterName()
128
            print "Param: ", param
129
            print "Resulta: ", paramValue, type(paramValue)
130
        return paramValue
131

    
132
    def __defineParameters_vector2sextante(self, param, paramValue):
133
                if isinstance(paramValue, str):
134
                    layer = gvsig.currentView().getLayer(paramValue)
135
                    paramValue = self.__createSextanteLayer(layer())
136
                else:
137
                    paramValue = self.__createSextanteLayer(paramValue())
138

    
139
                if DEV_INFO: print "Extent add"
140
                if self.__defaultAE == None:
141
                    self.__defaultAE = AnalysisExtent(paramValue)
142
                else:
143
                    self.__defaultAE.addExtent(AnalysisExtent(paramValue))
144
                if DEV_INFO: print "PARAM VALUE 1: ", paramValue
145
                return paramValue
146

    
147
    def __defineParameters_multi2sextante(self, param, paramValue):
148
                if DEV_INFO: print "PARAM VALUE PRE", paramValue
149
                paramValue2 = []
150
                for i in paramValue:
151
                    if isinstance(i, str):
152
                        layer = gvsig.currentView().getLayer(i)
153
                        if DEV_INFO: print "--------------- lidar: ", layer
154
                        i = self.__createSextanteLayer(layer)
155
                        ii = self.__createSextanteLayer(layer)
156

    
157
                    else:
158
                        if DEV_INFO: print type(i)
159
                        if isinstance(i, tuple): #si dentro de la lista viene una tupla identificamos que es un raster y su banda
160
                            rlb = RasterLayerAndBand(self.__createSextanteRaster(i[0]),i[1])  #puesta numero de banda
161
                            ii = self.__createSextanteRaster(i[0])
162
                            i = rlb
163
                            if DEV_INFO: print "RASTERLAYERBAND", rlb
164
                        else:
165
                            if str(type(i)) == "<type 'org.gvsig.raster.fmap.layers.DefaultFLyrRaster'>":
166
                                ii = self.__createSextanteRaster(i)
167
                                i = self.__createSextanteRaster(i)
168
                            else:
169
                                ii = self.__createSextanteLayer(i())
170
                                i = self.__createSextanteLayer(i())
171
                        if DEV_INFO: print "createStextenatnte Layer i :", i
172
                        paramValue2.append(i)
173
                    if self.__defaultAE == None:
174
                            try:
175
                                self.__defaultAE = AnalysisExtent(AnalysisExtent(ii))
176
                                self.__defaultAE.setCellSize(0.49) ### test
177
                                self.__defaultAE.setCellSizeZ(0.49)  ### test
178
                                #self.__defaultAE.addExtent( )
179
                                if DEV_INFO: print "----------- ini defaultAE"
180
                            except:
181
                                try:
182
                                    self.__defaultAE = AnalysisExtent(ii())
183
                                except:
184
                                    self.__defaultAE = AnalysisExtent(ii)
185
                    elif self.__defaultAE != None:
186
                            try:
187
                                ae = self.__defaultAE
188
                                #ae.addExtent(AnalysisExtent(ii))
189
                                if DEV_INFO: print "------------ diferente defaultAE"
190
                            except:
191

    
192
                                self.__defaultAE.addExtent(AnalysisExtent(ii()))
193
                    """
194
                    if self.__defaultAE == None:
195
                        try:
196
                            self.__defaultAE = AnalysisExtent(i)
197
                        except:
198
                            print "excepttttttttttttttt", i
199
                            ae = i.getRasterLayer()
200
                            self.__defaultAE = AnalysisExtent(ae)
201
                    else:
202
                        try:
203

204
                            self.__defaultAE.addExtent(AnalysisExtent(i))
205
                        except:
206
                            print 'exceptttttttttttttt 222222222"', i
207
                            ae = i.getRasterLayer()
208
                            print 'ae',ae
209
                            self.__defaultAE.addExtent(AnalysisExtent(ae))
210
                            #print self.__defaultAE
211
                    """
212

    
213
                paramValue = paramValue2
214

    
215
                if DEV_INFO:
216
                    print "PARAM VALUE 2: ", paramValue
217
                    print "****************** CONDI6: ", paramValue
218
                    print "****************** CONDI6: ", ArrayList(paramValue)
219
                newParamValue = ArrayList()
220
                for i in paramValue:
221
                    newParamValue.add(i)
222
                paramValue = newParamValue
223
                #print "***************** CONDI6: ", paramValue
224
                #from es.unex.sextante.parameters import ParameterMultipleInput
225
                #pmi = ParameterMultipleInput()
226
                #pmi.setParameterValue(paramValue)
227
                #paramValue = pmi
228
                if DEV_INFO: print "#####################################################################"
229
                return paramValue
230

    
231
    def __defineParameters_raster2sextante(self, param, paramValue):
232
                if isinstance(paramValue, str):
233
                    layer = gvsig.currentView().getLayer(paramValue)
234
                    paramValue = self.__createSextanteRaster(layer)
235
                else:
236
                    paramValue = self.__createSextanteRaster(paramValue)
237

    
238
                if DEV_INFO: print "** extent add+"
239
                if self.__defaultAE == None:
240
                    self.__defaultAE = AnalysisExtent(paramValue)
241
                else:
242
                    self.__defaultAE.addExtent(AnalysisExtent(paramValue))
243
                return paramValue
244

    
245
    def __defineParameters_table2sextante(self, param, paramValue):
246
                if isinstance(paramValue, str):
247
                    layer = gvsig.currentProject().getTable(paramValue)
248
                    paramValue = self.__createSextanteTable(layer())
249
                else:
250
                    paramValue = self.__createSextanteTable(paramValue())
251
                return paramValue
252

    
253
    def __defineParameters(self, algorithm, kwparams):
254
        """ Define input parameters """
255
        params = algorithm.getParameters()
256
        if DEV_INFO: print self.__defaultAE
257

    
258
        for i in xrange(0,params.getNumberOfParameters()):
259
            param = params.getParameter(i)
260
            if DEV_INFO: print "****************************************** PARAMETER *******************************************"
261
            #print "********************* ", dir(param)
262
            #print "********************* ", type(param)
263
            #print "********************* ", param.getParameterName()
264
            #print "********************* ", param.getParameterDescription()
265
            #print "********************* ", param.getParameterTypeName()
266
            #print "********************* ", param.getParameterTooltip()
267
            #print "********************* ", param.getParameterClass()
268
            #print "********************* ", param.getClass()
269
            #print "********************* ", param.parameterName
270
            #print "********************* ", param.parameterTypeName
271
            paramValue = self.__defineParameters_str2value( i, param, kwparams)
272
            #print type(paramValue)
273

    
274
            #Vector to SEXTANTE
275
            if DEV_INFO: print  "PARAMETER TYPE: ",param.getParameterTypeName()
276
            if param.getParameterTypeName() == "Vector Layer":
277
                paramValue = self.__defineParameters_vector2sextante(param, paramValue)
278

    
279
            # Multiple input: Vector and Raster
280
            elif param.getParameterTypeName() == "Multiple Input": #para vectores y raster
281
                paramValue = self.__defineParameters_multi2sextante(param, paramValue)
282
            #Raster to SEXTANTE
283
            elif param.getParameterTypeName() == "Raster Layer":
284
                paramValue = self.__defineParameters_raster2sextante(param, paramValue)
285
            #Table to SEXTANTE
286
            elif param.getParameterTypeName() == "Table":
287
                paramValue = self.__defineParameters_table2sextante(param, paramValue)
288
            #Set parameter value
289
            #print  "@@@@@@@@@@@@@@@@@@@@@@@@ cluster error: ", paramValue, type(paramValue)
290
            #print "@@@@@@@@@@@@@@@@@@@@@@@@ ", type(param)
291

    
292
            param.setParameterValue(paramValue)
293
            #print "@@@@@@@@@@@@@@", dir(param)
294

    
295
            #print "@@@@@@@@@@@@@@", param.isParameterValueCorrect()
296
            #print "@@@@@@@@@@@@@@ param:", param
297
            #print "@@@@@@@@@@@@@@ ", param.getParameterValueAsArrayList()
298

    
299

    
300
    def __defineExtent(self, algorithm, kwparams):
301
        """ Define Analysis Extent """
302
        if self.__defaultAE == None:
303
            if DEV_INFO: print "-------- cambiar extent"
304
            change=True
305
        else:
306
            if DEV_INFO: print "-------- no cambiar extent"
307
            change = False
308
            AExtent = self.__defaultAE
309
        changeCell = False
310
        if 'EXTENT' in kwparams.keys() and algorithm.getUserCanDefineAnalysisExtent() :
311
            changeCell = True
312
            frame = kwparams['EXTENT']
313
            if isinstance(frame, str): frame = gvsig.currentView().getLayer(frame)
314
            #print ("|"+str(frame)+"||"+str(type(frame)))
315
            if isinstance(frame, str) or isinstance(frame, DefaultViewDocument):
316
                AExtent = AnalysisExtent()
317
                if DEV_INFO: print "| EXTENT from VIEW"
318
                if isinstance(frame, DefaultViewDocument): view = frame
319
                else: view = gvsig.currentProject().getView(frame)
320
                envelope = view.getMap().getFullEnvelope()
321
                xlow = envelope.getLowerCorner().getX()
322
                ylow = envelope.getLowerCorner().getY()
323
                xup = envelope.getUpperCorner().getX()
324
                yup = envelope.getUpperCorner().getY()
325
                AExtent.setXRange(xlow, xup, False)
326
                AExtent.setYRange(ylow, yup, False)
327
                AExtent.setZRange(0, 0, False)
328
            elif isinstance(frame, DefaultFLyrRaster):
329
                if DEV_INFO: print "| EXTENT from RASTER"
330
                layer = self.__createSextanteRaster(frame)
331
                AExtent = AnalysisExtent(layer)
332
                changeCell = False
333
                #AExtent.setZRange(0, 1, True)
334
                if DEV_INFO: print AExtent
335
            elif isinstance(frame, list):
336
                if DEV_INFO: print "| EXTENT from LIST"
337
                AExtent = AnalysisExtent()
338
                AExtent.setCellSize(0.49)
339
                AExtent.setCellSizeZ(0.49)
340
                xlow, ylow, zlow, xup, yup, zup  = frame[0], frame[1], frame[2], frame[3], frame[4], frame[5]
341
                AExtent.setXRange(xlow, xup, True)
342
                AExtent.setYRange(ylow, yup, True)
343
                AExtent.setZRange(zlow, zup, True)
344
            elif isinstance(frame, FLayer):
345
                if DEV_INFO: print "| EXTENT from Layer"
346
                layer = self.__createSextanteLayer(frame())
347
                AExtent = AnalysisExtent(layer)
348
            else:
349
                raise Exception("Not Extent Define")
350
            algorithm.setAnalysisExtent(AExtent)
351

    
352
        elif change == True:
353
            if DEV_INFO: print ("| Not Extent: No input data")
354
            AExtent = AnalysisExtent()
355
            changeCell = True
356
            if self.__defaultAE != None:
357
                if DEV_INFO: print "| Extent from Algorithm Layers"
358
                AExtent = self.__defaultAE
359
            else:
360
                try:
361
                    if DEV_INFO: print "| Extent from View"
362
                    envelope = gvsig.currentView().getMap().getFullEnvelope()
363
                except:
364
                    raise Exception("None open View")
365

    
366
                if DEV_INFO: print "| Setting AExtent: ",
367
                try: #from view
368
                    xlow = envelope.getLowerCorner().getX()
369
                    ylow = envelope.getLowerCorner().getY()
370
                    zlow = 0
371
                    xup = envelope.getUpperCorner().getX()
372
                    yup = envelope.getUpperCorner().getY()
373
                    zup = 0
374
                    if DEV_INFO: print "| View: ",
375
                    if DEV_INFO: print xlow, ylow, xup,yup
376
                except: # default
377
                    xlow, ylow, zlow, xup, yup, zup = 0,0,0,100,100,0
378
                    if DEV_INFO: print "| Default:", xlow, ylow, xup, yup
379

    
380
                frame = Rectangle2D.Double(xlow, ylow, xup, yup)
381
                AExtent.setXRange(xlow, xup, False)
382
                AExtent.setYRange(ylow, yup, False)
383
                AExtent.setZRange(zlow, zup, False)
384
            algorithm.setAnalysisExtent(AExtent)
385

    
386
        #Set: cellsize
387
        if 'CELLSIZE' in kwparams.keys():
388
            AExtent.setCellSize(kwparams['CELLSIZE'])
389
            if DEV_INFO: print "| New Cellsize: ", kwparams['CELLSIZE'], AExtent.getCellSize()
390
        elif changeCell == True:
391
            AExtent.setCellSize(AExtent.getCellSize())
392
            if DEV_INFO: print "| Cellsize: ", AExtent.getCellSize()
393

    
394
        if 'CELLSIZEZ' in kwparams.keys():
395
            AExtent.setCellSizeZ(kwparams['CELLSIZEZ'])
396
            if DEV_INFO: print "| New Cellsize Z: ", kwparams['CELLSIZEZ'], AExtent.getCellSizeZ()
397
        elif changeCell == True:
398
            AExtent.setCellSize(AExtent.getCellSizeZ())
399
            if DEV_INFO: print "| CellsizeZ: ", AExtent.getCellSizeZ()
400

    
401
        if DEV_INFO: print "end extent: ", AExtent
402
        #AExtent.setZRange(0.0, 0.0, True)
403
        algorithm.setAnalysisExtent(AExtent)
404
        if DEV_INFO: print ("| Set Extent")
405

    
406
    def __defineOutput(self, algorithm, kwparams):
407
      if 'PATH' in kwparams.keys():
408
          path = kwparams['PATH']
409
          checkFilesExist(path)
410
          outputSet = algorithm.getOutputObjects()
411
          if outputSet.getOutputDataObjectsCount() == 1:
412
              out1 = outputSet.getOutput(0)
413
              out1.setOutputChannel(FileOutputChannel("New_name"))
414
              out1channel = out1.getOutputChannel()
415
              if isinstance(path, str):
416
                  out1channel.setFilename(path)
417
              elif isinstance(path, list):
418
                  out1channel.setFilename(path[0])
419
              else:
420
                  raise Exception("No valid path")
421
              if DEV_INFO: print "| PATH: Good path"
422

    
423
          elif outputSet.getOutputDataObjectsCount() > 1 and isinstance(path, list):
424
              for n in xrange(0, outputSet.getOutputDataObjectsCount()):
425
                  out1 = outputSet.getOutput(n)
426
                  out1.setOutputChannel(FileOutputChannel("New_name"))
427
                  out1channel = out1.getOutputChannel()
428
                  out1channel.setFilename(path[n])
429
                  if DEV_INFO: print "| PATH: Good path"
430
          else:
431
              raise Exception("Bad path")
432
      elif algorithm.getOutputObjects().getOutputObjectsCount()==0:
433
          if DEV_INFO: print "| Without output layers"
434
      elif algorithm.getOutputObjects().getOutput(0).getOutputChannel():
435
          output0 = algorithm.getOutputObjects().getOutput(0)
436
          out0 = output0.getOutputChannel()
437
          out0.setFilename(None)
438
          if DEV_INFO: print "| PATH: Without path"
439

    
440
    def __executeAlgorithm(self, algorithm):
441
      """Execute Algorithm"""
442
      #Check algorithm
443
      correctValues = algorithm.hasCorrectParameterValues()
444
      if DEV_INFO: print "| Parameter values:", correctValues
445
      if not correctValues: raise Exception("Not correct values")
446
      try:
447
          if DEV_INFO: print "| Pre-algorithm:", list(algorithm.algorithmAsCommandLineSentences)
448
      except:
449
          if DEV_INFO: print "| Not - algorithm"
450

    
451
      algorithm.execute( None, self.__outputFactory)
452
      print "| Algorithm:", list(algorithm.algorithmAsCommandLineSentences)
453

    
454
    def __getOutputObjects(self, algorithm):
455
      """Take outputObjets of the algorithm"""
456
      oos = algorithm.getOutputObjects()
457
      ret = dict()
458
      for i in xrange(0, oos.getOutputObjectsCount()):
459
        oo = oos.getOutput(i)
460
        value = oo.getOutputObject()
461
        if isinstance(value, FlyrVectIVectorLayer):
462
            if DEV_INFO: print "| Vector"
463
            store = value.getFeatureStore()
464
            layer = MapContextLocator.getMapContextManager().createLayer(value.getName(),store)
465
            store.dispose()
466
            ret[value.getName()] = layer
467
            layer.dispose()
468
        elif isinstance(value, IRasterLayer):
469
            if DEV_INFO: print "| Raster layer"
470
            value.postProcess()
471
            dalManager = DALLocator.getDataManager()
472
            mapContextManager = MapContextLocator.getMapContextManager()
473
            params = dalManager.createStoreParameters("Gdal Store")
474
            namefile = File(value.getFilename())
475
            params.setFile(namefile)
476
            dataStore = dalManager.createStore(params)
477
            layer = mapContextManager.createLayer(value.getName(), dataStore)
478
            ret[value.getName()] = layer
479
        else:
480
            try:
481
                ret[value.getName()] = value
482
            except:
483
                if not value == None:
484
                    x = 0
485
                    while True:
486
                        field = "value_" + str(x)
487
                        if any(field in s for s in ret.keys()):
488
                            x += 1
489
                        ret[str(x)] = value
490
                        break
491
      return ret
492

    
493

    
494
    def __applyOutputLoadParameters(self, layer, kwparams):
495

    
496
        # Filtro
497
        if "OUTPUT_FILTER" in kwparams:
498
            if kwparams["OUTPUT_FILTER"] in layer.getName():
499
                pass
500
            else:
501
                print "|| Params filter: ", kwparams["OUTPUT_FILTER"], " goes out"
502
                return None
503

    
504
        # Name of the output layer
505
        if "NAME" in kwparams:
506
            layer.setName((kwparams["NAME"]).decode("UTF-8"))
507
        elif "TOCNAME" in kwparams:
508
            layer.setName((kwparams["TOCNAME"]).decode("UTF-8"))
509
        else:
510
            layer.setName(layer.getName())
511

    
512
        # Add layer or not
513
        if "ADDLAYER" in kwparams:
514
            if kwparams["ADDLAYER"]==True:
515
                addlayer = True
516
            elif kwparams["ADDLAYER"]==False:
517
                addlayer = False
518
        else:
519
            addlayer = True #Default for add results
520

    
521
        # Where to add it
522
        if "OUTPUT_VIEW" in kwparams:
523
            outputview = (kwparams["OUTPUT_VIEW"]).decode("UTF-8")
524
            if isinstance(outputview, str):
525
                view = currentProject().getView(outputview)
526
            else:
527
                view = outputview
528
        else:
529
            view = gvsig.currentView()
530

    
531
        # Active
532
        if "VISIBLE" in kwparams:
533
            visible = kwparams["VISIBLE"]
534
        else:
535
            visible = True
536

    
537
        if addlayer==True:
538
            view.addLayer(layer)
539
        return layer
540

    
541
    def __applyOutputLoadParametersVectorial(self, layer, kwparams):
542

    
543
        # Filtro
544
        if "OUTPUT_FILTER" in kwparams:
545
            if kwparams["OUTPUT_FILTER"] in layer.getName():
546
                pass
547
            else:
548
                print "|| Params filter: ", kwparams["OUTPUT_FILTER"], " goes out"
549
                return
550

    
551

    
552
        # Add layer or not
553
        if "ADDLAYER" in kwparams:
554
            if kwparams["ADDLAYER"]==True:
555
                addlayer = True
556
            elif kwparams["ADDLAYER"]==False:
557
                addlayer = False
558
        else:
559
            addlayer = True #Default for add results
560

    
561
        # Where to add it
562
        if "OUTPUT_VIEW" in kwparams:
563
            outputview = (kwparams["OUTPUT_VIEW"]).decode("UTF-8")
564
            if isinstance(outputview, str):
565
                view = currentProject().getView(outputview)
566
            else:
567
                view = outputview
568
        else:
569
            view = gvsig.currentView()
570

    
571
        # Active
572
        if "VISIBLE" in kwparams:
573
            visible = kwparams["VISIBLE"]
574
        else:
575
            visible = True
576

    
577
        parameters = {}
578
        shpFile = layer.getFeatureStore().getFullName()
579
        parametersshp = layer.getFeatureStore().getParameters()
580
        parameters["CRS"] = gvsig.currentView().getProjectionCode()
581
        parameters["shpFile"]= shpFile #parametersshp.getSHPFileName()
582
        layer = gvsig.loadLayer("Shape", **parameters)
583

    
584
        #layer = loadLayer(layer.getFeatureStore().getFullName())
585
        if addlayer==True:
586
            # Name of the output layer
587
            if "NAME" in kwparams:
588
                layer.setName((kwparams["NAME"]).decode("UTF-8"))
589
            elif "TOCNAME" in kwparams:
590
                layer.setName((kwparams["TOCNAME"]).decode("UTF-8"))
591
            else:
592
                layer.setName(layer.getName())
593
            view.addLayer(layer)
594
        return layer
595

    
596
    def __returnOutputObjects(self, r, kwparams):
597
        if r == None: return
598
        outList = []
599
        print "| Output layers: "
600
        for value in r.values():
601
            if isinstance(value, unicode):
602
                outList.append(value.encode("UTF-8"))
603
                continue
604
            elif isinstance(value, FLyrVect):
605
                """
606

607
                parameters = {}
608

609
                parametersshp = value.getFeatureStore().getParameters()
610
                try:
611
                    parameters["CRS"] = parametersshp.getCRS()
612
                except:
613
                    parameters["CRS"] = gvsig.currentView().getProjectionCode()
614
                shpFile = value.getFeatureStore().getFullName()
615
                parameters["shpFile"]= shpFile
616
                layer = gvsig.loadLayer("Shape", **parameters)
617

618
                """
619

    
620
                print "|\t Value:", value.getName().encode("UTF-8")
621
                path = value.getDataStore().getFullName()
622
                print "|\t\tPath: ", path
623

    
624
                resultLyr = self.__applyOutputLoadParametersVectorial(value, kwparams)
625

    
626
                if resultLyr!=None:
627
                    outList.append(resultLyr)
628

    
629
            elif isinstance(value, FLayer):
630
                print "|\t Value:", value.getName()
631
                print "|\t\t", value.getFile()
632
                value = self.__applyOutputLoadParameters(value, kwparams)
633
                if value!=None:
634
                    outList.append(value)
635
            else:
636
                print "|\t Non-type \tValue: ", value
637
                outList.append(value)
638
                continue
639

    
640
        #Return object or list
641
        print "\n"
642
        print "OUTLIST: ", outList
643
        if len(outList) > 1: return outList
644
        elif len(outList) == 1: return outList[0]
645
        else: return None
646

    
647

    
648
    def execute(self, algorithmId, kwparams):
649
      """ Execute algorithm """
650
      print "| Algoritmo: ", algorithmId
651

    
652
      algorithm = self.getAlgorithms()[algorithmId]
653
      #print algorithm.getAlgorithmAsCommandLineSentences()
654

    
655
      #Input params
656
      self.__defineParameters(algorithm, kwparams)
657

    
658
      #Analisys Extension
659
      self.__defineExtent(algorithm, kwparams)
660

    
661
      #Output files
662
      self.__defineOutput(algorithm, kwparams)
663

    
664
      #Exec algorithm
665
      self.__executeAlgorithm(algorithm)
666

    
667
      #Output objects
668
      ret = self.__getOutputObjects(algorithm)
669
      r = self.__returnOutputObjects(ret, kwparams)
670

    
671
      return r
672

    
673
def runalg(algorithmId,*params, **kwparams):
674
    for i in range(0,len(params)):
675
      kwparams[i]=params[i]
676

    
677
    geoprocess = Geoprocess()
678
    r = geoprocess.execute(algorithmId, kwparams)
679
    del(geoprocess)
680
    return r
681

    
682
def algHelp(geoalgorithmId):
683
    geoprocess = Geoprocess()
684
    for algorithmId, algorithm in geoprocess.getAlgorithms().items():
685
        if algorithmId.encode('UTF-8') == geoalgorithmId.encode('UTF-8') or geoalgorithmId == "All":
686
            pass
687
        else:
688
            continue
689
        print "* Algorithm help: ", algorithm.getName().encode('UTF-8')
690
        print "*", algorithm.commandLineHelp.encode('UTF-8')
691
    del(geoprocess)
692

    
693
def algSearch(strSearch):
694
    print "\nInicio de busqueda.."
695
    geoprocess = Geoprocess()
696
    search = strSearch.lower().encode('ASCII','ignore')
697
    for algorithmId, algorithm in geoprocess.getAlgorithms().items():
698
        name = (algorithm.getName()).lower().encode('ASCII','ignore')
699
        group = (algorithm.getGroup()).lower().encode('ASCII','ignore')
700
        con1 = str(name).find(search) >= 0
701
        con2 = str(group).find(search) >= 0
702
        con3 = algorithmId.encode('ASCII').find(search) >= 0
703
        if con1 or con2 or con3:
704
            if con1 or con2:
705
                print "ID: ", algorithmId, " || GROUP: ", algorithm.getGroup().encode('UTF-8'), " || NAME: ", algorithm.getName().encode('UTF-8')
706
            else:
707
                print "*", algorithm.commandLineHelp.encode('UTF-8')
708
    print "..Busqueda finalizada\n"
709
    del(geoprocess)
710

    
711
def getProjectLayer(view,layer):
712
    """Get vector layer or raster"""
713

    
714
    try:
715
        if isinstance(view, str): view = gvsig.currentProject().getView(view)
716
        if isinstance(layer, str):
717
            return view.getLayer(layer)
718
        else:
719
            return layer
720
    except: #Bug: Raster problem with getLayer
721
        for i in gvsig.currentProject().getView(view).getLayers():
722
            if i.name == layer: return i
723

    
724
def getProjectTable(table):
725
    """Get table"""
726
    return gvsig.currentProject().getTable(table)
727

    
728
def checkFilesExist(files):
729
    """Path or Paths of files"""
730
    #raise a exception
731

    
732
    if isinstance(files, str):
733
        if os.path.isfile(files): raise Exception("File already exist" + files)
734
    elif isinstance(files, list):
735
        for fname in files:
736
            if os.path.isfile(fname): raise Exception("File already exist" + fname)
737

    
738

    
739
###
740
### MODEL TO SCRIPT
741
###
742

    
743

    
744
def model2script(pathXML, pathFile):
745
    #eliminar la ultima linea
746
    #pathXML = commonsdialog.openFileDialog("Selecciona archivo", 'C:/gsoc/')
747
    #pathXML = str(pathXML[0])
748
    #pathXML = 'C:/gsoc/test02.model'
749
    #pathFILE = 'C:/gsoc/script0002.py'
750
    import os.path
751
    if os.path.isfile(pathXML)==True:
752
        pass
753
    else:
754
        print "No valid model file path"
755
        return
756
    fileFile = open(pathXML, 'r')
757
    document = fileFile.read()
758
    import xml.dom.minidom
759
    root = xml.dom.minidom.parseString(document)
760
    #root
761
    inputObject = {}
762
    inputObjectParams = {}
763
    dataObject = {}
764
    algorithms = {}
765
    tab = "    "
766
    gvpyFile = open(pathFile, "w")
767
    #Cargamos los parametros
768
    print "\nData object"
769
    for child in root.getElementsByTagName("data_object"):
770
        #data_object - Parametros
771
        if "INNER" in child.getAttribute("key"):
772
            inputObjectParams[child.getAttribute("key")] = child.getAttribute("value")
773
        #data_object - result of algorithms
774
        else:
775
            inputObject[child.getAttribute("key")]=[child.getAttribute("value"), child.getAttribute("description").encode("UTF-8")]
776

    
777
    print "\n Attribute"
778
    for child in root.getElementsByTagName("input"):
779
        for i in child.getElementsByTagName("attribute"):
780
                if i.getAttribute("name")=="default": dataObject[child.getAttribute("name")] = i.getAttribute("value")
781

    
782
    print "\n Algorithm"
783
    order = 1
784
    for child in reversed(root.getElementsByTagName("algorithm")):
785
        print "Algoritmo: ", child
786
        keyAlgorithm = child.getAttribute("key")
787
        algorithmParams = {}
788
        algorithmParams["alg_cmd_line_name"]=child.getAttribute("alg_cmd_line_name")
789
        for i in child.getElementsByTagName("assignment"):
790
            algorithmParams[i.getAttribute("key")] = i.getAttribute("assigned_to")
791
        algorithmParams["result_of_algorithm"] = keyAlgorithm
792
        algorithms[order] = algorithmParams
793
        order +=1
794

    
795
    print "\n\n******* RESULTADO *******"
796
    print "inputObject: ", inputObject
797
    print "inputObjectParams: ", inputObjectParams
798
    print "algorithms: ", algorithms
799
    print "data object: ", dataObject
800

    
801
    #Writing script .py
802
    print "\nTransform to gvpy"
803
    for i in root.getElementsByTagName("model"):
804
        modelName = i.getAttribute("name")
805
    gvpyFile.write("# Modelo de SEXTANTE: " + modelName)
806
    gvpyFile.write(
807
"""
808
import gvsig
809
from gvsig.libs import gvpy
810
from gvsig import geom
811
import gvsig_raster
812

813
def main(*args):
814
""")
815

    
816
    print "gvpy - data_object"
817
    listInputObject = []
818
    for n in reversed(inputObject.keys()):
819
        listInputObject.append([n,inputObject[n][1]])
820

    
821
    print "gvpy - inputObjectParams"
822
    for n in (inputObjectParams.keys()):
823
        gvpyFile.write( tab + n + ' = "' + inputObjectParams[n] + '"\n' )
824

    
825
    print "gvpy - vars"
826
    for n in (dataObject.keys()):
827
        gvpyFile.write( tab + n +' = "' + dataObject[n] + '"\n\n' )
828

    
829

    
830
    print "gvpy - algorithms"
831
    #inputObject list of result algorithms names
832
    for n in reversed(sorted(algorithms.keys())): #reversed(algorithms.keys()):
833
        gvpy= ""
834
        alg = algorithms[n]
835
        #prefijo: buscar en los data_object el nombre que debe de llevar la capa resultado
836
        for i in listInputObject:
837
            if alg["result_of_algorithm"] in i[0]:
838
                prefix = i[0]
839
                description = i[1]
840
        #Escribimos el codigo del algoritmo
841
        gvpyFile.write( tab + '# '+ description + '\n')
842
        gvpy += prefix + '= gvpy.runalg("'+alg["alg_cmd_line_name"]+'"'
843
        for i in alg:
844
            if i == "alg_cmd_line_name" or i == "result_of_algorithm": continue
845
            gvpy += ', '+i+'='+ alg[i] + ''
846
        gvpy += ')'
847
        gvpyFile.write( tab + gvpy + "\n\n" )
848

    
849
    gvpyFile.close()
850

    
851
def main(*args):
852
    checkFilesExist("C:/gvsig/ran10.shp")
853
    r = runalg("generaterandomnormal", EXTENT = [0,0,0,500,500,0], MEAN =0.5, STDDEV = 0.5, ADDLAYER=False)
854
    #runalg("cluster" , INPUT=[(layer1, 0),(layer2,0)] , NUMCLASS=3)#, CELLSIZE=layer1.getCellSize(), CELLSIZEZ=1)#,EXTENT=layer1)
855
    #runalg("mergegrids", [layer1, layer2], "0")
856
    #v1 = runalg("randomvector",10, TYPE_POINT, EXTENT=[0,0,0,500,500,0], NAME="Random vector")
857

    
858
    #r = runalg("generaterandomnormal", EXTENT = [0,0,0,500,500,0], MEAN =0.5, STDDEV = 0.5)
859

    
860
    pass
861

    
862