[GRASS-SVN] r41610 - grass-addons/raster/r.fuzzy.system

svn_grass at osgeo.org svn_grass at osgeo.org
Mon Mar 29 07:52:45 EDT 2010


Author: jarekj71
Date: 2010-03-29 07:52:44 -0400 (Mon, 29 Mar 2010)
New Revision: 41610

Added:
   grass-addons/raster/r.fuzzy.system/Makefile
   grass-addons/raster/r.fuzzy.system/description.html
   grass-addons/raster/r.fuzzy.system/f_result.png
   grass-addons/raster/r.fuzzy.system/flood.map
   grass-addons/raster/r.fuzzy.system/flood.rul
   grass-addons/raster/r.fuzzy.system/fuzzylogic.c
   grass-addons/raster/r.fuzzy.system/helpers.c
   grass-addons/raster/r.fuzzy.system/io.c
   grass-addons/raster/r.fuzzy.system/local_proto.h
   grass-addons/raster/r.fuzzy.system/main.c
   grass-addons/raster/r.fuzzy.system/map_parser.c
   grass-addons/raster/r.fuzzy.system/r.fuzzy.system.tmp.html
   grass-addons/raster/r.fuzzy.system/rule_parser.c
   grass-addons/raster/r.fuzzy.system/system.c
Log:
new files



Added: grass-addons/raster/r.fuzzy.system/Makefile
===================================================================
--- grass-addons/raster/r.fuzzy.system/Makefile	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/Makefile	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,10 @@
+MODULE_TOPDIR = ../..
+
+PGM = r.fuzzy.system
+
+LIBES = $(ROWIOLIB) $(GISLIB)
+DEPENDENCIES = $(ROWIODEP) $(GISDEP)
+
+include $(MODULE_TOPDIR)/include/Make/Module.make
+
+default: cmd

Added: grass-addons/raster/r.fuzzy.system/description.html
===================================================================
--- grass-addons/raster/r.fuzzy.system/description.html	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/description.html	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,227 @@
+<h2>OPTIONS</h2>
+
+<p>
+<DT><b>maps</b></DT>
+<DD>A text file containing maps name and  fuzzy sets connected with map definition. Maps in text file must exist on a search path, except the output map. The name of output map must be identical with that of the output name parameter. If maps are in different mapsets the name require @. Map names in database cannot contain following symbols: <B> %,$ and #</B>. Every map name must start with map name identifier:<B> %</B>. Every set definition connected with cetrain map must follow the map name and must start with set identifier :<B> $</B>. The set definition must be in braces { } and requires parameters separated by semicolon. Any whitespaces like spaces, tabs, empty lines are allowed and may used to visual format of rule file.
+
+<PRE>$ set_name {side; points; boundary_shape; hedge; height }
+<UL>
+<li><B>set_name</B>: Any name of the fuzzy set. Must not contain symbols: <i> %,$ and #</i>
+<li><B>side</B>: Option indicate if set is fuzzified of both sides (both), left or right side. Available: <i>both, left, right</i>. 
+<li><B>points</B>: A list containing 4 (A,B,C,D) or 2 A,B) points separated by comma. Points definine  location of sets of boundaries. Points may not to be in map range, but it may lead to only 0 o 1 membership for the whole map. For "both" side parameters range between A and D defines base, but range between B and C core of the fuzzy set. Between A and B and C and D are set's boundaries. If side is "both" it require 4 points, else 2 points. Points values must be not-decreasing.
+<li><B>shape</B>: Parameter definied the shape of the fuzzy boundary. Available: <i>sshaped, linear, jshaped, gshaped</i>. The same boundaires are appled to  both sides of fuzzy set.
+<li><B>hedge</B>: Shape modifier the positive number means dilatation (power the fuzzy set by 2) the negative means concetration (square root of fuzzy set). The number means number of dilatation/concetration applied on fuzzy set.
+<li><B>height</B>: Height modifier. Range from 0 to 1. The  value 1 and indicate full membership beteen points B and C. If height is lesser than one the maximum memebrship is equal to height.
+</UL>
+<P>An example of fuzzy sets definiton:
+</PRE>
+<PRE>$ moderate {both; 90,100,120,130; sshaped; 0; 1}</PRE>
+
+<B>Special notes about sets definition for output map:</B><BR>
+These sets shall be created as triangular (both sides) sets with linear boundaries, without hedge and height modifiers:
+<PRE>$ moderate {both; 0,20,20,40; linear; 0; 1}</PRE>
+</DD>
+
+<DT><b>rules</b></DT>
+<DD>A text file containing rules for classification.Th typical fuzzy rule consists of one or more antecedents and one consequent:
+
+<PRE>IF elev IS high AND distance IS low THEN probability IS small
+
+where:
+antecetends: elev IS high; distance IS low
+consequent: probability IS small
+</PRE>
+
+The rule file has his own syntax. Because module creates only one result map, the map name is ommited. Every rule starts with $ and consist of consequent name and antecedents in braces { }. All maps and sets used in atecednets must be included in the maps file. At the begining of the calculation program checks if all names and sets are included in maps file. Names of the rules must be same as sets names of the output map. The rules file use following symbols:
+<UL>
+<li>IS is symbolised by <B>=</B>
+<li>IS NOT is symbolised by <B>~</B>
+<li>AND is symbolised by <B>&</B>
+<li>OR is symbolised by <B>|</B>
+<li>To  specify the order of operators must use parentheses <B>()</B>.
+</UL>
+<P>
+
+<P>An example of fuzzy rules definiton:
+<PRE>
+$ small {distance = high & elev = high};
+</PRE>
+</DD>
+<h2>ADVANCED OPTIONS</h2>
+In most cases default options shoud not be changed.
+<P>
+<DT><b>family</b></DT>
+<DD>AND and OR operations in fuzzy logic are made with T-norms, T-conorms. T-norms, T-conorms are a generalization of the two-valued logical conjunction and  disjunction  used by boolean logic, for fuzzy logics. Because there is more than one possible generalisation of logial operations, r.fuzzy.system provides 6 most popular families for fuzzy operations:
+<ul>
+<li><b>Zadeh</b> with minimum (Godel) t-norm and maximum T-conorm;
+<li><b>product</b> with product T-norm and probabilistic sum as T-conorm;
+<li><b>drastic</b> with drastic T-norm and drastic T-conorm;
+<li><b>Lukasiewicz</b> with Lukasiewicz T-norm and bounded sum as a T-conorm;
+<li><b>Fodor</b> with nilpotent minimum as T-norm and nilpotent maximum as T-conorm;
+<li><b>Hamacher</b> (simplified) with Hamacher product as T-norm and Einstein sum as T-conorm;
+</ul>
+<P>
+<TABLE cellspacing=4>
+<TR><TH>Family</TH><TH> T-NORM (AND) </TH><TH>T CONORM (OR) </TH></TR>
+<TR><TD>ZADEH</TD><TD> MIN(x,y)</TD><TD>MAX(x,y)</TD></TR>
+<TR><TD>PRODUCT</TD><TD>	x*y	</TD><TD>x + y -x * y</TD></TR>
+<TR><TD>DRASTIC	</TD><TD>IF MAX(x, y) == 1 THEN MIN(x, y) ELSE 0	</TD><TD>IF (MIN(x, y) == 0) THEN MAX(x, y) ELSE 1</TD></TR>
+<TR><TD>LUKASIEWICZ</TD><TD>	MAX((x+y-1),0)</TD><TD>	MIN((x+y),1)</TD></TR>
+<TR><TD>FODOR	</TD><TD>IF (x+y)>1 THEN MIN(x,y) ELSE 0	</TD><TD>IF (x+y<1) THEN MAX(x,y) ELSE 1</TD></TR>
+<TR><TD>HAMACHER</TD><TD>	IF (x==y==0) THEN 0 ELSE (x*y)/((x+y)-x*y)</TD><TD>	(x+y)/(1+x*y)</TD></TR>
+</TABLE>
+</DD>
+<DT><b>imp: implication </b></DT>
+<DD>Imlication determines the method of reshapening of consequents (fuzzy set) by antecedents (single value) : 
+<UL>
+<li><B>minimum</B> means the lowest value of the antecedtents and output set definition. It ussually creates trapezoidal consequent set definition.
+<li><B>product</B> means the multiplication of the antecedtents and output set definition. It ussually creates triangular consequent set definition.
+</UL>
+</DD>
+<DT><b>defuzz: deffuzyfication method</b></DT>
+<DD>Before deffuzification all consequents are agregated into one fuzzy set. Defuzzification is the process of conversion of aggregated fuzzy set into one crisp value. The r.fuzzy.system provides 5 methods of deffuzyfication:
+<UL>
+<li><B>centeroid</B> center of mass of the fuzzy set (in practise weighted mean);
+<li><B>bisector</B> a value wchich divide fuzzy set on two parts of equal area;
+<li><B>min</B> min (right limit) of highest part of the set;
+<li><B>mean</B> mean (center) of highest part of the set;
+<li><B>max</B> max (left limit) of highest part of the set;
+</UL>
+</DD>
+<DT><b>res: universe resolution</b></DT>
+<DD>The universe is an interval between the lowest and highest values of consequent and agregated fuzzy sets. The resolution provides number of elements of these fuzzy sets. The minimum and maximum for univese is taken from the minimal and maximal values of fuzzy set definition of output map Because it has strong impact on computation time and precision of deffuzification, values lower than 30 may impact on precision of final result, but values above 200 radically slow down computation time.
+</DD>
+<h2>VISUAL OUTPUT</h2>
+<DT><b>coordinates</b></DT>
+<DD>Coordinates of points to which output universe, all consequents sets and agregate set. It is useful for visual presentation or detail analysis of fuzzy rules behaviour. In that cases calculations are peroforemd n=only for selected point.
+
+<h2>OUTPUTS</h2>
+<DT><b>output</b></DT>
+<DD>Map containing deffuzified values. Map is always of type FCELLS and contains values defined in output universe. The output name must be the same as one of maps in maps definition file.
+</DD>
+<P>
+<DT><b>multipe output flag</b></DT>
+<DD>This flag is used to create fuzzified maps for every rule. The name of the map consist of otput map name, '_' and rule name (for example: output=probs and rule name high, the map name: probs_high). Values of maps ranges from 0  to 1. If map with such name exists will be overwritten without warning.
+</DD>
+<P>
+<h2>NOTES</H2>
+<H4>Calculation of boundary shape</H4>
+Depending on type of the boundary different equation are used to determine its shape:
+<P>
+
+<B>Linear:</B> the membership is calculated according following equation:<br>
+
+<pre><code>
+value  <=  A -> x = 0
+A< value > B -> x = (value-A)/(B-A)
+B <= value >= C -> x = 1
+C< value > D -> x = (D-value)/(D-C)
+value  >=  D -> x = 0
+</code></pre>
+<B>S-shaped, G-shaped and J shaped:</B>  use following equation to sommoth boundary:
+<pre><code>
+sin(x * Pi/2)^2 (for S-shaped)
+tan(x * Pi/4)^2 (for J-shaped)
+tan(x * Pi/4)^0.5 (for G-shaped)
+
+where:
+x current fuzzy value
+A,B,C,D inflection point,
+</code></pre>
+
+
+<h2>EXAMPLE</H2>
+<P>
+Fuzzy sets are sets whose elements have degrees of membership. Zadeh (1965) introduced Fuzzy sets as an extension of the classical notion of set. Classical  membership of elements in a set are binary terms: an element either belongs or does not belong to the set. Fuzzy set theory use the gradual membership of elements in a set. A membership function use values in the real unit interval [0, 1]. Classical sets, are special cases of the membership functions of fuzzy sets and only take values 0 or 1. Classical sets are in fuzzy set theory usually called crisp sets. The fuzzy set theory can be used in a wide range of domains in which information is  imprecise, such as most of the GIS operations.
+<P>
+Suppose we want to determine the flood risk on some area (Spearfish dataset) using two maps: distance to streams and elevation above streams. We can write some common sense rules:
+<PRE>
+IF elevation IS low AND distance IS near THEN risk IS veryprobable
+IF elevation IS low OR distance IS near THEN risk IS probable
+IF elevation IS high AND distance IS far THEN risk IS unprobable
+</PRE>
+In clasical boolean sense, we would taken some limits of ideas "near" "far" etc, but what about walues near the limit? The fuzzy set uses partial memberships which abolish these restrictions. In that sense to set "near" belongs all areas with distance no more than 100 m with full membership and from 100 to 200 m with partial membership grater than 0. Over 200 m we can assume that is not near.
+This allow to formulate fuzzy rules for distance map:
+<PRE>
+near: BELOW 100 = 1; FROM 100 TO 200 = {1 TO 0}; ABOVE 200 = 0;
+</PRE>
+
+To recive final map program calculate partial fuzzy set for all rules and next agregate it into one fuzzy set. These fuzzy sets are created on value sequence called universe. Every set has the number of elements equal to universe resolution. Such set cannot be stored as map so finally is deffuzified with method choosen by user.
+<P>
+First we need two maps created with r.stream package:
+
+<PRE>
+r.stream.extract elevation=elevation.10m at PERMANENT threshold=2000 stream_rast=streams direction=dirs 
+r.stream.order stream=streams dir=dirs horton=horton
+r.mapcalc "horton3=if(horton>2,horton,null()"
+r.stream.distance stream=streams dir=dirs dem=elevation.10m method=downstream distance=distance elevation=elevation 
+</PRE>
+
+Next, to perform analysis we need two files: one with definition of map used in analysis and definition of fuzzy sets for every map, and second with fuzzy rules. For this example:
+
+<P>MAPS
+<PRE>
+#flood.map
+	%elevation
+$ low {right; 2,6; sshaped; 0; 1}
+$ high {left; 2,6; sshaped; 0; 1}
+	%distance
+$ near {right; 40,80; sshaped; 0; 1}
+$ far {left; 40,80; sshaped; 0; 1}
+#output map
+	%flood
+$ unprob {both; 0,20,20,40; linear; 0;1}
+$ prob {both; 20,40,40,60; linear; 0;1}
+$ veryprob {both; 40,60,60,80; linear; 0;1}
+
+</PRE>
+<P>RULES:
+<PRE>
+#flood.rul
+$ unprob {elevation = high & distance = far};
+$ prob {distance = near | elevation = low};
+$ veryprob {distance = near & elevation = low};
+</PRE>
+
+finally we need run r.fuzzy.system:
+<PRE>
+r.fuzzy.system vars=flood.map rules=flod.rul output=flood 
+</PRE>
+
+Resulting map should look like this below. Yellow color means no risk, red high risk, green, blue end so on moderate risk.
+<CENTER><img src=f_result.png border=1></CENTER><br>
+
+<h2>SEE ALSO</h2>
+
+<em>
+<a href="r.fuzzy.logic.html">r.fuzzy.logic</a>,
+<a href="r.fuzzy.set.html">r.fuzzy.set</a>,
+<a href="r.mapcalc.html">r.mapcalc</a>,
+</em>
+
+
+
+<h2>REFERENCES</h2>
+
+Zadeh, L.A. (1965). "Fuzzy sets". Information and Control 8 (3): 338–353. doi:10.1016/S0019-9958(65)90241-X. ISSN 0019-9958.<P>
+
+Novák, Vilém (1989). Fuzzy Sets and Their Applications. Bristol: Adam Hilger. ISBN 0-85274-583-4.<P>
+
+Klir, George J.; Yuan, Bo (1995). Fuzzy sets and fuzzy logic: theory and applications. Upper Saddle River, NJ: Prentice Hall PTR. ISBN 0-13-101171-5.<P>
+
+Klir, George J.; St Clair, Ute H.; Yuan, Bo (1997). Fuzzy set theory: foundations and applications. Englewood Cliffs, NJ: Prentice Hall. ISBN 0133410587.<P>
+
+Meyer D, Hornik K (2009a). \Generalized and Customizable Sets in R." Journal of Statistical Software, 31(2), 1{27. URL http://www.jstatsoft.org/v31/i02/.<P>
+
+Meyer D, Hornik K (2009b). sets: Sets, Generalized Sets, and Customizable Sets. R~package version~1.0, URL http://CRAN.R-project.org/package=sets.<P>
+
+<h2>AUTHOR</h2>
+Jarek  Jasiewicz
+
+
+
+<h2>SEE ALSO</h2>
+<em>
+<a href="r.fuzzy.html">r.fuzzy</a>,
+<a href="r.mapcalc.html">r.mapcalc</a>,
+</em>

