i.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. """
  2. ***************************************************************************
  3. i.py
  4. ----
  5. Date : April 2016
  6. Copyright : (C) 2016 by Médéric Ribreux
  7. Email : mederic dot ribreux at medspx dot fr
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Médéric Ribreux'
  18. __date__ = 'April 2016'
  19. __copyright__ = '(C) 2016, Médéric Ribreux'
  20. import os
  21. from processing.tools.system import (isWindows, getTempFilename)
  22. from grassprovider.Grass7Utils import Grass7Utils
  23. from qgis.PyQt.QtCore import QDir
  24. from qgis.core import QgsProcessingParameterString
  25. from qgis.core import QgsMessageLog
  26. def orderedInput(alg, parameters, context, src, tgt, numSeq=None):
  27. """Import multiple rasters in order
  28. :param alg: algorithm object.
  29. :param parameters: algorithm parameters dict.
  30. :param context: algorithm context.
  31. :param src: Name of the source parameter.
  32. :param tgt: Name of a new input parameter.
  33. :param numSeq: List of a sequence for naming layers.
  34. """
  35. rootFilename = 'rast_{}.'.format(os.path.basename(getTempFilename(context=context)))
  36. # parameters[tgt] = rootFilename
  37. param = QgsProcessingParameterString(tgt, 'virtual input',
  38. rootFilename, False, False)
  39. alg.addParameter(param)
  40. rasters = alg.parameterAsLayerList(parameters, src, context)
  41. # Handle specific range
  42. if numSeq is None:
  43. numSeq = list(range(1, len(rasters) + 1))
  44. for idx, raster in enumerate(rasters):
  45. rasterName = '{}{}'.format(rootFilename, numSeq[idx])
  46. alg.loadRasterLayer(rasterName, raster, context, False, None, rasterName)
  47. # Don't forget to remove the old input parameter
  48. alg.removeParameter(src)
  49. def regroupRasters(alg, parameters, context, src, group, subgroup=None, extFile=None):
  50. """
  51. Group multiple input rasters into a group
  52. * If there is a subgroupField, a subgroup will automatically be created.
  53. * When an external file is provided, the file is copied into the respective
  54. directory of the subgroup.
  55. :param parameters:
  56. :param context:
  57. :param src: name of input parameter with multiple rasters.
  58. :param group: name of group.
  59. :param subgroup: name of subgroup.
  60. :param extFile: dict : parameterName:directory name
  61. """
  62. # Create a group parameter
  63. groupName = 'group_{}'.format(os.path.basename(getTempFilename(context=context)))
  64. param = QgsProcessingParameterString(group, 'virtual group',
  65. groupName, False, False)
  66. alg.addParameter(param)
  67. # Create a subgroup
  68. subgroupName = None
  69. if subgroup:
  70. subgroupName = 'subgroup_{}'.format(os.path.basename(getTempFilename(context=context)))
  71. param = QgsProcessingParameterString(subgroup, 'virtual subgroup',
  72. subgroupName, False, False)
  73. alg.addParameter(param)
  74. # Compute raster names
  75. rasters = alg.parameterAsLayerList(parameters, src, context)
  76. rasterNames = []
  77. for idx, raster in enumerate(rasters):
  78. name = '{}_{}'.format(src, idx)
  79. if name in alg.exportedLayers:
  80. rasterNames.append(alg.exportedLayers[name])
  81. # Insert a i.group command
  82. command = 'i.group group={}{} input={}'.format(
  83. groupName,
  84. ' subgroup={}'.format(subgroupName) if subgroup else '',
  85. ','.join(rasterNames))
  86. alg.commands.append(command)
  87. # Handle external files
  88. # if subgroupField and extFile:
  89. # for ext in extFile.keys():
  90. # extFileName = new_parameters[ext]
  91. # if extFileName:
  92. # shortFileName = os.path.basename(extFileName)
  93. # destPath = os.path.join(Grass7Utils.grassMapsetFolder(),
  94. # 'PERMANENT',
  95. # 'group', new_parameters[group.name()],
  96. # 'subgroup', new_parameters[subgroup.name()],
  97. # extFile[ext], shortFileName)
  98. # copyFile(alg, extFileName, destPath)
  99. alg.removeParameter(src)
  100. return groupName, subgroupName
  101. def importSigFile(alg, group, subgroup, src, sigDir='sig'):
  102. """
  103. Import a signature file into an
  104. internal GRASSDB folder
  105. """
  106. shortSigFile = os.path.basename(src)
  107. interSig = os.path.join(Grass7Utils.grassMapsetFolder(),
  108. 'PERMANENT', 'group', group, 'subgroup',
  109. subgroup, sigDir, shortSigFile)
  110. copyFile(alg, src, interSig)
  111. return shortSigFile
  112. def exportSigFile(alg, group, subgroup, dest, sigDir='sig'):
  113. """
  114. Export a signature file from internal GRASSDB
  115. to final destination
  116. """
  117. shortSigFile = os.path.basename(dest)
  118. interSig = os.path.join(Grass7Utils.grassMapsetFolder(),
  119. 'PERMANENT', 'group', group, 'subgroup',
  120. subgroup, sigDir, shortSigFile)
  121. moveFile(alg, interSig, dest)
  122. return interSig
  123. def exportInputRasters(alg, parameters, context, rasterDic):
  124. """
  125. Export input rasters
  126. Use a dict to make input/output link:
  127. { 'inputName1': 'outputName1', 'inputName2': 'outputName2'}
  128. """
  129. createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context)
  130. metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context)
  131. # Get inputs and outputs
  132. for inputName, outputName in rasterDic.items():
  133. fileName = os.path.normpath(
  134. alg.parameterAsOutputLayer(parameters, outputName, context))
  135. grassName = alg.exportedLayers[inputName]
  136. outFormat = Grass7Utils.getRasterFormatFromFilename(fileName)
  137. alg.exportRasterLayer(grassName, fileName, True, outFormat, createOpt, metaOpt)
  138. def verifyRasterNum(alg, parameters, context, rasters, mini, maxi=None):
  139. """Verify that we have at least n rasters in multipleInput"""
  140. num = len(alg.parameterAsLayerList(parameters, rasters, context))
  141. if num < mini:
  142. return False, 'You need to set at least {} input rasters for this algorithm!'.format(mini)
  143. if maxi and num > maxi:
  144. return False, 'You need to set a maximum of {} input rasters for this algorithm!'.format(maxi)
  145. return True, None
  146. # def file2Output(alg, output):
  147. # """Transform an OutputFile to a parameter"""
  148. # # Get the outputFile
  149. # outputFile = alg.getOutputFromName(output)
  150. # alg.removeOutputFromName(output)
  151. # # Create output parameter
  152. # param = getParameterFromString("ParameterString|{}|output file|None|False|False".format(output), 'GrassAlgorithm')
  153. # param.value = outputFile.value
  154. # alg.addParameter(param)
  155. # return outputFile
  156. def createDestDir(alg, toFile):
  157. """ Generates an mkdir command for GRASS7 script """
  158. # Creates the destination directory
  159. command = "{} \"{}\"".format(
  160. "MD" if isWindows() else "mkdir -p",
  161. QDir.toNativeSeparators(os.path.dirname(toFile))
  162. )
  163. alg.commands.append(command)
  164. def moveFile(alg, fromFile, toFile):
  165. """ Generates a move command for GRASS7 script """
  166. createDestDir(alg, toFile)
  167. command = "{} \"{}\" \"{}\"".format(
  168. "MOVE /Y" if isWindows() else "mv -f",
  169. QDir.toNativeSeparators(fromFile),
  170. QDir.toNativeSeparators(toFile)
  171. )
  172. alg.commands.append(command)
  173. def copyFile(alg, fromFile, toFile):
  174. """ Generates a copy command for GRASS7 script """
  175. createDestDir(alg, toFile)
  176. command = "{} \"{}\" \"{}\"".format(
  177. "COPY /Y" if isWindows() else "cp -f",
  178. QDir.toNativeSeparators(fromFile),
  179. QDir.toNativeSeparators(toFile))
  180. alg.commands.append(command)