-
Notifications
You must be signed in to change notification settings - Fork 444
/
make_tables.py
1862 lines (1533 loc) · 61.5 KB
/
make_tables.py
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
"""This is a helper module to generate tables that can be included in the documentation."""
# ruff: noqa: PTH102,PTH103,PTH107,PTH112,PTH113,PTH117,PTH118,PTH119,PTH122,PTH123,PTH202
from __future__ import annotations
from abc import abstractmethod
from dataclasses import dataclass
from enum import StrEnum, auto
import inspect
import io
import os
from pathlib import Path
import re
import textwrap
from types import FunctionType
from typing import Any, Callable, Dict, Iterable, List, Literal, Optional, Tuple, Type, Union, final
import numpy as np
import pyvista
import pyvista as pv
from pyvista.core.errors import VTKVersionError
from pyvista.examples import _dataset_loader, downloads
from pyvista.examples._dataset_loader import (
_MultiFileDownloadableLoadable,
_SingleFileDownloadableLoadable,
)
DatasetLoaderObj = Union[_MultiFileDownloadableLoadable, _SingleFileDownloadableLoadable]
# Paths to directories in which resulting rst files and images are stored.
CHARTS_TABLE_DIR = "api/plotting/charts"
CHARTS_IMAGE_DIR = "images/charts"
COLORS_TABLE_DIR = "api/utilities"
DATASET_GALLERY_DIR = "api/examples/dataset-gallery"
DATASET_GALLERY_IMAGE_DIR = "images/dataset-gallery"
def _aligned_dedent(txt):
"""Custom variant of `textwrap.dedent`.
Helper method to dedent the provided text up to the special alignment character ``'|'``.
"""
return textwrap.dedent(txt).replace('|', '')
class DocTable:
"""Helper class to create tables for the documentation.
The ``generate`` method creates the table rst file (and possibly any other
files, such as images, used by the table). This method internally calls
the ``fetch_data``, ``get_header`` and ``get_row`` methods, which should be
provided by any subclass.
Each table is generated from a list of 'row_data' provided by the ``fetch_data``
method. The ``get_header`` and ``get_row`` methods generate the required rst
for the table's header and table's rows respectively.
"""
path = None # Path to the rst file to which the table will be written
@classmethod
def generate(cls):
"""Generate this table."""
assert cls.path is not None, f"Subclass {cls} should specify a path."
if isinstance(cls.path, property):
cls.path = cls.path.fget(cls)
data = cls.fetch_data()
assert data is not None, f"No data was fetched by {cls}."
with io.StringIO() as fnew:
fnew.write(cls.get_header(data))
for i, row_data in enumerate(data):
row = cls.get_row(i, row_data)
if row is not None:
fnew.write(row)
# if file exists, verify that we have no new content
fnew.seek(0)
new_txt = fnew.read()
# determine if existing file needs to be rewritten
if Path(cls.path).exists():
with Path(cls.path).open(encoding="utf-8") as fold:
orig_txt = fold.read()
if orig_txt == new_txt:
new_txt = ''
# write if there is any text to write. This avoids resetting the documentation cache
if new_txt:
with open(cls.path, 'w', encoding="utf-8") as fout:
fout.write(new_txt)
pv.close_all()
@classmethod
def fetch_data(cls):
"""Get a list of row_data used to generate the table."""
raise NotImplementedError("Subclasses should specify a fetch_data method.")
@classmethod
def get_header(cls, data):
"""Get the table's header rst."""
raise NotImplementedError("Subclasses should specify a table header.")
@classmethod
def get_row(cls, i, row_data):
"""Get the rst for the given row. Can return ``None`` if no row should
be generated for the provided ``row_data``."""
raise NotImplementedError("Subclasses should specify a get_row method.")
class LineStyleTable(DocTable):
"""Class to generate line style table."""
path = f"{CHARTS_TABLE_DIR}/pen_line_styles.rst"
header = _aligned_dedent(
"""
|.. list-table:: Line styles
| :widths: 20 40 40
| :header-rows: 1
|
| * - Style
| - Description
| - Example
"""
)
row_template = _aligned_dedent(
"""
| * - ``"{}"``
| - {}
| - .. image:: /{}
"""
)
@classmethod
def fetch_data(cls):
# Fetch table data from ``LINE_STYLES`` dictionary.
return [{"style": ls, **data} for (ls, data) in pv.charts.Pen.LINE_STYLES.items()]
@classmethod
def get_header(cls, data):
return cls.header
@classmethod
def get_row(cls, i, row_data):
if row_data["descr"] is None:
return None # Skip line style if description is set to ``None``.
else:
# Create an image from the given line style and generate the row rst.
img_path = f"{CHARTS_IMAGE_DIR}/ls_{i}.png"
cls.generate_img(row_data["style"], img_path)
return cls.row_template.format(row_data["style"], row_data["descr"], img_path)
@staticmethod
def generate_img(line_style, img_path):
"""Generate and save an image of the given line_style."""
p = pv.Plotter(off_screen=True, window_size=[100, 50])
p.background_color = 'w'
chart = pv.Chart2D()
chart.line([0, 1], [0, 0], color="b", width=3.0, style=line_style)
chart.hide_axes()
p.add_chart(chart)
# Generate and crop the image
_, img = p.show(screenshot=True, return_cpos=True)
img = img[18:25, 22:85, :]
# exit early if the image already exists and is the same
if os.path.isfile(img_path) and pv.compare_images(img, img_path) < 1:
return
# save it
p._save_image(img, img_path, False)
class MarkerStyleTable(DocTable):
"""Class to generate marker style table."""
path = f"{CHARTS_TABLE_DIR}/scatter_marker_styles.rst"
header = _aligned_dedent(
"""
|.. list-table:: Marker styles
| :widths: 20 40 40
| :header-rows: 1
|
| * - Style
| - Description
| - Example
"""
)
row_template = _aligned_dedent(
"""
| * - ``"{}"``
| - {}
| - .. image:: /{}
"""
)
@classmethod
def fetch_data(cls):
# Fetch table data from ``MARKER_STYLES`` dictionary.
return [
{"style": ms, **data} for (ms, data) in pv.charts.ScatterPlot2D.MARKER_STYLES.items()
]
@classmethod
def get_header(cls, data):
return cls.header
@classmethod
def get_row(cls, i, row_data):
if row_data["descr"] is None:
return None # Skip marker style if description is set to ``None``.
else:
# Create an image from the given marker style and generate the row rst.
img_path = f"{CHARTS_IMAGE_DIR}/ms_{i}.png"
cls.generate_img(row_data["style"], img_path)
return cls.row_template.format(row_data["style"], row_data["descr"], img_path)
@staticmethod
def generate_img(marker_style, img_path):
"""Generate and save an image of the given marker_style."""
p = pv.Plotter(off_screen=True, window_size=[100, 100])
p.background_color = 'w'
chart = pv.Chart2D()
chart.scatter([0], [0], color="b", size=9, style=marker_style)
chart.hide_axes()
p.add_chart(chart)
# generate and crop the image
_, img = p.show(screenshot=True, return_cpos=True)
img = img[40:53, 47:60, :]
# exit early if the image already exists and is the same
if os.path.isfile(img_path) and pv.compare_images(img, img_path) < 1:
return
# save it
p._save_image(img, img_path, False)
class ColorSchemeTable(DocTable):
"""Class to generate color scheme table."""
path = f"{CHARTS_TABLE_DIR}/plot_color_schemes.rst"
header = _aligned_dedent(
"""
|.. list-table:: Color schemes
| :widths: 15 50 5 30
| :header-rows: 1
|
| * - Color scheme
| - Description
| - # colors
| - Example
"""
)
row_template = _aligned_dedent(
"""
| * - ``"{}"``
| - {}
| - {}
| - .. image:: /{}
"""
)
@classmethod
def fetch_data(cls):
# Fetch table data from ``COLOR_SCHEMES`` dictionary.
return [{"scheme": cs, **data} for (cs, data) in pv.colors.COLOR_SCHEMES.items()]
@classmethod
def get_header(cls, data):
return cls.header
@classmethod
def get_row(cls, i, row_data):
if row_data["descr"] is None:
return None # Skip color scheme if description is set to ``None``.
else:
# Create an image from the given color scheme and generate the row rst.
img_path = f"{CHARTS_IMAGE_DIR}/cs_{i}.png"
n_colors = cls.generate_img(row_data["scheme"], img_path)
return cls.row_template.format(
row_data["scheme"], row_data["descr"], n_colors, img_path
)
@staticmethod
def generate_img(color_scheme, img_path):
"""Generate and save an image of the given color_scheme."""
p = pv.Plotter(off_screen=True, window_size=[240, 120])
p.background_color = 'w'
chart = pv.Chart2D()
# Use a temporary plot to determine the total number of colors in this scheme
tmp_plot = chart.bar([0], [[1]] * 2, color=color_scheme, orientation="H")
n_colors = len(tmp_plot.colors)
plot = chart.bar([0], [[1]] * n_colors, color=color_scheme, orientation="H")
chart.remove_plot(tmp_plot)
plot.pen.color = 'w'
chart.x_range = [0, n_colors]
chart.hide_axes()
p.add_chart(chart)
# Generate and crop the image
_, img = p.show(screenshot=True, return_cpos=True)
img = img[34:78, 22:225, :]
# exit early if the image already exists and is the same
if os.path.isfile(img_path) and pv.compare_images(img, img_path) < 1:
return n_colors
# save it
p._save_image(img, img_path, False)
return n_colors
class ColorTable(DocTable):
"""Class to generate colors table."""
path = f"{COLORS_TABLE_DIR}/colors.rst"
header = _aligned_dedent(
"""
|.. list-table::
| :widths: 50 20 30
| :header-rows: 1
|
| * - Name
| - Hex value
| - Example
"""
)
row_template = _aligned_dedent(
"""
| * - {}
| - ``{}``
| - .. raw:: html
|
| <span style='width:100%; height:100%; display:block; background-color: {};'> </span>
"""
)
@classmethod
def fetch_data(cls):
# Fetch table data from ``hexcolors`` dictionary.
colors = {
name: {"name": name, "hex": hex_, "synonyms": []} for name, hex_ in pv.hexcolors.items()
}
# Add synonyms defined in ``color_synonyms`` dictionary.
for s, name in pv.colors.color_synonyms.items():
colors[name]["synonyms"].append(s)
return colors.values()
@classmethod
def get_header(cls, data):
return cls.header
@classmethod
def get_row(cls, i, row_data):
name_template = '``"{}"``'
names = [row_data["name"]] + row_data["synonyms"]
name = " or ".join(name_template.format(n) for n in names)
return cls.row_template.format(name, row_data["hex"], row_data["hex"])
def _get_doc(func: Callable[[], Any]) -> str:
"""Return the first line of the callable's docstring."""
return func.__doc__.splitlines()[0]
def _get_fullname(typ: Type) -> str:
"""Return the fully qualified name of the given type object."""
return f"{typ.__module__}.{typ.__qualname__}"
def _ljust_lines(lines: List[str], min_width=None) -> List[str]:
"""Left-justify a list of lines."""
min_width = min_width if min_width else _max_width(lines)
return [line.ljust(min_width) for line in lines]
def _max_width(lines: List[str]) -> int:
"""Compute the max line-width from a list of lines."""
return max(map(len, lines))
def _repeat_string(string: str, num_repeat: int) -> str:
"""Repeat `string` `num_repeat` times."""
return ''.join([string] * num_repeat)
def _pad_lines(
lines: Union[str, List[str]],
*,
pad_left: str = '',
pad_right: str = '',
ljust=False,
return_shape=False,
):
"""Add padding to the left or right of each line with a specified string.
Optionally, padding may be applied to left-justify the text such that the lines
all have the same width.
Optionally, the lines may be padded using a specified string on the left or right.
Parameters
----------
lines : str | list[str]
Lines to be padded. If a string, it is first split with splitlines.
pad_left : str, default: ''
String to pad the left of each line with.
pad_right : str, default: ''
String to pad the right of each line with.
ljust : bool, default: False
If ``True``, left-justify the lines such that they have equal width
before applying any padding.
return_shape : bool, default: False
If ``True``, also return the width and height of the padded lines.
"""
if is_str := isinstance(lines, str):
lines = lines.splitlines()
# Justify
lines = _ljust_lines(lines) if ljust else lines
# Pad
lines = [pad_left + line + pad_right for line in lines]
if return_shape:
width, height = _max_width(lines), len(lines)
lines = '\n'.join(lines) if is_str else lines
return lines, width, height
return '\n'.join(lines) if is_str else lines
def _indent_multi_line_string(
string: str, indent_size=3, indent_level: int = 1, omit_first_line=True
) -> str:
"""Indent each line of a multi-line string by a specified indentation level.
Optionally specify the indent size (e.g. 3 spaces for rst).
Optionally omit indentation from the first line if it is already indented.
This function is used to support de-denting formatted multi-line strings.
E.g. for the following rst text with item {} indented by 3 levels:
| .. some_directive::
|
| {}
a multi-line string input such as 'line1\nline2\nline3' will be formatted as:
| .. some_directive::
|
| line1\n line2\n line3
|
which will result in the correct indentation applied to all lines of the string.
"""
lines = string.splitlines()
indentation = _repeat_string(' ', num_repeat=indent_size * indent_level)
first_line = lines.pop(0) if omit_first_line else None
lines = _pad_lines(lines, pad_left=indentation) if len(lines) > 0 else lines
lines.insert(0, first_line) if first_line else None
return '\n'.join(lines)
def _as_iterable(item) -> Iterable[Any]:
return [item] if not isinstance(item, (Iterable, str)) else item
class DatasetCard:
"""Class for creating a rst-formatted card for a dataset.
Create a card with header, footer, and four grid items.
The four grid items are displayed as:
- 2x2 grid for large screens
- 4x1 grid for small screens
Each card has roughly following structure:
+-Card----------------------+
| Header: Dataset name |
| |
| +-Grid------------------+ |
| | Dataset doc | |
| +-----------------------+ |
| | Image | |
| +-----------------------+ |
| | Dataset metadata | |
| +-----------------------+ |
| | File metadata | |
| +-----------------------+ |
| |
| Footer: Data source links |
+---------------------------+
See https://sphinx-design.readthedocs.io/en/latest/index.html for
details on the directives used and their formatting.
"""
card_template = _aligned_dedent(
"""
|.. card::
|
| {}
|
| ^^^
|
| .. grid:: 1 2 2 2
| :margin: 1
|
| .. grid-item::
| :columns: 12 8 8 8
|
| {}
|
| .. grid-item::
| :columns: 12 4 4 4
|
| {}
|
| .. grid-item::
|
| .. card::
| :shadow: none
| :class-header: sd-text-center sd-font-weight-bold sd-px-0 sd-border-right-0 sd-border-left-0 sd-border-top-0
| :class-body: sd-border-0
|
| :octicon:`info` Dataset Info
| ^^^
| {}
|
| .. grid-item::
|
| .. card::
| :shadow: none
| :class-header: sd-text-center sd-font-weight-bold sd-px-0 sd-border-right-0 sd-border-left-0 sd-border-top-0
| :class-body: sd-border-0
|
| :octicon:`file` File Info
| ^^^
| {}
|
| +++
| {}
|
|
"""
)
HEADER_FOOTER_INDENT_LEVEL = 1
GRID_ITEM_INDENT_LEVEL = 3
GRID_ITEM_FIELDS_INDENT_LEVEL = 4
REF_ANCHOR_INDENT_LEVEL = 2
# Template for dataset name and badges
header_template = _aligned_dedent(
"""
|.. grid:: 1
| :margin: 0
|
| .. grid-item::
| :class: sd-text-center sd-font-weight-bold sd-fs-5
|
| {}
|
| .. grid-item::
| :class: sd-text-center
|
| {}
|
"""
)[1:-1]
# Template title with a reference anchor
dataset_title_with_ref_template = _aligned_dedent(
"""
|.. _{}:
|
|{}
"""
)[1:-1]
# Template for dataset func and doc
dataset_info_template = _aligned_dedent(
"""
|{}
|
|{}
"""
)[1:-1]
# Template for dataset image
# The image is encapsulated in its own card
image_template = _aligned_dedent(
"""
|.. card::
| :class-body: sd-px-0 sd-py-0 sd-rounded-3
|
| .. image:: /{}
"""
)[1:-1]
footer_template = _aligned_dedent(
"""
|.. dropdown:: Data Source
| :icon: mark-github
|
| {}
"""
)[1:-1]
# Format fields in a grid where the first item is a left-justified
# name and the second is a right-justified value.
# The grid boxes are justified to push them toward opposite sides.
#
# Smaller entries should fit on one line:
# | Field Value |
#
# Longer entries should fit on two lines:
# | LongField |
# | LongValue |
#
# Fields with many values should align to the right
# and can stack together on one line if they fit.
# | LongField |
# | LongValue |
# | ExtraLongValue |
# | Value3 Value4 |
field_grid_template = _aligned_dedent(
"""
|.. grid:: auto
| :class-container: sd-align-major-justify sd-px-0
| :class-row: sd-align-major-justify sd-px-0
| :margin: 1
| :padding: 0
| :gutter: 1
|
| .. grid-item::
| :columns: auto
| :class: sd-text-nowrap
|
| **{}**
|
| .. grid-item::
| :columns: auto
| :class: sd-text-right sd-text-nowrap
| :child-align: justify
|
| {}
|
"""
)[1:-1]
# If the field has more than one value, all additional values are
# placed in a second grid and aligned towards the 'right' side
# of the grid.
field_grid_extra_values_grid_template = _aligned_dedent(
"""
|.. grid:: auto
| :class-container: sd-align-major-end sd-px-0
| :class-row: sd-align-major-end sd-px-0
| :margin: 1
| :padding: 0
| :gutter: 1
|
"""
)[1:-1]
field_grid_extra_values_item_template = _aligned_dedent(
"""
| .. grid-item::
| :columns: auto
| :class: sd-text-right sd-text-nowrap
|
| {}
|
"""
)[1:-1]
_NOT_AVAILABLE_IMG_PATH = os.path.join(DATASET_GALLERY_IMAGE_DIR, 'not_available.png')
def __init__(
self,
dataset_name: str,
loader: DatasetLoaderObj,
):
self.dataset_name = dataset_name
self.loader = loader
self._badges: List[Optional[_BaseDatasetBadge]] = []
self.card = None
self.ref = None
def add_badge(self, badge: _BaseDatasetBadge):
self._badges.append(badge)
def generate(self):
# Get rst dataset name-related info
index_name, header_name, func_ref, func_doc, func_name = self._generate_dataset_name(
self.dataset_name
)
# Process dataset image
img_path = self._search_image_path(func_name)
self._process_img(img_path)
# Get rst file and instance metadata
(
file_size,
num_files,
file_ext,
reader_type,
dataset_type,
datasource_links,
n_cells,
n_points,
length,
dimensions,
spacing,
n_arrays,
) = DatasetCard._generate_dataset_properties(self.loader)
# Generate rst for badges
carousel_badges = self._generate_carousel_badges(self._badges)
celltype_badges = self._generate_celltype_badges(self._badges)
# Assemble rst parts into main blocks used by the card
header_block, header_ref_block = self._create_header_block(
index_name, header_name, carousel_badges
)
info_block = self._create_info_block(func_ref, func_doc)
img_block = self._create_image_block(img_path)
dataset_props_block = self._create_dataset_props_block(
dataset_type, celltype_badges, n_cells, n_points, length, dimensions, spacing, n_arrays
)
file_info_block = self._create_file_props_block(file_size, num_files, file_ext, reader_type)
footer_block = self._create_footer_block(datasource_links)
# Create two versions of the card
# First version has no ref label
card_no_ref = self.card_template.format(
header_block,
info_block,
img_block,
dataset_props_block,
file_info_block,
footer_block,
)
# Second version has a ref label in header
card_with_ref = self.card_template.format(
header_ref_block,
info_block,
img_block,
dataset_props_block,
file_info_block,
footer_block,
)
return card_no_ref, card_with_ref
@staticmethod
def _generate_dataset_properties(loader):
try:
# Get data from loader
loader.download()
# properties collected by the loader
file_size = DatasetPropsGenerator.generate_file_size(loader)
num_files = DatasetPropsGenerator.generate_num_files(loader)
file_ext = DatasetPropsGenerator.generate_file_ext(loader)
reader_type = DatasetPropsGenerator.generate_reader_type(loader)
dataset_type = DatasetPropsGenerator.generate_dataset_type(loader)
datasource_links = DatasetPropsGenerator.generate_datasource_links(loader)
# properties collected directly from the dataset
n_cells = DatasetPropsGenerator.generate_n_cells(loader)
n_points = DatasetPropsGenerator.generate_n_points(loader)
length = DatasetPropsGenerator.generate_length(loader)
dimensions = DatasetPropsGenerator.generate_dimensions(loader)
spacing = DatasetPropsGenerator.generate_spacing(loader)
n_arrays = DatasetPropsGenerator.generate_n_arrays(loader)
except VTKVersionError:
# Exception is caused by 'download_can'
# Set default values
NOT_AVAILABLE = '``Not available``'
file_size = NOT_AVAILABLE
num_files = NOT_AVAILABLE
file_ext = NOT_AVAILABLE
reader_type = NOT_AVAILABLE
dataset_type = NOT_AVAILABLE
datasource_links = NOT_AVAILABLE
n_cells = None
n_points = None
length = None
dimensions = None
spacing = None
n_arrays = None
return (
file_size,
num_files,
file_ext,
reader_type,
dataset_type,
datasource_links,
n_cells,
n_points,
length,
dimensions,
spacing,
n_arrays,
)
@staticmethod
def _generate_dataset_name(dataset_name: str):
# Format dataset name for indexing and section heading
index_name = dataset_name + '_dataset'
header = ' '.join([word.capitalize() for word in index_name.split('_')])
# Get the corresponding 'download' function of the loader
func_name = 'download_' + dataset_name
func = getattr(downloads, func_name)
# Get the card's header info
func_ref = f':func:`~{_get_fullname(func)}`'
func_doc = _get_doc(func)
return index_name, header, func_ref, func_doc, func_name
@staticmethod
def _generate_carousel_badges(badges: List[_BaseDatasetBadge]):
"""Sort badges by type and join all badge rst into a single string."""
module_badges, datatype_badges, special_badges, category_badges = [], [], [], []
for badge in badges:
if isinstance(badge, ModuleBadge):
module_badges.append(badge)
elif isinstance(badge, DataTypeBadge):
datatype_badges.append(badge)
elif isinstance(badge, SpecialDataTypeBadge):
special_badges.append(badge)
elif isinstance(badge, CategoryBadge):
category_badges.append(badge)
elif isinstance(badge, CellTypeBadge):
pass # process these separately
elif isinstance(badge, _BaseDatasetBadge):
raise NotImplementedError(f'No implementation for badge type {type(badge)}.')
all_badges = module_badges + datatype_badges + special_badges + category_badges
return ' '.join([badge.generate() for badge in all_badges])
@staticmethod
def _generate_celltype_badges(badges: List[_BaseDatasetBadge]):
"""Sort badges by type and join all badge rst into a single string."""
celltype_badges = [badge for badge in badges if isinstance(badge, CellTypeBadge)]
rst = '\n'.join([badge.generate() for badge in celltype_badges])
if rst == '':
rst = '``None``'
return rst
@staticmethod
def _search_image_path(dataset_download_func_name: str):
"""Search the thumbnail directory and return its path.
If no thumbnail is found, the path to a "not available" image is returned.
"""
# Search directory and match:
# any word character(s), then function name, then any non-word character(s),
# then a 3character file extension, e.g.:
# 'pyvista-examples...download_name...ext'
# or simply:
# 'download_name.ext'
all_filenames = '\n' + '\n'.join(os.listdir(DATASET_GALLERY_IMAGE_DIR)) + '\n'
match = re.search(
pattern=r'\n([\w|\-]*' + dataset_download_func_name + r'(\-\w*\.|\.)[a-z]{3})\n',
string=all_filenames,
flags=re.MULTILINE,
)
if match:
groups = match.groups()
assert (
sum(dataset_download_func_name in grp for grp in groups) <= 1
), f"More than one thumbnail image was found for {dataset_download_func_name}, got:\n{groups}"
img_fname = groups[0]
img_path = os.path.join(DATASET_GALLERY_IMAGE_DIR, img_fname)
assert os.path.isfile(img_path)
else:
print(f"WARNING: Missing thumbnail image file for \'{dataset_download_func_name}\'")
img_path = os.path.join(DATASET_GALLERY_IMAGE_DIR, 'not_available.png')
return img_path
@staticmethod
def _process_img(img_path):
"""Process the thumbnail image to ensure it's the right size."""
from PIL import Image
IMG_WIDTH, IMG_HEIGHT = 400, 300
if os.path.basename(img_path) == 'not_available.png':
not_available_mesh = pv.Text3D('Not Available')
p = pv.Plotter(off_screen=True, window_size=(IMG_WIDTH, IMG_HEIGHT))
p.background_color = 'white'
p.add_mesh(not_available_mesh, color='black')
p.view_xy()
p.camera.up = (1, IMG_WIDTH / IMG_HEIGHT, 0)
p.enable_parallel_projection()
img_array = p.show(screenshot=True)
# exit early if the image is the same
if os.path.isfile(img_path) and pv.compare_images(img_path, img_path) < 1:
return
img = Image.fromarray(img_array)
img.save(img_path)
else:
# Resize existing image if necessary
img = Image.open(img_path)
if img.width > IMG_WIDTH or img.height > IMG_HEIGHT:
img.thumbnail(size=(IMG_WIDTH, IMG_HEIGHT))
img.save(img_path)
@staticmethod
def _format_and_indent_from_template(*args, template=None, indent_level=None):
"""Format args using a template and indent all formatted lines by some amount."""
assert template is not None
assert indent_level is not None
formatted = template.format(*args)
return _indent_multi_line_string(formatted, indent_level=indent_level)
@classmethod
def _generate_field_grid(cls, field_name, field_values):
"""Generate a rst grid with field data.
The grid uses the class templates for the field name and field value(s).
"""
if field_values in [None, '']:
return None
value_lines = str(field_values).splitlines()
first_value = value_lines.pop(0)
field = cls.field_grid_template.format(field_name, first_value)
if len(value_lines) >= 1:
# Add another grid for extra values
extra_values_grid = cls.field_grid_extra_values_grid_template
extra_values = [
cls.field_grid_extra_values_item_template.format(val) for val in value_lines
]
return '\n'.join([field, extra_values_grid, *extra_values])
return field
@staticmethod
def _generate_field_block(fields: List[Tuple[str, Union[str, None]]], indent_level: int = 0):
"""Generate a grid for each field and combine the grids into an indented multi-line rst block.
Any fields with a `None` value are completely excluded from the block.
"""
field_grids = [DatasetCard._generate_field_grid(name, value) for name, value in fields]
block = '\n'.join([grid for grid in field_grids if grid])
return _indent_multi_line_string(block, indent_level=indent_level)
@classmethod
def _create_header_block(cls, index_name, header_name, carousel_badges):
"""Generate header rst block."""
# Two headers are created: one with a reference target and one without
header = cls._format_and_indent_from_template(
header_name,
carousel_badges,
template=cls.header_template,
indent_level=cls.HEADER_FOOTER_INDENT_LEVEL,
)
header_name_with_ref = DatasetCard._format_and_indent_from_template(
index_name,
header_name,
template=cls.dataset_title_with_ref_template,
indent_level=cls.REF_ANCHOR_INDENT_LEVEL,
)
header_ref = DatasetCard._format_and_indent_from_template(
header_name_with_ref,
carousel_badges,
template=cls.header_template,
indent_level=cls.HEADER_FOOTER_INDENT_LEVEL,
)
return header, header_ref
@classmethod
def _create_image_block(cls, img_path):
"""Generate rst block for the dataset image."""
return cls._format_and_indent_from_template(
img_path,
template=cls.image_template,
indent_level=cls.GRID_ITEM_INDENT_LEVEL,
)
@classmethod
def _create_info_block(cls, func_ref, func_doc):