Added: grass-addons/raster/r.fuzzy.system/f_result.png
===================================================================
(Binary files differ)


Property changes on: grass-addons/raster/r.fuzzy.system/f_result.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: grass-addons/raster/r.fuzzy.system/flood.map
===================================================================
--- grass-addons/raster/r.fuzzy.system/flood.map	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/flood.map	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,15 @@
+#flood.map
+
+	%elevation
+$ low {right; 2,6; sshaped; 0; 1}
+$ high {left; 2,6; sshaped; 0; 1}
+
+	%distance
+$ near {right; 40,80; sshaped; 0; 1}
+$ far {left; 40,80; sshaped; 0; 1}
+
+#output map
+	%flood
+$ unprob {both; 0,20,20,40; linear; 0;1}
+$ prob {both; 20,40,40,60; linear; 0;1}
+$ veryprob {both; 40,60,60,80; linear; 0;1}

Added: grass-addons/raster/r.fuzzy.system/flood.rul
===================================================================
--- grass-addons/raster/r.fuzzy.system/flood.rul	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/flood.rul	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,4 @@
+#flood.rul
+$ unprob {elevation = high & distance = far};
+$ prob {distance = near | elevation = low};
+$ veryprob {distance = near & elevation = low};

Added: grass-addons/raster/r.fuzzy.system/fuzzylogic.c
===================================================================
--- grass-addons/raster/r.fuzzy.system/fuzzylogic.c	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/fuzzylogic.c	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,118 @@
+#include "local_proto.h"
+
+float fuzzy(FCELL cell, SETS* set) {
+
+	float x;
+	
+	if (!set->side) { /* both left and right */
+		
+			if (cell <= set->points[0] || cell >= set->points[3])
+		return 0.;
+			if (cell >= set->points[1] && cell <= set->points[2])
+		return 1.;	
+
+		x = (cell < set->points[1]) ? (cell - set->points[0])/(set->points[1] - set->points[0])
+				: (set->points[3] - cell)/(set->points[3] - set->points[2]);
+	}
+	
+	if (set->side) { /* left: 1 OR right: 2 */
+
+			if (cell <= set->points[0])
+		return (set->side == 1) ? 0. : 1.;
+			if (cell >= set->points[1])
+		return (set->side == 1) ? 1. : 0.;
+	
+		x = (set->side == s_LEFT) ? (cell - set->points[0])/(set->points[1] - set->points[0])
+				: (set->points[1] - cell)/(set->points[1]-set->points[0]);
+	}
+
+		switch (set->shape) {
+			case s_LINEAR: break; 
+			case s_SSHAPE: x= pow(sin(x*PI2),2); break; 
+			case s_JSHAPE: x= pow(tan(x * PI4),2); break; 
+			case s_GSHAPE: x= pow(tan(x * PI4),1/2.); break;
+		}
+	
+		if(set->hedge)
+	x= (set->hedge>0)	? pow(x,pow(2,set->hedge)) : pow(x,pow(0.5,(-set->hedge)));
+
+		if(set->height<1)
+	x= x * set->height;	
+
+return (x>=0 && x<=1) ? x : -1; 
+}
+
+float f_and(float x, float y, int family) {
+
+	switch (family) {
+		
+			case l_ZADEH:
+		return MIN(x,y);
+			break;
+		
+			case l_PRODUCT:
+		return x*y;
+			break;	
+		
+			case l_DRASTIC:
+		return MAX(x, y) == 1 ? MIN(x, y) : 0;
+			break;	
+		
+			case l_LUKASIEWICZ:
+		return MAX((x+y-1),0);
+			break;
+		
+			case l_FODOR:
+		return (x+y)>1 ? MIN(x,y) : 0;	
+			break;
+			
+			case l_HAMACHER:
+		return (x==y==0) ? 0 : (x*y)/((x+y)-x*y);	
+			break;
+			
+
+				
+	}
+	return -1; /* error */
+}
+
+float f_or(float x, float y, int family) {
+			float b;
+	switch (family) {
+		
+			case l_ZADEH:
+		return MAX(x,y);
+			break;
+		
+			case l_PRODUCT:
+		return x + y -x * y;
+			break;	
+		
+			case l_DRASTIC:
+		return (MIN(x, y) == 0) ? MAX(x, y) : 1;
+			break;	
+		
+			case l_LUKASIEWICZ:
+		return MIN((x+y),1);
+			break;
+	
+			case l_FODOR:
+		return (x+y<1) ? MAX(x,y) : 1;		
+			break;
+			
+			case l_HAMACHER:
+		return (x+y)/(1+x*y);
+			break;
+	}
+	return -1; /* error */
+}
+
+
+float f_not(float x, int family) {
+	
+		if (family==l_HAMACHER)
+	return (1-x)/(1+x);
+		else
+	return ((1-x)<0 || (1-x)>1) ? -1 : 1-x;
+}
+

