OSDN Git Service

329fabbc57086e0de0ddf178bc7f38413b46bc67
[stigmata/stigmata.git] / src / main / java / jp / sourceforge / stigmata / ComparisonPair.java
1 package jp.sourceforge.stigmata;
2
3 import java.util.ArrayList;
4 import java.util.Iterator;
5 import java.util.List;
6
7 /**
8  * This class represents comparison pair.
9  * 
10  * @author  Haruaki TAMADA
11  */
12 public class ComparisonPair implements Iterable<ComparisonPairElement>{
13     private BirthmarkSet target1;
14     private BirthmarkSet target2;
15     private BirthmarkContext context;
16
17     /**
18      * constructor.
19      */
20     public ComparisonPair(BirthmarkSet target1, BirthmarkSet target2, BirthmarkContext context){
21         this.target1 = target1;
22         this.target2 = target2;
23         this.context = context;
24
25         if(target1.getBirthmarksCount() != target2.getBirthmarksCount()){
26             throw new IllegalArgumentException("birthmark count is not matched");
27         }
28     }
29
30     /**
31      * return a target.
32      * @see  #getTarget2()
33      */
34     public BirthmarkSet getTarget1(){
35         return target1;
36     }
37
38     /**
39      * return other target
40      * @see  #getTarget1()
41      */
42     public BirthmarkSet getTarget2(){
43         return target2;
44     }
45
46     /**
47      * calculates similarity between target1 and target2.
48      */
49     public double calculateSimilarity(){
50         double similarity = 0d;
51         int count = 0;
52         for(ComparisonPairElement elem: this){
53             double sim = elem.getSimilarity();
54             if(!Double.isNaN(sim) && !Double.isInfinite(sim)){
55                 similarity += sim;
56                 count++;
57             }
58         }
59         return similarity / count;
60     }
61
62     /**
63      * Returns a number of birthmarks contained a target.
64      * Note that other target must have same birthmarks.
65      */
66     public int getBirthmarksCount(){
67         return target1.getBirthmarksCount();
68     }
69
70     /**
71      * returns an iterator for comparing each birthmarks.
72      */
73     @Override
74     public synchronized Iterator<ComparisonPairElement> iterator(){
75         List<ComparisonPairElement> list = new ArrayList<ComparisonPairElement>();
76         BirthmarkEnvironment env = context.getEnvironment();
77         for(Iterator<String> i = target1.birthmarkTypes(); i.hasNext(); ){
78             String type = i.next();
79
80             Birthmark b1 = target1.getBirthmark(type);
81             Birthmark b2 = target2.getBirthmark(type);
82             if(b1 != null && b2 != null){
83                 list.add(new ComparisonPairElement(
84                     b1, b2, env.getService(type).getComparator(), context
85                 ));
86             }
87         }
88         return list.iterator();
89     }
90 }