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