Added: grass-addons/raster/r.fuzzy.system/helpers.c
===================================================================
--- grass-addons/raster/r.fuzzy.system/helpers.c	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/helpers.c	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,81 @@
+#include "local_proto.h"
+
+int get_nsets(FILE* fd, fpos_t position) {
+	
+	int nsets=0;
+	fsetpos (fd, &position);
+	char buf[500];
+
+	fgetpos (fd, &position);
+
+	
+	while (fgets(buf, sizeof buf, fd)) {
+			G_strip(buf);
+
+			if (*buf == '#' || *buf == 0 || *buf=='\n')
+		continue;	
+		
+			if (*buf == '$')
+		nsets++;
+	
+			if (*buf == '%')
+		break;	
+	}
+	fsetpos (fd, &position);	
+	return nsets;	
+}
+
+
+int char_strip(char *buf, char rem)
+{
+	register char *a, *b;
+		for (a = b = buf; *a == rem || *a == ' ' || *a == ' \t'; a++) ;
+			if (a != b)
+	while ((*b++ = *a++)) ;
+     
+  return 0;
+}
+
+int char_copy(const char *buf, char *res, int start, int stop)
+{
+	register int i,j;
+		for(i=start,j=0;i<stop;res[j++] = buf[i++]);
+			res[j]='\0';
+
+  return 0;
+}
+
+
+int get_universe (void) {
+	int i,j;
+	float min=100000000., max=0;
+
+	resolution +=1;
+	
+			for (i=0;i<nmaps;++i) {
+		if (s_maps[i].output)
+			break;
+		}
+	output_index=i;	
+		
+		for (j=0;j<s_maps[i].nsets;++j) {
+	
+	min = (s_maps[i].sets[j].points[0]<min) ? 
+		s_maps[i].sets[j].points[0] : min;
+	
+		if (s_maps[i].sets[j].side)
+	max = (s_maps[i].sets[j].points[1]>max) ? 
+		s_maps[i].sets[j].points[1] : max;	
+		else
+	max = (s_maps[i].sets[j].points[3]>max) ? 
+	s_maps[i].sets[j].points[3] : max;		
+		}
+ 
+	 
+	 	universe =(float*) G_calloc(resolution, sizeof(float));
+		for (i=0;i<resolution;++i)
+	universe[i]= min + ((max-min)/resolution) * i;
+
+	return 0; 
+}
+

Added: grass-addons/raster/r.fuzzy.system/io.c
===================================================================
--- grass-addons/raster/r.fuzzy.system/io.c	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/io.c	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,156 @@
+#include "local_proto.h"
+	
+int open_maps(void) {
+	
+	int i;
+	char* mapset;
+	struct Cell_head cellhd;
+	
+	for (i=0;i<nmaps;++i) {
+		
+			if (s_maps[i].output) {
+		s_maps[i].in_buf=NULL;
+		continue;
+			}
+		
+		mapset = G_find_cell2(s_maps[i].name, "");
+	
+	    if (mapset == NULL)
+		G_fatal_error(_("Raster map <%s> not found"), s_maps[i].name);
+	
+	    if ((s_maps[i].cfd = G_open_cell_old(s_maps[i].name, mapset)) < 0)
+		G_fatal_error(_("Unable to open raster map <%s>"), s_maps[i].name);
+	
+	    if (G_get_cellhd(s_maps[i].name, mapset, &cellhd) < 0)
+		G_fatal_error(_("Unable to read file header of <%s>"), s_maps[i].name);
+	
+		s_maps[i].raster_type = G_get_raster_map_type(s_maps[i].cfd);
+		s_maps[i].in_buf = G_allocate_raster_buf(s_maps[i].raster_type);
+		
+	}
+
+return 0;
+}
+
+
+int get_rows (int row) {
+	
+	int i;
+	for (i=0;i<nmaps;++i) {
+
+			if (s_maps[i].output)
+		continue;
+
+		if (G_get_raster_row(s_maps[i].cfd, s_maps[i].in_buf, row, s_maps[i].raster_type)<0) {
+			G_close_cell(s_maps[i].cfd);
+			G_fatal_error(_("Cannot to read <%s> at row <%d>"), s_maps[i].name,row);
+		}
+	}
+
+return 0;
+}
+
+int get_cells (int col) {
+	int i;
+	CELL c;
+	FCELL f;
+	DCELL d;
+	
+		for (i=0;i<nmaps;++i) {
+
+			if (s_maps[i].output)
+		continue;
+	
+			switch (s_maps[i].raster_type) {
+
+				case CELL_TYPE:
+				c = ((CELL *) s_maps[i].in_buf)[col];
+					if (G_is_null_value(&c,CELL_TYPE)) 
+				return 1;
+					else
+				s_maps[i].cell = (FCELL) c;
+					break;
+
+				case FCELL_TYPE:
+				f = ((FCELL *) s_maps[i].in_buf)[col];
+					if (G_is_null_value(&f,FCELL_TYPE))  
+				return 1;
+					else
+				s_maps[i].cell =  (FCELL) f;
+			break;
+
+				case DCELL_TYPE:
+			d = ((DCELL *) s_maps[i].in_buf)[col];
+					if (G_is_null_value(&d,DCELL_TYPE)) 
+				return 1;
+					else
+				s_maps[i].cell =  (FCELL) d;		
+			break;
+			}
+		} /* end for */
+
+return 0;
+}
+
+int create_output_maps(void) {
+		
+	STRING connector="_";
+	int i;
+	m_outputs = (OUTPUTS* )G_malloc(nrules * sizeof (OUTPUTS));
+
+	for (i=0;i<nrules;++i) {
+		strcpy(m_outputs[i].output_name,output);
+		strcat(m_outputs[i].output_name,connector);
+		strcat(m_outputs[i].output_name,s_rules[i].outname);
+		
+			if ((m_outputs[i].ofd = G_open_raster_new(m_outputs[i].output_name, FCELL_TYPE)) < 0)
+		G_fatal_error(_("Unable to create raster map <%s>"), m_outputs[i].output_name);
+	
+		m_outputs[i].out_buf = G_allocate_f_raster_buf();
+
+	}
+
+}
+
+int process_coors (char *answer) {
+
+	struct Cell_head window;
+	double x, y;
+	int i, j;
+	int r,c;
+	int num_points;
+	float result;
+	
+	G_get_window(&window);
+	num_points=sscanf(answer,"%lf,%lf", &x, &y);
+
+  r= (int) G_easting_to_col	(	x, &window); 
+  c= (int) G_northing_to_row	(	y, &window); 
+	
+	get_rows(r);
+	get_cells(c);
+	result=implicate();
+	
+				for (i=0;i<nrules;++i)
+		
+		fprintf(stdout,"ANTECEDENT %s: %5.3f\n",s_rules[i].outname,antecedents[i]);
+		fprintf(stdout,"RESULT (deffuzified):  %5.3f\n",result);
+	
+	
+	fprintf(stdout,"UNIVERSE,");
+			for (i=0;i<nrules;++i)
+		fprintf(stdout,"%s,",s_rules[i].outname);
+	fprintf(stdout,"AGREGATE \n");	
+	
+				for (i=0;i<resolution;++i) 
+		for (j=0;j<nrules+2;++j) {
+			fprintf(stdout,"%5.3f",visual_output[i][j]);
+				if (j<nrules+1)
+			fprintf(stdout,",");
+				else
+			fprintf(stdout,"\n");	
+		}
+	
+	exit(EXIT_SUCCESS);
+}
+

Added: grass-addons/raster/r.fuzzy.system/local_proto.h
===================================================================
--- grass-addons/raster/r.fuzzy.system/local_proto.h	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/local_proto.h	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,183 @@
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <grass/gis.h>
+#include <grass/glocale.h>
+
+#ifdef MAIN
+#  define GLOBAL
+#else
+#  define GLOBAL extern
+#endif
+
+/*
+PI2= PI/2
+PI4= PI/4
+*/
+#ifndef PI2
+	#define PI2 (2*atan(1))
+#endif
+
+#ifndef PI4
+	#define PI4 (atan(1))
+#endif
+
+#define STACKMAX 50
+#define VARMAX 31
+
+#define MAX(a,b) ((a) > (b) ? (a) : (b))
+#define MIN(a,b) ((a) < (b) ? (a) : (b))
+
+
+typedef char* STRING;
+
+typedef enum {
+l_ZADEH,
+l_PRODUCT,
+l_DRASTIC,
+l_LUKASIEWICZ,
+l_FODOR,
+l_HAMACHER
+} logics;
+
+typedef enum {
+s_LINEAR,
+s_SSHAPE,
+s_JSHAPE,
+s_GSHAPE
+} shapes;
+
+typedef enum {
+	s_BOTH,
+	s_LEFT,
+	s_RIGHT
+} sides;	
+
+typedef enum {
+	i_MIN,
+	i_PROD
+} implications;	
+
+typedef enum {
+	d_CENTEROID,
+	d_BISECTOR,
+	d_MINOFHIGHEST,
+	d_MAXOFHIGHEST,
+	d_MEANOFHIGHEST
+} defuzz;
+
+typedef enum {
+	E, /* ERROR */
+	S, /* SHIFT */
+	R, /* REDUCE */
+	A  /* ACCEPT */
+} actions;
+
+typedef enum {
+	t_START,	/* { */
+	t_AND,		/* & */
+	t_OR,			/* | */
+	t_IS_NOT,		/* ~ */
+	t_IS,			/* = */
+	t_LBRC,		/* ( */
+	t_RBRC,		/* ) */
+	t_STOP,		/* } */
+	t_size,		/* number of tokens */
+	t_VAL		/* value a product of MAP and VARIABLE */
+} tokens;
+
+typedef struct _sets { /* membership definition */
+	char setname[21];
+	sides side;
+	float points[4];
+	shapes shape; 
+	int hedge; 
+	float height;
+}SETS;
+
+typedef struct map {
+	char name[30];
+	int nsets;
+	int output; /* is output map? */
+	RASTER_MAP_TYPE raster_type;
+	fpos_t position;
+	void *in_buf;
+	float cell;
+	int cfd; /* file descriptor */
+	SETS *sets;
+} MAPS;
+
+typedef struct valuestacks {
+	float* value;
+	SETS* set;
+	char oper;
+	} VALUES;
+
+
+typedef struct rule {
+	char outname[20];
+	int output_set_index;
+	char parse_stack[STACKMAX][VARMAX]; 
+	int work_stack[STACKMAX];
+	VALUES value_stack[STACKMAX];
+	float weight;
+} RULES;
+
+typedef struct _outs {
+	char output_name[52];
+	int ofd; /* output file descriptor */
+	float* out_buf;
+} OUTPUTS;	
+
+
+STRING var_name_file;
+STRING rule_name_file;
+STRING output;
+MAPS* s_maps;
+RULES* s_rules;
+OUTPUTS* m_outputs;
+float** visual_output;
+float* universe;
+float* antecedents;
+int nmaps, nrules, output_index, multiple, coor_proc;
+int resolution;
+implications implication;
+defuzz defuzzyfication;
+logics family;
+
+char** rules;
+
+int char_strip(char *buf, char rem);
+int char_copy(const char *buf, char *res, int start, int stop);
+int get_nsets(FILE* fd, fpos_t position);
+int get_universe (void);
+
+int parse_map_file (STRING file);
+int parse_rule_file (STRING file);
+int parser (void);
+int open_maps(void);
+int create_output_maps(void);
+int get_rows(int row);
+int get_cols(int col);
+
+
+int parse_sets (SETS* set, char buf[], const char mapname[]);
+int parse_rules (int rule_num, int n, char buf[]);
+int process_coors (char *answer);
+
+float implicate (void);
+float parse_expression(int n);
+float defuzzify(float *agregate,int defuzzification, float max_antecedent);
+
+float f_and(float cellx, float celly, int family);
+float f_or(float cellx, float celly, int family);
+float f_not(float cellx, int family);
+float fuzzy(FCELL cell, SETS* set);
+
+
+int parse(void);
+
+
+
+void display (void);

