-
Notifications
You must be signed in to change notification settings - Fork 1
/
Plotting.py
1576 lines (1501 loc) · 70.5 KB
/
Plotting.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 time
import os
import sys
import re
import seaborn as sns
import pandas as pd
import geopandas as gpd
import numpy as np
import shapefile
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter, MaxNLocator
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import matplotlib.patches as mpatches
import matplotlib.patheffects as PathEffects
from mpl_toolkits.axes_grid1 import make_axes_locatable
import polylabel
import networkx as nx
import Utility as util
from Container import Container
np.set_printoptions(precision=4, suppress=True, linewidth=200)
class PolygonN(object):
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
x0, y0 = handlebox.xdescent, handlebox.ydescent
width, height = handlebox.width, handlebox.height
aspect = height/float(width)
verts = orig_handle.get_xy()
closed = orig_handle.get_closed()
minx, miny = verts[:,0].min(), verts[:,1].min()
maxx, maxy = verts[:,0].max(), verts[:,1].max()
aspect= (maxy-miny)/float((maxx-minx))
nvx = (verts[:,0]-minx)*float(height)/aspect/(maxx-minx)-x0
nvy = (verts[:,1]-miny)*float(height)/(maxy-miny)-y0
p = Polygon(np.c_[nvx, nvy], closed)
p.update_from(orig_handle)
p.set_transform(handlebox.get_transform())
handlebox.add_artist(p)
return p
class Plotting(Container):
debug = 0
default_colors = np.array(plt.rcParams["axes.prop_cycle"].by_key()["color"])
# defaults = {
# "bar.width": 0.8,
# "bar.bottom": 0.0,
# "bar.align": "center",
# "color.cycle": plt.rcParams["axes.prop_cycle"].by_key()["color"],
# }
line_width = 1
gt_line_width = 1.25 * line_width
pred_line_width = 0.75 * line_width
marker_size = 7
month_labels = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "January"]
feature_idx_map = {"FLOW_OUTcms": 3, "SWmm": 10, "PRECIPmm": 7}
feature_fullname_map = {
"FLOW_OUTcms": "Streamflow",
"dv_va": "Streamflow",
"SWmm": "Soil Moisture",
"PRECIPmm": "Precipitation",
"tmin": "Minimum Temperature",
"tmax": "Maximum Temperature",
"speedmph": "Vehicle Speed",
"occupancy": "Road Occupancy",
"power_MW": "Power",
"power_kWh": "Power",
"exchange_rate": "Exchange Rate",
"signal_mV": "Signal",
"confirmed": "Confirmed Cases",
"Avg_Speed": "Average Speed",
"return_air_humidity": "Return Air Humidity",
}
feature_SIunit_map = {
"FLOW_OUTcms": "$m^{3}/s$",
"dv_va": "$ft^{3}/s$",
"SWmm": "$mm$",
"PRECIPmm": "$mm$",
"tmin": "$\degree C$",
"tmax": "$\degree C$",
"speedmph": "$mph$",
"occupancy": "$\%$",
"power_MW": "$MW$",
"power_kWh": "$kWh$",
"signal_mV": "$mV$",
"Avg_Speed": "$mph$",
"return_air_humidity": "?",
}
feature_ylabel_map = {}
for feature in feature_fullname_map.keys():
feature_ylabel_map[feature] = feature_fullname_map[feature]
if feature in feature_SIunit_map:
feature_ylabel_map[feature] += " (%s)" % (feature_SIunit_map[feature])
dataset_legend_map = {
"littleriver_observed": "Little",
"wabashriver_swat": "Wabash(SWAT)",
"wabashriver_observed": "Wabash(GT)",
"los-loop_observed": "Los-Loop",
"sz-taxi_observed": "SX-Taxi",
"metr-la": "METR-LA",
"_metr-la": "_METR-LA",
"new-metr-la": "NEW_METR-LA",
"pems-bay": "PEMS-BAY",
"_pems-bay": "_PEMS-BAY",
"new-pems-bay": "NEW_PEMS-BAY",
"traffic": "Traffic",
"solar-energy": "Solar-Energy",
"electricity": "Electricity",
"exchange-rate": "Exchange Rate",
"ecg5000_observed": "ECG5000",
"covid-19_observed": "COVID-19",
"caltranspems_d05": "Caltrans PeMS District 5",
"us-streams": "US National Streams",
"us-streams-al": "Alaska",
"power": "HVAC",
}
partition_fullname_map = {"train": "Training", "valid": "Validation", "test": "Testing"}
partition_codename_map = {"train": "Train", "valid": "Valid", "test": "Test"}
feature_plot_order_map = {
"FLOW_OUTcms": "descending",
"dv_va": "descending",
"SWmm": "descending",
"speedmph": "descending",
"occupancy": "descending",
"power_MW": "descending",
"power_kWh": "descending",
"exchange_rate": "descending",
"signal_mV": "descending",
"confirmed": "descending",
"Avg_Speed": "descending",
"return_air_humidity": "descending",
}
def __init__(self):
self.set("plot_dir", "Plots")
self.set("lines", [])
plt.rcdefaults()
self.defaults = Container()
for key, value in plt.rcParams.items():
fields = key.split(".")
if len(fields) > 1:
self.defaults.set(fields[-1], value, path=fields[:-1])
else:
self.defaults.set(fields[-1], value)
self.defaults.bars = Container().set(
["width", "bottom", "align"],
[0.8, 0, "center"],
multi_value=True
)
def plot_networkx_graph(
self,
G,
node_positions=None,
node_sizes=None,
node_list="all",
edge_list="all",
node_alpha=1.0,
edge_alpha=1.0,
node_kwargs={},
edge_kwargs={},
label_kwargs={},
plot_edges=True,
plot_labels=True,
ax=None,
):
# Get node and edge sets to be plotted
if isinstance(node_list, str) and node_list == "all":
node_list = list(G.nodes())
if isinstance(edge_list, str) and edge_list == "all":
edge_list = list(G.edges())
elif isinstance(edge_list, np.ndarray):
if edge_list.shape[0] == 2:
edge_list = [(src, dst) for src, dst in np.transpose(edge_list)]
n_nodes = len(node_list)
n_edges = len(edge_list)
# Generate/prepare node and edge positions/sizes
if node_positions is None:
node_positions = np.random.uniform(size=(n_nodes, 2))
elif not isinstance(node_positions, dict):
node_positions = util.to_dict(node_list, node_positions)
if node_sizes is None:
node_sizes = 300
elif isinstance(node_sizes, dict):
node_sizes = util.get_dict_values(node_sizes, node_list)
if 0:
for node, pos in node_positions.items():
print(node, pos)
for node, size in zip(G.nodes(), node_sizes):
print(node, size)
# Plot it
node_kwargs = util.merge_dicts({"alpha": 3/4*node_alpha}, node_kwargs)
edge_kwargs = util.merge_dicts({"alpha": edge_alpha, "node_size": 1/4, "arrows": True}, edge_kwargs)
label_kwargs = util.merge_dicts({"alpha": node_alpha, "font_size": 5, "font_color": "r"}, label_kwargs)
if ax is None:
nx.draw_networkx_nodes(G, node_positions, nodelist=node_list, node_size=node_sizes, **node_kwargs)
if plot_edges:
nx.draw_networkx_edges(G, node_positions, edgelist=edge_list, **edge_kwargs)
if plot_labels:
nx.draw_networkx_labels(G, node_positions, **label_kwargs)
else:
nx.draw_networkx_nodes(G, node_positions, nodelist=node_list, node_size=node_sizes, ax=ax, **node_kwargs)
if plot_edges:
nx.draw_networkx_edges(G, node_positions, edgelist=edge_list, ax=ax, **edge_kwargs)
if plot_labels:
nx.draw_networkx_labels(G, node_positions, ax=ax, **label_kwargs)
# plt.axis("off")
def plot_shapes(self, shapes, ax=None, filled=False, **kwargs):
from shapely.geometry import Point, Polygon, MultiPolygon
if isinstance(shapes, str):
shapes = gpd.read_file(shapes)
elif not isinstance(shapes, gpd.GeoDataFrame):
raise ValueError("Input \"shapes\" may be str or geopandas.GeoDataFrame. Received %s" % (type(shapes)))
shapes = shapes.to_crs("epsg:4326")
polys = []
for i in range(len(shapes)):
poly = shapes.loc[i,:].geometry
if isinstance(poly, Polygon):
polys.append(np.array(poly.exterior.coords.xy))
elif isinstance(poly, MultiPolygon):
polys += [np.array(_poly.exterior.coords.xy) for _poly in poly.geoms]
else:
raise NotImplementedError("Unknown geometry type %s" % (type(poly)))
if ax is None:
ax = plt.gca()
for i, poly in enumerate(polys):
if filled:
ax.add_patch(plt.Polygon(poly.T, **kwargs))
else:
self.plot_line(poly[0,:], poly[1,:], ax=ax, **kwargs)
def plot_watershed(self, item_shapes_map, subbasin_river_map, path, highlight=True, watershed="", river_opts={"color_code": True, "name": True}):
cache_path = "Data" + os.sep + "SubbasinLabelCoordinateMap_Watershed[%s].pkl" % (watershed)
if os.path.exists(cache_path):
subbasin_coordinate_map = util.from_cache(cache_path)
else:
subbasin_coordinate_map = {}
for shape_rec in item_shapes_map["subbasins"].shapeRecords():
x = [i[0] for i in shape_rec.shape.points[:]]
y = [i[1] for i in shape_rec.shape.points[:]]
if watershed == "WabashRiver":
subbasin = shape_rec.record[0]
lon, lat = shape_rec.record[10], shape_rec.record[11]
elif watershed == "LittleRiver":
subbasin = shape_rec.record[8]
else:
raise NotImplementedError()
print("Computing Pole of Inaccessibility for ", subbasin)
coords = [[x_i, y_i] for x_i, y_i in zip(x, y)]
subbasin_coords = polylabel.polylabel([coords], 0.1)
subbasin_coordinate_map[subbasin] = subbasin_coords
util.to_cache(subbasin_coordinate_map, cache_path)
n_subbasins = len(subbasin_coordinate_map.keys())
# Normalize coordinates to [0, 1]
min_x, max_x, min_y, max_y = sys.float_info.max, -sys.float_info.max, sys.float_info.max, -sys.float_info.max
min_lon, max_lon, min_lat, max_lat = sys.float_info.max, -sys.float_info.max, sys.float_info.max, -sys.float_info.max
for item, shapes in item_shapes_map.items():
for shape in shapes.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
min_x, max_x, min_y, max_y = min(min(x), min_x), max(max(x), max_x), min(min(y), min_y), max(max(y), max_y)
# Get river color cycle
if len(subbasin_river_map) > 0:
if 1:
colors = np.array(plt.rcParams['axes.prop_cycle'].by_key()['color'])
indices = np.delete(np.arange(len(colors)), [3, 7])
else:
colors = np.array(plt.get_cmap("tab20b").colors)
indices = np.delete(np.arange(20), np.arange(0, 20, 4))
colors = colors[indices]
river_color_map = {}
i = 0
n_rivers, n_colors = len(set(subbasin_river_map.values())), len(colors)
indices = np.arange(n_rivers) % n_colors
np.random.seed(1)
indices = np.random.permutation(indices)
for river in subbasin_river_map.values():
if river not in river_color_map:
river_color_map[river] = colors[indices[i]]
i += 1
tmp = river_color_map["Flatrock"]
river_color_map["Flatrock"] = river_color_map["Muscatatuck"]
river_color_map["Muscatatuck"] = tmp
# River labeling setup
river_subbasins_map = {}
for subbasin, river in subbasin_river_map.items():
if river in river_subbasins_map:
river_subbasins_map[river] += [subbasin]
else:
river_subbasins_map[river] = [subbasin]
# Setup
train_color, test_color = "tab:grey", "tab:red"
np.random.seed(1)
n, r = 1276, 20
subbasins = np.arange(n) + 1
train_indices = sorted(np.random.choice(n, size=r, replace=False))
train_subbasins = subbasins[train_indices]
test_subbasins = sorted(np.delete(subbasins, train_indices)[np.random.choice(n-r, size=r, replace=False)])
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot()
subbasin_patches, river_patches = [], []
train_patches, test_patches, other_patches = [], [], []
subbasin_for_subbasin_legend = 1014
subbasin_for_river_legend = 644
highlight_train, highlight_test = highlight, highlight
highlight_train, highlight_test = highlight, highlight
for item, shapes in item_shapes_map.items():
i = 0
for shape_rec in shapes.shapeRecords():
i += 1
x = np.array([i[0] for i in shape_rec.shape.points[:]])
y = np.array([i[1] for i in shape_rec.shape.points[:]])
x = util.minmax_transform(x, min_x, max_x)
y = util.minmax_transform(y, min_y, max_y)
color = "k"
if "subbasins" in item:
print(dir(shape_rec))
print(shape_rec.record)
print(shape_rec.shape)
if watershed == "WabashRiver":
subbasin = shape_rec.record[0]
lon, lat = shape_rec.record[10], shape_rec.record[11]
elif watershed == "LittleRiver":
subbasin = shape_rec.record[8]
else:
raise NotImplementedError()
subbasin_loc = subbasin_coordinate_map[subbasin]
subbasin_x = util.minmax_transform(subbasin_loc[0], min_x, max_x)
subbasin_y = util.minmax_transform(subbasin_loc[1], min_y, max_y)
xy = np.stack([x, y], axis=1)
if subbasin in train_subbasins:
color = "w"
train_patches += [Polygon(xy)]
elif subbasin in test_subbasins:
color = "w"
test_patches += [Polygon(xy)]
else:
other_patches += [Polygon(xy)]
if subbasin == subbasin_for_subbasin_legend:
subbasin_legend_xy = xy
color = "k"
font_size = {"WabashRiver": 2.5, "LittleRiver": 20}[watershed]
plt.text(subbasin_x, subbasin_y, "%s" % (str(subbasin)), color=color, ha="center", va="center", fontsize=font_size)
line_width = {"WabashRiver": 0.5, "LittleRiver": 2.5}[watershed]
plt.plot(x, y, color="k", linewidth=line_width)
if "rivers" in item:
print(dir(shape_rec))
print(shape_rec.record)
print(shape_rec.shape)
if watershed == "WabashRiver":
subbasin = shape_rec.record[5]
elif watershed == "LittleRiver":
subbasin = shape_rec.record[0]
else:
raise NotImplementedError()
if 1:
max_d = {"WabashRiver": 0.01, "LittleRiver": sys.float_info.max}[watershed]
mask = [False]
for i in range(len(x)-1):
d = ((x[i] - x[i+1])**2 + (y[i] - y[i+1])**2)**(1/2)
mask += [d > max_d]
x, y = np.ma.masked_array(x, mask), np.ma.masked_array(y, mask)
if False:
if x[0] == x[-1] or y[0] == y[-1]:
x, y = x[:-1], y[:-1]
color = "tab:blue"
if len(subbasin_river_map) > 0 and river_opts["color_code"]:
river = subbasin_river_map[subbasin]
color = river_color_map[river]
line_width = {"WabashRiver": 0.625, "LittleRiver": 1.5}[watershed]
plt.plot(x, y, color=color, linewidth=line_width)
if subbasin == subbasin_for_river_legend:
xy = np.ma.stack([x, y], axis=1)
river_legend_xy = xy
if "subbasins" in item:
subbasin_patches = []
if highlight_train:
ax.add_collection(PatchCollection(train_patches, facecolor=train_color))
train_patch = Polygon(subbasin_legend_xy, color=train_color, label="Training Subbasin")
subbasin_patches += [train_patch]
if highlight_test:
ax.add_collection(PatchCollection(test_patches, facecolor=test_color))
test_patch = Polygon(subbasin_legend_xy, color=test_color, label="Testing Subbasin")
subbasin_patches += [test_patch]
if "rivers" in item and len(subbasin_river_map) > 0 and river_opts["name"]:
for river, subbasins in river_subbasins_map.items():
x = np.array([subbasin_coordinate_map[subbasin][0] for subbasin in subbasins])
y = np.array([subbasin_coordinate_map[subbasin][1] for subbasin in subbasins])
x = util.minmax_transform(x, min_x, max_x)
y = util.minmax_transform(y, min_y, max_y)
river_x, river_y = np.mean(x), np.mean(y)
color = river_color_map[river]
size = 4 * (np.log(len(subbasins)) / np.log(5))
if river == "Eel":
txt = plt.text(river_x+0.25, river_y+0.45, "%s" % (str(river)), color=color, ha="center", va="center", fontsize=size)
txt.set_path_effects([PathEffects.withStroke(linewidth=0.1*size, foreground="k")])
txt = plt.text(river_x-0.15, river_y-0.3, "%s" % (str(river)), color=color, ha="center", va="center", fontsize=size)
txt.set_path_effects([PathEffects.withStroke(linewidth=0.1*size, foreground="k")])
else:
txt = plt.text(river_x, river_y, "%s" % (str(river)), color=color, ha="center", va="center", fontsize=size)
txt.set_path_effects([PathEffects.withStroke(linewidth=0.1*size, foreground="k")])
river_patch_map = {}
for river in subbasin_river_map.values():
color = river_color_map[river]
if river not in river_patch_map:
river_patch_map[river] = Polygon(river_legend_xy, False, fill=False, color=color, label=river)
river_patches = list(river_patch_map.values())
handles = subbasin_patches# + river_patches[:]
if len(handles) > 0:
size = 15
if 1:
plt.legend(
handles=handles,
handler_map={Polygon: PolygonN()},
prop={"size": size}
)
else:
n_col = len(handles) // 3
n_col = 4
plt.legend(
handles=handles,
handler_map={Polygon: PolygonN()},
loc="upper center",
bbox_to_anchor=(0.5,1.1),
ncol=n_col,
fancybox=True,
shadow=True,
prop={"size": size}
)
dpi = 500
dpi = 1000
plt.axis("off")
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.savefig(path, bbox_inches="tight", dpi=dpi)
plt.close()
def plot_cluster_heatmap(self, mat, xtick_labels=[], ytick_labels=[], xlabel="", ylabel="", plot_numbers=True, transpose=False, size=(12, 12), rowcol_cluster=[True, True], ax=None):
data = {}
if xtick_labels == []:
xtick_labels = list(range(mat.shape[1]))
if ytick_labels == []:
ytick_labels = list(range(mat.shape[0]))
if transpose:
for i in range(mat.shape[0]):
data[ytick_labels[i]] = mat[i,:]
else:
for i in range(mat.shape[1]):
data[xtick_labels[i]] = mat[:,i]
data = pd.DataFrame(data)
if transpose:
data.index = xtick_labels
else:
data.index = ytick_labels
cg = sns.clustermap(data, method="average", metric="correlation", figsize=size, annot=plot_numbers, annot_kws={"fontsize": 0.7*size[0]}, row_cluster=rowcol_cluster[0], col_cluster=rowcol_cluster[1])
plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=0)
plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)
if transpose:
cg.ax_heatmap.set_xlabel(ylabel, fontsize=1.5*size[0])
cg.ax_heatmap.set_ylabel(xlabel, fontsize=1.5*size[0])
else:
cg.ax_heatmap.set_xlabel(xlabel, fontsize=1.5*size[0])
cg.ax_heatmap.set_ylabel(ylabel, fontsize=1.5*size[0])
return ax
def plot_heatmap(self, mat, xtick_locs=None, xtick_labels=[], ytick_locs=None, ytick_labels=[], xlabel="", ylabel="", cbar_label="", cmap="viridis", plot_cbar=True, plot_numbers=False, transpose=False, ax=None):
if ax is None:
ax = plt.gca()
if transpose:
mat = np.transpose(mat)
xtick_labels, ytick_labels = ytick_labels, xtick_labels
xlabel, ylabel = ylabel, xlabel
size = (mat.shape[1], mat.shape[0])
if plot_numbers:
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
plt.text(
j,
mat.shape[0]-1-i,
"%.4f" % (mat[i,j]),
ha="center",
va="center",
fontsize=0.5*size[0]
)
im = ax.imshow(mat, cmap=cmap, extent=[-0.5, mat.shape[1]-0.5, -0.5, mat.shape[0]-0.5])
if plot_cbar:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax)
cbar.ax.set_ylabel(cbar_label, rotation=-90, va="bottom", fontsize=16)
if ytick_locs is None:
ytick_locs = np.flip(np.arange(len(ytick_labels)))
if 1:
self.xticks(xtick_locs, xtick_labels, ax=ax, rotation=90)
self.yticks(ytick_locs, ytick_labels, ax=ax)
else:
self.xticks(xtick_locs, xtick_labels, ax=ax, fontsize=0.75*size[0], rotation=90)
self.yticks(ytick_locs, ytick_labels, ax=ax, fontsize=0.75*size[1])
self.xlabel(xlabel, ax=ax, fontsize=16)
self.ylabel(ylabel, ax=ax, fontsize=16)
return ax
def plot_graph_distributions(self, G, distributions, graph_name, plot_dir="Plots"):
# Degrees
path = plot_dir + os.sep + "GraphDistribution_Graph[%s]_Type[%s].png" % (
graph_name,
"degree"
)
if "degree" in distributions and not os.path.exists(path):
degree_dist = netprop.Degree_Distribution(G)
self.plot_distribution(
degree_dist,
path,
xlabel="Degree ($k$)",
ylabel="Nodes with Degree $k$ ($N_k$)",
title="Degree Distribution"
)
# Connected Components
path = plot_dir + os.sep + "GraphDistribution_Graph[%s]_Type[%s].png" % (
graph_name,
"connected_component"
)
if "connected_component" in distributions and not os.path.exists(path):
CC_dist = netprop.CC_Distribution(G)
self.plot_distribution(
CC_dist,
path,
xlabel="Weekly Connected Component Size",
ylabel="Count",
title="Connected Component Size Distribution",
xlog=False,
ylog=False,
intAxis=False
)
# Local Clustering Coefficients
path = plot_dir + os.sep + "GraphDistribution_Graph[%s]_Type[%s].png" % (
graph_name,
"local_clustering_coefficient"
)
if "local_clustering_coefficient" in distributions and not os.path.exists(path):
LCC_dist = netprop.Clustering_Analysis(G)
self.plot_distribution(
LCC_dist,
path,
xlabel="Clustering Coefficient",
ylabel="Number of Nodes",
title="Clustering Coefficient Distribution",
xlog=False,
ylog=False,
showLine=False
)
# Shortest Paths
path = plot_dir + os.sep + "GraphDistribution_Graph[%s]_Type[%s].png" % (
graph_name,
"shortest_path"
)
if "shortest_path" in distributions and not os.path.exists(path):
SPL_dist = netprop.ShortestPaths_Analysis(G)
self.plot_distribution(
SPL_dist,
path,
xlabel="Shortest Path Lengths (hops)",
ylabel="Number of Paths",
title="Shortest Path Length Distribution",
xlog=False,
ylog=False,
showLine=False,
intAxis=True
)
def plot_distribution(self, data, path="", xlabel="", ylabel="", title="", xlog = True, ylog= True, showLine=False, intAxis=False) :
counts = {}
for item in data :
if item not in counts :
counts[item] = 0
counts[item] += 1
counts = sorted(counts.items())
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter([k for (k, v) in counts] , [v for (k, v) in counts])
if(len(counts)<20): # for tiny graph
showLine=True
if showLine:
ax.plot([k for (k, v) in counts] , [v for (k, v) in counts])
if xlog:
ax.set_xscale("log")
if ylog:
ax.set_yscale("log")
if intAxis:
gca = fig.gca()
gca.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.xaxis.set_major_formatter(FormatStrFormatter("%.2e"))
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.xticks(rotation=60)
plt.title(title)
if isinstance(path, str) and path != "":
fig.savefig(path, bbox_inches="tight")
else:
fig.show()
plt.close()
# Purpose:
# Plot the probability density function for given data
# Notes:
# If receiving "underflow encountered in exp" error, increase/decrease bandwidth/n_bins value
# If PDF looks noisy, increase/decrease bandwidth/n_bins value
# If PDF doesn't sufficiently span the known value range, decrease/increase bandwidth/n_bins value
def plot_density(self, data, source="", bandwidth=None, n_bins=100, plt_mean=False, plt_median=False, plt_stddev=False, fill=False, line_kwargs={}):
from sklearn.neighbors import KernelDensity
from scipy.stats import gaussian_kde
from statsmodels.nonparametric.kde import KDEUnivariate
if self.debug:
print(data.shape, np.min(data), np.max(data))
X = np.reshape(data, -1)
x_range = np.max(X) - np.min(X)
if bandwidth is None:
bandwidth = x_range / n_bins
xs = np.linspace(np.min(X)-x_range/10, np.max(X)+x_range/10, n_bins+1, endpoint=True)
kde = KernelDensity(bandwidth=bandwidth)
kde.fit(np.reshape(X, [-1, 1]))
pdf = np.exp(kde.score_samples(np.reshape(xs, [-1, 1])))
# Interpolate line
from scipy.interpolate import make_interp_spline, BSpline
new_xs = np.linspace(np.min(xs), np.max(xs), 4*n_bins+1, endpoint=True)
new_ys = make_interp_spline(xs, pdf, k=3)(new_xs)
# pdf = pdf / np.sum(pdf)
label = "$%s$" % (source.replace(" ", " \\ "))
lines = plt.plot(
new_xs,
new_ys,
label=label,
**line_kwargs,
)
self.set("lines", self.get("lines") + lines)
if fill:
plt.fill_between(xs, 0, pdf, facecolor=color, alpha=0.2)
mean, median, std = np.mean(X), np.median(X), np.std(X)
if plt_mean:
height = np.interp(mean, xs, pdf)
label = "$\mu$"
if source in self.partition_codename_map:
label = "$\mu_{%s}$" % (self.partition_codename_map[source].replace(" ", " \\ "))
elif source != "":
label = "$\mu_{%s}$" % (source.replace(" ", " \\ "))
plt.vlines(mean, 0, height, label=label, color=color, ls="-.", linewidth=self.line_width)
if plt_median:
height = np.interp(median, xs, pdf)
label = "$Median$"
if source in self.partition_codename_map:
label = "$Median_{%s}$" % (self.partition_codename_map[source].replace(" ", " \\ "))
elif source != "":
label = "$Median_{%s}$" % (source.replace(" ", " \\ "))
plt.vlines(median, 0, height, label=label, color=color, ls=":", linewidth=self.line_width)
if plt_stddev:
height = np.interp(mean-std, xs, pdf)
plt.vlines(mean-std, 0, height, color=color, ls=":", linewidth=self.line_width)
height = np.interp(mean+std, xs, pdf)
label = "$\mu \pm \sigma$"
if source in self.partition_codename_map:
label = "$\mu_{%s} \pm \sigma_{%s}$" % (
self.partition_codename_map[source].replace(" ", " \\ "),
self.partition_codename_map[source].replace(" ", " \\ ")
)
elif source != "":
label = "$\mu_{%s} \pm \sigma_{%s}$" % (
source.replace(" ", " \\ "),
source.replace(" ", " \\ ")
)
label = "$\sigma_{%s}$" % (source.replace(" ", " \\ "))
plt.vlines(mean+std, 0, height, label=label, color=color, ls=":", linewidth=self.line_width)
y_max = -sys.float_info.max
for line in self.get("lines"):
y_max = max(y_max, np.max(line.get_ydata()))
self.lims(ylim=[-0.002*y_max, y_max*1.01])
self.legend()
return self.lines
def plot_time_series(self, x, y, temporal_labels=None, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
if x is None:
x = range(len(y))
line = self.plot_line(x, y, ax=ax, **kwargs)
if not temporal_labels is None:
indices = np.linspace(0, len(temporal_labels)-1, 7, dtype=int)
self.xticks(indices, temporal_labels[indices], ax=ax, rotation=60)
return line
def plot_line(self, x, y, ax=None, **kwargs):
if x is None:
x = range(len(y))
if ax is None:
ax = plt.gca()
kwargs = util.merge_dicts(
{},
kwargs,
)
return ax.plot(x, y, **kwargs)
def plot_bar(self, x, y, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
kwargs = util.merge_dicts(
{"width": 0.8, "bottom": 0.0, "align": "center"},
kwargs,
)
if x is None:
x = np.arange(len(y))
elif isinstance(x[0], str):
x = np.arange(len(x))
ax.bar(x, y, **kwargs)
def plot_scatter(self, x, y, labels=None, ax=None, scatter_kwargs={}, label_kwargs={}):
if ax is None:
ax = plt.gca()
scatter_kwargs = util.merge_dicts(
{
"s": 75,
"edgecolors": "none",
},
scatter_kwargs
)
label_kwargs = util.merge_dicts(
{"color": "w", "va": "center", "ha": "center", "fontsize": 5},
label_kwargs
)
if not labels is None:
for _x, _y, _label in zip(x, y, labels):
plt.text(_x, _y, _label, **label_kwargs)
ax.scatter(x, y, **scatter_kwargs)
def plot_trend(self, x, y, ax=None, **kwargs):
kwargs = util.merge_dicts(
{"color": "k", "linestyle": "--", "linewidth": 0.75},
kwargs,
)
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
self.plot_line(x, p(x), ax=ax, **kwargs)
def plot_axis(self, loc, axis="x", **kwargs):
if axis != "x" and axis != "y":
raise ValueError("Only x and y axis lines supported. Received axis=\"%s\"" % (axis))
kwargs = util.merge_dicts({"color": "k"}, kwargs)
plot_fn = plt.axhline
if axis == "y":
plot_fn = plt.axvline
plot_fn(loc, **kwargs)
def xlim(self, left=None, right=None, margin=0.0, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
curr_left, curr_right = ax.get_xlim()
# if not (left is None or right is None):
if not left is None:
ax.set_xlim(left=left, **kwargs)
if not right is None:
ax.set_xlim(right=right, **kwargs)
return curr_left, curr_right
def ylim(self, bottom=None, top=None, margin=0.0, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
curr_bottom, curr_top = ax.get_ylim()
# if not (bottom is None or top is None):
if not bottom is None:
ax.set_ylim(bottom=bottom, **kwargs)
if not top is None:
ax.set_ylim(top=top, **kwargs)
return curr_bottom, curr_top
def lim(self, xlim=None, ylim=None, xmargin=0.0, ymargin=0.0, ax=None, xlim_kwargs={}, ylim_kwargs={}):
if xlim is None:
xlim = (None, None)
if ylim is None:
ylim = (None, None)
left, right = self.xlim(xlim[0], xlim[1], xmargin, ax, **xlim_kwargs)
bottom, top = self.ylim(ylim[0], ylim[1], ymargin, ax, **ylim_kwargs)
return (left, right), (bottom, top)
def xticks(self, locs=None, labels=None, ax=None, **kwargs):
if locs is None and not labels is None:
locs = range(len(labels))
if ax is None:
ax = plt.gca()
_locs, _labels = ax.get_xticks(), ax.get_xticklabels()
if not locs is None:
ax.set_xticks(locs, labels, **kwargs)
return _locs, _labels
def yticks(self, locs=None, labels=None, ax=None, **kwargs):
if locs is None and not labels is None:
locs = range(len(labels))
if ax is None:
ax = plt.gca()
_locs, _labels = ax.get_yticks(), ax.get_yticklabels()
if not locs is None:
ax.set_yticks(locs, labels, **kwargs)
return _locs, _labels
def ticks(self, xticks=None, yticks=None, ax=None, xtick_kwargs={}, ytick_kwargs={}):
if xticks is None:
xticks = (None, None)
elif xticks == []:
xticks = ([], [])
else:
raise ValueError(xticks)
if yticks is None:
yticks = (None, None)
elif yticks == []:
yticks = ([], [])
else:
raise ValueError(yticks)
xlocs, xlabels = self.xticks(xticks[0], xticks[1], ax, **xtick_kwargs)
ylocs, ylabels = self.yticks(yticks[0], yticks[1], ax, **ytick_kwargs)
return (xlocs, xlabels), (ylocs, ylabels)
def xlabel(self, label, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
prev_label = ax.get_xlabel()
if not label is None:
ax.set_xlabel(label, **kwargs)
return prev_label
def ylabel(self, label, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
prev_label = ax.get_ylabel()
if not label is None:
ax.set_ylabel(label, **kwargs)
return prev_label
def labels(self, xlabel=None, ylabel=None, ax=None, xlabel_kwargs={}, ylabel_kwargs={}):
prev_xlabel = self.xlabel(xlabel, ax=ax, **xlabel_kwargs)
prev_ylabel = self.ylabel(ylabel, ax=ax, **ylabel_kwargs)
return prev_xlabel, prev_ylabel
def title(self, label=None, fontdict=None, loc="center", y=None, pad=6.0, ax=None):
if ax is None:
ax = plt.gca()
if label is None:
return ax.get_title()
return ax.set_title(label, fontdict=fontdict, loc=loc, y=y, pad=pad)
def style(self, style, ax=None, **kwargs):
if style in plt.style.available:
if ax is None:
plt.style.use(style, **kwargs)
else:
raise ValueError()
else:
if style =="grid":
kwargs = util.merge_dicts({"linestyle": ":"}, kwargs)
if ax is None:
ax = plt.gca()
ax.grid(**kwargs)
else:
raise ValueError()
def legend(self, handles=None, labels=None, ax=None, style="standard", **kwargs):
if style == "center":
kwargs = util.merge_dicts(
{
"loc": "upper center",
"bbox_to_anchor": (0.5, 1.05),
"ncol": 3,
"fancybox": True,
"prop": {"size": 7},
},
kwargs
)
elif style == "standard":
kwargs = util.merge_dicts(
{},
kwargs
)
else:
raise ValueError(style)
# kwargs = util.merge_dicts({"size": 7}, kwargs)
if ax is None:
ax = plt.gca()
if not (handles is None or labels is None):
ax.legend(handles, labels, **kwargs)
elif not handles is None:
ax.legend(handle=handles, **kwargs)
elif not labels is None:
ax.legend(labels, **kwargs)
else:
ax.legend(**kwargs)
def figure(self, size=(8, 8)):
return plt.figure(figsize=size)
def subplots(self, n=1, size=(8, 8)):
return plt.subplots(n, figsize=size)
def save_figure(self, path, dpi=200, fig=None):
if fig is None:
fig = plt
fig.savefig(path, bbox_inches="tight", dpi=dpi)
plt.close()
def show_figure(self):
plt.show()
plt.close()
def close(self):
plt.close()
def plot_learning_curve(self, train, valid, test, path):
plt.plot(train, color="k", label="Training", linewidth=self.line_width)
plt.plot(valid, color="r", label="Validation", linewidth=self.line_width)
plt.plot(test, color="g", label="Testing", linewidth=self.line_width)
plt.axvline(np.argsort(valid)[0], linestyle=":", color="k")
ymax = max(max(train), max(valid), max(test))
bottom, top = plt.ylim()
plt.ylim(bottom=0, top=0.8*ymax)
plt.ylabel("Mean Squared Error")
plt.xlabel("Epoch")
plt.legend()
plt.savefig(path)
plt.close()
# Precondition: predictions and groundtruth have the following shapes
# Yhats.shape=[n_windows, n_temporal_in, n_spatial, n_response]
# groundtruth.shape=[n_windows, n_temporal_in, n_spatial, n_response]
def plot_model_fit(self, Yhat, spatmp, partition, var):
# Unpacke variables
exec_var, plt_var, proc_var = var.execution, var.plotting, var.processing
plt_dir, line_opts, fig_opts = plt_var.get(["plot_dir", "line_options", "figure_options"])
line_kwargs = plt_var.line_kwargs
dataset = exec_var.get("dataset", partition)
n_temporal_in, n_temporal_out = var.mapping.temporal_mapping
n_predictor, n_response = spatmp.misc.get(["n_predictor", "n_response"])
response_features, response_indices = spatmp.misc.get(["response_features", "response_indices"])
n_spatial, spatial_labels, spatial_indices = spatmp.original.get(
["n_spatial", "spatial_labels", "spatial_indices"],
partition
)
# Filter statistics
statistics = spatmp.statistics
if exec_var.principle_data_form == "reduced":
statistics = spatmp.reduced_statistics
mins = spatmp.filter_axis(
statistics.minimums,
[0, 1],
[spatial_indices, response_indices]
)
maxes = spatmp.filter_axis(
statistics.maximums,
[0, 1],
[spatial_indices, response_indices]
)
meds = spatmp.filter_axis(
statistics.medians,
[0, 1],
[spatial_indices, response_indices]
)
means = spatmp.filter_axis(
statistics.means,
[0, 1],
[spatial_indices, response_indices]
)
stddevs = spatmp.filter_axis(
statistics.standard_deviations,
[0, 1],
[spatial_indices, response_indices]
)
# Get groundtruth data (Y, etc) then filter and reformat predictions (Yhat) to match groundtruth
# Pull groundtruth data - response_features Y, temporal_labels, and their periodic_indices
if exec_var.principle_data_form == "original":
Y = spatmp.original.get("response_features", partition)
temporal_labels = spatmp.original.get("temporal_labels", partition)
periodic_indices = spatmp.original.get("periodic_indices", partition)
# Reformat and filter predictions - filter for contiguous outputs then reshape
n_sample, n_temporal_out, n_spatial, n_feature = Yhat.shape
contiguous_window_indices = util.contiguous_window_indices(n_sample, n_temporal_out, 1)
Yhat = Yhat[contiguous_window_indices,:,:,:]
Yhat = np.reshape(Yhat, (-1,) + Yhat.shape[-2:])
elif exec_var.principle_data_form == "reduced":
Y = spatmp.reduced.get("response_features", partition)
temporal_labels = spatmp.reduced.get("temporal_labels", partition)
periodic_indices = spatmp.reduced.get("periodic_indices", partition)
Y, temporal_labels, periodic_indices = Y[0,:,:,:], temporal_labels[0,:], periodic_indices[0,:]
# Reformat and filter predictions - filter for contiguous outputs then reshape
n_channel, n_sample, n_temporal_out, n_spatial, n_feature = Yhat.shape
contiguous_window_indices = util.contiguous_window_indices(n_sample, n_temporal_out, 1)
Yhat = Yhat[0,contiguous_window_indices,:,:,:]
Yhat = np.reshape(Yhat, (-1,) + Yhat.shape[-2:])