950b956b0b955ebdad3cbbfbb37d4529c722a51a
[nit.git] / src / metrics / metrics_base.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Helpers for various statistics tools.
18 module metrics_base
19
20 import modelbuilder
21
22 redef class ToolContext
23
24 # --rta
25 var opt_rta = new OptionBool("Compute RTA metrics", "--rta")
26 # --generate_hyperdoc
27 var opt_generate_hyperdoc = new OptionBool("Generate Hyperdoc", "--generate_hyperdoc")
28
29 var opt_dir = new OptionString("Directory where some statistics files are generated", "-d", "--dir")
30 var output_dir: String = "."
31
32 redef init
33 do
34 super
35 self.option_context.add_option(opt_rta)
36 self.option_context.add_option(opt_generate_hyperdoc)
37 self.option_context.add_option(opt_dir)
38 end
39
40 redef fun process_options
41 do
42 super
43 var val = self.opt_dir.value
44 if val != null then
45 val = val.simplify_path
46 val.mkdir
47 self.output_dir = val
48 end
49 end
50 end
51
52 # A counter counts occurence of things
53 # Use this instead of a HashMap[E, Int]
54 class Counter[E: Object]
55 # Total number of counted occurences
56 var total: Int = 0
57
58 private var map = new HashMap[E, Int]
59
60 # The number of counted occurences of `e'
61 fun [](e: E): Int
62 do
63 var map = self.map
64 if map.has_key(e) then return map[e]
65 return 0
66 end
67
68 # Count one more occurence of `e'
69 fun inc(e: E)
70 do
71 self.map[e] = self[e] + 1
72 total += 1
73 end
74
75 # Return an array of elements sorted by occurences
76 fun sort: Array[E]
77 do
78 var res = map.keys.to_a
79 var sorter = new CounterSorter[E](self)
80 sorter.sort(res)
81 #res.sort !cmp a, b = map[a] <=> map[b]
82 return res
83 end
84 end
85
86 private class CounterSorter[E: Object]
87 super AbstractSorter[E]
88 var counter: Counter[E]
89 redef fun compare(a,b) do return self.counter.map[a] <=> self.counter.map[b]
90 end
91
92 # Helper function to display n/d and handle division by 0
93 fun div(n: Int, d: Int): String
94 do
95 if d == 0 then return "na"
96 return ((100*n/d).to_f/100.0).to_precision(2)
97 end