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   * PI Shaped Membership Function. Equivalent to Matlab 
20   * <a href="http://www.mathworks.com/help/toolbox/fuzzy/pimf.html">pimf</a> 
21   * function. 
22   *
23   * @since 0.1
24   */
25  public class PiShapedMembershipFunction implements MembershipFunction<Double> {
26  	
27  	private final double a;
28  	private final double b;
29  	private final double c;
30  	private final double d;
31  	
32  	public PiShapedMembershipFunction(double a, double b, double c, double d) {
33  		this.a = a;
34  		this.b = b;
35  		this.c = c;
36  		this.d = d;
37  	}
38  	
39  	public Double evaluate(Double x) {
40  		if(x <= a) {
41  			return 0.0;
42  		} else if (a <= x && x <= ((a+b)/2)) {
43  			return 2 * (FastMath.pow((x-a)/(b-a), 2));
44  		} else if(((a+b)/2) <= x && x <= b) {
45  			return 1 - (2 * FastMath.pow((x-b)/(b-a), 2));
46  		} else if(b <= x && x <= c) {
47  			return 1.0;
48  		} else if(c <= x && x <= (c+d)/2) {
49  			return 1 - (2 * (FastMath.pow((x-c)/(d-c), 2)));
50  		} else if((c+d)/2 <= x && x <= d) {
51  			return 2 * (FastMath.pow((x-d)/(d-c), 2));
52  		} else if(x >= d) {
53  			return 0.0;
54  		}
55  		return 0.0;
56  	}
57  	
58  	/* (non-Javadoc)
59  	 * @see java.lang.Object#equals(java.lang.Object)
60  	 */
61  	@Override
62  	public boolean equals(Object obj) {
63  		if(obj == null) {
64  			return false;
65  		}
66  		if(obj == this) {
67  			return true;
68  		}
69  		if(!(obj instanceof PiShapedMembershipFunction)) {
70  			return false;
71  		}
72  		final PiShapedMembershipFunction that = (PiShapedMembershipFunction)obj;
73  		return this.a == that.a && this.b == that.b && this.c == that.c && this.d == that.d;
74  	}
75  	
76  	/* (non-Javadoc)
77  	 * @see java.lang.Object#hashCode()
78  	 */
79  	@Override
80  	public int hashCode() {
81  		int hash = "PiShapedMembershipFunction".hashCode();
82  		hash <<= 2;
83  		hash ^= (int)this.a;
84  		hash <<= 2;
85  		hash ^= (int)this.b;
86  		hash <<= 2;
87  		hash ^= (int)this.c;
88  		hash <<= 2;
89  		hash ^= (int)this.d;
90  		return hash;
91  	}
92  	
93  	/* (non-Javadoc)
94  	 * @see java.lang.Object#toString()
95  	 */
96  	@Override
97  	public String toString() {
98  		return "PI Shaped Membership Function ["+a+" "+b+" "+c+" "+d+"]";
99  	}
100 	
101 }