Ejemplo n.º 1
0
def read_gaussfit(gaussfitfile, proflen):
    """
    read_gaussfitfile(gaussfitfile, proflen):
        Read a Gaussian-fit file as created by the output of pygaussfit.py.
            The input parameters are the name of the file and the number of
            bins to include in the resulting template file.  A numpy array
            of that length is returned.
    """

    phass = []
    ampls = []
    fwhms = []

    for line in open(gaussfitfile):
        if line.lstrip().startswith("const"):
            const = float(line.split()[2])
        if line.lstrip().startswith("phas"):
            phass.append(float(line.split()[2]))
        if line.lstrip().startswith("ampl"):
            ampls.append(float(line.split()[2]))
        if line.lstrip().startswith("fwhm"):
            fwhms.append(float(line.split()[2]))

    if not (len(phass) == len(ampls) == len(fwhms)):
        print "Number of phases, amplitudes, and FWHMs are not the same in '%s'!" % gaussfitfile
        return 0.0

    phass = np.asarray(phass)
    ampls = np.asarray(ampls)
    fwhms = np.asarray(fwhms)

    def tfunc(x, *args):
        #print type(args), len(args)
        ncomps = len(args) / 3
        phass = list(args[:ncomps])
        ampls = list(args[ncomps:2 * ncomps])
        fwhms = list(args[2 * ncomps:3 * ncomps])
        #const = args[-1]
        #y=const
        y = 0

        for ampl, phas, fwhm in zip(ampls, phass, fwhms):
            sigma = fwhm / 2.35482
            mean = phas % 1.0
            y += ampl * np.exp(-(x - mean)**2 /
                               (2 * sigma**2)) / (sigma * (2 * np.pi)**0.5)

        return y

    prof_params = list(phass) + list(ampls) + list(fwhms) + [const]
    global template_function
    template_function = lambda x: tfunc(x, *prof_params)

    template = np.zeros(proflen, dtype='d')
    for ii in range(len(ampls)):
        template += ampls[ii] * gaussian_profile(proflen, phass[ii], fwhms[ii])
    return template
Ejemplo n.º 2
0
 def plot_gaussians(self, params):
     plt.subplot(211)
     plt.cla()
     # Re-plot the original profile
     plt.plot(self.phases, self.profile, c='black', lw=3, alpha=0.3)
     plt.xlabel('Pulse Phase')
     plt.ylabel('Pulse Amplitude')
     DC = params[0]
     # Plot the individual gaussians
     for ii in range(self.numgaussians):
         phase, FWHM, amp = params[1+ii*3:4+ii*3]
         plt.plot(self.phases, DC + amp*gaussian_profile(self.proflen, phase, FWHM))
Ejemplo n.º 3
0
 def plot_gaussians(self, params):
     plt.subplot(211)
     plt.cla()
     # Re-plot the original profile
     plt.plot(self.phases, self.profile, c='black', lw=3, alpha=0.3)
     plt.xlabel('Pulse Phase')
     plt.ylabel('Pulse Amplitude')
     DC = params[0]
     # Plot the individual gaussians
     for ii in range(self.numgaussians):
         phase, FWHM, amp = params[1+ii*3:4+ii*3]
         plt.plot(self.phases, DC + amp*gaussian_profile(self.proflen, phase, FWHM))
Ejemplo n.º 4
0
    def make_gaussian(self, nbins):
        """Return an aray of length 'nbins' containing the gaussian component.

           Inputs:
               nbins: The number of bins in the profile
 
           Output:
               gaussian: Array of data
           
        """
        # Create an array for the Gaussian profile
        gaussian = self.amp*self.fwhm/2*np.sqrt(np.pi/np.log(2)) * \
                        psr_utils.gaussian_profile(nbins,self.phs,self.fwhm)
        return gaussian
Ejemplo n.º 5
0
    def make_gaussian(self, nbins):
        """Return an aray of length 'nbins' containing the gaussian component.

           Inputs:
               nbins: The number of bins in the profile

           Output:
               gaussian: Array of data

        """
        # Create an array for the Gaussian profile
        gaussian = self.amp*self.fwhm/2*np.sqrt(np.pi/np.log(2)) * \
                        psr_utils.gaussian_profile(nbins,self.phs,self.fwhm)
        return gaussian