Added: grass-addons/raster/r.fuzzy.system/main.c
===================================================================
--- grass-addons/raster/r.fuzzy.system/main.c	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/main.c	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,228 @@
+/*
+ * 
+ * 
+ */
+
+#define MAIN
+#include "local_proto.h"
+
+int main(int argc, char **argv)
+{
+	struct Option *file_vars, 
+								*file_rules, 
+								*par_family,
+								*par_resolution,
+								*par_defuzzify,
+								*par_implication,
+								*in_coor_opt,
+								*opt_output;
+		
+	struct History history;
+	
+	struct Flag *out_multiple;
+	
+	int nrows, ncols;
+	int row, col;
+	int outfd;
+	float tmp;
+	FCELL *out_buf;		
+		
+	int i,j, n;
+	G_gisinit(argv[0]);
+
+  file_vars = G_define_standard_option(G_OPT_F_INPUT);
+  file_vars->key = "maps";
+  file_vars->required = NO;
+  file_vars->description = _("Name of fuzzy variable file");
+    
+  file_rules = G_define_standard_option(G_OPT_F_INPUT);
+  file_rules->key = "rules";
+  file_rules->required = NO;
+  file_rules->description = _("Name of rules file");
+    
+	par_family=G_define_option();
+	par_family->key = "family";
+	par_family->type = TYPE_STRING;
+	par_family->options = "Zadeh,product,drastic,Lukasiewicz,Fodor,Hamacher";
+	par_family->answer = "Zadeh";
+	par_family->required = YES;
+	par_family->description = _("Fuzzy logic family");
+	par_family->guisection = _("Advanced options");
+
+	par_defuzzify=G_define_option();
+	par_defuzzify->key = "defuz";
+	par_defuzzify->type = TYPE_STRING;
+	par_defuzzify->options = "centeroid,bisector,min,max,mean";
+	par_defuzzify->answer = "bisector";
+	par_defuzzify->required = YES;
+	par_defuzzify->description = _("Defuzzyfication method");
+	par_defuzzify->guisection = _("Advanced options");
+	
+	par_implication=G_define_option();
+	par_implication->key = "imp";
+	par_implication->type = TYPE_STRING;
+	par_implication->options = "minimum, product";
+	par_implication->answer = "minimum";
+	par_implication->required = YES;
+	par_implication->description = _("Implication method");
+	par_implication->guisection = _("Advanced options");
+	
+	par_resolution=G_define_option();
+	par_resolution->key = "res";
+	par_resolution->type = TYPE_INTEGER;
+	par_resolution->answer = "100";
+	par_resolution->required = YES;
+	par_resolution->description = _("Universe resolution");
+	par_resolution->guisection = _("Advanced options");
+	
+	in_coor_opt = G_define_option();	/* input coordinates de outlet */
+  in_coor_opt->key = "coors";
+  in_coor_opt->type = TYPE_STRING;
+  in_coor_opt->key_desc = "x,y";
+  in_coor_opt->answer = NULL;
+  in_coor_opt->required = NO;
+  in_coor_opt->multiple = NO;
+  in_coor_opt->description = "Coordinate of cell for witch output  detail data";
+  in_coor_opt->guisection = _("Visual Output");
+
+  out_multiple = G_define_flag();
+  out_multiple->key = 'm';
+  out_multiple->description = _("Create addational fuzzy output maps for every rule");
+  
+  
+  opt_output = G_define_standard_option(G_OPT_R_OUTPUT);
+  opt_output->description = _("Name of output file");
+    
+    if (G_parser(argc, argv))
+	exit(EXIT_FAILURE);
+		
+	
+	var_name_file=file_vars->answer;
+	rule_name_file=file_rules->answer;
+	output = opt_output->answer;
+	multiple = (out_multiple->answer != 0);
+	coor_proc = (in_coor_opt->answer) ? 1 : 0;
+	
+	resolution = atoi(par_resolution->answer);
+		if(resolution<10)
+	G_fatal_error(_("Universe resolution too small, choose greater value"));
+			if(resolution>500)
+	G_warning(_("Universe resolution is very high, computation may take a long time"));
+
+	  		if (!strcmp(par_family->answer, "Zadeh"))
+	family=l_ZADEH;
+		else if (!strcmp(par_family->answer, "product"))
+	family=l_PRODUCT;
+		else if (!strcmp(par_family->answer, "drastic"))
+	family=l_DRASTIC;
+		else if (!strcmp(par_family->answer, "Lukasiewicz"))
+	family=l_LUKASIEWICZ;
+		else if (!strcmp(par_family->answer, "Fodor"))
+	family=l_FODOR;
+			else if (!strcmp(par_family->answer, "Hamacher"))
+	family=l_HAMACHER;
+	
+				 if (!strcmp(par_implication->answer, "minimum"))
+	implication=i_MIN;
+		else if (!strcmp(par_implication->answer, "product"))
+	implication=i_PROD;
+
+	  		if (!strcmp(par_defuzzify->answer, "centeroid"))
+	defuzzyfication=d_CENTEROID;
+		else if (!strcmp(par_defuzzify->answer, "bisector"))
+	defuzzyfication=d_BISECTOR;
+		else if (!strcmp(par_defuzzify->answer, "min_of_heightest"))
+	defuzzyfication=d_MINOFHIGHEST;
+		else if (!strcmp(par_defuzzify->answer, "max_of_heightest"))
+	defuzzyfication=d_MAXOFHIGHEST;
+		else if (!strcmp(par_defuzzify->answer, "mean_of_heightest"))
+	defuzzyfication=d_MEANOFHIGHEST;
+			
+	nrows = G_window_rows();
+	ncols = G_window_cols();
+	
+	parse_map_file (var_name_file);
+	parse_rule_file (rule_name_file);
+	get_universe();
+	open_maps();
+	
+		if(coor_proc)
+	process_coors (in_coor_opt->answer);
+		
+	   if ((outfd = G_open_raster_new(output, FCELL_TYPE)) < 0)
+	G_fatal_error(_("Unable to create raster map <%s>"), output);
+	out_buf = G_allocate_f_raster_buf();
+	
+	
+	
+		if(multiple)
+	create_output_maps();
+	
+		G_message("Calculate...");
+	
+		for (row=0;row<nrows;++row) {
+			G_percent(row, nrows, 2);
+			get_rows(row);
+				for (col=0; col<ncols;++col) {
+
+					if(get_cells(col)) {
+						G_set_f_null_value(&out_buf[col],1);
+							
+							if(multiple) {
+									for (i=0;i<nrules;++i)
+								G_set_f_null_value(&m_outputs[i].out_buf[col],1);	
+							}	
+					}	else {
+						out_buf[col]=implicate();
+							if (out_buf[col]==-9999)
+						G_set_f_null_value(&out_buf[col],1);	
+							
+							if(multiple) {
+									for (i=0;i<nrules;++i)
+								m_outputs[i].out_buf[col]=antecedents[i];
+							}
+					}
+				}	
+
+					if (G_put_raster_row(outfd, out_buf, FCELL_TYPE) < 0)
+	    G_fatal_error(_("Failed writing raster map <%s> at row <%d>"), output,row);
+	    
+						if(multiple)
+					for (i=0;i<nrules;++i)
+						if (G_put_raster_row(m_outputs[i].ofd, m_outputs[i].out_buf, FCELL_TYPE) < 0)
+	    G_fatal_error(_("Failed writing raster map <%s> at row <%d>"), m_outputs[i].output_name,row);
+		}
+		G_percent(row, nrows, 2);
+
+	
+	G_message("Close...");
+	for (i=0;i<nmaps;++i) {
+			if (s_maps[i].output)
+		continue;
+			
+		G_free(s_maps[i].in_buf);
+		G_close_cell(s_maps[i].cfd);
+	}
+
+	G_free(out_buf);
+	G_close_cell(outfd);
+	G_short_history(output, "raster", &history);
+	G_command_history(&history);
+	G_write_history(output, &history);
+	
+			if(multiple)
+	for (i=0;i<nrules;++i) {
+		G_free(m_outputs[i].out_buf);
+		G_close_cell(m_outputs[i].ofd);
+		G_short_history(m_outputs[i].output_name, "raster", &history);
+		G_command_history(&history);
+		G_write_history(m_outputs[i].output_name, &history);
+	}	
+G_message("Done!");
+exit(EXIT_SUCCESS);
+
+}
+
+
+
+

