Ejemplo n.º 1
0
def shiftBilinear(img, shift):
    """
    Shift an array like  scipy.ndimage.interpolation.shift(input, shift, mode="wrap", order="infinity")
    :param input: 2d numpy array
    :param shift: 2-tuple of float
    :return: shifted image

    """
    shape = img.shape
    x = numpy.zeros((shape[0] * shape[1], 2), numpy.float)
    x[:,0] = shift[0] + numpy.outer(numpy.arange(shape[0]), numpy.ones(shape[1])).reshape(-1)
    x[:,1] = shift[1] + numpy.outer(numpy.ones(shape[0]), numpy.arange(shape[1])).reshape(-1)
    shifted = SpecfitFuns.interpol([numpy.arange(shape[0]),
                                    numpy.arange(shape[1])], img, x)
    shifted.shape = shape[0], shape[1]
    return shifted
Ejemplo n.º 2
0
def shiftBilinear(img, shift):
    """
    Shift an array like  scipy.ndimage.interpolation.shift(input, shift, mode="wrap", order="infinity")
    :param input: 2d numpy array
    :param shift: 2-tuple of float
    :return: shifted image

    """
    shape = img.shape
    x = numpy.zeros((shape[0] * shape[1], 2), numpy.float)
    x[:, 0] = shift[0] + numpy.outer(numpy.arange(shape[0]),
                                     numpy.ones(shape[1])).reshape(-1)
    x[:, 1] = shift[1] + numpy.outer(numpy.ones(shape[0]),
                                     numpy.arange(shape[1])).reshape(-1)
    shifted = SpecfitFuns.interpol(
        [numpy.arange(shape[0]),
         numpy.arange(shape[1])], img, x)
    shifted.shape = shape[0], shape[1]
    return shifted
 def slit(self,pars,x):
     """
     Function to calulate slit width and knife edge cut
     """
     return 0.5*SpecfitFuns.slit(pars,x)
 def stepUp(self,pars,x):
     """
     Error function like.
     """
     return 0.5*SpecfitFuns.upstep(pars,x)
 def stepDown(self,pars,x):
     """
     Complementary error function like.
     """
     return 0.5*SpecfitFuns.downstep(pars,x)
 def hypermet(self,pars,x):
     """
     Default hypermet function
     """
     return SpecfitFuns.ahypermet(pars, x, 15, 0)
Ejemplo n.º 7
0
    def _getStripBackground(self, x=None, y=None):
        #this makes the assumption x are equally spaced
        #and I should build a spline if that is not the case
        #but I do not want to put a dependency on SciPy
        if y is not None:
            ywork = y
        else:
            ywork = self._y

        if x is not None:
            xwork = x
        else:
            xwork = self._x

        n=len(xwork)
        #loop for anchors
        anchorslist = []
        if self._fitConfiguration['fit']['stripanchorsflag']:
            if self._fitConfiguration['fit']['stripanchorslist'] is not None:
                oldShape = xwork.shape
                ravelled = xwork
                ravelled.shape = -1
                for channel in self._fitConfiguration['fit']['stripanchorslist']:
                    if channel <= ravelled[0]:continue
                    index = numpy.nonzero(ravelled >= channel)
                    if len(index):
                        index = min(index)
                        if index > 0:
                            anchorslist.append(index)
                ravelled.shape = oldShape

        #work with smoothed data
        ysmooth = self._getSmooth(xwork, ywork)
        
        #SNIP algorithm
        if self._fitConfiguration['fit']['stripalgorithm'] in ["SNIP", 1]:
            if DEBUG:
                print("CALCULATING SNIP")
            if len(anchorslist) == 0:
                anchorslist = [0, len(ysmooth)-1]
            anchorslist.sort()
            result = 0.0 * ysmooth
            lastAnchor = 0
            width = self._fitConfiguration['fit']['snipwidth']
            for anchor in anchorslist:
                if (anchor > lastAnchor) and (anchor < len(ysmooth)):
                    result[lastAnchor:anchor] =\
                            SpecfitFuns.snip1d(ysmooth[lastAnchor:anchor], width, 0)
                    lastAnchor = anchor
            if lastAnchor < len(ysmooth):                
                result[lastAnchor:] =\
                        SpecfitFuns.snip1d(ysmooth[lastAnchor:], width, 0)
            return result
        
        #strip background
        niter = self._fitConfiguration['fit']['stripiterations']
        if niter > 0:
            if DEBUG:
                print("CALCULATING STRIP")
                print("iterations = ", niter)
                print("constant   = ",
                      self._fitConfiguration['fit']['stripconstant'])
                print("width      = ",
                      self._fitConfiguration['fit']['stripwidth'])
                print("anchors    = ", anchorslist)
            result=SpecfitFuns.subac(ysmooth,
                                  self._fitConfiguration['fit']['stripconstant'],
                                  niter,
                                  self._fitConfiguration['fit']['stripwidth'],
                                  anchorslist)
            if niter > 1000:
                #make sure to get something smooth
                result = SpecfitFuns.subac(result,
                                  self._fitConfiguration['fit']['stripconstant'],
                                  500,1,
                                  anchorslist)
            else:
                #make sure to get something smooth but with less than
                #500 iterations
                result = SpecfitFuns.subac(result,
                                  self._fitConfiguration['fit']['stripconstant'],
                                  int(self._fitConfiguration['fit']['stripwidth']*2),
                                  1,
                                  anchorslist)
        else:
            if DEBUG:
                print("NO STRIP, NO SNIP")
            result     = numpy.zeros(ysmooth.shape, numpy.float) + min(ysmooth)

        return result
Ejemplo n.º 8
0
        self.okButton.clicked.connect(self.accept)

    def getParameters(self):
        parametersDict = self.parametersWidget.getParameters()
        return parametersDict

    def setParameters(self, ddict):
        return self.parametersWidget.setParameters(ddict)


