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 @ 847

History | View | Annotate | Download (33.7 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
          elif outputSet.getOutputDataObjectsCount() > 1 and isinstance(path, list):
423
              for n in xrange(0, outputSet.getOutputDataObjectsCount()):
424
                  out1 = outputSet.getOutput(n)
425
                  out1.setOutputChannel(FileOutputChannel("New_name"))
426
                  out1channel = out1.getOutputChannel()
427
                  out1channel.setFilename(path[n])
428
                  if DEV_INFO: print "| PATH: Good path"
429
          else:
430
              raise Exception("Bad path")
431

    
432
      elif algorithm.getOutputObjects().getOutput(0).getOutputChannel():
433
          output0 = algorithm.getOutputObjects().getOutput(0)
434
          out0 = output0.getOutputChannel()
435
          out0.setFilename(None)
436
          if DEV_INFO: print "| PATH: Without path"
437

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

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

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

    
491

    
492
    def __applyOutputLoadParameters(self, layer, kwparams):
493

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

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

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

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

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

    
535
        if addlayer==True:
536
            view.addLayer(layer)
537
        return layer
538

    
539
    def __applyOutputLoadParametersVectorial(self, layer, kwparams):
540

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

    
549

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

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

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

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

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

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

605
                parameters = {}
606

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

616
                """
617

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

    
622
                resultLyr = self.__applyOutputLoadParametersVectorial(value, kwparams)
623

    
624
                if resultLyr!=None:
625
                    outList.append(resultLyr)
626

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

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

    
645

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

    
650
      algorithm = self.getAlgorithms()[algorithmId]
651
      #print algorithm.getAlgorithmAsCommandLineSentences()
652

    
653
      #Input params
654
      self.__defineParameters(algorithm, kwparams)
655

    
656
      #Analisys Extension
657
      self.__defineExtent(algorithm, kwparams)
658

    
659
      #Output files
660
      self.__defineOutput(algorithm, kwparams)
661

    
662
      #Exec algorithm
663
      self.__executeAlgorithm(algorithm)
664

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

    
669
      return r
670

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

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

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

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

    
709
def getProjectLayer(view,layer):
710
    """Get vector layer or raster"""
711

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

    
722
def getProjectTable(table):
723
    """Get table"""
724
    return gvsig.currentProject().getTable(table)
725

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

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

    
736

    
737
###
738
### MODEL TO SCRIPT
739
###
740

    
741

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

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

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

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

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

811
def main(*args):
812
""")
813

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

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

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

    
827

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

    
847
    gvpyFile.close()
848

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

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

    
858
    pass
859

    
860