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
|
#/*##########################################################################
# Copyright (C) 2004-2014 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.
#
#############################################################################*/
__author__ = "V.A. Sole - ESRF Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
"""
A Stack plugin is a module that will be automatically added to the PyMca stack windows
in order to perform user defined operations on the data stack.
These plugins will be compatible with any stack window that provides the functions:
#data related
getStackDataObject
getStackData
getStackInfo
setStack
#images related
addImage
removeImage
replaceImage
#mask related
setSelectionMask
getSelectionMask
#displayed curves
getActiveCurve
getGraphXLimits
getGraphYLimits
#information method
stackUpdated
selectionMaskUpdated
"""
import numpy
import logging
_logger = logging.getLogger(__name__)
try:
from PyMca5 import StackPluginBase
from PyMca5.PyMcaGui import CalculationThread
except ImportError:
_logger.warning("XASStackNormalizationPlugin importing bases from somewhere else")
from . import StackPluginBase
from . import CalculationThread
from PyMca5.PyMcaGui import PyMcaQt as qt
from PyMca5.PyMcaGui import StackPluginResultsWindow
from PyMca5.PyMcaPhysics.xas import XASNormalization
from PyMca5.PyMcaGui.physics.xas import XASNormalizationWindow
class XASStackNormalizationPlugin(StackPluginBase.StackPluginBase):
def __init__(self, stackWindow, **kw):
if _logger.getEffectiveLevel() == logging.DEBUG:
StackPluginBase.pluginBaseLogger.setLevel(logging.DEBUG)
StackPluginBase.StackPluginBase.__init__(self, stackWindow, **kw)
self.methodDict = {}
text = "Replace current stack by a normalized one."
function = self.XASNormalize
info = text
icon = None
self.methodDict["XANES Normalization"] =[function,
info,
icon]
self.__methodKeys = ["XANES Normalization"]
self.widget = None
self.imageWidget = None
#Methods implemented by the plugin
def stackUpdated(self):
if self.widget is not None:
self.widget.close()
self.widget = None
def selectionMaskUpdated(self):
if self.imageWidget is None:
return
if self.imageWidget.isHidden():
return
mask = self.getStackSelectionMask()
self.imageWidget.setSelectionMask(mask)
def stackClosed(self):
if self.imageWidget is not None:
self.imageWidget.close()
if self.widget is not None:
self.widget.close()
def getMethods(self):
return self.__methodKeys
def getMethodToolTip(self, name):
return self.methodDict[name][1]
def getMethodPixmap(self, name):
return self.methodDict[name][2]
def applyMethod(self, name):
return self.methodDict[name][0]()
# own stuff
def mySlot(self, ddict):
_logger.debug("mySlot %s %s", ddict['event'], ddict.keys())
if ddict['event'] == "selectionMaskChanged":
self.setStackSelectionMask(ddict['current'])
elif ddict['event'] == "addImageClicked":
self.addImage(ddict['image'], ddict['title'])
elif ddict['event'] == "removeImageClicked":
self.removeImage(ddict['title'])
elif ddict['event'] == "replaceImageClicked":
self.replaceImage(ddict['image'], ddict['title'])
elif ddict['event'] == "resetSelection":
self.setStackSelectionMask(None)
def XASNormalize(self):
stack = self.getStackDataObject()
if not isinstance(stack.data, numpy.ndarray):
text = "This method does not work with dynamically loaded stacks"
raise TypeError(text)
activeCurve = self.getActiveCurve()
if activeCurve in [None, []]:
return
x, spectrum, legend, info = activeCurve
if self.widget is None:
self.widget = XASNormalizationWindow.XASNormalizationDialog(None,
spectrum, energy=x)
else:
oldParameters = self.widget.getParameters()
oldEnergy = self.widget.parametersWidget.energy
oldEMin = oldEnergy.min()
oldEMax = oldEnergy.max()
self.widget.setData(spectrum, energy=x)
if abs(oldEMin - x.min()) < 1:
if abs(oldEMax - x.max()) < 1:
self.widget.setParameters(oldParameters)
ret = self.widget.exec()
if ret:
parameters = self.widget.getParameters()
# TODO: this dictionary adaptation should be made
# by the configuration
if parameters['auto_edge']:
edge = None
else:
edge = parameters['edge_energy']
energy = x
pre_edge_regions = parameters['pre_edge']['regions']
post_edge_regions = parameters['post_edge']['regions']
algorithm ='polynomial'
algorithm_parameters = {}
algorithm_parameters['pre_edge_order'] = parameters['pre_edge']\
['polynomial']
algorithm_parameters['post_edge_order'] = parameters['post_edge']\
['polynomial']
result = self.__replaceStackByXASNormalizedData(stack,
energy=energy,
edge=edge,
pre_edge_regions=pre_edge_regions,
post_edge_regions=post_edge_regions,
algorithm=algorithm,
algorithm_parameters=algorithm_parameters)
if result[0] == 'Exception':
# exception occurred
raise Exception(result[1], result[2], result[3])
else:
edges, jumps, errors = result
images, names = self.getStackROIImagesAndNames()
edges.shape = images[0].shape
jumps.shape = images[0].shape
errors.shape = images[0].shape
self.setStack(stack)
if self.imageWidget is None:
self.imageWidget = StackPluginResultsWindow.StackPluginResultsWindow(\
usetab=False,profileselection=True)
self.imageWidget.buildAndConnectImageButtonBox()
qt = StackPluginResultsWindow.qt
self.imageWidget.sigMaskImageWidgetSignal.connect(self.mySlot)
self.methodDict["Show Images"] =[self._showImageWidget,
"Show calculated jump and edge position images",
None]
self.__methodKeys.append("Show Images")
self.imageWidget.setStackPluginResults([jumps, errors, edges],
image_names=['Jump',
'Errors',
'Edge Position'])
self._showImageWidget()
def __replaceStackByXASNormalizedData(self, *var, **kw):
self._progress = 0.0
thread = CalculationThread.CalculationThread(\
calculation_method=self.replaceStackByXASNormalizedData,
calculation_vars=var,
calculation_kw=kw)
thread.start()
CalculationThread.waitingMessageDialog(thread,
message="Please wait. Calculation going on.",
parent=self.widget,
modal=True,
update_callback=self._waitingCallback)
return thread.result
def _waitingCallback(self):
ddict = {}
ddict['message'] = "Calculation Progress = %d %%" % self._progress
return ddict
def _showImageWidget(self):
if self.imageWidget is None:
return
#Show
self.imageWidget.show()
self.imageWidget.raise_()
#update
self.selectionMaskUpdated()
def replaceStackByXASNormalizedData(self,
stack,
energy=None,
edge=None,
pre_edge_regions=None,
post_edge_regions=None,
algorithm='polynomial',
algorithm_parameters=None):
"""
Performs an in place replacement of a set of spectra by a set of
normalized spectra.
"""
mcaIndex = -1
if hasattr(stack, "info") and hasattr(stack, "data"):
actualData = stack.data
mcaIndex = stack.info.get('McaIndex', -1)
else:
actualData = stack
if not isinstance(actualData, numpy.ndarray):
raise TypeError("Currently this method only supports numpy arrays")
# Take a data view
oldShape = actualData.shape
data = actualData[:]
DONE = 0
if mcaIndex in [-1, len(data.shape)-1]:
data.shape = -1, oldShape[-1]
edges = numpy.zeros(data.shape[0], numpy.float32)
jumps = numpy.zeros(data.shape[0], numpy.float32)
errors = numpy.zeros(data.shape[0], numpy.float32)
total = 0.01 * data.shape[0]
for i in range(data.shape[0]):
self._progress = i / total
try:
ene, spe, ed, jmp = XASNormalization.XASNormalization(data[i,:],
energy=energy,
edge=edge,
pre_edge_regions=pre_edge_regions,
post_edge_regions=post_edge_regions,
algorithm=algorithm,
algorithm_parameters=algorithm_parameters)[0:4]
except:
# what to do?
# for the data is clear (set to 0)
# for the jump 0 is also a good compromise
# for the edge?
data[i, :] = 0
errors[i] = 1
jumps[i] = 0
edges[i] = 0
continue
if not DONE:
c0 = (numpy.nonzero(energy >= (ed + pre_edge_regions[0][0]))[0]).min()
c1 = (numpy.nonzero(energy <= (ed + post_edge_regions[-1][1]))[-1]).max()
c1 += 1
DONE = True
if ((spe.max()-spe.min()) > 10.) or (jmp < 0):
data[i, :] = 0.0
# should I give some useless values?
edges[i] = 0.0
# perhaps the case of large jump should be kept ...
jumps[i] = 0.0
elif 0:
# this approach removed
data[i,:c0] = spe[c0]
data[i, c0:c1] = spe[c0:c1]
if c1 < data.shape[1]:
data[i, c1:] = spe[c1]
edges[i] = ed
jumps[i] = jmp
else:
# it seems more appropriate to set the channels below and
# above limits to 0 than to the corresponding limits of the region
data[i,:c0] = 0.0
data[i, c0:c1] = spe[c0:c1]
data[i, c1:] = 0.0
edges[i] = ed
jumps[i] = jmp
self._progress = 100
data.shape = oldShape
elif mcaIndex == 0:
data.shape = oldShape[0], -1
edges = numpy.zeros(data.shape[-1], numpy.float32)
jumps = numpy.zeros(data.shape[-1], numpy.float32)
errors = numpy.zeros(data.shape[-1], numpy.float32)
total = 0.01 * data.shape[-1]
for i in range(data.shape[-1]):
self._progress = i / total
try:
ene, spe, ed, jmp = XASNormalization.XASNormalization(data[:, i],
energy=energy,
edge=edge,
pre_edge_regions=pre_edge_regions,
post_edge_regions=post_edge_regions,
algorithm=algorithm,
algorithm_parameters=algorithm_parameters)[0:4]
except:
# what to do?
# for the data is clear (set to 0)
# for the jump 0 is also a good compromise
# for the edge?
data[:, i] = 0
jumps[i] = 0
edges[i] = 0
errors[i] = 1
continue
if not DONE:
c0 = (numpy.nonzero(energy >= (ed + pre_edge_regions[0][0]))[0]).min()
c1 = (numpy.nonzero(energy <= (ed + post_edge_regions[-1][1]))[-1]).max()
c1 += 1
DONE = True
if ((spe.max()-spe.min()) > 10.) or (jmp < 0):
data[:, i] = 0.0
# should I give some useless values?
edges[i] = 0.0
jumps[i] = 0.0
else:
# it seems more appropriate to set the channels below and
# above limits to 0 than to the corresponding limits of the region
data[:c0, i] = 0.0
data[c0:c1, i] = spe[c0:c1]
if c1 < data.shape[0]:
data[c1:, i] = 0.0
edges[i] = ed
jumps[i] = jmp
self._progress = 100
data.shape = oldShape
else:
raise ValueError("Unsupported 1D index %d" % mcaIndex)
return edges, jumps, errors
MENU_TEXT = "XAS Stack Normalization"
def getStackPluginInstance(stackWindow, **kw):
ob = XASStackNormalizationPlugin(stackWindow)
return ob
|