metrics: allow Metric sorting
[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 # Copyright 2014 Alexandre Terrasa <alexandre@moz-code.org>
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 # Helpers for various statistics tools.
19 module metrics_base
20
21 import model_utils
22 import modelbuilder
23 import csv
24 import counter
25 import console
26
27 redef class ToolContext
28
29 # --all
30 var opt_all = new OptionBool("Compute all metrics", "--all")
31
32 # --mmodules
33 var opt_mmodules = new OptionBool("Compute metrics about mmodules", "--mmodules")
34 # --mclassses
35 var opt_mclasses = new OptionBool("Compute metrics about mclasses", "--mclasses")
36 # --mendel
37 var opt_mendel = new OptionBool("Compute mendel metrics", "--mendel")
38 # --inheritance
39 var opt_inheritance = new OptionBool("Compute metrics about inheritance usage", "--inheritance")
40 # --genericity
41 var opt_refinement = new OptionBool("Compute metrics about refinement usage", "--refinement")
42 # --self
43 var opt_self = new OptionBool("Compute metrics about the usage of explicit and implicit self", "--self")
44 # --ast
45 var opt_ast = new OptionBool("Compute metrics about the usage of nodes and identifiers in the AST", "--ast")
46 # --nullables
47 var opt_nullables = new OptionBool("Compute metrics on nullables send", "--nullables")
48 # --static-types
49 var opt_static_types = new OptionBool("Compute explicit static types metrics", "--static-types")
50 # --tables
51 var opt_tables = new OptionBool("Compute tables metrics", "--tables")
52 # --rta
53 var opt_rta = new OptionBool("Compute RTA metrics", "--rta")
54 # --generate-csv
55 var opt_csv = new OptionBool("Export metrics in CSV format", "--csv")
56 # --generate_hyperdoc
57 var opt_generate_hyperdoc = new OptionBool("Generate Hyperdoc", "--generate_hyperdoc")
58 # --poset
59 var opt_poset = new OptionBool("Complete metrics on posets", "--poset")
60
61 # --no-colors
62 var opt_nocolors = new OptionBool("Disable colors in console outputs", "--no-colors")
63
64
65 var opt_dir = new OptionString("Directory where some statistics files are generated", "-d", "--dir")
66 var output_dir: String = "."
67
68 redef init
69 do
70 super
71 self.option_context.add_option(opt_all)
72 self.option_context.add_option(opt_mmodules)
73 self.option_context.add_option(opt_mclasses)
74 self.option_context.add_option(opt_mendel)
75 self.option_context.add_option(opt_inheritance)
76 self.option_context.add_option(opt_refinement)
77 self.option_context.add_option(opt_self)
78 self.option_context.add_option(opt_ast)
79 self.option_context.add_option(opt_nullables)
80 self.option_context.add_option(opt_static_types)
81 self.option_context.add_option(opt_tables)
82 self.option_context.add_option(opt_rta)
83 self.option_context.add_option(opt_csv)
84 self.option_context.add_option(opt_generate_hyperdoc)
85 self.option_context.add_option(opt_poset)
86 self.option_context.add_option(opt_dir)
87 self.option_context.add_option(opt_nocolors)
88 end
89
90 redef fun process_options(args)
91 do
92 super
93 var val = self.opt_dir.value
94 if val != null then
95 val = val.simplify_path
96 val.mkdir
97 self.output_dir = val
98 end
99 end
100
101 # colorize heading 1 for console output
102 fun format_h1(str: String): String do
103 if opt_nocolors.value then return str
104 return str.yellow.bold
105 end
106
107 fun format_h2(str: String): String do
108 if opt_nocolors.value then return str
109 return str.bold
110 end
111
112 fun format_h3(str: String): String do
113 if opt_nocolors.value then return str
114 return str
115 end
116
117 fun format_h4(str: String): String do
118 if opt_nocolors.value then return str
119 return str.green
120 end
121
122 fun format_p(str: String): String do
123 if opt_nocolors.value then return str
124 return str.light_gray
125 end
126
127 end
128
129 redef class MClass
130 # is the class imported from standard lib?
131 fun is_standard: Bool do
132 return self.intro_mmodule.mgroup.mproject.name == "standard"
133 end
134 end
135
136 redef class MModule
137 # is the module imported from standard lib?
138 fun is_standard: Bool do
139 return self.mgroup.mproject.name == "standard"
140 end
141 end
142
143 # A Metric is used to collect data about things
144 #
145 # The concept is reified here for a better organization and documentation
146 interface Metric
147 type ELM: Object
148 type VAL: Object
149 type RES: Map[ELM, VAL]
150
151 fun name: String is abstract
152 fun desc: String is abstract
153
154 # Clear all results for this metric
155 fun clear is abstract
156
157 # Values for each element
158 fun values: RES is abstract
159
160 # Collect metric values on elements
161 fun collect(elements: Set[ELM]) is abstract
162
163 # The value calculated for the element
164 fun [](element: ELM): VAL do return values[element]
165
166 # Does the element have a value for this metric?
167 fun has_element(element: ELM): Bool do return values.has_key(element)
168
169 # The values average
170 fun avg: Float is abstract
171
172 # Pretty print the metric results in console
173 fun to_console(indent: Int, colors: Bool) do
174 if values.is_empty then
175 if colors then
176 print "{"\t" * indent}{name}: {desc} -- nothing".green
177 else
178 print "{"\t" * indent}{name}: {desc} -- nothing"
179 end
180 return
181 end
182
183 var max = self.max
184 var min = self.min
185 if colors then
186 print "{"\t" * indent}{name}: {desc}".green
187 print "{"\t" * indent} avg: {avg}".light_gray
188 print "{"\t" * indent} max: {max} ({self[max]})".light_gray
189 print "{"\t" * indent} min: {min} ({self[min]})".light_gray
190 print "{"\t" * indent} std: {std_dev}".light_gray
191 else
192 print "{"\t" * indent}{name}: {desc}"
193 print "{"\t" * indent} avg: {avg}"
194 print "{"\t" * indent} max: {max} ({self[max]})"
195 print "{"\t" * indent} min: {min} ({self[min]})"
196 print "{"\t" * indent} std: {std_dev}"
197 end
198 end
199
200 # The values standard derivation
201 fun std_dev: Float is abstract
202
203 # The element with the highest value
204 fun max: ELM is abstract
205
206 # The element with the lowest value
207 fun min: ELM is abstract
208
209 # The value threshold above what elements are considered as 'interesting'
210 fun threshold: Float do return avg + std_dev
211
212 # The set of element above the threshold
213 fun above_threshold: Set[ELM] is abstract
214
215 # Sort the metric keys by values
216 fun sort: Array[ELM] do
217 return values.keys_sorted_by_values(default_reverse_comparator)
218 end
219 end
220
221 # A Metric that collects integer data
222 #
223 # Used to count things
224 class IntMetric
225 super Metric
226
227 redef type VAL: Int
228 redef type RES: Counter[ELM]
229
230 protected var values_cache = new Counter[ELM]
231 redef fun values do return values_cache
232
233 redef fun clear do values_cache.clear
234
235 fun sum: Int do return values_cache.sum
236
237 redef fun max do
238 assert not values_cache.is_empty
239 return values_cache.max.as(not null)
240 end
241
242 redef fun min do
243 assert not values_cache.is_empty
244 return values_cache.min.as(not null)
245 end
246
247 # Values average
248 redef fun avg: Float do return values_cache.avg
249
250 redef fun std_dev: Float do return values_cache.std_dev
251
252 redef fun above_threshold do
253 var above = new HashSet[ELM]
254 var threshold = threshold
255 for element, value in values do
256 if value.to_f > threshold then above.add(element)
257 end
258 return above
259 end
260
261 redef fun to_console(indent, colors) do
262 super
263 if colors then
264 print "{"\t" * indent} sum: {sum}".light_gray
265 else
266 print "{"\t" * indent} sum: {sum}"
267 end
268 end
269 end
270
271 # A Metric that collects float datas
272 #
273 # Used sor summarization
274 class FloatMetric
275 super Metric
276
277 redef type VAL: Float
278
279 protected var values_cache = new HashMap[ELM, VAL]
280 redef fun values do return values_cache
281
282 redef fun clear do values_cache.clear
283
284 fun sum: Float do
285 var sum = 0.0
286 for v in values.values do sum += v
287 return sum
288 end
289
290 redef fun max do
291 assert not values.is_empty
292 var max: nullable Float = null
293 var elem: nullable ELM = null
294 for e, v in values do
295 if max == null or v > max then
296 max = v
297 elem = e
298 end
299 end
300 return elem.as(not null)
301 end
302
303 redef fun min do
304 assert not values.is_empty
305 var min: nullable Float = null
306 var elem: nullable ELM = null
307 for e, v in values do
308 if min == null or v < min then
309 min = v
310 elem = e
311 end
312 end
313 return elem.as(not null)
314 end
315
316 redef fun avg do
317 if values.is_empty then return 0.0
318 return sum / values.length.to_f
319 end
320
321 redef fun std_dev: Float do
322 var sum = 0.0
323 for value in values.values do
324 sum += (value - avg).pow(2.to_f)
325 end
326 return (sum / values.length.to_f).sqrt
327 end
328
329 redef fun above_threshold do
330 var above = new HashSet[ELM]
331 var threshold = threshold
332 for element, value in values do
333 if value > threshold then above.add(element)
334 end
335 return above
336 end
337
338 redef fun to_console(indent, colors) do
339 super
340 if colors then
341 print "{"\t" * indent} sum: {sum}".light_gray
342 else
343 print "{"\t" * indent} sum: {sum}"
344 end
345 end
346 end
347
348 # A MetricSet is a metric holder
349 #
350 # It purpose is to be extended with a metric collect service
351 class MetricSet
352 type ELM: Object
353
354 # Metrics to compute
355 var metrics: Set[Metric] = new HashSet[Metric]
356
357 # Add a metric to the set
358 fun register(metrics: Metric...) do for metric in metrics do self.metrics.add(metric)
359
360 # Clear all results for all metrics
361 fun clear do for metric in metrics do metric.clear
362
363 # Collect all metrics for this set of class
364 fun collect(elements: Set[ELM]) do
365 for metric in metrics do metric.collect(elements)
366 end
367
368 # Pretty print the resuls in console
369 fun to_console(indent: Int, colors: Bool) do
370 for metric in metrics do metric.to_console(indent, colors)
371 end
372
373 # Export the metric set in CSV format
374 fun to_csv: CsvDocument do
375 var csv = new CsvDocument
376
377 csv.format = new CsvFormat('"', ';', "\n")
378
379 # set csv headers
380 csv.header.add("entry")
381 for metric in metrics do csv.header.add(metric.name)
382
383 # collect all entries to merge metric results
384 var entries = new HashSet[ELM]
385 for metric in metrics do
386 for entry in metric.values.keys do entries.add(entry)
387 end
388
389 # collect results
390 for entry in entries do
391 var line = [entry.to_s]
392 for metric in metrics do
393 if metric.has_element(entry) then
394 line.add(metric[entry].to_s)
395 else
396 line.add("n/a")
397 end
398 end
399 csv.records.add(line)
400 end
401 return csv
402 end
403 end