if __name__ == "__main__":
    app = qt.QApplication([])
    if len(sys.argv) > 1:
        from PyMca5.PyMcaIO import specfilewrapper as specfile
        sf = specfile.Specfile(sys.argv[1])
        scan = sf[0]
        data = scan.data()
        energy = data[0, :]
        spectrum = data[1, :]
        w = XASNormalizationDialog(None, spectrum, energy=energy)
    else:
        from PyMca5 import SpecfitFuns
        noise = numpy.random.randn(1500.)
        x = 8000. + numpy.arange(1500.)
        y = SpecfitFuns.upstep([100, 8500., 50], x)
        w = XASNormalizationDialog(None, y + numpy.sqrt(y)* noise, energy=x)
    ret=w.exec_()
    if ret:
        print(w.getParameters())

Ejemplo n.º 9
0
    def getParameters(self):
        parametersDict = self.parametersWidget.getParameters()
        return parametersDict

    def setParameters(self, ddict):
        return self.parametersWidget.setParameters(ddict)

    def setSpectrum(self, energy, mu):
        self.parametersWidget.setData(mu, energy=energy)


if __name__ == "__main__":
    app = qt.QApplication([])
    if len(sys.argv) > 1:
        from PyMca5.PyMcaIO import specfilewrapper as specfile
        sf = specfile.Specfile(sys.argv[1])
        scan = sf[0]
        data = scan.data()
        energy = data[0, :]
        spectrum = data[1, :]
        w = XASNormalizationDialog(None, spectrum, energy=energy)
    else:
        from PyMca5 import SpecfitFuns
        noise = numpy.random.randn(1500)
        x = 8000. + numpy.arange(1500.)
        y = SpecfitFuns.upstep([100, 8500., 50], x)
        w = XASNormalizationDialog(None, y + numpy.sqrt(y) * noise, energy=x)
    ret = w.exec_()
    if ret:
        print(w.getParameters())
Ejemplo n.º 10
0
    def fftAlignment(self):
        curves = self.getMonotonicCurves()
        nCurves = len(curves)
        if nCurves < 2:
            raise ValueError("At least 2 curves needed")
            return

        # get legend of active curve
        try:
            activeCurveLegend = self.getActiveCurve()[2]
            if activeCurveLegend is None:
                activeCurveLegend = curves[0][2]
            for curve in curves:
                if curve[2] == activeCurveLegend:
                    activeCurve = curve
                    break
        except:
            activeCurve = curves[0]

        # apply between graph limits
        x0, y0 = activeCurve[0:2]
        xmin, xmax =self.getGraphXLimits()

        for curve in curves:
            xmax = float(min(xmax, curve[0][-1]))
            xmin = float(max(xmin, curve[0][0]))

        idx = numpy.nonzero((x0 >= xmin) & (x0 <= xmax))[0]
        x0 = numpy.take(x0, idx)
        y0 = numpy.take(y0, idx)

        #make sure values are regularly spaced
        xi = numpy.linspace(x0[0], x0[-1], len(idx)).reshape(-1, 1)
        yi = SpecfitFuns.interpol([x0], y0, xi, y0.min())
        x0 = xi * 1
        y0 = yi * 1

        y0.shape = -1
        fft0 = numpy.fft.fft(y0)
        y0.shape = -1, 1
        x0.shape = -1, 1
        nChannels = x0.shape[0]

        # built a couple of temporary array of spectra for handy access
        shiftList = []
        curveList = []
        i = 0
        for idx in range(nCurves):
            x, y, legend, info = curves[idx][0:4]

            if x.size != x0.size:
                needInterpolation = True
            elif numpy.allclose(x, x0):
                # no need for interpolation
                needInterpolation = False
            else:
                needInterpolation = True

            if needInterpolation:
                # we have to interpolate
                x.shape = -1
                y.shape = -1
                xi = x0[:] * 1
                y = SpecfitFuns.interpol([x], y, xi, y0.min())
                x = xi

            y.shape = -1
            i += 1

            # now calculate the shift
            ffty = numpy.fft.fft(y)

            if numpy.allclose(fft0, ffty):
                shiftList.append(0.0)
            else:
                shift = numpy.fft.ifft(fft0 * ffty.conjugate()).real
                shift2 = numpy.zeros(shift.shape, dtype=shift.dtype)
                m = shift2.size//2
                shift2[m:] = shift[:-m]
                shift2[:m] = shift[-m:]
                threshold = 0.80*shift2.max()
                #threshold = shift2.mean()
                idx = numpy.nonzero(shift2 > threshold)[0]
                #print("max indices = %d" % (m - idx))
                shift = (shift2[idx] * idx/shift2[idx].sum()).sum()
                #print("shift = ", shift - m, "in x units = ", (shift - m) * (x[1]-x[0]))

                # shift the curve
                shift = (shift - m) * (x[1]-x[0])
                x.shape = -1
                y = numpy.fft.ifft(numpy.exp(-2.0*numpy.pi*numpy.sqrt(numpy.complex(-1))*\
                                numpy.fft.fftfreq(len(x), d=x[1]-x[0])*shift)*ffty)
                y = y.real
                y.shape = -1
            curveList.append([x, y, legend + "SHIFT", False, False])
        curveList[-1][-2] = True
        curveList[-1][-1] = False
        x, y, legend, replot, replace = curveList[0]
        self.addCurve(x, y, legend=legend, replot=True, replace=True)
        for i in range(1, len(curveList)):
            x, y, legend, replot, replace = curveList[i]
            self.addCurve(x,
                          y,
                          legend=legend,
                          info=None,
                          replot=replot,
                          replace=False)
        return