Example #1
0
def CheckTetrahedron(vertices,point):
    vert=sci.copy(vertices)
    check_1=CheckSide(vert,point)    vert=sci.roll(vert,1,axis=0)
    check_2=CheckSide(vert,point)    vert=sci.roll(vert,1,axis=0)
    check_3=CheckSide(vert,point)    vert=sci.roll(vert,1,axis=0)
    check_4=CheckSide(vert,point)    sum_check=check_1+check_2+check_3+check_4    if(sum_check==4.):
        return 1
Example #2
0
    def shift_inner(arr, nx, ny, window=False, padding='reflect'):
        """
        Shifts an array by nx and ny respectively.

        """

        if ((nx % 1. == 0.) and (ny % 1. ==0)):
            return sp.roll(sp.roll(arr, int(ny), axis=0),
                           int(nx), axis=1)
        else:
            atype = arr.dtype
            if padding:
                x, y = arr.shape
                pwx, pwy = int(pow(2., np.ceil(np.log2(1.5*arr.shape[0])))), int(pow(2., np.ceil(np.log2(1.5*arr.shape[1]))))
                pwx2, pwy2 = (pwx-x)/2, (pwy-y)/2
                if pad=='zero':
                    arr = pad.with_constant(arr, pad_width=((pwx2, pwx2), (pwy2, pwy2)))
                else:
                    arr = pad.with_reflect(arr, pad_width=((pwx2, pwx2), (pwy2, pwy2)))
            phaseFactor = sp.exp(complex(0., -2.*sp.pi)*(ny*spf.fftfreq(arr.shape[0])[:, np.newaxis]+nx*spf.fftfreq(arr.shape[1])[np.newaxis, :]))
            if window:
                window = spf.fftshift(CXData._tukeywin(arr.shape[0], alpha=0.35))
                arr = spf.ifft2(spf.fft2(arr)*phaseFactor*window)
            else:
                arr = spf.ifft2(spf.fft2(arr)*phaseFactor)
            if padding:
                arr = arr[pwx/4:3*pwx/4, pwy/4:3*pwy/4]

        if atype == 'complex':
            return arr
        else:
            return np.real(arr)
Example #3
0
def config_code(solid, x, y):
    solid = roll( solid, -x + 1, axis = 0 )
    solid = roll( solid, -y + 1, axis = 1 )

    key = solid[0:3,0:3] * codex

    return key.sum()
Example #4
0
    def __rearrange(self, objectivePoint=None):
        septalIndex             = None;
        septalPoint             = None;
        closestPoint            = None;

        if objectivePoint is None:
            if self.septum is None:
                raise Exception("No septal point provided in function call and no septal point provided in constructor. Aborting arrangement. ");
            else:
                septalIndex     = self.septum;
        else:
            print(" *  Using provided septal point as rearranging point.");
            self.__septum       = objectivePoint;
            septalIndex         = objectivePoint;

        if septalIndex in self.boundary:
            closestPoint        = septalIndex;
            closestPointIndex   = where(self.boundary==septalIndex);

            if len(closestPointIndex) == 1:
                if len(closestPointIndex[0]) == 1:
                    closestPointIndex = closestPointIndex[0][0];
                else:
                    raise Exception("It seems your vtk file has more than one point ID associated to the objective point. Check your input data or contact the maintainer.");
            else:
                raise Exception("It seems your vtk file has more than one point ID associated to the objective point. Check your input data or contact the maintainer.");

            self.__boundary     = roll(self.boundary, -closestPointIndex);
        else:
            try:
                septalPoint     = self.points[:, septalIndex];
            except:
                raise Exception("Septal point provided out of data bounds; the point does not exist (it is out of bounds) or a point identifier beyond the total amount of points has been provided. Check input.");

            if len(self.boundary.shape) == 1:
                septalPoint     = repmat(septalPoint,
                                    self.boundary.size, 1);
                septalPoint     = septalPoint .transpose();
            else:
                raise Exception("It seems you have multiple boundaries. Contact the package maintainer.");

            distanceToObjectivePoint    = (self.points[:, self.boundary] - septalPoint);
            distanceToObjectivePoint    = sqrt((distanceToObjectivePoint**2).sum(0));
            closestPointIndex           = where(distanceToObjectivePoint == distanceToObjectivePoint.min());

            if len(closestPointIndex) == 1:
                if len(closestPointIndex[0]) == 1:
                    closestPointIndex   = closestPointIndex[0][0];
                else:
                    raise Exception("It seems your vtk file has more than one point ID associated to the objective point. Check your input data or contact the maintainer.");
            else:
                raise Exception("It seems your vtk file has more than one point ID associated to the objective point. Check your input data or contact the maintainer.");

            self.__boundary     = roll(self.boundary, -closestPointIndex);
Example #5
0
def plot_walk(positions, velocities):
    def exponential_distribution(x, mfp):
        return sp.exp(-mfp * x) * mfp

    pos_figure = pl.figure("Position")

    pos_figure.gca().plot(positions[:, 0], positions[:, 1])

    pos_figure.gca().add_artist(an.make_patch(container))

    pos_figure.gca().axis([
        -container.get_radius(),
        container.get_radius(), -container.get_radius(),
        container.get_radius()
    ])

    pos_figure.savefig("random_walk%dd.png" % ndims)

    # Find where collisions happen.
    velocity_rolled = sp.roll(velocities, 1, axis=0)
    velocity_change = (velocity_rolled - velocities)[1:]

    magnitude_change = spl.norm(velocity_change, axis=1)

    collision_positions = positions[1:][magnitude_change != 0]
    collision_positions_rolled = sp.roll(collision_positions, 1, axis=0)

    displacements = (collision_positions_rolled - collision_positions)[1:]

    distances = spl.norm(displacements, axis=1)

    mfp_figure = pl.figure("Mean Free Path")
    freq_dens, bins, patches = mfp_figure.gca().hist(distances,
                                                     bins=40,
                                                     normed=True)

    bin_width = bins[1] - bins[0]
    bin_centres = (bin_width / 2.0) + bins[:-1]

    params, cov = spo.curve_fit(exponential_distribution, bin_centres,
                                freq_dens)

    print params, sp.sqrt(cov)

    mfp_figure.gca().plot(bins, exponential_distribution(bins, *params))

    mfp_figure.gca().legend(["Exponential Distribution", "Path Length"])

    mfp_figure.gca().set_xlabel(r"$\rm{Path\ Length\ /\ m}$")
    mfp_figure.gca().set_ylabel(r"$\rm{Probability\ Density\ /\ m^{-1}}$")

    mfp_figure.savefig("mean_free_path_%dd" % ndims)
Example #6
0
def cshift(arr1, nx, ny):
    """
    Shifts a complex array by nx and ny respectively.
    """
    nx*=1.
    ny*=1.
    
    if ((nx % 1. == 0.) and (ny % 1. ==0)):
        return sp.roll(sp.roll(arr1, int(ny), axis=0),
                       int(nx), axis=1 )
    else:
    
        return spf.ifft2(spnf.fourier_shift(spf.fft2(arr1),(ny,nx)))
def compute_correlation(im1,im2,nbNeigh):
    cor = sp.zeros( (2*nbNeigh+1,2*nbNeigh+1) )

    std1 = sp.std(im1[im1!=0.])
    std2 = sp.std(im2[im2!=0.])
    norm = std1*std2

    for i in range(-nbNeigh,nbNeigh+1):
        for j in range(-nbNeigh,nbNeigh+1):
            mult = im1*sp.roll(sp.roll(im2,i,axis=1),j,axis=0)/norm
            cor[nbNeigh+j,nbNeigh+i] = (mult[mult!=0.]).mean()

    return cor
