Exemplo n.º 1
0
 def description_sanity(self):
   """
     Check sanity of 'description'
   """
   gf = fuf.GaussFit1d()
   gff = gf + gf
   self.assertEqual(gff.description(), "Gaussian(No. 1) + Gaussian(No. 2)", "Wrong description: " + gff.description())
Exemplo n.º 2
0
  def Convonlve_sanity(self):    
      
    from PyAstronomy import funcFit as fuf
    import numpy as np 
    
      
    class Broad(fuf.GaussFit1d):  
      def convolve(self, x, y):
        tmp = self.evaluate(x)
        tmp/=np.sum(tmp) * self["A"]
        return np.convolve(tmp, y, mode='same')

    resp = Broad()
    pm = fuf.GaussFit1d() + fuf.PolyFit1d(1)

    m = fuf.ConvolutionModel(resp, pm)
    
    m["A_Gaussian"] = 1.0
    m["sig_Gaussian"] = 1.0
    m["sig_Response"] = 1.0
    m["A_Response"] = 1.0

    x = np.linspace(-5, 5, 101)
    yy = m.evaluate(x)

    pm["A_Gaussian"] = 1.0
    pm["sig_Gaussian"] = np.sqrt(2)*1.0
    
    self.assertAlmostEqual(np.max(np.abs(m.evaluate(x) - pm.evaluate(x))), 0.0, delta=1e-12, \
                           msg="ConvolutionModel and GaussFit1d deviate more than expected.")
Exemplo n.º 3
0
    def saveState_sanity(self):
        gf = fuf.GaussFit1d()
        gf.assignValue({"A": 1, "mu": 2, "off": 3, "sig": 4, "lin": 5.0})
        gf.setRestriction({"A": [0, 10], "off": [None, 7.8]})
        gf.thaw(["A", "mu", "lin"])
        dat = gf.saveState("saveState.tmp", clobber=True)

        gf2 = fuf.GaussFit1d()
        gf2.restoreState("saveState.tmp")
        self.assertEqual(gf2.parameters(), gf.parameters())
        self.assertEqual(gf2.getRestrictions(), gf.getRestrictions())
        self.assertEqual(gf2.frozenParameters(), gf.frozenParameters())

        gf2.restoreState(dat)
        self.assertEqual(gf2.parameters(), gf.parameters())
        self.assertEqual(gf2.getRestrictions(), gf.getRestrictions())
        self.assertEqual(gf2.frozenParameters(), gf.frozenParameters())
Exemplo n.º 4
0
 def parameterAssignment1_sanity(self):
   gf = fuf.GaussFit1d()
   origVars = ["A", "mu", "sig", "off", "lin"]
   vals     = [1.0, 2.0,  3.0,   4.0,    5.0]
   for k, v in zip(origVars, vals):
     gf[k] = v
   for k, v in zip(origVars, vals):
     self.assertEquals(v, gf[k])
   gf.assignValue(dict(zip(origVars, numpy.zeros(len(origVars)))))
   self.assertEquals(numpy.sum(list(gf.parameters().values())), 0.0)
Exemplo n.º 5
0
 def combine1_sanity(self):
   gf = fuf.GaussFit1d()
   gff = gf + gf + gf
   for p in six.iterkeys(gff.parameters()):
     gff[p] = numpy.random.random()
     gff.thaw(p); gff.thaw([p,p])
     gff.freeze(p); gff.freeze([p,p])
     gff.setRestriction({p:[None, None]})
   for prop in ["A", "mu", "sig", "off", "lin"]:
     for c in [1,2,3]:
       gff[prop, "Gaussian", c] = numpy.random.random()
       s = (prop, "Gaussian", c)
       gff.thaw(s); gff.thaw([s,s])
       gff.freeze(s); gff.freeze([s,s])
       gff.setRestriction({s:[None, 10.]})
Exemplo n.º 6
0
 def sanity_IAGVFitExample(self):
   """
     Checking example of IAGVFit
   """
   from PyAstronomy import pyaGui
   from PyAstronomy import funcFit as fuf
   import numpy as np
   
   # Data for the plot
   x = np.linspace(5000., 5010, 200)
   y = np.ones(len(x))
   yerr = np.ones(len(x)) * 0.01
   y += np.random.normal(0., 0.01, len(x))
   
   gf = fuf.GaussFit1d()
   gf["A"] = -0.3
   gf["mu"] = 5004.
   gf["sig"] = 0.2
   y += gf.evaluate(x)
   
   # Create interactive fitter
   igv = pyaGui.IAGVFit(x, y, yerr=yerr, mode="gauss")