Added: grass-addons/raster/r.fuzzy.system/map_parser.c
===================================================================
--- grass-addons/raster/r.fuzzy.system/map_parser.c	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/map_parser.c	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,213 @@
+#include "local_proto.h"
+
+int parse_map_file (STRING file) 
+{	
+	FILE* fd;
+	int line=0;
+	char buf[500];
+	STRING mapset;
+	char map[30];
+	int nmaps2=0, nsets=0;
+	fpos_t init;
+	fpos_t position;
+	int set_num;
+	
+	int i;
+	
+	fd = fopen(file, "r");
+			if (!fd)
+	G_fatal_error(_("Cannot open varaible file '%s'"), file);
+
+	fgetpos (fd, &init);
+	
+	nmaps=0; 
+	/* number of maps */
+	while (fgets(buf, sizeof buf, fd)) {
+		G_strip(buf);
+				if (*buf != '%')
+		continue;
+		nmaps++;
+	}
+	s_maps=(MAPS*)G_malloc(nmaps * sizeof(MAPS));
+	fsetpos (fd, &init); /* reset position */
+	
+	while (fgets(buf, sizeof buf, fd)) {
+			line++;
+	
+	G_strip(buf);
+		if (*buf == '#' || *buf == 0 || *buf=='\n')
+	continue;	
+	
+		if (*buf != '%' && *buf !='$')
+	G_fatal_error(_("Wrong syntax at line %d: line must start with #, % or $ or be empty line"), line);
+	
+		if (*buf == '%') {
+	
+			fgetpos (fd, &position);
+
+			sscanf(buf, "%[^\n]", map);
+			char_strip(map,'%');
+			G_strip(map);
+			mapset = G_find_cell2(map, "");
+
+				if (mapset == NULL && strcmp(map,output))
+			G_fatal_error(_("Raster map <%s> not found"), map);
+			
+			G_strcpy(s_maps[nmaps2].name,map);
+			s_maps[nmaps2].position=position;
+			s_maps[nmaps2].nsets=get_nsets(fd,position);
+			s_maps[nmaps2].output= (strcmp(map,output)) ? 0 : 1;
+			
+				if (!s_maps[nmaps2].nsets)
+			G_warning(_("map <%s> has no rules"),s_maps[nmaps2].name);
+
+					if (s_maps[nmaps2].nsets)
+			s_maps[nmaps2].sets = (SETS *)G_malloc(s_maps[nmaps2].nsets * sizeof(SETS));
+			
+			set_num=0;
+			while (fgets(buf, sizeof buf, fd)) {
+				G_strip(buf);
+
+					if (*buf == '#' || *buf == 0 || *buf=='\n')
+				continue;
+						if (*buf == '%')
+				break;		
+
+				parse_sets(&s_maps[nmaps2].sets[set_num++],buf,s_maps[nmaps2].name);
+
+			}
+			fsetpos (fd, &position);
+
+				if (nmaps2++ > nmaps)
+			G_fatal_error(_("number of maps do not match"));
+			
+		}
+   
+	} /* end while */
+	
+	fclose(fd);
+	return 0;
+}
+
+
+int parse_sets (SETS* set, char buf[], const char mapname[]) {
+	
+	char tmp[20];
+	int i;
+	
+	char_strip(buf,'$');
+	
+	{ /* check length of fuzzy value (cannot be longer than 20) */
+	sscanf(buf, "%[^{] %[^\n]",tmp,buf);
+	G_strip(tmp);
+
+		if(strlen(tmp)<21)
+	G_strcpy(set->setname,tmp);
+		else
+	G_fatal_error(_("Map: <%s>, Membership: <%s>: Value name cannot be longer than 20 chars, but has %d chars"),
+		mapname,tmp,strlen(tmp));
+	} /* check length of fuzzy value */
+
+	{ /* check if side is valid (both,left,right) */
+	int done=1;
+	STRING sides[]={"both","left","right"};
+	
+	char_strip(buf,'{');
+	sscanf(buf, "%[^;] %[^\n]", tmp,buf);
+	
+	done=0;
+		for(i=0;i<3;++i) 
+	if(strcmp(tmp,sides[i])==0) {
+		done=1;
+		break;
+		}	
+		
+		if (done)
+	set->side=i;
+		else
+	G_fatal_error(_(" Map: <%s>, Membership: <%s>:  <side> parameter must be:  <left,right,both> but is: <%s>"),
+		mapname, set->setname, tmp);
+	} /* end check if side is valid */
+	
+	
+		{ /* check number of points and order.  Point number limited to 10 chars including coma*/
+	char p[11];
+	int npoints;
+		
+	char_strip(buf,';');
+	sscanf(buf, "%[^;] %[^\n]", tmp,buf);
+	char_strip(tmp,';');
+	
+	npoints= set->side ? 2 : 4;
+	
+		for (i=0;i<npoints;++i) {
+	sscanf(tmp, "%[^,] %[^\n]", p,tmp);
+
+			if(tmp[0]!=',' && i<(npoints-1))
+	G_fatal_error(_("Map: <%s>, Variable: <%s>: Require %d points but has %d"),
+		mapname, set->setname, npoints,  i+1);
+		
+			if(sscanf(p,"%f",&set->points[i])!=1)
+		G_fatal_error(_("Map: <%s>, Variable: <%s>: Points must be numeric  but is: %s or space between '-' and digit"),
+		mapname, set->setname, p);	
+	
+	char_strip(tmp,',');
+	
+		if (i>0 && (set->points[i] < set->points[i-1]))
+	G_fatal_error(_("Map: <%s>, Membership: <%s>: Points sequence must be non-declining"),
+		mapname, set->setname);
+		}
+	
+	} /* check number of points and order */
+	
+	
+	{ /* check if shape is valid (linear,sshaped,jshaped,gshaped) */
+	int done=1;
+	STRING shapes[]={"linear","sshaped","jshaped", "gshaped"};
+	
+	char_strip(buf,';');
+	sscanf(buf, "%[^;] %[^\n]", tmp,buf);
+	
+	done=0;
+		for(i=0;i<4;++i) 
+	if(strcmp(tmp,shapes[i])==0) {
+		done=1;
+		break;
+		}	
+		
+		if (done)
+	set->shape=i;
+		else
+	G_fatal_error(_(" Map: <%s>, Variable: <%s>:  <shape> parameter must be: <linear,sshaped,jshaped,gshaped> but is: <%s>"),
+		mapname, set->setname, tmp);
+	} /* end check if shape is valid */
+	
+	
+	{ /* check if hedge is valid  (integer) */
+	char_strip(buf,';');
+	sscanf(buf, "%[^;] %[^\n]", tmp,buf);
+	
+			if(sscanf(tmp,"%d",&set->hedge)!=1)
+	G_fatal_error(_("Map: <%s>, variable: <%s>: Hedge must be numeric  but is: %s or space between '-' and digit"),
+		mapname, set->setname, tmp);
+	
+	} /* end check if hedge is valid */
+	
+	
+		{ /* check if height is valid  (float 0-1) */
+	char_strip(buf,';');
+	sscanf(buf, "%[^}] %[^\n]", tmp,buf);
+
+			if(sscanf(tmp,"%f",&set->height)!=1)
+	G_fatal_error(_("Map: <%s>, Variable: <%s>: Height must be  non-negative numeric lesser than 1 but is: %s"),
+		mapname, set->setname, tmp);
+		
+			if(set->height<=0 || set->height>1)
+	G_fatal_error(_("Map: <%s>, Variable: <%s>: Height must be  non-negative numeric lesser than 1 but is: %f"),
+		mapname, set->setname, set->height);		
+	
+	} /* end check if height is valid */
+
+return 0;
+}	
+