Ejemplo n.º 6
0
def read_gaussfit(gaussfitfile, Nprofbins):
    """
    read_gaussfitfile(gaussfitfile, proflen):
        Read a Gaussian-fit file as created by the output of pygaussfit.py.
            The input parameters are the name of the file and the number of
            bins to include in the resulting template file.  A numpy array
            of that length is returned.
    """

    phass = []
    ampls = []
    fwhms = []

    for line in open(gaussfitfile):
        if line.lstrip().startswith("const"):
            const = float(line.split()[2])
        if line.lstrip().startswith("phas"):
            phass.append(float(line.split()[2]))
        if line.lstrip().startswith("ampl"):
            ampls.append(float(line.split()[2]))
        if line.lstrip().startswith("fwhm"):
            fwhms.append(float(line.split()[2]))

    if not (len(phass) == len(ampls) == len(fwhms)):
        print "Number of phases, amplitudes, and FWHMs are not the same in '%s'!" % gaussfitfile
        return 0.0

    phass = np.asarray(phass)
    ampls = np.asarray(ampls)
    fwhms = np.asarray(fwhms)

    # Find max value and apply corrections to amplitudes.
    neg_amp_params = list(phass) + list(-1.0 * ampls) + list(fwhms)
    y_find_max = lambda x: tfunc(x, *neg_amp_params)
    max_amp_phase = fmin(y_find_max, 0.5,
                         disp=0)  # Silently find max value (fmin with -1*func)
    ampls /= -1 * y_find_max(max_amp_phase)

    prof_params = list(phass) + list(ampls) + list(fwhms)
    global template_function
    template_function = lambda x: tfunc(x, *prof_params)

    template = np.zeros(Nprofbins, dtype='d')
    for ii in range(len(ampls)):
        template += ampls[ii] * gaussian_profile(Nprofbins, phass[ii],
                                                 fwhms[ii])

    return template
Ejemplo n.º 7
0
def gen_gaussians(params, N):
    """
    gen_gaussians(params, N):
        Return a model of a DC-component + M gaussians
            params is a sequence of 1+M*3 values
                the first value is the DC component.  Each remaining
                group of three represents the gaussians phase (0-1),
                FWHM (0-1), and amplitude (>0.0).
            N is the number of points in the model.
    """
    numgaussians = (len(params)-1)/3
    model = Num.zeros(N, dtype='d') + params[0]
    for ii in range(numgaussians):
        phase, FWHM, amp = params[1+ii*3:4+ii*3]
        model += amp * gaussian_profile(N, phase, FWHM)
    return model
Ejemplo n.º 8
0
def gen_gaussians(params, N):
    """
    gen_gaussians(params, N):
        Return a model of a DC-component + M gaussians
            params is a sequence of 1+M*3 values
                the first value is the DC component.  Each remaining
                group of three represents the gaussians phase (0-1),
                FWHM (0-1), and amplitude (>0.0).
            N is the number of points in the model.
    """
    numgaussians = (len(params)-1)/3
    model = Num.zeros(N, dtype='d') + params[0]
    for ii in range(numgaussians):
        phase, FWHM, amp = params[1+ii*3:4+ii*3]
        model += amp * gaussian_profile(N, phase, FWHM)
    return model
Ejemplo n.º 9
0
def make_gaussians_presto(params, nbins):
    """
    Produce one or more Gaussian profiles with the specified parameters.

    Parameters
    ----------
    params : array_like
        The parameters of the desried Gaussian profiles.  The first entry is
        the offset from a zero baseline and the remaining entries are
        amplitudes, full widths at half max, and phases, i.e.
        params = [offset, amp_1, fwhm_1, phase_1, amp_2, fwhm_2, phase_2, etc.]
    nbins : int
        The number of bins in the profile

    Returns
    -------
    gaussians : ndarray, shape(nbins,)
        
    """
    # Determine the number of Gaussian profiles to make
    ngaussians = (len(params) - 1) / 3
    # Set up some lists to store the individual parameters
    amplitudes = []
    fwhms = []
    phases = []
    # Get each parameter and store it
    offset = params[0]
    for nn in xrange(ngaussians):
        amplitudes.append(params[1 + 3 * nn])
        fwhms.append(params[1 + 3 * nn + 1])
        phases.append(params[1 + 3 * nn + 2])

    # Create an array for the Gaussian profile
    gaussians = N.zeros(nbins) + offset
    # Add each individual Gaussian to the full profile
    for a, w, p in zip(amplitudes, fwhms, phases):
        gaussians += a * w / 2 * N.sqrt(N.pi / N.log(2)) * PU.gaussian_profile(
            nbins, p, w)

    return gaussians
