[GRASS-SVN] r53842 - in grass-addons/grass6/raster/mcda: r.in.drsa r.mcda.ahp r.mcda.electre r.mcda.regime r.mcda.roughset
svn_grass at osgeo.org
svn_grass at osgeo.org
Thu Nov 15 12:53:35 PST 2012
Author: gianluca
Date: 2012-11-15 12:53:34 -0800 (Thu, 15 Nov 2012)
New Revision: 53842
Modified:
grass-addons/grass6/raster/mcda/r.in.drsa/r.in.drsa.py
grass-addons/grass6/raster/mcda/r.mcda.ahp/r.mcda.ahp.py
grass-addons/grass6/raster/mcda/r.mcda.electre/dominance.c
grass-addons/grass6/raster/mcda/r.mcda.regime/regime.c
grass-addons/grass6/raster/mcda/r.mcda.roughset/r.mcda.roughset.py
Log:
Modified: grass-addons/grass6/raster/mcda/r.in.drsa/r.in.drsa.py
===================================================================
--- grass-addons/grass6/raster/mcda/r.in.drsa/r.in.drsa.py 2012-11-15 17:10:54 UTC (rev 53841)
+++ grass-addons/grass6/raster/mcda/r.in.drsa/r.in.drsa.py 2012-11-15 20:53:34 UTC (rev 53842)
@@ -1,15 +1,15 @@
#!/usr/bin/env python
############################################################################
#
-# MODULE: r.in.drsa
-# AUTHOR: Gianluca Massei - Antonio Boggia
-# PURPOSE: Import roles from *.rls file and apply those condition
-# at geographics information system for generate a raster
-# map classified under Dominance Rough Set Approach
-# COPYRIGHT: c) 2010 Gianluca Massei, Antonio Boggia and the GRASS
-# Development Team. This program is free software under the
-# GNU General PublicLicense (>=v2). Read the file COPYING
-# that comes with GRASS for details.
+# MODULE: r.in.drsa
+# AUTHOR: Gianluca Massei - Antonio Boggia
+# PURPOSE: Import roles from *.rls file and apply those condition
+# at geographics information system for generate a raster
+# map classified under Dominance Rough Set Approach
+# COPYRIGHT: c) 2010 Gianluca Massei, Antonio Boggia and the GRASS
+# Development Team. This program is free software under the
+# GNU General PublicLicense (>=v2). Read the file COPYING
+# that comes with GRASS for details.
#
#############################################################################
@@ -36,11 +36,17 @@
#%flag
#% key:k
#% description:file *.rls from software 4eMka2
+#% answer:true
#%end
#%flag
#% key:j
-#% description:file *.rls from software jMAF
+#% description:file *.rls from software jMAF (NOT YET IMPLEMENTED)
#%end
+#%flag
+#% key: l
+#% description: do not remove single rules in vector format
+#% answer:false
+#%end
@@ -50,106 +56,124 @@
import string
def parser_4eMka2_rule(tags):
- "parser file *.rls from 4eMka2 software and extract information for make new classified raster"
- rule=dict()
- rules_list=[]
- for t in tags:
- condition=[]
- decision=[]
- row=t.split()
- if(len(row)>0 and row[0]=="Rule"):
- #rules_list.append(row)
- i=row.index("=>")
- for j in range(2,i):
- if( row[j]!="&"):
- condition.append(row[j].strip('[,;]'))
- for j in range(i+1,len(row)-2):
- decision.append(row[j].strip('[,;]'))
- rule={'id_rule':row[1].strip('[.;]'),
- 'condition':condition,
- 'decision':string.join(decision),
- 'support':int(row[-2].strip('[.,;]')),
- 'strength':row[-1].strip('[,:]')}
- rules_list.append(rule)
-
- rls = open('rules',"w")
- for l in rules_list:
- factor=l['decision'].strip('()').split(' ')
- rls.write('%s=%s %s \n' % (l['id_rule'],l['id_rule'], " ".join(factor)))
- rls.close
- return rules_list
-
+ "parser file *.rls from 4eMka2 software and extract information for make new classified raster"
+ rule=dict()
+ rules=[]
+ for t in tags:
+ condition=[]
+ decision=[]
+ row=t.split()
+ if(len(row)>0 and row[0]=="Rule"):
+ #rules_list.append(row)
+ i=row.index("=>")
+ for j in range(2,i):
+ if( row[j]!="&"):
+ condition.append(row[j].strip('[,;]'))
+ for j in range(i+1,len(row)-2):
+ decision.append(row[j].strip('([,;])'))
+ rule={'id_rule':row[1].strip('[.;]'),
+ 'condition':condition,
+ 'decision':(decision[0]),
+ 'class':"_".join(decision[1:]),
+ 'support':int(row[-2].strip('[.,;]')),
+ 'strength':row[-1].strip('[,:]')}
+ rules.append(rule)
+ rls = open('rules',"w")
+ for l in rules:
+ factor=l['decision'].strip('()').split(' ')
+ rls.write('id_rule:%s - condition:%s - decision: %s - class:%s \n' % (l['id_rule'],l['condition'], l['decision'],l['class']))
+ rls.close
+ return rules
+
def parser_JAMM_rule(tags):
- "parser file *.rls from JAMM software and extract information for make new classified raster"
+ "parser file *.rls from JAMM software and extract information for make new classified raster"
-
+
def parser_mapcalc(rules,i):
- "parser to build a formula to be included in mapcalc command"
- mapalgebra="if("
- for j in rules[i]['condition'][:-1]:
- mapalgebra+= j + " && "
- mapalgebra+=rules[i]['condition'][-1]+","+rules[i]['id_rule']+",null())"
- return mapalgebra
+ "parser to build a formula to be included in mapcalc command"
+ mapalgebra="if("
+ for j in rules[i]['condition'][:-1]:
+ mapalgebra+= j + " && "
+ mapalgebra+=rules[i]['condition'][-1]+","+rules[i]['id_rule']+",null())"
+ return mapalgebra
def clean_rules(rules):
- "cleans rules to no processed vaue from rules (eg = -> ==) "
- for i in range(len(rules)):
- for j in rules[i]['condition']:
- if (j.find("<=")!=-1):
- return 1
- elif (j.find("<=")!=-1):
- return 1
- elif (j.find("=")!=-1):
- j=j.replace("=","==")
- return 0
- else:
- return -1
-
-
+ "cleans rules to no processed vaue from rules (eg = -> ==) "
+ for i in range(len(rules)):
+ for j in rules[i]['condition']:
+ if (j.find("<=")!=-1):
+ return 1
+ elif (j.find("<=")!=-1):
+ return 1
+ elif (j.find("=")!=-1):
+ j=j.replace("=","==")
+ return 0
+ else:
+ return -1
+def patch_georules(maps,outputMap):
+ labels=["_".join(m.split('_')[1:]) for m in maps]
+ labels=list(set(labels))
+ for l in labels:
+ print "mapping %s rule" % str(l)
+ map_synth=[]
+ for m in maps:
+ if l == "_".join(m.split('_')[1:]):
+ map_synth.append(m)
+ if len(map_synth)>1:
+ grass.run_command("r.patch", overwrite='True', input=(",".join(map_synth)), output=l )
+ else:
+ grass.run_command("g.copy",rast=(str(map_synth),l))
+
+ grass.run_command("r.to.vect", overwrite='True', flags='s', input=l, output=l, feature='area')
+ grass.run_command("v.db.addcol", map=l, columns='rule varchar(25)')
+ grass.run_command("v.db.update", map=l, column='rule', value=l)
+ grass.run_command("v.db.update", map=l, column='label', value=l)
+ mapstring=",".join(labels)
+
+ if len(maps)>1:
+ grass.run_command("v.patch", overwrite='True', flags='e', input=mapstring, output=outputMap)
+ else:
+ grass.run_command("g.copy",vect=(mapstring,outputMap))
+
+
def main():
- input_rules = options['input']
- outputMap = options['output']
+ input_rules = options['input']
+ outputMap = options['output']
- gregion = grass.region()
- nrows = gregion['rows']
- ncols = gregion['cols']
- ewres=int(gregion['ewres'])
- nsres=int(gregion['nsres'])
-
- input_rules=open(input_rules,"r")
- tags=input_rules.readlines()
-
- rules=[] #single rule (dictionary) in array
- maps=[]
- rules=parser_4eMka2_rule(tags)
-## clean_rules(rules)
- for i in range(len(rules)):
- mappa="rule"+rules[i]['id_rule']
- formula=parser_mapcalc(rules,i)
- grass.mapcalc(mappa +"=" +formula)
- maps.append(mappa)
-
- mapstring=",".join(maps)
-
- for m in maps:
- grass.run_command("r.to.vect", overwrite='True', flags='s', input=m, output=m, feature='area')
- grass.run_command("v.db.addcol", map=m, columns='rule varchar(25)')
- grass.run_command("v.db.update", map=m, column='rule', value=m)
- grass.run_command("v.patch", overwrite='True', flags='e', input=mapstring, output=outputMap)
-
- grass.run_command("r.patch", input=maps, flags='-o', output='rulesMap')
- grass.run_command("r.reclass", input='rulesMap', flags='-o', output='roughMAP', rules='rules')
- grass.run_command("r.to.vect", input='roughMAP', flags='-o', output=outputMap, feature='area')
-
- grass.run_command("g.remove", rast=mapstring)
- grass.run_command("g.remove", vect=mapstring)
- grass.run_command("g.remove", vect="rulesMap,roughMAP")
-
- input_rules.close()
+ gregion = grass.region()
+ nrows = gregion['rows']
+ ncols = gregion['cols']
+ ewres=int(gregion['ewres'])
+ nsres=int(gregion['nsres'])
+
+ input_rules=open(input_rules,"r")
+ tags=input_rules.readlines()
+
+ rules=[] #single rule (dictionary) in array
+ maps=[]
+ rules=parser_4eMka2_rule(tags)
+## clean_rules(rules)
+ for i in range(len(rules)):
+ mappa="r"+rules[i]['id_rule']+"_"+rules[i]['class']
+ formula=parser_mapcalc(rules,i)
+ grass.mapcalc(mappa +"=" +formula)
+ maps.append(mappa)
+
+ maplist=",".join(maps)
+ print maplist
+ patch_georules(maps,outputMap)
+
+ if not flags['l']:
+ grass.run_command("g.remove",flags="quiet", rast=maplist)
+ grass.run_command("g.remove",flags="quiet", vect=maplist)
+ input_rules.close()
+ return 0
+
+
if __name__ == "__main__":
- options, flags = grass.parser()
- sys.exit(main())
+ options, flags = grass.parser()
+ sys.exit(main())
Modified: grass-addons/grass6/raster/mcda/r.mcda.ahp/r.mcda.ahp.py
===================================================================
--- grass-addons/grass6/raster/mcda/r.mcda.ahp/r.mcda.ahp.py 2012-11-15 17:10:54 UTC (rev 53841)
+++ grass-addons/grass6/raster/mcda/r.mcda.ahp/r.mcda.ahp.py 2012-11-15 20:53:34 UTC (rev 53842)
@@ -47,10 +47,12 @@
import sys
import grass.script as grass
import numpy as np
+import warnings
def calculateWeight(pairwise):
"Define vector of weight based on eigenvector and eigenvalues"
pairwise=np.genfromtxt(pairwise, delimiter=",")
+ warnings.simplefilter("ignore", np.ComplexWarning)
eigenvalues, eigenvector=np.linalg.eig(pairwise)
maxindex=np.argmax(eigenvalues)
eigenvalues=np.float32(eigenvalues)
Modified: grass-addons/grass6/raster/mcda/r.mcda.electre/dominance.c
===================================================================
--- grass-addons/grass6/raster/mcda/r.mcda.electre/dominance.c 2012-11-15 17:10:54 UTC (rev 53841)
+++ grass-addons/grass6/raster/mcda/r.mcda.electre/dominance.c 2012-11-15 20:53:34 UTC (rev 53842)
@@ -52,11 +52,16 @@
{
int row1, col1, row2, col2;
int i, j, k, cont;
- double *row_sum_conc = G_alloc_vector(nrows * ncols);
- double *col_sum_conc = G_alloc_vector(nrows * ncols);
- double *row_sum_disc = G_alloc_vector(nrows * ncols);
- double *col_sum_disc = G_alloc_vector(nrows * ncols);
+ double *row_sum_conc;
+ double *col_sum_conc;
+ double *row_sum_disc;
+ double *col_sum_disc;
+ row_sum_conc=G_malloc(ncriteria * nrows * ncols * sizeof(double*));
+ col_sum_conc=G_malloc(ncriteria * nrows * ncols * sizeof(double*));
+ row_sum_disc=G_malloc(ncriteria * nrows * ncols * sizeof(double*));
+ col_sum_disc=G_malloc(ncriteria * nrows * ncols * sizeof(double*));
+
k = 0; /* make pairwise comparation and build concordance/discordance matrix */
for (row1 = 0; row1 < nrows; row1++)
{
@@ -69,13 +74,11 @@
for (col2 = 0; col2 < ncols; col2++)
{
double conc = 0, disc = 0;
-
for (i = 0; i < ncriteria; i++)
{
- double d =
- decision_vol[row1][col1][i] -
- decision_vol[row2][col2][i];
- if (d >= 0)
+ double d;
+ d = decision_vol[row1][col1][i] - decision_vol[row2][col2][i];
+ if (d >= 0 )
conc += weight_vect[i];
if (d < disc) /*WARNING: if(d>conc) */
/**/ disc = -d;
@@ -84,11 +87,12 @@
col_sum_conc[j] += conc;
row_sum_disc[k] += disc;
col_sum_disc[j] += disc;
+
j++; /* increase rows index up to nrows*ncols */
}
}
- k++; /* increase columns index up to nrows*ncols */
+ k++; /* increase columns index up to nrows*ncols */;
}
}
Modified: grass-addons/grass6/raster/mcda/r.mcda.regime/regime.c
===================================================================
--- grass-addons/grass6/raster/mcda/r.mcda.regime/regime.c 2012-11-15 17:10:54 UTC (rev 53841)
+++ grass-addons/grass6/raster/mcda/r.mcda.regime/regime.c 2012-11-15 20:53:34 UTC (rev 53842)
@@ -51,7 +51,9 @@
{
int row1, col1, row2, col2;
int i, j, k, cont;
- double *row_sum_regime = G_alloc_vector(nrows * ncols);
+ double *row_sum_regime;
+
+ row_sum_regime=G_malloc(ncriteria * nrows * ncols * sizeof(double*));
j = 0; /* make pairwise comparation and built regime matrix */
for (row1 = 0; row1 < nrows; row1++)
@@ -77,9 +79,9 @@
row_sum_regime[j] += reg;
}
}
+ G_percent(j, nrows*ncols, 2);
j++; /* increase rows index up to nrows*ncols */
}
- G_percent(row1, nrows, 1);
}
/*calculate concordance and discordance index and storage in decision_vol */
Modified: grass-addons/grass6/raster/mcda/r.mcda.roughset/r.mcda.roughset.py
===================================================================
--- grass-addons/grass6/raster/mcda/r.mcda.roughset/r.mcda.roughset.py 2012-11-15 17:10:54 UTC (rev 53841)
+++ grass-addons/grass6/raster/mcda/r.mcda.roughset/r.mcda.roughset.py 2012-11-15 20:53:34 UTC (rev 53842)
@@ -60,6 +60,7 @@
#%flag
#% key: l
#% description: do not remove single rules in vector format
+#% answer:false
#%end
#%flag
#% key: n
@@ -71,8 +72,8 @@
import copy
import numpy as np
from time import time, ctime
-##from grass.script import core as grass
import grass.script as grass
+import grass.script.array as garray
def BuildFileISF(attributes, preferences, decision, outputMap, outputTxt):
@@ -463,21 +464,6 @@
attributes=infosystem['attributes']
RULES=[]
-## *** AT LEAST {>= Class} - Type 1 rules *** "
- for a in Lu[1:]:
- B=a['objects']
- E=Find_rules (B, infosystem, 'one')
- for e in E:
- for i in e:
- i['class']=a['class']
- i['label']=attributes[i['criterion']-1]['name']
- i['type']='at_last'
- if (attributes[i['criterion']-1]['preference']=='gain'):
- i['sign']='>='
- else:
- i['sign']='<='
- RULES.append(e)
-
## *** AT MOST {<= Class} - Type 3 rules ***"
for b in Ld[:-1]:
@@ -493,20 +479,33 @@
else:
i['sign']='>='
RULES.append(e)
+
+## *** AT LEAST {>= Class} - Type 1 rules *** "
+ for a in Lu[1:]:
+ B=a['objects']
+ E=Find_rules (B, infosystem, 'one')
+ for e in E:
+ for i in e:
+ i['class']=a['class']
+ i['label']=attributes[i['criterion']-1]['name']
+ i['type']='at_least'
+ if (attributes[i['criterion']-1]['preference']=='gain'):
+ i['sign']='>='
+ else:
+ i['sign']='<='
+ RULES.append(e)
return RULES
def Print_rules(RULES, outputTxt):
"Print rls output file"
-
i=1
outfile=open(outputTxt+".rls","w")
outfile.write('[RULES]\n')
for R in RULES:
outfile.write("%d: " % i, )
- #"&".join(e)
for e in R:
outfile.write("( %s %s %.3f )" % (e['label'], e['sign'],e['condition'] ))
outfile.write("=> ( class %s , %s )\n" % ( e['type'], e['class'] ))
@@ -532,67 +531,79 @@
grass.mapcalc(mappa +"=" +formula)
i+=1
mapstring=",".join(maps)
- print mapstring
+
- for m in maps:
- print "mappa:", m
- grass.run_command("r.to.vect", overwrite='True', flags='s', input=m, output=m, feature='area')
- grass.run_command("v.db.addcol", map=m, columns='rule varchar(25)')
- grass.run_command("v.db.update", map=m, column='rule', value=m)
- grass.run_command("v.db.update", map=m, column='label', value=" ".join(m.split('_')[1:]))
+ #make one layer for each label rule
+ labels=["_".join(m.split('_')[1:]) for m in maps]
+ labels=list(set(labels))
+ for l in labels:
+ print "mapping %s rule" % str(l)
+ map_synth=[]
+ for m in maps:
+ if l == "_".join(m.split('_')[1:]):
+ map_synth.append(m)
+ if len(map_synth)>1:
+ grass.run_command("r.patch", overwrite='True', input=(",".join(map_synth)), output=l )
+ else:
+ grass.run_command("g.copy",rast=(str(map_synth),l))
+ print "__",str(map_synth),l
+ grass.run_command("r.to.vect", overwrite='True', flags='s', input=l, output=l, feature='area')
+ grass.run_command("v.db.addcol", map=l, columns='rule varchar(25)')
+ grass.run_command("v.db.update", map=l, column='rule', value=l)
+ grass.run_command("v.db.update", map=l, column='label', value=l)
+ mapslabels=",".join(labels)
+
if len(maps)>1:
- grass.run_command("v.patch", overwrite='True', flags='e', input=mapstring, output=outputMap)
+ grass.run_command("v.patch", overwrite='True', flags='e', input=mapslabels, output=outputMap)
else:
- grass.run_command("g.copy",vect=(mapstring,outputMap))
-
- grass.run_command("g.remove", rast=mapstring)
+ grass.run_command("g.copy",vect=(mapslabels,outputMap))
+
if not flags['l']:
+ grass.run_command("g.remove", rast=mapstring)
grass.run_command("g.remove", vect=mapstring)
-
-
+
return 0
def main():
"main function for DOMLEM algorithm"
+ #try:
+ start=time()
+ attributes = options['criteria'].split(',')
+ preferences=options['preferences'].split(',')
+ decision=options['decision']
+ outputMap= options['outputMap']
+ outputTxt= options['outputTxt']
+ out=BuildFileISF(attributes, preferences, decision, outputMap, outputTxt)
+ infosystem=FileToInfoSystem(out)
+
+ UnionOfClasses(infosystem)
+ DownwardUnionClass=DownwardUnionsOfClasses(infosystem)
+ UpwardUnionClass=UpwardUnionsOfClasses(infosystem)
+ Dominating=DominatingSet(infosystem)
+ Dominated=DominatedSet(infosystem)
+## upward union class
+ print "elaborate upward union"
+ Lu=LowerApproximation(UpwardUnionClass, Dominating) #lower approximation of upward union for type 1 rules
+ Uu=UpperApproximation(UpwardUnionClass,Dominated ) #upper approximation of upward union
+ UpwardBoundary=Boundaries(Uu, Lu)
+## downward union class
+ print "elaborate downward union"
+ Ld=LowerApproximation(DownwardUnionClass, Dominated) # lower approximation of downward union for type 3 rules
+ Ud=UpperApproximation(DownwardUnionClass,Dominating ) # upper approximation of downward union
+ DownwardBoundary=Boundaries(Ud, Ld)
+ QualityOfQpproximation(DownwardBoundary, infosystem)
+ print "RULES extraction (*)"
+ RULES=Domlem(Lu,Ld, infosystem)
+ Parser_mapcalc(RULES, outputMap)
+ Print_rules(RULES, outputTxt)
+ end=time()
+ print "Time computing-> %.4f s" % (end-start)
+ return 0
+ #except:
+ #print "ERROR! Rules does not generated!"
+ #sys.exit()
- try:
- start=time()
- attributes = options['criteria'].split(',')
- preferences=options['preferences'].split(',')
- decision=options['decision']
- outputMap= options['outputMap']
- outputTxt= options['outputTxt']
- out=BuildFileISF(attributes, preferences, decision, outputMap, outputTxt)
- infosystem=FileToInfoSystem(out)
-
- UnionOfClasses(infosystem)
- DownwardUnionClass=DownwardUnionsOfClasses(infosystem)
- UpwardUnionClass=UpwardUnionsOfClasses(infosystem)
- Dominating=DominatingSet(infosystem)
- Dominated=DominatedSet(infosystem)
- ## upward union class
- print "elaborate upward union"
- Lu=LowerApproximation(UpwardUnionClass, Dominating) #lower approximation of upward union for type 1 rules
- Uu=UpperApproximation(UpwardUnionClass,Dominated ) #upper approximation of upward union
- UpwardBoundary=Boundaries(Uu, Lu)
- ## downward union class
- print "elaborate downward union"
- Ld=LowerApproximation(DownwardUnionClass, Dominated) # lower approximation of downward union for type 3 rules
- Ud=UpperApproximation(DownwardUnionClass,Dominating ) # upper approximation of downward union
- DownwardBoundary=Boundaries(Ud, Ld)
- QualityOfQpproximation(DownwardBoundary, infosystem)
- print "RULES extraction (*)"
- RULES=Domlem(Lu,Ld, infosystem)
- Parser_mapcalc(RULES, outputMap)
- Print_rules(RULES, outputTxt)
- end=time()
- print "Time computing-> %.4f s" % (end-start)
- return 0
- except:
- print "ERROR! Rules does not generated!"
- sys.exit()
-
if __name__ == "__main__":
options, flags = grass.parser()
sys.exit(main())
More information about the grass-commit
mailing list