Added: grass-addons/raster/r.fuzzy.system/r.fuzzy.system.tmp.html
===================================================================
--- grass-addons/raster/r.fuzzy.system/r.fuzzy.system.tmp.html	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/r.fuzzy.system.tmp.html	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,308 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>GRASS GIS manual: r.fuzzy.system</title>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<link rel="stylesheet" href="grassdocs.css" type="text/css">
+</head>
+<body bgcolor="white">
+
+<img src="grass_logo.png" alt="GRASS logo"><hr align=center size=6 noshade>
+
+<h2>NAME</h2>
+<em><b>r.fuzzy.system</b></em> <h2>KEYWORDS</h2>
+<h2>SYNOPSIS</h2>
+<b>r.fuzzy.system</b><br>
+<b>r.fuzzy.system help</b><br>
+<b>r.fuzzy.system</b> [-<b>m</b>]  [<b>maps</b>=<em>name</em>]   [<b>rules</b>=<em>name</em>]  <b>family</b>=<em>string</em> <b>defuz</b>=<em>string</em> <b>imp</b>=<em>string</em> <b>res</b>=<em>integer</em>  [<b>coors</b>=<em>x,y</em>]  <b>output</b>=<em>name</em>  [--<b>overwrite</b>]  [--<b>verbose</b>]  [--<b>quiet</b>] 
+
+<h3>Flags:</h3>
+<DL>
+<DT><b>-m</b></DT>
+<DD>Create addational fuzzy output maps for every rule</DD>
+
+<DT><b>--overwrite</b></DT>
+<DD>Allow output files to overwrite existing files</DD>
+<DT><b>--verbose</b></DT>
+<DD>Verbose module output</DD>
+<DT><b>--quiet</b></DT>
+<DD>Quiet module output</DD>
+</DL>
+
+<h3>Parameters:</h3>
+<DL>
+<DT><b>maps</b>=<em>name</em></DT>
+<DD>Name of fuzzy variable file</DD>
+
+<DT><b>rules</b>=<em>name</em></DT>
+<DD>Name of rules file</DD>
+
+<DT><b>family</b>=<em>string</em></DT>
+<DD>Fuzzy logic family</DD>
+<DD>Options: <em>Zadeh,product,drastic,Lukasiewicz,Fodor,Hamacher</em></DD>
+<DD>Default: <em>Zadeh</em></DD>
+
+<DT><b>defuz</b>=<em>string</em></DT>
+<DD>Defuzzyfication method</DD>
+<DD>Options: <em>centeroid,bisector,min,max,mean</em></DD>
+<DD>Default: <em>bisector</em></DD>
+
+<DT><b>imp</b>=<em>string</em></DT>
+<DD>Implication method</DD>
+<DD>Options: <em>minimum, product</em></DD>
+<DD>Default: <em>minimum</em></DD>
+
+<DT><b>res</b>=<em>integer</em></DT>
+<DD>Universe resolution</DD>
+<DD>Default: <em>100</em></DD>
+
+<DT><b>coors</b>=<em>x,y</em></DT>
+<DD>Coordinate of cell for witch output  detail data</DD>
+
+<DT><b>output</b>=<em>name</em></DT>
+<DD>Name of output file</DD>
+
+</DL>
+<h2>OPTIONS</h2>
+
+<p>
+<DT><b>maps</b></DT>
+<DD>A text file containing maps name and and connected with map fuzzy sets definition. Maps in text file must exist in a search path, except the output map. The name oof output map must be identical with that output name parameter. If maps are teken from different mapsets the name require @. Map names in database cannot contain following symbols: <B> %,$ and #</B>. Every map name must start with map name identifier:<B> %</B>. Every set definition connected with cetrain map must follow the map name and must start with set identifier :<B> $</B>, and naturally finish with EOL. The set definition must be in braces { } and requires parameters separated by semicolon. Any whitespaces like spaces, tabs, empty lines are allowed and may used to visual format of rule file.
+
+<PRE>$ set_name {side; points; boundary_shape; hedge; height }</PRE>
+<UL>
+<li><B>set_name</B>: Any name of fuzzy set. Must not contain symbols: <i> %,$ and #</i>
+<li><B>side</B>: Option indicat if set is fuzzified ob both side s (both), left or right side. See description for details. Available: <i>both, left, right</i>. 
+<li><B>points</B>: A list containing 4 (A,B,C,D) or 2 A,B) points searated by comma. defining set boundaries. Points must not to be in map range, but it may lead to only 0 o 1 membership for the whole map. For "both" side parameters range between A and D defines base, but range between B and C core of the fuzzy set. Between A and B and C and D are set's boundaries. If side is "both" it require 4 points, else 2 points.
+<li><B>shape</B>: Parameter definied the shape of the fuzzy boundary. Available: <i>sshaped, linear, jshaped, gshaped</i>. The same boundaires are appled to  both sides of fuzzy set.
+<li><B>hedge</B>: Shape modifier the positive number means dilatation (power of fuzzy set by 2) the negative means concetration (square root of fuzzy set). The number means number of dilatation/concetration applied on fuzzy set.
+<li><B>height</B>: Height modifier. Range from 0 to 1. The  value 1 and indicate full membership beteen points B and C. If height is lesser than one the maximum memebrship is equal to height.
+</UL>
+<h3>An example of fuzzy sets definiton for elev map:</h3>
+<PRE>
+  %elev
+$ low {right; 60,100; sshaped; 0; 1}
+$ moderate {both; 90,100,120,130; sshaped; 0; 1}
+$ high {left; 120,130; sshaped; 0; 1}
+</PRE>
+
+<center>
+<h3>Fuzzy set definition:<h3>
+<img src=set.png border=1><br>
+</center>
+</DD>
+<p>
+<H3>Special notes about output fuzzy set definition</H3>
+
+<DT><b>rules</b></DT>
+<DD>A text file containing rules for classification.Th typical fuzzy rule consists of antecedents and consequent:
+
+<PRE>IF elev IS high AND wetness IS low THEN probability IS small</PRE>
+
+Because module creates only one result map, the consequent map name is ommited. Every rule starts with $ and consist of consequent name and antecedents in braces { }. All maps and sets used in atecednats must be included in the maps file. At the begining of the calculation program checks if all names and sets are included in maps file. Names of the consequents must be same as sets names of the output map. The rules file use following symbology:
+<UL>
+<li>IS is symbolised by <B>=</B>
+<li>IS NOT is symbolised by <B>~</B>
+<li>AND is symbolised by <B>&</B>
+<li>OR is symbolised by <B>|</B>
+</UL>
+<P>
+To  specify the order of operators must use parentheses. Optional number at the end of the  rule symbolize weight of the rule (curently not in use).
+
+<h3>An example of fuzzy rules definiton file:</h3>
+<PRE>
+#This is example of fuzzy rules definition for flood probablity .
+$ small {distance = high & elev = high} 1;
+$ medium {distance = low | (elev = low & distance ~ low) };
+$ high {distance = low & elev = low};
+</PRE>
+
+<h2>ADVANCED OPTIONS</h2>
+In most cases default options shoud not be changed.
+<DT><b>family</b></DT>
+<DD>AND and OR operations in fuzzy logic are made with T-norms, T-conorms. T-norms, T-conorms are a generalization of the two-valued logical conjunction and  disjunction  used by boolean logic, for fuzzy logics. Because there is more than one possible generalisation of logial operations, r.fuzzy.system provides 6 most popular families for fuzzy operations:
+<ul>
+<li><b>Zadeh</b> with minimum (Godel) t-norm and maximum T-conorm;
+<li><b>product</b> with product T-norm and probabilistic sum as T-conorm;
+<li><b>drastic</b> with drastic T-norm and drastic T-conorm;
+<li><b>Lukasiewicz</b> with Lukasiewicz T-norm and bounded sum as a T-conorm;
+<li><b>Fodor</b> with nilpotent minimum as T-norm and nilpotent maximum as T-conorm;
+<li><b>Hamacher</b> (simplified) with Hamacher product as T-norm and Einstein sum as T-conorm;
+</ul>
+<P>
+<TABLE cellspacing=4>
+<TR><TH>Family</TH><TH> T-NORM (AND) </TH><TH>T CONORM (OR) </TH></TR>
+<TR><TD>ZADEH</TD><TD> MIN(x,y)</TD><TD>MAX(x,y)</TD></TR>
+<TR><TD>PRODUCT</TD><TD>	x*y	</TD><TD>x + y -x * y</TD></TR>
+<TR><TD>DRASTIC	</TD><TD>IF MAX(x, y) == 1 THEN MIN(x, y) ELSE 0	</TD><TD>IF (MIN(x, y) == 0) THEN MAX(x, y) ELSE 1</TD></TR>
+<TR><TD>LUKASIEWICZ</TD><TD>	MAX((x+y-1),0)</TD><TD>	MIN((x+y),1)</TD></TR>
+<TR><TD>FODOR	</TD><TD>IF (x+y)>1 THEN MIN(x,y) ELSE 0	</TD><TD>IF (x+y<1) THEN MAX(x,y) ELSE 1</TD></TR>
+<TR><TD>HAMACHER</TD><TD>	IF (x==y==0) THEN 0 ELSE (x*y)/((x+y)-x*y)</TD><TD>	(x+y)/(1+x*y)</TD></TR>
+</TABLE>
+<P>
+<DT><b>implication</b></DT>
+<DD>Imlication determines the transition between antecedents and consequents: 
+<UL>
+<li><B>minimum</B> means the lowest value of the antecedtents and output set definition. It ussually creates trapezoidal consequent set definition.
+<li><B>product</B> means the multiplication of the antecedtents and output set definition. It ussually creates triangular consequent set definition.
+</UL>
+
+<DT><b>defuzzification</b></DT>
+<DD>Defuzzification is the process of conversion of fuzzy set into one crisp value. Before deffuzification all consequents are agregated into one fuzzy set. The r.fuzzy.system provides 5 methods of deffuzyfication:
+<UL>
+<li><B>centeroid</B> center of mass of the fuzzy set (in practise weighted mean);
+<li><B>bisector</B> a value wchich divide fuzzy set on two parts of equal area;
+<li><B>min</B> min (right limit) of highest part of the set;
+<li><B>mean</B> mean (center) of highest part of the set;
+<li><B>max</B> max (left limit) of highest part of the set;
+</UL>
+
+
+<DT><b>universe resolution</b></DT>
+<DD>The universe is an interval between the lowest and highest values of fuzzy sets of output map. The resolution provides number of elements of partial fuzzy sets of every rules and final agregated fuzzy set before defuzzyfication. Because it has strong inpact on computation time and precision of deffuzification, values lower than 30 may change final result, but values above 200 radically slow down computation time.
+
+<h2>VISUAL OUTPUT</h2>
+<DT><b>coordinates</b></DT>
+<DD>Coordinates of points to which output universe, all consequents sets and agregate set. It is useful for visual presentation or detail analysis of fuzzy rules behaviour. In that cases calculations are peroforemd n=only for selected point.
+
+<h2>OUTPUTS</h2>
+<DT><b>output</b></DT>
+<DD>Map containing deffuzified values. Map is always of type FCELLS and contains values defined in output universe. The output name must be the same as one of maps in maps definition file.</DD>
+<P>
+<DT><b>multipe output flag</b></DT>
+<DD>This flag is used to create fuzzified maps for every rule. The name of the map consist of otput map name, '_' and rule name (for example: output=probs and rule name high, the map name: probs_high). Values of maps ranges from 0  to 1. If map with such name exist will be overwritten without warning.
+
+
+
+<h2>DESCRIPTION</h2>
+<P>
+<H4>Definition of fuzzy set</H4>
+
+
+
+<h2>NOTES</H2>
+<H4>Calculation of boundary shape</H4>
+Depending on type of the boundary different equation are used to determine its shape:
+<P>
+
+<B>Linear:</B> the membership is calculated according following equation:<br>
+
+<pre><code>
+value  <=  A -> x = 0
+A< value > B -> x = (value-A)/(B-A)
+B <= value >= C -> x = 1
+C< value > D -> x = (D-value)/(D-C)
+value  >=  D -> x = 0
+</code></pre>
+<B>S-shaped, G-shaped and J shaped:</B>  use following equation to sommoth boundary:
+<pre><code>
+sin(x * Pi/2)^2 (for S-shaped)
+tan(x * Pi/4)^2 (for J-shaped)
+tan(x * Pi/4)^0.5 (for G-shaped)
+
+where:
+x current fuzzy value
+A,B,C,D inflection point,
+</code></pre>
+
+
+<h2>EXAMPLE</H2>
+<P>
+Fuzzy sets are sets whose elements have degrees of membership. Zadeh (1965) introduced Fuzzy sets as an extension of the classical notion of set. Classical  membership of elements in a set are binary terms: an element either belongs or does not belong to the set. Fuzzy set theory use the gradual membership of elements in a set. A membership function use values in the real unit interval [0, 1]. Classical sets, are special cases of the membership functions of fuzzy sets and only take values 0 or 1. Classical sets are in fuzzy set theory usually called crisp sets. The fuzzy set theory can be used in a wide range of domains in which information is  imprecise, such as most of the GIS operations.
+<P>
+Suppose we want to determine the flood risk on some area (Spearfish dataset) using two maps: distance to streams and elevation above streams. The common sense rules are;
+<PRE>
+IF elevation IS low AND distance IS near THEN risk IS veryprobable
+IF elevation IS low OR distance IS near THEN risk IS probable
+IF elevation IS high AND distance IS far THEN risk IS unprobable
+</PRE>
+In clasical boolean sense, we would taken some limits of ideas "near" "far" etc, but what about walues near the limit? The fuzzy set uses partial memberships which abolish these restrictions. In that sense to set "near" belongs all areas with distance no more than 100 m with full membership and from 100 to 200 m with partial membership grater than 0. Over 200 m we can assume that is not near.
+This allow to formulate fuzzy rules for distance map:
+<PRE>
+near: BELOW 100 = 1; FROM 100 TO 200 = {1 TO 0}; ABOVE 200 = 0;
+</PRE>
+
+To recive final map we need to calculate partial fuzzy set for all rules and next agregate it into one fuzzy set. These fuzzy sets are created on value sequence called universe. Every set has the number of elements equal to universe resolution. It cannot be stored as map so it require defuzzification.
+<P>
+First we need two maps: we can create with r.stream package:
+
+<PRE>
+r.stream.extract elevation=elevation.10m at PERMANENT threshold=2000 stream_rast=streams direction=dirs 
+r.stream.order stream=streams dir=dirs horton=horton
+r.mapcalc "horton3=if(horton>2,horton,null()"
+r.stream.distance stream=streams dir=dirs dem=elevation.10m method=downstream distance=distance elevation=elevation 
+</PRE>
+
+Next, to perform analysis we need two files: one with definition of map used in analysis and definition of fuzzy sets for every map, and second with fuzzy rules. For this example:
+
+<P>MAPS
+<PRE>
+#flood.map
+	%elevation
+$ low {right; 2,6; sshaped; 0; 1}
+$ high {left; 2,6; sshaped; 0; 1}
+	%distance
+$ near {right; 40,80; sshaped; 0; 1}
+$ far {left; 40,80; sshaped; 0; 1}
+#output map
+	%flood
+$ unprob {both; 0,20,20,40; linear; 0;1}
+$ prob {both; 20,40,40,60; linear; 0;1}
+$ veryprob {both; 40,60,60,80; linear; 0;1}
+
+</PRE>
+<P>RULES:
+<PRE>
+#flood.rul
+$ unprob {elevation = high & distance = far};
+$ prob {distance = near | elevation = low};
+$ veryprob {distance = near & elevation = low};
+</PRE>
+
+finally we need run r.fuzzy.system:
+<PRE>
+r.fuzzy.system vars=flood.map rules=flod.rul output=flood 
+</PRE>
+
+Resulting map should look like this:
+<img src=f_result.png border=1><br>
+
+<h2>SEE ALSO</h2>
+
+<em>
+<a href="r.fuzzy.logic.html">r.fuzzy.logic</a>,
+<a href="r.fuzzy.set.html">r.fuzzy.set</a>,
+<a href="r.mapcalc.html">r.mapcalc</a>,
+</em>
+
+
+
+<h2>REFERENCES</h2>
+
+Zadeh, L.A. (1965). "Fuzzy sets". Information and Control 8 (3): 338–353. doi:10.1016/S0019-9958(65)90241-X. ISSN 0019-9958.<P>
+
+Novák, Vilém (1989). Fuzzy Sets and Their Applications. Bristol: Adam Hilger. ISBN 0-85274-583-4.<P>
+
+Klir, George J.; Yuan, Bo (1995). Fuzzy sets and fuzzy logic: theory and applications. Upper Saddle River, NJ: Prentice Hall PTR. ISBN 0-13-101171-5.<P>
+
+Klir, George J.; St Clair, Ute H.; Yuan, Bo (1997). Fuzzy set theory: foundations and applications. Englewood Cliffs, NJ: Prentice Hall. ISBN 0133410587.<P>
+
+Meyer D, Hornik K (2009a). \Generalized and Customizable Sets in R." Journal of Statistical Software, 31(2), 1{27. URL http://www.jstatsoft.org/v31/i02/.<P>
+
+Meyer D, Hornik K (2009b). sets: Sets, Generalized Sets, and Customizable Sets. R~package version~1.0, URL http://CRAN.R-project.org/package=sets.<P>
+
+<h2>AUTHOR</h2>
+Jarek  Jasiewicz
+
+
+
+<h2>SEE ALSO</h2>
+<em>
+<a href="r.fuzzy.html">r.fuzzy</a>,
+<a href="r.mapcalc.html">r.mapcalc</a>,
+</em>
+<HR>
+<P><a href="index.html">Main index</a> - <a href="raster.html">raster index</a> - <a href="full_index.html">Full index</a></P>
+<P>&copy; 2003-2009 <a href="http://grass.osgeo.org">GRASS Development Team</a></p>
+</body>
+</html>