Ejemplo n.º 10
0
def make_gaussians_presto(params, nbins):
    """
    Produce one or more Gaussian profiles with the specified parameters.

    Parameters
    ----------
    params : array_like
        The parameters of the desried Gaussian profiles.  The first entry is
        the offset from a zero baseline and the remaining entries are
        amplitudes, full widths at half max, and phases, i.e.
        params = [offset, amp_1, fwhm_1, phase_1, amp_2, fwhm_2, phase_2, etc.]
    nbins : int
        The number of bins in the profile

    Returns
    -------
    gaussians : ndarray, shape(nbins,)
        
    """
    # Determine the number of Gaussian profiles to make
    ngaussians = (len(params) - 1)/3
    # Set up some lists to store the individual parameters
    amplitudes = []
    fwhms      = []
    phases     = []
    # Get each parameter and store it
    offset = params[0]
    for nn in xrange(ngaussians):
        amplitudes.append(params[1+3*nn])
        fwhms.append(params[1+3*nn+1])
        phases.append(params[1+3*nn+2])
        
    # Create an array for the Gaussian profile
    gaussians = N.zeros(nbins) + offset
    # Add each individual Gaussian to the full profile
    for a,w,p in zip(amplitudes, fwhms, phases):
        gaussians += a*w/2*N.sqrt(N.pi/N.log(2))*PU.gaussian_profile(nbins,p,w)

    return gaussians
Ejemplo n.º 11
0
def read_gaussfitfile(gaussfitfile, proflen):
    """
    read_gaussfitfile(gaussfitfile, proflen):
        Read a Gaussian-fit file as created by the output of pygaussfit.py.
            The input parameters are the name of the file and the number of
            bins to include in the resulting template file.  A numpy array
            of that length is returned.

    Originally from PRESTO's psr_utils.py
    """
    phass = []
    ampls = []
    fwhms = []
    const = 0
    for line in open(gaussfitfile):
        if line.lstrip().startswith("phas"):
            phass.append(float(line.split()[2]))
        if line.lstrip().startswith("ampl"):
            ampls.append(float(line.split()[2]))
        if line.lstrip().startswith("fwhm"):
            fwhms.append(float(line.split()[2]))
        if line.lstrip().startswith("const"):
            const = float(line.split()[2])
    if not (len(phass) == len(ampls) == len(fwhms)):
        print "Number of phases, amplitudes, and FWHMs are not the same in '%s'!" % gaussfitfile
        return 0.0
    phass = np.asarray(phass)
    ampls = np.asarray(ampls)
    fwhms = np.asarray(fwhms)

    gauss_data = np.zeros((len(ampls), proflen))
    for ii in range(len(ampls)):
        data = ampls[ii] * psr_utils.gaussian_profile(proflen, phass[ii],
                                                      fwhms[ii])
        dc = np.min(data)
        const += dc
        gauss_data[ii] = data - dc
    return gauss_data, const
Ejemplo n.º 12
0
def read_gaussfitfile(gaussfitfile, proflen):
    """
    read_gaussfitfile(gaussfitfile, proflen):
        Read a Gaussian-fit file as created by the output of pygaussfit.py.
            The input parameters are the name of the file and the number of
            bins to include in the resulting template file.  A numpy array
            of that length is returned.

    Originally from PRESTO's psr_utils.py
    """
    phass = []
    ampls = []
    fwhms = []
    const = 0
    for line in open(gaussfitfile):
        if line.lstrip().startswith("phas"):
            phass.append(float(line.split()[2]))
        if line.lstrip().startswith("ampl"):
            ampls.append(float(line.split()[2]))
        if line.lstrip().startswith("fwhm"):
            fwhms.append(float(line.split()[2]))
        if line.lstrip().startswith("const"):
            const = float(line.split()[2])
    if not (len(phass) == len(ampls) == len(fwhms)):
        print "Number of phases, amplitudes, and FWHMs are not the same in '%s'!"%gaussfitfile
        return 0.0
    phass = np.asarray(phass)
    ampls = np.asarray(ampls)
    fwhms = np.asarray(fwhms)
    
    gauss_data = np.zeros((len(ampls), proflen))
    for ii in range(len(ampls)):
        data = ampls[ii]*psr_utils.gaussian_profile(proflen, phass[ii], fwhms[ii])
        dc = np.min(data)
        const += dc
        gauss_data[ii] = data - dc
    return gauss_data, const
