1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License"); 
3    * you may not use this file except in compliance with the License. 
4    * You may obtain a copy of the License at
5    *
6    *     http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software 
9    * distributed under the License is distributed on an 
10   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
11   * either express or implied. See the License for the specific language 
12   * governing permissions and limitations under the License.
13   */
14  package fuzzy.mf;
15  
16  import org.apache.commons.math3.util.FastMath;
17  
18  /**
19   * Z-Shaped Membership Function. Equivalent to Matlab 
20   * <a href="http://www.mathworks.com/help/toolbox/fuzzy/zmf.html">zmf</a> 
21   * function.
22   *
23   * @since 0.1
24   */
25  public class ZShapedMembershipFunction implements MembershipFunction<Double> {
26  	
27  	private final double a;
28  	private final double b;
29  	
30  	public ZShapedMembershipFunction(double a, double b) {
31  		this.a = a;
32  		this.b = b;
33  	}
34  	
35  	public Double evaluate(Double x) {
36  		if(x <= a) {
37  			return 1.0;
38  		} else if(a <= x && x <= (a+b)/2) {
39  			return 1-(2 * FastMath.pow((x-a)/(b-a), 2));
40  		} else if((a+b)/2 <= x && x <= b) {
41  			return 2 * FastMath.pow((x-b)/(b-a), 2);
42  		} else if(x >= b) {
43  			return 0.0;
44  		}
45  		
46  		// TODO: find out what happens in Matlab when the value is out of range
47  		return 0.0;
48  	}
49  
50  	/* (non-Javadoc)
51  	 * @see java.lang.Object#equals(java.lang.Object)
52  	 */
53  	@Override
54  	public boolean equals(Object obj) {
55  		if(obj == null) {
56  			return false;
57  		}
58  		if(obj == this) {
59  			return true;
60  		}
61  		if(!(obj instanceof ZShapedMembershipFunction)) {
62  			return false;
63  		}
64  		final ZShapedMembershipFunction that = (ZShapedMembershipFunction)obj;
65  		return this.a == that.a && this.b == that.b;
66  	}
67  	
68  	/* (non-Javadoc)
69  	 * @see java.lang.Object#hashCode()
70  	 */
71  	@Override
72  	public int hashCode() {
73  		int hash = "ZShapedMembershipFunction".hashCode();
74  		hash <<= 2;
75  		hash ^= (int)this.a;
76  		hash <<= 2;
77  		hash ^= (int)this.b;
78  		return hash;
79  	}
80  	
81  	/* (non-Javadoc)
82  	 * @see java.lang.Object#toString()
83  	 */
84  	@Override
85  	public String toString() {
86  		return "Z-Shaped Membership Function ["+this.a+" "+this.b+"]";
87  	}
88  	
89  }