Added: grass-addons/raster/r.fuzzy.system/rule_parser.c
===================================================================
--- grass-addons/raster/r.fuzzy.system/rule_parser.c	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/rule_parser.c	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,277 @@
+#include "local_proto.h"
+
+int parse_rule_file(STRING file) {
+		FILE* fd;
+	char buf[800];
+	char tmp[30];
+	STRING mapset;
+	char map[30];
+	fpos_t init;
+	int rule_num=0;
+	int n=0, i;
+			
+	fd = fopen(file, "r");
+			if (!fd)
+	G_fatal_error(_("Cannot open rules file '%s'"), file);
+
+	fgetpos (fd, &init);
+	
+		while (fgets(buf, sizeof buf, fd)) {
+		G_strip(buf);
+				if (*buf != '$')
+		continue;
+		nrules++;
+		}
+		
+	s_rules =(RULES *) G_malloc((nrules)* sizeof(RULES));
+	rules =  (char** )G_malloc ((nrules)* sizeof(char*));
+		for (i=0;i<nrules;++i)
+	rules[i]=(char* )G_malloc (21* sizeof(char*));
+	
+	fsetpos (fd, &init); /* reset position */
+	
+	for (n=nmaps;n>0;--n)	
+			if (!strcmp(s_maps[n-1].name,output))
+		break; /*max index of output map */
+		
+		if(n==0)
+	G_fatal_error (_("No defininition for output map: <%s> in map file"), output);
+	
+	while (fgets(buf, sizeof buf, fd)) {
+		G_strip(buf);
+			if (*buf != '$')
+		continue;
+
+		parse_rules(rule_num++,n,buf);
+
+	 /* next rule */
+	}	
+	
+
+	fclose(fd);
+	return 0;
+
+} /* END parse_rule_file */
+
+
+	
+int parse_rules(int rule_num, int n, char buf[]) {
+
+	int i,j,l,o;
+	int done=1;
+	int stack_top;
+	char tmp[30];
+	char opr[] = {'=','&','|',';','~','(',')','{','}'};
+	
+		i=j=stack_top=0; /* variables of the while loop */
+		char_strip(buf,'$');
+		
+
+{ /* check the name of fuzzy value (must be defined in rules) */
+	int s,p;
+	
+	sscanf(buf, "%[^{] %[^\n]",tmp,buf);
+	G_strip(buf);
+	G_strip(tmp);
+	
+			done=1;
+			for (s=0;s<=s_maps[n-1].nsets;++s) {/* output map */
+			
+				if(!strcmp(s_maps[n-1].sets[s].setname,tmp)) {
+
+								for (p=0;p<=rule_num;++p) /* check if values are unique */
+							if(!strcmp(tmp,rules[p]))
+						G_fatal_error(_("Variable value <%s> exist, Variable values must be unique"),tmp);
+										
+						strcpy(rules[rule_num],tmp);
+						done=0;	
+						break;
+				}
+			}
+		if(done)
+	G_fatal_error(_("Output map do not have variable value <%s>"),tmp);
+	strcpy(s_rules[rule_num].outname,tmp);
+	s_rules[rule_num].output_set_index=s;
+
+} /* check the name of fuzzy value */
+
+/* ******************************************************************* */
+		
+{	/* parse rule expression and create parse stack */
+	
+	
+	do {
+		for(o=0;o<(sizeof opr);++o) {
+			if(buf[i]==opr[o]) {
+				char_copy(buf,tmp,j,i);
+				if (i>0) {
+					char_strip(tmp,buf[j]);
+					s_rules[rule_num].parse_stack[stack_top][0]=buf[j];
+					s_rules[rule_num].parse_stack[stack_top++][1]='\0';
+					G_strip(tmp);
+				}	
+					if(strlen(tmp)) /* is not blank */
+				strcpy(s_rules[rule_num].parse_stack[stack_top++],tmp);	
+		
+				j=i;
+				break;
+			}
+		}	
+			if(i>799)	
+		G_fatal_error(_("rule string is too long or lack of closing element"));
+		
+	}	while (buf[i++]!='}');  		/* rule is rot */
+		
+	strcpy(s_rules[rule_num].parse_stack[stack_top++],"}"); /* add closing element only if OK*/
+
+
+} /* end parse rule expression and create parse stack */
+
+/* ******************************************************************* */
+
+
+{	/* adding weight */
+
+char local[900];
+char weight[10];
+
+sscanf(buf, "%[^}] %[^;]",local,weight);
+char_strip(weight,'}');
+G_strip(weight);
+	if(strlen(weight)==0)
+strcpy(weight,"1");
+s_rules[rule_num].weight=atof(weight);
+	if(s_rules[rule_num].weight<=0.)
+G_fatal_error(_("Weight must be grater than 0 or non-number character"));
+
+} 
+
+{ /* check if rule syntax is proper and map names and vars values exist*/
+int k;
+int work_stack_pos=0;
+int lbrc=0, rbrc=0; /* left and right brackets */
+
+		done=1;
+		for (i=0;i<stack_top;++i) { /* most external loop */
+//if(i>0)
+//G_message("PARSE STACK %d %d",s_rules[rule_num].work_stack[i-1],i-1)	;
+			if(*s_rules[rule_num].parse_stack[i]=='{') {
+				
+				s_rules[rule_num].work_stack[work_stack_pos]= t_START;	
+				
+					if (i>0)
+				G_fatal_error(_("line %d Syntax error near <%s %s>"),
+					rule_num+1, s_rules[rule_num].parse_stack[i-1],	s_rules[rule_num].parse_stack[i]);
+
+				work_stack_pos++;
+				continue;
+			} /* END { */
+			
+			if(*s_rules[rule_num].parse_stack[i]=='=' || 
+					*s_rules[rule_num].parse_stack[i]=='~')  { /* =, ~ */
+					
+				for (j=0;j<nmaps;++j) {
+					if(!strcmp(s_rules[rule_num].parse_stack[i-1],s_maps[j].name)) {
+						for(k=0;k<s_maps[j].nsets;++k) {
+							if(!strcmp(s_rules[rule_num].parse_stack[i+1],s_maps[j].sets[k].setname)) {
+
+								s_rules[rule_num].work_stack[work_stack_pos]= t_VAL;
+								s_rules[rule_num].value_stack[work_stack_pos].value=&s_maps[j].cell;
+								s_rules[rule_num].value_stack[work_stack_pos].set  =&s_maps[j].sets[k];
+								s_rules[rule_num].value_stack[work_stack_pos].oper =*s_rules[rule_num].parse_stack[i];
+								done=0;
+								break;
+							}	
+						}
+					}
+				}	/* END for j */
+	
+					if(done)
+				G_fatal_error(_("There is no map <%s> or variable <%s>"),s_rules[rule_num].parse_stack[i-1],
+					s_rules[rule_num].parse_stack[i+1]);
+					 /* end for j */
+					
+					if (s_rules[rule_num].work_stack[work_stack_pos-1] != t_AND && 
+						s_rules[rule_num].work_stack[work_stack_pos-1] != t_OR &&
+						s_rules[rule_num].work_stack[work_stack_pos-1] != t_START &&								
+						s_rules[rule_num].work_stack[work_stack_pos-1] != t_LBRC )
+				G_fatal_error(_("line %d Syntax error near <%s %s>"),
+					rule_num+1, s_rules[rule_num].parse_stack[i-1],	s_rules[rule_num].parse_stack[i]);
+			
+				work_stack_pos++;
+				continue;
+			} /* END =, ~ */
+			
+				if(*s_rules[rule_num].parse_stack[i]=='&' || 
+					*s_rules[rule_num].parse_stack[i]=='|') { /* &, | */
+
+				s_rules[rule_num].work_stack[work_stack_pos]=
+					(*s_rules[rule_num].parse_stack[i]=='|') ? t_OR : t_AND;
+
+					if (s_rules[rule_num].work_stack[work_stack_pos-1] != t_VAL && 
+							s_rules[rule_num].work_stack[work_stack_pos-1] != t_RBRC) 
+				G_fatal_error(_("line %d Syntax error near <%s %s>"),
+					rule_num+1, s_rules[rule_num].parse_stack[i-1],	s_rules[rule_num].parse_stack[i]);
+				
+				work_stack_pos++;
+				continue;
+			} /* END &, | */
+			
+			if(*s_rules[rule_num].parse_stack[i]=='(') {
+				
+				s_rules[rule_num].work_stack[work_stack_pos]= t_LBRC;
+				lbrc++;
+				
+					if (s_rules[rule_num].work_stack[work_stack_pos-1] != t_AND && 
+							s_rules[rule_num].work_stack[work_stack_pos-1] != t_OR &&
+							s_rules[rule_num].work_stack[work_stack_pos-1] != t_START &&								
+							s_rules[rule_num].work_stack[work_stack_pos-1] != t_LBRC )
+				G_fatal_error(_("line %d Syntax error near <%s %s>"),
+					rule_num+1, s_rules[rule_num].parse_stack[i-1],	s_rules[rule_num].parse_stack[i]);
+				
+				work_stack_pos++;
+				continue;
+			} /* END ( */
+
+			if(*s_rules[rule_num].parse_stack[i]==')') {
+
+					s_rules[rule_num].work_stack[work_stack_pos]= t_RBRC;
+					rbrc++;
+							
+					if (s_rules[rule_num].work_stack[work_stack_pos-1] != t_VAL &&
+							s_rules[rule_num].work_stack[work_stack_pos-1] != t_RBRC)
+				G_fatal_error(_("line %d Syntax error near <%s %s>"),
+					rule_num+1, s_rules[rule_num].parse_stack[i-1],	s_rules[rule_num].parse_stack[i]);
+				
+				work_stack_pos++;
+				continue;				
+			} /* END ) */
+		
+			if(*s_rules[rule_num].parse_stack[i]=='}') {
+
+					s_rules[rule_num].work_stack[work_stack_pos]= t_STOP;	
+							
+						if (s_rules[rule_num].work_stack[work_stack_pos-1] != t_VAL &&
+								s_rules[rule_num].work_stack[work_stack_pos-1] != t_RBRC)
+				G_fatal_error(_("line %d Syntax error near <%s %s>"),
+					rule_num+1, s_rules[rule_num].parse_stack[i-1],	s_rules[rule_num].parse_stack[i]);
+				
+				work_stack_pos++;
+				continue;					
+			} /* END } */
+
+		} /* most external loop */
+
+	if (lbrc!=rbrc)
+G_fatal_error(_("line %d Left and right of brackets do not match"),rule_num+1);
+		
+} /* END check if rule syntax is proper and map names and vars values exist*/
+
+return 0;
+} /* END parse_rules */
+
+
+
+
+
+

