forked from wassimj/topologicpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlotly.py
1410 lines (1323 loc) · 62.8 KB
/
Plotly.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
import topologicpy
import topologic
import plotly
import plotly.graph_objects as go
from topologicpy.Vertex import Vertex
from topologicpy.Edge import Edge
from topologicpy.Wire import Wire
from topologicpy.Face import Face
from topologicpy.Cell import Cell
from topologicpy.CellComplex import CellComplex
from topologicpy.Cluster import Cluster
from topologicpy.Topology import Topology
import numpy as np
class Plotly:
@staticmethod
def AddColorBar(figure, values=[], nTicks=5, xPosition=-0.15, width=15, outlineWidth=0, title="", subTitle="", units="", colorScale="viridis", mantissa=4):
"""
Adds a color bar to the input figure
Parameters
----------
figure : plotly.graph_objs._figure.Figure
The input plotly figure.
values : list , optional
The input list of values to use for the color bar. The default is [].
nTicks : int , optional
The number of ticks to use on the color bar. The default is 5.
xPosition : float , optional
The x location of the color bar. The default is -0.15.
width : int , optional
The width in pixels of the color bar. The default is 15
outlineWidth : int , optional
The width in pixels of the outline of the color bar. The default is 0.
title : str , optional
The title of the color bar. The default is "".
subTitle : str , optional
The subtitle of the color bar. The default is "".
units: str , optional
The units used in the color bar. The default is ""
colorScale : str , optional
The desired type of plotly color scales to use (e.g. "viridis", "plasma"). The default is "viridis". For a full list of names, see https://plotly.com/python/builtin-colorscales/.
mantissa : int , optional
The desired length of the mantissa for the values listed on the color bar. The default is 4.
Returns
-------
plotly.graph_objs._figure.Figure
The input figure with the color bar added.
"""
if not isinstance(figure, plotly.graph_objs._figure.Figure):
return None
if units:
units = "Units: "+units
minValue = min(values)
maxValue = max(values)
step = (maxValue - minValue)/float(nTicks-1)
r = [round(minValue+i*step, mantissa) for i in range(nTicks)]
r[-1] = round(maxValue, mantissa)
# Define the minimum and maximum range of the colorbar
rs = [str(x) for x in r]
# Define the colorbar as a trace with no data, x or y coordinates
colorbar_trace = go.Scatter(
x=[0],
y=[0],
mode="markers",
showlegend=False,
marker=dict(
size=0,
colorscale=colorScale, # choose the colorscale
cmin=minValue,
cmax=maxValue,
color=['rgba(0,0,0,0)'],
colorbar=dict(
x=xPosition,
title="<b>"+title+"</b><br>"+subTitle+"<br>"+units, # title of the colorbar
ticks="outside", # position of the ticks
tickvals=r, # values of the ticks
ticktext=rs, # text of the ticks
tickmode="array",
thickness=width,
outlinewidth=outlineWidth,
)
)
)
figure.add_trace(colorbar_trace)
return figure
@staticmethod
def Colors():
"""
Returns the list of named CSS colors that plotly can use.
Returns
-------
list
The list of named CSS colors.
"""
return ["aliceblue","antiquewhite","aqua",
"aquamarine","azure","beige",
"bisque","black","blanchedalmond",
"blue","blueviolet","brown",
"burlywood","cadetblue",
"chartreuse","chocolate",
"coral","cornflowerblue","cornsilk",
"crimson","cyan","darkblue",
"darkcyan","darkgoldenrod","darkgray",
"darkgrey","darkgreen","darkkhaki",
"darkmagenta","darkolivegreen","darkorange",
"darkorchid","darkred","darksalmon",
"darkseagreen","darkslateblue","darkslategray",
"darkslategrey","darkturquoise","darkviolet",
"deeppink","deepskyblue","dimgray",
"dimgrey","dodgerblue","firebrick",
"floralwhite","forestgreen","fuchsia",
"gainsboro","ghostwhite","gold",
"goldenrod","gray","grey",
"green"," greenyellow","honeydew",
"hotpink","indianred","indigo",
"ivory","khaki","lavender",
"lavenderblush","lawngreen","lemonchiffon",
"lightblue","lightcoral","lightcyan",
"lightgoldenrodyellow","lightgray","lightgrey",
"lightgreen","lightpink","lightsalmon",
"lightseagreen","lightskyblue","lightslategray",
"lightslategrey","lightsteelblue","lightyellow",
"lime","limegreen","linen",
"magenta","maroon","mediumaquamarine",
"mediumblue","mediumorchid","mediumpurple",
"mediumseagreen","mediumslateblue","mediumspringgreen",
"mediumturquoise","mediumvioletred","midnightblue",
"mintcream","mistyrose","moccasin",
"navajowhite","navy","oldlace",
"olive","olivedrab","orange",
"orangered","orchid","palegoldenrod",
"palegreen","paleturquoise","palevioletred",
"papayawhip","peachpuff","peru",
"pink","plum","powderblue",
"purple","red","rosybrown",
"royalblue","rebeccapurple","saddlebrown",
"salmon","sandybrown","seagreen",
"seashell","sienna","silver",
"skyblue","slateblue","slategray",
"slategrey","snow","springgreen",
"steelblue","tan","teal",
"thistle","tomato","turquoise",
"violet","wheat","white",
"whitesmoke","yellow","yellowgreen"]
@staticmethod
def DataByDGL(data, labels):
"""
Returns a data frame from the DGL data.
Parameters
----------
data : list
The data to display.
labels : list
The labels to use for the data. The data with the labels in this list will be extracted and used in the returned dataFrame.
Returns
-------
pd.DataFrame
A pandas dataFrame
"""
import pandas as pd
if isinstance(data[labels[0]][0], int):
xAxis_list = list(range(1,data[labels[0]][0]+1))
else:
xAxis_list = data[labels[0]][0]
plot_data = [xAxis_list]
for i in range(1,len(labels)):
plot_data.append(data[labels[i]][0][:len(xAxis_list)])
dlist = list(map(list, zip(*plot_data)))
df = pd.DataFrame(dlist, columns=labels)
return df
@staticmethod
def DataByGraph(graph, vertexColor="white", vertexSize=6, vertexLabelKey=None, vertexGroupKey=None, vertexGroups=[], showVertices=True, edgeColor="black", edgeWidth=1, edgeLabelKey=None, edgeGroupKey=None, edgeGroups=[], showEdges=True):
"""
Creates plotly vertex and edge data from the input graph.
Parameters
----------
graph : topologic.Graph
The input graph.
vertexLabelKey : str , optional
The dictionary key to use to display the vertex label. The default is None.
vertexGroupKey : str , optional
The dictionary key to use to display the vertex group. The default is None.
edgeLabelKey : str , optional
The dictionary key to use to display the edge label. The default is None.
edgeGroupKey : str , optional
The dictionary key to use to display the edge group. The default is None.
edgeColor : str , optional
The desired color of the output edges. This can be any plotly color string and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color.
The default is "black".
edgeWidth : float , optional
The desired thickness of the output edges. The default is 1.
vertexColor : str , optional
The desired color of the output vertices. This can be any plotly color string and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color.
The default is "black".
vertexSize : float , optional
The desired size of the vertices. The default is 1.1.
showEdges : bool , optional
If set to True the edges will be drawn. Otherwise, they will not be drawn. The default is True.
showVertices : bool , optional
If set to True the vertices will be drawn. Otherwise, they will not be drawn. The default is True.
Returns
-------
list
The vertex and edge data list.
"""
from topologicpy.Vertex import Vertex
from topologicpy.Edge import Edge
from topologicpy.Dictionary import Dictionary
from topologicpy.Topology import Topology
from topologicpy.Graph import Graph
import plotly.graph_objs as go
if not isinstance(graph, topologic.Graph):
return None
v_labels = []
v_groupList = []
data = []
if showVertices:
vertices = Graph.Vertices(graph)
if vertexLabelKey or vertexGroupKey:
for v in vertices:
Xn=[Vertex.X(v) for v in vertices] # x-coordinates of nodes
Yn=[Vertex.Y(v) for v in vertices] # y-coordinates of nodes
Zn=[Vertex.Z(v) for v in vertices] # x-coordinates of nodes
v_label = ""
v_group = ""
d = Topology.Dictionary(v)
if d:
try:
v_label = str(Dictionary.ValueAtKey(d, key=vertexLabelKey)) or ""
except:
v_label = ""
try:
v_group = str(Dictionary.ValueAtKey(d, key=vertexGroupKey)) or ""
except:
v_group = ""
try:
v_groupList.append(vertexGroups.index(v_group))
except:
v_groupList.append(len(vertexGroups))
if not v_label == "" and not v_group == "":
v_label = v_label+" ("+v_group+")"
v_labels.append(v_label)
else:
for v in vertices:
Xn=[Vertex.X(v) for v in vertices] # x-coordinates of nodes
Yn=[Vertex.Y(v) for v in vertices] # y-coordinates of nodes
Zn=[Vertex.Z(v) for v in vertices] # x-coordinates of nodes
if len(list(set(v_groupList))) < 2:
v_groupList = vertexColor
if len(v_labels) < 1:
v_labels = ""
v_trace=go.Scatter3d(x=Xn,
y=Yn,
z=Zn,
mode='markers',
name='Graph Vertices',
legendgroup=4,
legendrank=4,
marker=dict(symbol='circle',
size=vertexSize,
color=v_groupList,
colorscale='Viridis',
line=dict(color=edgeColor, width=0.5)
),
text=v_labels,
hoverinfo='text'
)
data.append(v_trace)
if showEdges:
Xe=[]
Ye=[]
Ze=[]
e_labels = []
e_groupList = []
edges = Graph.Edges(graph)
if edgeLabelKey or edgeGroupKey:
for e in edges:
sv = Edge.StartVertex(e)
ev = Edge.EndVertex(e)
Xe+=[Vertex.X(sv),Vertex.X(ev), None] # x-coordinates of edge ends
Ye+=[Vertex.Y(sv),Vertex.Y(ev), None] # y-coordinates of edge ends
Ze+=[Vertex.Z(sv),Vertex.Z(ev), None] # z-coordinates of edge ends
e_label = ""
e_group = ""
d = Topology.Dictionary(e)
if d:
try:
e_label = str(Dictionary.ValueAtKey(d, key=edgeLabelKey)) or ""
except:
e_label = ""
try:
e_group = str(Dictionary.ValueAtKey(d, key=edgeGroupKey)) or ""
except:
e_group = ""
try:
e_groupList.append(edgeGroups.index(e_group))
except:
e_groupList.append(len(edgeGroups))
if not e_label == "" and not e_group == "":
e_label = e_label+" ("+e_group+")"
e_labels.append(e_label)
else:
for e in edges:
sv = Edge.StartVertex(e)
ev = Edge.EndVertex(e)
Xe+=[Vertex.X(sv),Vertex.X(ev), None] # x-coordinates of edge ends
Ye+=[Vertex.Y(sv),Vertex.Y(ev), None] # y-coordinates of edge ends
Ze+=[Vertex.Z(sv),Vertex.Z(ev), None] # z-coordinates of edge ends
if len(list(set(e_groupList))) < 2:
e_groupList = edgeColor
if len(e_labels) < 1:
e_labels = ""
e_trace=go.Scatter3d(x=Xe,
y=Ye,
z=Ze,
mode='lines',
name='Graph Edges',
legendgroup=5,
legendrank=5,
line=dict(color=e_groupList, width=edgeWidth),
text=e_labels,
hoverinfo='text'
)
data.append(e_trace)
return data
@staticmethod
def DataByTopology(topology,
showVertices=True, vertexSize=1.1, vertexColor="black",
vertexLabelKey=None, vertexGroupKey=None, vertexGroups=[],
vertexMinGroup=None, vertexMaxGroup=None,
showVertexLegend=False, vertexLegendLabel="Topology Vertices", vertexLegendRank=1,
vertexLegendGroup=1,
showEdges=True, edgeWidth=1, edgeColor="black",
edgeLabelKey=None, edgeGroupKey=None, edgeGroups=[],
edgeMinGroup=None, edgeMaxGroup=None,
showEdgeLegend=False, edgeLegendLabel="Topology Edges", edgeLegendRank=2,
edgeLegendGroup=2,
showFaces=True, faceOpacity=0.5, faceColor="white",
faceLabelKey=None, faceGroupKey=None, faceGroups=[],
faceMinGroup=None, faceMaxGroup=None,
showFaceLegend=False, faceLegendLabel="Topology Faces", faceLegendRank=3,
faceLegendGroup=3,
intensityKey=None, colorScale="Viridis"):
"""
Creates plotly face, edge, and vertex data.
Parameters
----------
topology : topologic.Topology
The input topology. This must contain faces and or edges.
showVertices : bool , optional
If set to True the vertices will be drawn. Otherwise, they will not be drawn. The default is True.
vertexSize : float , optional
The desired size of the vertices. The default is 1.1.
vertexColor : str , optional
The desired color of the output vertices. This can be any plotly color string and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color.
The default is "black".
vertexLabelKey : str , optional
The dictionary key to use to display the vertex label. The default is None.
vertexGroupKey : str , optional
The dictionary key to use to display the vertex group. The default is None.
vertexGroups : list , optional
The list of vertex groups against which to index the color of the vertex. The default is [].
vertexMinGroup : int or float , optional
For numeric vertexGroups, vertexMinGroup is the desired minimum value for the scaling of colors. This should match the type of value associated with the vertexGroupKey. If set to None, it is set to the minimum value in vertexGroups. The default is None.
edgeMaxGroup : int or float , optional
For numeric vertexGroups, vertexMaxGroup is the desired maximum value for the scaling of colors. This should match the type of value associated with the vertexGroupKey. If set to None, it is set to the maximum value in vertexGroups. The default is None.
showVertexLegend : bool, optional
If set to True, the legend for the vertices of this topology is shown. Otherwise, it isn't. The default is False.
vertexLegendLabel : str , optional
The legend label string used to identify vertices. The default is "Topology Vertices".
vertexLegendRank : int , optional
The legend rank order of the vertices of this topology. The default is 1.
vertexLegendGroup : int , optional
The number of the vertex legend group to which the vertices of this topology belong. The default is 1.
showEdges : bool , optional
If set to True the edges will be drawn. Otherwise, they will not be drawn. The default is True.
edgeWidth : float , optional
The desired thickness of the output edges. The default is 1.
edgeColor : str , optional
The desired color of the output edges. This can be any plotly color string and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color.
The default is "black".
edgeLabelKey : str , optional
The dictionary key to use to display the edge label. The default is None.
edgeGroupKey : str , optional
The dictionary key to use to display the edge group. The default is None.
edgeGroups : list , optional
The list of edge groups against which to index the color of the edge. The default is [].
edgeMinGroup : int or float , optional
For numeric edgeGroups, edgeMinGroup is the desired minimum value for the scaling of colors. This should match the type of value associated with the edgeGroupKey. If set to None, it is set to the minimum value in edgeGroups. The default is None.
edgeMaxGroup : int or float , optional
For numeric edgeGroups, edgeMaxGroup is the desired maximum value for the scaling of colors. This should match the type of value associated with the edgeGroupKey. If set to None, it is set to the maximum value in edgeGroups. The default is None.
showEdgeLegend : bool, optional
If set to True, the legend for the edges of this topology is shown. Otherwise, it isn't. The default is False.
edgeLegendLabel : str , optional
The legend label string used to identify edges. The default is "Topology Edges".
edgeLegendRank : int , optional
The legend rank order of the edges of this topology. The default is 2.
edgeLegendGroup : int , optional
The number of the edge legend group to which the edges of this topology belong. The default is 2.
showFaces : bool , optional
If set to True the faces will be drawn. Otherwise, they will not be drawn. The default is True.
faceOpacity : float , optional
The desired opacity of the output faces (0=transparent, 1=opaque). The default is 0.5.
faceColor : str , optional
The desired color of the output faces. This can be any plotly color string and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color.
The default is "white".
faceLabelKey : str , optional
The dictionary key to use to display the face label. The default is None.
faceGroupKey : str , optional
The dictionary key to use to display the face group. The default is None.
faceGroups : list , optional
The list of face groups against which to index the color of the face. This can bhave numeric or string values. This should match the type of value associated with the faceGroupKey. The default is [].
faceMinGroup : int or float , optional
For numeric faceGroups, minGroup is the desired minimum value for the scaling of colors. This should match the type of value associated with the faceGroupKey. If set to None, it is set to the minimum value in faceGroups. The default is None.
faceMaxGroup : int or float , optional
For numeric faceGroups, maxGroup is the desired maximum value for the scaling of colors. This should match the type of value associated with the faceGroupKey. If set to None, it is set to the maximum value in faceGroups. The default is None.
showFaceLegend : bool, optional
If set to True, the legend for the faces of this topology is shown. Otherwise, it isn't. The default is False.
faceLegendLabel : str , optional
The legend label string used to idenitfy edges. The default is "Topology Faces".
faceLegendRank : int , optional
The legend rank order of the faces of this topology. The default is 3.
faceLegendGroup : int , optional
The number of the face legend group to which the faces of this topology belong. The default is 3.
intensityKey: str, optional
If not None, the dictionary of each vertex is searched for the value associated with the intensity key. This value is then used to color-code the vertex based on the colorScale. The default is None.
colorScale : str , optional
The desired type of plotly color scales to use (e.g. "Viridis", "Plasma"). The default is "Viridis". For a full list of names, see https://plotly.com/python/builtin-colorscales/.
Returns
-------
list
The vertex, edge, and face data list.
"""
from topologicpy.Topology import Topology
from topologicpy.Dictionary import Dictionary
from topologicpy.Color import Color
def vertexData(vertices, dictionaries=None, color="black", size=1.1, labelKey=None, groupKey=None, minGroup=None, maxGroup=None, groups=[], legendLabel="Topology Vertices", legendGroup=1, legendRank=1, showLegend=True, colorScale="Viridis"):
x = []
y = []
z = []
labels = []
groupList = []
label = ""
group = ""
if labelKey or groupKey:
if groups:
if len(groups) > 0:
if type(groups[0]) == int or type(groups[0]) == float:
if not minGroup:
minGroup = min(groups)
if not maxGroup:
maxGroup = max(groups)
else:
minGroup = 0
maxGroup = len(groups) - 1
else:
minGroup = 0
maxGroup = 1
for m, v in enumerate(vertices):
x.append(v[0])
y.append(v[1])
z.append(v[2])
label = ""
group = ""
if len(dictionaries) > 0:
d = dictionaries[m]
if d:
try:
label = str(Dictionary.ValueAtKey(d, key=labelKey)) or ""
except:
label = ""
try:
group = Dictionary.ValueAtKey(d, key=groupKey) or None
except:
group = ""
try:
if type(group) == int or type(group) == float:
if group < minGroup:
group = minGroup
if group > maxGroup:
group = maxGroup
color = Color.ByValueInRange(group, minValue=minGroup, maxValue=maxGroup, colorScale=colorScale)
else:
color = Color.ByValueInRange(groups.index(group), minValue=minGroup, maxValue=maxGroup, colorScale=colorScale)
color = "rgb("+str(color[0])+","+str(color[1])+","+str(color[2])+")"
groupList.append(color)
except:
groupList.append(len(groups))
labels.append(label)
else:
for v in vertices:
x.append(v[0])
y.append(v[1])
z.append(v[2])
if len(list(set(groupList))) < 2:
groupList = color
if len(labels) < 1:
labels = ""
return go.Scatter3d(x=x,
y=y,
z=z,
name=legendLabel,
showlegend=showLegend,
marker=dict(color=groupList, size=vertexSize),
mode='markers',
legendgroup=legendGroup,
legendrank=legendRank,
text=labels,
hoverinfo='text',
hovertext=labels
)
def edgeData(vertices, edges, dictionaries=None, color="black", width=1, labelKey=None, groupKey=None, minGroup=None, maxGroup=None, groups=[], legendLabel="Topology Edges", legendGroup=2, legendRank=2, showLegend=True, colorScale="Viridis"):
x = []
y = []
z = []
labels = []
groupList = []
label = ""
group = ""
if labelKey or groupKey:
if groups:
if len(groups) > 0:
if type(groups[0]) == int or type(groups[0]) == float:
if not minGroup:
minGroup = min(groups)
if not maxGroup:
maxGroup = max(groups)
else:
minGroup = 0
maxGroup = len(groups) - 1
else:
minGroup = 0
maxGroup = 1
for m, e in enumerate(edges):
sv = vertices[e[0]]
ev = vertices[e[1]]
x+=[sv[0],ev[0], None] # x-coordinates of edge ends
y+=[sv[1],ev[1], None] # y-coordinates of edge ends
z+=[sv[2],ev[2], None] # z-coordinates of edge ends
label = ""
group = ""
if len(dictionaries) > 0:
d = dictionaries[m]
if d:
try:
label = str(Dictionary.ValueAtKey(d, key=labelKey)) or ""
except:
label = ""
try:
group = Dictionary.ValueAtKey(d, key=groupKey) or None
except:
group = ""
try:
if type(group) == int or type(group) == float:
if group < minGroup:
group = minGroup
if group > maxGroup:
group = maxGroup
color = Color.ByValueInRange(group, minValue=minGroup, maxValue=maxGroup, colorScale=colorScale)
else:
color = Color.ByValueInRange(groups.index(group), minValue=minGroup, maxValue=maxGroup, colorScale=colorScale)
color = "rgb("+str(color[0])+","+str(color[1])+","+str(color[2])+")"
groupList.append(color)
except:
groupList.append(len(groups))
labels.append(label)
else:
for e in edges:
sv = vertices[e[0]]
ev = vertices[e[1]]
x+=[sv[0],ev[0], None] # x-coordinates of edge ends
y+=[sv[1],ev[1], None] # y-coordinates of edge ends
z+=[sv[2],ev[2], None] # z-coordinates of edge ends
if len(list(set(groupList))) < 2:
groupList = color
if len(labels) < 1:
labels = ""
return go.Scatter3d(x=x,
y=y,
z=z,
name=legendLabel,
showlegend=showLegend,
marker_size=0,
mode="lines",
line=dict(color=groupList, width=edgeWidth),
legendgroup=legendGroup,
legendrank=legendRank,
text=labels,
hoverinfo='text')
def faceData(vertices, faces, dictionaries=None, color="white", opacity=0.5, labelKey=None, groupKey=None, minGroup=None, maxGroup=None, groups=[], legendLabel="Topology Faces", legendGroup=3, legendRank=3, showLegend=True, intensities=None, colorScale="Viridis"):
x = []
y = []
z = []
for v in vertices:
x.append(v[0])
y.append(v[1])
z.append(v[2])
i = []
j = []
k = []
labels = []
groupList = []
label = ""
group = ""
if labelKey or groupKey:
if groups:
if len(groups) > 0:
if type(groups[0]) == int or type(groups[0]) == float:
if not minGroup:
minGroup = min(groups)
if not maxGroup:
maxGroup = max(groups)
else:
minGroup = 0
maxGroup = len(groups) - 1
else:
minGroup = 0
maxGroup = 1
for m, f in enumerate(faces):
i.append(f[0])
j.append(f[1])
k.append(f[2])
label = ""
group = ""
if len(dictionaries) > 0:
d = dictionaries[m]
if d:
try:
label = str(Dictionary.ValueAtKey(d, key=labelKey)) or ""
except:
label = ""
try:
group = Dictionary.ValueAtKey(d, key=groupKey) or None
except:
group = ""
try:
if type(group) == int or type(group) == float:
if group < minGroup:
group = minGroup
if group > maxGroup:
group = maxGroup
color = Color.ByValueInRange(group, minValue=minGroup, maxValue=maxGroup, colorScale=colorScale)
else:
color = Color.ByValueInRange(groups.index(group), minValue=minGroup, maxValue=maxGroup, colorScale=colorScale)
color = "rgb("+str(color[0])+","+str(color[1])+","+str(color[2])+")"
groupList.append(color)
except:
groupList.append(len(groups))
labels.append(label)
else:
for f in faces:
i.append(f[0])
j.append(f[1])
k.append(f[2])
if len(list(set(groupList))) < 2:
groupList = None
if len(labels) < 1:
labels = ""
trace = go.Mesh3d(
x = x,
y = y,
z = z,
i = i,
j = j,
k = k,
name = legendLabel,
showlegend = showLegend,
legendgroup = legendGroup,
legendrank = legendRank,
color = color,
facecolor = groupList,
colorscale = colorScale,
intensity = intensities,
opacity = opacity,
hoverinfo = 'text',
text = labels,
hovertext = labels,
flatshading = True,
showscale = False,
lighting = {"facenormalsepsilon": 0},
)
return trace
from topologicpy.Cluster import Cluster
from topologicpy.Topology import Topology
from topologicpy.Dictionary import Dictionary
if not isinstance(topology, topologic.Topology):
return None
e_dictionaries = None
if edgeLabelKey or edgeGroupKey:
e_dictionaries = []
tp_edges = Topology.SubTopologies(topology, subTopologyType="edge")
for tp_edge in tp_edges:
e_dictionaries.append(Topology.Dictionary(tp_edge))
f_dictionaries = None
if faceLabelKey or faceGroupKey:
f_dictionaries = []
tp_faces = Topology.SubTopologies(topology, subTopologyType="face")
for tp_face in tp_faces:
f_dictionaries.append(Topology.Dictionary(tp_face))
data = []
tp_verts = Topology.SubTopologies(topology, subTopologyType="vertex")
vertices = []
v_dictionaries = []
intensities = []
for i, tp_v in enumerate(tp_verts):
vertices.append([tp_v.X(), tp_v.Y(), tp_v.Z()])
d = Topology.Dictionary(tp_v)
if intensityKey:
if d:
v = Dictionary.ValueAtKey(d, key=intensityKey)
if not v == None:
intensities.append(v)
else:
intensities.append(0)
else:
intensities.append(0)
else:
intensities = None
if vertexLabelKey or vertexGroupKey:
v_dictionaries.append(d)
#if intensities:
#intensities = [float(m)/max(intensities) for m in intensities]
if showVertices:
data.append(vertexData(vertices, dictionaries=v_dictionaries, color=vertexColor, size=vertexSize, labelKey=vertexLabelKey, groupKey=vertexGroupKey, minGroup=vertexMinGroup, maxGroup=vertexMaxGroup, groups=vertexGroups, legendLabel=vertexLegendLabel, legendGroup=vertexLegendGroup, legendRank=vertexLegendRank, showLegend=showVertexLegend, colorScale=colorScale))
if showEdges and topology.Type() > topologic.Vertex.Type():
tp_edges = Topology.SubTopologies(topology, subTopologyType="edge")
edges = []
for tp_edge in tp_edges:
sv = Edge.StartVertex(tp_edge)
si = Vertex.Index(sv, tp_verts)
ev = Edge.EndVertex(tp_edge)
ei = Vertex.Index(ev, tp_verts)
edges.append([si, ei])
data.append(edgeData(vertices, edges, dictionaries=e_dictionaries, color=edgeColor, width=edgeWidth, labelKey=edgeLabelKey, groupKey=edgeGroupKey, minGroup=edgeMinGroup, maxGroup=edgeMaxGroup, groups=edgeGroups, legendLabel=edgeLegendLabel, legendGroup=edgeLegendGroup, legendRank=edgeLegendRank, showLegend=showEdgeLegend, colorScale=colorScale))
if showFaces and topology.Type() >= topologic.Face.Type():
tp_faces = Topology.SubTopologies(topology, subTopologyType="face")
triangles = []
f_dictionaries = []
for tp_face in tp_faces:
temp_faces = Face.Triangulate(tp_face)
for tri in temp_faces:
triangles.append(tri)
if faceLabelKey or faceGroupKey:
f_dictionaries.append(Topology.Dictionary(tp_face))
faces = []
for tri in triangles:
w = Face.ExternalBoundary(tri)
w_vertices = Topology.SubTopologies(w, subTopologyType="vertex")
temp_f = []
for w_v in w_vertices:
i = Vertex.Index(vertex=w_v, vertices=tp_verts, tolerance=0.01)
temp_f.append(i)
faces.append(temp_f)
data.append(faceData(vertices, faces, dictionaries=f_dictionaries, color=faceColor, opacity=faceOpacity, labelKey=faceLabelKey, groupKey=faceGroupKey, minGroup=faceMinGroup, maxGroup=faceMaxGroup, groups=faceGroups, legendLabel=faceLegendLabel, legendGroup=faceLegendGroup, legendRank=faceLegendRank, showLegend=showFaceLegend, intensities=intensities, colorScale=colorScale))
return data
@staticmethod
def FigureByConfusionMatrix(matrix,
categories=[],
minValue=None,
maxValue=None,
title="Confusion Matrix",
xTitle = "Actual",
yTitle = "Predicted",
width=950,
height=500,
showScale = True,
colorScale='Viridis',
colorSamples=10,
backgroundColor='rgba(0,0,0,0)',
marginLeft=0,
marginRight=0,
marginTop=40,
marginBottom=0):
"""
Returns a Plotly Figure of the input confusion matrix. Actual categories are displayed on the X-Axis, Predicted categories are displayed on the Y-Axis.
Parameters
----------
matrix : list or numpy.array
The matrix to display.
categories : list
The list of categories to use on the X and Y axes.
minValue : float , optional
The desired minimum value to use for the color scale. If set to None, the minmum value found in the input matrix will be used. The default is None.
maxValue : float , optional
The desired maximum value to use for the color scale. If set to None, the maximum value found in the input matrix will be used. The default is None.
title : str , optional
The desired title to display. The default is "Confusion Matrix".
xTitle : str , optional
The desired X-axis title to display. The default is "Actual".
yTitle : str , optional
The desired Y-axis title to display. The default is "Predicted".
width : int , optional
The desired width of the figure. The default is 950.
height : int , optional
The desired height of the figure. The default is 500.
showScale : bool , optional
If set to True, a color scale is shown on the right side of the figure. The default is True.
colorScale : str , optional
The desired type of plotly color scales to use (e.g. "Viridis", "Plasma"). The default is "Viridis". For a full list of names, see https://plotly.com/python/builtin-colorscales/.
colorSamples : int , optional
The number of discrete color samples to use for displaying the data. The default is 10.
backgroundColor : str , optional
The desired background color. This can be any plotly color string and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color.
The default is 'rgba(0,0,0,0)' (transparent).
marginLeft : int , optional
The desired left margin in pixels. The default is 0.
marginRight : int , optional
The desired right margin in pixels. The default is 0.
marginTop : int , optional
The desired top margin in pixels. The default is 40.
marginBottom : int , optional
The desired bottom margin in pixels. The default is 0.
"""
if not isinstance(matrix, list) and not isinstance(matrix, np.ndarray):
print("Plotly.FigureByConfusionMatrix - Error: The input matrix is not of the correct type. Returning None.")
return None
figure = Plotly.FigureByMatrix(matrix,
xCategories=categories,
minValue=minValue,
maxValue=maxValue,
title=title,
xTitle=xTitle,
yTitle=yTitle,
width=width,
height=height,
showScale=showScale,
colorScale=colorScale,
colorSamples=colorSamples,
backgroundColor=backgroundColor,
marginLeft=marginLeft,
marginRight=marginRight,
marginTop=marginTop,
marginBottom=marginBottom)
layout = {
"yaxis": {"autorange": "reversed"},
}
figure.update_layout(layout)
return figure
@staticmethod
def FigureByMatrix(matrix,
xCategories=[],
yCategories=[],
minValue=None,
maxValue=None,
title="Matrix",
xTitle = "X Axis",
yTitle = "Y Axis",
width=950,
height=950,
showScale = False,
colorScale='gray',
colorSamples=10,
backgroundColor='rgba(0,0,0,0)',
marginLeft=0,
marginRight=0,
marginTop=40,
marginBottom=0):
"""
Returns a Plotly Figure of the input matrix.
Parameters
----------
matrix : list or numpy.array
The matrix to display.
categories : list
The list of categories to use on the X and Y axes.
minValue : float , optional
The desired minimum value to use for the color scale. If set to None, the minmum value found in the input matrix will be used. The default is None.
maxValue : float , optional
The desired maximum value to use for the color scale. If set to None, the maximum value found in the input matrix will be used. The default is None.
title : str , optional
The desired title to display. The default is "Confusion Matrix".
xTitle : str , optional
The desired X-axis title to display. The default is "Actual".
yTitle : str , optional
The desired Y-axis title to display. The default is "Predicted".
width : int , optional
The desired width of the figure. The default is 950.
height : int , optional
The desired height of the figure. The default is 500.
showScale : bool , optional
If set to True, a color scale is shown on the right side of the figure. The default is True.
colorScale : str , optional
The desired type of plotly color scales to use (e.g. "Viridis", "Plasma"). The default is "Viridis". For a full list of names, see https://plotly.com/python/builtin-colorscales/.
colorSamples : int , optional
The number of discrete color samples to use for displaying the data. The default is 10.
backgroundColor : str , optional
The desired background color. This can be any plotly color string and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color.
The default is 'rgba(0,0,0,0)' (transparent).
marginLeft : int , optional
The desired left margin in pixels. The default is 0.
marginRight : int , optional
The desired right margin in pixels. The default is 0.
marginTop : int , optional
The desired top margin in pixels. The default is 40.
marginBottom : int , optional
The desired bottom margin in pixels. The default is 0.
"""
#import plotly.figure_factory as ff
import plotly.graph_objects as go
import plotly.express as px
if not isinstance(matrix, list) and not isinstance(matrix, np.ndarray):
print("Plotly.FigureByMatrix - Error: The input matrix is not of the correct type. Returning None.")
return None
annotations = []
if isinstance(matrix, list):
matrix = np.array(matrix)
colors = px.colors.sample_colorscale(colorScale, [n/(colorSamples -1) for n in range(colorSamples)])
if not xCategories:
xCategories = [x for x in range(len(matrix[0]))]
if not yCategories:
yCategories = [y for y in range(len(matrix))]
if not maxValue or not minValue:
max_values = []
min_values = []