Skip to content
Permalink
Browse files

Add i.albedo and i.cluster algorithms

  • Loading branch information
Médéric RIBREUX
Médéric RIBREUX committed Apr 24, 2016
1 parent 1b06324 commit 651302e360bbbc457a4252913694e7564af52375
@@ -0,0 +1,11 @@
i.albedo
Computes broad band albedo from surface reflectance.
Imagery (i.*)
ParameterMultipleInput|input|Name of input raster maps|3|False
ParameterBoolean|-m|MODIS (7 input bands:1,2,3,4,5,6,7)|False
ParameterBoolean|-n|NOAA AVHRR (2 input bands:1,2)|False
ParameterBoolean|-l|Landsat 5+7 (6 input bands:1,2,3,4,5,7)|False
ParameterBoolean|-a|ASTER (6 input bands:1,3,5,6,8,9)|False
ParameterBoolean|-c|Aggressive mode (Landsat)|False
ParameterBoolean|-d|Soft mode (MODIS)|False
OutputRaster|output|Albedo
@@ -0,0 +1,13 @@
i.cluster
Generates spectral signatures for land cover types in an image using a clustering algorithm.
Imagery (i.*)
ParameterMultipleInput|input|Input rasters|3|False
ParameterNumber|classes|Initial number of classes (1-255)|1|255|1|True
ParameterFile|seed|Name of file containing initial signatures|False|True
ParameterString|sample|Sampling intervals (by row and col)|None|False|True
ParameterNumber|iterations|Maximum number of iterations|1|None|30|True
ParameterNumber|convergence|Percent convergence|0.0|100.0|98.0|True
ParameterNumber|separation|Cluster separation|0.0|None|0.0|True
ParameterNumber|min_size|Minimum number of pixels in a class|1|None|17|True
OutputFile|signaturefile|Signature File
OutputFile|reportfile|Final Report File
@@ -0,0 +1,185 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
i.py
----
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
***************************************************************************
* *
* 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__ = 'Médéric Ribreux'
__date__ = 'March 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'

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

__revision__ = '$Format:%H$'

from processing.core.parameters import ParameterRaster, getParameterFromString
from processing.tools.system import isWindows


def multipleOutputDir(alg, field, basename=None):
"""
Handle multiple output of rasters into a
directory.
"""
# We need to know where is the output directory
outputDir = alg.getOutputValue(field)

# We need to grab the variable basename
if basename:
commands = ["for r in $(g.list type=rast pattern='{}*'); do".format(basename)]
# Otherwise, export everything
else:
commands = ["for r in $(g.list type=rast); do".format(basename)]
commands.append(" r.out.gdal -c -t input=${{r}} output={}/${{r}}.tif createopt=\"TFW=YES,COMPRESS=LZW\"".format(outputDir))
commands.append("done")
alg.commands.extend(commands)
alg.outputCommands.extend(commands)


def orderedInput(alg, inputParameter, targetParameterDef):
"""Inport multiple rasters in the order"""
rasters = alg.getParameterValue(inputParameter).split(';')
# TODO: make targetParameter
inputParameter = getParameterFromString(targetParameterDef)
rootFilename = '{}_'.format(alg.getTempFilename())
inputParameter.value = rootFilename
alg.addParameter(inputParameter)
for idx in range(len(rasters)):
layer = rasters[idx]
if layer in alg.exportedLayers.keys():
continue
else:
destFilename = '{}{}'.format(rootFilename, idx + 1)
alg.setSessionProjectionFromLayer(layer, alg.commands)
alg.exportedLayers[layer] = destFilename
command = 'r.external input={} band=1 output={} --overwrite -o'.format(layer, destFilename)
alg.commands.append(command)

alg.setSessionProjectionFromProject(alg.commands)

region = \
unicode(alg.getParameterValue(alg.GRASS_REGION_EXTENT_PARAMETER))
regionCoords = region.split(',')
command = 'g.region'
command += ' -a'
command += ' n=' + unicode(regionCoords[3])
command += ' s=' + unicode(regionCoords[2])
command += ' e=' + unicode(regionCoords[1])
command += ' w=' + unicode(regionCoords[0])
cellsize = alg.getParameterValue(alg.GRASS_REGION_CELLSIZE_PARAMETER)
if cellsize:
command += ' res=' + unicode(cellsize)
else:
command += ' res=' + unicode(alg.getDefaultCellsize())
alignToResolution = \
alg.getParameterValue(alg.GRASS_REGION_ALIGN_TO_RESOLUTION)
if alignToResolution:
command += ' -a'
alg.commands.append(command)
return rootFilename