Exemplo n.º 7
0
 def sanity_modelExplorer(self):
   """
     Check sanity of the model explorer example
   """
   import numpy as np
   from PyAstronomy import pyaGui
   from PyAstronomy import funcFit as fuf
   
   # Create a Gaussian fitting instance
   # and set some parameters
   gg = fuf.GaussFit1d()
   gg["A"] = 1.0
   gg["sig"] = 0.5
   
   # Let A and mu be free during a fit
   gg.thaw(["A", "mu"])
   
   # Create some artificial data
   x = np.linspace(-2., 2., 100)
   yerr = np.ones(len(x))*0.01
   y = gg.evaluate(x) + np.random.normal(0.,0.01, len(x))
   
   # In order to use the interactive explorer, you
   # need a class, which plots the model. The default
   # class for this purpose is "FFModelPlotFit", which
   # needs the x and y values. Optionally, you can specify
   # errors via `yerr`. Depending on the setting for
   # "withResiduals", the residuals will be shown or not.
   mp = pyaGui.FFModelPlotFit(x, y, yerr=yerr, withResiduals=True)
   
   # Use the function ffmodelExplorer (note the lowercase letters)
   # to create an instance of the FFModelExplorer class, which
   # needs to be given the model (gg in this case) and
   # the plotter (and fitter), which we created above.
   # 
   g = pyaGui.ffmodelExplorer(gg, mp)
Exemplo n.º 8
0
def broadGaussFast(x, y, sigma, edgeHandling=None, maxsig=None):
    """
    Apply Gaussian broadening. 

    This function broadens the given data using a Gaussian
    kernel.

    Parameters
    ----------
    x, y : arrays
        The abscissa and ordinate of the data.
    sigma : float
        The width (i.e., standard deviation) of the Gaussian
        profile used in the convolution.
    edgeHandling : string, {None, "firstlast"}, optional
        Determines the way edges will be handled. If None,
        nothing will be done about it. If set to "firstlast",
        the spectrum will be extended by using the first and
        last value at the start or end. Note that this is
        not necessarily appropriate. The default is None.
    maxsig : float, optional
        The extent of the broadening kernel in terms of
        standard deviations. By default, the Gaussian broadening
        kernel will be extended over the entire given spectrum,
        which can cause slow evaluation in the case of large spectra.
        A reasonable choice could, e.g., be five.  

    Returns
    -------
    Broadened data : array
        The input data convolved with the Gaussian
        kernel.
    """
    # Check whether x-axis is linear
    dxs = x[1:] - x[0:-1]
    if abs(max(dxs) - min(dxs)) > np.mean(dxs) * 1e-6:
        raise (PE.PyAValError(
            "The x-axis is not equidistant, which is required.",
            where="broadGaussFast"))

    if maxsig is None:
        lx = len(x)
    else:
        lx = int(((sigma * maxsig) / dxs[0]) * 2.0) + 1
    # To preserve the position of spectral lines, the broadening function
    # must be centered at N//2 - (1-N%2) = N//2 + N%2 - 1
    nx = (np.arange(lx, dtype=np.int) - sum(divmod(lx, 2)) + 1) * dxs[0]
    gf = fuf.GaussFit1d()
    gf["A"] = 1.0
    gf["sig"] = sigma
    e = gf.evaluate(nx)
    # This step ensured that the
    e /= np.sum(e)

    if edgeHandling == "firstlast":
        nf = len(y)
        y = np.concatenate((np.ones(nf) * y[0], y, np.ones(nf) * y[-1]))
        result = np.convolve(y, e, mode="same")[nf:-nf]
    elif edgeHandling is None:
        result = np.convolve(y, e, mode="same")
    else:
        raise (PE.PyAValError("Invalid value for `edgeHandling`: " +
                              str(edgeHandling),
                              where="broadGaussFast",
                              solution="Choose either 'firstlast' or None"))
    return result