Debian Codegraph @

pbcommand/models/report.py

raw symbols SCIP
1 """
2 Common PacBio Report model
3
4 Author: Johann Miller and Michael Kocher
5 """
6
7 import abc
8 import csv
9 import datetime
10 import json
11 import logging
12 import os
13 import re
14 import uuid as U # to allow use of uuid as local var
15 import warnings
16 from collections import defaultdict, OrderedDict
17 from pprint import pformat
18
19 import pbcommand
20
21
22 log = logging.getLogger(__name__)
23
24 __all__ = [
25 'PbReportError',
26 'Attribute',
27 'Report',
28 'Plot',
29 'PlotlyPlot',
30 'PlotGroup',
31 'Column',
32 'Table',
33 ]
34
35 # If/when the Report datamodel change, this needs to be changed using
36 # the semver model
37 PB_REPORT_SCHEMA_VERSION = "1.0.1"
38
39 _HAS_NUMPY = False
40
41 try:
42 import numpy as np
43 _HAS_NUMPY = True
44 except ImportError:
45 pass
46
47
48 def _get_decoder():
49 """
50 There's a bit of nonsense here to support the exiting pbreports python
51 package.
52
53 numpy is only used for Report that have Table columns that are numpy arrays.
54 This really should have strictly defined in the original API to only support
55 native python lists. Similarly with numpy scalars in Report Attributes.
56
57 :return: None | numpy decoder
58 """
59 if _HAS_NUMPY:
60 class NumpyJsonEncoder(json.JSONEncoder):
61
62 # This appears to be an issue with pylint that generates a
63 # false positive related to how python defines the base class
64 # https://github.com/PyCQA/pylint/issues/414
65 def default(self, obj): # pylint: disable=E0202
66 if isinstance(obj, np.core.numerictypes.floating):
67 return float(obj)
68 if isinstance(obj, np.core.numerictypes.integer):
69 return int(obj)
70 if isinstance(obj, np.ndarray) and obj.ndim == 1:
71 return [float(x) for x in obj]
72 # Let the base class default method raise the TypeError
73 return json.JSONEncoder.default(self, obj)
74 return NumpyJsonEncoder
75 else:
76 return None
77
78
79 def _to_json_with_decoder(d):
80 decoder_or_none = _get_decoder()
81 if decoder_or_none is None:
82 return json.dumps(d, sort_keys=True, indent=4, separators=(',', ': '))
83 else:
84 return json.dumps(d, cls=decoder_or_none, sort_keys=True,
85 indent=4, separators=(',', ': '))
86
87
88 class PbReportError(Exception):
89 pass
90
91
92 class BaseReportElement(metaclass=abc.ABCMeta):
93 def __init__(self, id_):
94 if not isinstance(id_, str):
95 raise PbReportError(
96 "Type error. id '{i}' cannot be {t}.".format(i=id_, t=type(id_)))
97
98 if not re.match('^[a-z0-9_]+$', id_):
99 msg = "id '{i}' for {x} must contain only lower-case alphanumeric or underscore characters".format(
100 x=self.__class__.__name__, i=id_)
101 log.error(msg)
102 raise PbReportError(msg)
103
104 self._id = id_
105 self._ids = set([])
106
107 def is_unique(self, id_):
108 """
109 Raise an error if a BaseReportElement with this id has already
110 been added.
111 :param id_: (int) id of child BaseReportElement
112 """
113 if id_ in self._ids:
114 msg = "an element with id '{i}' has already been added to {t}.".format(
115 i=id_, t=str(type(self)))
116 log.error(msg)
117 raise PbReportError(msg)
118 self._ids.add(id_)
119
120 @property
121 def id(self):
122 return self._id
123
124 @abc.abstractmethod
125 def _get_attrs_simple(self):
126 """
127 Return a list of attributes names where each
128 attribute returns a simple type like a string, int, or float.
129 The 'id' attribute should NOT be included.
130 Example [ 'title' ]
131 """
132 raise NotImplementedError
133
134 @abc.abstractmethod
135 def _get_attrs_complex_list(self):
136 """
137 Return a list of attributes names where each
138 attribute returns a list of BaseReportElement objects which
139 implement to_dict()
140 """
141 raise NotImplementedError
142
143 def to_dict(self, id_parts=None):
144 """
145 Return a dict-view of this object.
146 Recursively descend in to collections of BaseReportElement instances,
147 calling to_dict on each.
148
149 Additionally, prepends the id with a '.'-delimited string of
150 parent id's
151
152 :param id_parts: (list of string) Parent id's, as a function of depth within the object graph
153 """
154 if id_parts is None:
155 # start the part list
156 id_parts = [self.id]
157 else:
158 id_parts.append(self.id)
159
160 d = {a: getattr(self, a) for a in self._get_attrs_simple()}
161
162 d['id'] = '.'.join([str(v) for v in id_parts])
163 complex_attrs = self._get_attrs_complex_list()
164
165 for ca in complex_attrs:
166 d[ca] = []
167 for i in getattr(self, ca):
168 copy = []
169 copy.extend(id_parts)
170 d[ca].append(i.to_dict(copy))
171 # yank the last id so it doesn't prepend the next item of same type.
172 # slicing doesn't work on original list. need copy! bug 23799
173 id_parts = copy[:-1]
174
175 if len(id_parts) > 1:
176 # yank the last id part, so it doesn't prepend the next
177 # category of attributes
178 id_parts = id_parts[:-1]
179 return d
180
181
182 class Attribute(BaseReportElement):
183
184 """
185 An attribute always has an id and a value. A name is optional.
186 """
187
188 def __init__(self, id_, value, name=None):
189 """
190 :param id_: (str) Unique id for attribute (Not None, or Empty)
191 :param value: (str, float) Numeric values should be float values. Formatting is performed durning the report rendering
192 :param name: (str, None) optional display name. Can be changed in portal display rules
193 """
194 BaseReportElement.__init__(self, id_)
195 self._value = value
196 self._name = name
197
198 @property
199 def value(self):
200 return self._value
201
202 @property
203 def name(self):
204 return self._name
205
206 def _get_attrs_simple(self):
207 return ['value', 'name']
208
209 def _get_attrs_complex_list(self):
210 return []
211
212 def __eq__(self, other):
213 if isinstance(other, Attribute):
214 if self.name == other.name and self.value == other.value and self.id == other.id:
215 return True
216 return False
217
218 def __repr__(self):
219 n = "" if self.name is None else self.name[:10]
220 _d = dict(k=self.__class__.__name__,
221 i=self.id,
222 v=str(self.value)[:10],
223 n=n)
224 return "<{k} id:{i} value:{v} name:{n} >".format(**_d)
225
226
227 class PlotGroup(BaseReportElement):
228
229 """
230 A plotGroup is a container of plots.
231 """
232
233 def __init__(self, id_, title=None, legend=None, thumbnail=None, plots=()):
234 """
235 :param id_: (str) id of plotgroup. Not None or Empty
236 :param title: (str, None) Title of the plotGroup, displayed to user.
237 :param legend: (str, None) Path to legend image, if applicable
238 :param thumbnail: (str, None)Path to thumbnail image, if applicable
239 :param plots: (list of Plot instances)
240 """
241 BaseReportElement.__init__(self, id_)
242 self._title = title
243 self._legend = legend
244 self._thumbnail = thumbnail
245 self._plots = []
246 if plots:
247 for plot in plots:
248 self.add_plot(plot)
249
250 @property
251 def title(self):
252 return self._title
253
254 @property
255 def legend(self):
256 return self._legend
257
258 @property
259 def thumbnail(self):
260 return self._thumbnail
261
262 @property
263 def plots(self):
264 return self._plots
265
266 @property
267 def nplots(self):
268 return len(self.plots)
269
270 def __repr__(self):
271 _d = dict(k=self.__class__.__name__,
272 i=self.id,
273 t=self.title,
274 n=self.nplots)
275 return "<{k} id:{i} title:{t} nplots:{n} >".format(**_d)
276
277 def _get_attrs_simple(self):
278 return ['title', 'legend', 'thumbnail']
279
280 def _get_attrs_complex_list(self):
281 return ['plots']
282
283 def get_plot_by_id(self, id_):
284
285 for plot in self.plots:
286 if plot.id == id_:
287 return plot
288
289 return None
290
291 def add_plot(self, plot):
292 """
293 Add a plot to the plotGroup
294 """
295 if not isinstance(plot, Plot):
296 raise TypeError(
297 "Unable to add plot. Got type {x} expect Plot".format(x=type(plot)))
298 BaseReportElement.is_unique(self, plot.id)
299 self._plots.append(plot)
300
301 def to_dict(self, id_parts=None):
302 return BaseReportElement.to_dict(self, id_parts=id_parts)
303
304
305 def _validate_not_abs_path(path):
306 if os.path.isabs(path):
307 raise ValueError("paths must be relative. Got {i}".format(i=path))
308
309
310 class Plot(BaseReportElement):
311
312 """
313 A plot contains a path to image file.
314 """
315 PLOT_TYPE = "image"
316
317 def __init__(self, id_, image, caption=None, thumbnail=None, title=None):
318 """
319 :param id_: (str, not None, or empty) Unique id for plot.
320 :param image: (str) Required - not None - path to image
321 :param caption: (str, None) Plot caption displayed to user under plot.
322 :param thumbnail: (str, None) thumbnail path
323 :param title: str Display Name of the Plot
324
325 Paths must be given as relative
326 """
327 BaseReportElement.__init__(self, id_)
328
329 if image is None:
330 raise PbReportError('image cannot be None')
331 _validate_not_abs_path(image)
332
333 self._image = image
334 self._caption = caption
335 self.title = title
336 if thumbnail is not None:
337 _validate_not_abs_path(thumbnail)
338
339 self._thumbnail = thumbnail
340
341 def __repr__(self):
342 _d = dict(k=self.__class__.__name__,
343 i=self.id,
344 p=self.image)
345 return "<{k} {i} {p} >".format(**_d)
346
347 @property
348 def image(self):
349 return self._image
350
351 @property
352 def thumbnail(self):
353 return self._thumbnail
354
355 @property
356 def caption(self):
357 return self._caption
358
359 @property
360 def plotType(self):
361 return self.PLOT_TYPE
362
363 def _get_attrs_simple(self):
364 return ['image', 'caption', 'title', 'plotType', 'thumbnail']
365
366 def _get_attrs_complex_list(self):
367 return []
368
369
370 class PlotlyPlot(Plot):
371 PLOT_TYPE = "plotly"
372
373 def __init__(self, id_, image, caption=None, thumbnail=None, title=None,
374 plotly_version=None):
375 self._plotly_version = plotly_version
376 super().__init__(id_, image, caption, thumbnail, title)
377
378 @property
379 def plotlyVersion(self):
380 return self._plotly_version
381
382 def _get_attrs_simple(self):
383 return ['image', 'caption', 'title', 'plotType', 'plotlyVersion']
384
385
386 class Table(BaseReportElement):
387
388 """
389 A table consists of an id, title, and list of columns.
390 """
391
392 def __init__(self, id_, title=None, columns=()):
393 """
394 :param id_: (str), Unique id for table in report.
395 :param title: (str, None)
396 :param columns: (list of column instances)
397 """
398 BaseReportElement.__init__(self, id_)
399 self._title = title
400 self._columns = []
401 if columns:
402 for column in columns:
403 self.add_column(column)
404
405 def __repr__(self):
406 _d = dict(k=self.__class__.__name__,
407 i=self.id,
408 t=self.title,
409 n=self.ncolumns)
410 return "<{k} {i} title:{t} ncolumns:{n} >".format(**_d)
411
412 def __str__(self):
413 pad = 2
414 max_values = max(len(column.values) for column in self.columns)
415 # max length for each column value
416 max_lengths = {}
417 headers = []
418 for c in self.columns:
419 this_header = ""
420 if c.header is not None:
421 this_header = c.header
422 if c.values:
423 n = max(max(len(str(v)) for v in c.values), len(this_header))
424 else:
425 n = len(this_header)
426 max_lengths[c] = n
427 headers.append(this_header)
428
429 header = "".join([h.ljust(max_lengths[c] + pad)
430 for h in headers])
431
432 outs = list()
433 outs.append("")
434 outs.append("Table id:{i}".format(i=self.id))
435 outs.append("-" * len(header))
436 outs.append(header)
437 outs.append("-" * len(header))
438
439 for i in range(max_values):
440 out = []
441 for column in self.columns:
442 try:
443 l = max_lengths[column] + pad
444 out.append(str(column.values[i]).ljust(l))
445 except IndexError as e:
446 log.warn(e)
447 out.append("No Value ")
448
449 outs.append(" ".join(out))
450
451 return "\n".join(outs)
452
453 @property
454 def id(self):
455 return self._id
456
457 @property
458 def title(self):
459 return self._title
460
461 @property
462 def ncolumns(self):
463 return len(self.columns)
464
465 @property
466 def columns(self):
467 return self._columns
468
469 def _get_attrs_simple(self):
470 return ['title']
471
472 def _get_attrs_complex_list(self):
473 return ['columns']
474
475 def get_column_by_id(self, id_):
476
477 for col in self.columns:
478 if col.id == id_:
479 return col
480
481 return None
482
483 def add_column(self, column):
484 """
485 Add a column to the table
486
487 :param column: (Column instance)
488 """
489 if not isinstance(column, Column):
490 raise TypeError(
491 "Got type {x}. Expected Column type.".format(x=type(column)))
492
493 BaseReportElement.is_unique(self, column.id)
494 self._columns.append(column)
495
496 def append_data(self, column_index, item):
497 """
498 This should be deprecated in favor of `add_data_by_column_id`.
499
500 Append datum to a column by column index
501
502 :param column_index: (int) Index into internal column list
503 :param item: (float, str) data item.
504 """
505 if column_index < len(self._columns):
506 self._columns[column_index].values.append(item)
507 else:
508 raise IndexError(
509 "Unable to find index {i} in columns.".format(i=column_index))
510
511 def add_data_by_column_id(self, column_id, value):
512 """Add a value to column.
513
514 :param column_id: (str) Column id
515 :param value: (float, str, int)
516 """
517 if column_id in [c.id for c in self.columns]:
518 # _columns should really be a dict
519 # self._columns[column_id].values.append(value)
520 for column in self.columns:
521 if column_id == column.id:
522 column.values.append(value)
523 else:
524 raise KeyError("Unable to Column with id '{i}' to assign value {v}".format(
525 i=column_id, v=value))
526
527 @staticmethod
528 def merge(tables):
529 table_id = tables[0].id
530 table_title = tables[0].title
531 column_ids = sorted([col.id for col in tables[0].columns])
532
533 col_collisions = {col_id: [] for col_id in column_ids}
534 for table in tables:
535 assert table.id == table_id
536 assert table.title == table_title
537 assert sorted([col.id for col in table.columns]) == column_ids
538 for col in table.columns:
539 col_collisions[col.id].append(col)
540 columns = {}
541 for col_id, cols in col_collisions.items():
542 assert len(cols) == len(tables)
543 columns[col_id] = Column.merge(cols)
544 # order by table[0]'s column order:
545 columns = [columns[col.id] for col in tables[0].columns]
546 return Table(table_id, table_title, columns=columns)
547
548 def to_csv(self, file_name, delimiter=',', float_format=None):
549 if len(self.columns) == 0:
550 return ""
551 for column in self.columns:
552 if len(column.values) != len(self.columns[0].values):
553 raise ValueError("Column lengths differ ({i} versus {j}".format(
554 i=len(column.values),
555 j=len(self.columns[0].values)))
556
557 def _to_str(x):
558 if not float_format or not isinstance(x, float):
559 return str(x)
560 elif float_format.startswith("%"):
561 return float_format % x
562 elif float_format.startswith("{"):
563 return float_format.format(x)
564 with open(file_name, "w") as csv_out:
565 writer = csv.writer(
566 csv_out,
567 delimiter=delimiter,
568 lineterminator="\n")
569 writer.writerow([c.header for c in self.columns])
570 for i in range(len(self.columns[0].values)):
571 writer.writerow([_to_str(c.values[i]) for c in self.columns])
572
573 def to_columns_d(self):
574 """
575 Returns the columns as a list of dicts
576
577 """
578 items = []
579 if self.columns:
580 for i in range(self.columns[0].nvalues):
581 dx = {}
582 for c in self.columns:
583 dx[c.id] = c.values[i]
584 items.append(dx)
585
586 return items
587
588
589 class Column(BaseReportElement):
590
591 """
592 A column consists of an id, header, and list of values.
593 """
594
595 def __init__(self, id_, header=None, values=()):
596 """
597 :param id_: (str)
598 :param header: (str, None) Header of Column.
599 """
600 BaseReportElement.__init__(self, id_)
601 self._id = id_
602 self._header = header
603 self._values = list(values)
604
605 def __repr__(self):
606 _d = dict(k=self.__class__.__name__,
607 i=self.id,
608 h=self.header,
609 n=self.nvalues)
610 return "<{k} id:{i} header:{h} nvalues:{n} >".format(**_d)
611
612 @property
613 def id(self):
614 return self._id
615
616 @property
617 def header(self):
618 return self._header
619
620 @property
621 def nvalues(self):
622 return len(self.values)
623
624 @property
625 def values(self):
626 return self._values
627
628 def _get_attrs_simple(self):
629 return ['header', 'values']
630
631 def _get_attrs_complex_list(self):
632 return []
633
634 @staticmethod
635 def merge(columns):
636 column_id = columns[0].id
637 column_header = columns[0].header
638 values = []
639 for col in columns:
640 assert col.id == column_id
641 assert col.header == column_header
642 values.extend(col.values)
643 return Column(column_id, column_header, values=values)
644
645
646 class Report(BaseReportElement):
647
648 """
649 A report is a container for attributes, plotGroups, and tables.
650 It can be serialized to json.
651 """
652
653 def __init__(self, id_, title=None, tables=(), attributes=(),
654 plotgroups=(), dataset_uuids=(), uuid=None, tags=()):
655 """
656 :param id_: (str) Should be a string that identifies the report, like 'adapter'.
657 :param title: Display name of report Defaults to the Report+id if None (added in 0.3.9)
658 :param tables: (list of table instances)
659 :param attributes: (list of attribute instances)
660 :param plotgroups: (list of plot group instances)
661 :param dataset_uuids: list[string] DataSet uuids of files used to generate the report
662 :param uuid: the unique identifier for the Report
663 :param tags: a list of strings
664 """
665 BaseReportElement.__init__(self, id_)
666 self._attributes = []
667 self._plotgroups = []
668 self._tables = []
669 self.title = "Report {i}".format(i=self.id) if title is None else title
670 # FIXME(mkocher)(2016-3-30) Add validation to make sure it's a well formed value
671 # this needs to be required
672 self.uuid = uuid if uuid is not None else str(U.uuid4())
673
674 if tables:
675 for table in tables:
676 self.add_table(table)
677 if attributes:
678 for attr in attributes:
679 self.add_attribute(attr)
680 if plotgroups:
681 for plotgroup in plotgroups:
682 self.add_plotgroup(plotgroup)
683
684 # Datasets that
685 self._dataset_uuids = dataset_uuids
686
687 self.tags = tags
688
689 @property
690 def dataset_uuids(self):
691 return self._dataset_uuids
692
693 def add_attribute(self, attribute):
694 """Add an attribute to the report
695 :param attribute: (Attribute instance)
696 """
697 if not isinstance(attribute, Attribute):
698 TypeError("Got type {x}. Expected Attribute type.".format(
699 x=type(attribute)))
700
701 BaseReportElement.is_unique(self, attribute.id)
702 self._attributes.append(attribute)
703
704 def add_plotgroup(self, plotgroup):
705 """
706 Add a plotgroup to the report
707 """
708 if not isinstance(plotgroup, PlotGroup):
709 TypeError("Got type {x}. Expected Attribute type.".format(
710 x=type(plotgroup)))
711
712 BaseReportElement.is_unique(self, plotgroup.id)
713 self._plotgroups.append(plotgroup)
714
715 def add_table(self, table):
716 """
717 Add a table to the report
718 """
719 #BaseReportElement.is_unique(self, table.id)
720 self._tables.append(table)
721
722 def __repr__(self):
723 t = ",".join(self.tags) if self.tags else ""
724 _d = dict(k=self.__class__.__name__,
725 i=self.id,
726 n=self.title,
727 a=len(self.attributes),
728 p=len(self.plotGroups),
729 t=len(self.tables), u=self.uuid, g=t)
730 return "<{k} id:{i} title:{n} uuid:{u} nattributes:{a} nplot_groups:{p} ntables:{t} tags:{g} >".format(
731 **_d)
732
733 @property
734 def attributes(self):
735 return self._attributes
736
737 @property
738 def plotGroups(self):
739 return self._plotgroups
740
741 @property
742 def tables(self):
743 return self._tables
744
745 def _get_attrs_simple(self):
746 return []
747
748 def _get_attrs_complex_list(self):
749 return ['attributes', 'plotGroups', 'tables']
750
751 def get_attribute_by_id(self, id_):
752 """Get an attribute by id. The id should NOT contain the root report id
753
754 :returns: (None, Attribute)
755
756 Example:
757 report.get_attribute_by_id('nmovies')
758
759 *NOT*
760 report.get_attribute_by_id('overview.nmovies')
761 """
762 for attr in self.attributes:
763 if attr.id == id_:
764 return attr
765
766 return None
767
768 def get_table_by_id(self, id_):
769
770 for table in self.tables:
771 if table.id == id_:
772 return table
773
774 return None
775
776 def get_plotgroup_by_id(self, id_):
777
778 for pg in self.plotGroups:
779 if pg.id == id_:
780 return pg
781
782 return None
783
784 def to_dict(self, id_parts=None):
785
786 _d = dict(v=pbcommand.get_version(),
787 t=datetime.datetime.now().isoformat())
788
789 d = BaseReportElement.to_dict(self, id_parts=id_parts)
790 d['_comment'] = "Generated with pbcommand version {v} at {t}".format(
791 **_d)
792
793 # Required in 1.0.0 of the spec
794 d['uuid'] = self.uuid
795 d['title'] = self.title
796 d['version'] = PB_REPORT_SCHEMA_VERSION
797 d['dataset_uuids'] = list(set(self.dataset_uuids))
798
799 d['tags'] = self.tags
800
801 return d
802
803 def to_json(self):
804 """Return a json string of the report"""
805
806 from pbcommand.schemas import validate_pbreport
807
808 try:
809 s = _to_json_with_decoder(self.to_dict())
810 # FIXME(mkocher)(2016-6-20) Enable schema validation
811 # this needs to be processed by the decoder, then validate the
812 # dict
813 # _ = validate_pbreport(json.loads(s))
814 return s
815 except TypeError as e:
816 msg = "Unable to serialize report due to {e} \n".format(e=e)
817 log.error(msg)
818 log.error("Object: " + pformat(self.to_dict()))
819 raise
820
821 def write_json(self, file_name):
822 """
823 Serialized the report to a json file.
824
825 :param file_name: (str) Path to write output json file to.
826 """
827 with open(file_name, 'w') as f:
828 f.write(self.to_json())
829 # log.info("Wrote report {r}".format(r=file_name))
830
831 @staticmethod
832 def from_simple_dict(report_id, raw_d, namespace):
833 """
834 Generate a Report with populated attributes, starting from a flat
835 dictionary (without namespace).
836 """
837 attributes = []
838 for k, v in raw_d.items():
839 ns = "_".join([namespace, k.lower()])
840 # These can't be none for some reason
841 if v is not None:
842 a = Attribute(ns, v, name=k)
843 attributes.append(a)
844 else:
845 warnings.warn("skipping null entry {k}->{v}".format(k=k, v=v))
846 return Report(report_id, attributes=attributes)
847
848 @staticmethod
849 def merge(reports):
850 report_id = reports[0].id
851
852 def _merge_attributes_d(attributes_list):
853 attrs = OrderedDict()
854 for ax in attributes_list:
855 for a in ax:
856 if a.id in attrs:
857 attrs[a.id].append(a.value)
858 else:
859 attrs[a.id] = [a.value]
860 return attrs
861
862 def _merge_attributes_names(attributes_list):
863 names = {}
864 for ax in attributes_list:
865 for a in ax:
866 if a.id in names:
867 assert names[a.id] == a.name
868 else:
869 names[a.id] = a.name
870 return names
871
872 def _attributes_to_table(attributes_list, table_id, title):
873 attrs = _merge_attributes_d(attributes_list)
874 labels = _merge_attributes_names(attributes_list)
875 columns = [Column(k.lower(), header=labels[k], values=values)
876 for k, values in attrs.items()]
877 table = Table(table_id, title=title, columns=columns)
878 return table
879
880 def _to_sum(values):
881 if len(values) > 0 and isinstance(values[0], str):
882 return ",".join(values)
883 return sum(values)
884
885 def _sum_attributes(attributes_list):
886 d = _merge_attributes_d(attributes_list)
887 labels = _merge_attributes_names(attributes_list)
888 return [Attribute(k, _to_sum(values), name=labels[k])
889 for k, values in d.items()]
890
891 def _merge_tables(tables):
892 """Pass through singletons, Table.merge dupes"""
893 id_collisions = defaultdict(list)
894 merged = []
895 for tab in tables:
896 id_collisions[tab.id].append(tab)
897 for tabs in id_collisions.values():
898 if len(tabs) == 1:
899 merged.append(tabs[0])
900 else:
901 merged.append(Table.merge(tabs))
902 return merged
903 attr_list = []
904 table_list = []
905 dataset_uuids = set()
906 for report in reports:
907 assert report.id == report_id
908 attr_list.append(report.attributes)
909 table_list.extend(report.tables)
910 dataset_uuids.update(set(report.dataset_uuids))
911 table = _attributes_to_table(attr_list, 'chunk_metrics',
912 "Chunk Metrics")
913 tables = _merge_tables(table_list)
914 tables.append(table)
915 merged_attributes = _sum_attributes(attr_list)
916 return Report(report_id, attributes=merged_attributes, tables=tables,
917 dataset_uuids=sorted(list(dataset_uuids)))
918
919
920 ########################################################################
921 # SPECIFICATION MODELS
922
923 FS_RE = r"{([GMkp]{0,1})(:)([,]{0,1})([\.]{0,1})([0-9]*)([dfg]{1})}(.*)$"
924
925
926 def validate_format(format_str):
927 m = re.match(FS_RE, format_str)
928 if m is None:
929 raise ValueError("Format string '{s}' is uninterpretable".format(
930 s=format_str))
931 return m
932
933
934 def format_metric(format_str, value):
935 """
936 Format a report metric (attribute or table column value) according to our
937 in-house rules. These resemble Python format strings (plus optional
938 suffix), but with the addition of optional scaling flags.
939 """
940 if value is None:
941 return "NA"
942 elif format_str is None:
943 return str(value)
944 else:
945 m = validate_format(format_str)
946 if m.groups()[0] == 'p':
947 value *= 100.0
948 elif m.groups()[0] == 'G':
949 value /= 1000000000.0
950 elif m.groups()[0] == 'M':
951 value /= 1000000.0
952 elif m.groups()[0] == 'k':
953 value /= 1000.0
954 if isinstance(value, float) and m.groups()[5] == 'd':
955 value = int(value)
956 fs_python = "{{:{:s}{:s}{:s}{:s}}}".format(*(m.groups()[2:6]))
957 formatted = fs_python.format(value)
958 # the percent symbol can be implicit
959 if m.groups()[0] == 'p' and m.groups()[-1] == '':
960 return formatted + "%"
961 else:
962 return formatted + m.groups()[-1]
963
964
965 # FIXME this needs to be standardized
966 DATA_TYPES = {
967 "int": int,
968 "long": int,
969 "float": float,
970 "string": str,
971 "boolean": bool
972 }
973
974
975 class AttributeSpec:
976
977 def __init__(self, id_, name, description, type_, format_=None,
978 is_hidden=False, scale=None):
979 self.id = id_
980 self.name = name
981 self.description = description
982 self._type = type_
983 self.format_str = format_
984 self.is_hidden = is_hidden
985 self.scale = scale
986
987 @property
988 def type(self):
989 return DATA_TYPES[self._type]
990
991 @staticmethod
992 def from_dict(d):
993 format_str = d.get("format", None)
994 if format_str is not None:
995 validate_format(format_str)
996 assert d["type"] in DATA_TYPES, d["type"]
997 return AttributeSpec(d['id'].split(".")[-1], d['name'],
998 d['description'], d["type"], format_str,
999 d.get("isHidden", False), d.get("scale", None))
1000
1001 def validate_attribute(self, attr):
1002 assert attr.id == self.id
1003 if attr.value is not None and not isinstance(attr.value, self.type):
1004 msg = "Attribute {i} has value of type {v} (expected {t})".format(
1005 i=self.id, v=type(attr.value).__name__, t=self.type)
1006 raise TypeError(msg)
1007
1008 def is_fractional_percentage(self):
1009 if self.format_str:
1010 m = validate_format(self.format_str)
1011 return m.groups()[0] == 'p'
1012 return False
1013
1014
1015 class ColumnSpec:
1016
1017 def __init__(self, id_, header, description, type_, format_=None,
1018 is_hidden=False, scale=None):
1019 self.id = id_
1020 self.header = header
1021 self.description = description
1022 self._type = type_
1023 self.format_str = format
1024 self.is_hidden = is_hidden
1025 self.scale = scale
1026
1027 @property
1028 def type(self):
1029 return DATA_TYPES[self._type]
1030
1031 @staticmethod
1032 def from_dict(d):
1033 format_str = d.get("format", None)
1034 if format_str is not None:
1035 validate_format(format_str)
1036 assert d["type"] in DATA_TYPES, d["type"]
1037 return ColumnSpec(d['id'].split(".")[-1], d['header'],
1038 d['description'], d["type"], format_str,
1039 d.get("isHidden", False), d.get("scale", None))
1040
1041 def validate_column(self, col):
1042 assert col.id == self.id
1043 for value in col.values:
1044 if value is not None and not isinstance(value, self.type):
1045 msg = "Column {i} contains value of type {v} (expected {t})".format(
1046 i=self.id, v=type(value).__name__, t=self.type)
1047 if isinstance(value, int) and self._type == "float":
1048 warnings.warn(msg)
1049 else:
1050 raise TypeError(msg)
1051
1052
1053 class TableSpec:
1054
1055 def __init__(self, id_, title, description, columns):
1056 self.id = id_
1057 self.title = title
1058 self.description = description
1059 self.columns = columns
1060 self._col_dict = {c.id: c for c in columns}
1061
1062 @staticmethod
1063 def from_dict(d):
1064 return TableSpec(d['id'].split(".")[-1], d['title'], d['description'],
1065 [ColumnSpec.from_dict(c) for c in d['columns']])
1066
1067 def get_column_spec(self, id_):
1068 return self._col_dict.get(id_, None)
1069
1070
1071 class PlotSpec:
1072
1073 def __init__(self, id_, description, caption, title, xlabel, ylabel):
1074 self.id = id_
1075 self.description = description
1076 self.caption = caption
1077 self.title = title
1078 self.xlabel = xlabel
1079 self.ylabel = ylabel
1080
1081 @staticmethod
1082 def from_dict(d):
1083 return PlotSpec(d['id'].split(".")[-1], d['description'],
1084 d['caption'], d['title'],
1085 d.get('xlabel', None), d.get('ylabel', None))
1086
1087
1088 class PlotGroupSpec:
1089
1090 def __init__(self, id_, title, description, legend, plots=()):
1091 self.id = id_
1092 self.title = title
1093 self.description = description
1094 self.legend = legend
1095 self.plots = plots
1096 self._plot_dict = {p.id: p for p in plots}
1097
1098 @staticmethod
1099 def from_dict(d):
1100 return PlotGroupSpec(d['id'].split(".")[-1], d['title'],
1101 d["description"], d['legend'],
1102 [PlotSpec.from_dict(p) for p in d['plots']])
1103
1104 def get_plot_spec(self, id_):
1105 return self._plot_dict.get(id_, None)
1106
1107
1108 class ReportSpec:
1109 """
1110 Model for a specification of the expected content of a uniquely
1111 identified report. For obvious reasons this mirrors the Report model,
1112 minus values and with added view metadata. These specs should usually
1113 be written out explicitly in JSON rather than built programatically.
1114 """
1115
1116 def __init__(self, id_, version, title, description, attributes=(),
1117 plotgroups=(), tables=(), hidden=False):
1118 self.id = id_
1119 self.version = version
1120 self.title = title
1121 self.description = description
1122 self.attributes = attributes
1123 self.plotgroups = plotgroups
1124 self.tables = tables
1125 self._attr_dict = {a.id: a for a in attributes}
1126 self._plotgrp_dict = {p.id: p for p in plotgroups}
1127 self._table_dict = {t.id: t for t in tables}
1128 self.hidden = hidden
1129
1130 @staticmethod
1131 def from_dict(d):
1132 hidden = d.get("isHidden", False)
1133 return ReportSpec(d['id'], d['version'], d['title'], d['description'],
1134 [AttributeSpec.from_dict(a)
1135 for a in d['attributes']],
1136 [PlotGroupSpec.from_dict(p)
1137 for p in d['plotGroups']],
1138 [TableSpec.from_dict(t) for t in d['tables']],
1139 hidden=hidden)
1140
1141 def get_attribute_spec(self, id_):
1142 return self._attr_dict.get(id_, None)
1143
1144 def get_plotgroup_spec(self, id_):
1145 return self._plotgrp_dict.get(id_, None)
1146
1147 def get_plot_spec(self, pg_id, plot_id):
1148 pg_spec = self._plotgrp_dict.get(pg_id)
1149 if pg_spec is not None:
1150 return pg_spec.get_plot_spec(plot_id)
1151
1152 def get_table_spec(self, id_):
1153 return self._table_dict.get(id_, None)
1154
1155 def validate_report(self, rpt):
1156 """
1157 Check that a generated report corresponding to this spec is compliant
1158 with the expected types and object IDs. (Missing objects will not
1159 result in an error, but unexpected object IDs will.)
1160 """
1161 assert rpt.id == self.id
1162 # TODO check version?
1163 errors = []
1164 for attr in rpt.attributes:
1165 attr_spec = self.get_attribute_spec(attr.id)
1166 if attr_spec is None:
1167 errors.append("Attribute {i} not found in spec".format(
1168 i=attr.id))
1169 else:
1170 try:
1171 attr_spec.validate_attribute(attr)
1172 except TypeError as e:
1173 errors.append(str(e))
1174 try:
1175 format_metric(attr_spec.format_str, attr.value)
1176 except (ValueError, TypeError) as e:
1177 log.error(e)
1178 errors.append("Couldn't format {i}: {e}".format(
1179 i=attr.id, e=str(e)))
1180 for table in rpt.tables:
1181 table_spec = self.get_table_spec(table.id)
1182 if table_spec is None:
1183 errors.append("Table {i} not found in spec".format(i=table.id))
1184 else:
1185 for column in table.columns:
1186 column_spec = table_spec.get_column_spec(column.id)
1187 if column_spec is None:
1188 errors.append("Column {i} not found in spec".format(
1189 i=column.id))
1190 else:
1191 try:
1192 column_spec.validate_column(column)
1193 except TypeError as e:
1194 errors.append(str(e))
1195 for pg in rpt.plotGroups:
1196 pg_spec = self.get_plotgroup_spec(pg.id)
1197 if pg_spec is None:
1198 errors.append("Plot group {i} not found in spec".format(
1199 i=pg.id))
1200 else:
1201 for plot in pg.plots:
1202 plot_spec = pg_spec.get_plot_spec(plot.id)
1203 # FIXME how should we handle plots with variable IDs?
1204 # maybe let the title/caption vary and keep the ID
1205 # constant?
1206 if plot_spec is None:
1207 warnings.warn("Plot {i} not found in spec".format(
1208 i=plot.id))
1209 # errors.append("Plot {i} not found in spec".format(
1210 # i=plot.id))
1211 if len(errors) > 0:
1212 raise ValueError(
1213 "Report {i} failed validation against spec:\n{e}".format(
1214 i=self.id, e="\n".join(errors)))
1215 return rpt
1216
1217 def is_valid_report(self, rpt):
1218 """
1219 Returns True if report passes spec validation.
1220 """
1221 try:
1222 rpt = self.validate_report(rpt)
1223 return True
1224 except ValueError:
1225 return False
1226
1227 def apply_view(self, rpt, force=False):
1228 """
1229 Propagate view metadata (i.e. labels) to a Report object corresponding to
1230 this spec.
1231 """
1232 assert rpt.id == self.id
1233 for attr in rpt.attributes:
1234 attr_spec = self.get_attribute_spec(attr.id)
1235 if force or attr.name in [None, ""]:
1236 attr._name = attr_spec.name
1237 for table in rpt.tables:
1238 table_spec = self.get_table_spec(table.id)
1239 if force or table.title in [None, ""]:
1240 table._title = table_spec.title
1241 for col in table.columns:
1242 col_spec = table_spec.get_column_spec(col.id)
1243 if force or col.header in [None, ""]:
1244 col._header = col_spec.header
1245 for pg in rpt.plotGroups:
1246 pg_spec = self.get_plotgroup_spec(pg.id)
1247 if force or pg.title in [None, ""]:
1248 pg._title = pg_spec.title
1249 for plot in pg.plots:
1250 plot_spec = pg_spec.get_plot_spec(plot.id)
1251 # FIXME see comment above - maybe we just need to repeat IDs?
1252 if plot_spec is not None:
1253 if force or plot.title in [None, ""]:
1254 plot.title = plot_spec.title
1255 if force or plot.caption in [None, ""]:
1256 plot._caption = plot_spec.caption
1257 else:
1258 # warnings.warn("Can't find spec for {i}".format(i=plot.id))
1259 pass
1260 return rpt