Example #8
0
def array_factor(number_of_elements, scan_angle, element_spacing, frequency, theta, window_type, side_lobe_level):
    """
    Calculate the array factor for a linear binomial excited array.
    :param window_type: The string name of the window.
    :param side_lobe_level: The sidelobe level for Tschebyscheff window (dB).
    :param number_of_elements: The number of elements in the array.
    :param scan_angle: The angle to which the main beam is scanned (rad).
    :param element_spacing: The distance between elements.
    :param frequency: The operating frequency (Hz).
    :param theta: The angle at which to evaluate the array factor (rad).
    :return: The array factor as a function of angle.
    """
    # Calculate the wavenumber
    k = 2.0 * pi * frequency / c

    # Calculate the phase
    psi = k * element_spacing * (cos(theta) - cos(scan_angle))

    # Calculate the coefficients
    if window_type == 'Uniform':
        coefficients = ones(number_of_elements)
    elif window_type == 'Binomial':
        coefficients = binom(number_of_elements-1, range(0, number_of_elements))
    elif window_type == 'Tschebyscheff':
        warnings.simplefilter("ignore", UserWarning)
        coefficients = chebwin(number_of_elements, at=side_lobe_level, sym=True)
    elif window_type == 'Kaiser':
        coefficients = kaiser(number_of_elements, 6, True)
    elif window_type == 'Blackman-Harris':
        coefficients = blackmanharris(number_of_elements, True)
    elif window_type == 'Hanning':
        coefficients = hanning(number_of_elements, True)
    elif window_type == 'Hamming':
        coefficients = hamming(number_of_elements, True)

    # Calculate the offset for even/odd
    offset = int(floor(number_of_elements / 2))

    # Odd case
    if number_of_elements & 1:
        coefficients = roll(coefficients, offset + 1)
        coefficients[0] *= 0.5
        af = sum(coefficients[i] * cos(i * psi) for i in range(offset + 1))
        return af / amax(abs(af))
    # Even case
    else:
        coefficients = roll(coefficients, offset)
        af = sum(coefficients[i] * cos((i + 0.5) * psi) for i in range(offset))
        return af / amax(abs(af))
Example #9
0
    def __calc_homeomorphism(self):
        """Calculation of the conformal mapping between LV endocardial surfaces 
        and a 2D disk. The approximation of the Laplacian computation is based 
        on cotangent weights.
        """

        start = time.time()

        if (self.laplacian is not None) and (self.boundary is not None):
            numPoints = self.polydata.GetNumberOfPoints()
            diagonal = self.laplacian.sum(0)
            diagonalSparse = spdiags(diagonal, 0, numPoints, numPoints)
            homeomorphism_laplacian = diagonalSparse - self.laplacian

            # Finds non-zero elements in the laplacian matrix
            (nzj, nzi) = self.laplacian.nonzero()

            for point in self.boundary:
                positions = where(nzi == point)[0]

                homeomorphism_laplacian[nzi[positions], nzj[positions]] = 0
                homeomorphism_laplacian[point, point] = 1

            # Finds a distribution of the boundary points around a circle
            boundaryNext = roll(self.boundary, -1)
            boundaryNextPoints = self.points[:, boundaryNext]
            distanceToNext = boundaryNextPoints - self.points[:, self.boundary]

            euclideanNorm = sqrt((distanceToNext**2).sum(0))
            perimeter = euclideanNorm.sum()

            fraction = euclideanNorm / perimeter

            angles = cumsum(2 * pi * fraction)
            angles = roll(angles, 1)
            angles[0] = 0

            # Creates the constrain for the homeomorphism
            Z = zeros((2, angles.size))
            Z[0, :] = cos(angles)
            Z[1, :] = sin(angles)

            boundaryConstrain = zeros((2, self.polydata.GetNumberOfPoints()))
            boundaryConstrain[:, self.boundary] = Z

            self.__homeomorphism = spsolve(
                homeomorphism_laplacian,
                boundaryConstrain.transpose()).transpose()
Example #10
0
def unpack_segment(Seg, num_lags=200, intercept=True):
    """ """

    lags = sp.arange(-num_lags / 2, num_lags / 2, 1, dtype='int32')

    Y = sp.stack([asig.magnitude.flatten() for asig in Seg.analogsignals],
                 axis=1)
    t_start = Seg.analogsignals[0].t_start.rescale('ms')
    t_stop = Seg.analogsignals[0].t_stop.rescale('ms')
    dt = Seg.analogsignals[0].sampling_period.rescale('ms')

    X = []
    for event in Seg.events:
        st = neo.core.SpikeTrain(event.times, t_stop=t_stop)
        bst = ele.conversion.BinnedSpikeTrain(st,
                                              binsize=dt,
                                              t_start=t_start,
                                              t_stop=t_stop)
        reg = bst.to_array().flatten()
        for lag in lags:
            X.append(sp.roll(reg, lag))

    X = sp.stack(X, axis=1)

    if intercept:
        X = sp.concatenate([sp.ones((X.shape[0], 1)), X], 1)

    t_lags = lags * dt.magnitude
    return Y, X, t_lags
Example #11
0
 def flip_boundary(self):
     """The method for extracting the boundaries can result in clockwise or 
     counterclockwise boundaries. This method is used to flip the rotation 
     direction if needed.
     """
     self.__boundary = flipud(self.boundary)
     self.__boundary = roll(self.boundary, 1)
Example #12
0
def vel_rhs_matrices(p_dof_grid, vel_dof_grid, axis):
    # shape and locus correction
    s = p_dof_grid.shape

    pdofs = p_dof_grid.max() + 1
    vel_dofs = vel_dof_grid.max() + 1

    # Eq definition
    vel_rhs_mat = sparse.lil_matrix( ( pdofs, vel_dofs ) )

    rolled_p = roll(p_dof_grid, 1, axis=axis)
    
    for x in range(s[0]):
      for y in range(s[1]):
        point = (x,y)

        if vel_dof_grid[point] < 0:
            continue 
        vel_dof = vel_dof_grid[point]
       
        p1 = p_dof_grid[point]
        if p1 >= 0:
            vel_rhs_mat[p1, vel_dof] = 1

        p2 = rolled_p[point]
        if p2 >= 0:
            vel_rhs_mat[p2, vel_dof] = -1

    return vel_rhs_mat.tocsc()
Example #13
0
    def flip_boundary(self):
        """ """

        print("TO-DO: DOCUMENTATION")

        self.__boundary = flipud(self.boundary)
        self.__boundary = roll(self.boundary, 1)
def calc(ops):
  #Initialize prion levels to 
  prions=scipy.zeros(ops.lifespan)
  prions[0]=ops.initial_infect

  R=scipy.exp(scipy.log(ops.R)/ops.timestep)

  c=scipy.zeros(ops.lifespan)
  feedback=ops.feedback.split(',')
  for n in range(len(feedback)):
      c[n]=float(feedback[n])

  times=[]
  plevels=[]
  for y in range(ops.years):
    for t in range(ops.timestep):
      times.append(y+t/float(ops.timestep))
      plevels.append(prions.sum())
      print "%f\t%f" % (y+t/float(ops.timestep),prions.sum())
      prions*=R
    prions=scipy.roll(prions,1)
    ly=prions[0]
    prions[0]=0
    prions+=ly*c

  return times,plevels
Example #15
0
    def GetWithinBoundaryDistances(self):
        boundaryNext = scipy.roll(self.__boundary, -1)
        boundaryNextPoints = self.__pointData[:, boundaryNext]

        distanceToNext = boundaryNextPoints - self.GetBoundaryPoints()

        return scipy.sqrt((distanceToNext**2).sum(0))
def calc(ops):
  prions=scipy.zeros(ops.lifespans+ops.lifespann)
  prions[0]=ops.initial_infect

  R=scipy.zeros(ops.lifespans+ops.lifespann)
  R[0:ops.lifespans]=scipy.exp(scipy.log(ops.Rs)/ops.timestep)
  R[ops.lifespans:]=scipy.exp(scipy.log(ops.Rn)/ops.timestep)

  c=scipy.zeros(ops.lifespans+ops.lifespann)
  feedback=ops.feedback.split(',')
  for n in range(len(feedback)):
      c[n]=float(feedback[n])

  times=[]
  slevels=[]
  nlevels=[]
  print c
  for y in range(ops.years):
    for t in range(ops.timestep):
      times.append(y+t/float(ops.timestep))
      slevels.append(prions[0:ops.lifespans].sum())
      nlevels.append(prions[ops.lifespans+1:].sum())
      print "%f\t%f\t%f" % (y+t/float(ops.timestep),prions[0:ops.lifespans].sum(),prions[ops.lifespans:].sum())
      prions*=R
    prions=scipy.roll(prions,1)
    feedback_from_n_to_s=prions[0]
    feedback_from_s_to_n=prions[ops.lifespans]
    prions[0]=0
    prions[ops.lifespans]=0
    prions[0:ops.lifespans]+=feedback_from_n_to_s*c[0:ops.lifespans]
    prions[ops.lifespans:]+=feedback_from_s_to_n*c[ops.lifespans:]

  return times,slevels,nlevels
Example #17
0
    def GetWithinBoundaryDistances(self):
        boundaryNext            = roll(self.__boundary, -1);
        boundaryNextPoints      = self.__pointData[:, boundaryNext];

        distanceToNext          = boundaryNextPoints - self.GetBoundaryPoints();

        return sqrt((distanceToNext**2).sum(0));
