1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
|
# -*- coding: utf-8 -*-
"""
Utilities for generating static image and line plots of near-publishable quality
Created on Thu May 05 13:29:12 2020
@author: Gerd Duscher
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import sidpy
import sidpy
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import ipywidgets
from IPython.display import display
import scipy
# import matplotlib.animation as animation
from ..hdf.dtype_utils import is_complex_dtype
if sys.version_info.major == 3:
unicode = str
default_cmap = plt.cm.viridis
class CurveVisualizer(object):
def __init__(self, dset, spectrum_number=0, figure=None, **kwargs):
scale_bar = kwargs.pop('scale_bar', False)
colorbar = kwargs.pop('colorbar', True)
set_title = kwargs.pop('set_title', True)
if not isinstance(dset, sidpy.Dataset):
raise TypeError('dset should be a sidpy.Dataset object')
if dset.data_type.name != 'SPECTRUM':
raise TypeError("sidpy.Dataset should have DataType 'Spectrum' ")
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
if figure is None:
self.fig = plt.figure(**fig_args)
else:
self.fig = figure
self.dset = dset
self.selection = []
self.spectral_dims = []
for dim, axis in dset._axes.items():
if axis.dimension_type == sidpy.DimensionType.SPECTRAL:
self.selection.append(slice(None))
self.spectral_dims.append(dim)
else:
if spectrum_number <= dset.shape[dim]:
self.selection.append(slice(spectrum_number, spectrum_number + 1))
self.spectral_dims.append(dim)
else:
self.spectrum_number = 0
self.selection.append(slice(0, 1))
self.spectral_dims.append(dim)
# Handle the simple cases first:
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
self.dim = self.dset._axes[self.spectral_dims[0]]
if is_complex_dtype(dset.dtype):
# Plot real and imaginary
self.fig, self.axes = plt.subplots(nrows=2, **fig_args)
self.axes[0].plot(self.dim.values, self.dset.squeeze().abs().compute(), **kwargs)
if set_title:
self.axes[0].set_title(self.dset.title + '\n(Magnitude)', pad=15)
self.axes[0].set_xlabel(self.dset.labels[0])
self.axes[0].set_ylabel(self.dset.data_descriptor)
self.axes[0].ticklabel_format(style='sci', scilimits=(-2, 3))
if set_title:
self.axes[1].set_title(self.dset.title + '\n(Phase)', pad=15)
self.axes[1].set_ylabel('Phase (rad)')
self.axes[1].set_xlabel(self.dset.labels[0]) # + x_suffix)
self.axes[1].ticklabel_format(style='sci', scilimits=(-2, 3))
self.fig.tight_layout()
self.fig.canvas.draw_idle()
else:
self.axis = self.fig.add_subplot(1, 1, 1, **fig_args)
self.axis.plot(self.dim.values, self.dset.compute(), **kwargs)
if self.dset.variance is not None:
self.axis.fill_between(self.dim.values,
self.dset.compute()-self.dset.variance,
self.dset.compute()+self.dset.variance,
alpha = 0.3, **kwargs)
if set_title:
self.axis.set_title(self.dset.title, pad=15)
self.axis.set_xlabel(self.dset.labels[self.spectral_dims[0]])
self.axis.set_ylabel(self.dset.data_descriptor)
self.axis.ticklabel_format(style='sci', scilimits=(-2, 3))
self.fig.canvas.draw_idle()
class ImageVisualizer(object):
"""
Interactive display of image plot
The stack can be scrolled through with a mouse wheel or the slider
The usual zoom effects of matplotlib apply.
Works on every backend because it only depends on matplotlib.
Important: keep a reference to this class to maintain interactive properties so usage is:
>>view = plot_stack(dataset, {'spatial':[0,1], 'stack':[2]})
Input:
------
- dset: NSIDask _dataset
- figure: optional
matplotlib figure
- image_number optional
if this is a stack of images we can choose which one we want.
kwargs optional
additional arguments for matplotlib and a boolean value with keyword 'scale_bar'
"""
def __init__(self, dset, figure=None, image_number=0, **kwargs):
"""
plotting of data according to two axis marked as SPATIAL in the dimensions
"""
if not isinstance(dset, sidpy.Dataset):
raise TypeError('dset should be a sidpy.Dataset object')
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
if figure is None:
self.fig = plt.figure(**fig_args)
else:
self.fig = figure
self.dset = dset
self.image_number = image_number
self.selection = []
self.image_dims = []
for dim, axis in dset._axes.items():
if axis.dimension_type in [sidpy.DimensionType.SPATIAL, sidpy.DimensionType.RECIPROCAL]:
self.selection.append(slice(None))
self.image_dims.append(dim)
else:
if image_number <= dset.shape[dim]:
self.selection.append(slice(image_number, image_number + 1))
else:
self.image_number = 0
self.selection.append(slice(0, 1))
if len(self.image_dims) != 2:
raise TypeError('We need two dimensions with dimension_type SPATIAL or RECIPROCAL to plot an image')
if is_complex_dtype(self.dset.dtype):
self.plot_complex_image(**kwargs)
else:
self.axis = self.fig.add_subplot(1, 1, 1)
self.plot_image(**kwargs)
if self.dset.variance is not None:
if self.dset.variance.shape != self.dset.shape:
raise ValueError('Variance array must have the same dimensionality as the dataset')
self._variance_button = ipywidgets.widgets.Dropdown(options=[('z', 1), ('σ', 2), ('z + σ', 3), ('z - σ', 4)],
value=1,
description='Image',
tooltip='What to plot: image data (z), variance of z (σ), etc.',
layout=ipywidgets.Layout(width='20%', height='40px', ))
self._variance_button.observe(self._var_button_event, 'value') # pixel or unit wise
self.fig.canvas.draw_idle()
drop_down_menu = ipywidgets.HBox([self._variance_button])
display(drop_down_menu)
def plot_image(self, **kwargs):
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
scale_bar = kwargs.pop('scale_bar', False)
self.colorbar = kwargs.pop('colorbar', True)
set_title = kwargs.pop('set_title', True)
rgb = False
if set_title:
self.axis.set_title(self.dset.title)
if len(self.dset.shape) > 2:
if self.dset.shape[2] > 4:
self.axis.set_title(self.dset.title + '_image {}'.format(self.image_number))
else:
rgb = True
if rgb:
self.img = self.axis.imshow(self.dset, extent=self.dset.get_extent(self.image_dims), **kwargs)
else:
self.img = self.axis.imshow(self.dset[tuple(self.selection)].squeeze().T,
extent=self.dset.get_extent(self.image_dims), **kwargs)
self.axis.set_xlabel(self.dset.labels[self.image_dims[0]])
self.axis.set_ylabel(self.dset.labels[self.image_dims[1]])
if scale_bar:
plt.axis('off')
extent = self.dset.get_extent(self.image_dims)
size_of_bar = int((extent[1] - extent[0]) / 10 + .5)
if size_of_bar < 1:
size_of_bar = 1
scalebar = AnchoredSizeBar(plt.gca().transData,
size_of_bar, '{} {}'.format(size_of_bar,
self.dset._axes[self.image_dims[0]].units),
'lower left',
pad=1,
color='white',
frameon=False,
size_vertical=.2)
plt.gca().add_artist(scalebar)
if self.colorbar:
cbar = self.fig.colorbar(self.img)
cbar.set_label(self.dset.data_descriptor)
self.axis.ticklabel_format(style='sci', scilimits=(-2, 3))
self.fig.tight_layout()
self.img.axes.figure.canvas.draw_idle()
def plot_complex_image(self, **kwargs):
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
scale_bar = kwargs.pop('scale_bar', False)
self.colorbar = kwargs.pop('colorbar', True)
self.axes = []
# magnitude
self.axes.append(self.fig.add_subplot(121))
self.img = self.axes[0].imshow(self.dset[tuple(self.selection)].abs().squeeze().T,
extent=self.dset.get_extent(self.image_dims), **kwargs)
self.axes[0].set_xlabel(self.dset.labels[self.image_dims[0]])
self.axes[0].set_ylabel(self.dset.labels[self.image_dims[1]])
self.axes[0].set_title(self.dset.title + '\n(Magnitude)', pad=15)
if self.colorbar:
cbar = self.fig.colorbar(self.img)
cbar.set_label("{} [{}]".format(self.dset.quantity, self.dset.units))
self.axes[0].ticklabel_format(style='sci', scilimits=(-2, 3))
# phase
self.axes.append(self.fig.add_subplot(122, sharex=self.axes[0], sharey=self.axes[0]))
self.img_c = self.axes[1].imshow(self.dset[tuple(self.selection)].squeeze().angle().T,
extent=self.dset.get_extent(self.image_dims), **kwargs)
self.axes[1].set_xlabel(self.dset.labels[self.image_dims[0]])
self.axes[1].set_ylabel(self.dset.labels[self.image_dims[1]])
self.axes[1].set_title(self.dset.title + '\n(Phase)', pad=15)
if self.colorbar:
cbar_c = self.fig.colorbar(self.img_c)
cbar_c.set_label(self.dset.data_descriptor)
self.axes[1].ticklabel_format(style='sci', scilimits=(-2, 3))
if scale_bar:
for ax in self.axes:
ax.axis('off')
extent = self.dset.get_extent(self.image_dims)
size_of_bar = int((extent[1] - extent[0]) / 10 + .5)
if size_of_bar < 1:
size_of_bar = 1
scalebar = AnchoredSizeBar(ax.transData,
size_of_bar, '{} {}'.format(size_of_bar,
self.dset._axes[self.image_dims[0]].units),
'lower left',
pad=1,
color='white',
frameon=False,
size_vertical=.2)
ax.add_artist(scalebar)
self.fig.tight_layout()
def _var_button_event(self, event):
disp = event.new
self._update_image(disp)
def _update_image(self, event_value, **kwargs):
_data = {1: self.dset[tuple(self.selection)].squeeze().T,
2: self.dset.variance[tuple(self.selection)].squeeze().T,
3: self.dset.variance[tuple(self.selection)].squeeze().T + self.dset[tuple(self.selection)].squeeze().T,
4: self.dset[tuple(self.selection)].squeeze().T - self.dset.variance[tuple(self.selection)].squeeze().T}
if is_complex_dtype(self.dset.dtype):
_dat = np.array(_data[event_value] + 0*1j)
self.img.set_data(np.abs(_dat))
self.img.set_clim(np.abs(_dat).min(), np.abs(_dat).max())
self.img_c.set_data(np.angle(_dat))
self.img_c.set_clim(np.angle(_dat).min(), np.angle(_dat).max())
else:
self.img.set_data(_data[event_value])
self.img.set_clim(_data[event_value].min(), _data[event_value].max())
class ImageStackVisualizer(object):
"""
Interactive display of image stack plot
The stack can be scrolled through with a mouse wheel or the slider
The usual zoom effects of matplotlib apply.
Works on every backend because it only depends on matplotlib.
Important: keep a reference to this class to maintain interactive properties so usage is:
>>kwargs = {'scale_bar': True, 'cmap': 'hot'}
>>view = ImageStackVisualizer(dataset, **kwargs )
Input:
------
- dset: sidpy Dataset
- figure: optional
matplotlib figure
- kwargs: optional
matplotlib additional arguments like {cmap: 'hot'}
"""
def __init__(self, dset, figure=None, **kwargs):
if not isinstance(dset, sidpy.Dataset):
raise TypeError('dset should be a sidpy.Dataset object')
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
self.set_title = kwargs.pop('set_title', True)
if figure is None:
self.fig = plt.figure(**fig_args)
else:
self.fig = figure
if dset.ndim < 3:
raise TypeError('dataset must have at least three dimensions')
self.stack_dim = -1
self.image_dims = []
self.selection = []
for dim, axis in dset._axes.items():
if axis.dimension_type in [sidpy.DimensionType.SPATIAL, sidpy.DimensionType.RECIPROCAL]:
self.selection.append(slice(None))
self.image_dims.append(dim)
elif axis.dimension_type == sidpy.DimensionType.TEMPORAL or len(dset) == 3:
self.selection.append(slice(0, 1))
self.stack_dim = dim
else:
self.selection.append(slice(0, 1))
if len(self.image_dims) != 2:
raise TypeError('We need two dimensions with dimension_type spatial to plot an image')
if self.stack_dim < 0:
raise TypeError('We need one dimensions with dimension_type stack, time or frame')
if len(self.image_dims) < 2:
raise TypeError('Two SPATIAL dimension are necessary for this plot')
self.dset = dset
# self.axis = self.fig.add_axes([0.0, 0.2, .9, .7])
self.ind = 0
self.plot_fit_labels = False
self.number_of_slices = self.dset.shape[self.stack_dim]
if self.set_title:
if 'fit_dataset' in dir(dset):
if dset.fit_dataset:
if dset.metadata['fit_parms_dict']['fit_parameters_labels'] is not None:
self.plot_fit_labels = True
img_titles = dset.metadata['fit_parms_dict']['fit_parameters_labels']
self.image_titles = ['Fitting Parm: ' + img_titles[k] for k in range(len(img_titles))]
else:
self.image_titles = 'Fitting Maps: ' + dset.title + '\n use scroll wheel to navigate images'
else:
self.image_titles = 'Fitting Maps: ' + dset.title + '\n use scroll wheel to navigate images'
else:
self.image_titles = 'Image stack: ' + dset.title + '\n use scroll wheel to navigate images'
self.axis = None
self.plot_image(**kwargs)
self.axis = plt.gca()
# self.axis.set_title(image_titles)
self.img.axes.figure.canvas.mpl_connect('scroll_event', self._onscroll)
self.play = ipywidgets.Play(value=0,
min=0,
max=self.number_of_slices,
step=1,
interval=500,
description="Press play",
disabled=False)
self.slider = ipywidgets.IntSlider(value=0,
min=0,
max=self.number_of_slices,
continuous_update=False,
description="Frame:")
# set the slider function
ipywidgets.interactive(self._update, frame=self.slider)
# link slider and play function
ipywidgets.jslink((self.play, 'value'), (self.slider, 'value'))
# We add a button to average the images
self.button = ipywidgets.widgets.ToggleButton(value=False,
description='Average',
disabled=False,
button_style='',
tooltip='Average Images of Stack')
self.average = False
self.button.observe(self._average_slices, 'value')
if self.dset.variance is not None:
if self.dset.variance.shape != self.dset.shape:
raise ValueError('Variance array must have the same dimensionality as the dataset')
self._variance_button = ipywidgets.widgets.Dropdown(options=[('z', 1), ('σ', 2), ('z + σ', 3), ('z - σ', 4)],
value=1,
tooltip='What to plot: image data (z), variance of z (σ), etc.',)
self._variance_button.observe(self._var_button_event, 'value')
widg0 = ipywidgets.HBox([self.play, self.slider])
widg1 = ipywidgets.HBox([self.button, self._variance_button])
widg = ipywidgets.VBox([widg0, widg1])
self.display = 1 # 0 - without var, 1 z, 2 sigma, 3 z-sigma, 4 z+sigma
else:
widg = ipywidgets.HBox([self.play, self.slider, self.button])
self.display = 0
display(widg)
# self.anim = animation.FuncAnimation(self.fig, self._updatefig, interval=200, blit=False, repeat=True)
self._update()
def plot_image(self, **kwargs):
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
scale_bar = kwargs.pop('scale_bar', False)
colorbar = kwargs.pop('colorbar', True)
self.axis = plt.gca()
if self.set_title:
self.axis.set_title(self.dset.title)
self.img = self.axis.imshow(self.dset[tuple(self.selection)].squeeze().T,
extent=self.dset.get_extent(self.image_dims), **kwargs)
self.axis.set_xlabel(self.dset.labels[self.image_dims[0]])
self.axis.set_ylabel(self.dset.labels[self.image_dims[1]])
if scale_bar:
plt.axis('off')
extent = self.dset.get_extent(self.image_dims)
size_of_bar = int((extent[1] - extent[0]) / 10 + .5)
if size_of_bar < 1:
size_of_bar = 1
scalebar = AnchoredSizeBar(plt.gca().transData,
size_of_bar, '{} {}'.format(size_of_bar,
self.dset._axes[self.image_dims[0]].units),
'lower left',
pad=1,
color='white',
frameon=False,
size_vertical=.2)
plt.gca().add_artist(scalebar)
if colorbar:
cbar = self.fig.colorbar(self.img)
cbar.set_label(self.dset.data_descriptor)
self.axis.ticklabel_format(style='sci', scilimits=(-2, 3))
self.fig.tight_layout()
self.img.axes.figure.canvas.draw_idle()
def _average_slices(self, event):
self.average = event.new
self._update(self.ind)
# if event.new:
# if len(self.dset.shape) == 3:
# image_stack = self.dset
# else:
# stack_selection = self.selection.copy()
# stack_selection[self.stack_dim] = slice(None)
# image_stack = self.dset[stack_selection].squeeze()
#
# self.img.set_data(image_stack.mean(axis=self.stack_dim).T)
# self.fig.canvas.draw_idle()
# elif event.old:
# self.ind = self.ind % self.number_of_slices
# self._update(self.ind)
def _onscroll(self, event):
if event.button == 'up':
self.slider.value = (self.slider.value + 1) % self.number_of_slices
else:
self.slider.value = (self.slider.value - 1) % self.number_of_slices
self.ind = int(self.slider.value)
def _var_button_event(self, event):
self.display = event.new
self._update(self.ind)
def _update(self, frame=0):
if self.display == 2:
_dset = self.dset.variance
elif self.display == 3:
_dset = self.dset + self.dset.variance
elif self.display == 4:
_dset = self.dset - self.dset.variance
else:
_dset = self.dset
if self.average:
if len(self.dset.shape) == 3:
image_stack = _dset
else:
stack_selection = self.selection.copy()
stack_selection[self.stack_dim] = slice(None)
image_stack = self.dset[stack_selection].squeeze()
self.img.set_data(image_stack.mean(axis=self.stack_dim).T)
self.fig.canvas.draw_idle()
else:
self.ind = frame
self.selection[self.stack_dim] = slice(frame, frame + 1)
self.img.set_data((_dset[tuple(self.selection)].squeeze()).T)
self.img.set_clim(_dset[tuple(self.selection)].min(), _dset[tuple(self.selection)].max())
self.img.axes.figure.canvas.draw_idle()
if self.plot_fit_labels:
self.axis.set_title(self.image_titles[frame])
else:
self.axis.set_title(self.image_titles)
class SpectralImageVisualizerBase(object):
"""
### Interactive spectrum imaging plot
If there is a 4D dataset, and one of them is named 'channel',
then you can plot the channel spectra too
"""
def __init__(self, dset, figure=None, horizontal=True, **kwargs):
if not isinstance(dset, sidpy.Dataset):
raise TypeError('dset should be a sidpy.Dataset object')
scale_bar = kwargs.pop('scale_bar', False)
colorbar = kwargs.pop('colorbar', True)
self.set_title = kwargs.pop('set_title', True)
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
if figure is None:
self.fig = plt.figure(**fig_args)
else:
self.fig = figure
self.image_dims = []
self.energy_axis = []
self.channel_axis = []
self.dset = dset
self.verify_dataset()
self.horizontal = horizontal
self.x = 0
self.y = 0
self.bin_x = 1
self.bin_y = 1
self.set_dataset()
if horizontal:
self.axes = self.fig.subplots(ncols=2)
else:
self.axes = self.fig.subplots(nrows=2, **fig_args)
if self.set_title:
self.fig.canvas.manager.set_window_title(self.dset.title)
self.set_image(**kwargs)
self.set_spectrum()
self.fig.tight_layout()
self.cid = self.axes[1].figure.canvas.mpl_connect('button_press_event', self._onclick)
self.fig.canvas.draw_idle()
def verify_dataset(self):
dset = self.dset
if len(dset.shape) < 3:
raise TypeError('dataset must have at least three dimensions')
if len(dset.shape) > 4:
raise TypeError('dataset must have at most four dimensions')
# We need one stack dim and two image dimes as lists in dictionary
selection = []
image_dims = []
spectral_dim = []
channel_dim = []
for dim, axis in dset._axes.items():
if axis.dimension_type in [sidpy.DimensionType.SPATIAL, sidpy.DimensionType.RECIPROCAL]:
selection.append(slice(None))
image_dims.append(dim)
elif axis.dimension_type == sidpy.DimensionType.SPECTRAL:
selection.append(slice(0, 1))
spectral_dim.append(dim)
elif axis.dimension_type == sidpy.DimensionType.CHANNEL:
channel_dim.append(dim)
else:
selection.append(slice(0, 1))
if len(image_dims) != 2:
raise TypeError('We need two dimensions with dimension_type SPATIAL: to plot an image')
if len(channel_dim) >1:
raise ValueError("We have more than one Channel Dimension, this won't work for the visualizer")
if len(spectral_dim)>1:
raise ValueError("We have more than one Spectral Dimension, this won't work for the visualizer...")
if self.dset.variance is not None:
if self.dset.variance.shape != self.dset.shape:
raise ValueError('Variance array must have the same dimensionality as the dataset')
if len(dset.shape) == 4:
if len(channel_dim) != 1:
raise TypeError("We need one dimension with type CHANNEL \
for a spectral image plot for a 4D dataset")
elif len(dset.shape)==3:
if len(spectral_dim) != 1:
raise TypeError("We need one dimension with dimension_type SPECTRAL \
to plot a spectra for a 3D dataset")
self.image_dims = image_dims
self.energy_axis = spectral_dim[0]
if len(channel_dim)>0:
self.channel_axis = channel_dim
return True
def set_dataset(self):
size_x = self.dset.shape[self.image_dims[0]]
size_y = self.dset.shape[self.image_dims[1]]
self.energy_scale = self.dset._axes[self.energy_axis].values
self.extent = [0, size_x, size_y, 0]
self.rectangle = [0, size_x, 0, size_y]
self.scaleX = 1.0
self.scaleY = 1.0
self.analysis = []
self.plot_legend = False
self.extent_rd = self.dset.get_extent(self.image_dims)
def set_image(self, **kwargs):
if len(self.channel_axis)>0:
self.image = self.dset.mean(axis=(self.energy_axis,self.channel_axis[0]))
else:
self.image = self.dset.mean(axis=(self.energy_axis))
self.axes[0].imshow(self.image.T, extent=self.extent, **kwargs)
if 1 in self.dset.shape:
self.axes[0].set_aspect('auto')
self.axes[0].get_yaxis().set_visible(False)
else:
self.axes[0].set_aspect('equal')
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5))
self.axes[0].set_xticklabels(np.round(np.linspace(self.extent[0], self.extent[1], 5),2))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5))
self.axes[0].set_yticklabels(np.round(np.linspace(self.extent[2], self.extent[3], 5),1))
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
'px'))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
'px'))
self.rect = patches.Rectangle((0, 0), self.bin_x, self.bin_y, linewidth=1, edgecolor='r',
facecolor='red', alpha=0.2)
self.axes[0].add_patch(self.rect)
def set_spectrum(self):
self.intensity_scale = 1.
self.spectrum = self.get_spectrum()
if len(self.energy_scale)!=self.spectrum.shape[0]:
self.spectrum = self.spectrum.T
self.axes[1].plot(self.energy_scale, self.spectrum.compute())
# add variance shadow graph
if self.variance is not None:
#3d - many curves
if len(self.variance.shape) > 1:
for i in range(len(self.variance)):
self.axes[1].fill_between(self.energy_scale,
self.spectrum.compute().T[i] - self.variance[i],
self.spectrum.compute().T[i] + self.variance[i],
alpha=0.3) # , **kwargs)
# 2d - one curve at each point
else:
self.axes[1].fill_between(self.energy_scale,
self.spectrum.compute() - self.variance,
self.spectrum.compute() + self.variance,
alpha=0.3) # , **self.kwargs)
self.axes[1].set_title('spectrum {}, {}'.format(self.x, self.y))
self.xlabel = self.dset.labels[self.energy_axis]
self.ylabel = self.dset.data_descriptor
self.axes[1].set_xlabel(self.dset.labels[self.energy_axis]) # + x_suffix)
self.axes[1].set_ylabel(self.dset.data_descriptor)
self.axes[1].ticklabel_format(style='sci', scilimits=(-2, 3))
self.fig.tight_layout()
self.cid = self.axes[1].figure.canvas.mpl_connect('button_press_event', self._onclick)
self.button = ipywidgets.widgets.Dropdown( options=[('Pixel Wise', 1), ('Units Wise', 2)],
value=1,
description='Image',
tooltip='How to plot spatial data: Pixel Wise (by px), Units wise (in given units)',
layout = ipywidgets.Layout(width='30%', height='50px',))
self.button.observe(self._pw_uw, 'value') #pixel or unit wise
self.fig.canvas.draw_idle()
widg = ipywidgets.HBox([self.button])
display(widg)
def _update_image(self, event_value):
#pixel wise or unit wise listener
if event_value==1:
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5))
self.axes[0].set_xticklabels(np.round(np.linspace(self.extent[0], self.extent[1], 5),2))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5))
self.axes[0].set_yticklabels(np.round(np.linspace(self.extent[2], self.extent[3], 5),2))
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
'px'))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
'px'))
else:
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
self.dset._axes[self.image_dims[0]].units))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
self.dset._axes[self.image_dims[1]].units))
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5),)
self.axes[0].set_xticklabels(np.round(np.linspace(self.extent_rd[0], self.extent_rd[1], 5), 2))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5),)
self.axes[0].set_yticklabels(np.round(np.linspace(self.extent_rd[2], self.extent_rd[3], 5), 2))
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
self.dset._axes[self.image_dims[0]].units))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
self.dset._axes[self.image_dims[1]].units))
if self.dset._axes[self.image_dims[0]].units =='m':
scaled_values_y = self.dset._axes[self.image_dims[1]].values*1E9
scaled_values_x = self.dset._axes[self.image_dims[0]].values*1E9
if scaled_values_x.mean() >=0.1 and scaled_values_x.mean() <=1000:
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5),)
self.axes[0].set_xticklabels(np.round(np.linspace(scaled_values_x[0], scaled_values_x[-1], 5), 2))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5),)
self.axes[0].set_yticklabels(np.round(np.linspace(scaled_values_y[0], scaled_values_y[-1], 5), 2))
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
'nm'))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
'nm'))
return
def set_bin(self, bin_xy):
old_bin_x = self.bin_x
old_bin_y = self.bin_y
if isinstance(bin_xy, list):
self.bin_x = int(bin_xy[0])
self.bin_y = int(bin_xy[1])
else:
self.bin_x = int(bin_xy)
self.bin_y = int(bin_xy)
if self.bin_x > self.dset.shape[self.image_dims[0]]:
self.bin_x = self.dset.shape[self.image_dims[0]]
if self.bin_y > self.dset.shape[self.image_dims[1]]:
self.bin_y = self.dset.shape[self.image_dims[1]]
self.rect.set_width(self.rect.get_width() * self.bin_x / old_bin_x)
self.rect.set_height((self.rect.get_height() * self.bin_y / old_bin_y))
if self.x + self.bin_x > self.dset.shape[self.image_dims[0]]:
self.x = self.dset.shape[0] - self.bin_x
if self.y + self.bin_y > self.dset.shape[self.image_dims[1]]:
self.y = self.dset.shape[1] - self.bin_y
self.rect.set_xy([self.x * self.rect.get_width() / self.bin_x + self.rectangle[0],
self.y * self.rect.get_height() / self.bin_y + self.rectangle[2]])
self._update()
def get_spectrum(self):
if self.x > self.dset.shape[self.image_dims[0]] - self.bin_x:
self.x = self.dset.shape[self.image_dims[0]] - self.bin_x
if self.y > self.dset.shape[self.image_dims[1]] - self.bin_y:
self.y = self.dset.shape[self.image_dims[1]] - self.bin_y
selection = []
for dim, axis in self.dset._axes.items():
if axis.dimension_type == sidpy.DimensionType.SPATIAL:
if dim == self.image_dims[0]:
selection.append(slice(self.x, self.x + self.bin_x))
else:
selection.append(slice(self.y, self.y + self.bin_y))
elif axis.dimension_type == sidpy.DimensionType.SPECTRAL:
selection.append(slice(None))
elif axis.dimension_type == sidpy.DimensionType.CHANNEL:
selection.append(slice(None))
else:
selection.append(slice(0, 1))
self.spectrum = self.dset[tuple(selection)].mean(axis=tuple(self.image_dims))
if self.dset.variance is not None:
self.variance = self.dset.variance[tuple(selection)].mean(axis=tuple(self.image_dims))
else:
self.variance = None
# * self.intensity_scale[self.x,self.y]
return self.spectrum.squeeze()
def _onclick(self, event):
self.event = event
if event.inaxes in [self.axes[0]]:
x = int(event.xdata)
y = int(event.ydata)
x = int(x - self.rectangle[0])
y = int(y - self.rectangle[2])
if x >= 0 and y >= 0:
if x <= self.rectangle[1] and y <= self.rectangle[3]:
self.x = int(x / (self.rect.get_width() / self.bin_x))
self.y = int(y / (self.rect.get_height() / self.bin_y))
if self.x + self.bin_x > self.dset.shape[self.image_dims[0]]:
self.x = self.dset.shape[self.image_dims[0]] - self.bin_x
if self.y + self.bin_y > self.dset.shape[self.image_dims[1]]:
self.y = self.dset.shape[self.image_dims[1]] - self.bin_y
self.rect.set_xy([self.x * self.rect.get_width() / self.bin_x + self.rectangle[0],
self.y * self.rect.get_height() / self.bin_y + self.rectangle[2]])
self._update()
else:
if event.dblclick:
bottom = float(self.spectrum.min())
if bottom < 0:
bottom *= 1.02
else:
bottom *= 0.98
top = float(self.spectrum.max())
if top > 0:
top *= 1.02
else:
top *= 0.98
self.axes[1].set_ylim(bottom=bottom, top=top)
def _update(self, ev=None):
xlim = self.axes[1].get_xlim()
ylim = self.axes[1].get_ylim()
self.axes[1].clear()
self.get_spectrum()
if len(self.energy_scale)!=self.spectrum.shape[0]:
self.spectrum = self.spectrum.T
self.axes[1].plot(self.energy_scale, self.spectrum.compute(), label='experiment')
if self.dset.variance is not None:
#3d - many curves
if len(self.variance.shape) > 1:
for i in range(len(self.variance)):
self.axes[1].fill_between(self.energy_scale,
self.spectrum.compute().T[i] - self.variance[i],
self.spectrum.compute().T[i] + self.variance[i],
alpha=0.3)
# 2d - one curve at each point
else:
self.axes[1].fill_between(self.energy_scale,
self.spectrum.compute() - self.variance,
self.spectrum.compute() + self.variance,
alpha=0.3)
self.axes[1].set_title('spectrum {}, {}'.format(self.x, self.y))
self.axes[1].set_xlim(xlim)
#self.axes[1].set_ylim(ylim)
self.axes[1].set_xlabel(self.xlabel)
self.axes[1].set_ylabel(self.ylabel)
self.fig.canvas.draw_idle()
def set_legend(self, set_legend):
self.plot_legend = set_legend
def get_xy(self):
return [self.x, self.y]
@staticmethod
def _closest_point(array_coord, point):
diff = array_coord - point
return np.argmin(diff[:,0]**2 + diff[:,1]**2)
class SpectralImageVisualizer(SpectralImageVisualizerBase):
def __init__(self, dset, figure=None, horizontal=True, **kwargs):
super().__init__(dset, figure, horizontal, **kwargs)
self.button = ipywidgets.widgets.Dropdown( options=[('Pixel Wise', 1), ('Units Wise', 2)],
value=1,
description='Image',
tooltip='How to plot spatial data: Pixel Wise (by px), Units wise (in given units)',
layout = ipywidgets.Layout(width='30%', height='50px',))
self.button.observe(self._pw_uw, 'value') #pixel or unit wise
def _pw_uw(self, event):
pw_uw = event.new
self.update_image(pw_uw)
def update_image(self, event_value):
#pixel wise or unit wise listener
if event_value==1:
self.axes[0].xaxis.set_ticks(ticks=list(np.linspace(self.extent[0], self.extent[1], 5)),
labels=list(np.round(np.linspace(self.extent[0], self.extent[1], 5),2)))
self.axes[0].yaxis.set_ticks(list(np.linspace(self.extent[2], self.extent[3], 5)),
list(np.round(np.linspace(self.extent[2], self.extent[3], 5),1)))
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
'px'))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
'px'))
else:
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
self.dset._axes[self.image_dims[0]].units))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
self.dset._axes[self.image_dims[1]].units))
self.axes[0].xaxis.set_ticks(np.linspace(self.extent[0], self.extent[1], 5),
list(np.round(np.linspace(self.extent_rd[0], self.extent_rd[1], 5), 2)),
minor=False)
self.axes[0].yaxis.set_ticks(np.linspace(self.extent[2], self.extent[3], 5),
list(np.round(np.linspace(self.extent_rd[2], self.extent_rd[3], 5), 2)),
minor=False)
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
self.dset._axes[self.image_dims[0]].units))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
self.dset._axes[self.image_dims[1]].units))
if self.dset._axes[self.image_dims[0]].units =='m':
scaled_values_y = self.dset._axes[self.image_dims[1]].values*1E9
scaled_values_x = self.dset._axes[self.image_dims[0]].values*1E9
if scaled_values_x.mean() >=0.1 and scaled_values_x.mean() <=1000:
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5),
list(np.round(np.linspace(scaled_values_x[0], scaled_values_x[-1], 5), 2)))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5),
list(np.round(np.linspace(scaled_values_y[0], scaled_values_y[-1], 5), 2)))
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[self.image_dims[0]].quantity,
'nm'))
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[self.image_dims[1]].quantity,
'nm'))
return
class PointCloudVisualizer(object):
"""
Interactive point cloud visualization
"""
def __init__(self, dset, base_image = None, figure=None, horizontal=True, **kwargs):
if not isinstance(dset, sidpy.Dataset):
raise TypeError('dset should be a sidpy.Dataset object')
self.dset = dset
if self.dset.variance is not None:
if self.dset.variance.shape != self.dset.shape:
raise ValueError('Variance array must have the same dimensionality as the dataset')
#kwargs parsing
scale_bar = kwargs.pop('scale_bar', False)
self.set_title = kwargs.pop('set_title', True)
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
#initial checks
if len(dset.shape) < 2:
raise TypeError('dataset must have at least two dimensions')
if len(dset.shape) > 3:
raise TypeError('dataset must have at most tree dimensions')
if dset.point_cloud is None:
raise TypeError(r'''must contain dataset.point_cloud attribute''')
selection = []
point_dims = []
spectral_dim = []
channel_dim = []
for dim, axis in dset._axes.items():
if axis.dimension_type == sidpy.DimensionType.POINT_CLOUD:
selection.append(slice(None))
point_dims.append(dim)
elif axis.dimension_type == sidpy.DimensionType.SPECTRAL:
selection.append(slice(0, 1))
spectral_dim.append(dim)
elif axis.dimension_type == sidpy.DimensionType.CHANNEL:
channel_dim.append(dim)
else:
selection.append(slice(0, 1))
#checking dimension types
if len(channel_dim) >1:
raise ValueError("We have more than one Channel Dimension, this won't work for the visualizer")
if len(spectral_dim)>1:
raise ValueError("We have more than one Spectral Dimension, this won't work for the visualizer...")
if len(dset.shape)==3:
if len(channel_dim)!=1:
raise TypeError("We need one dimension with type CHANNEL \
for a spectral image plot for a 4D dataset")
elif len(dset.shape)==2:
if len(spectral_dim) != 1:
raise TypeError("We need one dimension with dimension_type SPECTRAL \
to plot a spectra for a 3D dataset")
#figure creation
if figure is None:
self.fig = plt.figure(**fig_args)
else:
self.fig = figure
if horizontal:
self.axes = self.fig.subplots(ncols=2)
else:
self.axes = self.fig.subplots(nrows=2, **fig_args)
if self.set_title:
self.fig.canvas.manager.set_window_title(self.dset.title)
#pull base_image
if base_image is not None:
self.image, self.px_coord = self._base_image(base_image)
else:
if len(channel_dim) > 0:
self.cloud= dset.mean(axis=(spectral_dim[0], channel_dim[0]))
else:
self.cloud = dset.mean(axis=(spectral_dim[0],))
self.image, self.px_coord = self._mask_image()
self.x = 0
self.y = 0
size_x, size_y = self.image.shape
self.extent = [0, size_x, size_y, 0]
self.rectangle = [0, size_x, 0, size_y]
if 'quantity' in self.dset.point_cloud:
_quantity = self.dset.point_cloud['quantity']
if isinstance(_quantity, str):
_quantity = (_quantity, _quantity)
elif not (isinstance(_quantity, list) or isinstance(_quantity, tuple)):
raise ValueError('Quantity in Dataset.point_cloud should be str or list, or tuple.')
else:
_quantity = ('distance', 'distance')
self.axes[0].imshow(self.image.T, extent=self.extent, **kwargs)
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5),)
self.axes[0].set_xticklabels(np.round(np.linspace(self.extent[0], self.extent[1], 5),1))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5),)
self.axes[0].set_yticklabels(np.round(np.linspace(self.extent[2], self.extent[3], 5),1))
self.axes[0].set_xlabel('{} [{}]'.format(_quantity[0], 'px'))
self.axes[0].set_ylabel('{} [{}]'.format(_quantity[1], 'px'))
self.axes[0].scatter(self.px_coord[:,0], self.px_coord[:,1], color='red', s=1)
if scale_bar:
self._scale_bar()
#---spectral part----
#find closest spectrum
#self.tree = cKDTree(self.px_coord)
_point_number = self.tree.query(np.array([self.x, self.y]))[1]
self.sel_point = self.axes[0].scatter(self.px_coord[_point_number, 0], self.px_coord[_point_number, 1],
color='red', s=10, edgecolors='darkred')
self.spectrum, self.variance = self.get_spectrum(_point_number)
self.energy_axis = spectral_dim[0]
if len(channel_dim)>0: self.channel_axis = channel_dim
self.energy_scale = self.dset._axes[self.energy_axis].values
self.spectrum_plot = [] #list is required for the case of several channels
if len(self.spectrum.shape) > 1:
for i in range(len(self.spectrum)):
_spectrum_plot, = self.axes[1].plot(self.energy_scale, self.spectrum.compute()[i])
self.spectrum_plot.append(_spectrum_plot)
else:
_spectrum_plot, = self.axes[1].plot(self.energy_scale, self.spectrum.compute())
self.spectrum_plot.append(_spectrum_plot)
self.fill_between = []
if self.variance is not None:
#3d - many curves
if len(self.variance.shape) > 1:
for i in range(len(self.variance)):
_fill_between = self.axes[1].fill_between(self.energy_scale,
self.spectrum[i] - self.variance[i],
self.spectrum[i] + self.variance[i],
alpha=0.3, **kwargs)
self.fill_between.append(_fill_between)
# 2d - one curve at each point
else:
_fill_between = self.axes[1].fill_between(self.energy_scale,
self.spectrum - self.variance,
self.spectrum + self.variance,
alpha=0.3, **kwargs)
self.fill_between.append(_fill_between)
self.axes[1].set_title('point {}'.format(_point_number))
self.axes[1].set_xlabel(self.dset.labels[self.energy_axis])
self.axes[1].set_ylabel(self.dset.data_descriptor)
self.axes[1].ticklabel_format(style='sci', scilimits=(-2, 3))
self.fig.tight_layout()
self.cid = self.axes[1].figure.canvas.mpl_connect('button_press_event', self._onclick)
self.button = ipywidgets.widgets.Dropdown( options=[('Pixel Wise', 1), ('Units Wise', 2)],
value=1,
descrption='Image',
tooltip='How to plot spatial data: Pixel Wise (by px), Units wise (in given units)',
layout = ipywidgets.Layout(width='30%', height='50px',))
self.button.observe(self._pw_uw, 'value') #pixel or unit wise
self.fig.canvas.draw_idle()
widg = ipywidgets.HBox([self.button])
display(widg)
def _pw_uw(self, event):
pw_uw = event.new
self._update_image(pw_uw)
def _update_image(self, event_value):
# pixel wise or unit wise listener
if 'spacial_units' in self.dset.point_cloud:
_sp_units = self.dset.point_cloud['spacial_units']
if isinstance(_sp_units, str):
_sp_units = (_sp_units, _sp_units)
elif not (isinstance(_sp_units, list) or isinstance(_sp_units, tuple)):
raise ValueError('Spacial units in Dataset.point_cloud should be str or list, or tuple.')
if 'quantity' in self.dset.point_cloud:
_quantity = self.dset.point_cloud['quantity']
if isinstance(_quantity, str):
_quantity = (_quantity, _quantity)
elif not (isinstance(_quantity, list) or isinstance(_quantity, tuple)):
raise ValueError('Quantity in Dataset.point_cloud should be str or list, or tuple.')
else:
_quantity = ('distance', 'distance')
if event_value == 1:
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5),)
self.axes[0].set_xticklabels(np.round(np.linspace(self.extent[0], self.extent[1], 5), 1))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5),)
self.axes[0].set_yticklabels(np.round(np.linspace(self.extent[2], self.extent[3], 5), 1))
self.axes[0].set_xlabel('{} [{}]'.format(_quantity[0], 'px'))
self.axes[0].set_ylabel('{} [{}]'.format(_quantity[1], 'px'))
else:
self.axes[0].set_xticks(np.linspace(self.extent[0], self.extent[1], 5),)
self.axes[0].set_xticklabels(np.round(np.linspace(self.real_extent[0], self.real_extent[1], 5), 2))
self.axes[0].set_yticks(np.linspace(self.extent[2], self.extent[3], 5),)
self.axes[0].set_yticklabels(np.round(np.linspace(self.real_extent[2], self.real_extent[3], 5), 2))
if 'spacial_units' in self.dset.point_cloud:
self.axes[0].set_xlabel('{} [{}]'.format(_quantity[0], _sp_units[0]))
self.axes[0].set_ylabel('{} [{}]'.format(_quantity[1], _sp_units[1]))
else:
self.axes[0].set_xlabel('{}'.format(_quantity[0]))
self.axes[0].set_ylabel('{}'.format(_quantity[1]))
def _base_image(self, base_image):
if not isinstance(base_image, sidpy.Dataset):
raise TypeError('base_image should be a sidpy.Dataset object')
if base_image.data_type.value != sidpy.DataType.IMAGE.value:
raise TypeError(f'base_image expected to be IMAGE')
if 'coordinates' in self.dset.point_cloud:
coord = self.dset.point_cloud['coordinates']
else:
raise NotImplementedError('Datasets with data_type POINT_CLOUD must contain coordinates\
in point_cloud attribute')
image_dims = []
selection = []
for dim, axis in base_image._axes.items():
if axis.dimension_type in [sidpy.DimensionType.SPATIAL, sidpy.DimensionType.RECIPROCAL]:
image_dims.append(dim)
selection.append(slice(None))
else:
selection.append(slice(0, 1))
if len(image_dims) != 2:
raise TypeError('We need two dimensions with dimension_type SPATIAL or RECIPROCAL to plot an image')
self.image = base_image[tuple(selection)].squeeze()
im_size = self.image.shape
_x0, _x1, _y1, _y0 = base_image.get_extent(image_dims)
_delta_x = _x1 - _x0
_delta_y = _y1 - _y0
self.real_extent = [_x0, _x1, _y1, _y0]
self.dset.point_cloud['spacial_units'] = (base_image._axes[image_dims[0]].units,
base_image._axes[image_dims[1]].units)
self.dset.point_cloud['quantity'] = (base_image._axes[image_dims[0]].quantity,
base_image._axes[image_dims[1]].quantity)
_px_x = np.array((coord[:,0] - _x0)*im_size[1]/_delta_x).astype(int)
_px_y = np.array((coord[:, 1] - _y0) * im_size[0]/_delta_y).astype(int)
_px_coord = np.array([_px_x, _px_y]).T
self.tree = scipy.spatial.cKDTree(_px_coord)
return self.image, _px_coord
def _scale_bar(self):
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
self.axes[0].axis('off')
extent = self.extent
size_of_bar = int((extent[1] - extent[0]) / 10 + .5)
if 'units' in self.dset.point_cloud:
_units = self.dset.point_cloud['units']
else:
_units = 'px'
if size_of_bar < 1:
size_of_bar = 1
scalebar = AnchoredSizeBar(self.axes[0].transData,
size_of_bar, '{} {}'.format(size_of_bar,
_units),
'lower left',
pad=1,
color='white',
frameon=False,
size_vertical=size_of_bar/5)
self.axes[0].add_artist(scalebar)
def _onclick(self, event):
self.event = event
if event.inaxes in [self.axes[0]]:
self.x = round(event.xdata)
self.y = round(event.ydata)
_point_number = self.tree.query(np.array([self.x, self.y]))[1]
self.spectrum, self.variance = self.get_spectrum(_point_number)
if len(self.spectrum.shape) > 1:
for i in range(len(self.spectrum)):
self.spectrum_plot[i].set_data(self.energy_scale, self.spectrum.compute()[i])
else:
self.spectrum_plot[0].set_data(self.energy_scale, self.spectrum.compute())
if self.variance is not None:
# 3d - many curves
if len(self.variance.shape) > 1:
for i in range(len(self.variance)):
_c = self.fill_between[i].get_facecolor()[0]
self.fill_between[i].remove()
self.fill_between[i] = self.axes[1].fill_between(self.energy_scale,
self.spectrum[i] - self.variance[i],
self.spectrum[i] + self.variance[i],
color= _c)
else:
_c = self.fill_between[0].get_facecolor()[0]
self.fill_between[0].remove()
self.fill_between[0] = self.axes[1].fill_between(self.energy_scale,
self.spectrum - self.variance,
self.spectrum + self.variance,
color=_c)
self.axes[1].set_title('point {}'.format(_point_number))
self.sel_point.set_offsets(np.column_stack((self.px_coord[_point_number, 0],
self.px_coord[_point_number, 1])))
self.fig.canvas.draw_idle()
else:
if event.dblclick:
bottom = float(self.spectrum.min())
if bottom < 0:
bottom *= 1.02
else:
bottom *= 0.98
top = float(self.spectrum.max())
if top > 0:
top *= 1.02
else:
top *= 0.98
self.axes[1].set_ylim(bottom=bottom, top=top)
def get_spectrum(self, point_number):
'''
Getting the spectrum by the point number in the point cloud.
Parameters
----------
point_number: int
Returns
-------
self.spectrum: sidpy.array
'''
selection = []
for dim, axis in self.dset._axes.items():
if axis.dimension_type == sidpy.DimensionType.POINT_CLOUD:
selection.append(point_number)
elif axis.dimension_type == sidpy.DimensionType.SPECTRAL:
selection.append(slice(None))
elif axis.dimension_type == sidpy.DimensionType.CHANNEL:
selection.append(slice(None))
else:
selection.append(slice(0, 1))
self.spectrum = self.dset[tuple(selection)].squeeze()
if self.dset.variance is not None:
self.variance = self.dset.variance[tuple(selection)].squeeze()
else:
self.variance = None
return self.spectrum, self.variance
def _mask_image(self):
'''
Griddata transformation of the unstructured point cloud to the numpy 2D array
Returns
-------
2D np.array - image data
2D np.array - coordinate data
'''
if 'coordinates' in self.dset.point_cloud:
coord = self.dset.point_cloud['coordinates']
else:
raise NotImplementedError('Datasets with data_type POINT_CLOUD must contain coordinates\
in point_cloud attribute')
# minimal image size in 50x50px or equal to the number of point for dimensions
im_size = max(50, coord.shape[0])
_x0, _x1 = np.min(coord, axis=0)[0], np.max(coord, axis=0)[0]
_y0, _y1 = np.min(coord, axis=0)[1], np.max(coord, axis=0)[1]
_delta_x = _x1 - _x0
_delta_y = _y1 - _y0
#to extend filed of view
_x0, _x1 = _x0 - 0.05*_delta_x, _x1 + 0.05*_delta_x
_y0, _y1 = _y0 - 0.05*_delta_y, _y1 + 0.05 * _delta_y
self.real_extent = [_x0, _x1, _y1, _y0]
_px_x = np.array((coord[:,0] - _x0)*im_size/(_x1-_x0)).astype(int)
_px_y = np.array((coord[:, 1] - _y0) * im_size/ (_y1-_y0)).astype(int)
_px_coord = np.array([_px_x, _px_y]).T
self.tree = scipy.spatial.cKDTree(_px_coord)
grid_x, grid_y = np.mgrid[0:im_size, 0:im_size]
mask = scipy.interpolate.griddata(_px_coord, self.cloud, (grid_x, grid_y), method='nearest')
return mask, _px_coord
def get_xy(self):
return [self.x, self.y]
class FourDimImageVisualizer(object):
"""
### Interactive 4D imaging plot
Either you specify only two spatial dimensions or you specify
scan_x and scan_y
image_4d_x, image_4d_y
If none of the keywords are specified, it is assumed that the order is slowest to fastest dimension.
"""
def __init__(self, dset, figure=None, horizontal=True, **kwargs):
if not isinstance(dset, sidpy.Dataset):
raise TypeError('dset should be a sidpy.Dataset object')
scale_bar = kwargs.pop('scale_bar', False)
colorbar = kwargs.pop('colorbar', True)
self.set_title = kwargs.pop('set_title', True)
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
if figure is None:
self.fig = plt.figure(**fig_args)
else:
self.fig = figure
if len(dset.shape) < 4:
raise TypeError('dataset must have at least four dimensions')
# Find scan and 4D_image dimension
scan_x = kwargs.pop('scan_x', None)
scan_y = kwargs.pop('scan_y', None)
image_x = kwargs.pop('image_4d_x', None)
image_y = kwargs.pop('image_4d_y', None)
self.gamma = kwargs.pop('gamma', False)
for dim, axis in dset._axes.items():
if axis.dimension_type in [sidpy.DimensionType.SPATIAL]:
if scan_y is None:
scan_y = dim
elif scan_x is None:
scan_x = dim
# We assume slow scan first order
if scan_y is None or scan_x is None:
scan_y = 0
scan_x = 1
if image_y is None:
for dim in range(4):
if dim not in [scan_x, scan_y]:
image_y = dim
break
if image_x is None:
for dim in range(4):
if dim not in [image_y, scan_x, scan_y]:
image_x = dim
break
image_dims = [scan_x, scan_y]
dims_4d = [image_x, image_y]
if len(image_dims) != 2:
raise TypeError('We need two dimensions with dimension_type SPATIAL: to plot an image')
if len(dims_4d) != 2:
raise TypeError('We need two dimension with dimension_type other than spatial for a 4D image plot')
self.horizontal = horizontal
self.x = 0
self.y = 0
self.bin_x = 1
self.bin_y = 1
image_dims = [scan_x, scan_y]
size_x = dset.shape[image_dims[0]]
size_y = dset.shape[image_dims[1]]
self.dset = dset
self.extent = [0, size_x, size_y, 0]
self.rectangle = [0, size_x, 0, size_y]
self.scaleX = 1.0
self.scaleY = 1.0
self.analysis = []
self.plot_legend = False
self.image_dims = image_dims
self.dims_4d = dims_4d
if is_complex_dtype(dset.dtype):
number_of_plots = 3
else:
number_of_plots = 2
self.number_of_plots = number_of_plots
if horizontal:
self.axes = self.fig.subplots(ncols=number_of_plots)
else:
self.axes = self.fig.subplots(nrows=number_of_plots, **fig_args)
if self.set_title:
self.fig.canvas.manager.set_window_title(self.dset.title)
self.image = np.array(dset).mean(axis=tuple(dims_4d))
if is_complex_dtype(dset.dtype):
self.image = np.abs(np.array(dset)).mean(axis=tuple(dims_4d))
self.axes[0].imshow(self.image.T, extent=self.dset.get_extent(self.image_dims), **kwargs)
#if horizontal:
self.axes[0].set_xlabel('{} [{}]'.format(self.dset._axes[image_dims[0]].quantity,
self.dset._axes[image_dims[0]].units))
#else:
self.axes[0].set_ylabel('{} [{}]'.format(self.dset._axes[image_dims[1]].quantity,
self.dset._axes[image_dims[1]].units))
self.axes[0].set_aspect('equal')
# self.rect = patches.Rectangle((0,0),1,1,linewidth=1,edgecolor='r',facecolor='red', alpha = 0.2)
self.rect = patches.Rectangle((0, 0), self.bin_x, self.bin_y, linewidth=1, edgecolor='r',
facecolor='red', alpha=0.2)
self.axes[0].add_patch(self.rect)
self.intensity_scale = 1.
self.image_4d = self.get_image_4d()
if is_complex_dtype(dset.dtype):
self.image_4d = np.abs(self.image_4d)
if self.gamma:
self.image_4d = np.log(1+self.image_4d)
self.reciprocal_extent = None
if len(self.dset.get_extent(self.dset.get_spectral_dims()))==4:
self.reciprocal_extent = self.dset.get_extent(self.dset.get_spectral_dims())
self.axes[1].imshow(self.image_4d, extent = self.reciprocal_extent)
if self.set_title:
self.axes[1].set_title('set {}, {}'.format(self.x, self.y))
self.xlabel = self.dset.labels[self.dims_4d[0]]
self.ylabel = self.dset.labels[self.dims_4d[1]]
self.axes[1].set_xlabel(self.xlabel) # + x_suffix)
self.axes[1].set_ylabel(self.ylabel)
self.axes[1].ticklabel_format(style='sci', scilimits=(-2, 3))
if is_complex_dtype(dset.dtype):
self.axes[2].imshow(np.angle(np.array(self.image_4d)))
if self.set_title:
self.axes[1].set_title('power {}, {}'.format(self.x, self.y))
self.axes[2].set_title('phase {}, {}'.format(self.x, self.y))
self.axes[2].set_xlabel(self.xlabel) # + x_suffix)
self.axes[2].set_ylabel(self.ylabel)
self.axes[2].ticklabel_format(style='sci', scilimits=(-2, 3))
self.fig.tight_layout()
self.cid = self.axes[1].figure.canvas.mpl_connect('button_press_event', self._onclick)
self.fig.canvas.draw_idle()
def set_bin(self, bin_xy):
old_bin_x = self.bin_x
old_bin_y = self.bin_y
if isinstance(bin_xy, list):
self.bin_x = int(bin_xy[0])
self.bin_y = int(bin_xy[1])
else:
self.bin_x = int(bin_xy)
self.bin_y = int(bin_xy)
if self.bin_x > self.dset.shape[self.image_dims[0]]:
self.bin_x = self.dset.shape[self.image_dims[0]]
if self.bin_y > self.dset.shape[self.image_dims[1]]:
self.bin_y = self.dset.shape[self.image_dims[1]]
self.rect.set_width(self.rect.get_width() * self.bin_x / old_bin_x)
self.rect.set_height((self.rect.get_height() * self.bin_y / old_bin_y))
if self.x + self.bin_x > self.dset.shape[self.image_dims[0]]:
self.x = self.dset.shape[0] - self.bin_x
if self.y + self.bin_y > self.dset.shape[self.image_dims[1]]:
self.y = self.dset.shape[1] - self.bin_y
self.rect.set_xy([self.x * self.rect.get_width() / self.bin_x + self.rectangle[0],
self.y * self.rect.get_height() / self.bin_y + self.rectangle[2]])
self._update()
def get_image_4d(self):
from sidpy import DimensionType
if self.x > self.dset.shape[self.image_dims[0]] - self.bin_x:
self.x = self.dset.shape[self.image_dims[0]] - self.bin_x
if self.y > self.dset.shape[self.image_dims[1]] - self.bin_y:
self.y = self.dset.shape[self.image_dims[1]] - self.bin_y
selection = []
for dim, axis in self.dset._axes.items():
# print(dim, axis.dimension_type)
if dim == self.image_dims[0]:
selection.append(slice(self.x, self.x + self.bin_x))
elif dim == self.image_dims[1]:
selection.append(slice(self.y, self.y + self.bin_y))
elif dim in self.dims_4d:
selection.append(slice(None))
else:
selection.append(slice(0, 1))
self.image_4d = self.dset[tuple(selection)].mean(axis=tuple(self.image_dims))
# * self.intensity_scale[self.x,self.y]
return self.image_4d.squeeze()
def _onclick(self, event):
self.event = event
if event.inaxes in [self.axes[0]]:
x = int(event.xdata)
y = int(event.ydata)
x = int(x - self.rectangle[0])
y = int(y - self.rectangle[2])
if x >= 0 and y >= 0:
if x <= self.rectangle[1] and y <= self.rectangle[3]:
self.x = int(x / (self.rect.get_width() / self.bin_x))
self.y = int(y / (self.rect.get_height() / self.bin_y))
if self.x + self.bin_x > self.dset.shape[self.image_dims[0]]:
self.x = self.dset.shape[self.image_dims[0]] - self.bin_x
if self.y + self.bin_y > self.dset.shape[self.image_dims[1]]:
self.y = self.dset.shape[self.image_dims[1]] - self.bin_y
self.rect.set_xy([self.x * self.rect.get_width() / self.bin_x + self.rectangle[0],
self.y * self.rect.get_height() / self.bin_y + self.rectangle[2]])
self._update()
def _update(self, ev=None):
xlim = self.axes[1].get_xlim()
ylim = self.axes[1].get_ylim()
self.axes[1].clear()
self.get_image_4d()
if is_complex_dtype(self.dset.dtype):
self.axes[2].clear()
self.image_4d = np.abs(self.image_4d)
self.axes[2].imshow(np.angle(self.image_4d))
if self.set_title:
self.axes[1].set_title('power {}, {}'.format(self.x, self.y))
self.axes[2].set_title('phase {}, {}'.format(self.x, self.y))
self.axes[2].set_xlabel(self.xlabel) # + x_suffix)
self.axes[2].set_ylabel(self.ylabel)
self.axes[2].ticklabel_format(style='sci', scilimits=(-2, 3))
else:
if self.set_title:
self.axes[1].set_title('set {}, {}'.format(self.x, self.y))
if self.gamma:
self.image_4d = np.log(1+self.image_4d)
self.axes[1].imshow(self.image_4d,
extent = self.reciprocal_extent)
self.axes[1].set_xlim(xlim)
self.axes[1].set_ylim(ylim)
self.axes[1].set_xlabel(self.xlabel)
self.axes[1].set_ylabel(self.ylabel)
self.fig.canvas.draw_idle()
def set_legend(self, set_legend):
self.plot_legend = set_legend
def get_xy(self):
return [self.x, self.y]
class ComplexSpectralImageVisualizer(object):
"""
### Interactive spectrum imaging plot for Complex Data
## 4D and complex data also works
"""
def __init__(self, dset, figure=None, horizontal=True, **kwargs):
if not isinstance(dset, sidpy.Dataset):
raise TypeError('dset should be a sidpy.Dataset object')
scale_bar = kwargs.pop('scale_bar', False)
colorbar = kwargs.pop('colorbar', True)
self.set_title = kwargs.pop('set_title', True)
fig_args = dict()
temp = kwargs.pop('figsize', None)
if temp is not None:
fig_args['figsize'] = temp
if figure is None:
self.fig = plt.figure(**fig_args)
else:
self.fig = figure
if len(dset.shape) > 4:
raise TypeError('dataset must have four dimensions at max')
if 'complex' not in dset.dtype.name:
raise TypeError('This visualizer is only for Complex Data, data type is {}'.format(dset.dtype))
# We need one stack dim and two image dimes as lists in dictionary
selection = []
image_dims = []
spectral_dim = []
channel_dim = []
for dim, axis in dset._axes.items():
if axis.dimension_type in [sidpy.DimensionType.SPATIAL, sidpy.DimensionType.RECIPROCAL]:
selection.append(slice(None))
image_dims.append(dim)
elif axis.dimension_type == sidpy.DimensionType.SPECTRAL:
selection.append(slice(0, 1))
spectral_dim.append(dim)
elif axis.dimension_type == sidpy.DimensionType.CHANNEL:
channel_dim.append(dim)
else:
selection.append(slice(0, 1))
if len(image_dims) != 2:
raise TypeError('We need two dimensions with dimension_type SPATIAL: to plot an image')
if len(channel_dim) >1:
raise ValueError("We have more than one Channel Dimension, this won't work for the visualizer")
if len(spectral_dim)>1:
raise ValueError("We have more than one Spectral Dimension, this won't work for the visualizer...")
if len(dset.shape)==4:
if len(channel_dim)!=1:
raise TypeError("We need one dimension with type CHANNEL \
for a spectral image plot for a 4D dataset")
elif len(dset.shape)==3:
if len(spectral_dim) != 1:
raise TypeError("We need one dimension with dimension_type SPECTRAL \
to plot a spectra for a 3D dataset")
self.horizontal = horizontal
self.x = 0
self.y = 0
self.bin_x = 1
self.bin_y = 1
size_x = dset.shape[image_dims[0]]
size_y = dset.shape[image_dims[1]]
self.dset = dset
self.energy_axis = spectral_dim[0]
if len(channel_dim)>0: self.channel_axis = channel_dim
self.energy_scale = dset._axes[self.energy_axis].values
self.extent = [0, size_x, size_y, 0]
self.rectangle = [0, size_x, 0, size_y]
self.scaleX = 1.0
self.scaleY = 1.0
self.analysis = []
self.plot_legend = False
self.ri_ap = 'Real and Imaginary' #real/imaginary of amplitude/phase plotting
self.image_dims = image_dims
self.spec_dim = spectral_dim[0]
if horizontal:
self.axes = self.fig.subplots(ncols=3)
else:
self.axes = self.fig.subplots(nrows=3, **fig_args)
if self.set_title:
self.fig.canvas.manager.set_window_title(self.dset.title)
if len(channel_dim)>0:
self.image = dset.mean(axis=(spectral_dim[0],channel_dim[0]))
else:
self.image = dset.mean(axis=(spectral_dim[0]))
if 1 in self.dset.shape:
self.image = dset.squeeze()
self.axes[0].set_aspect('auto')
else:
self.axes[0].set_aspect('equal')
#self.axes[0].imshow(np.abs(self.image.T), extent=self.extent, **kwargs)# throwing an error
self.axes[0].imshow(np.abs(np.array(self.image)).T, extent=self.extent, **kwargs)
if horizontal:
self.axes[0].set_xlabel('{} [pixels]'.format(self.dset._axes[image_dims[0]].quantity))
else:
self.axes[0].set_ylabel('{} [pixels]'.format(self.dset._axes[image_dims[1]].quantity))
if 1 in self.dset.shape:
self.axes[0].set_aspect('auto')
self.axes[0].get_yaxis().set_visible(False)
else:
self.axes[0].set_aspect('equal')
self.rect = patches.Rectangle((0, 0), self.bin_x, self.bin_y, linewidth=1, edgecolor='r',
facecolor='red', alpha=0.2)
self.axes[0].add_patch(self.rect)
self.intensity_scale = 1.
self.spectrum = self.get_spectrum()
if len(self.energy_scale)!=self.spectrum.shape[0]:
self.spectrum = self.spectrum.T
self.axes[1].plot(self.energy_scale, np.real(self.spectrum.compute()), label = 'Real')
self.axes[2].plot(self.energy_scale, np.imag(self.spectrum.compute()), label = 'Imaginary')
for ax_ind in [1,2]:
self.axes[ax_ind].set_title('spectrum {}, {}'.format(self.x, self.y))
self.xlabel = self.dset.labels[self.spec_dim]
self.ylabel = self.dset.data_descriptor
self.axes[ax_ind].set_xlabel(self.dset.labels[self.spec_dim]) # + x_suffix)
self.axes[ax_ind].set_ylabel(self.dset.data_descriptor)
self.axes[ax_ind].ticklabel_format(style='sci', scilimits=(-2, 3))
leg = self.axes[ax_ind].legend(loc = 'best')
leg.get_frame().set_linewidth(0.0)
self.fig.tight_layout()
self.cid = self.axes[1].figure.canvas.mpl_connect('button_press_event', self._onclick)
self.button = ipywidgets.Dropdown(options=['Real and Imaginary', 'Amplitude and Phase'],
description='Plot',
disabled=False,
tooltip='How to plot complex data')
self.button.observe(self._ri_ap, 'value') #real/imag or amp/phase
widg = ipywidgets.HBox([self.button])
display(widg)
self.fig.canvas.draw_idle()
def _ri_ap(self, event):
self.ri_ap = event.new
self._update()
def set_bin(self, bin_xy):
old_bin_x = self.bin_x
old_bin_y = self.bin_y
if isinstance(bin_xy, list):
self.bin_x = int(bin_xy[0])
self.bin_y = int(bin_xy[1])
else:
self.bin_x = int(bin_xy)
self.bin_y = int(bin_xy)
if self.bin_x > self.dset.shape[self.image_dims[0]]:
self.bin_x = self.dset.shape[self.image_dims[0]]
if self.bin_y > self.dset.shape[self.image_dims[1]]:
self.bin_y = self.dset.shape[self.image_dims[1]]
self.rect.set_width(self.rect.get_width() * self.bin_x / old_bin_x)
self.rect.set_height((self.rect.get_height() * self.bin_y / old_bin_y))
if self.x + self.bin_x > self.dset.shape[self.image_dims[0]]:
self.x = self.dset.shape[0] - self.bin_x
if self.y + self.bin_y > self.dset.shape[self.image_dims[1]]:
self.y = self.dset.shape[1] - self.bin_y
self.rect.set_xy([self.x * self.rect.get_width() / self.bin_x + self.rectangle[0],
self.y * self.rect.get_height() / self.bin_y + self.rectangle[2]])
self._update()
def get_spectrum(self):
if self.x > self.dset.shape[self.image_dims[0]] - self.bin_x:
self.x = self.dset.shape[self.image_dims[0]] - self.bin_x
if self.y > self.dset.shape[self.image_dims[1]] - self.bin_y:
self.y = self.dset.shape[self.image_dims[1]] - self.bin_y
selection = []
for dim, axis in self.dset._axes.items():
# print(dim, axis.dimension_type)
if axis.dimension_type == sidpy.DimensionType.SPATIAL:
if dim == self.image_dims[0]:
selection.append(slice(self.x, self.x + self.bin_x))
else:
selection.append(slice(self.y, self.y + self.bin_y))
elif axis.dimension_type == sidpy.DimensionType.SPECTRAL:
selection.append(slice(None))
elif axis.dimension_type == sidpy.DimensionType.CHANNEL:
selection.append(slice(None))
else:
selection.append(slice(0, 1))
self.spectrum = self.dset[tuple(selection)].mean(axis=tuple(self.image_dims))
# * self.intensity_scale[self.x,self.y]
return self.spectrum.squeeze()
def _onclick(self, event):
self.event = event
if event.inaxes in [self.axes[0]]:
x = int(event.xdata)
y = int(event.ydata)
x = int(x - self.rectangle[0])
y = int(y - self.rectangle[2])
if x >= 0 and y >= 0:
if x <= self.rectangle[1] and y <= self.rectangle[3]:
self.x = int(x / (self.rect.get_width() / self.bin_x))
self.y = int(y / (self.rect.get_height() / self.bin_y))
if self.x + self.bin_x > self.dset.shape[self.image_dims[0]]:
self.x = self.dset.shape[self.image_dims[0]] - self.bin_x
if self.y + self.bin_y > self.dset.shape[self.image_dims[1]]:
self.y = self.dset.shape[self.image_dims[1]] - self.bin_y
self.rect.set_xy([self.x * self.rect.get_width() / self.bin_x + self.rectangle[0],
self.y * self.rect.get_height() / self.bin_y + self.rectangle[2]])
self._update()
else:
if event.dblclick:
bottom = float(self.spectrum.min())
if bottom < 0:
bottom *= 1.02
else:
bottom *= 0.98
top = float(self.spectrum.max())
if top > 0:
top *= 1.02
else:
top *= 0.98
self.axes[1].set_ylim(bottom=bottom, top=top)
def _update(self, ev=None):
xlim_ax1 = self.axes[1].get_xlim()
ylim_ax1 = self.axes[1].get_ylim()
xlim_ax2 = self.axes[2].get_xlim()
ylim_ax2 = self.axes[2].get_ylim()
xlims = [xlim_ax1,xlim_ax2]
ylims = [ylim_ax1, ylim_ax2]
self.axes[1].clear()
self.axes[2].clear()
self.get_spectrum()
if len(self.energy_scale)!=self.spectrum.shape[0]:
self.spectrum = self.spectrum
if self.ri_ap == 'Real and Imaginary':
self.axes[1].plot(self.energy_scale, np.real(self.spectrum.compute()), label='Real')
self.axes[2].plot(self.energy_scale, np.imag(self.spectrum.compute()), label='Imaginary')
else:
self.axes[1].plot(self.energy_scale, np.abs(self.spectrum.compute()), label='Amplitude')
self.axes[2].plot(self.energy_scale, np.angle(self.spectrum.compute()), label='Phase')
for ind,ax_ind in enumerate([1,2]):
if self.set_title:
self.axes[ax_ind].set_title('spectrum {}, {}'.format(self.x, self.y))
self.axes[ax_ind].set_xlim(xlims[ind])
self.axes[ax_ind].set_xlabel(self.xlabel)
self.axes[ax_ind].set_ylabel(self.ylabel)
leg = self.axes[ax_ind].legend(loc = 'best')
leg.get_frame().set_linewidth(0.0)
self.fig.canvas.draw_idle()
self.fig.tight_layout()
def set_legend(self, set_legend):
self.plot_legend = set_legend
def get_xy(self):
return [self.x, self.y]
class SpectralImageFitVisualizer(SpectralImageVisualizer):
def __init__(self, original_dataset, fit_dataset, figure=None, horizontal=True):
'''
Visualizer for spectral image datasets, fit by the Sidpy Fitter
This class is called by Sidpy Fitter for visualizing the raw/fit dataset interactively.
Inputs:
- original_dataset: sidpy.Dataset containing the raw data
- fit_dataset: sidpy.Dataset with the fitted data. This is returned by the
Sidpy Fitter after functional fitting.
- figure: (Optional, default None) - handle to existing figure
- horiziontal: (Optional, default True) - whether spectrum should be plotted horizontally
'''
super().__init__(original_dataset, figure, horizontal)
self.fit_dset = fit_dataset
self.axes[1].clear()
self.get_fit_spectrum()
self.axes[1].plot(self.energy_scale, self.spectrum, 'bo')
self.axes[1].plot(self.energy_scale, self.fit_spectrum, 'r-')
def get_fit_spectrum(self):
if self.x > self.dset.shape[self.image_dims[0]] - self.bin_x:
self.x = self.dset.shape[self.image_dims[0]] - self.bin_x
if self.y > self.dset.shape[self.image_dims[1]] - self.bin_y:
self.y = self.dset.shape[self.image_dims[1]] - self.bin_y
selection = []
for dim, axis in self.dset._axes.items():
if axis.dimension_type == sidpy.DimensionType.SPATIAL:
if dim == self.image_dims[0]:
selection.append(slice(self.x, self.x + self.bin_x))
else:
selection.append(slice(self.y, self.y + self.bin_y))
elif axis.dimension_type == sidpy.DimensionType.SPECTRAL:
selection.append(slice(None))
else:
selection.append(slice(0, 1))
self.spectrum = np.array(self.dset[tuple(selection)].mean(axis=tuple(self.image_dims)))
self.fit_spectrum = np.array(self.fit_dset[tuple(selection)].mean(axis=tuple(self.image_dims)))
# * self.intensity_scale[self.x,self.y]
return self.fit_spectrum.squeeze(), self.spectrum.squeeze()
def _update(self, ev=None):
xlim = self.axes[1].get_xlim()
ylim = self.axes[1].get_ylim()
self.axes[1].clear()
self.get_fit_spectrum()
self.axes[1].plot(self.energy_scale, self.spectrum, 'bo', label='experiment')
self.axes[1].plot(self.energy_scale, self.fit_spectrum, 'r-', label='fit')
if self.set_title:
self.axes[1].set_title('spectrum {}, {}'.format(self.x, self.y))
self.axes[1].set_xlim(xlim)
#self.axes[1].set_ylim(ylim)
self.axes[1].set_xlabel(self.xlabel)
self.axes[1].set_ylabel(self.ylabel)
self.fig.canvas.draw_idle()
|