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
|
#/*##########################################################################
# Copyright (C) 2004-2020 V.A. Sole, European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
"""This module defines a :class:`ScanWindow` inheriting a
:class:`PlotWindow` with additional tools and actions."""
__author__ = "V.A. Sole - ESRF Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import sys
import os
import logging
import numpy
import time
import traceback
from PyMca5.PyMcaGui import PyMcaQt as qt
if hasattr(qt, 'QString'):
QString = qt.QString
else:
QString = qt.safe_str
if __name__ == "__main__":
app = qt.QApplication([])
from PyMca5.PyMcaGui.io import PyMcaFileDialogs
from PyMca5.PyMcaGui.plotting import PlotWindow
from . import ScanFit
from PyMca5.PyMcaMath import SimpleMath
from PyMca5.PyMcaCore import DataObject
import copy
from PyMca5.PyMcaGui import PyMcaPrintPreview
from PyMca5.PyMcaCore import PyMcaDirs
from . import ScanWindowInfoWidget
#implement the plugins interface
from PyMca5.PyMcaGui import QPyMcaMatplotlibSave1D
MATPLOTLIB = True
#force understanding of utf-8 encoding
#otherways it cannot generate svg output
try:
import encodings.utf_8
except:
#not a big problem
pass
PLUGINS_DIR = None
try:
import PyMca5
if os.path.exists(os.path.join(os.path.dirname(PyMca5.__file__), "PyMcaPlugins")):
from PyMca5 import PyMcaPlugins
PLUGINS_DIR = os.path.dirname(PyMcaPlugins.__file__)
else:
directory = os.path.dirname(__file__)
while True:
if os.path.exists(os.path.join(directory, "PyMcaPlugins")):
PLUGINS_DIR = os.path.join(directory, "PyMcaPlugins")
break
directory = os.path.dirname(directory)
if len(directory) < 5:
break
userPluginsDirectory = PyMca5.getDefaultUserPluginsDirectory()
if userPluginsDirectory is not None:
if PLUGINS_DIR is None:
PLUGINS_DIR = userPluginsDirectory
else:
PLUGINS_DIR = [PLUGINS_DIR, userPluginsDirectory]
except:
pass
_logger = logging.getLogger(__name__)
class ScanWindow(PlotWindow.PlotWindow):
def __init__(self, parent=None, name="Scan Window", specfit=None, backend=None,
plugins=True, newplot=True, roi=True, fit=True,
control=True, position=True, info=False, **kw):
super(ScanWindow, self).__init__(parent,
newplot=newplot,
plugins=plugins,
backend=backend,
roi=roi,
fit=fit,
control=control,
position=position,
**kw)
self.setDataMargins(0, 0, 0.025, 0.025)
#self._togglePointsSignal()
self.setPanWithArrowKeys(True)
self.setWindowType("SCAN")
# this two objects are the same
self.dataObjectsList = self._curveList
# but this is tricky
self.dataObjectsDict = {}
self.setWindowTitle(name)
self.matplotlibDialog = None
if PLUGINS_DIR is not None:
if type(PLUGINS_DIR) == type([]):
pluginDir = PLUGINS_DIR
else:
pluginDir = [PLUGINS_DIR]
self.getPlugins(method="getPlugin1DInstance",
directoryList=pluginDir)
if info:
self.scanWindowInfoWidget = ScanWindowInfoWidget.\
ScanWindowInfoWidget()
self.infoDockWidget = qt.QDockWidget(self)
self.infoDockWidget.layout().setContentsMargins(0, 0, 0, 0)
self.infoDockWidget.setWidget(self.scanWindowInfoWidget)
self.infoDockWidget.setWindowTitle(self.windowTitle()+(" Info"))
self.addDockWidget(qt.Qt.BottomDockWidgetArea,
self.infoDockWidget)
controlMenu = qt.QMenu()
controlMenu.addAction(QString("Show/Hide Legends"),
self.toggleLegendWidget)
controlMenu.addAction(QString("Show/Hide Info"),
self._toggleInfoWidget)
controlMenu.addAction(QString("Toggle Crosshair"),
self.toggleCrosshairCursor)
controlMenu.addAction(QString("Toggle Arrow Keys Panning"),
self.toggleArrowKeysPanning)
self.setControlMenu(controlMenu)
else:
self.scanWindowInfoWidget = None
#self.fig = None
if fit:
self.scanFit = ScanFit.ScanFit(specfit=specfit)
self.printPreview = PyMcaPrintPreview.PyMcaPrintPreview(modal = 0)
self.simpleMath = SimpleMath.SimpleMath()
self.outputDir = None
self.outputFilter = None
#signals
# this one was made in the base class
#self.setCallback(self.graphCallback)
if fit:
from PyMca5.PyMcaGui.math.fitting import SimpleFitGui
self.customFit = SimpleFitGui.SimpleFitGui()
self.scanFit.sigScanFitSignal.connect(self._scanFitSignalReceived)
self.customFit.sigSimpleFitSignal.connect( \
self._customFitSignalReceived)
self.fitButtonMenu = qt.QMenu()
self.fitButtonMenu.addAction(QString("Simple Fit"),
self._simpleFitSignal)
self.fitButtonMenu.addAction(QString("Customized Fit") ,
self._customFitSignal)
def _toggleInfoWidget(self):
if self.infoDockWidget.isHidden():
self.infoDockWidget.show()
legend = self.getActiveCurve(just_legend=True)
if legend is not None:
ddict ={}
ddict['event'] = "curveClicked"
ddict['label'] = legend
ddict['legend'] = legend
self.graphCallback(ddict)
else:
self.infoDockWidget.hide()
def _buildLegendWidget(self):
if self.legendWidget is None:
super(ScanWindow, self)._buildLegendWidget()
if hasattr(self, "infoDockWidget") and \
hasattr(self, "roiDockWidget"):
self.tabifyDockWidget(self.infoDockWidget,
self.roiDockWidget,
self.legendDockWidget)
elif hasattr(self, "infoDockWidget"):
self.tabifyDockWidget(self.infoDockWidget,
self.legendDockWidget)
def _toggleROI(self, position=None):
super(ScanWindow, self)._toggleROI(position=position)
if hasattr(self, "infoDockWidget"):
self.tabifyDockWidget(self.infoDockWidget,
self.roiDockWidget)
def setDispatcher(self, w):
w.sigAddSelection.connect(self._addSelection)
w.sigRemoveSelection.connect(self._removeSelection)
w.sigReplaceSelection.connect(self._replaceSelection)
def _addSelection(self, selectionlist, replot=True):
"""Add curves to plot and data objects to :attr:`dataObjectsDict`
"""
_logger.debug("_addSelection(self, selectionlist) " +
str(selectionlist))
if type(selectionlist) == type([]):
sellist = selectionlist
else:
sellist = [selectionlist]
if len(self._curveList):
activeCurve = self.getActiveCurve(just_legend=True)
else:
activeCurve = None
nSelection = len(sellist)
for selectionIndex in range(nSelection):
sel = sellist[selectionIndex]
if selectionIndex == (nSelection - 1):
actualReplot = replot
else:
actualReplot = False
source = sel['SourceName']
key = sel['Key']
legend = sel['legend'] #expected form sourcename + scan key
if not ("scanselection" in sel): continue
if sel['scanselection'] == "MCA":
continue
if not sel["scanselection"]:
continue
if len(key.split(".")) > 2:
continue
dataObject = sel['dataobject']
# only one-dimensional selections considered
if dataObject.info["selectiontype"] != "1D":
continue
# there must be something to plot
if not hasattr(dataObject, 'y'):
continue
if len(dataObject.y) == 0:
# nothing to be plot
continue
else:
for i in range(len(dataObject.y)):
if numpy.isscalar(dataObject.y[i]):
dataObject.y[i] = numpy.array([dataObject.y[i]])
if not hasattr(dataObject, 'x'):
ylen = len(dataObject.y[0])
if ylen:
xdata = numpy.arange(ylen).astype(numpy.float)
else:
#nothing to be plot
continue
if getattr(dataObject, 'x', None) is None:
ylen = len(dataObject.y[0])
if not ylen:
# nothing to be plot
continue
xdata = numpy.arange(ylen).astype(numpy.float)
elif len(dataObject.x) > 1:
_logger.debug("Mesh plots. Ignoring")
continue
else:
if numpy.isscalar(dataObject.x[0]):
dataObject.x[0] = numpy.array([dataObject.x[0]])
xdata = dataObject.x[0]
sps_source = False
if 'SourceType' in sel:
if sel['SourceType'] == 'SPS':
sps_source = True
if sps_source:
ycounter = -1
if 'selection' not in dataObject.info:
dataObject.info['selection'] = copy.deepcopy(sel['selection'])
for ydata in dataObject.y:
xlabel = None
ylabel = None
ycounter += 1
if dataObject.m is None:
mdata = [numpy.ones(len(ydata)).astype(numpy.float)]
elif len(dataObject.m[0]) > 0:
if len(dataObject.m[0]) == len(ydata):
index = numpy.nonzero(dataObject.m[0])[0]
if not len(index):
continue
xdata = numpy.take(xdata, index)
ydata = numpy.take(ydata, index)
mdata = numpy.take(dataObject.m[0], index)
#A priori the graph only knows about plots
ydata = ydata/mdata
else:
raise ValueError("Monitor data length different than counter data")
else:
mdata = [numpy.ones(len(ydata)).astype(numpy.float)]
ylegend = 'y%d' % ycounter
if dataObject.info['selection'] is not None:
if type(dataObject.info['selection']) == type({}):
if 'x' in dataObject.info['selection']:
#proper scan selection
ilabel = dataObject.info['selection']['y'][ycounter]
ylegend = dataObject.info['LabelNames'][ilabel]
ylabel = ylegend
if sel['selection']['x'] is not None:
if len(dataObject.info['selection']['x']):
xlabel = dataObject.info['LabelNames'] \
[dataObject.info['selection']['x'][0]]
dataObject.info["xlabel"] = xlabel
dataObject.info["ylabel"] = ylabel
newLegend = legend + " " + ylegend
self.dataObjectsDict[newLegend] = dataObject
self.addCurve(xdata, ydata, legend=newLegend, info=dataObject.info,
xlabel=xlabel, ylabel=ylabel, replot=False)
# replot=actualReplot)
if self.scanWindowInfoWidget is not None:
if not self.infoDockWidget.isHidden():
activeLegend = self.getActiveCurve(just_legend=True)
if activeLegend is not None:
if activeLegend == newLegend:
self.scanWindowInfoWidget.updateFromDataObject\
(dataObject)
else:
dummyDataObject = DataObject.DataObject()
dummyDataObject.y=[numpy.array([])]
dummyDataObject.x=[numpy.array([])]
self.scanWindowInfoWidget.updateFromDataObject(dummyDataObject)
else:
# we have to loop for all y values
ycounter = -1
for ydata in dataObject.y:
ylen = len(ydata)
if ylen == 1:
if len(xdata) > 1:
ydata = ydata[0] * numpy.ones(len(xdata)).astype(numpy.float)
elif len(xdata) == 1:
xdata = xdata[0] * numpy.ones(ylen).astype(numpy.float)
ycounter += 1
newDataObject = DataObject.DataObject()
newDataObject.info = copy.deepcopy(dataObject.info)
if dataObject.m is not None:
for imon in range(len(dataObject.m)):
if numpy.isscalar(dataObject.m[imon]):
dataObject.m[imon] = \
numpy.array([dataObject.m[imon]])
if dataObject.m is None:
mdata = numpy.ones(len(ydata)).astype(numpy.float)
elif len(dataObject.m[0]) > 0:
if len(dataObject.m[0]) == len(ydata):
index = numpy.nonzero(dataObject.m[0])[0]
if not len(index):
continue
xdata = numpy.take(xdata, index)
ydata = numpy.take(ydata, index)
mdata = numpy.take(dataObject.m[0], index)
#A priori the graph only knows about plots
ydata = ydata/mdata
elif len(dataObject.m[0]) == 1:
mdata = numpy.ones(len(ydata)).astype(numpy.float)
mdata *= dataObject.m[0][0]
index = numpy.nonzero(dataObject.m[0])[0]
if not len(index):
continue
xdata = numpy.take(xdata, index)
ydata = numpy.take(ydata, index)
mdata = numpy.take(dataObject.m[0], index)
#A priori the graph only knows about plots
ydata = ydata/mdata
else:
raise ValueError("Monitor data length different than counter data")
else:
mdata = numpy.ones(len(ydata)).astype(numpy.float)
newDataObject.x = [xdata]
newDataObject.y = [ydata]
newDataObject.m = [mdata]
newDataObject.info['selection'] = copy.deepcopy(sel['selection'])
ylegend = 'y%d' % ycounter
xlabel = None
ylabel = None
if sel['selection'] is not None:
if type(sel['selection']) == type({}):
if 'x' in sel['selection']:
#proper scan selection
newDataObject.info['selection']['x'] = sel['selection']['x']
newDataObject.info['selection']['y'] = [sel['selection']['y'][ycounter]]
newDataObject.info['selection']['m'] = sel['selection']['m']
ilabel = newDataObject.info['selection']['y'][0]
ylegend = newDataObject.info['LabelNames'][ilabel]
ylabel = ylegend
if len(newDataObject.info['selection']['x']):
ilabel = newDataObject.info['selection']['x'][0]
xlabel = newDataObject.info['LabelNames'][ilabel]
else:
xlabel = "Point number"
if ('operations' in dataObject.info) and len(dataObject.y) == 1:
newDataObject.info['legend'] = legend
symbol = 'x'
else:
symbol = None
newDataObject.info['legend'] = legend + " " + ylegend
newDataObject.info['selectionlegend'] = legend
yaxis = None
if "plot_yaxis" in dataObject.info:
yaxis = dataObject.info["plot_yaxis"]
elif 'operations' in dataObject.info:
if dataObject.info['operations'][-1] == 'derivate':
yaxis = 'right'
# do not keep unnecessary references
self.dataObjectsDict[newDataObject.info['legend']] = newDataObject
self.addCurve(xdata, ydata, legend=newDataObject.info['legend'],
info=newDataObject.info,
symbol=symbol,
yaxis=yaxis,
xlabel=xlabel,
ylabel=ylabel,
replot=False)
self.dataObjectsList = self._curveList
try:
if activeCurve is None:
if len(self._curveList) > 0:
activeCurve = self._curveList[0]
ddict = {}
ddict['event'] = "curveClicked"
ddict['label'] = activeCurve
self.graphCallback(ddict)
finally:
if replot:
#self.replot()
self.resetZoom()
self.updateLegends()
def _removeSelection(self, selectionlist):
_logger.debug("_removeSelection(self, selectionlist)",selectionlist)
if type(selectionlist) == type([]):
sellist = selectionlist
else:
sellist = [selectionlist]
removelist = []
for sel in sellist:
source = sel['SourceName']
key = sel['Key']
if not ("scanselection" in sel):
continue
if sel['scanselection'] == "MCA":
continue
if not sel["scanselection"]:
continue
if len(key.split(".")) > 2:
continue
legend = sel['legend'] # expected form sourcename + scan key
if type(sel['selection']) == type({}):
if 'y' in sel['selection']:
for lName in ['cntlist', 'LabelNames']:
if lName in sel['selection']:
for index in sel['selection']['y']:
removelist.append(legend +" "+\
sel['selection'][lName][index])
if len(removelist):
self.removeCurves(removelist)
def removeCurves(self, removeList, replot=True):
for legend in removeList:
if legend == removeList[-1]:
self.removeCurve(legend, replot=replot)
else:
self.removeCurve(legend, replot=False)
if legend in self.dataObjectsDict:
del self.dataObjectsDict[legend]
self.dataObjectsList = self._curveList
def _replaceSelection(self, selectionlist):
"""Delete existing curves and data objects, then add new selection.
"""
_logger.debug("_replaceSelection(self, selectionlist) %s" % selectionlist)
if type(selectionlist) == type([]):
sellist = selectionlist
else:
sellist = [selectionlist]
doit = False
for sel in sellist:
if not ("scanselection" in sel):
continue
if sel['scanselection'] == "MCA":
continue
if not sel["scanselection"]:
continue
if len(sel["Key"].split(".")) > 2:
continue
dataObject = sel['dataobject']
if dataObject.info["selectiontype"] == "1D":
if hasattr(dataObject, 'y'):
doit = True
break
if not doit:
return
self.clearCurves()
self.dataObjectsDict={}
self.dataObjectsList=self._curveList
self._addSelection(selectionlist, replot=True)
def _handleMarkerEvent(self, ddict):
if ddict['event'] == 'markerMoved':
label = ddict['label']
if label.startswith('ROI'):
return self._handleROIMarkerEvent(ddict)
else:
_logger.debug("Unhandled marker %s" % label)
return
def graphCallback(self, ddict):
_logger.debug("graphCallback", ddict)
if ddict['event'] in ['markerMoved', 'markerSelected']:
self._handleMarkerEvent(ddict)
elif ddict['event'] in ["mouseMoved", "MouseAt"]:
if self._toggleCounter > 0:
activeCurve = self.getActiveCurve()
if activeCurve in [None, []]:
self._handleMouseMovedEvent(ddict)
else:
x, y, legend, info = activeCurve[0:4]
# calculate the maximum distance
xMin, xMax = self.getGraphXLimits()
maxXDistance = abs(xMax - xMin)
yMin, yMax = self.getGraphYLimits()
maxYDistance = abs(yMax - yMin)
if (maxXDistance > 0.0) and (maxYDistance > 0.0):
closestIndex = (pow((x - ddict['x'])/maxXDistance, 2) + \
pow((y - ddict['y'])/maxYDistance, 2))
else:
closestIndex = (pow(x - ddict['x'], 2) + \
pow(y - ddict['y'], 2))
xText = '----'
yText = '----'
if len(closestIndex):
closestIndex = closestIndex.argmin()
xCurve = x[closestIndex]
if abs(xCurve - ddict['x']) < (0.05 * maxXDistance):
yCurve = y[closestIndex]
if abs(yCurve - ddict['y']) < (0.05 * maxYDistance):
xText = '%.7g' % xCurve
yText = '%.7g' % yCurve
if xText == '----':
if self.getGraphCursor():
self._xPos.setStyleSheet("color: rgb(255, 0, 0);")
self._yPos.setStyleSheet("color: rgb(255, 0, 0);")
xText = '%.7g' % ddict['x']
yText = '%.7g' % ddict['y']
else:
self._xPos.setStyleSheet("color: rgb(0, 0, 0);")
self._yPos.setStyleSheet("color: rgb(0, 0, 0);")
else:
self._xPos.setStyleSheet("color: rgb(0, 0, 0);")
self._yPos.setStyleSheet("color: rgb(0, 0, 0);")
self._xPos.setText(xText)
self._yPos.setText(yText)
else:
self._xPos.setStyleSheet("color: rgb(0, 0, 0);")
self._yPos.setStyleSheet("color: rgb(0, 0, 0);")
self._handleMouseMovedEvent(ddict)
elif ddict['event'] in ["curveClicked", "legendClicked"]:
legend = ddict["label"]
if legend is None:
if len(self.dataObjectsList):
legend = self.dataObjectsList[0]
else:
return
if legend not in self.dataObjectsList:
_logger.debug("unknown legend %s" % legend)
return
#force the current x label to the appropriate value
dataObject = self.dataObjectsDict[legend]
if 'selection' in dataObject.info:
ilabel = dataObject.info['selection']['y'][0]
ylabel = dataObject.info['LabelNames'][ilabel]
if len(dataObject.info['selection']['x']):
ilabel = dataObject.info['selection']['x'][0]
xlabel = dataObject.info['LabelNames'][ilabel]
else:
xlabel = "Point Number"
if len(dataObject.info['selection']['m']):
ilabel = dataObject.info['selection']['m'][0]
ylabel += "/" + dataObject.info['LabelNames'][ilabel]
else:
xlabel = dataObject.info.get('xlabel', None)
ylabel = dataObject.info.get('ylabel', None)
if xlabel is not None:
self.setGraphXLabel(xlabel)
if ylabel is not None:
self.setGraphYLabel(ylabel)
self.setGraphTitle(legend)
self.setActiveCurve(legend)
#self.setGraphTitle(legend)
if self.scanWindowInfoWidget is not None:
if not self.infoDockWidget.isHidden():
self.scanWindowInfoWidget.updateFromDataObject\
(dataObject)
elif ddict['event'] == "removeCurveEvent":
legend = ddict['legend']
self.removeCurves([legend])
elif ddict['event'] == "renameCurveEvent":
legend = ddict['legend']
newlegend = ddict['newlegend']
if legend in self.dataObjectsDict:
self.dataObjectsDict[newlegend]= copy.deepcopy(self.dataObjectsDict[legend])
self.dataObjectsDict[newlegend].info['legend'] = newlegend
self.dataObjectsList.append(newlegend)
self.removeCurves([legend], replot=False)
self.newCurve(self.dataObjectsDict[newlegend].x[0],
self.dataObjectsDict[newlegend].y[0],
legend=self.dataObjectsDict[newlegend].info['legend'])
#make sure the plot signal is forwarded because we have overwritten
#its handling
self.sigPlotSignal.emit(ddict)
def _customFitSignalReceived(self, ddict):
if ddict['event'] == "FitFinished":
newDataObject = self.__customFitDataObject
xplot = ddict['x']
yplot = ddict['yfit']
newDataObject.x = [xplot]
newDataObject.y = [yplot]
newDataObject.m = [numpy.ones(len(yplot)).astype(numpy.float)]
#here I should check the log or linear status
self.dataObjectsDict[newDataObject.info['legend']] = newDataObject
self.addCurve(xplot,
yplot,
legend=newDataObject.info['legend'])
def _scanFitSignalReceived(self, ddict):
_logger.debug("_scanFitSignalReceived", ddict)
if ddict['event'] == "EstimateFinished":
return
if ddict['event'] == "FitFinished":
newDataObject = self.__fitDataObject
xplot = self.scanFit.specfit.xdata * 1.0
yplot = self.scanFit.specfit.gendata(parameters=ddict['data'])
newDataObject.x = [xplot]
newDataObject.y = [yplot]
newDataObject.m = [numpy.ones(len(yplot)).astype(numpy.float)]
self.dataObjectsDict[newDataObject.info['legend']] = newDataObject
self.addCurve(x=xplot, y=yplot, legend=newDataObject.info['legend'])
def _fitIconSignal(self):
_logger.debug("_fitIconSignal")
self.fitButtonMenu.exec_(self.cursor().pos())
def _simpleFitSignal(self):
_logger.debug("_simpleFitSignal")
self._QSimpleOperation("fit")
def _customFitSignal(self):
_logger.debug("_customFitSignal")
self._QSimpleOperation("custom_fit")
def _saveIconSignal(self):
_logger.debug("_saveIconSignal")
if self._ownSave:
self._QSimpleOperation("save")
else:
self.emitIconSignal("save")
def _averageIconSignal(self):
_logger.debug("_averageIconSignal")
self._QSimpleOperation("average")
def _smoothIconSignal(self):
_logger.debug("_smoothIconSignal")
self._QSimpleOperation("smooth")
def _getOutputFileName(self):
#get outputfile
self.outputDir = PyMcaDirs.outputDir
if self.outputDir is None:
self.outputDir = os.getcwd()
wdir = os.getcwd()
elif os.path.exists(self.outputDir):
wdir = self.outputDir
else:
self.outputDir = os.getcwd()
wdir = self.outputDir
filterlist = ['Specfile MCA *.mca',
'Specfile Scan *.dat',
'Specfile MultiScan *.dat',
'Raw ASCII *.txt',
'","-separated CSV *.csv',
'";"-separated CSV *.csv',
'"tab"-separated CSV *.csv',
'OMNIC CSV *.csv',
'Widget PNG *.png',
'Widget JPG *.jpg',
'Graphics PNG *.png',
'Graphics EPS *.eps',
'Graphics SVG *.svg']
fileList, fileFilter = PyMcaFileDialogs.getFileList(self,
filetypelist=filterlist,
message="Output File Selection",
currentdir=wdir,
single=True,
mode="SAVE",
getfilter=True,
currentfilter=self.outputFilter)
if not len(fileList):
return
filterused = fileFilter.split()
filetype = filterused[1]
extension = filterused[2]
outdir = qt.safe_str(fileList[0])
try:
self.outputDir = os.path.dirname(outdir)
PyMcaDirs.outputDir = os.path.dirname(outdir)
except:
print("setting output directory to default")
self.outputDir = os.getcwd()
try:
outputFile = os.path.basename(outdir)
except:
outputFile = outdir
if len(outputFile) < 5:
outputFile = outputFile + extension[-4:]
elif outputFile[-4:] != extension[-4:]:
outputFile = outputFile + extension[-4:]
return os.path.join(self.outputDir, outputFile), filetype, filterused
def _QSimpleOperation(self, operation):
try:
self._simpleOperation(operation)
except:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setInformativeText(str(sys.exc_info()[1]))
msg.setDetailedText(traceback.format_exc())
msg.exec_()
def _saveOperation(self, fileName, fileType, fileFilter):
filterused = fileFilter
filetype = fileType
filename = fileName
if os.path.exists(filename):
os.remove(filename)
if filterused[0].upper() == "WIDGET":
fformat = filename[-3:].upper()
if hasattr(qt.QPixmap, "grabWidget"):
pixmap = qt.QPixmap.grabWidget(self)
else:
pixmap = self.grab()
if not pixmap.save(filename, fformat):
qt.QMessageBox.critical(self,
"Save Error",
"%s" % sys.exc_info()[1])
return
try:
if filename[-3:].upper() in ['EPS', 'PNG', 'SVG']:
self.graphicsSave(filename)
return
except:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setText("Graphics Saving Error: %s" % (sys.exc_info()[1]))
msg.exec_()
return
systemline = os.linesep
os.linesep = '\n'
try:
if sys.version < "3.0":
ffile=open(filename, "wb")
else:
ffile=open(filename, "w", newline='')
except IOError:
msg = qt.QMessageBox(self)
msg.setIcon(qt.QMessageBox.Critical)
msg.setText("Input Output Error: %s" % (sys.exc_info()[1]))
msg.exec_()
return
x, y, legend, info = self.getActiveCurve()
xlabel = info.get("xlabel", "X")
ylabel = info.get("ylabel", "Y")
if 0:
if "selection" in info:
if type(info['selection']) == type({}):
if 'x' in info['selection']:
#proper scan selection
ilabel = info['selection']['y'][0]
ylegend = info['LabelNames'][ilabel]
ylabel = ylegend
if info['selection']['x'] is not None:
if len(info['selection']['x']):
xlabel = info['LabelNames'] [info['selection']['x'][0]]
else:
xlabel = "Point number"
try:
if filetype in ['Scan', 'MultiScan']:
ffile.write("#F %s\n" % filename)
savingDate = "#D %s\n"%(time.ctime(time.time()))
ffile.write(savingDate)
ffile.write("\n")
ffile.write("#S 1 %s\n" % legend)
ffile.write(savingDate)
ffile.write("#N 2\n")
ffile.write("#L %s %s\n" % (xlabel, ylabel) )
for i in range(len(y)):
ffile.write("%.7g %.7g\n" % (x[i], y[i]))
ffile.write("\n")
if filetype == 'MultiScan':
scan_n = 1
curveList = self.getAllCurves()
for x, y, key, info in curveList:
if key == legend:
continue
xlabel = info.get("xlabel", "X")
ylabel = info.get("ylabel", "Y")
if 0:
if "selection" in info:
if type(info['selection']) == type({}):
if 'x' in info['selection']:
#proper scan selection
ilabel = info['selection']['y'][0]
ylegend = info['LabelNames'][ilabel]
ylabel = ylegend
if info['selection']['x'] is not None:
if len(info['selection']['x']):
xlabel = info['LabelNames'] [info['selection']['x'][0]]
else:
xlabel = "Point number"
scan_n += 1
ffile.write("#S %d %s\n" % (scan_n, key))
ffile.write(savingDate)
ffile.write("#N 2\n")
ffile.write("#L %s %s\n" % (xlabel, ylabel) )
for i in range(len(y)):
ffile.write("%.7g %.7g\n" % (x[i], y[i]))
ffile.write("\n")
elif filetype == 'ASCII':
for i in range(len(y)):
ffile.write("%.7g %.7g\n" % (x[i], y[i]))
elif filetype == 'CSV':
if "," in filterused[0]:
csvseparator = ","
elif ";" in filterused[0]:
csvseparator = ";"
elif "OMNIC" in filterused[0]:
csvseparator = ","
else:
csvseparator = "\t"
if "OMNIC" not in filterused[0]:
ffile.write('"%s"%s"%s"\n' % (xlabel,csvseparator,ylabel))
for i in range(len(y)):
ffile.write("%.7E%s%.7E\n" % (x[i], csvseparator,y[i]))
else:
ffile.write("#F %s\n" % filename)
ffile.write("#D %s\n"%(time.ctime(time.time())))
ffile.write("\n")
ffile.write("#S 1 %s\n" % legend)
ffile.write("#D %s\n"%(time.ctime(time.time())))
ffile.write("#@MCA %16C\n")
ffile.write("#@CHANN %d %d %d 1\n" % (len(y), x[0], x[-1]))
ffile.write("#@CALIB %.7g %.7g %.7g\n" % (0, 1, 0))
ffile.write(self.array2SpecMca(y))
ffile.write("\n")
ffile.close()
os.linesep = systemline
except:
os.linesep = systemline
raise
return
def _simpleOperation(self, operation):
if operation == 'subtract':
self._subtractOperation()
return
if operation == "save":
#getOutputFileName
filename = self._getOutputFileName()
if filename is None:
return
self._saveOperation(filename[0], filename[1], filename[2])
return
if operation != "average":
#get active curve
legend = self.getActiveCurveLegend()
if legend is None:return
found = False
for key in self.dataObjectsList:
if key == legend:
found = True
break
if found:
dataObject = self.dataObjectsDict[legend]
else:
print("I should not be here")
print("active curve =",legend)
print("but legend list = ",self.dataObjectsList)
return
y = dataObject.y[0]
if dataObject.x is not None:
x = dataObject.x[0]
else:
x = numpy.arange(len(y)).astype(numpy.float)
ilabel = dataObject.info['selection']['y'][0]
ylabel = dataObject.info['LabelNames'][ilabel]
if len(dataObject.info['selection']['x']):
ilabel = dataObject.info['selection']['x'][0]
xlabel = dataObject.info['LabelNames'][ilabel]
else:
xlabel = "Point Number"
else:
x = []
y = []
legend = ""
i = 0
ndata = 0
for key in self._curveList:
_logger.debug("key -> ", key)
if key in self.dataObjectsDict:
x.append(self.dataObjectsDict[key].x[0]) #only the first X
if len(self.dataObjectsDict[key].y) == 1:
y.append(self.dataObjectsDict[key].y[0])
else:
sel_legend = self.dataObjectsDict[key].info['legend']
ilabel = 0
#I have to get the proper y associated to the legend
if sel_legend in key:
if key.index(sel_legend) == 0:
label = key[len(sel_legend):]
while (label.startswith(' ')):
label = label[1:]
if not len(label):
break
if label in self.dataObjectsDict[key].info['LabelNames']:
ilabel = self.dataObjectsDict[key].info['LabelNames'].index(label)
_logger.debug("LABEL = ", label)
_logger.debug("ilabel = ", ilabel)
y.append(self.dataObjectsDict[key].y[ilabel])
if i == 0:
legend = key
firstcurve = key
i += 1
else:
legend += " + " + key
lastcurve = key
ndata += 1
if ndata == 0: return #nothing to average
dataObject = self.dataObjectsDict[firstcurve]
#create the output data object
newDataObject = DataObject.DataObject()
newDataObject.data = None
newDataObject.info = copy.deepcopy(dataObject.info)
if 'selectionlegend' in newDataObject.info:
del newDataObject.info['selectionlegend']
if not ('operations' in newDataObject.info):
newDataObject.info['operations'] = []
newDataObject.info['operations'].append(operation)
sel = {}
sel['SourceType'] = "Operation"
#get new x and new y
if operation == "derivate":
#xmin and xmax
xlimits=self.getGraphXLimits()
xplot, yplot = self.simpleMath.derivate(x, y, xlimits=xlimits)
ilabel = dataObject.info['selection']['y'][0]
ylabel = dataObject.info['LabelNames'][ilabel]
newDataObject.info['LabelNames'][ilabel] = ylabel+"'"
newDataObject.info['plot_yaxis'] = "right"
sel['SourceName'] = legend
sel['Key'] = "'"
sel['legend'] = legend + sel['Key']
outputlegend = legend + sel['Key']
elif operation == "average":
xplot, yplot = self.simpleMath.average(x, y)
if len(legend) < 80:
sel['SourceName'] = legend
sel['Key'] = ""
sel['legend'] = "(%s)/%d" % (legend, ndata)
outputlegend = "(%s)/%d" % (legend, ndata)
else:
sel['SourceName'] = legend
legend = "Average of %d from %s to %s" % (ndata, firstcurve, lastcurve)
sel['Key'] = ""
sel['legend'] = legend
outputlegend = legend
elif operation == "swapsign":
xplot = x * 1
yplot = -y
sel['SourceName'] = legend
sel['Key'] = ""
sel['legend'] = "-(%s)" % legend
outputlegend = "-(%s)" % legend
elif operation == "smooth":
xplot = x * 1
yplot = self.simpleMath.smooth(y)
sel['SourceName'] = legend
sel['Key'] = ""
sel['legend'] = "%s Smooth" % legend
outputlegend = "%s Smooth" % legend
if 'operations' in dataObject.info:
if len(dataObject.info['operations']):
if dataObject.info['operations'][-1] == "smooth":
sel['legend'] = legend
outputlegend = legend
elif operation == "forceymintozero":
xplot = x * 1
yplot = y - min(y)
sel['SourceName'] = legend
sel['Key'] = ""
sel['legend'] = "(%s) - ymin" % legend
outputlegend = "(%s) - ymin" % legend
elif operation == "fit":
#remove a existing fit if present
xmin,xmax=self.getGraphXLimits()
outputlegend = legend + " Fit"
for key in self._curveList:
if key == outputlegend:
self.removeCurves([outputlegend], replot=False)
break
self.scanFit.setData(x = x,
y = y,
xmin = xmin,
xmax = xmax,
legend = legend)
if self.scanFit.isHidden():
self.scanFit.show()
self.scanFit.raise_()
elif operation == "custom_fit":
#remove a existing fit if present
xmin, xmax=self.getGraphXLimits()
outputlegend = legend + "Custom Fit"
keyList = list(self._curveList)
for key in keyList:
if key == outputlegend:
self.removeCurves([outputlegend], replot=False)
break
self.customFit.setData(x = x,
y = y,
xmin = xmin,
xmax = xmax,
legend = legend)
if self.customFit.isHidden():
self.customFit.show()
self.customFit.raise_()
else:
raise ValueError("Unknown operation %s" % operation)
if operation not in ["fit", "custom_fit"]:
newDataObject.x = [xplot]
newDataObject.y = [yplot]
newDataObject.m = [numpy.ones(len(yplot)).astype(numpy.float)]
#and add it to the plot
if True and (operation not in ['fit', 'custom_fit']):
sel['dataobject'] = newDataObject
sel['scanselection'] = True
sel['selection'] = copy.deepcopy(dataObject.info['selection'])
sel['selectiontype'] = "1D"
if operation == 'average':
self._replaceSelection([sel])
elif operation != 'fit':
self._addSelection([sel])
else:
self.__fitDataObject = newDataObject
return
else:
newDataObject.info['legend'] = outputlegend
if operation == 'fit':
self.__fitDataObject = newDataObject
return
if operation == 'custom_fit':
self.__customFitDataObject = newDataObject
return
self.dataObjectsDict[newDataObject.info['legend']] = newDataObject
#here I should check the log or linear status
self.addCurve(x=xplot, y=yplot, legend=newDataObject.info['legend'], replot=False)
self.replot()
def graphicsSave(self, filename):
#use the plugin interface
x, y, legend, info = self.getActiveCurve()[:4]
curveList = self.getAllCurves()
size = (6, 3) #in inches
bw = False
if len(curveList) > 1:
legends = True
else:
legends = False
if self.matplotlibDialog is None:
self.matplotlibDialog = QPyMcaMatplotlibSave1D.\
QPyMcaMatplotlibSaveDialog(size=size,
logx=self._logX,
logy=self._logY,
legends=legends,
bw = bw)
mtplt = self.matplotlibDialog.plot
mtplt.setParameters({'logy':self._logY,
'logx':self._logX,
'legends':legends,
'bw':bw})
xmin, xmax = self.getGraphXLimits()
ymin, ymax = self.getGraphYLimits()
mtplt.setLimits(xmin, xmax, ymin, ymax)
legend0 = legend
xdata = x
ydata = y
dataCounter = 1
alias = "%c" % (96+dataCounter)
mtplt.addDataToPlot( xdata, ydata, legend=legend0, alias=alias )
for curve in curveList:
xdata, ydata, legend, info = curve[0:4]
if legend == legend0:
continue
dataCounter += 1
alias = "%c" % (96+dataCounter)
mtplt.addDataToPlot( xdata, ydata, legend=legend, alias=alias )
if sys.version < '3.0':
self.matplotlibDialog.setXLabel(qt.safe_str(self.getGraphXLabel()))
self.matplotlibDialog.setYLabel(qt.safe_str(self.getGraphYLabel()))
else:
self.matplotlibDialog.setXLabel(self.getGraphXLabel())
self.matplotlibDialog.setYLabel(self.getGraphYLabel())
if legends:
mtplt.plotLegends()
ret = self.matplotlibDialog.exec_()
if ret == qt.QDialog.Accepted:
mtplt.saveFile(filename)
return
def getActiveCurveLegend(self):
return super(ScanWindow,self).getActiveCurve(just_legend=True)
def _deriveIconSignal(self):
_logger.debug("_deriveIconSignal")
self._QSimpleOperation('derivate')
def _swapSignIconSignal(self):
_logger.debug("_swapSignIconSignal")
self._QSimpleOperation('swapsign')
def _yMinToZeroIconSignal(self):
_logger.debug("_yMinToZeroIconSignal")
self._QSimpleOperation('forceymintozero')
def _subtractIconSignal(self):
_logger.debug("_subtractIconSignal")
self._QSimpleOperation('subtract')
def _subtractOperation(self):
#identical to twice the average with the negative active curve
#get active curve
legend = self.getActiveCurveLegend()
if legend is None:
return
found = False
for key in self.dataObjectsList:
if key == legend:
found = True
break
if found:
dataObject = self.dataObjectsDict[legend]
else:
print("I should not be here")
print("active curve =",legend)
print("but legend list = ",self.dataObjectsList)
return
x = dataObject.x[0]
y = dataObject.y[0]
ilabel = dataObject.info['selection']['y'][0]
ylabel = dataObject.info['LabelNames'][ilabel]
if len(dataObject.info['selection']['x']):
ilabel = dataObject.info['selection']['x'][0]
xlabel = dataObject.info['LabelNames'][ilabel]
else:
xlabel = "Point Number"
xActive = x
yActive = y
yActiveLegend = legend
yActiveLabel = ylabel
xActiveLabel = xlabel
operation = "subtract"
sel_list = []
i = 0
ndata = 0
keyList = list(self._curveList)
for key in keyList:
legend = ""
x = [xActive]
y = [-yActive]
_logger.debug("key -> ", key)
if key in self.dataObjectsDict:
x.append(self.dataObjectsDict[key].x[0]) #only the first X
if len(self.dataObjectsDict[key].y) == 1:
y.append(self.dataObjectsDict[key].y[0])
ilabel = self.dataObjectsDict[key].info['selection']['y'][0]
else:
sel_legend = self.dataObjectsDict[key].info['legend']
ilabel = self.dataObjectsDict[key].info['selection']['y'][0]
#I have to get the proper y associated to the legend
if sel_legend in key:
if key.index(sel_legend) == 0:
label = key[len(sel_legend):]
while (label.startswith(' ')):
label = label[1:]
if not len(label):
break
if label in self.dataObjectsDict[key].info['LabelNames']:
ilabel = self.dataObjectsDict[key].info['LabelNames'].index(label)
_logger.debug("LABEL = ", label)
_logger.debug("ilabel = ", ilabel)
y.append(self.dataObjectsDict[key].y[ilabel])
outputlegend = "(%s - %s)" % (key, yActiveLegend)
ndata += 1
xplot, yplot = self.simpleMath.average(x, y)
yplot *= 2
#create the output data object
newDataObject = DataObject.DataObject()
newDataObject.data = None
newDataObject.info.update(self.dataObjectsDict[key].info)
if not ('operations' in newDataObject.info):
newDataObject.info['operations'] = []
newDataObject.info['operations'].append(operation)
newDataObject.info['LabelNames'][ilabel] = "(%s - %s)" % \
(newDataObject.info['LabelNames'][ilabel], yActiveLabel)
newDataObject.x = [xplot]
newDataObject.y = [yplot]
newDataObject.m = None
sel = {}
sel['SourceType'] = "Operation"
sel['SourceName'] = key
sel['Key'] = ""
sel['legend'] = outputlegend
sel['dataobject'] = newDataObject
sel['scanselection'] = True
sel['selection'] = copy.deepcopy(dataObject.info['selection'])
#sel['selection']['y'] = [ilabel]
sel['selectiontype'] = "1D"
sel_list.append(sel)
if True:
#The legend menu was not working with the next line
#but if works if I add the list
self._replaceSelection(sel_list)
else:
oldlist = list(self.dataObjectsDict)
self._addSelection(sel_list)
self.removeCurves(oldlist)
#The plugins interface
def getGraphYLimits(self):
#if the active curve is mapped to second axis
#I should give the second axis limits
return super(ScanWindow, self).getGraphYLimits()
#end of plugins interface
def addCurve(self, x, y, legend=None, info=None, replace=False, replot=True,
color=None, symbol=None, linestyle=None,
xlabel=None, ylabel=None, yaxis=None,
xerror=None, yerror=None, **kw):
if legend in self._curveList:
if info is None:
info = {}
oldStuff = self.getCurve(legend)
if len(oldStuff):
oldX, oldY, oldLegend, oldInfo = oldStuff
else:
oldInfo = {}
if color is None:
color = info.get("plot_color", oldInfo.get("plot_color", None))
if symbol is None:
symbol = info.get("plot_symbol",oldInfo.get("plot_symbol", None))
if linestyle is None:
linestyle = info.get("plot_linestyle",oldInfo.get("plot_linestyle", None))
if yaxis is None:
yaxis = info.get("plot_yaxis",oldInfo.get("plot_yaxis", None))
else:
if info is None:
info = {}
if color is None:
color = info.get("plot_color", None)
if symbol is None:
symbol = info.get("plot_symbol", None)
if linestyle is None:
linestyle = info.get("plot_linestyle", None)
if yaxis is None:
yaxis = info.get("plot_yaxis", None)
if legend in self.dataObjectsDict:
# the info is changing
super(ScanWindow, self).addCurve(x, y, legend=legend, info=info,
replace=replace, replot=replot, color=color, symbol=symbol,
linestyle=linestyle, xlabel=xlabel, ylabel=ylabel, yaxis=yaxis,
xerror=xerror, yerror=yerror, **kw)
else:
# create the data object
self.newCurve(x, y, legend=legend, info=info,
replace=replace, replot=replot, color=color, symbol=symbol,
linestyle=linestyle, xlabel=xlabel, ylabel=ylabel, yaxis=yaxis,
xerror=xerror, yerror=yerror, **kw)
def newCurve(self, x, y, legend=None, info=None, replace=False, replot=True,
color=None, symbol=None, linestyle=None,
xlabel=None, ylabel=None, yaxis=None,
xerror=None, yerror=None, **kw):
if legend is None:
legend = "Unnamed curve 1.1"
if xlabel is None:
xlabel = "X"
if ylabel is None:
ylabel = "Y"
if info is None:
info = {}
# this is awfull but I have no other way to pass the plot information ...
if color is not None:
info["plot_color"] = color
if symbol is not None:
info["plot_symbol"] = symbol
if linestyle is not None:
info["plot_linestyle"] = linestyle
if yaxis is not None:
info["plot_yaxis"] = yaxis
newDataObject = DataObject.DataObject()
newDataObject.x = [x]
newDataObject.y = [y]
newDataObject.m = None
newDataObject.info = copy.deepcopy(info)
newDataObject.info['legend'] = legend
newDataObject.info['SourceName'] = legend
newDataObject.info['Key'] = ""
newDataObject.info['selectiontype'] = "1D"
newDataObject.info['LabelNames'] = [xlabel, ylabel]
newDataObject.info['selection'] = {'x': [0], 'y': [1]}
sel_list = []
sel = {}
sel['SourceType'] = "Operation"
sel['SourceName'] = legend
sel['Key'] = ""
sel['legend'] = legend
sel['dataobject'] = newDataObject
sel['scanselection'] = True
sel['selection'] = {'x':[0], 'y':[1], 'm':[], 'cntlist':[xlabel, ylabel]}
#sel['selection']['y'] = [ilabel]
sel['selectiontype'] = "1D"
sel_list.append(sel)
if replace:
self._replaceSelection(sel_list)
else:
self._addSelection(sel_list, replot=replot)
def printGraph(self):
if self.printPreview.printer is None:
# setup needed
self.printPreview.setup()
self._printer = self.printPreview.printer
if self._printer is None:
# printer was not selected
return
#self._printer = None
if PlotWindow.PlotWidget.SVG:
svg = True
self._svgRenderer = self.getSvgRenderer()
else:
svg = False
if hasattr(self, "getWidgetHandle"):
widget = self.getWidgetHandle()
else:
widget = self.centralWidget()
if hasattr(widget, "grab"):
pixmap = widget.grab()
else:
pixmap = qt.QPixmap.grabWidget(widget)
title = None
comment = None
if self.scanWindowInfoWidget is not None:
if not self.infoDockWidget.isHidden():
info = self.scanWindowInfoWidget.getInfo()
title = info['scan'].get('source', None)
comment = info['scan'].get('scan', None)+"\n"
h, k, l = info['scan'].get('hkl')
if h != "----":
comment += "H = %s K = %s L = %s\n" % (h, k, l)
peak = info['graph']['peak']
peakAt = info['graph']['peakat']
fwhm = info['graph']['fwhm']
fwhmAt = info['graph']['fwhmat']
com = info['graph']['com']
mean = info['graph']['mean']
std = info['graph']['std']
minimum = info['graph']['min']
maximum = info['graph']['max']
delta = info['graph']['delta']
xLabel = self.getGraphXLabel()
comment += "Peak %s at %s = %s\n" % (peak, xLabel, peakAt)
comment += "FWHM %s at %s = %s\n" % (fwhm, xLabel, fwhmAt)
comment += "COM = %s Mean = %s STD = %s\n" % (com, mean, std)
comment += "Min = %s Max = %s Delta = %s\n" % (minimum,
maximum,
delta)
if hasattr(self, "scanFit"):
if not self.scanFit.isHidden():
if comment is None:
comment = ""
comment += "\n"
comment += self.scanFit.getText()
if svg:
self.printPreview.addSvgItem(self._svgRenderer,
title=None,
comment=comment,
commentPosition="LEFT")
else:
self.printPreview.addPixmap(pixmap,
title=None,
comment=comment,
commentPosition="LEFT")
if self.printPreview.isHidden():
self.printPreview.show()
self.printPreview.raise_()
def getSvgRenderer(self, printer=None):
if printer is None:
if self.printPreview.printer is None:
# setup needed
self.printPreview.setup()
self._printer = self.printPreview.printer
printer = self._printer
if printer is None:
# printer was not selected
# return a renderer without adjusting the viewbox
if sys.version < '3.0':
import cStringIO as StringIO
imgData = StringIO.StringIO()
else:
from io import StringIO
imgData = StringIO()
self.saveGraph(imgData, fileFormat='svg')
imgData.flush()
imgData.seek(0)
svgData = imgData.read()
imgData = None
svgRenderer = qt.QSvgRenderer()
svgRenderer._svgRawData = svgData
svgRenderer._svgRendererData = qt.QXmlStreamReader(svgData)
if not svgRenderer.load(svgRenderer._svgRendererData):
raise RuntimeError("Cannot interpret svg data")
return svgRenderer
# we have what is to be printed
if sys.version < '3.0':
import cStringIO as StringIO
imgData = StringIO.StringIO()
else:
from io import StringIO
imgData = StringIO()
self.saveGraph(imgData, fileFormat='svg')
imgData.flush()
imgData.seek(0)
svgData = imgData.read()
imgData = None
svgRenderer = qt.QSvgRenderer()
#svgRenderer = PlotWindow.PlotWindow.getSvgRenderer(self)
# we have to specify the bounding box
config = self.getPrintConfiguration()
width = config['width']
height = config['height']
xOffset = config['xOffset']
yOffset = config['yOffset']
units = config['units']
keepAspectRatio = config['keepAspectRatio']
dpix = printer.logicalDpiX()
dpiy = printer.logicalDpiY()
# get the available space
availableWidth = printer.width()
availableHeight = printer.height()
# convert the offsets to dpi
if units.lower() in ['inch', 'inches']:
xOffset = xOffset * dpix
yOffset = yOffset * dpiy
if width is not None:
width = width * dpix
if height is not None:
height = height * dpiy
elif units.lower() in ['cm', 'centimeters']:
xOffset = (xOffset/2.54) * dpix
yOffset = (yOffset/2.54) * dpiy
if width is not None:
width = (width/2.54) * dpix
if height is not None:
height = (height/2.54) * dpiy
else:
# page units
xOffset = availableWidth * xOffset
yOffset = availableHeight * yOffset
if width is not None:
width = availableWidth * width
if height is not None:
height = availableHeight * height
availableWidth -= xOffset
availableHeight -= yOffset
if width is not None:
if (availableWidth + 0.1) < width:
txt = "Available width %f is less than requested width %f" % \
(availableWidth, width)
raise ValueError(txt)
availableWidth = width
if height is not None:
if (availableHeight + 0.1) < height:
txt = "Available height %f is less than requested height %f" % \
(availableHeight, height)
raise ValueError(txt)
availableHeight = height
if keepAspectRatio:
#get the aspect ratio
widget = self.getWidgetHandle()
if widget is None:
# does this make sense?
graphWidth = availableWidth
graphHeight = availableHeight
else:
graphWidth = float(widget.width())
graphHeight = float(widget.height())
graphRatio = graphHeight / graphWidth
# that ratio has to be respected
bodyWidth = availableWidth
bodyHeight = availableWidth * graphRatio
if bodyHeight > availableHeight:
bodyHeight = availableHeight
bodyWidth = bodyHeight / graphRatio
else:
bodyWidth = availableWidth
bodyHeight = availableHeight
body = qt.QRectF(xOffset,
yOffset,
bodyWidth,
bodyHeight)
# this does not work if I set the svgData before
svgRenderer.setViewBox(body)
svgRenderer._viewBox = body
if not sys.version.startswith("2"):
svgData = svgData.encode(encoding="utf-8",
errors="replace")
svgRenderer._svgRawData = svgData
svgRenderer._svgRendererData = qt.QXmlStreamReader(svgData)
if not svgRenderer.load(svgRenderer._svgRendererData):
raise RuntimeError("Cannot interpret svg data")
return svgRenderer
def test():
w = ScanWindow()
x = numpy.arange(1000.)
y = 10 * x + 10000. * numpy.exp(-0.5*(x-500)*(x-500)/400)
w.addCurve(x, y, legend="dummy", replot=True, replace=True)
w.resetZoom()
app.lastWindowClosed.connect(app.quit)
w.show()
app.exec_()
if __name__ == "__main__":
test()
app = None
|