Example #1
0
File: imv.py Project: sldion/DNACC
def squeeze(a):
    "Returns a with any ones from the shape of a removed"
    a = Numeric.asarray(a)
    b = Numeric.asarray(a.shape)
    val = Numeric.reshape(a,
                          tuple(Numeric.compress(Numeric.not_equal(b, 1), b)))
    return val
Example #2
0
    def test_feedback_mode(self):
        l = 250
        r = 300
        b = 200
        t = 350

        stimulus = VisionEgg.MoreStimuli.Target2D(
            position=(l, b),
            anchor='lowerleft',
            size=(r - l, t - b),
        )

        self.ortho_viewport.parameters.stimuli = [stimulus]

        gl.glFeedbackBuffer(1000, gl.GL_3D)

        gl.glRenderMode(gl.GL_FEEDBACK)
        self.ortho_viewport.draw()
        feedback_buffer = gl.glRenderMode(gl.GL_RENDER)

        sent_verts = [(l, b, 0), (r, b, 0), (r, t, 0), (l, t, 0)]
        recv_verts = feedback_buffer[0][1]

        self.failUnless(
            len(sent_verts) == len(recv_verts),
            'feedback received wrong number of verts')

        for s, r in zip(sent_verts, recv_verts):
            s = Numeric.asarray(s)
            r = Numeric.asarray(r)
            diff = abs(s - r)
            err = sum(diff)
            self.failUnless(err < 1e-10, 'verts changed')
Example #3
0
    def test_ve3d_mixed_transforms(self):
        import VisionEgg.ThreeDeeMath as ve3d

        l = 250
        r = 300
        b = 200
        t = 350
        
        stimulus = VisionEgg.MoreStimuli.Target2D(
            position=(l,b),
            anchor='lowerleft',
            size=(r-l,t-b),
            )

        # M mimics the projection matrix (modelview matrix is effectively identity)
        M = self.ortho_viewport.parameters.projection.get_matrix().copy()
        M = ve3d.TransformMatrix(M)
        M.translate(10,20,0)
        self.ortho_viewport.parameters.projection.translate(10,20,0)
        
        self.ortho_viewport.parameters.stimuli = [ stimulus ]

        gl.glFeedbackBuffer(1000,gl.GL_3D)
        
        gl.glRenderMode( gl.GL_FEEDBACK )
        self.ortho_viewport.draw()
        feedback_buffer = gl.glRenderMode( gl.GL_RENDER )

        sent_verts = [(l,b,0),
                      (r,b,0),
                      (r,t,0),
                      (l,t,0)]
        gl_recv_verts = feedback_buffer[0][1]

        clip_coords = M.transform_vertices( sent_verts )
        norm_device = ve3d.normalize_homogeneous_rows(clip_coords)
        ve3d_recv_verts = self.ortho_viewport.norm_device_2_window(norm_device)

        # check x and y coords
        for g,v in zip(gl_recv_verts,ve3d_recv_verts):
            g=Numeric.asarray(g[:2])
            v=Numeric.asarray(v[:2])
            diff = abs(g-v)
            err = sum(diff)
            self.failUnless( err < 1e-10,
                             'VisionEgg.ThreeDeeMath calculated window position wrong')
        
        # check z coord
        for g,v in zip(gl_recv_verts,ve3d_recv_verts):
            err = abs(g[2]-v[2])
            self.failUnless( err < 1e-10,
                             'VisionEgg.ThreeDeeMath calculated window depth wrong')
Example #4
0
    def test_ve3d_mixed_transforms(self):
        import VisionEgg.ThreeDeeMath as ve3d

        l = 250
        r = 300
        b = 200
        t = 350

        stimulus = VisionEgg.MoreStimuli.Target2D(
            position=(l, b),
            anchor='lowerleft',
            size=(r - l, t - b),
        )

        # M mimics the projection matrix (modelview matrix is effectively identity)
        M = self.ortho_viewport.parameters.projection.get_matrix().copy()
        M = ve3d.TransformMatrix(M)
        M.translate(10, 20, 0)
        self.ortho_viewport.parameters.projection.translate(10, 20, 0)

        self.ortho_viewport.parameters.stimuli = [stimulus]

        gl.glFeedbackBuffer(1000, gl.GL_3D)

        gl.glRenderMode(gl.GL_FEEDBACK)
        self.ortho_viewport.draw()
        feedback_buffer = gl.glRenderMode(gl.GL_RENDER)

        sent_verts = [(l, b, 0), (r, b, 0), (r, t, 0), (l, t, 0)]
        gl_recv_verts = feedback_buffer[0][1]

        clip_coords = M.transform_vertices(sent_verts)
        norm_device = ve3d.normalize_homogeneous_rows(clip_coords)
        ve3d_recv_verts = self.ortho_viewport.norm_device_2_window(norm_device)

        # check x and y coords
        for g, v in zip(gl_recv_verts, ve3d_recv_verts):
            g = Numeric.asarray(g[:2])
            v = Numeric.asarray(v[:2])
            diff = abs(g - v)
            err = sum(diff)
            self.failUnless(
                err < 1e-10,
                'VisionEgg.ThreeDeeMath calculated window position wrong')

        # check z coord
        for g, v in zip(gl_recv_verts, ve3d_recv_verts):
            err = abs(g[2] - v[2])
            self.failUnless(
                err < 1e-10,
                'VisionEgg.ThreeDeeMath calculated window depth wrong')
Example #5
0
def eq (a, b):
    "Test if the two sequences are essentially equal"
    seq_a = has_length(a)
    seq_b = has_length(b)
    if (seq_a and not seq_b) or (not seq_a and seq_b):
        raise ValueError(
            "trying to compare a sequence and non-sequence: a=%r b=%r" %
            (a,b))
    aa = Numeric.asarray(a)
    ab = Numeric.asarray(b)
    if aa.shape != ab.shape:
        raise ValueError("sequences have different shapes:\na%s=%r\nb%s=%r" %
                         (aa.shape, a, ab.shape, b))
    return Numeric.allclose(aa,ab)
Example #6
0
    def __init__(self, data, xvals=None, yvals=None, **keyw):
        """GridData constructor.

        Arguments:

            'data' -- a 2-d array with dimensions (numx,numy)
            'xvals' -- a 1-d array with dimension (numx)
            'yvals' -- a 1-d array with dimension (numy)

        'data' is meant to hold the values of a function f(x,y) tabulated
        on a grid of points, such that 'data[i,j] == f(xvals[i],
        yvals[j])'.  These data are written to a datafile as 'x y f(x,y)'
        triplets that can be used by gnuplot's splot command.  Thus if you
        have three arrays in the above format and a Gnuplot instance
        called g, you can plot your data by typing for example:

            g.splot(Gnuplot.GridData(data,xvals,yvals))

        If 'xvals' and/or 'yvals' are omitted, integers (starting with
        0) are used for that coordinate.  The data are written to a
        temporary file; no copy of the data is kept in memory.

        """

        data = Numeric.asarray(data, Numeric.Float)
        assert len(data.shape) == 2
        (numx, numy) = data.shape

        if xvals is None:
            xvals = Numeric.arange(numx)
        else:
            xvals = Numeric.asarray(xvals, Numeric.Float)
            assert len(xvals.shape) == 1
            assert xvals.shape[0] == numx

        if yvals is None:
            yvals = Numeric.arange(numy)
        else:
            yvals = Numeric.asarray(yvals, Numeric.Float)
            assert len(yvals.shape) == 1
            assert yvals.shape[0] == numy

        set = Numeric.transpose(
            Numeric.array(
                (Numeric.transpose(Numeric.resize(xvals, (numy, numx))),
                 Numeric.resize(yvals, (numx, numy)),
                 data)), (1,2,0))

        apply(File.__init__, (self, TempArrayFile(set)), keyw)
Example #7
0
    def main(self):
        while 1:
            if self.dataReady("inbox"):
                address, arguments = self.recv("inbox")
                address = address.split("/")[-1]
                if address == "On":
                    self.on = True
                    noteNumber, frequency, velocity = arguments
                    self.frequency = frequency
                    self.amplitude = velocity
                elif address == "Off":
                    self.on = False

            if self.dataReady("event"):
                self.recv("event")
                if self.on:
                    while self.channel.get_queue() == None:
                        sample, phase = self.generateSample(
                            self.frequency, self.amplitude, self.phase)
                        self.phase = phase
                        sample *= 2**15 - 1
                        sample = sample.astype("int16")
                        sample = Numeric.asarray(sample)
                        self.channel.queue(pygame.sndarray.make_sound(sample))
                self.lastSendTime += self.period
                self.scheduleAbs("Send", self.lastSendTime + self.period)
            if not self.anyReady():
                self.pause()
Example #8
0
 def main(self):
     while 1:
         if self.dataReady("inbox"):
             address, arguments = self.recv("inbox")
             address = address.split("/")[-1]
             if address == "On":
                 self.on = True
                 noteNumber, frequency, velocity = arguments
                 self.frequency = frequency
                 self.amplitude = velocity
             elif address == "Off":
                 self.on = False
             
         if self.dataReady("event"):
             self.recv("event")
             if self.on:
                 while self.channel.get_queue() == None:
                     sample, phase = self.generateSample(self.frequency,
                                                         self.amplitude,
                                                         self.phase)
                     self.phase = phase
                     sample *= 2**15-1
                     sample = sample.astype("int16")
                     sample = Numeric.asarray(sample)
                     self.channel.queue(pygame.sndarray.make_sound(sample))
             self.lastSendTime += self.period
             self.scheduleAbs("Send", self.lastSendTime + self.period)
         if not self.anyReady():
             self.pause()
Example #9
0
File: FFT.py Project: IanReid/ABFGP
def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti, 
             work_function=fftpack.cfftf, fft_cache = _fft_cache ):
    a = Numeric.asarray(a)

    if n == None: n = a.shape[axis]

    try:
        wsave = fft_cache[n]
    except(KeyError):
        wsave = init_function(n)
        fft_cache[n] = wsave

    if a.shape[axis] != n:
        s = list(a.shape)
        if s[axis] > n:
            index = [slice(None)]*len(s)
            index[axis] = slice(0,n)
            a = a[index]
        else:
            index = [slice(None)]*len(s)
            index[axis] = slice(0,s[axis])
            s[axis] = n
            z = Numeric.zeros(s, a.typecode())
            z[index] = a
            a = z

    if axis != -1:
        a = Numeric.swapaxes(a, axis, -1)
    r = work_function(a, wsave)
    if axis != -1:
        r = Numeric.swapaxes(r, axis, -1)
    return r
Example #10
0
File: FFT.py Project: IanReid/ABFGP
def _raw_fftnd(a, s=None, axes=None, function=fft):
    a = Numeric.asarray(a)
    s, axes = _cook_nd_args(a, s, axes)
    itl = range(len(axes))
    itl.reverse()
    for ii in itl:
        a = function(a, n=s[ii], axis=axes[ii])
    return a
Example #11
0
def _raw_fftnd(a, s=None, axes=None, function=fft):
    a = Numeric.asarray(a)
    s, axes = _cook_nd_args(a, s, axes)
    itl = range(len(axes))
    itl.reverse()
    for ii in itl:
        a = function(a, n=s[ii], axis=axes[ii])
    return a
Example #12
0
    def test_ve3d_simple(self):
        import VisionEgg.ThreeDeeMath as ve3d

        l = 250
        r = 300
        b = 200
        t = 350

        sent_verts = [(l, b, 0), (r, b, 0), (r, t, 0), (l, t, 0)]

        recv_verts = self.ortho_viewport.eye_2_window(sent_verts)
        for s, r in zip(sent_verts, recv_verts):
            s = Numeric.asarray(s[:2])  # only testing 2D
            r = Numeric.asarray(r[:2])  # only testing 2D
            diff = abs(s - r)
            err = sum(diff)
            self.failUnless(err < 1e-10, 'verts changed')
Example #13
0
def gradient (lambdas, keys, dirs):
    expectations = compute_expectations(lambdas, keys, dirs)

    g = []
    for f in keys:
        g.append(expectations[f]-constraints[f]+(lambdas[keys.index(f)]/.5))
        #g.append(constraints[f]-expectations[f]-(lambdas[keys.index(f)]/.5))

    return Num.asarray(g)
Example #14
0
    def __init__(self, *set, **keyw):
        """Construct a Data object from a numeric array.

        Create a Data object (which is a type of PlotItem) out of one
        or more Float Python Numeric arrays (or objects that can be
        converted to a Float Numeric array).  If the routine is passed
        one array, the last index ranges over the values comprising a
        single data point (e.g., [x, y, and sigma]) and the rest of
        the indices select the data point.  If the routine is passed
        more than one array, they must have identical shapes, and then
        each data point is composed of one point from each array.
        I.e., 'Data(x,x**2)' is a PlotItem that represents x squared
        as a function of x.  For the output format, see the comments
        in ArrayFile.

        The array is first written to a temporary file, then that file
        is plotted.  Keyword arguments recognized (in addition to those
        recognized by PlotItem):

            cols=<tuple> -- write only the specified columns from each
                            data point to the file.  Since cols is
                            used by python, the columns should be
                            numbered in the python style (starting
                            from 0), not the gnuplot style (starting
                            from 1).

        The data are immediately written to the temp file; no copy is
        kept in memory.

        """

        if len(set) == 1:
            # set was passed as a single structure
            set = Numeric.asarray(set, Numeric.Float)
        else:
            # set was passed column by column (for example, Data(x,y))
            set = Numeric.asarray(set, Numeric.Float)
            dims = len(set.shape)
            # transpose so that the last index selects x vs. y:
            set = Numeric.transpose(set, (dims-1,) + tuple(range(dims-1)))
        if keyw.has_key('cols') and keyw['cols'] is not None:
            set = Numeric.take(set, keyw['cols'], -1)
            del keyw['cols']
        apply(File.__init__, (self, TempArrayFile(set)), keyw)
Example #15
0
def plot(*items, **keyw):
    """plot data using gnuplot through Gnuplot.

    This command is roughly compatible with old Gnuplot plot command.
    It is provided for backwards compatibility with the old functional
    interface only.  It is recommended that you use the new
    object-oriented Gnuplot interface, which is much more flexible.

    It can only plot Numeric array data.  In this routine an NxM array
    is plotted as M-1 separate datasets, using columns 1:2, 1:3, ...,
    1:M.

    Limitations:

        - If persist is not available, the temporary files are not
          deleted until final python cleanup.

    """

    newitems = []
    for item in items:
        # assume data is an array:
        item = Numeric.asarray(item, Numeric.Float)
        dim = len(item.shape)
        if dim == 1:
            newitems.append(Data(item[:, Numeric.NewAxis], with='lines'))
        elif dim == 2:
            if item.shape[1] == 1:
                # one column; just store one item for tempfile:
                newitems.append(Data(item, with='lines'))
            else:
                # more than one column; store item for each 1:2, 1:3, etc.
                tempf = TempArrayFile(item)
                for col in range(1, item.shape[1]):
                    newitems.append(File(tempf, using=(1,col+1), with='lines'))
        else:
            raise DataException("Data array must be 1 or 2 dimensional")
    items = tuple(newitems)
    del newitems

    if keyw.has_key('file'):
        g = Gnuplot()
        # setup plot without actually plotting (so data don't appear
        # on the screen):
        g._add_to_queue(items)
        g.hardcopy(keyw['file'])
        # process will be closed automatically
    elif test_persist():
        g = Gnuplot(persist=1)
        apply(g.plot, items)
        # process will be closed automatically
    else:
        g = Gnuplot()
        apply(g.plot, items)
        # prevent process from being deleted:
        _gnuplot_processes.append(g)
Example #16
0
 def get_data(self):
     """
   Reads the data from the EPICS mca record.  Returns the data with Mca.get_data().
   """
     nuse = self.pvs['data']['nuse'].getw()
     nchans = max(nuse, 1)
     data = self.pvs['data']['val'].getw(count=nchans)
     data = Numeric.asarray(data)
     Mca.Mca.set_data(self, data)
     return Mca.Mca.get_data(self)
Example #17
0
 def get_data(self):
    """
    Reads the data from the EPICS mca record.  Returns the data with Mca.get_data().
    """
    nuse = self.pvs['data']['nuse'].getw()
    nchans = max(nuse,1)
    data = self.pvs['data']['val'].getw(count=nchans)
    data = Numeric.asarray(data)
    Mca.Mca.set_data(self, data)
    return Mca.Mca.get_data(self)
Example #18
0
def float_array(m):
    """Return the argument as a Numeric array of type at least 'Float32'.

    Leave 'Float64' unchanged, but upcast all other types to
    'Float32'.  Allow also for the possibility that the argument is a
    python native type that can be converted to a Numeric array using
    'Numeric.asarray()', but in that case don't worry about
    downcasting to single-precision float.

    """

    try:
        # Try Float32 (this will refuse to downcast)
        return Numeric.asarray(m, Numeric.Float32)
    except TypeError:
        # That failure might have been because the input array was
        # of a wider data type than Float32; try to convert to the
        # largest floating-point type available:
        return Numeric.asarray(m, Numeric.Float)
Example #19
0
def float_array(m):
    """Return the argument as a Numeric array of type at least 'Float32'.

    Leave 'Float64' unchanged, but upcast all other types to
    'Float32'.  Allow also for the possibility that the argument is a
    python native type that can be converted to a Numeric array using
    'Numeric.asarray()', but in that case don't worry about
    downcasting to single-precision float.

    """

    try:
        # Try Float32 (this will refuse to downcast)
        return Numeric.asarray(m, Numeric.Float32)
    except TypeError:
        # That failure might have been because the input array was
        # of a wider data type than Float32; try to convert to the
        # largest floating-point type available:
        return Numeric.asarray(m, Numeric.Float)
Example #20
0
    def test_ve3d_simple(self):
        import VisionEgg.ThreeDeeMath as ve3d

        l = 250
        r = 300
        b = 200
        t = 350
        
        sent_verts = [(l,b,0),
                      (r,b,0),
                      (r,t,0),
                      (l,t,0)]

        recv_verts = self.ortho_viewport.eye_2_window(sent_verts)
        for s,r in zip(sent_verts,recv_verts):
            s=Numeric.asarray(s[:2]) # only testing 2D
            r=Numeric.asarray(r[:2]) # only testing 2D
            diff = abs(s-r)
            err = sum(diff)
            self.failUnless( err < 1e-10,
                             'verts changed')
Example #21
0
def fit_gaussian(chans, counts):
   """
   Fits a peak to a Gaussian using a linearizing method
   Returns (amplitude, centroid, fwhm).
   Inputs:
      chans:
         An array of x-axis coordinates, typically channel numbers

      counts:
         An array of y-axis coordinates, typically counts or intensity

   Outputs:
      Returns a tuple(amplitude, centroid, fwhm)
      amplitude:
         The peak height of the Gaussian in y-axis units
      centroid:
         The centroid of the gaussian in x-axis units

      fwhm:
         The Full Width Half Maximum (FWHM) of the fitted peak

   Method:
      Takes advantage of the fact that the logarithm of a Gaussian peak is a
      parabola.  Fits the coefficients of the parabola using linear least
      squares.  This means that the input Y values (counts)  must not be 
      negative.  Any values less than 1 are replaced by 1.
   """
   center = (chans[0] + chans[-1])/2.
   x = Numeric.asarray(chans, Numeric.Float)-center
   y = Numeric.log(Numeric.clip(counts, 1, max(counts)))
   w = Numeric.asarray(counts, Numeric.Float)**2
   w = Numeric.clip(w, 1., max(w))
   fic = polyfitw(x, y, w, 2)
   fic[2] = min(fic[2], -.001)  # Protect against divide by 0
   amplitude = Numeric.exp(fic[0] - fic[1]**2/(4.*fic[2]))
   centroid  = center - fic[1]/(2.*fic[2])
   sigma     = Numeric.sqrt(-1/(2.*fic[2]))
   fwhm      = 2.35482 * sigma
   return amplitude, centroid, fwhm
Example #22
0
def fit_gaussian(chans, counts):
    """
   Fits a peak to a Gaussian using a linearizing method
   Returns (amplitude, centroid, fwhm).
   Inputs:
      chans:
         An array of x-axis coordinates, typically channel numbers

      counts:
         An array of y-axis coordinates, typically counts or intensity

   Outputs:
      Returns a tuple(amplitude, centroid, fwhm)
      amplitude:
         The peak height of the Gaussian in y-axis units
      centroid:
         The centroid of the gaussian in x-axis units

      fwhm:
         The Full Width Half Maximum (FWHM) of the fitted peak

   Method:
      Takes advantage of the fact that the logarithm of a Gaussian peak is a
      parabola.  Fits the coefficients of the parabola using linear least
      squares.  This means that the input Y values (counts)  must not be 
      negative.  Any values less than 1 are replaced by 1.
   """
    center = (chans[0] + chans[-1]) / 2.
    x = Numeric.asarray(chans, Numeric.Float) - center
    y = Numeric.log(Numeric.clip(counts, 1, max(counts)))
    w = Numeric.asarray(counts, Numeric.Float)**2
    w = Numeric.clip(w, 1., max(w))
    fic = polyfitw(x, y, w, 2)
    fic[2] = min(fic[2], -.001)  # Protect against divide by 0
    amplitude = Numeric.exp(fic[0] - fic[1]**2 / (4. * fic[2]))
    centroid = center - fic[1] / (2. * fic[2])
    sigma = Numeric.sqrt(-1 / (2. * fic[2]))
    fwhm = 2.35482 * sigma
    return amplitude, centroid, fwhm
    def Load(self, file_name):
        """
	"""
        t1 = time.time()
	self.data = ms3d_ascii_importer.convert_milkshape( file_name )
	t2 = time.time()
	self._debug("load time of milk:%s:" % (t2 - t1), 2)
	d = self.data["mesh_data"][0]

	material_index = d["material_index"]
	self._debug("material_index:%s" % material_index, 2)


	self.texcoords= Numeric.asarray(d["texcoords"], 'f')
	self.points = Numeric.asarray(d["points"], 'f')
	self.normals = Numeric.asarray(d["normals"], 'f')
	self.indices =  Numeric.asarray(d["indices"], 'i')


        if material_index != -1:
	    m = self.data["materials"][material_index]
	    self._debug("m.material_name:%s" % m.material_name, 2)
	    self._debug("m.diffuse_texture_name:%s" %m.diffuse_texture_name, 2)
	    self._debug("m.alpha_texture_name :%s" %m.alpha_texture_name, 2)
            
            
	    self.image_name =  apply(os.path.join, os.path.split(m.diffuse_texture_name[2:])) 

            #NOTE: FIXME:  materials don't need textures.
            #NOTE: FIXME: there are different textures too.
            
	    self._is_tex = 1
	    #time.sleep(2)
	else:
	    self._is_tex = 0
        
        
	self.skeleton = MilkSkeleton(self.data)
Example #24
0
File: FFT.py Project: IanReid/ABFGP
def real_fftnd(a, s=None, axes=None):
    """real_fftnd(a, s=None, axes=None)

    The n-dimensional discrete Fourier transform of a real array a. A real
    transform as real_fft is performed along the axis specified by the last
    element of axes, then complex transforms as fft are performed along the
    other axes."""
    
    a = Numeric.asarray(a).astype(Numeric.Float)
    s, axes = _cook_nd_args(a, s, axes)
    a = real_fft(a, s[-1], axes[-1])
    for ii in range(len(axes)-1):
        a = fft(a, s[ii], axes[ii])
    return a
Example #25
0
def real_fftnd(a, s=None, axes=None):
    """real_fftnd(a, s=None, axes=None)

    The n-dimensional discrete Fourier transform of a real array a. A real
    transform as real_fft is performed along the axis specified by the last
    element of axes, then complex transforms as fft are performed along the
    other axes."""

    a = Numeric.asarray(a).astype(Numeric.Float)
    s, axes = _cook_nd_args(a, s, axes)
    a = real_fft(a, s[-1], axes[-1])
    for ii in range(len(axes) - 1):
        a = fft(a, s[ii], axes[ii])
    return a
Example #26
0
def inverse_real_fftnd(a, s=None, axes=None):
    """inverse_real_fftnd(a, s=None, axes=None)

    The inverse of real_fftnd. The transform implemented in inverse_fft is
    applied along all axes but the last, then the transform implemented in
    inverse_real_fft is performed along the last axis. As with
    inverse_real_fft, the length of the result along that axis must be
    specified if it is to be odd."""

    a = Numeric.asarray(a).astype(Numeric.Complex)
    s, axes = _cook_nd_args(a, s, axes, invreal=1)
    for ii in range(len(axes) - 1):
        a = inverse_fft(a, s[ii], axes[ii])
    a = inverse_real_fft(a, s[-1], axes[-1])
    return a
Example #27
0
File: FFT.py Project: IanReid/ABFGP
def inverse_real_fftnd(a, s=None, axes=None):
    """inverse_real_fftnd(a, s=None, axes=None)

    The inverse of real_fftnd. The transform implemented in inverse_fft is
    applied along all axes but the last, then the transform implemented in
    inverse_real_fft is performed along the last axis. As with
    inverse_real_fft, the length of the result along that axis must be
    specified if it is to be odd."""
    
    a = Numeric.asarray(a).astype(Numeric.Complex)
    s, axes = _cook_nd_args(a, s, axes, invreal=1)
    for ii in range(len(axes)-1):
        a = inverse_fft(a, s[ii], axes[ii])
    a = inverse_real_fft(a, s[-1], axes[-1])
    return a
Example #28
0
    def Load(self, file_name):
        """
	"""
        t1 = time.time()
        self.data = ms3d_ascii_importer.convert_milkshape(file_name)
        t2 = time.time()
        self._debug("load time of milk:%s:" % (t2 - t1), 2)
        d = self.data["mesh_data"][0]

        material_index = d["material_index"]
        self._debug("material_index:%s" % material_index, 2)

        self.texcoords = Numeric.asarray(d["texcoords"], 'f')
        self.points = Numeric.asarray(d["points"], 'f')
        self.normals = Numeric.asarray(d["normals"], 'f')
        self.indices = Numeric.asarray(d["indices"], 'i')

        if material_index != -1:
            m = self.data["materials"][material_index]
            self._debug("m.material_name:%s" % m.material_name, 2)
            self._debug("m.diffuse_texture_name:%s" % m.diffuse_texture_name,
                        2)
            self._debug("m.alpha_texture_name :%s" % m.alpha_texture_name, 2)

            self.image_name = apply(os.path.join,
                                    os.path.split(m.diffuse_texture_name[2:]))

            #NOTE: FIXME:  materials don't need textures.
            #NOTE: FIXME: there are different textures too.

            self._is_tex = 1
            #time.sleep(2)
        else:
            self._is_tex = 0

        self.skeleton = MilkSkeleton(self.data)
Example #29
0
    def test_feedback_mode(self):
        l = 250
        r = 300
        b = 200
        t = 350
        
        stimulus = VisionEgg.MoreStimuli.Target2D(
            position=(l,b),
            anchor='lowerleft',
            size=(r-l,t-b),
            )
        
        self.ortho_viewport.parameters.stimuli = [ stimulus ]

        gl.glFeedbackBuffer(1000,gl.GL_3D)
        
        gl.glRenderMode( gl.GL_FEEDBACK )
        self.ortho_viewport.draw()
        feedback_buffer = gl.glRenderMode( gl.GL_RENDER )

        sent_verts = [(l,b,0),
                      (r,b,0),
                      (r,t,0),
                      (l,t,0)]
        recv_verts = feedback_buffer[0][1]

        self.failUnless( len(sent_verts) == len(recv_verts),
                         'feedback received wrong number of verts')

        for s,r in zip(sent_verts,recv_verts):
            s=Numeric.asarray(s)
            r=Numeric.asarray(r)
            diff = abs(s-r)
            err = sum(diff)
            self.failUnless( err < 1e-10,
                             'verts changed')
Example #30
0
File: FFT.py Project: IanReid/ABFGP
def inverse_hermite_fft(a, n=None, axis=-1):
    """hermite_fft(a, n=None, axis=-1)
    inverse_hermite_fft(a, n=None, axis=-1)

    These are a pair analogous to real_fft/inverse_real_fft, but for the
    opposite case: here the signal is real in the frequency domain and has
    Hermite symmetry in the time domain. So here it's hermite_fft for which
    you must supply the length of the result if it is to be odd.

    inverse_hermite_fft(hermite_fft(a), len(a)) == a
    within numerical accuracy."""
    
    a = Numeric.asarray(a).astype(Numeric.Float)
    if n == None:
        n = Numeric.shape(a)[axis]
    return Numeric.conjugate(real_fft(a, n, axis))/n
Example #31
0
    def main(self):
        while 1:
            if not pygame.mixer.get_init():
                pygame.mixer.init(self.sampleRate, -16, 1, self.bufferSize)
            else:
                if self.dataReady("inbox"):
                    numpyArray = self.recv("inbox")
                    # Scale to 16 bit int
                    numpyArray *= 2**15-1
                    numpyArray = numpyArray.astype("int16")
                    numericArray = Numeric.asarray(numpyArray)
                    sound = pygame.sndarray.make_sound(numericArray)
                    sound.play()

            if not self.anyReady():
                self.pause()
Example #32
0
def inverse_hermite_fft(a, n=None, axis=-1):
    """hermite_fft(a, n=None, axis=-1)
    inverse_hermite_fft(a, n=None, axis=-1)

    These are a pair analogous to real_fft/inverse_real_fft, but for the
    opposite case: here the signal is real in the frequency domain and has
    Hermite symmetry in the time domain. So here it's hermite_fft for which
    you must supply the length of the result if it is to be odd.

    inverse_hermite_fft(hermite_fft(a), len(a)) == a
    within numerical accuracy."""

    a = Numeric.asarray(a).astype(Numeric.Float)
    if n == None:
        n = Numeric.shape(a)[axis]
    return Numeric.conjugate(real_fft(a, n, axis)) / n
Example #33
0
    def main(self):
        while 1:
            if not pygame.mixer.get_init():
                pygame.mixer.init(self.sampleRate, -16, 1, self.bufferSize)
            else:
                if self.dataReady("inbox"):
                    numpyArray = self.recv("inbox")
                    # Scale to 16 bit int
                    numpyArray *= 2**15 - 1
                    numpyArray = numpyArray.astype("int16")
                    numericArray = Numeric.asarray(numpyArray)
                    sound = pygame.sndarray.make_sound(numericArray)
                    sound.play()

            if not self.anyReady():
                self.pause()
Example #34
0
 def fitrzw(self, przw=None, funct=rzw_dist_model):
    """
    dftvector.fitrzw(przw=None, funct=rzw_dist_model):):
         Fit a model consisting of an arbitrary phase, Fourier
         frequency offset (dr), Fourier f-dot (z), and Fourier
         f-dotdot (w) to dftvector.  Return the best fitting
         parameters in an array of [phase, dr, z, w].  If 'przw'
         is defined it is used as the starting guess for the
         fit.  If 'funct' is defined that is the function that
         is used during the minimization.
    """
    if przw:
       przw = Numeric.asarray(przw) / Numeric.array([1.0, 1.0, 4.0, 20.0])
    else:
       przw = Numeric.array([0.0, 0.0, 0.0, 0.0])
    retval = leastsq(funct, przw, args=(self))
    print(retval[1])
    return retval[0] * Numeric.array([1.0, 1.0, 4.0, 20.0])
Example #35
0
 def fitrzw(self, przw=None, funct=rzw_dist_model):
     """
   dftvector.fitrzw(przw=None, funct=rzw_dist_model):):
        Fit a model consisting of an arbitrary phase, Fourier
        frequency offset (dr), Fourier f-dot (z), and Fourier
        f-dotdot (w) to dftvector.  Return the best fitting
        parameters in an array of [phase, dr, z, w].  If 'przw'
        is defined it is used as the starting guess for the
        fit.  If 'funct' is defined that is the function that
        is used during the minimization.
   """
     if przw:
         przw = Numeric.asarray(przw) / Numeric.array([1.0, 1.0, 4.0, 20.0])
     else:
         przw = Numeric.array([0.0, 0.0, 0.0, 0.0])
     retval = leastsq(funct, przw, args=(self))
     print(retval[1])
     return retval[0] * Numeric.array([1.0, 1.0, 4.0, 20.0])
Example #36
0
File: FFT.py Project: IanReid/ABFGP
def real_fft(a, n=None, axis=-1):
    """real_fft(a, n=None, axis=-1) 

    Will return the n point discrete Fourier transform of the real valued
    array a. n defaults to the length of a. n is the length of the input, not
    the output.

    The returned array will be the nonnegative frequency terms of the
    Hermite-symmetric, complex transform of the real array. So for an 8-point
    transform, the frequencies in the result are [ 0, 1, 2, 3, 4]. The first
    term will be real, as will the last if n is even. The negative frequency
    terms are not needed because they are the complex conjugates of the
    positive frequency terms. (This is what I mean when I say
    Hermite-symmetric.)

    This is most efficient for n a power of two."""

    a = Numeric.asarray(a).astype(Numeric.Float)
    return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftf, _real_fft_cache)
Example #37
0
def real_fft(a, n=None, axis=-1):
    """real_fft(a, n=None, axis=-1) 

    Will return the n point discrete Fourier transform of the real valued
    array a. n defaults to the length of a. n is the length of the input, not
    the output.

    The returned array will be the nonnegative frequency terms of the
    Hermite-symmetric, complex transform of the real array. So for an 8-point
    transform, the frequencies in the result are [ 0, 1, 2, 3, 4]. The first
    term will be real, as will the last if n is even. The negative frequency
    terms are not needed because they are the complex conjugates of the
    positive frequency terms. (This is what I mean when I say
    Hermite-symmetric.)

    This is most efficient for n a power of two."""

    a = Numeric.asarray(a).astype(Numeric.Float)
    return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftf, _real_fft_cache)
Example #38
0
 def rzwinfo(self, przw):
    """
    dftvector.rzwinfo(self, przw):
         Nicely print the conversions of the przw array.
    """
    modprzw = Numeric.asarray(copy(przw[1:]))
    modprzw[0] = (self.r + modprzw[0])
    [f, fd, fdd] = (modprzw / self.T**Numeric.array([1.0, 2.0, 3.0])).tolist()
    [p, pd, pdd] = p_to_f(f, fd, fdd)
    print ""
    print "      Phase (rad) = %.3f" % (przw[0])
    print "      Phase (deg) = %.3f" % (przw[0] * 180.0 / umath.pi)
    print "     Fourier freq = %.3f" % (modprzw[0])
    print "     Fourier fdot = %.5g" % (modprzw[1])
    print "  Fourier fdotdot = %.5g" % (modprzw[2])
    print "   Frequency (Hz) = %.9f" % (f)
    print "      fdot (Hz/s) = %.5g" % (fd)
    print " fdotdot (Hz/s^2) = %.5g" % (fdd)
    print "       Period (s) = %.12f" % (p)
    print "       pdot (s/s) = %.5g" % (pd)
    print "  pdotdot (s/s^2) = %.5g" % (pdd)
    print ""
Example #39
0
 def rzwinfo(self, przw):
    """
    dftvector.rzwinfo(self, przw):
         Nicely print the conversions of the przw array.
    """
    modprzw = Numeric.asarray(copy(przw[1:]))
    modprzw[0] = (self.r + modprzw[0])
    [f, fd, fdd] = (modprzw / self.T**Numeric.array([1.0, 2.0, 3.0])).tolist()
    [p, pd, pdd] = p_to_f(f, fd, fdd)
    print("")
    print("      Phase (rad) = %.3f" % (przw[0]))
    print("      Phase (deg) = %.3f" % (przw[0] * 180.0 / umath.pi))
    print("     Fourier freq = %.3f" % (modprzw[0]))
    print("     Fourier fdot = %.5g" % (modprzw[1]))
    print("  Fourier fdotdot = %.5g" % (modprzw[2]))
    print("   Frequency (Hz) = %.9f" % (f))
    print("      fdot (Hz/s) = %.5g" % (fd))
    print(" fdotdot (Hz/s^2) = %.5g" % (fdd))
    print("       Period (s) = %.12f" % (p))
    print("       pdot (s/s) = %.5g" % (pd))
    print("  pdotdot (s/s^2) = %.5g" % (pdd))
    print("")
Example #40
0
def inverse_fft(a, n=None, axis=-1):
    """inverse_fft(a, n=None, axis=-1) 

    Will return the n point inverse discrete Fourier transform of a.  n
    defaults to the length of a. If n is larger than a, then a will be
    zero-padded to make up the difference. If n is smaller than a, then a will
    be truncated to reduce its size.

    The input array is expected to be packed the same way as the output of
    fft, as discussed in it's documentation.

    This is the inverse of fft: inverse_fft(fft(a)) == a within numerical
    accuracy.

    This is most efficient for n a power of two. This also stores a cache of
    working memory for different sizes of fft's, so you could theoretically
    run into memory problems if you call this too many times with too many
    different n's."""

    a = Numeric.asarray(a).astype(Numeric.Complex)
    if n == None:
        n = Numeric.shape(a)[axis]
    return _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftb, _fft_cache) / n
Example #41
0
File: FFT.py Project: IanReid/ABFGP
def inverse_real_fft(a, n=None, axis=-1):
    """inverse_real_fft(a, n=None, axis=-1)
    
    Will return the real valued n point inverse discrete Fourier transform of
    a, where a contains the nonnegative frequency terms of a Hermite-symmetric
    sequence. n is the length of the result, not the input. If n is not
    supplied, the default is 2*(len(a)-1). If you want the length of the
    result to be odd, you have to say so.

    If you specify an n such that a must be zero-padded or truncated, the
    extra/removed values will be added/removed at high frequencies. One can
    thus resample a series to m points via Fourier interpolation by: a_resamp
    = inverse_real_fft(real_fft(a), m).

    This is the inverse of real_fft:
    inverse_real_fft(real_fft(a), len(a)) == a
    within numerical accuracy."""

    a = Numeric.asarray(a).astype(Numeric.Complex)
    if n == None:
        n = (Numeric.shape(a)[axis] - 1) * 2
    return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftb,
                    _real_fft_cache) / n
Example #42
0
def inverse_real_fft(a, n=None, axis=-1):
    """inverse_real_fft(a, n=None, axis=-1)
    
    Will return the real valued n point inverse discrete Fourier transform of
    a, where a contains the nonnegative frequency terms of a Hermite-symmetric
    sequence. n is the length of the result, not the input. If n is not
    supplied, the default is 2*(len(a)-1). If you want the length of the
    result to be odd, you have to say so.

    If you specify an n such that a must be zero-padded or truncated, the
    extra/removed values will be added/removed at high frequencies. One can
    thus resample a series to m points via Fourier interpolation by: a_resamp
    = inverse_real_fft(real_fft(a), m).

    This is the inverse of real_fft:
    inverse_real_fft(real_fft(a), len(a)) == a
    within numerical accuracy."""

    a = Numeric.asarray(a).astype(Numeric.Complex)
    if n == None:
        n = (Numeric.shape(a)[axis] - 1) * 2
    return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftb,
                    _real_fft_cache) / n
Example #43
0
File: FFT.py Project: IanReid/ABFGP
def inverse_fft(a, n=None, axis=-1):
    """inverse_fft(a, n=None, axis=-1) 

    Will return the n point inverse discrete Fourier transform of a.  n
    defaults to the length of a. If n is larger than a, then a will be
    zero-padded to make up the difference. If n is smaller than a, then a will
    be truncated to reduce its size.

    The input array is expected to be packed the same way as the output of
    fft, as discussed in it's documentation.

    This is the inverse of fft: inverse_fft(fft(a)) == a within numerical
    accuracy.

    This is most efficient for n a power of two. This also stores a cache of
    working memory for different sizes of fft's, so you could theoretically
    run into memory problems if you call this too many times with too many
    different n's."""

    a = Numeric.asarray(a).astype(Numeric.Complex)
    if n == None:
        n = Numeric.shape(a)[axis]
    return _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftb, _fft_cache) / n
Example #44
0
def _raw_fft(a,
             n=None,
             axis=-1,
             init_function=fftpack.cffti,
             work_function=fftpack.cfftf,
             fft_cache=_fft_cache):
    a = Numeric.asarray(a)

    if n == None: n = a.shape[axis]

    try:
        wsave = fft_cache[n]
    except (KeyError):
        wsave = init_function(n)
        fft_cache[n] = wsave

    if a.shape[axis] != n:
        s = list(a.shape)
        if s[axis] > n:
            index = [slice(None)] * len(s)
            index[axis] = slice(0, n)
            a = a[index]
        else:
            index = [slice(None)] * len(s)
            index[axis] = slice(0, s[axis])
            s[axis] = n
            z = Numeric.zeros(s, a.typecode())
            z[index] = a
            a = z

    if axis != -1:
        a = Numeric.swapaxes(a, axis, -1)
    r = work_function(a, wsave)
    if axis != -1:
        r = Numeric.swapaxes(r, axis, -1)
    return r
Example #45
0
 def __sub__(self, other):
     return self.blob.as_array() - Numeric.asarray(other)
Example #46
0
 def __mul__(self, other):
     return Numeric.multiply(self.blob.as_array(), Numeric.asarray(other))
Example #47
0
    def Draw(self):
        self.Resize(self.width, self.height)

        if self.IsShown():
            self.glcanvas.SetCurrent()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslatef(self.delta_x, self.delta_y, -1.5*max(self.width*self.scale, self.height*self.scale))
        glRotatef(math.degrees(self.angle_x), 0, 1, 0)
        glRotatef(math.degrees(self.angle_y), 1, 0, 0)

        if self.drawAxes:
            glBegin(GL_LINES)
            glVertex3f(0.0, 0.0, 0.0)
            glVertex3f(10.0, 0.0, 0.0)
            glVertex3f(0.0, 0.0, 0.0)
            glVertex3f(0.0, 10.0, 0.0)
            glVertex3f(0.0, 0.0, 0.0)
            glVertex3f(0.0, 0.0, 10.0)
            glEnd()

        if self.graph != None and len(self.vertex_data) > 0:
            glEnableClientState(GL_VERTEX_ARRAY)

            # This shows each point
            glPointSize(5.0)
            if self.vertex_color_data != None and len(self.vertex_color_data) == len(self.vertex_data):
                color_array = True
            else:
                color_array = False
                glColor4f(0.0, 0.0, 1.0, 1.0)
            if color_array:
                glColorPointerf(self.vertex_color_data)
                glEnableClientState(GL_COLOR_ARRAY)
            glVertexPointerf(self.vertex_data)
            glDrawArrays(GL_POINTS, 0, len(self.vertex_data))            

            # This puts a green ring around each point.
            #glPointSize(8.0)
            #glColor4f(0.0, 1.0, 0.0, 1.0)
            #glVertexPointerf(self.vertex_data)
            #glDrawArrays(GL_POINTS, 0, len(self.vertex_data))

            # This draws the edges
            if color_array:
                glDisableClientState(GL_COLOR_ARRAY)
            glColor4f(1.0, 0.0, 0.0, 1.0)
            glVertexPointerf(self.edge_data)
            glDrawArrays(GL_LINES, 0, len(self.edge_data))
            glDisableClientState(GL_VERTEX_ARRAY)

            if self.graph.is_directed():
                (left, top, right, bottom) = self.compute_rect()
                delta = right-left
                fraction = 0.03
                for e in self.graph.edges:
                    u = self.graph.source(e)
                    v = self.graph.target(e)
                    u_loc = Numeric.asarray(self.position_map[u])
                    v_loc = Numeric.asarray(self.position_map[v])
                    direction = Numeric.zeros((3,))
                    direction[0] = v_loc[0] - u_loc[0]
                    direction[1] = v_loc[1] - u_loc[1]
                    if len(v_loc) > 2:
                        direction[2] = v_loc[2] - u_loc[2]
                    direction_norm = math.sqrt(sum(direction*direction))         
                    try:
                        direction = direction / direction_norm
                    except:
                        pass
                    if len(v_loc) > 2:
                        p = Numeric.asarray((0, 0, 0))
                    else:
                        p = Numeric.asarray((0, 0))                    
                    p = Numeric.asarray((0, 0, 0)) #
                    p[0] = v_loc[0] - delta*fraction*direction[0]
                    p[1] = v_loc[1] - delta*fraction*direction[1]
                    p[2] = 0 - delta*fraction*direction[2] #
                    if len(v_loc) > 2:
                        p[2] = v_loc[2] - delta*fraction*direction[2]
                    p[2] = 0 - delta*fraction*direction[2] #

                    o = Numeric.asarray((-1.0*direction[1], direction[0], 0)) # p x <0,0,-1>
                    o = o / math.sqrt(sum(o*o))
                        
                    glBegin(GL_TRIANGLES)
                    glVertex3f(p[0] + delta*fraction*0.25*o[0], \
                               p[1] + delta*fraction*0.25*o[1], \
                               p[2] + delta*fraction*0.25*o[2])
                    if len(v_loc) > 2:
                        glVertex3f(v_loc[0], v_loc[1], v_loc[2])
                    else:
                        glVertex3f(v_loc[0], v_loc[1], 0)
                    glVertex3f(p[0] - delta*fraction*0.25*o[0], \
                               p[1] - delta*fraction*0.25*o[1], \
                               p[2] - delta*fraction*0.25*o[2])
                    glEnd()

                    o2 = Numeric.asarray((p[1]*o[2] - p[2]*o[1],\
                                          -1.0*(p[0]*o[2] - p[2]*o[0]),\
                                          p[0]*o[1] - p[1]*o[0])) # p x o
#                    print o2, "(", o, ")"
                    try:
                        o2 = o2 / math.sqrt(sum(o2*o2))
                    except:
                        pass
                    glBegin(GL_TRIANGLES)
                    glVertex3f(p[0] + delta*fraction*0.25*o2[0], \
                               p[1] + delta*fraction*0.25*o2[1], \
                               p[2] + delta*fraction*0.25*o2[2])
                    if len(v_loc) > 2:
                        glVertex3f(v_loc[0], v_loc[1], v_loc[2])
                    else:
                        glVertex3f(v_loc[0], v_loc[1], 0)
                    glVertex3f(p[0] - delta*fraction*0.5*o[0], \
                               p[1] - delta*fraction*0.5*o[1], \
                               p[2] - delta*fraction*0.5*o[2])                    
                    glEnd()

                   
        if self.active_vertex != None:
            pos = self.position_map[self.active_vertex]
            glDisable(GL_LIGHTING)
            glEnable (GL_BLEND);
            glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            z = 0.
            if len(pos) == 3:
                z = pos[2]
            glTranslatef(pos[0], pos[1], z)
            glColorf(1.0, 1.0, 0.0, 0.5)
            glutSolidSphere(DEFAULT_RADIUS*1.5, DEFAULT_SLICES, DEFAULT_SLICES)
            glDisable(GL_BLEND)
            glEnable(GL_LIGHTING)

        if self.selection != None:
            selection = self.selection
            sel_left = min(selection[0].x, selection[1].x)
            sel_right = max(selection[0].x, selection[1].x)
            sel_bottom = min(selection[0].y, selection[1].y)
            sel_top = max(selection[0].y, selection[1].y)
            glColor4f(0.5, 0.5, 0.5, .25)
            glEnable(GL_COLOR_LOGIC_OP)
            glLogicOp(GL_XOR)
            glBegin(GL_LINE_LOOP)
            glVertex(sel_left, sel_bottom)
            glVertex(sel_left, sel_top)
            glVertex(sel_right, sel_top)
            glVertex(sel_right, sel_bottom)
            glEnd()    
            glDisable(GL_COLOR_LOGIC_OP)
            self.selection = None

        self.glcanvas.SwapBuffers()
Example #48
0
 def _load_numeric_array(self, node):
     import Numeric
     return Numeric.asarray(node.read())
Example #49
0
def tabulate_function(f, xvals, yvals=None, typecode=None, ufunc=0):
    """Evaluate and tabulate a function on a 1- or 2-D grid of points.

    f should be a function taking one or two floating-point
    parameters.

    If f takes one parameter, then xvals should be a 1-D array and
    yvals should be None.  The return value is a Numeric array
    '[f(x[0]), f(x[1]), ..., f(x[-1])]'.

    If f takes two parameters, then 'xvals' and 'yvals' should each be
    1-D arrays listing the values of x and y at which 'f' should be
    tabulated.  The return value is a matrix M where 'M[i,j] =
    f(xvals[i],yvals[j])', which can for example be used in the
    'GridData' constructor.

    If 'ufunc=0', then 'f' is evaluated at each point using a Python
    loop.  This can be slow if the number of points is large.  If
    speed is an issue, you should write 'f' in terms of Numeric ufuncs
    and use the 'ufunc=1' feature described next.

    If called with 'ufunc=1', then 'f' should be a function that is
    composed entirely of ufuncs (i.e., a function that can operate
    element-by-element on whole matrices).  It will be passed the
    xvals and yvals as rectangular matrices.

    """

    if yvals is None:
        # f is a function of only one variable:
        xvals = Numeric.asarray(xvals, typecode)

        if ufunc:
            return f(xvals)
        else:
            if typecode is None:
                typecode = xvals.typecode()

            m = Numeric.zeros((len(xvals),), typecode)
            for xi in range(len(xvals)):
                x = xvals[xi]
                m[xi] = f(x)
            return m
    else:
        # f is a function of two variables:
        xvals = Numeric.asarray(xvals, typecode)
        yvals = Numeric.asarray(yvals, typecode)

        if ufunc:
            return f(xvals[:,Numeric.NewAxis], yvals[Numeric.NewAxis,:])
        else:
            if typecode is None:
                # choose a result typecode based on what '+' would return
                # (yecch!):
                typecode = (Numeric.zeros((1,), xvals.typecode()) +
                            Numeric.zeros((1,), yvals.typecode())).typecode()

            m = Numeric.zeros((len(xvals), len(yvals)), typecode)
            for xi in range(len(xvals)):
                x = xvals[xi]
                for yi in range(len(yvals)):
                    y = yvals[yi]
                    m[xi,yi] = f(x,y)
            return m
Example #50
0
"""
Example #51
0
# Prep the individual data files (makes topocentric data)

print("\n\n**** Making topocentric data files...\n\n")

ns = []
epochs = []
for filenum in range(len(files)):
    file = files[filenum]
    if (datatype=='pkmb'):
        (nout, dt, epoch) = pkmb_prepdata(optlist, file, filenum)
    ns.append(nout)
    epochs.append(epoch)
if (numout):
    epochs.append(epochs[0] + numout * dt / 86400.0)
    ns.append(0)
ns = Numeric.asarray(ns)
epochs = Numeric.asarray(epochs)

# Calculate the amount of padding to add after each file

binsneeded = ((epochs[1:] - epochs[:-1]) * 86400.0 /
              dt + 0.5).astype('i')
padbins = binsneeded - ns[:-1]

# Add padding to the data topocentric files we just wrote

print("\n\n**** Adding padding...\n\n")

for filenum in range(len(padbins)):
    outfile = optlist['o']+repr(filenum)+'.dat'
    if (padbins[filenum] > 0):
def floatIdent(size):
    return Numeric.asarray(Numeric.identity(size), Numeric.Float)
Example #53
0
def tabulate_function(f, xvals, yvals=None, typecode=None, ufunc=0):
    """Evaluate and tabulate a function on a 1- or 2-D grid of points.

    f should be a function taking one or two floating-point
    parameters.

    If f takes one parameter, then xvals should be a 1-D array and
    yvals should be None.  The return value is a Numeric array
    '[f(x[0]), f(x[1]), ..., f(x[-1])]'.

    If f takes two parameters, then 'xvals' and 'yvals' should each be
    1-D arrays listing the values of x and y at which 'f' should be
    tabulated.  The return value is a matrix M where 'M[i,j] =
    f(xvals[i],yvals[j])', which can for example be used in the
    'GridData' constructor.

    If 'ufunc=0', then 'f' is evaluated at each point using a Python
    loop.  This can be slow if the number of points is large.  If
    speed is an issue, you should write 'f' in terms of Numeric ufuncs
    and use the 'ufunc=1' feature described next.

    If called with 'ufunc=1', then 'f' should be a function that is
    composed entirely of ufuncs (i.e., a function that can operate
    element-by-element on whole matrices).  It will be passed the
    xvals and yvals as rectangular matrices.

    """

    if yvals is None:
        # f is a function of only one variable:
        xvals = Numeric.asarray(xvals, typecode)

        if ufunc:
            return f(xvals)
        else:
            if typecode is None:
                typecode = xvals.typecode()

            m = Numeric.zeros((len(xvals), ), typecode)
            for xi in range(len(xvals)):
                x = xvals[xi]
                m[xi] = f(x)
            return m
    else:
        # f is a function of two variables:
        xvals = Numeric.asarray(xvals, typecode)
        yvals = Numeric.asarray(yvals, typecode)

        if ufunc:
            return f(xvals[:, Numeric.NewAxis], yvals[Numeric.NewAxis, :])
        else:
            if typecode is None:
                # choose a result typecode based on what '+' would return
                # (yecch!):
                typecode = (Numeric.zeros(
                    (1, ), xvals.typecode()) + Numeric.zeros(
                        (1, ), yvals.typecode())).typecode()

            m = Numeric.zeros((len(xvals), len(yvals)), typecode)
            for xi in range(len(xvals)):
                x = xvals[xi]
                for yi in range(len(yvals)):
                    y = yvals[yi]
                    m[xi, yi] = f(x, y)
            return m
Example #54
0
 def __add__(self, other):
     return self.blob.as_array() + Numeric.asarray(other)
Example #55
0
 def __setslice__(self, i, j, value):
     self.blob.as_array()[i:j] = Numeric.asarray(value, self._typecode)
Example #56
0
# Prep the individual data files (makes topocentric data)

print "\n\n**** Making topocentric data files...\n\n"

ns = []
epochs = []
for filenum in xrange(len(files)):
    file = files[filenum]
    if (datatype == 'pkmb'):
        (nout, dt, epoch) = pkmb_prepdata(optlist, file, filenum)
    ns.append(nout)
    epochs.append(epoch)
if (numout):
    epochs.append(epochs[0] + numout * dt / 86400.0)
    ns.append(0)
ns = Numeric.asarray(ns)
epochs = Numeric.asarray(epochs)

# Calculate the amount of padding to add after each file

binsneeded = ((epochs[1:] - epochs[:-1]) * 86400.0 / dt + 0.5).astype('i')
padbins = binsneeded - ns[:-1]

# Add padding to the data topocentric files we just wrote

print "\n\n**** Adding padding...\n\n"

for filenum in xrange(len(padbins)):
    outfile = optlist['o'] + ` filenum ` + '.dat'
    if (padbins[filenum] > 0):
        command = 'patchdata ' + ` padbins[
Example #57
0
 def __rsub__(self, other):
     return Numeric.asarray(other) - self.blob.as_array()