Added: grass-addons/raster/r.fuzzy.system/system.c
===================================================================
--- grass-addons/raster/r.fuzzy.system/system.c	                        (rev 0)
+++ grass-addons/raster/r.fuzzy.system/system.c	2010-03-29 11:52:44 UTC (rev 41610)
@@ -0,0 +1,186 @@
+#include "local_proto.h"
+
+float implicate (void) {
+	
+int i, j;
+float* agregate=NULL;
+int set_index;
+float consequent;
+float max_antecedent=0;
+
+agregate =(float*) G_calloc(resolution, sizeof(float));
+antecedents=(float*) G_malloc(nrules * sizeof(float));
+
+	if(coor_proc)
+visual_output= (float**) G_malloc (resolution * sizeof(float*));
+
+	for (j=0;j<nrules;++j) {
+		antecedents[j]=parse_expression(j);
+		max_antecedent=(max_antecedent > antecedents[j]) ? max_antecedent : antecedents[j];
+	}
+	
+				if(max_antecedent==0.)
+		return -9999; /* for all rules value is 0 */
+	
+			if(coor_proc)
+	for (i=0;i<resolution;++i) {
+		visual_output[i]= (float*) G_calloc (nrules+2, sizeof(float));
+		visual_output[i][0]=universe[i];
+	}
+	
+	for (j=0;j<nrules;++j) {
+		
+			if(defuzzyfication > d_BISECTOR && antecedents[j]< max_antecedent) 
+		continue;
+
+		for (i=0;i<resolution;++i) {
+
+			consequent=fuzzy(universe[i],
+				&s_maps[output_index].sets[set_index]);
+			set_index=s_rules[j].output_set_index;
+			consequent=(!implication) ? MIN(antecedents[j],consequent) : 
+				antecedents[j]*consequent;
+			agregate[i]=MAX(agregate[i],consequent);
+
+				if(coor_proc)
+			visual_output[i][j+1]=consequent;	
+		}
+	}	
+					if(coor_proc)
+				for (i=0;i<resolution;++i)
+		visual_output[i][j+1]=agregate[i];
+		
+		return defuzzify(agregate,defuzzyfication,max_antecedent);
+}
+
+float parse_expression(int n) {
+	
+/*  tokens and actions must heve the same order */
+actions parse_tab[t_size][t_size] ={
+/* stk -----------INPUT------------------*/	
+/*        {    &    |    ~    =    (    )    }     */
+/*        --   --   --   --   --   --   --   --
+/* { */ { E,   S,   S,   E,   E,   S,   E,   A  },
+/* & */	{ E,   R,   R,   E,   E,   S,   R,   R  },
+/* | */	{ E,   R,   R,   E,   E,   S,   R,   R  },
+/* ~ */	{ E,   E,   E,   E,   E,   E,   E,   E  },
+/* = */	{ E,   E,   E,   E,   E,   E,   E,   E  }, 
+/* ( */	{ E,   S,   S,   E,   E,   S,   S,   E  },
+/* ) */	{ E,   R,   R,   E,   E,   E,   R,   R  },
+/* } */	{ E,   E,   E,   E,   E,   E,   E,   E  }
+};
+
+tokens operator_stack[STACKMAX];
+float values_stack[STACKMAX];
+	
+int i=0, k=0;
+int opr_top=0;
+int val_top=0;
+int set_index;
+float f_value;
+
+
+		do { 
+
+			if(s_rules[n].work_stack[i]==t_START) {/* first token */
+						if (i>0)
+					G_fatal_error("operator stack error, contact author");
+				operator_stack[opr_top]=t_START;
+				continue;
+			}
+			
+			if(s_rules[n].work_stack[i]==t_VAL) {
+				f_value=fuzzy(*s_rules[n].value_stack[i].value, s_rules[n].value_stack[i].set);
+				values_stack[++val_top]=(s_rules[n].value_stack[i].oper=='~') ? 
+					f_not(f_value,family) : f_value; 
+				continue;
+			}
+
+			if (s_rules[n].work_stack[i]<t_size) {
+						
+				switch (parse_tab[operator_stack[opr_top]][s_rules[n].work_stack[i]]) {
+					
+						case E: /* error */
+					G_fatal_error ("Stack error, contact author");
+					break;
+						
+						case S: /* shift */
+					operator_stack[++opr_top]=s_rules[n].work_stack[i];
+					break;
+				
+						case R: /* reduce */
+						
+							switch (operator_stack[opr_top]) {
+							
+								case t_AND :
+							values_stack[val_top-1]=f_and(values_stack[val_top],values_stack[val_top-1],family);
+							val_top--;
+							break;
+		
+								case t_OR :
+							values_stack[val_top-1]=f_or(values_stack[val_top],values_stack[val_top-1],family);
+							val_top--;
+							break;
+							
+							case t_RBRC :
+						opr_top--;
+						break;	
+							}
+					
+					opr_top--;
+					i--;
+					break;
+					
+						case A: /* accept */
+							if(!val_top)
+					G_fatal_error("Last Stack error, contact autor");
+					return values_stack[val_top];
+				
+				}
+			}
+		} while(s_rules[n].work_stack[i++]!=t_STOP);
+}
+
+
+
+
+float defuzzify(float *agregate,int defuzzification, float max_antecedent) {
+	int i;
+	float d_value=0;
+	float sum_agregate=0;
+	float tmp;
+
+	for (i=0;i<resolution;sum_agregate += agregate[i++]);
+			
+	switch (defuzzification) {
+		
+		case d_CENTEROID :
+				for (i=0;i<resolution;++i) 
+			d_value += (universe[i] * agregate[i]);
+			return d_value/sum_agregate;
+		
+		case d_BISECTOR :
+			for (i=0, tmp=0;(tmp+= agregate[i])<sum_agregate/2;++i);
+			return universe[i];
+			
+		case d_MINOFHIGHEST :
+			for (i=0; agregate[i++]<max_antecedent;);	
+			return universe[i];
+						
+		case d_MAXOFHIGHEST :
+			for (i=resolution; agregate[i--]<max_antecedent;);	
+			return universe[i];
+					
+		case d_MEANOFHIGHEST :
+			sum_agregate=0;
+			for (i=0;i<resolution;++i) {
+					if(agregate[i]<max_antecedent)
+				continue;
+				d_value += (universe[i] * agregate[i]);
+				sum_agregate += agregate[i];
+			}	
+			return d_value/sum_agregate;
+	}
+
+	return -9999;
+}



More information about the grass-commit mailing list