def regroupRasters(alg, field, groupField, subgroupField=None):
"""
Group multiple input rasters into a group
"""
# List of rasters names
rasters = alg.getParameterFromName(field)
rastersList = rasters.value.split(';')
alg.parameters.remove(rasters)

# Insert a i.group command
group = getParameterFromString("ParameterString|{}|group of rasters|None|False|False".format(groupField))
group.value = alg.getTempFilename()
alg.addParameter(group)

if subgroupField:
subgroup = getParameterFromString("ParameterString|{}|subgroup of rasters|None|False|False".format(subgroupField))
subgroup.value = alg.getTempFilename()
alg.addParameter(subgroup)

command = 'i.group group={}{} input={}'.format(
group.value,
' subgroup={}'.format(subgroup.value) if subgroup else '',
','.join([alg.exportedLayers[f] for f in rastersList])
)
alg.commands.append(command)

# modify parameters values
alg.processCommand()

# Re-add input rasters
alg.addParameter(rasters)
# Delete group:
alg.parameters.remove(group)
if subgroupField:
alg.parameters.remove(subgroup)

if subgroupField:
return group.value, subgroup.value

return group.value


def exportInputRasters(alg, rasterDic):
"""
Export input rasters
Use a dict to make input/output link:
{ 'inputName1': 'outputName1', 'inputName2': 'outputName2'}
"""
# Get inputs and outputs
for inputName, outputName in rasterDic.iteritems():
inputRaster = alg.getParameterValue(inputName)
outputRaster = alg.getOutputFromName(outputName)
command = 'r.out.gdal -c -t --overwrite createopt="TFW=YES,COMPRESS=LZW" input={} output=\"{}\"'.format(
alg.exportedLayers[inputRaster],
outputRaster.value
)
alg.commands.append(command)
alg.outputCommands.append(command)


def verifyRasterNum(alg, rasters, mini, maxi=None):
"""Verify if we have at least n rasters in multipleInput"""
num = len(alg.getParameterValue(rasters).split(';'))
if num < mini:
return 'You need to set at least {} input rasters for this algorithm!'.format(mini)
if maxi and num > maxi:
return 'You need to set a maximum of {} input rasters for this algorithm!'.format(maxi)
return None


def file2Output(alg, output):
"""Transform an OutputFile to a parameter"""
# Get the outputFile
outputFile = alg.getOutputFromName(output)
alg.removeOutputFromName(output)

# Create output parameter
param = getParameterFromString("ParameterString|{}|output file|None|False|False".format(output))
param.value = outputFile.value
alg.addParameter(param)

return outputFile


def moveFile(alg, fromFile, toFile):
# move the file
if isWindows():
command = "MOVE /Y {} {}".format(fromFile, toFile)
else:
command = "mv -f {} {}".format(fromFile, toFile)
alg.commands.append(command)
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
i_albedo.py
-----------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
***************************************************************************
* *
* 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__ = 'Médéric Ribreux'
__date__ = 'March 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'

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

__revision__ = '$Format:%H$'

from i import verifyRasterNum


def checkParameterValuesBeforeExecuting(alg):
if alg.getParameterValue('-m'):
return verifyRasterNum(alg, 'input', 7)
elif alg.getParameterValue('-n'):
return verifyRasterNum(alg, 'input', 2)
elif alg.getParameterValue('-l') or alg.getParameterValue('-a'):
return verifyRasterNum(alg, 'input', 6)
return None
@@ -0,0 +1,54 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
i_cluster.py
------------
Date : March 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
***************************************************************************
* *
* 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__ = 'Médéric Ribreux'
__date__ = 'March 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'

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

__revision__ = '$Format:%H$'

from i import regroupRasters, file2Output, moveFile
from os import path
from ..Grass7Utils import Grass7Utils


def processCommand(alg):
# We need to extract the basename of the signature file
signatureFile = alg.getOutputFromName('signaturefile')
origSigFile = signatureFile.value
shortSigFile = path.basename(origSigFile)
alg.setOutputValue('signaturefile', shortSigFile)

# Transform output files in string parameters
signatureFile = file2Output(alg, 'signaturefile')
reportFile = file2Output(alg, 'reportfile')

# Regroup rasters
group, subgroup = regroupRasters(alg, 'input', 'group', 'subgroup')

# Re-add signature files
alg.addOutput(signatureFile)
alg.addOutput(reportFile)

# Find Grass directory
interSig = path.join(Grass7Utils.grassMapsetFolder(), 'PERMANENT', 'group', group, 'subgroup', subgroup, 'sig', shortSigFile)
moveFile(alg, interSig, origSigFile)
alg.setOutputValue('signaturefile', origSigFile)

0 comments on commit 651302e

Please sign in to comment.
You can’t perform that action at this time.