Example #18
0
    def get_boundary_node_distances(self):
        boundaryNext            = roll(self.boundary, -1);
        boundaryNextPoints      = self.points[:, boundaryNext];

        distanceToNext          = boundaryNextPoints - self.boundary_points;

        return sqrt((distanceToNext**2).sum(0));
def _sgw(k, s):
    """ Shifted histogram of Gaussian weights, centered appropriately """
    x = sp.linspace(0.0, 1.0, k)
    if s == sp.inf:
        w = sp.ones((k,)) / float(k)
    else:
        w = stats.norm.pdf(x, loc=x[k//2], scale=s)
    return sp.roll(w / w.sum(), shift=int(sp.ceil(k/2.0)))
Example #20
0
    def __calc_homeomorphism(self):
        """ """

        print("TO-DO: DOCUMENTATION")

        if (self.laplacian is not None) and (self.boundary is not None):
            numPoints = self.polydata.GetNumberOfPoints()
            diagonal = self.laplacian.sum(0)
            diagonalSparse = spdiags(diagonal, 0, numPoints, numPoints)
            homeomorphism_laplacian = diagonalSparse - self.laplacian

            # Finds non-zero elements in the laplacian matrix
            (nzi, nzj) = find(self.laplacian)[0:2]

            for point in self.boundary:
                positions = where(nzi == point)[0]

                homeomorphism_laplacian[nzi[positions], nzj[positions]] = 0
                homeomorphism_laplacian[point, point] = 1

            # Finds a distribution of the boundary points around a circle
            boundaryNext = roll(self.boundary, -1)
            boundaryNextPoints = self.points[:, boundaryNext]
            distanceToNext = boundaryNextPoints - self.points[:, self.boundary]

            euclideanNorm = sqrt((distanceToNext**2).sum(0))
            perimeter = euclideanNorm.sum()

            fraction = euclideanNorm / perimeter

            angles = cumsum(2 * pi * fraction)
            angles = roll(angles, 1)
            angles[0] = 0

            # Creates the constrain for the homeomorphism
            Z = zeros((2, angles.size))
            Z[0, :] = cos(angles)
            Z[1, :] = sin(angles)

            boundaryConstrain = zeros((2, self.polydata.GetNumberOfPoints()))
            boundaryConstrain[:, self.boundary] = Z

            self.__homeomorphism = spsolve(
                homeomorphism_laplacian,
                boundaryConstrain.transpose()).transpose()
Example #21
0
    def GetWithinBoundaryAngles(self):
        circleLength = 2 * scipy.pi
        fraction = self.GetWithinBoundaryDistancesAsFraction()

        angles = scipy.cumsum(circleLength * fraction)
        angles = scipy.roll(angles, 1)
        angles[0] = 0

        return angles
Example #22
0
	def shift(self, arr1, nx, ny):
	    """
	    Shifts an array by nx and ny respectively.
	    """
	    
	    xpix, ypix = arr1.shape
	    
	    if ((nx % 1. == 0.) and (ny % 1. ==0)):
	        return sp.roll(sp.roll(arr1, int(nx), axis=0),
	                       int(ny), axis=1 )
	    else:
	        xfreqs, yfreqs = spf.fftfreq(xpix), spf.fftfreq(ypix)
	        phaseFactor = sp.zeros((xpix,ypix),dtype=complex)
	        for i in xrange(xpix):
	            for j in xrange(ypix):
	                phaseFactor[i,j] = sp.exp(complex(0., -2.*sp.pi)*(ny*yfreqs[j]+nx*xfreqs[i]))
	        tmp = spf.ifft2(spf.fft2(arr1)*phaseFactor)
	        return sp.real(tmp.copy())
Example #23
0
    def GetWithinBoundaryAngles(self):
        circleLength            = 2*pi;
        fraction                = self.GetWithinBoundaryDistancesAsFraction();

        angles                  = cumsum(circleLength*fraction);
        angles                  = roll(angles, 1);
        angles[0]               = 0;

        return angles;
Example #24
0
    def __calc_boundary_node_angles(self):
        circleLength            = 2*pi;
        fraction                = self.get_boundary_node_distances_fraction();

        angles                  = cumsum(circleLength*fraction);
        angles                  = roll(angles, 1);
        angles[0]               = 0;

        return angles;
Example #25
0
    def on_data(self, t, Fx, Fy):
        """ called when UDP payload with raw force data is received """

        # store data
        self.Buffer = sp.roll(self.Buffer, -1, 0)
        self.Buffer[-1, :] = [Fx, Fy]

        # calculate offset
        self.Fx_off, self.Fy_off = sp.median(self.Buffer, 0)

        # remove offset
        Fx -= self.Fx_off
        Fy -= self.Fy_off

        Fm = sp.array([Fx, Fy])

        # # physical cursor
        # m = 20 # mass
        # lam = 1000 # friction factor

        # # friction as a force acting in the opposite direction of F and proportional to v
        # Ff = self.v_last*lam*-1

        # Fges = Fm+Ff

        # # dt = t - self.t_last # to catch first data sample error
        # # if dt > 0.05:
        # #     dt = 0.01
        # dt = 0.01 # this depends on the bonsai sketch

        # dv = Fges/m * dt

        # v = self.v_last + dv

        # self.X = self.X_last + v * dt
        # self.X = sp.clip(self.X,-10,10)

        # self.t_last = t
        # self.v_last = v
        # self.X_last = self.X

        # send the processed data to arduino
        # ba = struct.pack("ff",self.X[0],self.X[1])
        # self.Signals.processed_lc_data_available.emit(*self.X)

        # emit signal for DisplayController
        # Fx = Fx / 1e3
        # Fy = Fy / 1e3

        self.processed_lc_data_available.emit(Fx, Fy)

        # send coordinates to Arduino via second serial
        ba = struct.pack("ff", Fx, Fy)
        cmd = str.encode('[') + ba + str.encode(']')

        if self.arduino_2nd_ser.is_open:
            self.arduino_2nd_ser.write(cmd)
Example #26
0
def shift_nsa(arr1, nx, ny):
    """
    Shifts an array by nx and ny respectively.
    """
    
    pix_x, pix_y = arr1.shape[0], arr1.shape[1]
    nx*=1.
    ny*=1.
    
    if ((nx % 1. == 0.) and (ny % 1. ==0)):
        return sp.roll(sp.roll(arr1, int(ny), axis=0),
                       int(nx), axis=1 )
    else:
        freqs_x, freqs_y = spf.fftfreq(pix_x), spf.fftfreq(pix_y)
        phaseFactor = sp.zeros((pix_x,pix_y),dtype=complex)
        for i in xrange(pix_x):
            for j in xrange(pix_y):
                phaseFactor[i,j] = sp.exp(complex(0., -2.*sp.pi)*(nx*freqs_x[i]+ny*freqs_y[j]))
        tmp = spf.ifft2(spf.fft2(arr1)*phaseFactor)
        return sp.real(tmp.copy())
Example #27
0
def makeCovmat(lagsDatasum,lagsNoisesum,pulses_s,Nlags):
    
    axvec=sp.roll(sp.arange(lagsDatasum.ndim),1)
    # Get the covariance matrix
    R=sp.transpose(lagsDatasum/sp.sqrt(2.*pulses_s),axes=axvec)
    Rw=sp.transpose(lagsNoisesum/sp.sqrt(2.*pulses_s),axes=axvec)
    l=sp.arange(Nlags)
    T1,T2=sp.meshgrid(l,l)
    R0=R[sp.zeros_like(T1)]
    Rw0=Rw[sp.zeros_like(T1)]
    Td=sp.absolute(T1-T2)
    Tl = T1>T2
    R12 =R[Td]
    R12[Tl]=sp.conjugate(R12[Tl])
    Rw12 =Rw[Td]
    Rw12[Tl]=sp.conjugate(Rw12[Tl])
    Ctt=R0*R12+R[T1]*sp.conjugate(R[T2])+Rw0*Rw12+Rw[T1]*sp.conjugate(Rw[T2])
    avecback=sp.roll(sp.arange(Ctt.ndim),-2)
    Cttout = sp.transpose(Ctt,avecback)
    return Cttout
Example #28
0
def makeCovmat(lagsDatasum,lagsNoisesum,pulses_s,Nlags):

    axvec=sp.roll(sp.arange(lagsDatasum.ndim),1)
    # Get the covariance matrix
    R=sp.transpose(lagsDatasum/sp.sqrt(2.*pulses_s),axes=axvec)
    Rw=sp.transpose(lagsNoisesum/sp.sqrt(2.*pulses_s),axes=axvec)
    l=sp.arange(Nlags)
    T1,T2=sp.meshgrid(l,l)
    R0=R[sp.zeros_like(T1)]
    Rw0=Rw[sp.zeros_like(T1)]
    Td=sp.absolute(T1-T2)
    Tl = T1>T2
    R12 =R[Td]
    R12[Tl]=sp.conjugate(R12[Tl])
    Rw12 =Rw[Td]
    Rw12[Tl]=sp.conjugate(Rw12[Tl])
    Ctt=R0*R12+R[T1]*sp.conjugate(R[T2])+Rw0*Rw12+Rw[T1]*sp.conjugate(Rw[T2])
    avecback=sp.roll(sp.arange(Ctt.ndim),-2)
    Cttout = sp.transpose(Ctt,avecback)
    return Cttout
Example #29
0
    def shift_inner(arr, nx, ny, window=False, padding='reflect'):
        """
        Shifts an array by nx and ny respectively.

        """

        if ((nx % 1. == 0.) and (ny % 1. == 0)):
            return sp.roll(sp.roll(arr, int(ny), axis=0), int(nx), axis=1)
        else:
            atype = arr.dtype
            if padding:
                x, y = arr.shape
                pwx, pwy = int(pow(2., np.ceil(np.log2(
                    1.5 * arr.shape[0])))), int(
                        pow(2., np.ceil(np.log2(1.5 * arr.shape[1]))))
                pwx2, pwy2 = (pwx - x) / 2, (pwy - y) / 2
                if pad == 'zero':
                    arr = pad.with_constant(arr,
                                            pad_width=((pwx2, pwx2), (pwy2,
                                                                      pwy2)))
                else:
                    arr = pad.with_reflect(arr,
                                           pad_width=((pwx2, pwx2), (pwy2,
                                                                     pwy2)))
            phaseFactor = sp.exp(
                complex(0., -2. * sp.pi) *
                (ny * spf.fftfreq(arr.shape[0])[:, np.newaxis] +
                 nx * spf.fftfreq(arr.shape[1])[np.newaxis, :]))
            if window:
                window = spf.fftshift(
                    CXData._tukeywin(arr.shape[0], alpha=0.35))
                arr = spf.ifft2(spf.fft2(arr) * phaseFactor * window)
            else:
                arr = spf.ifft2(spf.fft2(arr) * phaseFactor)
            if padding:
                arr = arr[pwx / 4:3 * pwx / 4, pwy / 4:3 * pwy / 4]

        if atype == 'complex':
            return arr
        else:
            return np.real(arr)
Example #30
0
def velocity_dof(domain, ax):
    # Calculate velocity dof numbers forr each cell
    rm = roll( domain, 1, axis=ax )
    type_3 = logical_and( domain, rm )
    type_2 = logical_or(  domain, rm )
    
    dof = cumsum( logical_not( logical_or( type_3, type_2 ) ) ).reshape( domain.shape ) - 1
    # Do logic to figure out type 2 and 3
    dof[type_2 == 1] = -2
    dof[type_3 == 1] = -3

    return dof.astype(int64)
Example #31
0
def fftw_cshift(arr1, nx, ny, fft, ifft):
    
    """
    Shifts an array by nx and ny respectively.
    """
    
    pix = arr1.shape[0]
    nx*=1.
    ny*=1.
    
    if ((nx % 1. == 0.) and (ny % 1. ==0)):
        return sp.roll(sp.roll(arr1, int(ny), axis=0),
                       int(nx), axis=1 )
    else:
        freqs = spf.fftfreq(pix)
        arr1=fft(arr1)
        for i in xrange(pix):
            for j in xrange(pix):
                arr1[i,j] *= sp.exp(complex(0., -2.*sp.pi)*(nx*freqs[i]+ny*freqs[j]))
        arr1 = ifft(arr1)
        return arr1
Example #32
0
def varacf(acf):
    """This calculates the variances of an ACF. """
    axisvec =sp.roll( sp.arange(acf.ndim),1)
    acftrans = sp.transpose(acf,tuple(axisvec))
    acfvar = sp.zeros_like(acftrans)
    axisvec = sp.roll(axisvec,-2)
    N= acftrans.shape[0]

    for l in range(N):
        for m in range(-(N+l)+1,N-l-1):
            constterm = (N-sp.absolute(m)+l)
            # for r1, Rxx(m)
            if sp.absolute(m)>=N-1:
                r1=sp.zeros_like(acftrans[0])
            elif m>=0:
                r1 = acftrans[m]
            elif m<0:
                r1=acftrans[-m]

            # for r2, Rxx(m+1)
            m2=m+l
            if sp.absolute(m2)>=N-1:
                r2=sp.zeros_like(acftrans[0])
            elif m2>=0:
                r2 = acftrans[m2]
            elif m2<0:
                r2=acftrans[-m2]

            # for r3, Rxx(m-1)
            m3=m+l
            if sp.absolute(m3)>=N-1:
                r3=sp.zeros_like(acftrans[0])
            elif m3>=0:
                r3 = acftrans[m3]
            elif m3<0:
                r3=acftrans[-m3]

            acfvar[l]=acfvar[l]+constterm*(sp.absolute(r1)**2+sp.absolute(r2*r3))

    return sp.transpose(acfvar/N,tuple(axisvec))
Example #33
0
    def takeabs(fdf3,actual):
        delta_t = 12
        jh = 288/delta_t
        ans = []
        for restf in fdf3.columns:
        a = fdf3[restf]
        for shift in range(jh):
            ans.append(scipy.absolute(scipy.roll(a,shift*delta_t) - actual).sum())
        indexloc = ans.index(min(ans))
        pstar = indexloc/jh
        jstar= indexloc%jh
        adf=fdf3[pstar]
        adff=np.roll(adf,jstar)
        adff1=pd.Series(adff)
        print adff1,"pd.Series(adff)"
        return adff1
    
    @staticmethod
    def mergdat(mergpat,bestpat):
        bestpat = pd.concat([mergpat,bestpat], axis=1)
        return bestpat
    
    @staticmethod
    def diaggragate():
        d1 = datetime.datetime.now()
        files = glob.glob('test/*.csv')
        for j in files:
        home_id = re.findall(r'\d+', j.split('_')[0])[0]
        ite = 0
        words = ['air','dryer','furnace','lights_plugs','refrigerator']
        # for readit in range(0,14400,1440):
        for readit in range(0,2880,288):
        testf = pd.read_csv(j, skiprows=readit , nrows=288)
        bestpatmp = pd.DataFrame()
        actual = testf.iloc[:,7]
        print actual
        for  i in words:
            ghj = '*_'+i+'_weekday_out.csv'
            allFiles = glob.glob(ghj)
            data3 = preparedata(allFiles,ite)
            kmpat = kmeansdata(data3)
            bestpat = takeabs(kmpat,actual)
            actual = actual.subtract(bestpat)
            print actual, "actual"
            bestpatmp = mergdat(bestpatmp,bestpat)
        bestpatmp.to_csv('solution_'+home_id+'.csv', mode='a', index = False, index_label = False, header=False)
        ite += 1


        d2 = datetime.datetime.now()

        print d2 - d1
Example #34
0
    def on_udp_data(self, t, x, y):
        """ update display """
        self.cursor.setData(x=[x - self.Controller.Fx_off],
                            y=[y - self.Controller.Fy_off])

        self.cursor_raw.setData(x=[x], y=[y])

        self.lc_raw_data = sp.roll(self.lc_raw_data, -1, 0)
        self.lc_raw_data[-1, :] = [x, y]

        self.cursor_hist.setData(
            x=self.lc_raw_data[:, 0] - self.Controller.Fx_off,
            y=self.lc_raw_data[:, 1] - self.Controller.Fy_off)
Example #35
0
def bior2_6(length, width):
    length = int(length)
    width = int(width)
    i = sp.arange(0, 13*width)
    u = _psi_bior2_6[_scale_max*i/width]/sp.sqrt(width)
    n = int(abs((length-width*13)/2))
    if length > width*13:
        u = sp.concatenate((u,sp.zeros(length-width*13)), axis=0)
        u = sp.roll(u, n)
    elif length < width*13:
        u = u[n:n+length]
 
    return u
Example #36
0
def run():
    defaults = PaperDefaults()

    #David's globals
    size = 51
    npoints = 64
    cval1 = 0.25
    cval2 = 0.75
    sval = 0.75
    test_contrasts = sp.array([0., 8., 32.])
    mask_contrasts = sp.array([0., 8., 32.])

    # experiment parameters
    idx1 = int(cval1 * npoints)
    idx2 = int(cval2 * npoints)

    # simulate populations
    imc = stim.get_center_surround(size=size, csize=9, cval=cval1, sval=sp.nan)
    ims = stim.get_center_surround(size=size, csize=9, cval=sp.nan, sval=sval)
    x1 = utils.get_population(imc,
                              npoints=npoints,
                              kind='gaussian',
                              scale=0.1,
                              fdomain=(0, 1))
    x2 = sp.roll(x1, int((cval2 - cval1) * npoints), axis=-3)
    xs = utils.get_population(ims,
                              npoints=npoints,
                              kind='gaussian',
                              scale=0.1,
                              fdomain=(0, 1))
    x = []

    for k1 in test_contrasts:
        for k2 in mask_contrasts:
            x.append(k1 / 100. * x1 + k2 / 100. * x2)
    x = sp.array(x) + sp.array([xs])

    # Experimental data
    extra_vars = {}
    extra_vars['size'] = size
    extra_vars['npoints'] = npoints
    extra_vars['sval'] = sval
    extra_vars['figure_name'] = 'cross_orientation_suppression'
    extra_vars['return_var'] = 'O'
    extra_vars['idx1'] = idx1
    extra_vars['idx2'] = idx2
    extra_vars['test_contrasts'] = test_contrasts
    extra_vars['mask_contrasts'] = mask_contrasts
    optimize_model(x, [], extra_vars, defaults)
Example #37
0
    def spectrumAnalyzer(self):

        # FFT する信号の初期化
        signal = zeros(fftLen, dtype=float)

        # Update
        print('音声入力ループ')

        sound_data = []
        # 適当に5秒間実行して終了
        for n in xrange(0, self.fs * 7 / self.chunk):
            try:
                # dataは文字列型
                data = self.stream.read(self.chunk)
            except IOError as ex:
                # よくわからんけど、しばらく実行していると結構な頻度でミスってる
                if ex[1] != pyaudio.paInputOverflowed:
                    raise
                data = '\x00' * self.chunk
                print('errorrrrrrrrrrrrrrrrrr')

            num_data = fromstring(data, dtype='int16')
            signal = roll(signal, - self.chunk)
            signal[- len(num_data):] = num_data
            fftspec = my_fft(signal)

            spec = abs(fftspec[1: fftLen / 2 + 1]) * signal_scale  # スペクトル
            # print('Max : %.5f' % freq_list[np.argmax(spec)])

            if max(spec) >= 2000 and np.argmax(spec) > 3:
                print('spec: %s' % str(max(spec)))
                max_list_num = np.argmax(spec)
                print('Max : %8.3f , %s, %s' % (
                    self.freq_list[max_list_num][0],
                    self.my_piano.octa_mark[self.freq_list[max_list_num][1]],
                    self.my_piano.onkai[self.freq_list[max_list_num][2]])
                )
                sound_data.append(phone_scale[self.freq_list[max_list_num][2]])
            else:
                print('none')
                sound_data.append('N')

            self.specItem.plot(spec, clear=True)
            QtGui.QApplication.processEvents()

        self.save_score_data(sound_data, self.chunk/float(self.fs), OUTPUT_FILE_NAME)

        self.stream.close()
        self.p.terminate()
Example #38
0
def pad_shift(arr1, nx, ny):
    """
    Shifts an array by nx and ny respectively.
    """
    initial_size = arr1.shape
    new_arr = sp.zeros((2*arr1.shape[0], 2*arr1.shape[1]))
    new_arr[:arr1.shape[0], :arr1.shape[1]] = arr1
    arr1=new_arr
    pix = arr1.shape[0]
    nx*=1.
    ny*=1.
    window = spf.fftshift(np.hamming(pix)[:,np.newaxis]*np.hamming(pix)[np.newaxis,:])
    if ((nx % 1. == 0.) and (ny % 1. ==0)):
        return sp.roll(sp.roll(arr1, int(ny), axis=0),
                       int(nx), axis=1 )
    else:
        freqs = spf.fftfreq(pix)
        phaseFactor = sp.zeros((pix,pix),dtype=complex)
        for i in xrange(pix):
            for j in xrange(pix):
                phaseFactor[i,j] = sp.exp(complex(0., -2.*sp.pi)*(nx*freqs[j]+ny*freqs[i]))
        tmp = spf.ifft2(spf.fft2(arr1)*phaseFactor*window)

        return sp.real(tmp.copy())
Example #39
0
def pyglowinput(
        latlonalt=[65.1367, -147.4472, 250.00],
        dn_list=[datetime(2015, 3, 21, 8, 00),
                 datetime(2015, 3, 21, 20, 00)],
        z=None):

    if z is None:
        z = sp.linspace(50., 1000., 200)
    dn_diff = sp.diff(dn_list)
    dn_diff_sec = dn_diff[-1].seconds
    timelist = sp.array([calendar.timegm(i.timetuple()) for i in dn_list])
    time_arr = sp.column_stack((timelist, sp.roll(timelist, -1)))
    time_arr[-1, -1] = time_arr[-1, 0] + dn_diff_sec

    v = []
    coords = sp.column_stack((sp.zeros((len(z), 2), dtype=z.dtype), z))
    all_spec = ['O+', 'NO+', 'O2+', 'H+', 'HE+']
    Param_List = sp.zeros((len(z), len(dn_list), len(all_spec), 2))
    for idn, dn in enumerate(dn_list):
        for iz, zcur in enumerate(z):
            latlonalt[2] = zcur
            pt = Point(dn, *latlonalt)
            pt.run_igrf()
            pt.run_msis()
            pt.run_iri()

            # so the zonal pt.u and meriodinal winds pt.v  will coorispond to x and y even though they are
            # supposed to be east west and north south. Pyglow does not seem to have
            # vertical winds.
            v.append([pt.u, pt.v, 0])

            for is1, ispec in enumerate(all_spec):
                Param_List[iz, idn, is1, 0] = pt.ni[ispec] * 1e6

            Param_List[iz, idn, :, 1] = pt.Ti

            Param_List[iz, idn, -1, 0] = pt.ne * 1e6
            Param_List[iz, idn, -1, 1] = pt.Te
    Param_sum = Param_List[:, :, :, 0].sum(0).sum(0)
    spec_keep = Param_sum > 0.
    species = sp.array(all_spec)[spec_keep[:-1]].tolist()
    species.append('e-')
    Param_List[:, :] = Param_List[:, :, spec_keep]
    Iono_out = IonoContainer(coords,
                             Param_List,
                             times=time_arr,
                             species=species)
    return Iono_out
Example #40
0
def takeabs(fdf3,actual):
    delta_t = 60
    jh = 1440/delta_t
    ans = []
    for restf in fdf3.columns:
        a = fdf3[restf]
        for shift in range(jh):
            ans.append(scipy.absolute(scipy.roll(a,shift) - actual).sum())
    indexloc = ans.index(min(ans))
    pstar = indexloc/jh
    jstar= indexloc%jh
    adf=fdf3[pstar]
    adff=np.roll(adf,jstar)
    adff1=pd.Series(adff)
    print adff1,"pd.Series(adff)"
    return adff1
def temporal_kernel(vec, memory_vec, integration_Tt, kernel_params):
    """
	Apply temporal kernel to current values of activity or gain levels. 
	This function discretely integrates the convolution of the 
	temporal kernel with a vector of activities held in a finite
	length of memory. To account for the fact that the kernel has
	features at a finer timescale than the integration time, the
	activities are interpolated in between these times to convolve
	on a finer timescale. integration_Tt is the time vector of the 
	full integration of the estimation.
	"""

    kernel_T, kernel_dt, kernel_tau_1, kernel_tau_2, kernel_shape_1, \
     kernel_shape_2, kernel_alpha, kernel_scale, = kernel_params

    # Length of memory vector based on signal sampling rate
    signal_dt = integration_Tt[1] - integration_Tt[0]
    signal_Tt = sp.linspace(0, kernel_T, int(kernel_T / signal_dt) + 1)
    memory_vec_len = len(signal_Tt)

    # Finer mesh for kernel integration, utilizing kernel_dt
    kernel_Tt = sp.arange(0, kernel_T, kernel_dt)

    # Assign memory vector holding past activity levels; replace t = 0
    # value with current vector value; roll rest to previous times
    if memory_vec is None:
        memory_vec = sp.zeros(vec.shape + (memory_vec_len, ))
    memory_vec = sp.roll(memory_vec, 1)
    memory_vec[..., 0] = vec

    # Interpolating function to get finer mesh for kernel integration
    interp_f = interp1d(signal_Tt, memory_vec)

    # Get kernel and Yy, Yy0 at points on scale of kernel_dt
    vec_interped = interp_f(kernel_Tt)
    kernel = kernel_scale * (
        gamma.pdf(kernel_Tt, kernel_shape_1, scale=kernel_tau_1) - kernel_alpha
        * gamma.pdf(kernel_Tt, kernel_shape_2, scale=kernel_tau_2))

    # Apply the filter
    vec = sp.sum(vec_interped * kernel * kernel_dt, axis=-1)

    return vec, memory_vec
Example #42
0
def pyglowinput(latlonalt=[65.1367, -147.4472, 250.00], dn_list=[datetime(2015, 3, 21, 8, 00), datetime(2015, 3, 21, 20, 00)], z=None):


    if z is None:
        z = sp.linspace(50., 1000., 200)
    dn_diff = sp.diff(dn_list)
    dn_diff_sec = dn_diff[-1].seconds
    timelist = sp.array([calendar.timegm(i.timetuple()) for i in dn_list])
    time_arr = sp.column_stack((timelist, sp.roll(timelist, -1)))
    time_arr[-1, -1] = time_arr[-1, 0]+dn_diff_sec

    v=[]
    coords = sp.column_stack((sp.zeros((len(z), 2), dtype=z.dtype), z))
    all_spec = ['O+', 'NO+', 'O2+', 'H+', 'HE+']
    Param_List = sp.zeros((len(z), len(dn_list),len(all_spec),2))
    for idn, dn in enumerate(dn_list):
        for iz, zcur in enumerate(z):
            latlonalt[2] = zcur
            pt = Point(dn, *latlonalt)
            pt.run_igrf()
            pt.run_msis()
            pt.run_iri()

            # so the zonal pt.u and meriodinal winds pt.v  will coorispond to x and y even though they are
            # supposed to be east west and north south. Pyglow does not seem to have
            # vertical winds.
            v.append([pt.u, pt.v, 0])

            for is1, ispec in enumerate(all_spec):
                Param_List[iz, idn, is1, 0] = pt.ni[ispec]*1e6

            Param_List[iz, idn, :, 1] = pt.Ti

            Param_List[iz, idn, -1, 0] = pt.ne*1e6
            Param_List[iz, idn, -1, 1] = pt.Te
    Param_sum = Param_List[:, :, :, 0].sum(0).sum(0)
    spec_keep = Param_sum > 0.
    species = sp.array(all_spec)[spec_keep[:-1]].tolist()
    species.append('e-')
    Param_List[:, :] = Param_List[:, :, spec_keep]
    Iono_out = IonoContainer(coords, Param_List, times = time_arr, species=species)
    return Iono_out
def compute_shifts(x, sess, ctx, extra_vars, default_parameters):
    start = timer()
    sess.run(
        tf.group(tf.global_variables_initializer(),
                 tf.local_variables_initializer()))  # depreciated

    # tf.group(tf.global_variables_initializer())
    feed_dict = {
        ctx.X:
        x,
        # ctx.xi:default_parameters._DEFAULT_PARAMETERS['xi'].reshape(-1,1),
        ctx.alpha:
        default_parameters._DEFAULT_PARAMETERS['alpha'].reshape(-1, 1),
        ctx.beta:
        default_parameters._DEFAULT_PARAMETERS['beta'].reshape(-1, 1),
        ctx.mu:
        default_parameters._DEFAULT_PARAMETERS['mu'].reshape(-1, 1),
        ctx.nu:
        default_parameters._DEFAULT_PARAMETERS['nu'].reshape(-1, 1),
        ctx.gamma:
        default_parameters._DEFAULT_PARAMETERS['gamma'].reshape(-1, 1),
        ctx.delta:
        default_parameters._DEFAULT_PARAMETERS['delta'].reshape(-1, 1)
    }

    if default_parameters.optimize_omega:
        _, _, _, k = x.shape
        weights = _sgw(k=k, s=default_parameters._DEFAULT_PARAMETERS['omega']) \
            if defaults['_DEFAULT_PARAMETERS']['continuous'] else _sdw(k=k, s=default_parameters._DEFAULT_PARAMETERS['omega'])
        q_array = sp.array(
            [sp.roll(weights, shift=shift) for shift in range(k)])
        q_array.shape = (1, 1, k, k)
        feed_dict[ctx._gpu_q] = q_array
    if extra_vars['return_var'] == 'I':
        y = sess.run(ctx.out_I, feed_dict=feed_dict)
    elif extra_vars['return_var'] == 'O':
        y = sess.run(ctx.out_O, feed_dict=feed_dict)
    end = timer()
    run_time = end - start
    return y, run_time
	def set_uniform_ordered_Kk(self, clip=True):
		"""
		Set K1 and K2 where each receptor from same Gaussian, and the 
		tuning curves are ordered such that row one is centered at N1, etc.
		"""
		self.Kk1 = random_matrix([self.Mm, self.Nn], [self.uniform_Kk1_lo, 
								self.uniform_Kk1_hi], sample_type='uniform',
								seed = self.seed_Kk1)
		
		self.Kk2 = random_matrix([self.Mm, self.Nn], [self.uniform_Kk2_lo, 
								self.uniform_Kk2_hi], sample_type='uniform', 
								seed = self.seed_Kk2)
		if clip == True:
			array_dict = clip_array(dict(Kk1 = self.Kk1, Kk2 = self.Kk2))
			self.Kk1 = array_dict['Kk1']
			self.Kk2 = array_dict['Kk2']
							
		for iM in range(self.Mm):
			self.Kk2[iM, :] = sp.sort(self.Kk2[iM, :])
			tmp = sp.hstack((self.Kk2[iM, :], self.Kk2[iM, ::-1]))
			self.Kk2[iM, :] = tmp[::2]
			self.Kk2[iM, :] = sp.roll(self.Kk2[iM, :], iM*int(self.Nn/self.Mm))
Example #45
0
def make_amb(Fsorg,m_up,plen,pulse,nspec=128,winname = 'boxcar'):
    """
        Make the ambiguity function dictionary that holds the lag ambiguity and
        range ambiguity. Uses a sinc function weighted by a blackman window. Currently
        only set up for an uncoded pulse.

        Args:
            Fsorg (:obj:`float`): A scalar, the original sampling frequency in Hertz.
            m_up (:obj:`int`): The upsampled ratio between the original sampling rate and the rate of
            the ambiguity function up sampling.
            plen (:obj:`int`): The length of the pulse in samples at the original sampling frequency.
            nlags (:obj:`int`): The number of lags used.

        Returns:
            Wttdict (:obj:`dict`): A dictionary with the keys 'WttAll' which is the full ambiguity function
            for each lag, 'Wtt' is the max for each lag for plotting, 'Wrange' is the
            ambiguity in the range with the lag dimension summed, 'Wlag' The ambiguity
            for the lag, 'Delay' the numpy array for the lag sampling, 'Range' the array
            for the range sampling and 'WttMatrix' for a matrix that will impart the ambiguity
            function on a pulses.
    """
    nspec = int(nspec)
    nlags = len(pulse)
    # make the sinc
    nsamps = sp.floor(8.5*m_up)
    nsamps = int(nsamps-(1-sp.mod(nsamps, 2)))
    # need to incorporate summation rule
    vol = 1.
    nvec = sp.arange(-sp.floor(nsamps/2.0), sp.floor(nsamps/2.0)+1)
    pos_windows = ['boxcar', 'triang', 'blackman', 'hamming', 'hann',
                   'bartlett', 'flattop', 'parzen', 'bohman', 'blackmanharris',
                   'nuttall', 'barthann']
    curwin = scisig.get_window(winname, nsamps)
    # Apply window to the sinc function. This will act as the impulse respons of the filter
    outsinc = curwin*sp.sinc(nvec/m_up)
    outsinc = outsinc/sp.sum(outsinc)
    dt = 1/(Fsorg*m_up)
    #make delay vector
    Delay_num = sp.arange(-(len(nvec)-1),m_up*(nlags+5))
    Delay = Delay_num*dt

    t_rng = sp.arange(0, 1.5*plen, dt)
    if len(t_rng) > 2e4:
        raise ValueError('The time array is way too large. plen should be in seconds.')
    numdiff = len(Delay)-len(outsinc)
    numback = int(nvec.min()/m_up-Delay_num.min())
    numfront = numdiff-numback
#    outsincpad  = sp.pad(outsinc,(0,numdiff),mode='constant',constant_values=(0.0,0.0))
    outsincpad  = sp.pad(outsinc,(numback, numfront), mode='constant',
                         constant_values=(0.0, 0.0))
    (d2d, srng)=sp.meshgrid(Delay, t_rng)
    # envelop function
    t_p = sp.arange(nlags)/Fsorg
    envfunc = sp.interp(sp.ravel(srng-d2d), t_p,pulse, left=0., right=0.).reshape(d2d.shape)
#    envfunc = sp.zeros(d2d.shape)
#    envfunc[(d2d-srng+plen-Delay.min()>=0)&(d2d-srng+plen-Delay.min()<=plen)]=1
    envfunc = envfunc/sp.sqrt(envfunc.sum(axis=0).max())
    #create the ambiguity function for everything
    Wtt = sp.zeros((nlags, d2d.shape[0], d2d.shape[1]))
    cursincrep = sp.tile(outsincpad[sp.newaxis, :], (len(t_rng), 1))
    Wt0 = cursincrep*envfunc
    Wt0fft = sp.fft(Wt0, axis=1)
    for ilag in sp.arange(nlags):
        cursinc = sp.roll(outsincpad, ilag*m_up)
        cursincrep = sp.tile(cursinc[sp.newaxis, :], (len(t_rng), 1))
        Wta = cursincrep*envfunc
        #do fft based convolution, probably best method given sizes
        Wtafft = scfft.fft(Wta, axis=1)

        nmove = len(nvec)-1
        Wtt[ilag] = sp.roll(scfft.ifft(Wtafft*sp.conj(Wt0fft), axis=1).real,
                            nmove, axis=1)

    # make matrix to take
    imat = sp.eye(nspec)
    tau = sp.arange(-sp.floor(nspec/2.), sp.ceil(nspec/2.))/Fsorg
    tauint = Delay
    interpmat = spinterp.interp1d(tau, imat, bounds_error=0, axis=0)(tauint)
    lagmat = sp.dot(Wtt.sum(axis=1), interpmat)
    W0 = lagmat[0].sum()
    for ilag in range(nlags):
        lagmat[ilag] = ((vol+ilag)/(vol*W0))*lagmat[ilag]

    Wttdict = {'WttAll':Wtt, 'Wtt':Wtt.max(axis=0), 'Wrange':Wtt.sum(axis=1),
               'Wlag':Wtt.sum(axis=2), 'Delay':Delay, 'Range':v_C_0*t_rng/2.0,
               'WttMatrix':lagmat}
    return Wttdict
Example #46
0
def ddx(f):
    return (scipy.roll(f,1)-scipy.roll(f,-1))/(2.*dx)
Example #47
0
def d2dx2(f):
    return (scipy.roll(f,1)-2*f+scipy.roll(f,-1))/dx**2
Example #48
0
 def __init__(self, arr1, arr2, dt):
     self.delta_t = dt
     self.np1, self.np2 = np.array(arr1), np.array(arr2)
     self.err = np.array([scipy.absolute(scipy.roll(self.np2, dt*i)-self.np1).sum() for i in range(self.np1.size/dt)])
Example #49
0
def spectrumAnalyzer():
    global fftLen, capture_setting, signal_scale
    # ========================
    #  Capture Sound from Mic
    # ========================
    ch = capture_setting["ch"]
    fs = capture_setting["fs"]
    chunk = capture_setting["chunk"]

    p = pyaudio.PyAudio()
    apiCnt = p.get_host_api_count()

    # どのマイクが利用可能か?
    # print("Host API Count: %d" % apiCnt)
    # for cnt in range(apiCnt):
    # 	print(p.get_host_api_info_by_index(cnt))

    input_deveice_index = 1 # マイクの選択(どうせ1しか使えない...)

    stream = p.open(
                format=capture_setting["format"],
                channels=capture_setting["ch"],
                rate=capture_setting["fs"],
                input=True,
                frames_per_buffer=capture_setting["chunk"])

    ### FFT する信号の初期化
    signal = zeros(fftLen, dtype = float)

    # ========
    #  Layout
    # ========

    ### アプリケーション作成
    app = QtGui.QApplication([])
    app.quitOnLastWindowClosed()

    ### メインウィンドウ
    mainWindow = QtGui.QMainWindow()
    mainWindow.setWindowTitle("Spectrum Analyzer") # Title
    mainWindow.resize(800, 300) # Size

    ### キャンパス
    centralWid = QtGui.QWidget()
    mainWindow.setCentralWidget(centralWid)

    ### レイアウト!!
    lay = QtGui.QVBoxLayout()
    centralWid.setLayout(lay)

    ### スペクトル表示用ウィジット
    specWid = pg.PlotWidget(name="spectrum")
    specItem = specWid.getPlotItem()
    specItem.setMouseEnabled(y = False) # y軸方向に動かせなくする
    specItem.setYRange(0, 1000)
    specItem.setXRange(0, fftLen / 4, padding = 0) # デフォで表示する幅をいじれる

    ### Axis
    # X軸についてのいろいろプロット?
    specAxis = specItem.getAxis("bottom")
    specAxis.setLabel("Frequency [Hz]")

    specAxis.setScale(fs / 2. / (fftLen / 2 + 1))
    hz_interval = 1000
    # たぶん、この部分が適当
    newXAxis = (arange(int(fs / 2 / hz_interval)) + 1) * hz_interval

    oriXAxis = newXAxis / (fs / 2. / (fftLen / 2 + 1))
    specAxis.setTicks([zip(oriXAxis, newXAxis)])

    ### キャンパスにのせる
    lay.addWidget(specWid)

    ### ウィンドウ表示
    mainWindow.show()

    freq_list = np.fft.fftfreq( fftLen, d=capture_setting["fs"]**-1)
    np.savetxt( "output.txt", freq_list)
    print(type(freq_list))

    print(freq_list[0:len(freq_list)/2])
    print(len(freq_list)/2)

    sys.exit(-1)

    ### Update
    print("音声入力ループ")
    while 1:
      try:
        data = stream.read(chunk)
        # print("ok")
      except IOError as ex:
        # よくわからんけど、しばらく実行していると結構な頻度でミスってる
        if ex[1] != pyaudio.paInputOverflowed:
          raise
        data = '\x00' * chunk
        print("error")

      num_data = fromstring(data, dtype = "int16")
      signal = roll(signal, - chunk)
      # signal[- chunk :] = num_data
      # len(num_data) == chunk == shitf のはず
      signal[- len(num_data) :] = num_data
      fftspec = my_fft( signal)

      spec = abs(fftspec[1 : fftLen / 2 + 1] * signal_scale) # スペクトル
      print("Max : %.5f" % freq_list[np.argmax(spec)])

      specItem.plot( spec, clear = True)
      # specItem.plot( fftspec, clear = True)
      QtGui.QApplication.processEvents()
Example #50
0
# coding: utf-8

from scipy import identity
from scipy import dot, roll
from scipy.linalg import inv

I = identity(10) # (10*10) の単位行列

print I, "\n"

# 行列積
I_ar = dot(I, I.T)

print I_ar, "\n"

# 行列の回転(シフト)
I_roll_3 = roll(I, 3, axis = 1) # 第2次元を3つシフト

print I_roll_3, "\n"

# 逆行列
I_inv = inv(I) # 単位行列の逆行列は単位行列

print I_inv, "\n"
Example #51
0
def calculate_steps(contour):
    shifted = sp.roll(contour, 1)
    shifted[0] = 0
    return contour - shifted
Example #52
0
inPCM.setrate(fs)
inPCM.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inPCM.setperiodsize(chunk)
  
signal = zeros(fftLen, dtype = float)

tmpSound = 0
up = 0
down = 0
max = 0
count = 0

while 1: # Check Baby Crying or not
	length, data = inPCM.read()
        num_data = fromstring(data, dtype = "int16")
        signal = roll(signal, - chunk)
        signal[- chunk :] = num_data
        fftspec = fft(signal)
	babySound = abs(fftspec[146]*signal_scale) # This is may be baby's crying Hz (1000Hz)
	# First, check baby's minimum sound
	if babySound > 50 and babySound < 150:
		totalStartTimer = time.time() # Timer start
		totalEndTimer = 0
		
		while totalEndTimer - totalStartTimer < 50: # Check during 50 seconds
			totalEndTimer = time.time()
			
			if babySound >= tmpSound: # If recent sound is higher than previous sound, doubt baby's sound
				up = 1		  
				print "up"
				startTimer = time.time() # Start timer for filtering other sound
Example #53
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "f:nh", ["mom-file=", "no-idx", "help"])
        except getopt.GetoptError as msg:
            raise Usage(msg)

        for o, a in opts:
            if o in ["-h", "--help"]:
                print(" Usage: %s [OPTIONS] FILE" % argv[0], file=sys.stderr)
                print(" Options:", file=sys.stderr)
                print("  -f, --mom-file\t: Momentum list file (default: %s)" % default_mom_list,
                      file=sys.stderr)
                print("  -n, --no-idx\t\t: Suppress output of last index \n\t\t\t  (e.g. for scalar, pseudo-scalar where there is only a single entry)", file=sys.stderr)
                print("  -h, --help\t\t: This help message", file=sys.stderr)
                print 
                return 2

            elif o in ["-f", "--mom-file"]:
                user_mom_list = a

            elif o in ["-n", "--no-idx"]:
                user_suppress_idx = True

            else:
                print(" %s: ignoring unhandled option" % o, file=sys.stderr)

        if len(args) != 1:
            raise Usage(" Usage: %s [OPTIONS] FILE" % argv[0])

    except Usage as err:
        print(err.msg, file=sys.stderr)
        print(" for help use --help", file=sys.stderr)
        return 2

    try:
        mom_list = user_mom_list
    except NameError:
        mom_list = default_mom_list

    try:
        suppress_idx = user_suppress_idx
    except NameError:
        suppress_idx = default_suppress_idx

    ar = scipy.array
    fname = args[0]

    fp = open(fname, "rb")
    line = fp.readline().decode()
    ### first line should contain "begin-header"
    if line != "begin-header;\n":
        print("Malformed header")
        raise IOError

    ### Now get the rest of the header
    header = [line.split(";")[0],]
    while True:
        line = fp.readline()
        if len(line) == 0:
            print("File ended unexpectedly")
            raise IOError

        line = line.decode().split(";")[0]
        header.append(line)
        if line == "end-header":
            break

    ### The data
    buf = fp.read()
    fp.close()

    ### Header parser
    def parse(tag, header):
        line = [x for x in header if re.search(tag, x)]
        if len(line) != 1:
            print("%s not found in header" % tag)
            raise ValueError
    
        return line[0].split("=")[1].strip()


    dims = [int(x) for x in parse("lattice dimensions", header).split(",")]
    src_pos = [int(x) for x in parse("source position", header).split(",")]
    site_tags = [x.strip() for x in parse("lattice-site tags", header).split(",")]
    site_size = len(site_tags)
    t_ins = [int(x) for x in parse("t-insertions", header).split(",")]
    nt_ins = len(t_ins)

    nelems = site_size*nt_ins*dims[0]*dims[1]*dims[2]*2
    if len(buf) != nelems*8:
        print("binary data size miss-match")
        raise ValueError

    fmt = ">" + "".join(nelems*["d"])
    buf = struct.unpack(fmt, buf)
    buf = ar(buf).reshape([-1, 2])
    thrp = buf[:, 0] + complex(0, 1)*buf[:, 1]
    thrp = thrp.reshape([nt_ins, dims[2], dims[1], dims[0], site_size])

    for ax,shift in zip([0, 1, 2], [src_pos[2],src_pos[1],src_pos[0]]):
        thrp = scipy.roll(thrp, shift=-shift, axis=ax+1)

    thrp_p = []
    for t in range(nt_ins):
        p = []
        for s in range(site_size):
            x = thrp[t, :, :, :, s]
            p.append(scipy.fftpack.fftn(x))
        thrp_p.append(p)

    moms = open(mom_list, "r").readlines()
    moms = [x.split() for x in moms]
    moms = [[int(x) for x in y] for y in moms]
    for it,t in enumerate(t_ins):
        for k,s in enumerate(site_tags):
            name = s.replace("(", "").replace(")", "").split(":")[0]
            index = s.replace("(", "").replace(")", "").split(":")[1].strip()
            for m in moms:
                x = (dims[0] - m[0]) % dims[0]
                y = (dims[1] - m[1]) % dims[1]
                z = (dims[2] - m[2]) % dims[2]
                if suppress_idx:
                    print("%s %+d %+d %+d %+13.6e %+13.6e" % (t, m[0], m[1], m[2], 
                                                              thrp_p[it][k][z, y, x].real, 
                                                              thrp_p[it][k][z, y, x].imag))
                else:
                    print("%s %+d %+d %+d %+13.6e %+13.6e %s" % (t, m[0], m[1], m[2], 
                                                                 thrp_p[it][k][z, y, x].real, 
                                                                 thrp_p[it][k][z, y, x].imag, index))
                    
    return 0
  degree = sp.arccos(max*34000/10) ##34000: speed of sound wave, 10: distance of microphone array

  ##find noise direction
  ##delete 2 max value
  max_idx = a_csp.argmax(0)
  a_csp[max_idx] = 0
  max_idx = a_csp.argmax(0)
  a_csp[max_idx] = 0
  
  #find second max value 
  max_n = a_csp.max(0)/16000 #noise time interval
  max_n_idx = a_csp.argmax(0)
  degree_n = sp.arccos(max_n*34000/10)

  ##shift left wave to max_n_idx to normalize
  noise_nml_wave_l = sp.roll(wave_l, max_n_idx, 0)   
  for i in range(max_n_idx):
    noise_nml_wave_l[i] = 0

  ##substract right wave
  substract_wave = noise_nml_wave_l
  for i in range(sz_l):
    substract_wave[i] = wave_r[i] + noise_nml_wave_l[i]

  time_axis = sp.loadtxt('left.dat', usecols=(0,), unpack=True)
  output = sp.zeros((2, sz_l))
  output[0] = time_axis
  output[1] = noise_nml_wave_l
  output = sp.transpose(output)

  sp.savetxt('output.dat', output, fmt='%.10f', delimiter='\t', newline='\n')
def lagwindow_bw(window,lag_window,Fs):
    w_norm = window/s.sqrt(s.sum(window**2))
    l_shift = s.roll(lag_window,len(window)-1)
    return Fs/s.sum((l_shift*s.signal.correlate(w_norm,w_norm))**2)
Example #56
0
def spectrumAnalyzer():
	global fftLen, capture_setting, signal_scale
	##########################
	# Capture Sound from Mic #
	##########################
	ch = capture_setting["ch"]
	fs = capture_setting["fs"]
	chunk = capture_setting["chunk"]
	inPCM = alsaaudio.PCM(alsaaudio.PCM_CAPTURE)
	inPCM.setchannels(ch)
	inPCM.setrate(fs)
	inPCM.setformat(alsaaudio.PCM_FORMAT_S16_LE)
	inPCM.setperiodsize(chunk)

	signal = zeros(fftLen, dtype = float)

	##########
	# Layout #
	##########
	app = QtGui.QApplication([])
	app.quitOnLastWindowClosed()

	mainWindow = QtGui.QMainWindow()
	mainWindow.setWindowTitle("Spectrum Analyzer")
	mainWindow.resize(800, 300)

	centralWid = QtGui.QWidget()
	mainWindow.setCentralWidget(centralWid)

	lay = QtGui.QVBoxLayout()
	centralWid.setLayout(lay)

	specWid = pg.PlotWidget(name="spectrum")
	specItem = specWid.getPlotItem()
	specItem.setMouseEnabled(y = False)
	specItem.setYRange(0, 1000)
	specItem.setXRange(0, fftLen / 2, padding = 0)

	specAxis = specItem.getAxis("bottom")
	specAxis.setLabel("Frequency [Hz]")
	specAxis.setScale(fs / 2. / (fftLen / 2 + 1))
	hz_interval = 500
	newXAxis = (arange(int(fs / 2 / hz_interval)) + 1) * hz_interval
	oriXAxis = newXAxis / (fs / 2. / (fftLen / 2 + 1))
	specAxis.setTicks([zip(oriXAxis, newXAxis)])

	lay.addWidget(specWid)

	mainWindow.show()

	# update
	for time in range(100):
		length, data = inPCM.read()
		num_data = fromstring(data, dtype = "int16")
		signal = roll(signal, - chunk)
		signal[- chunk :] = num_data
		fftspec = fft(signal)

		print signal[1800:1900]
		specItem.plot(abs(fftspec[1 : fftLen / 2 + 1] * signal_scale), clear = True)
		QtGui.QApplication.processEvents()