-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
1301 lines (1120 loc) · 45.1 KB
/
core.py
File metadata and controls
1301 lines (1120 loc) · 45.1 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Definition of language and plots
"""
import os
import sys
import math
import json
import tempfile
import webbrowser
import warnings
from typing import List, Tuple, Any, Union
import numpy as npy
import matplotlib.pyplot as plt
from matplotlib import patches
from dessia_common import DessiaObject, full_classname
from dessia_common.typings import Subclass
from dessia_common.vectored_objects import from_csv, Catalog, ParetoSettings
from plot_data import templates
import plot_data.colors
npy.seterr(divide='raise')
def delete_none_from_dict(dict1):
"""
Delete input dictionary's keys where value is None.
"""
dict2 = {}
for key, value in dict1.items():
if isinstance(value, dict):
dict2[key] = delete_none_from_dict(value)
else:
if value is not None:
dict2[key] = value
return dict2
class PlotDataObject(DessiaObject):
"""
Abstract interface for DessiaObject implementation in module
"""
def __init__(self, type_: str, name: str = '', **kwargs):
self.type_ = type_
DessiaObject.__init__(self, name=name, **kwargs)
def to_dict(self):
"""
Redefines DessiaObject's to_dict() in order to remove keys where
value is None.
"""
dict_ = DessiaObject.to_dict(self, use_pointers=False)
del dict_['object_class']
new_dict_ = delete_none_from_dict(dict_)
return new_dict_
@classmethod
def dict_to_object(cls, dict_):
"""
:rtype: Subclass[PlotDataObject]
"""
type_ = dict_['type_']
object_class = TYPE_TO_CLASS[type_]
dict_['object_class'] = full_classname(object_=object_class,
compute_for='class')
return DessiaObject.dict_to_object(dict_=dict_, force_generic=True)
def plot_data(self):
raise NotImplementedError('It is strange to call plot_data method from a plot_data object.'
f' Check the class {self.__class__.__name__} you are calling')
class HatchingSet(DessiaObject):
"""
A class for setting hatchings on a surface.
:param stroke_width: lines' width
:type stroke_width: float
:param hatch_spacing: the spacing between two hatching in pixels
:type hatch_spacing: float
"""
def __init__(self, stroke_width: float = 1, hatch_spacing: float = 10,
name: str = ''):
self.stroke_width = stroke_width
self.hatch_spacing = hatch_spacing
DessiaObject.__init__(self, name=name)
class Window(DessiaObject):
def __init__(self, width: float, height: float, name: str = ''):
self.width = width
self.height = height
DessiaObject.__init__(self, name=name)
class EdgeStyle(DessiaObject):
"""
A class for customizing edges (such as lines) style.
:param line_width: line width in pixels.
:type line_width: float
:param color_stroke: the edge's color (rgb255).
:type color_stroke: plot_data.Colors.Color
:param dashline: a list of positive floats [a1,...,an] representing \
a pattern where a_2i is the number of solid pixels and a_2i+1 is \
the number of empty pixels.
:type dashline: List[float]
"""
def __init__(self, line_width: float = None, color_stroke: plot_data.colors.Color = None,
dashline: List[int] = None, name: str = ''):
self.line_width = line_width
self.color_stroke = color_stroke
self.dashline = dashline
DessiaObject.__init__(self, name=name)
DEFAULT_EDGESTYLE = EdgeStyle(color_stroke=plot_data.colors.BLACK)
class PointStyle(DessiaObject):
"""
A class for customizing Point2D.
:param color_fill: must be in rgb255.
:type color_fill: str
:param color_stroke: must be in rgb255.
:type color_stroke: str
:param stroke_width: the point contour's width.
:type stroke_width: float
:param size: must be 1, 2, 3 or 4.
:type size: float
:param shape: 'circle', 'square' or 'crux'.
:type shape: str
"""
def __init__(self, color_fill: str = None, color_stroke: str = None,
stroke_width: float = None,
size: float = None, shape: str = None, name: str = ''):
self.color_fill = color_fill
self.color_stroke = color_stroke
self.stroke_width = stroke_width
self.size = size # 1, 2, 3 or 4
self.shape = shape
DessiaObject.__init__(self, name=name)
class TextStyle(DessiaObject):
"""
A class for customizing Text.
:param text_color: the text's color
:type text_color: plot_data.colors.Colors
:param font_size: the font size
:type font_size: float
:param font_style: 'Arial', 'Verdana', 'Times New Roman', 'Courier \
New', 'serif' or 'sans-serif'
:type font_style: str
:param text_align_x: "left", "right", "center", "start" or "end". \
More info on https://www.w3schools.com/tags/canvas_textalign.asp
:type text_align_x: str
:param text_align_y: "top", "hanging", "middle", "alphabetic", \
"ideographic" or "bottom". More info on \
https://www.w3schools.com/tags/canvas_textbaseline.asp
:type text_align_y: str
:param bold:
:type bold: bool
:param italic:
:type italic: bool
:param angle: Text angle in degrees. The angle is clockwise.
:type angle: float
"""
def __init__(self, text_color: plot_data.colors.Color = None,
font_size: float = None,
font_style: str = None,
text_align_x: str = None, text_align_y: str = None,
bold: bool = None, italic: bool = None,
angle: float = None, name: str = ''):
self.text_color = text_color
self.font_size = font_size
self.font_style = font_style
self.text_align_x = text_align_x
self.text_align_y = text_align_y
self.bold = bold
self.italic = italic
self.angle = angle
DessiaObject.__init__(self, name=name)
class SurfaceStyle(DessiaObject):
"""
A class for customizing surfaces.
:param color_fill: fill color
:type color_fill: str
:param opacity: from 0 (transparent) to 1 (opaque).
:type opacity: float
:param hatching: for setting hatchings
:type hatching: HatchingSet
"""
def __init__(self, color_fill: str = None, opacity: float = None,
hatching: HatchingSet = None, name: str = ''):
self.color_fill = color_fill
self.opacity = opacity
self.hatching = hatching
DessiaObject.__init__(self, name=name)
class Text(PlotDataObject):
"""
A class for displaying texts on canvas. Text is a primitive and can be
instantiated by PrimitiveGroup.
:param comment: the comment you want to display
:type comment: str
:param position_x: the text's x position
:type position_x: float
:param position_y: the text's y position
:type position_y: float
:param text_style: for customization (optional)
:type text_style: TextStyle
:param text_scaling: True if you want the text the be rescaled \
when zooming and False otherwise.
:type text_scaling: bool
:param max_width: Set a maximum length for the text. If the text \
is longer than max_width, it is split into several lines.
:type max_width: float
:param multi_lines: This parameter is only useful when max_width parameter is set \
In that case, you can choose between squishing the text in one line or writing on \
multiple lines.
:type multi_lines: bool
"""
def __init__(self, comment: str, position_x: float, position_y: float,
text_style: TextStyle = None, text_scaling: bool = None,
max_width: float = None, multi_lines: bool = True, name: str = ''):
self.comment = comment
self.text_style = text_style
self.position_x = position_x
self.position_y = position_y
self.text_scaling = text_scaling
self.max_width = max_width
self.multi_lines = multi_lines
PlotDataObject.__init__(self, type_='text', name=name)
def mpl_plot(self, ax=None, color='k', alpha=1.):
"""
Plots using Matplotlib.
"""
if not ax:
_, ax = plt.subplots()
ax.text(self.position_x, self.position_y,
self.comment,
color=color,
alpha=alpha)
return ax
class Line2D(PlotDataObject):
"""
An infinite line. Line2D is a primitive and can be instantiated by \
PrimitiveGroups.
:param point1: first endpoint of the line segment [x1, y1].
:type point1: List[float]
:param point2: first endpoint of the line segment [x2, y2].
:type point2: List[float]
:param edge_style: for customization
:type edge_style: EdgeStyle
"""
def __init__(self, point1: List[float], point2: List[float],
edge_style: EdgeStyle = None, name: str = ''):
self.data = point1 + point2
self.edge_style = edge_style
PlotDataObject.__init__(self, type_='line2d', name=name)
def mpl_plot(self, ax=None):
"""
Plots using matplotlib.
"""
if ax is None:
_, ax = plt.subplots()
if not self.edge_style:
color = DEFAULT_EDGESTYLE.color_stroke.rgb
dashes = DEFAULT_EDGESTYLE.dashline
else:
color = self.edge_style.color_stroke.rgb
dashes = self.edge_style.dashline
ax.axline((self.data[0], self.data[1]), (self.data[2], self.data[3]),
color=color, dashes=dashes)
class LineSegment2D(PlotDataObject):
"""
A line segment. This is a primitive that can be called by \
PrimitiveGroup.
:param point1: first endpoint of the line segment [x1, y1].
:type point1: List[float]
:param point2: first endpoint of the line segment [x2, y2].
:type point2: List[float]
:param edge_style: for customization
:type edge_style: EdgeStyle
"""
def __init__(self, point1: List[float], point2: List[float],
edge_style: EdgeStyle = None,
name: str = ''):
self.data = point1 + point2
if edge_style is None:
self.edge_style = EdgeStyle()
else:
self.edge_style = edge_style
PlotDataObject.__init__(self, type_='linesegment2d', name=name)
def bounding_box(self):
"""
:return: the line segment's bounding box.
:rtype: float, float, float, float
"""
return (min(self.data[0], self.data[2]),
max(self.data[0], self.data[2]),
min(self.data[1], self.data[3]),
max(self.data[1], self.data[3]))
def mpl_plot(self, ax=None):
"""
Plots using matplotlib.
"""
if not ax:
_, ax = plt.subplots()
if self.edge_style and self.edge_style.color_stroke:
color = self.edge_style.color_stroke.rgb
else:
color = plot_data.colors.BLACK.rgb
ax.plot([self.data[0], self.data[2]], [self.data[1], self.data[3]],
color=color)
return ax
class LineSegment(LineSegment2D):
def __init__(self, data: List[float], edge_style: EdgeStyle = None,
name: str = ''):
LineSegment2D.__init__(self, data=data, edge_style=edge_style,
name=name)
warnings.warn("LineSegment is deprecated, use LineSegment2D instead",
DeprecationWarning)
class Wire(PlotDataObject):
"""
A set of connected lines. It also provides highlighting feature.
:param lines: [(x1, y1), ..., (xn,yn)]
:type lines: List[Tuple[float, float]]
:param edge_style: Line settings
:type edge_style: EdgeStyle
:param tooltip: a message that is displayed in a tooltip
:type tooltip: str
"""
def __init__(self, lines: List[Tuple[float, float]], edge_style: EdgeStyle = None,
tooltip: str = None, name: str = ""):
self.lines = lines
self.edge_style = edge_style
self.tooltip = tooltip
PlotDataObject.__init__(self, type_="wire", name=name)
class Circle2D(PlotDataObject):
"""
A circle. It is a primitive and can be instantiated by PrimitiveGroup.
:param cx: the center's x position.
:type cx: float
:param cy: the center's y position
:type cy: float
:param r: radius
:type r: float
:param edge_style: customization of the circle's contour
:type edge_style: EdgeStyle
:param surface_style: customization of the circle's interior
:type surface_style: SurfaceStyle
:param tooltip: tooltip message
:type tooltip: str
"""
def __init__(self, cx: float, cy: float, r: float,
edge_style: EdgeStyle = None,
surface_style: SurfaceStyle = None,
tooltip: str = None,
name: str = ''):
self.edge_style = edge_style
self.surface_style = surface_style
self.r = r
self.cx = cx
self.cy = cy
self.tooltip = tooltip
PlotDataObject.__init__(self, type_='circle', name=name)
def bounding_box(self):
"""
:return: the circle's bounding box
:rtype: float, float, float, float
"""
return self.cx - self.r, self.cx + self.r, self.cy - self.r, self.cy + self.r
def mpl_plot(self, ax=None):
"""
Plots using matplotlib
"""
if not ax:
_, ax = plt.subplots()
if self.edge_style:
edgecolor = self.edge_style.color_stroke.rgb
dashes = DEFAULT_EDGESTYLE.dashline
else:
edgecolor = DEFAULT_EDGESTYLE.color_stroke.rgb
dashes = DEFAULT_EDGESTYLE.dashline
if self.surface_style:
facecolor = self.surface_style.color_fill
surface_alpha = self.surface_style.opacity
else:
facecolor = None
surface_alpha = 0
ax.add_patch(patches.Circle((self.cx, self.cy), self.r,
edgecolor=edgecolor,
facecolor=facecolor,
fill=surface_alpha > 0))
return ax
class Point2D(PlotDataObject):
"""
A class for instantiating a point.
:param cx: the point center's x position
:type cx: float
:param cy: the point center's y position
:type cy: float
:param point_style: the point's customization.
:type point_style: PointStyle
"""
def __init__(self, cx: float, cy: float,
point_style: PointStyle = None,
name: str = ''):
self.cx = cx
self.cy = cy
self.point_style = point_style
PlotDataObject.__init__(self, type_='point', name=name)
def bounding_box(self):
"""
:return: the point's bounding box.
:rtype: float, float, float, float
"""
return self.cx, self.cx, self.cy, self.cy
class Axis(PlotDataObject):
"""
A class that contains information for drawing axis.
:param nb_points_x: the average number of points displayed on the \
x-axis.
:type nb_points_x: int
:param nb_points_y: the average number of points displayed on the \
y-axis.
:type nb_points_y: int
:param graduation_style: for graduation customization
:type graduation_style: TextStyle
:param axis_style: for customizing the axis itself.
:type axis_style: EdgeStyle
:param arrow_on: True if you want an arrow to be displayed on axis,\
False otherwise.
:type arrow_on: bool
:param grid_on: True if you want the display a grid, False otherwise
:type grid_on: bool
"""
def __init__(self, nb_points_x: int = 10, nb_points_y: int = 10,
graduation_style: TextStyle = None,
axis_style: EdgeStyle = None, arrow_on: bool = False,
grid_on: bool = True, name: str = ''):
self.nb_points_x = nb_points_x
self.nb_points_y = nb_points_y
self.graduation_style = graduation_style
if graduation_style is None:
self.graduation_style = TextStyle(text_color=plot_data.colors.GREY)
self.axis_style = axis_style
if axis_style is None:
self.axis_style = EdgeStyle(color_stroke=plot_data.colors.LIGHTGREY)
self.arrow_on = arrow_on
self.grid_on = grid_on
PlotDataObject.__init__(self, type_='axis', name=name)
class Tooltip(PlotDataObject):
"""
A class that contains information for drawing a tooltip when \
clicking on points.
A tooltip object is instantiated by Scatter and Dataset classes.
:param attributes: a list containing the attributes \
you want to display. Attributes must be taken from Dataset's or \
Scatter's elements.
:type attributes: List[str]
:param surface_style: for customizing the tooltip's interior
:type surface_style: SurfaceStyle
:param text_style: for customizing its text
:type text_style: TextStyle
:param tooltip_radius: a tooltip is rounded-rectangle-shaped. \
This parameter defines its corners radius.
:type tooltip_radius: float
"""
def __init__(self, attributes: List[str] = None,
text: str = None,
surface_style: SurfaceStyle = None,
text_style: TextStyle = None, tooltip_radius: float = None,
name: str = ''):
self.attributes = attributes
self.text = text
self.surface_style = surface_style
if surface_style is None:
self.surface_style = SurfaceStyle(color_fill=plot_data.colors.LIGHTBLUE,
opacity=0.75)
self.text_style = text_style
if text_style is None:
self.text_style = TextStyle(text_color=plot_data.colors.BLACK, font_size=10)
self.tooltip_radius = tooltip_radius
PlotDataObject.__init__(self, type_='tooltip', name=name)
class Dataset(PlotDataObject):
"""
Numerous points are joined by line segments to display a \
mathematical curve.
Datasets are instantiated by Graph2D to display multiple datasets \
on one canvas.
:param elements: A list of vectors. Vectors must have the same \
attributes (ie the same keys)
:type elements: List[dict]
:param edge_style: for customizing line segments.
:type edge_style: EdgeStyle
:param point_style: for customizing points
:type point_style: PointStyle
:param tooltip: an object containing all information for drawing \
tooltips
:type tooltip: Tooltip
:param display_step: a value that limits the number of points \
displayed.
:type display_step: int
:param attribute_names: [attribute_x, attribute_y] where \
attribute_x is the attribute displayed on x-axis and attribute_y \
is the attribute displayed on y-axis.
:type attribute_names: [str, str]
"""
attribute_names = None
def __init__(self, elements=None,
edge_style: EdgeStyle = None, tooltip: Tooltip = None,
point_style: PointStyle = None,
display_step: int = 1, name: str = ''):
self.edge_style = edge_style
self.tooltip = tooltip
self.point_style = point_style
if elements is None:
self.elements = []
else:
self.elements = elements
self.display_step = display_step
PlotDataObject.__init__(self, type_='dataset', name=name)
class Graph2D(PlotDataObject):
"""
Takes one or several Datasets as input and displays them all in \
one canvas.
:param graphs: a list of Datasets
:type graphs: List[Dataset]
:param x_variable: variable that you want to display on x axis
:type x_variable: str
:param y_variable: variable that you want to display on y axis
:type y_variable: str
:param axis: an object containing all information needed for \
drawing axis
:type axis: Axis
:param log_scale_x: True or False
:type log_scale_x: bool
:param log_scale_y: True or False
:type log_scale_y: bool
"""
def __init__(self, graphs: List[Dataset], x_variable: str, y_variable: str,
axis: Axis = None, log_scale_x: bool = None,
log_scale_y: bool = None, name: str = ''):
self.graphs = graphs
self.attribute_names = [x_variable, y_variable]
if axis is None:
self.axis = Axis()
else:
self.axis = axis
self.log_scale_x = log_scale_x
self.log_scale_y = log_scale_y
PlotDataObject.__init__(self, type_='graph2d', name=name)
def mpl_plot(self):
# axs = plt.subplots(len(self.graphs))
_, ax = plt.subplots()
xname, yname = self.attribute_names[:2]
for dataset in self.graphs:
x = []
y = []
for element in dataset.elements:
x.append(element[xname])
y.append(element[yname])
ax.plot(x, y)
ax.set_xlabel(xname)
ax.set_ylabel(yname)
return ax
class Heatmap(DessiaObject):
"""
Heatmap is a scatter plot's view. This class contains the Heatmap's parameters.
:param size: A tuple of two integers corresponding to the number of squares on the horizontal and vertical sides.
:type size: Tuple[int, int]
:param colors: The list of colors ranging from low density to high density, \
e.g. colors=[plot_data.colors.BLUE, plot_data.colors.RED] \
so the low density areas tend to be blue while higher density areas tend to be red.
:type colors: List[Colors]
:param edge_style: The areas separating lines settings
:type edge_style: EdgeStyle
"""
def __init__(self, size: Tuple[int, int] = None, colors: List[plot_data.colors.Color] = None,
edge_style: EdgeStyle = None, name: str = ''):
self.size = size
self.colors = colors
self.edge_style = edge_style
DessiaObject.__init__(self, name=name)
class Scatter(PlotDataObject):
"""
A class for drawing scatter plots.
:param elements: A list of vectors. Vectors must have the same \
attributes (ie the same keys)
:type elements: List[dict]
:param x_variable: variable that you want to display on x axis
:type x_variable: str
:param y_variable: variable that you want to display on y axis
:type y_variable: str
:param tooltip: an object containing all information needed for \
drawing tooltips
:type tooltip: Tooltip
:param point_style: for points' customization
:type point_style: PointStyle
:param axis: an object containing all information needed for \
drawing axis
:type axis: Axis
:param log_scale_x: True or False
:type log_scale_x: bool
:param log_scale_y: True or False
:type log_scale_y: bool
:param heatmap: Heatmap view settings
:type heatmap: Heatmap
:param heatmap_view: Heatmap view when loading the object. If set \
to False, you'd still be able to enable it using the button.
:type heatmap_view: bool
"""
def __init__(self, x_variable: str, y_variable: str,
tooltip: Tooltip = None,
point_style: PointStyle = None,
elements: List[Any] = None, axis: Axis = None,
log_scale_x: bool = None, log_scale_y: bool = None,
heatmap: Heatmap = None, heatmap_view: bool = None,
name: str = ''):
self.tooltip = tooltip
self.attribute_names = [x_variable, y_variable]
self.point_style = point_style
if not elements:
self.elements = []
else:
self.elements = elements
if not axis:
self.axis = Axis()
else:
self.axis = axis
self.log_scale_x = log_scale_x
self.log_scale_y = log_scale_y
self.heatmap = heatmap
self.heatmap_view = heatmap_view
PlotDataObject.__init__(self, type_='scatterplot', name=name)
class PieChart(PlotDataObject):
"""
A class for drawing pie plots.
:param elements: A list of vectors. Vectors must have the same \
attributes (ie the same keys)
:type elements: List[dict]
:param x_variable: variable that you want to display on x axis
:type x_variable: str
:param tooltip: an object containing all information needed for \
drawing tooltips
:type tooltip: Tooltip
:param point_style: for points' customization
:type point_style: PointStyle
"""
def __init__(self, x_variable: str, elements: List[Any] = None,
tooltip: Tooltip = None,
point_style: PointStyle = None,
edge_style: EdgeStyle = None,
axis: Axis = None,
name: str = ''):
self.tooltip = tooltip
self.attribute_names = [x_variable]
self.point_style = point_style
if not elements:
self.elements = []
else:
self.elements = elements
if not axis:
self.axis = Axis()
else:
self.axis = axis
PlotDataObject.__init__(self, type_='piechart', name=name)
class ScatterMatrix(PlotDataObject):
def __init__(self, elements: List[Any] = None, axes: List[str] = None,
point_style: PointStyle = None, surface_style: SurfaceStyle = None,
name: str = ""):
self.elements = elements
self.axes = axes
self.point_style = point_style
self.surface_style = surface_style
PlotDataObject.__init__(self, type_="scattermatrix", name=name)
class Arc2D(PlotDataObject):
"""
A class for drawing arcs. Arc2D is a primitive and can be \
instantiated by PrimitiveGroup. By default, the arc is drawn anticlockwise.
:param cx: the arc center's x position
:type cx: float
:param cy: the arc center's y position
:type cy: float
:param r: radius
:type r: float
:param start_angle: the start angle in radian
:type start_angle: float
:param end_angle: the end angle in radian
:type end_angle: float
:param data: a list of relevant points for drawing an arc using \
BSPline method. This argument is useless unless the arc2D is part of\
a Contour2D. In such case, the arc must be instantiated by volmdlr.
:type data: List[dict]
:param anticlockwise: True if you want the arc the be drawn \
anticlockwise, False otherwise
:type anticlockwise: bool
:param edge_style: for customization
:type edge_style: EdgeStyle
"""
def __init__(self, cx: float, cy: float, r: float, start_angle: float,
end_angle: float, data=None, anticlockwise: bool = None,
edge_style: EdgeStyle = None,
name: str = ''):
self.cx = cx
self.cy = cy
self.r = r
self.start_angle = start_angle
self.end_angle = end_angle
self.data = data
self.anticlockwise = anticlockwise
self.edge_style = edge_style
PlotDataObject.__init__(self, type_='arc', name=name)
def bounding_box(self):
"""
:return: the arc's bounding box
:rtype: float, float, float, float
"""
return self.cx - self.r, self.cx + self.r, self.cy - self.r, self.cy + self.r
def mpl_plot(self, ax=None):
"""
Plots using matplotlib
"""
if not ax:
_, ax = plt.subplots()
if self.edge_style:
edgecolor = self.edge_style.color_stroke
else:
edgecolor = plot_data.colors.BLACK.rgb
ax.add_patch(
patches.Arc((self.cx, self.cy), 2 * self.r, 2 * self.r, angle=0,
theta1=self.start_angle * 0.5 / math.pi * 360,
theta2=self.end_angle * 0.5 / math.pi * 360,
edgecolor=edgecolor))
return ax
class Contour2D(PlotDataObject):
"""
A Contour2D is a closed polygon that is formed by multiple \
primitives. Contour2D can be instantiated by PrimitiveGroup.
:param plot_data_primitives: a list of primitives \
(Arc2D, LineSegment2D)
:type plot_data_primitives: List[Union[Arc2D, LineSegment2D]]
:param edge_style: for contour's customization
:type edge_style: EdgeStyle
:param surface_style: for customizing the interior of the contour
:type surface_style: SurfaceStyle
:param tooltip: A message that is displayed in a tooltip
:type tooltip: str
"""
def __init__(self, plot_data_primitives: List[Union[Arc2D, LineSegment2D]],
edge_style: EdgeStyle = None,
surface_style: SurfaceStyle = None, tooltip: str = None, name: str = ''):
self.plot_data_primitives = plot_data_primitives
self.edge_style = edge_style
self.surface_style = surface_style
self.tooltip = tooltip
PlotDataObject.__init__(self, type_='contour', name=name)
def bounding_box(self):
"""
:return: the contour's bounding box
:rtype: float, float, float, float
"""
xmin, xmax, ymin, ymax = math.inf, -math.inf, math.inf, -math.inf
for plot_data_primitive in self.plot_data_primitives:
if hasattr(plot_data_primitive, 'bounding_box'):
bb = plot_data_primitive.bounding_box()
xmin, xmax, ymin, ymax = min(xmin, bb[0]), max(xmax, bb[1]), \
min(ymin, bb[2]), max(ymax, bb[3])
return xmin, xmax, ymin, ymax
def mpl_plot(self, ax=None):
"""
Plots using matplotlib
"""
for primitive in self.plot_data_primitives:
ax = primitive.mpl_plot(ax=ax)
return ax
class Label(PlotDataObject):
"""
An object that adds a label to PrimitiveGroups.
:param title: the text displayed in the label
:type title: str
:param text_style: customizing the text
:type text_style: TextStyle
:param rectangle_surface_style: the label's rectangle interior \
customization
:type rectangle_surface_style: SurfaceStyle
:param rectangle_edge_style: the label's rectangle edge customization
:type rectangle_edge_style: EdgeStyle
"""
def __init__(self, title: str, text_style: TextStyle = None,
rectangle_surface_style: SurfaceStyle = None,
rectangle_edge_style: EdgeStyle = None, name: str = ''):
self.title = title
self.text_style = text_style
self.rectangle_surface_style = rectangle_surface_style
self.rectangle_edge_style = rectangle_edge_style
PlotDataObject.__init__(self, type_='label', name=name)
class MultipleLabels(PlotDataObject):
"""
Draws one or several labels. MultipleLabels can be instantiated \
by PrimitiveGroup.
:param labels: a list of Labels
:type labels: List[Label]
"""
def __init__(self, labels: List[Label], name: str = ''):
self.labels = labels
PlotDataObject.__init__(self, type_='multiplelabels', name=name)
class PrimitiveGroup(PlotDataObject):
"""
A class for drawing multiple primitives and contours inside a canvas.
:param primitives: a list of Contour2D, Arc2D, LineSegment2D, \
Circle2D, Line2D or MultipleLabels
:type primitives: List[Union[Contour2D, Arc2D, LineSegment2D, \
Circle2D, Line2D, MultipleLabels, Wire]]
"""
def __init__(self, primitives: List[Union[Contour2D, Arc2D, LineSegment2D,
Circle2D, Line2D, MultipleLabels, Wire]],
name: str = ''):
self.primitives = primitives
PlotDataObject.__init__(self, type_='primitivegroup', name=name)
def mpl_plot(self, ax=None, equal_aspect=True):
"""
Plots using matplotlib
"""
ax = self.primitives[0].mpl_plot(ax=ax)
for primitive in self.primitives[1:]:
primitive.mpl_plot(ax=ax)
ax.set_aspect('equal')
return ax
def bounding_box(self):
"""
:return: the primitive group's bounding box
:rtype: float, flaot, float, float
"""
xmin, xmax, ymin, ymax = math.inf, -math.inf, math.inf, -math.inf
for primitive in self.primitives:
if not hasattr(primitive, 'bounding_box'):
continue
p_xmin, p_xmax, p_ymin, p_ymax = primitive.bounding_box()
xmin = min(xmin, p_xmin)
xmax = max(xmax, p_xmax)
ymin = min(ymin, p_ymin)
ymax = max(ymax, p_ymax)
return xmin, xmax, ymin, ymax
class PrimitiveGroupsContainer(PlotDataObject):
"""
A class for drawing several PrimitiveGroups in one canvas.
:param primitive_groups: a list of PrimitiveGroups
:type primitive_groups: List[PrimitiveGroup]
:param sizes: [size0,...,size_n] where size_i = [width_i, length_i]\
is the size of primitive_groups[i]
:type sizes: List[Tuple[float, float]]
:param coords: In the same way as sizes but for coordinates.
:type coords: List[Tuple[float, float]]
:param associated_elements: A list containing the associated \
elements indices. associated_elements[i] is associated with \
primitive_groups[i]. It only works if this object is inside a \
MultiplePlots.
:type associated_elements: List[int]
:param x_variable: variable that you want to display on x axis
:type x_variable: str
:param y_variable: variable that you want to display on y axis
:type y_variable: str
"""
def __init__(self, primitive_groups: List[PrimitiveGroup],
sizes: List[Tuple[float, float]] = None,
coords: List[Tuple[float, float]] = None,
associated_elements: List[int] = None,
x_variable: str = None, y_variable: str = None,
name: str = ''):
for i, value in enumerate(primitive_groups):
if not isinstance(value, PrimitiveGroup):
primitive_groups[i] = PrimitiveGroup(primitives=value)
self.primitive_groups = primitive_groups
if sizes is not None and isinstance(sizes[0], int):
sizes = [sizes] * len(primitive_groups)
self.sizes = sizes
self.coords = coords
if associated_elements: