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