Ejemplo n.º 13
0
    print("Creating a summed profile of length %d bins using DM = %f" %
          (numbins, DM))

    # Read the template profile or create an appropriate Gaussian
    if templatefilenm is not None:
        template = psr_utils.read_profile(templatefilenm)
        # Resample the template profile to have the correct number of bins (if required)
        if not len(template) == numbins:
            oldlen = len(template)
            template = sinc_interp.periodic_interp(template, numbins)[::oldlen]
    else:
        if gaussfitfile is not None:
            template = psr_utils.read_gaussfitfile(gaussfitfile, numbins)
        else:
            template = psr_utils.gaussian_profile(numbins, 0.0, gaussianwidth)
    # Normalize it
    template -= min(template)
    template /= max(template)
    # Rotate it so that it becomes a "true" template according to FFTFIT
    shift, eshift, snr, esnr, b, errb, ngood = measure_phase(
        template, template)
    template = psr_utils.fft_rotate(template, shift)

    # Determine the off-pulse bins
    if bkgd_vals is not None:
        Pgplot.plotxy(template, labx="Phase bins")
        Pgplot.plotxy(template[bkgd_vals],
                      Num.arange(numbins)[bkgd_vals],
                      line=None,
                      symbol=2,
Ejemplo n.º 14
0
from __future__ import print_function
#>>> print fftfit.__doc__
#This module 'fftfit' is auto-generated with f2py (version:2.13.175-1250).
#Functions:
#  zbrent = zbrent(x1,x2,f1,f2,tol,tmp,pha,nsum)
#  dchisqr = dchisqr(tau,tmp,r,nsum)
#  cprof(y,c,amp,pha,nmax=len(y),nh=(len(c)-1))
#  fccf(amp,pha,shift)
#  ffft(d,npts,isign,ireal)
#  fftfit(prof,s,phi,nmax,shift,eshift,snr,esnr,b,errb,ngood)

import numpy as num
from psr_utils import gaussian_profile, TWOPI
from fftfit import cprof, fftfit

template = gaussian_profile(64, 0.5, 0.1)
c, amp, pha = cprof(template)
#pha.savespace()
pha1 = pha[0]
pha = num.fmod(pha - num.arange(1, len(pha) + 1) * pha1, TWOPI)
for phs in [0.1, 0.3, 0.7]:
    prof = gaussian_profile(64, phs, 0.1) + num.random.standard_normal(64)
    shift, eshift, snr, esnr, b, errb, ngood = fftfit(prof, amp, pha)
    print("True phs = %f, measured phs = %f +/- %f" %
          (phs, shift / len(prof), eshift / len(prof)))
Ejemplo n.º 15
0
        #        delay, which is based on the topocentric frequency fold_pfd.hifreq
        sumsubdelays = (psr_utils.delay_from_DM(fold_pfd.bestdm, sumsubfreqs) -
                        psr_utils.delay_from_DM(fold_pfd.bestdm, fold_pfd.hifreq))/SECPERDAY
    else:
        fold_pfd.subfreqs = Num.asarray([0.0])
        sumsubfreqs = Num.asarray([0.0])
        sumsubdelays = Num.asarray([0.0])

    # Read the template profile
    if templatefilenm is not None:
        template = psr_utils.read_profile(templatefilenm, normalize=1)
    else:
        if (gaussfitfile):
            template = psr_utils.read_gaussfitfile(gaussfitfile, fold_pfd.proflen)
        else:
            template = psr_utils.gaussian_profile(fold_pfd.proflen, 0.0, gaussianwidth)
        template = template / max(template)
    #from Pgplot import *
    #plotxy(template)
    #closeplot()
    # Determine the Telescope used
    if (not fold.topo):
        obs = '@'  # Solarsystem Barycenter
    else:
        try: obs = scopes[fold_pfd.telescope.split()[0]]
        except KeyError:  print "Unknown telescope!!!"

    # Read the polyco file (if required)
    if (fold.psr and fold.topo):
        if (fold_pfd.__dict__.has_key("polycos") and
            not fold_pfd.polycos==0):
Ejemplo n.º 16
0
    else:
        fold_pfd.subfreqs = Num.asarray([0.0])
        sumsubfreqs = Num.asarray([0.0])
        sumsubdelays = Num.asarray([0.0])
        subdelays2 = Num.asarray([0.0])
        sumsubdelays_phs = Num.asarray([0.0])

    # Read the template profile
    if templatefilenm is not None:
        template = psr_utils.read_profile(templatefilenm, normalize=1)
    else:
        if (gaussfitfile):
            template = psr_utils.read_gaussfitfile(gaussfitfile,
                                                   fold_pfd.proflen)
        else:
            template = psr_utils.gaussian_profile(fold_pfd.proflen, 0.0,
                                                  gaussianwidth)
        template = template / max(template)
    #from Pgplot import *
    #plotxy(template)
    #closeplot()
    # Determine the Telescope used
    if (not fold.topo):
        obs = '@'  # Solarsystem Barycenter
    else:
        try:
            if t2format:
                obs = scopes2[fold_pfd.telescope.split()[0]]
            else:
                obs = scopes[fold_pfd.telescope.split()[0]]
        except KeyError:
            sys.stderr.write("Unknown telescope!!! : " + fold_pfd.telescope)
Ejemplo n.º 17
0
from __future__ import print_function
#>>> print fftfit.__doc__
#This module 'fftfit' is auto-generated with f2py (version:2.13.175-1250).
#Functions:
#  zbrent = zbrent(x1,x2,f1,f2,tol,tmp,pha,nsum)
#  dchisqr = dchisqr(tau,tmp,r,nsum)
#  cprof(y,c,amp,pha,nmax=len(y),nh=(len(c)-1))
#  fccf(amp,pha,shift)
#  ffft(d,npts,isign,ireal)
#  fftfit(prof,s,phi,nmax,shift,eshift,snr,esnr,b,errb,ngood)

import numpy as num
from psr_utils import gaussian_profile, TWOPI
from fftfit import cprof, fftfit

template = gaussian_profile(64, 0.5, 0.1)
c,amp,pha = cprof(template)
#pha.savespace()
pha1 = pha[0]
pha = num.fmod(pha-num.arange(1,len(pha)+1)*pha1,TWOPI)
for phs in [0.1, 0.3, 0.7]:
    prof = gaussian_profile(64, phs, 0.1)+num.random.standard_normal(64)
    shift,eshift,snr,esnr,b,errb,ngood = fftfit(prof,amp,pha)
    print("True phs = %f, measured phs = %f +/- %f" % (phs, shift/len(prof),eshift/len(prof)))
Ejemplo n.º 18
0
            SEFD = float(a)

    print "Creating a summed profile of length %d bins using DM = %f"%(numbins, DM)

    # Read the template profile or create an appropriate Gaussian
    if templatefilenm is not None:
        template = psr_utils.read_profile(templatefilenm)
        # Resample the template profile to have the correct number of bins (if required)
        if not len(template)==numbins:
            oldlen = len(template)
            template = sinc_interp.periodic_interp(template, numbins)[::oldlen]
    else:
        if gaussfitfile is not None:
            template = psr_utils.read_gaussfitfile(gaussfitfile, numbins)
        else:
            template = psr_utils.gaussian_profile(numbins, 0.0, gaussianwidth)
    # Normalize it
    template -= min(template)
    template /= max(template)
    # Rotate it so that it becomes a "true" template according to FFTFIT
    shift,eshift,snr,esnr,b,errb,ngood = measure_phase(template, template)
    template = psr_utils.fft_rotate(template, shift)
        
    # Determine the off-pulse bins
    if bkgd_vals is not None:
        Pgplot.plotxy(template, labx="Phase bins")
        Pgplot.plotxy(template[bkgd_vals], Num.arange(numbins)[bkgd_vals],
                      line=None, symbol=2, color='red')
        Pgplot.closeplot()
        offpulse_inds = bkgd_vals
        onpulse_inds = set(Num.arange(numbins)) - set(bkgd_vals)
Ejemplo n.º 19
0
                                                       write=options.addphase)

    if not options.unbinned:
        if not HAVE_PRESTO:
            raise ImportError, 'Presto tools not found; binned fitting not available!'
        # Read template profile
        if (options.template is not None):
            template = psr_utils.read_profile(options.template, normalize=1)
        else:
            if (options.gauss is not None):
                template = psr_utils.read_gaussfitfile(options.gauss,
                                                       options.nbins)
            else:
                print >> sys.stderr, "WARNING: Using single gaussian template!"
                gaussianwidth = 0.1  # DEFAULT
                template = psr_utils.gaussian_profile(options.nbins, 0.0,
                                                      gaussianwidth)
            template = template / template.max()
    else:
        if options.gauss is not None:
            template = LCTemplate(template=options.gauss)
        elif options.template is not None:
            template = LCTemplate(template=options.template)
        elif options.edf:
            print 'EDF option selected; will use EDF for template.'
            template = None
        else:  # default is kernel density estimator
            print 'No template provided -- Please build one with itemplate.py and supply it!'
            sys.exit(1)

    if options.unbinned:
        if options.edf: