[SciPy-user] Circular Buffer

Samuel GARCIA sgarcia@olfac.univ-lyon1...
Thu Feb 26 05:17:20 CST 2009


HI,
I am writting a circular buffer for a acuisiqtion program.

The idea is simple use and derivate a numpy.array for changing one 
behaviour : the buffer is circular.
So when the slice arrive to the end it start at the begining with the 
modulo size of the buffer.

Here is a draft of implementation of this for 1d.

Question :
-is there something more clerver in line 27 to avoid concatenate and so 
a duplication of the array
- does someones already implement this for ND ?

Thanks

Samuel

# -*- coding: utf-8 -*-




import numpy


class CircularBuffer1d():
    def __init__(self , shape , dtype = 'f'):
        self.shape = shape
        self.array = numpy.zeros(shape , dtype = dtype)
       
    def __getitem__(self , sl):
        if type(sl) == int:
            return self.array[sl%self.shape[0]]
        elif type(sl) == slice :
            if sl.start is None :
                start = 0
            else :
                start = sl.start % self.shape[0]
            stop = sl.stop % self.shape[0]
            if stop>start :
                return self.array[start:stop]
            else :
                return numpy.concatenate( ( self.array[start:], 
self.array[: stop ]) , axis = 0)
   
    def __setitem__(self , sl, a):
        if type(sl) == int:
            self.array[sl%self.shape[0]] = a
        elif type(sl) == slice :
            if sl.start is None :
                start = 0
            else :
                start = sl.start % self.shape[0]
           
            stop = sl.stop % self.shape[0]
           
            if stop>start :
                self.array[start:stop] = a
            else :
                self.array[start:] = a[:self.shape[0] - start]
                self.array[: a.shape[0]-(self.shape[0] - start) ] = 
a[self.shape[0] - start:]


c  = CircularBuffer1d( (30,) , dtype = 'f')
print c.array
c[14:17] = numpy.ones((3))
print c.array
c[58:63] = numpy.arange(5)+1
print c.array
c[14] = 14
c[15] = 15
print c.array
print c[15:15]

c[15:15] = numpy.arange(30)
print c[0:30]





-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Samuel Garcia
Laboratoire de Neurosciences Sensorielles, Comportement, Cognition.
CNRS - UMR5020 - Universite Claude Bernard LYON 1
Equipe logistique et technique
50, avenue Tony Garnier
69366 LYON Cedex 07
FRANCE
Tél : 04 37 28 74 64
Fax : 04 37 28 76 01
http://olfac.univ-lyon1.fr/unite/equipe-07/
http://neuralensemble.org/trac/OpenElectrophy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



More information about the SciPy-user mailing list