csv: Clean `CsvDocument` a little bit.
[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 end
215
216 # A Metric that collects integer data
217 #
218 # Used to count things
219 class IntMetric
220 super Metric
221
222 redef type VAL: Int
223 redef type RES: Counter[ELM]
224
225 protected var values_cache = new Counter[ELM]
226 redef fun values do return values_cache
227
228 redef fun clear do values_cache.clear
229
230 fun sum: Int do return values_cache.sum
231
232 redef fun max do
233 assert not values_cache.is_empty
234 return values_cache.max.as(not null)
235 end
236
237 redef fun min do
238 assert not values_cache.is_empty
239 return values_cache.min.as(not null)
240 end
241
242 # Values average
243 redef fun avg: Float do return values_cache.avg
244
245 redef fun std_dev: Float do return values_cache.std_dev
246
247 redef fun above_threshold do
248 var above = new HashSet[ELM]
249 var threshold = threshold
250 for element, value in values do
251 if value.to_f > threshold then above.add(element)
252 end
253 return above
254 end
255
256 redef fun to_console(indent, colors) do
257 super
258 if colors then
259 print "{"\t" * indent} sum: {sum}".light_gray
260 else
261 print "{"\t" * indent} sum: {sum}"
262 end
263 end
264 end
265
266 # A Metric that collects float datas
267 #
268 # Used sor summarization
269 class FloatMetric
270 super Metric
271
272 redef type VAL: Float
273
274 protected var values_cache = new HashMap[ELM, VAL]
275 redef fun values do return values_cache
276
277 redef fun clear do values_cache.clear
278
279 fun sum: Float do
280 var sum = 0.0
281 for v in values.values do sum += v
282 return sum
283 end
284
285 redef fun max do
286 assert not values.is_empty
287 var max: nullable Float = null
288 var elem: nullable ELM = null
289 for e, v in values do
290 if max == null or v > max then
291 max = v
292 elem = e
293 end
294 end
295 return elem.as(not null)
296 end
297
298 redef fun min do
299 assert not values.is_empty
300 var min: nullable Float = null
301 var elem: nullable ELM = null
302 for e, v in values do
303 if min == null or v < min then
304 min = v
305 elem = e
306 end
307 end
308 return elem.as(not null)
309 end
310
311 redef fun avg do
312 if values.is_empty then return 0.0
313 return sum / values.length.to_f
314 end
315
316 redef fun std_dev: Float do
317 var sum = 0.0
318 for value in values.values do
319 sum += (value - avg).pow(2.to_f)
320 end
321 return (sum / values.length.to_f).sqrt
322 end
323
324 redef fun above_threshold do
325 var above = new HashSet[ELM]
326 var threshold = threshold
327 for element, value in values do
328 if value > threshold then above.add(element)
329 end
330 return above
331 end
332
333 redef fun to_console(indent, colors) do
334 super
335 if colors then
336 print "{"\t" * indent} sum: {sum}".light_gray
337 else
338 print "{"\t" * indent} sum: {sum}"
339 end
340 end
341
342 end
343
344 # A MetricSet is a metric holder
345 #
346 # It purpose is to be extended with a metric collect service
347 class MetricSet
348 type ELM: Object
349
350 # Metrics to compute
351 var metrics: Set[Metric] = new HashSet[Metric]
352
353 # Add a metric to the set
354 fun register(metrics: Metric...) do for metric in metrics do self.metrics.add(metric)
355
356 # Clear all results for all metrics
357 fun clear do for metric in metrics do metric.clear
358
359 # Collect all metrics for this set of class
360 fun collect(elements: Set[ELM]) do
361 for metric in metrics do metric.collect(elements)
362 end
363
364 # Pretty print the resuls in console
365 fun to_console(indent: Int, colors: Bool) do
366 for metric in metrics do metric.to_console(indent, colors)
367 end
368
369 # Export the metric set in CSV format
370 fun to_csv: CsvDocument do
371 var csv = new CsvDocument
372
373 # set csv headers
374 csv.header.add("entry")
375 for metric in metrics do csv.header.add(metric.name)
376
377 # collect all entries to merge metric results
378 var entries = new HashSet[ELM]
379 for metric in metrics do
380 for entry in metric.values.keys do entries.add(entry)
381 end
382
383 # collect results
384 for entry in entries do
385 var line = [entry.to_s]
386 for metric in metrics do
387 if metric.has_element(entry) then
388 line.add(metric[entry].to_s)
389 else
390 line.add("n/a")
391 end
392 end
393 csv.records.add(line)
394 end
395 return csv
396 end
397 end