Beispiel #1
0
    def __init__(self,hue,sat,val):
        """Each matrix must be the same size, with values in the range 0.0 to 1.0."""
        shape = hue.shape # Assumed same as sat.shape and val.shape
        rmat = Numeric.zeros(shape,Numeric.Float)
        gmat = Numeric.zeros(shape,Numeric.Float)
        bmat = Numeric.zeros(shape,Numeric.Float)

        # Note: should someday file a feature request for PIL for them
        # to accept an image of type 'HSV', so that they will do this
        # conversion themselves, without us needing an explicit loop
        # here.  That should speed this up.
        ch = hue.clip(0.0,1.0)
        cs = sat.clip(0.0,1.0)
        cv = val.clip(0.0,1.0)

        for i in range(shape[0]):
            for j in range(shape[1]):
                r,g,b = hsv_to_rgb(ch[i,j],cs[i,j],cv[i,j])
                rmat[i,j] = r
                gmat[i,j] = g
                bmat[i,j] = b

        rImage = self._arrayToImage(rmat)
        gImage = self._arrayToImage(gmat)
        bImage = self._arrayToImage(bmat)

        super(HSVBitmap,self).__init__(Image.merge('RGB',(rImage,gImage,bImage)))
Beispiel #2
0
 def _sendchipdata(self, pbStep):
     if self._chipdataN != None:
         # approximation
         coefs = Numeric.zeros((self._chipdataN.shape[0], self.kernelSize+1, self._chipdataN.shape[2]), Numeric.Float)
         curves = Numeric.zeros(self._chipdataN.shape, Numeric.Float)
         if self.kernel == 0:
             appx = chipappx.ApproxOrthPolyBasis(range(self._chipdataN.shape[1]), self.kernelSize+1)
             self.progressBarAdvance(pbStep)
             for idx2 in range(self._chipdataN.shape[2]):
                 if self.useSignificance and self.cbUseSignificance.isEnabled():
                     coefs[:,:,idx2] = appx.getAppxCoef2d_significant(self._chipdataN[:,:,idx2], self.kernelSize+1, self.alphas[self.alpha])
                 else:
                     coefs[:,:,idx2] = appx.getAppxCoef(self._chipdataN[:,:,idx2])
                 self.progressBarAdvance(pbStep)
                 curves[:,:,idx2] = appx.getAppxCurve(coefs[:,:,idx2])
                 self.progressBarAdvance(pbStep)
         elif self.kernel == 1:
             appx = chipappx.TrigonomerticBasis(self._chipdataN.shape[1], self.kernelSize+1)
             self.progressBarAdvance(pbStep)
             for idx2 in range(self._chipdataN.shape[2]):
                 # 2007-10-11: trigonometric functions do not use getAppxCoef2d_significant
                 #if self.useSignificance and self.cbUseSignificance.isEnabled():
                 #    coefs[:,:,idx2] = appx.getAppxCoef2d_significant(self._chipdataN[:,:,idx2], self.kernelSize+1, self.alphas[self.alpha])
                 #else:
                 coefs[:,:,idx2] = appx.getAppxCoef(self._chipdataN[:,:,idx2])
                 self.progressBarAdvance(pbStep)
                 curves[:,:,idx2] = appx.getAppxCurve(coefs[:,:,idx2])
                 self.progressBarAdvance(pbStep)
         chipcoefNew = []    # [(dirname0, [etCoef0, etCoef1, ...]), ...]
         chipcurvesNew = []  # [(dirname0, [etCurves0, etCurves1, ...]), ...]
         idxTotal = 0
         for (dirname, etList) in self._chipdata:
             etCoefListNew = []
             etCurvesListNew = []
             for et in etList:
                 # domain with class and metas
                 if et.domain.classVar != None:
                     domainClassMetas = orange.Domain([et.domain.classVar])
                 else:
                     domainClassMetas = orange.Domain([])
                 domainClassMetas.addmetas(et.domain.getmetas())
                 # exampleTable with class and metas
                 etClassMetas = orange.ExampleTable(domainClassMetas, et)
                 # appx. coefficients
                 domainCoef = orange.Domain(map(lambda x: orange.FloatVariable("C%i" % x), range(coefs.shape[1])), None)
                 etCoef = orange.ExampleTable(domainCoef, coefs[:,:,idxTotal].tolist())
                 etCoefListNew.append(orange.ExampleTable([etCoef, etClassMetas]))
                 etCoefListNew[-1].name = et.name
                 # appx. curve
                 etCurve = orange.ExampleTable(orange.Domain(et.domain.attributes, None), curves[:,:,idxTotal].tolist())
                 etCurvesListNew.append(orange.ExampleTable([etCurve, etClassMetas]))
                 etCurvesListNew[-1].name = et.name
                 idxTotal += 1
             chipcoefNew.append((dirname, etCoefListNew))
             chipcurvesNew.append((dirname, etCurvesListNew))
         self.send("Approximated Structured Data", chipcurvesNew)
         self.send("Structured Approximation Coefficients", chipcoefNew)
     else:
         self.send("Approximated Structured Data", None)
         self.send("Structured Approximation Coefficients", None)
    def extrude(self):
        """Virtual Method to do the extrusion along a 3D path with a 2D shape
        using the gle extrusion. We then get the geometry information
        using the extrusion method in Feedback mode. This will then be
        used to build a triangle strip."""
        
        from gle import glec
        gle.gleSetJoinStyle ( self.normalStyle | self.joinStyle )
        glec.gleFeedBack()

        contpts = Numeric.array(self.shape2D.contpts)
        contourPoints = contpts[:,:2]
        contnorm = Numeric.array(self.shape2D.contnorm)
        contourNormals = contnorm[:,:2]
        
        gle.gleExtrusion(contourPoints, contourNormals,
                         self.contourUp,
                         self.trace3D,
                         self.materials[1028].prop[0][:,:3] )

        glec.gleTextureMode(0)
        v,n,s = glec.gleGetTriangleMesh()

        vinv = Numeric.zeros( v.shape, 'd')
        vinv[::2] = v[1::2]
        vinv[1::2] = v[::2]

        ninv = Numeric.zeros( n.shape, 'd')
        ninv[::2] = n[1::2]
        ninv[1::2] = n[::2]

        return vinv, ninv, s
Beispiel #4
0
def sn(signal,noise,stime,npatches):
    """Compute the optimal S/N for signal, sampled at intervals of
    stime, and for the total duration represented in the array, against noise
    represented by the time series noise; npatches overlapping periods are used
    to estimate the PSD of the noise."""

    # compute signal spectrum without windowing or averaging
    sspec = spect(signal,stime,0)

    # compute the noise spectrum, using segment averaging
    nspec = spect(noise,stime,npatches)

    # interpolate the noise to be defined on the same frequencies
    # of the signal's spectrum

    ispec = Numeric.zeros(Numeric.shape(sspec),dtype='d')
    ispec[:,0] = sspec[:,0]

    # ispec[:,1] = arrayfns.interp(nspec[:,1],nspec[:,0],ispec[:,0])
    ispec[:,1] = linearinterpolate(nspec[:,1],nspec[:,0],ispec[:,0])

    # the (S/N)^2 is given by 2T times the integrated ratio
    # of the spectral densities (the factor of 2 because the spectral
    # density is one-sided); notice however that the df is 1/T,
    # so we need only to sum up the array containing the ratio,
    # and multiply by two

    sratio = Numeric.zeros(Numeric.shape(sspec)[0],dtype='d')
    sratio[1:] = sspec[1:,1] / ispec[1:,1]
    sn2 = 2.0 * sum(sratio[1:])

    return math.sqrt(sn2)
    def derivatives(self):
        # make array of numbers
        depthString = self.getDepthString()
        self.depth = Numeric.array(depthString, 'c')[2::4].astype(Numeric.Int8)
        self.dsq = Numeric.reshape(self.depth, (self.w, self.h))
        self.fstD = Numeric.zeros((self.w, self.h), Numeric.Int8)
        self.sndD = Numeric.zeros((self.w, self.h), Numeric.Int8)
        self.deriv = Numeric.zeros((self.w, self.h), Numeric.Int8)

        for i in range(1, self.w-1):
            for j in range(1, self.h-1):
                a, b = self._derivatives(i,j)
                self.fstD[i][j] = a
                self.sndD[i][j] = b
                self.deriv[i][j] = max(a, b)
                
#        self.deriv = Numeric.choose( Numeric.greater(self.fstD,self.sndD),
#                                     (self.fstD,self.sndD) )

        self.fstDim = Image.fromstring('P', (self.w,self.h),
                                       self.fstD.tostring())

        self.sndDim = Image.fromstring('P', (self.w,self.h),
                                       self.sndD.tostring())
        
        self.derivim = Image.fromstring('P', (self.w,self.h),
                                        self.deriv.tostring() )
Beispiel #6
0
def read_chk(file):
    file = open(chkfile,mode='rb')
    n = array.array('i')
    n.read(file, 1)
    naa=n[0]
    str = array.array('c')
    str.read(file,naa)
    seq = str.tostring()
    out =N.zeros((naa,20), typecode=N.Float64)
    col =N.zeros((naa), typecode=N.Int)
    quality = N.zeros((naa), typecode=N.Float64)

    for i in range(naa):
        v = array.array('d')
        v.read(file,20)
        data=N.array(v, typecode=N.Float64)
        if sum(data)==0:
            col[i] = 0
            for j in range(20):
                out[i,j] = qij[aaNum[seq[i]],j]
        else:
            col[i] = 1
            for j in range(20):
                out[i,j] = data[mapping[j]]
        for k in [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]:
            quality[i] = quality[i] - out[i,k]*log(out[i,k])
    file.close()
    return naa, seq, out, col, quality
Beispiel #7
0
 def test_sequenceRepeats(self):
     """match2seq sequence repeat test"""
     seq1 = 'ABCDEFG~~~~~~~~~~~~~~~'
     seq2 = '~~~~~'
     mask1, mask2 = compareSequences( seq1, seq2 )
     self.assert_( N.all( mask1 == N.zeros( len(seq1 ) )) )
     self.assert_( N.all( mask2 == N.zeros( len(seq2 ) )) )
def MaxInnerProd(ser1, ser2, PSD):
  size = Numeric.shape(ser1)[0]
  pdlen = size/2
  nyquistf = 0.5/15.0   #   !!! hardcoded !!!!
  freqs = Numeric.arange(0,pdlen+1,dtype='d') * (nyquistf / pdlen)
  if(Numeric.shape(ser2)[0] != size):
     print "size of time series must be the same"
     sys.exit(1)
  if(Numeric.shape(PSD)[0] != pdlen):
     print "wrong size of psd: ", pdlen, Numeric.shape(PSD)
     sys.exit(1)
  fourier1 = FFT.fft(ser1)
  fourier2 = FFT.fft(ser2)
  prod1 = Numeric.zeros(pdlen+1, dtype='d')
  prod2 = Numeric.zeros(pdlen+1, dtype='d')
  prod1[0] = 0.0
  prod1[1:pdlen] = numpy.multiply(fourier1[1:pdlen],numpy.conjugate(fourier2[1:pdlen])) + numpy.multiply(fourier1[-1:pdlen:-1],numpy.conjugate(fourier2[-1:pdlen:-1]))
  prod1[pdlen] = fourier1[pdlen]*fourier2[pdlen]
  prod2[0] = 0.0
  prod2[1:pdlen] = numpy.multiply(fourier1[1:pdlen],numpy.conjugate(fourier2[1:pdlen]*1.j)) + numpy.multiply((fourier1[-1:pdlen:-1]),numpy.conjugate(fourier2[-1:pdlen:-1]*(-1.j)))
  prod2[pdlen] = fourier1[pdlen]*fourier2[pdlen]
  Numeric.divide(prod1[1:], PSD, prod1[1:]) 
  Numeric.divide(prod2[1:], PSD, prod2[1:]) 
  olap0 = 0.0
  olappiby2 = 0.0
  for i in xrange(pdlen):
      if (freqs[i] > fLow and freqs[i]<= fHigh):
           olap0 += prod1[i]
	   olappiby2 += prod2[i]
  olap0 = 2.0*olap0/float(size)
  olappiby2 = 2.0*olappiby2/float(size)
#  olap0 =  2.0*(numpy.sum(prod1[1:]))/float(size) #it must be scaled by dt
#  olappiby2 =  2.0*(numpy.sum(prod2[1:]))/float(size) #it must be scaled by dt
  print "angle of maxim. = ", math.atan(olappiby2/olap0)
  return sqrt(olap0**2 + olappiby2**2) 
Beispiel #9
0
 def getAppxCoef2d_pVals(self, arr2d, maxNumCoef):
     """Returns[:,j] the probability that coef. j and all subsequent coef. are equal to 0.
     Reference: Ott, pp.606.
     Use only the first k appx. coef. with pvals below some alpha.
     
     The significance of the coef. estimated by comparing the variance drop of the model2 with the variance of the model1, where:
       model 1: complete model with maxNumCoef coef. different from 0
       model 2: reduced model with coef. in range (0,k) different from 0
     null hypothesis (H0): coef. k,k+1,...,maxNumCoef are equal to 0
         if H0 rejected (pval below some alpha (e.g. 0.05) -> there exist an important coef. among coef. k,k+1,...,maxNumCoef
     repeat the test for k=0,1,...maxNumCoef-1
     """
     assert len(arr2d.shape) == 2, "2d array expected"
     assert 0 < maxNumCoef <= self.k
     coefMax = self.getAppxCoef(arr2d, maxNumCoef)
     curveMax = self.getAppxCurve(coefMax)
     SSE1 = Numeric.add.reduce((arr2d-curveMax)**2,1)
     MSE1 = SSE1 / (arr2d.shape[1]-maxNumCoef)
     #print "SSE1[0], MSE1[0]",SSE1[0], MSE1[0]
     pvals = Numeric.zeros((arr2d.shape[0], maxNumCoef), Numeric.Float)
     for k in range(maxNumCoef):  # test cofInd: [maxNum-1, maxNum-2, ..., minNum]
         #print "Keeping %i coeff" % (k)
         shpk = list(coefMax.shape)
         shpk[1] -= k
         coefk = Numeric.concatenate((coefMax[:,:k], Numeric.zeros((shpk), Numeric.Float)),1)
         curvek = self.getAppxCurve(coefk)
         SSE2 = Numeric.add.reduce((arr2d-curvek)**2,1)
         MSdrop =(SSE2-SSE1) / (maxNumCoef-k)
         F = MSdrop / MSE1
         #2007-10-11: F -> F.filled(???)
         pvals[:,k] = scipy.stats.fprob((maxNumCoef-k), arr2d.shape[1]-maxNumCoef, F.filled(ApproxOrthPolyBasis._F_fillValue))
     return pvals
Beispiel #10
0
    def test_loadDataset(self):
        the_data = UTisocontour.loadDataset(UTisocontour.CONTOUR_FLOAT,
                                      UTisocontour.CONTOUR_REG_3D, 3, 1,
                                      ["pot-2eti-glucose-3fields.raw"]);


        isovar   = 0
        timestep = 0
        isovalue = 0.23

        isoc = UTisocontour.getContour3d(the_data, isovar, timestep, isovalue,
                                       UTisocontour.NO_COLOR_VARIABLE)

        print("nvert:", isoc.nvert)
        print("ntri:", isoc.ntri)
        #assert isoc.nvert == 12816
        assert isoc.nvert == 3204
        assert isoc.ntri == 6392
        vert = Numeric.zeros((isoc.nvert,3)).astype('f')
        norm = Numeric.zeros((isoc.nvert,3)).astype('f')
        col = Numeric.zeros((isoc.nvert)).astype('f')
        tri = Numeric.zeros((isoc.ntri,3)).astype('i')
        UTisocontour.getContour3dData(isoc, vert, norm, col, tri, 0)

        # signature stuff
        nsig = UTisocontour.getNumberOfSignatures(the_data)
        sig0 = UTisocontour.getSignatureFunctions(the_data, 0, 0)
        sig1 = UTisocontour.getSignatureFunctions(the_data, 1, 0)
        sig2 = UTisocontour.getSignatureFunctions(the_data, 2, 0)
        print(sig0.name, sig0.nval)
        print(sig1.name, sig1.nval)
        print(sig2.name, sig2.nval)

        print("signatureValues:", UTisocontour.getSignatureValues(the_data, 0, 0, 0.23))
Beispiel #11
0
def newMap(width, height):
    global m, mt
    m = Numeric.zeros((width, height))     
    mt = Numeric.zeros((width, height), 'O')
    (w, h) = m.shape
    for i in xrange(0, w):
        for j in xrange(0, h):
            mt[i,j] = t
Beispiel #12
0
def findQuaternionMatrix(collection, point_ref, conf1, conf2 = None, matrix = True ):
	
        universe = collection.universe()
        if conf1.universe != universe:
                raise ValueError, "conformation is for a different universe"
        if conf2 is None:
                conf1, conf2 = conf2, conf1
        else:
                if conf2.universe != universe:
                        raise ValueError, "conformation is for a different universe"
        ref = conf1
        conf = conf2
        weights = universe.masses()
        weights = weights/collection.mass()
        ref_cms = point_ref.position().array
        pos = N.zeros((3,), N.Float)
        pos = point_ref.position(conf).array
        possq = 0.
        cross = N.zeros((3, 3), N.Float)
        for a in collection.atomList():
                r = a.position(conf).array - pos
                r_ref = a.position(ref).array-ref_cms
                w = weights[a]
                possq = possq + w*N.add.reduce(r*r) \
                                                + w*N.add.reduce(r_ref*r_ref)
                cross = cross + w*r[:, N.NewAxis]*r_ref[N.NewAxis, :]
        k = N.zeros((4, 4), N.Float)
        k[0, 0] = -cross[0, 0]-cross[1, 1]-cross[2, 2]
        k[0, 1] = cross[1, 2]-cross[2, 1]
        k[0, 2] = cross[2, 0]-cross[0, 2]
        k[0, 3] = cross[0, 1]-cross[1, 0]
        k[1, 1] = -cross[0, 0]+cross[1, 1]+cross[2, 2]
        k[1, 2] = -cross[0, 1]-cross[1, 0]
        k[1, 3] = -cross[0, 2]-cross[2, 0]
        k[2, 2] = cross[0, 0]-cross[1, 1]+cross[2, 2]
        k[2, 3] = -cross[1, 2]-cross[2, 1]
        k[3, 3] = cross[0, 0]+cross[1, 1]-cross[2, 2]
        for i in range(1, 4):
                for j in range(i):
                        k[i, j] = k[j, i]
        k = 2.*k
        for i in range(4):
                k[i, i] = k[i, i] + possq - N.add.reduce(pos*pos)
        import numpy.oldnumeric.linear_algebra as LinearAlgebra
        e, v = LinearAlgebra.eigenvectors(k)
        i = N.argmin(e)
        v = v[i]
        if v[0] < 0: v = -v
        if e[i] <= 0.:
                rms = 0.
        else:
                rms = N.sqrt(e[i])
	if matrix:
		emax = N.argmax(e)
		QuatMatrix = v
		return Quaternion.Quaternion(QuatMatrix),v, e, e[i],e[emax], rms
	else:
		return Quaternion.Quaternion(v), Vector(ref_cms), Vector(pos), rms
def glXQueryExtension( dpy):
    """
    dpy - Display*
return - bool, int, int: support, errorBase, eventBase
"""
    errorBase = Numeric.zeros( 1, Numeric.Int32)
    eventBase = Numeric.zeros( 1, Numeric.Int32)
    res = _glxlib.glXQueryExtension( dpy, errorBase, eventBase)
    return res, errorBase[ 0], eventBase[ 0]
def glXQueryVersion( dpy):
    """
    dpy - Display*
return - bool, int, int: support, major, minor
"""
    major = Numeric.zeros( 1, Numeric.Int32)
    minor = Numeric.zeros( 1, Numeric.Int32)
    res = _glxlib.glXQueryVersion( dpy, major, minor)
    return res, major[ 0], minor[ 0]
Beispiel #15
0
def lowess2(x, y, xest, f=2./3., iter=3):
    """Returns estimated values of y in data points xest (or None if estimation fails).
    Lowess smoother: Robust locally weighted regression.
    The lowess function fits a nonparametric regression curve to a scatterplot.
    The arrays x and y contain an equal number of elements; each pair
    (x[i], y[i]) defines a data point in the scatterplot. The function returns
    the estimated (smooth) values of y.

    The smoothing span is given by f. A larger value for f will result in a
    smoother curve. The number of robustifying iterations is given by iter. The
    function will run faster with a smaller number of iterations."""
    x = Numeric.asarray(x, 'd')
    y = Numeric.asarray(y, 'd')
    xest = Numeric.asarray(xest, 'd')
    n = len(x)
    nest = len(xest)
    r = min(int(Numeric.ceil(f*n)),n-1) # radius: num. of points to take into LR
    h = [Numeric.sort(abs(x-x[i]))[r] for i in range(n)]    # distance of the r-th point from x[i]
    w = Numeric.clip(abs(([x]-Numeric.transpose([x]))/h),0.0,1.0)
    w = 1-w*w*w
    w = w*w*w
    hest = [Numeric.sort(abs(x-xest[i]))[r] for i in range(nest)]    # r-th min. distance from xest[i] to x
    west = Numeric.clip(abs(([xest]-Numeric.transpose([x]))/hest),0.0,1.0)  # shape: (len(x), len(xest)
    west = 1-west*west*west
    west = west*west*west
    yest = Numeric.zeros(n,'d')
    yest2 = Numeric.zeros(nest,'d')
    delta = Numeric.ones(n,'d')
    try:
        for iteration in range(iter):
            # fit xest
            for i in range(nest):
                weights = delta * west[:,i]
                b = Numeric.array([sum(weights*y), sum(weights*y*x)])
                A = Numeric.array([[sum(weights), sum(weights*x)], [sum(weights*x), sum(weights*x*x)]])
                beta = LinearAlgebra.solve_linear_equations(A,b)
                yest2[i] = beta[0] + beta[1]*xest[i]
            # fit x (to calculate residuals and delta)
            for i in range(n):
                weights = delta * w[:,i]
                b = Numeric.array([sum(weights*y), sum(weights*y*x)])
                A = Numeric.array([[sum(weights), sum(weights*x)], [sum(weights*x), sum(weights*x*x)]])
                beta = LinearAlgebra.solve_linear_equations(A,b)
                yest[i] = beta[0] + beta[1]*x[i]
            residuals = y-yest
            s = MLab.median(abs(residuals))
            delta = Numeric.clip(residuals/(6*s),-1,1)
            delta = 1-delta*delta
            delta = delta*delta
    except LinearAlgebra.LinAlgError:
        print "Warning: NumExtn.lowess2: LinearAlgebra.solve_linear_equations: Singular matrix"
        yest2 = None
    return yest2
    def _FirstValues(self, data=None, shape=None, datatype=None):
        if __debug__:
         if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
	"""Set the initial set of values, always returns a copy"""

	if data is not None:
	    if len(data)==0:
	        self.ashape = (0,) + self.ashape[1:]
		return Numeric.zeros( self.ashape, self.type)
	    elif isarray(data):  # data is an Numeric array
		if not datatype:
		    if self.type: datatype = self.type
		    else: raise AttributeError('I Need a datatype')

		if data.typecode() == self.type: # right type
		    if shape is None: self.ashape = data.shape
		    if data.shape == self.ashape: return Numeric.array(data)
		    else: return Numeric.reshape(data, shape )
		else: # bad type
		    data = data.astype(datatype)
		    if shape is None: self.ashape = data.shape
#		    if data.shape == self.ashape: return Numeric.array(data)
		    if data.shape == self.ashape: return data
		    else: return Numeric.reshape(data, shape)

	    else: # data is not an array
		if datatype and shape:
		    data = Numeric.array( data, self.type)
		    return Numeric.reshape( data, shape )
		elif datatype:
		    d=Numeric.array( data, datatype)
		    self.ashape = d.shape
		    return d
		else:
                    try:
                        d=Numeric.array( data,  self.type)
                    except ValueError:
                        raise ValueError('Bad argument')
		    if d.dtype.char in Numeric.typecodes['Integer'] or \
		       d.dtype.char in Numeric.typecodes['UnsignedInteger']:
			d=Numeric.array( data, viewerConst.IPRECISION)
		    else:
			d=Numeric.array( data, viewerConst.FPRECISION)
		    self.ashape = d.shape
		    return d

	else: # No data
		if datatype and shape:
		    d = Numeric.zeros( (0,), self.type)
		    d.shape = shape
		    return  d
		else:
		    raise AttributeError('I Need a datatype and a shape')
Beispiel #17
0
 def __init__(self, points, k, normalization=NORM_NORM_T0_1, force=False):
     """
     calculate k polynomials of degree 0 to k-1 orthogonal on a set of distinct points
     map points to interval [-1,1]
     INPUT:  points: array of dictinct points where polynomials are orthogonal
             k: number of polynomials of degree 0 to k-1
             force=True creates basis even if orthogonality is not satisfied due to numerical error
     USES:   x: array of points mapped to [-1,1]
             T_: matrix of values of polynomials calculated at x, shape (k,len(x))
             TT_ = T_ * Numeric.transpose(T_)
             TTinv_ = inverse(TT_)
             sc_: scaling factors
             a, b: coefficients for calculating T (2k-4 different from 0, i.e. 6 for k=5)
             n: number of points = len(points)
             normalization = {0|1|2}
     """
     self.k = k  # number of basis polynomials of order 0 to k-1
     self._force = force
     self.points = Numeric.asarray(points, Numeric.Float)
     self.pointsMin = min(points)
     self.pointsMax = max(points)
     # scaling x to [-1,1] results in smaller a and b, T is not affected; overflow is NOT a problem!
     self.xMin = -1
     self.xMax = 1
     self.x = self._map(self.points, self.pointsMin, self.pointsMax, self.xMin, self.xMax)
     # calculate basis polynomials
     self.n = len(points) # the number of approximation points
     t = Numeric.zeros((k,self.n),Numeric.Float)
     a = Numeric.zeros((k,1),Numeric.Float)
     b = Numeric.zeros((k,1),Numeric.Float)
     t[0,:] = Numeric.ones(self.n,Numeric.Float)
     if k > 1: t[1,:] = self.x - sum(self.x)/self.n
     for i in range(1,k-1):
         a[i+1] = Numeric.innerproduct(self.x, t[i,:] * t[i,:]) / Numeric.innerproduct(t[i,:],t[i,:])
         b[i] = Numeric.innerproduct(t[i,:], t[i,:]) / Numeric.innerproduct(t[i-1,:],t[i-1,:])
         t[i+1,:] = (self.x - a[i+1]) * t[i,:] - b[i] * t[i-1,:]
     self.a = a
     self.b = b
     # prepare for approximation
     self._T0 = t
     # orthonormal
     _TT0 = Numeric.matrixmultiply(self._T0, Numeric.transpose(self._T0))
     self.sc1 = Numeric.sqrt(Numeric.reshape(Numeric.diagonal(_TT0),(self.k,1))) # scaling factors = sqrt sum squared self._T0
     self._T1 = self._T0 / self.sc1
     # orthonormal and T[0] == 1
     self.sc2 = Numeric.sqrt(Numeric.reshape(Numeric.diagonal(_TT0),(self.k,1)) / self.n) # scaling factors = sqrt 1/n * sum squared self._T0
     self._T2 = self._T0 / self.sc2
     # T[:,-1] == 1
     self.sc3 = Numeric.take(self._T0, (-1,), 1) # scaling factors = self._T0[:,-1]
     self._T3 = self._T0 / self.sc3
     # set the variables according to the chosen normalization
     self.setNormalization(normalization)
    def ResetTransformation(self, redo=1):
        if __debug__:
         if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
        """Reset the tranformations (Rotation, translation, pivot, scale)"""
	self.rotation = Numeric.identity(4).astype('f')
	self.rotation.shape = (16, )
	self.translation = Numeric.zeros( (3,), 'f')
	self.pivot = Numeric.zeros( (3,), 'f')
	self.scale = Numeric.ones( (3,), 'f')
        if self.viewer:
            if self.viewer.currentObject != self.viewer.rootObject \
               and redo:
                self.viewer.deleteOpenglList()
Beispiel #19
0
    def loadString(mapname, text):
        compiled = compile(text, mapname, 'exec')
        localVars = {}
        eval(compiled, {}, localVars)
        mapData = localVars

        if mapData["VERSION"] != 1:
            raise "Map version %d not supported" % mapData["VERSION"]
        width = mapData['WIDTH']
        height = mapData['HEIGHT']
#        tilePropertiesTemplate = {}
        waterHeight = 0
        waterColor = [0.3, 0.3, 0.6]
        if mapData.has_key('WATER_HEIGHT'):
            waterHeight = mapData['WATER_HEIGHT']
        if mapData.has_key('WATER_COLOR'):
            waterColor = mapData['WATER_COLOR']
        if mapData.has_key('TILE_PROPERTIES'):
            tags = mapData['TILE_PROPERTIES']
            for k in tags.keys():
                tags[k]['name'] = k
                if not tags[k].has_key('waterColor'):
                    tags[k]['waterColor'] = waterColor
                if not tags[k].has_key('waterHeight'):
                    tags[k]['waterHeight'] = waterHeight
        else:
            tags = {}
        layoutLines = mapData['LAYOUT'].split('\n')
        layoutLines.pop(0)
        zdata = Numeric.zeros((width, height))
        tileProperties = Numeric.zeros((width, height), Numeric.PyObject)
        y = 0
        for line in layoutLines:
            if re.match(re.compile(r'^\s*$'), line):
                continue
            tiles = re.split(re.compile(r'\s+(?!-?\d+,)(?!-?\d+\])'), line)
            for x in xrange(0, width):
                tileData = tiles[x]
                tileProperties[x,y] = {}
                m = re.match(re.compile(
                    r'(\d+)(\[(-?\d+), (-?\d+), (-?\d+), (-?\d+)\])?(wh(\d+))?(\w*)'), tileData)
                zdata[x,y] = int(m.group(1))
                tileProperties[x,y]['tag'] = m.group(9)
                if m.group(2) != None:
                    tileProperties[x,y]['cornerHeights'] = [int(m.group(3)),int(m.group(4)),int(m.group(5)),int(m.group(6))]
                if m.group(7) != None:
                    tileProperties[x,y]['waterHeight'] = int(m.group(8))
            y += 1
        m = Map(width, height, zdata, tileProperties, waterHeight, waterColor, tags)
        m.setLoadString(text)
        return m
def computeIsocontour(isovalue, data):
    isoc = isocontour.getContour3d(data, 0, 0, isovalue,
                                   isocontour.NO_COLOR_VARIABLE)

    if isoc.nvert==0 or isoc.ntri==0:
        return [], [], []
    vert = Numeric.zeros((isoc.nvert,3)).astype('f')
    norm = Numeric.zeros((isoc.nvert,3)).astype('f')
    col = Numeric.zeros((isoc.nvert)).astype('f')
    tri = Numeric.zeros((isoc.ntri,3)).astype('i')
    isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)
    if len(vert) == 0 or len(tri) == 0:
         return [], [], []
    return vert, tri, norm
Beispiel #21
0
def random2DArray( matrix, ranNr=1, mask=None):
    """
    Create randomized 2D array containing ones and zeros.

    @param matrix: matrix to randomize
    @type  matrix: 2D array
    @param mask: mask OR None (default: None)
    @type  mask: list(1|0)
    @param ranNr: number of matricies to add up (default: 1)
    @type  ranNr: integer

    @return: 2D array or |ranNr| added contact matricies
    @rtype:2D array

    @raise MathUtilError: if mask does not fit matrix
    """
    ## get shape of matrix
    a,b = N.shape( matrix )

    ## get array from matrix that is to be randomized
    if mask is not None:
        if len(mask) == len( N.ravel(matrix) ):
            array = N.compress( mask, N.ravel(matrix) )

        if len(mask) != len( N.ravel(matrix) ):
            raise MathUtilError(
                'MatUtils.random2DArray - mask of incorrect length' +
                '\tMatrix length: %i Mask length: %i'\
                %(len( N.ravel(matrix) ), len(mask)))

    if not mask:
        array = N.ravel(matrix)

    ## number of ones and length of array
    nOnes = int( N.sum( array ) )
    lenArray = len( array )
    ranArray = N.zeros( lenArray )

    ## create random array
    for n in range(ranNr):
        ranArray += randomMask( nOnes, lenArray )

    ## blow up to size of original matix
    if mask is not None:
        r = N.zeros(a*b)
        N.put( r, N.nonzero(mask), ranArray)
        return N.reshape( r, (a,b) )

    if not mask:
        return  N.reshape( ranArray, (a,b) )
Beispiel #22
0
 def __init__(self, pnts):
     pnts = numerix.transpose(numerix.asarray(pnts, numerix.Float))
     npnts = pnts.shape[1]
     if npnts < 3:
         raise NURBSError, 'Point sequence error'
     cntrl = numerix.zeros((pnts.shape[0], 2 * npnts - 2), numerix.Float)
     cntrl[:,0] = pnts[:,0]
     cntrl[:,-1] = pnts[:,-1]
     cntrl[:,1:-2:2] = pnts[:,1:-1]
     cntrl[:,2:-1:2] = pnts[:,1:-1]
     uknots = numerix.zeros(npnts * 2, numerix.Float)
     uknots[0::2] = numerix.arange(npnts)
     uknots[1::2] = numerix.arange(npnts)
     Crv.__init__(self, cntrl, uknots)
    def GetMatrix(self, root=None, instance=None, scale=True, transpose=True):
        if __debug__:
         if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
	"""Returns the matrix by which this object is transformed
scale = False: returns the rotation and translation. no scaling info included
               Used to save the transformed geom --> coords --> new pdb file
instance is a list of integer instance indices for all parents
"""
        if root is None:
            root = self.viewer.rootObject

        if instance is None:
            instance = [0]
            p = self.parent
            while p:
                instance.append(0)
                p = p.parent

        GL.glPushMatrix()
        GL.glLoadIdentity()
        #print 'GetMatrix', instance
        self.BuildMat(self, root, scale, instance)
        #GL.glMultMatrixf(self.instanceMatricesFortran[instanceList[0]]])
        m = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f')
        GL.glPopMatrix()
        if Numeric.alltrue(m==Numeric.zeros(16).astype('f')):
            # this happens when Pmv has no GUI
            m = Numeric.identity(4)
        if transpose:
            return Numeric.transpose(Numeric.reshape(m, (4,4)))
        else:
            return Numeric.reshape(m, (4,4))
Beispiel #24
0
    def __make_hsv_matrices(self,hsc_matrices,shape,normalize,range_=False):
        """
        Sub-function of plot() that return the h,s,v matrices corresponding
        to the current matrices in sliced_matrices_dict. The shape of the matrices
        in the dict is passed, as well as the normalize boolean parameter.
        The result specified a bitmap in hsv coordinate.

        Applies normalizing and cropping if required.
        """
        zero=zeros(shape,Float)
        one=ones(shape,Float)

        s,h,c = hsc_matrices
        # Determine appropriate defaults for each matrix
        if s is None: s=one # Treat as full strength by default
        if c is None: c=one # Treat as full confidence by default
        if h is None:       # No color, gray-scale plot.
            h=zero
            c=zero

        # If normalizing, offset the matrix so that the minimum
        # value is 0.0 and then scale to make the maximum 1.0
        if normalize!='None':
             s=self._normalize(s,range_=range_)
             # CEBALERT: I meant False, right?
             c=self._normalize(c,range_=False)


        # This translation from SHC to HSV is valid only for black backgrounds;
        # it will need to be extended also to support white backgrounds.
        hue,sat,val=h,c,s
        return (hue,sat,val)
Beispiel #25
0
  def __make_rgb_matrices(self, rgb_matrices,shape,normalize,range_=False):
        """
        Sub-function of plot() that return the h,s,v matrices
        corresponding to the current matrices in
        sliced_matrices_dict. The shape of the matrices in the dict is
        passed, as well as the normalize boolean parameter.  The
        result specified a bitmap in hsv coordinate.

        Applies normalizing and cropping if required.
        """
        zero=zeros(shape,Float)

        r,g,b = rgb_matrices
        # Determine appropriate defaults for each matrix
        if r is None: r=zero
        if g is None: g=zero
        if b is None: b=zero

        # CEBALERT: have I checked this works?
        if normalize!='None':
             r = self._normalize(r,range_=range_)
             g = self._normalize(g,range_=range_)
             b = self._normalize(b,range_=range_)

        return (r,g,b)
Beispiel #26
0
    def _re_bound(self,plot_bounding_box,mat,box,density):

        # CEBHACKALERT: for Julien...
        # If plot_bounding_box is that of a Sheet, it will already have been
        # setup so that the density in the x direction and the density in the
        # y direction are equal.
        # If plot_bounding_box comes from elsewhere (i.e. you create it from
        # arbitrary bounds), it might need to be adjusted to ensure the density
        # in both directions is the same (see Sheet.__init__()). I don't know where
        # you want to do that; presumably the code should be common to Sheet and
        # where it's used in the plotting?
        #
        # It's possible we can move some of the functionality
        # into SheetCoordinateSystem.
        if plot_bounding_box.containsbb_exclusive(box):
             ct = SheetCoordinateSystem(plot_bounding_box,density,density)
             new_mat = zeros(ct.shape,Float)
             r1,r2,c1,c2 = Slice(box,ct)
             new_mat[r1:r2,c1:c2] = mat
        else:
             scs = SheetCoordinateSystem(box,density,density)
             s=Slice(plot_bounding_box,scs)
             s.crop_to_sheet(scs)
             new_mat = s.submatrix(mat)

        return new_mat
Beispiel #27
0
    def __init__(self):
        self.dataObjectsDict = {}
        self.Isommet=Numeric.zeros([200], Numeric.Int)
#        self.VisTable = crtConcentracao.startGui()
        self.Vispectdic={}
        self.vinfo={}
        #self.Elementos=Elementos.Elementos('elementos')
        self.A1 = None
        self.B1 = None
        self.Absi = None
        self.NoPic = None
        self.Area = None
        self.Bgnd = None
        self.Resol=None
        self.Id=None
        self.Fi=None
        self.Erreur=None
        self.Lt=None
        self.sig=None
        self.ideb=None
        self.ifin=None
        self.moyamont = None
        self.moyaval = None
        self.Y1 = None
        self.Y2 = None
        self.ro=None
        self.kres=None
        self.slope=None
        self.offset=None
        self.f1zfin=None
        self.f1zdeb=None
        self.vy=Numeric.array([],Numeric.Float64)
Beispiel #28
0
    def __init__(self,**params):
        """
        SLISSOM-specific init, where dynamic threshold stuff
        gets initialized. 
        """
        super(SLISSOM,self).__init__(**params)
        self.dynamic_threshold = \
            Numeric.zeros(self.activity.shape).astype(activity_type)    
        self.spike = Numeric.zeros(self.activity.shape) 
        self.spike_history = Numeric.zeros(self.activity.shape)
        self.membrane_potential = \
            Numeric.zeros(self.activity.shape).astype(activity_type)

        num_traces = len(self.trace_coords)
        self.membrane_potential_trace = \
            Numeric.zeros((num_traces,self.trace_n)).astype(activity_type)      
def InnerProd(ser1, ser2, PSD):
  size = Numeric.shape(ser1)[0]
  pdlen = size/2
  nyquistf = 0.5/15.0   #   !!! hardcoded !!!!
  freqs = Numeric.arange(0,pdlen+1,dtype='d') * (nyquistf / pdlen)
  if(Numeric.shape(ser2)[0] != size):
     print "size of time series must be the same"
     sys.exit(1)
  if(Numeric.shape(PSD)[0] != pdlen):
     print "wrong size of psd: ", pdlen, Numeric.shape(PSD)
     sys.exit(1)
  fourier1 = FFT.fft(ser1)
  fourier2 = FFT.fft(ser2)
  prod = Numeric.zeros(pdlen+1, dtype='d')
  prod[0] = 0.0
  prod[1:pdlen] = numpy.multiply(fourier1[1:pdlen],numpy.conjugate(fourier2[1:pdlen])) + numpy.multiply(fourier1[-1:pdlen:-1],numpy.conjugate(fourier2[-1:pdlen:-1]))
  prod[pdlen] = fourier1[pdlen]*fourier2[pdlen]
  Numeric.divide(prod[1:], PSD, prod[1:]) 
  olap0 = 0.0
  for i in xrange(pdlen):
      if (freqs[i] > fLow and freqs[i]<= fHigh):
           olap0 += prod[i]
  olap0 = 2.0*olap0/float(size)
 # olap0 =  2.0*(numpy.sum(prod[1:]))/float(size) #it must be scaled by dt
  return  olap0
Beispiel #30
0
 def CalcJacobian(self):
     """
     Use crude numerical differences to approximate Jacobian
     return inverse
     """
     jacobian = zeros((self.numberActive, self.numberActive), Float)
     for cont in self.activeControllers:
         cont.SaveBase()
     self.errors = self.GetErrors()
         
     delta = 0.1
     for i in range(self.numberActive):
         self.flowsheet.InfoMessage('ContDerivCalc', (self.flowsheet.GetPath(), i))
         cont = self.activeControllers[i]
         cont.SetOutput(delta)
         self.flowsheet.InnerSolve()
         jacobian[:,i] = (self.GetErrors() - self.errors)/delta
         cont.SetOutput(0.0)
         
     self.flowsheet.InnerSolve()
     
     try:
         self.jacobian = inverse(jacobian)
     except:
         raise Error.SimError('CouldNotInvertJacobian', self.flowsheet.GetPath())
Beispiel #31
0
def RGBRamp(size=256, upperValue=.6666666666666667):
    """Generate an RGB color ramp, values range from 0.0 to 1.0"""

    assert size > 0
    hsv = HSVRamp(size, upperValue)
    rgb = Numeric.zeros( (hsv.shape[0], 3), viewerConst.FPRECISION )
    for i in xrange(hsv.shape[0]):
        rgb[i] = ToRGB(hsv[i])
    return rgb
Beispiel #32
0
def gluGetTessProperty(tess, property):
    """
    tess - GLUtesselator*
    property - GLenum
return - GLdouble
"""
    data = Numeric.zeros(1, 'd')
    _glulib.gluGetTessProperty(nurb, property, data)
    return data[0]
Beispiel #33
0
 def thumbz_cb(self, events=None):
     val = self.thumbz.value
     rot = Numeric.zeros((4, 4), 'f')
     rot[0][0] = math.cos(val)
     rot[0][1] = -math.sin(val)
     rot[1][0] = math.sin(val)
     rot[1][1] = math.cos(val)
     rot[2][2] = 1.0
     self.updateVector(rot)
Beispiel #34
0
 def read(self, address, threshold=None):
     if self.verbose: print "Reading...",
     s = self.select(address, threshold)
     counts = Numeric.zeros(self.dataLength)
     for i in range(len(s)):
         if s[i]:
             counts += self.memory[i].counters
     if self.verbose: print "done!"
     return [rnd3(x) for x in counts]
Beispiel #35
0
 def wt2mat(self):
     n = len(self.neighbors)
     w = Numeric.zeros((n, n), Numeric.Float)
     for i in range(n):
         if self.numneigh[i]:
             kk = 1.0 / self.numneigh[i]
             for j in self.neighbors[i]:
                 w[i][j] = kk
     return w
Beispiel #36
0
def gluGetNurbsProperty(nurb, property):
    """
    nurb - GLUnurbs*
    property - GLenum
return - GLfloat
"""
    data = Numeric.zeros(1, 'f')
    _glulib.gluGetNurbsProperty(nurb, property, data)
    return data[0]
Beispiel #37
0
 def getHistogram(self):
     GL.glHistogram(GL.GL_HISTOGRAM, 256, GL.GL_RGB, GL.GL_FALSE)
     GL.glEnable(GL.GL_HISTOGRAM)
     self.redraw()
     values = Numeric.zeros((256, 3), Numeric.UInt16)
     #seg faults
     GL.glGetHistogram(GL.GL_HISTOGRAM, GL.GL_TRUE, GL.GL_RGB,
                       GL.GL_UNSIGNED_SHORT, values)
     return values
Beispiel #38
0
def findNearestAtoms(mol, vertices, **kw):
    """None <- color(mol,vertices2,**kw)
    mol:           reference molecule
    vertices:      list of lists(coordinates): the first three items in each list
                   must be coordinates x,y,z of a point.
                   
    atomIndices is the index of the nearest atom to the vertex, such that
    mol.allAtoms[atomIndices[x]] is the nearest atom to vertices[x]
    vertexIndices is the list of nearest vertices to an atom, such that
    vertexIndices[x] = [vertex1,vertex2,...] are the vertices associated with
    mol.allAtoms[x]
    """

    coords = mol.allAtoms.coords
    if not hasattr(mol, 'bhtree'):
        print "Building bhtree for ", mol
        ids = Numeric.arange(len(coords)).astype('i')
        bhtree = bhtreelib.TBHTree(coords, ids, 10, 10, 9999.0)
        mol.bhtree = bhtree

    vertexIndices = {}
    atomIndices = {}
    for x in range(len(coords)):
        vertexIndices[x + 1] = []

    cutoff = 5.
    for x in range(len(vertices)):
        xyz = vertices[x]
        result = Numeric.zeros((len(vertices), )).astype('i')
        dist = Numeric.zeros((len(vertices), )).astype('f')
        nb2 = mol.bhtree.ClosePointsDist2(tuple(xyz[:3]), cutoff, result, dist)
        while nb2 == 0:
            cutoff = cutoff + 5.
            nb2 = mol.bhtree.ClosePointsDist2(tuple(xyz[:3]), cutoff, result,
                                              dist)
        result = result[:nb2]
        dist = dist[:nb2]
        idx = dist.tolist().index(min(dist))
        atnum = result[idx] + 1
        atomIndices[x] = atnum
        vertexIndices[atnum].append(x)

    return atomIndices, vertexIndices
Beispiel #39
0
def readarray(filename):
    file = open(filename, 'r')
    lines = [line.split() for line in file.readlines() if line[0] != '#']    
    file.close()
    
    bshape = (len(lines),len(lines[0]))

    if bshape[1] == 1:
        buffer = Numeric.zeros(bshape[0],'d')

        for index in xrange(0,bshape[0]):
            buffer[index] = float(lines[index][0])
    else:
        buffer = Numeric.zeros(bshape,'d')

        for index in xrange(0,buffer.shape[0]):
            buffer[index,:] = map(float,lines[index])

    return buffer
Beispiel #40
0
    def _cylinderTemplate(self):

        npoly = self.quality * 5

        v = Numeric.zeros(((npoly + 1), 2, 3), 'f')
        n = Numeric.zeros(((npoly + 1), 3), 'f')
        self.npoly = npoly

        a = -math.pi  # starting angle
        d = 2 * math.pi / npoly  # increment

        for i in range(npoly + 1):
            n[i][0] = v[i][0][0] = v[i][1][0] = math.cos(a)
            n[i][1] = v[i][0][1] = v[i][1][1] = math.sin(a)
            n[i][2] = v[i][1][2] = 0.0
            v[i][0][2] = 1.0
            a = a + d

        return v, n
Beispiel #41
0
    def __init__(self, radius):
        """Radius is the the sphere radius (integer).
A 3D array of size 2*radius + 1 will contain the discrete sphere
"""
        import numpy.oldnumeric as Numeric
        size = 2 * radius + 1
        self.centerIndex = radius
        self.grid = Numeric.zeros((size, size, size), Numeric.UnsignedInt8)
        # put ones in voxels inside or on the sphere
        self.Sphere(radius)
Beispiel #42
0
def vvmult(a, b):
    """
    Compute a vector product for 3D vectors
    """
    import numpy.oldnumeric as Numeric
    res = Numeric.zeros(3, 'f')
    res[0] = a[1] * b[2] - a[2] * b[1]
    res[1] = a[2] * b[0] - a[0] * b[2]
    res[2] = a[0] * b[1] - a[1] * b[0]
    return res
Beispiel #43
0
def MaxInnerProd(ser1, ser2, PSD):
    size = Numeric.shape(ser1)[0]
    pdlen = size / 2
    nyquistf = 0.5 / 15.0  #   !!! hardcoded !!!!
    freqs = Numeric.arange(0, pdlen + 1, dtype='d') * (nyquistf / pdlen)
    if (Numeric.shape(ser2)[0] != size):
        print "size of time series must be the same"
        sys.exit(1)
    if (Numeric.shape(PSD)[0] != pdlen):
        print "wrong size of psd: ", pdlen, Numeric.shape(PSD)
        sys.exit(1)
    fourier1 = FFT.fft(ser1)
    fourier2 = FFT.fft(ser2)
    prod1 = Numeric.zeros(pdlen + 1, dtype='d')
    prod2 = Numeric.zeros(pdlen + 1, dtype='d')
    prod1[0] = 0.0
    prod1[1:pdlen] = numpy.multiply(
        fourier1[1:pdlen], numpy.conjugate(
            fourier2[1:pdlen])) + numpy.multiply(
                fourier1[-1:pdlen:-1], numpy.conjugate(fourier2[-1:pdlen:-1]))
    prod1[pdlen] = fourier1[pdlen] * fourier2[pdlen]
    prod2[0] = 0.0
    prod2[1:pdlen] = numpy.multiply(
        fourier1[1:pdlen], numpy.conjugate(
            fourier2[1:pdlen] * 1.j)) + numpy.multiply(
                (fourier1[-1:pdlen:-1]),
                numpy.conjugate(fourier2[-1:pdlen:-1] * (-1.j)))
    prod2[pdlen] = fourier1[pdlen] * fourier2[pdlen]
    Numeric.divide(prod1[1:], PSD, prod1[1:])
    Numeric.divide(prod2[1:], PSD, prod2[1:])
    olap0 = 0.0
    olappiby2 = 0.0
    for i in xrange(pdlen):
        if (freqs[i] > fLow and freqs[i] <= fHigh):
            olap0 += prod1[i]
            olappiby2 += prod2[i]
    olap0 = 2.0 * olap0 / float(size)
    olappiby2 = 2.0 * olappiby2 / float(size)
    #  olap0 =  2.0*(numpy.sum(prod1[1:]))/float(size) #it must be scaled by dt
    #  olappiby2 =  2.0*(numpy.sum(prod2[1:]))/float(size) #it must be scaled by dt
    print "angle of maxim. = ", math.atan(olappiby2 / olap0)
    return sqrt(olap0**2 + olappiby2**2)
Beispiel #44
0
    def _normalize(self, a, range_):
        """
        Normalize an array s to be in the range 0 to 1.0.
        For an array of identical elements, returns an array of ones
        if the elements are greater than zero, and zeros if the
        elements are less than or equal to zero.
        """
        if range_:  # i.e. not False, not None (expecting a tuple)
            range_min = float(range_[0])
            range_max = float(range_[1])

            if range_min == range_max:
                if range_min > 0:
                    resu = ones(a.shape)
                else:
                    resu = zeros(a.shape)
            else:
                a_offset = a - range_min
                resu = a_offset / (range_max - range_min)

            return resu
        else:
            if range_ is None:
                if not hasattr(self, 'value_range'):
                    self.value_range = (a.min(), a.max())
                else:
                    # If normalizing multiple matrices, take the largest values
                    self.value_range = (min(self.value_range[0], a.min()),
                                        max(self.value_range[1], a.max()))
                return None  # (indicate that array was not scaled)
            else:  # i.e. range_ is False
                a_offset = a - a.min()
                max_a_offset = a_offset.max()

                if max_a_offset > 0:
                    a = divide(a_offset, float(max_a_offset))
                else:
                    if min(a.ravel()) <= 0:
                        a = zeros(a.shape, Float)
                    else:
                        a = ones(a.shape, Float)
                return a
Beispiel #45
0
    def _arcTemplate(self, angle):

        nsegments = self.nsegments
        assert (nsegments > 1)
        import numpy.oldnumeric as Numeric, math

        self.v = Numeric.zeros(((nsegments + 1), 3), 'f')
        self.n = Numeric.zeros(((nsegments + 1), 3), 'f')
        self.nsegments = nsegments

        angRad = angle * pi * 0.00555555555556
        a = -pi  # starting angle
        d = angRad / nsegments  # increment

        for i in range(nsegments + 1):
            self.n[i][0] = self.v[i][0] = cos(a)
            self.n[i][1] = self.v[i][1] = sin(a)
            self.n[i][2] = 1.0
            self.v[i][2] = 0.0
            a = a + d
Beispiel #46
0
def rankData(n, inverse=False):
    """Returns ranks of 1D Numeric array in range 1...shape[0].
    """
    n = Numeric.asarray(n)
    assert Numeric.rank(n) == 1
    r = Numeric.zeros(n.shape[0], Numeric.Float)
    Numeric.put(r, Numeric.argsort(n), Numeric.arange(n.shape[0]))
    if inverse:
        return -1*r+n.shape[0]
    else:
        return r+1
Beispiel #47
0
def glAreTexturesResident(textures):
    """wrapper over _gllib.glAreTexturesResident
    Return None if all textures are resident, or a Numeric Array.
    """

    ncell = len(textures)

    residences = Numeric.zeros(ncell, GLboolean)

    return not(_gllib.glAreTexturesResident( ncell, textures, residences) ) \
           and residences or None
Beispiel #48
0
def gluProject(obj, model, proj, view):
    """
    obj - seq( 3, GLdouble)
    model - seq( gl.MODELVIEW_MATRIX, GLfloat)
    perspective - seq( gl.PROJECTION_MATRIX, GLfloat)
    view - seq( gl.VIEWPORT, GLfloat)
    return - Numeric array (shape: (3,), type: GLdouble)
    """
    win = Numeric.zeros(3, GLdouble)
    gluProjectv(obj, model, proj, view, win[0:1], win[1:2], win[2:3])
    return win
Beispiel #49
0
def gluUnProject(obj, model, proj, view):
    """
    obj - seq( 3, GLdouble)
    model - seq( gl.MODELVIEW_MATRIX, GLfloat)
    perspective - seq( gl.PROJECTION_MATRIX, GLfloat)
    view - seq( gl.VIEWPORT, GLfloat)
return - Numeric.array ( 3, GLdouble)
    """
    win = Numeric.zeros(3, GLdouble)
    gluUnProjectv(obj, model, proj, view, win)
    return win[:3]
Beispiel #50
0
def getobs(snum,stime,observables,zerotime=0.0,display=0,forcepython=0):
    if len(Numeric.shape(observables)) == 0:
        obsobj = checkobs([observables])
                
        if obsobj and (not forcepython):
            array = Numeric.zeros(snum,dtype='d')

            if display:
                lisaswig.fastgetobsc(array,snum,stime,obsobj,zerotime)
            else:
                lisaswig.fastgetobs(array,snum,stime,obsobj,zerotime)
        else:
            if display:
                return getobscount(snum,stime,observables,zerotime)
            else:
                array = Numeric.zeros(snum,dtype='d')
            
                for i in Numeric.arange(0,snum):
                    array[i] = observables(zerotime+i*stime)
    else:
        obsobj = checkobs(observables)

        if obsobj and (not forcepython):
            obslen = Numeric.shape(observables)[0]
            array = Numeric.zeros((snum,obslen),dtype='d')

            if display:
                lisaswig.fastgetobsc(array,snum,stime,obsobj,zerotime)
            else:
                lisaswig.fastgetobs(array,snum,stime,obsobj,zerotime)
        else:
            if display:
                return getobscount(snum,stime,observables,zerotime)
            else:
                obslen = Numeric.shape(observables)[0]
                array = Numeric.zeros((snum,obslen),dtype='d')
            
                for i in Numeric.arange(0,snum):
                    for j in xrange(0,obslen):
                        array[i,j] = observables[j](zerotime+i*stime)
    return array
Beispiel #51
0
    def _cylinderTemplateDaniel(self, quality=None):
        """ This template doesn't put the last point over the first point
        as done in the other template. In addition, it computes and
        returns face indices. I don't compute normals 
        This template is used by asIndexedyPolygons()"""

        if quality is None:
            quality = self.quality * 5

        import numpy.oldnumeric as Numeric, math

        v = Numeric.zeros(((quality), 2, 3), 'f')
        n = Numeric.zeros(((quality), 3), 'f')

        f = []

        a = -math.pi  # starting angle
        d = 2 * math.pi / quality  # increment

        # compute vertices
        for i in range(quality):
            v[i][0][0] = v[i][1][0] = math.cos(a)
            v[i][0][1] = v[i][1][1] = math.sin(a)
            v[i][1][2] = 0.0
            v[i][0][2] = 1.0
            a = a + d

        lV = len(v)

        # compute template cylinder faces
        for i in range(lV - 1):  # cylinder body
            f.append([i, i + 1, lV + i + 1])
            f.append([lV + i + 1, lV + i, i])
        f.append([lV - 1, 0, lV])  #close last point to first
        f.append([lV - 1, lV, lV + i + 1])
        for i in range(lV - 2):  # cylinder bottom cap
            f.append([0, i + 2, i + 1])
        for i in range(lV - 2):  # cylinder top cap
            f.append([lV + i + 1, lV + i + 2, lV])

        return v, f
Beispiel #52
0
 def _NormalizeN(self):
     eqn = Numeric.zeros((3, ), Numeric.Float)
     for i in (0, 1, 2):
         eqn[i] = self.rotation[i]
     n = Numeric.add.reduce(eqn * eqn)
     assert n > 0.0
     if n > 0.00001:
         self.n = 1.0 / sqrt(n)
         self.eqn[:3] = eqn
     else:
         self.n = 1.0
         self.eqn[:3] = [1.0, 0.0, 0.0]
    def patchAround(self, center, nAtoms):
        """
        patchAround( float_center, int_nAtoms ) -> mask for self.model
        Create single patch of nAtoms atoms that are closest to center.
        """
        dist = self.__distances(center)
        order = N.argsort(dist)

        r = N.zeros(len(self.model), 'i')
        N.put(r, order[:nAtoms], 1)

        return self.centerPatch(r)
Beispiel #54
0
 def __init__(self,
              p00=[-.5, -.5],
              p01=[.5, -.5],
              p10=[-.5, .5],
              p11=[.5, .5]):
     coefs = numerix.zeros((4, 2, 2), numerix.Float)
     coefs[3, :, :] = numerix.ones((2, 2), numerix.Float)
     coefs[0:len(p00), 0, 0] = p00
     coefs[0:len(p01), 0, 1] = p01
     coefs[0:len(p10), 1, 0] = p10
     coefs[0:len(p11), 1, 1] = p11
     Srf.__init__(self, coefs, [0., 0., 1., 1.], [0., 0., 1., 1.])
Beispiel #55
0
def raggedList2mtrx(raggedList):
    """convert a bottom triangular ragged list (with optional empty list at the beginning) to a square matrix"""
    if len(raggedList[0]) == 0:
        raggedList = raggedList[1:]
    rlLen = len(raggedList) + 1
    m = Numeric.zeros((rlLen, rlLen), Numeric.Float)
    idx = 0
    for lst in raggedList:
        idx += 1
        m[idx, :idx] = Numeric.array(lst, Numeric.Float)
        m[:idx, idx] = Numeric.array(lst, Numeric.Float)
    return m
Beispiel #56
0
 def splag(self, x):
     n = len(x)
     if type(x) == list:
         wx = [0 for i in range(n)]
     elif type(x) == type(Numeric.array(1)):
         wx = Numeric.zeros(n, Numeric.Float)
     for i in range(n):
         if self.numneigh[i]:
             for j in self.neighbors[i]:
                 wx[i] += x[j]
             wx[i] /= self.numneigh[i]
     return wx
Beispiel #57
0
def CreateLinearDistArray(nuVals, bound1, bound2):
    """Create a Numeric array of values distributed linearly

    nuVals -- Number of values desired
    bound1 -- Boundary 1. Can be a numeric array
    bound2 -- Boundary 2. Can be a numeric array

    """
    if hasattr(bound1, 'shape'):
        #A bit convoluted but all it does it putting in a list something like this
        #nuVals =5, shape = (3, 4) -> (5, 3, 4)
        dim = [nuVals]
        dim.extend(list(bound1.shape)) 
        vals = zeros(dim, Float)
    else:
        vals = zeros(nuVals, Float)
        
    delta = (bound2 - bound1) / (nuVals - 1)
    for i in range(nuVals): vals[i] = delta * i + bound1

    return vals
Beispiel #58
0
 def getAppxCoef(self, arr2d, numCoef=None):
     """returns approx. coeffients given the number of coefficients different from zero"""
     assert len(arr2d.shape) == 2
     if numCoef == None:
         numCoef = self.k
     else:
         assert 0 <= numCoef <= self.k, "number of coefficients not in range [0," + str(
             self.k) + "]"
     coef = self.basis.getApproxCoeff(arr2d)
     coef[:, numCoef:] = Numeric.zeros(
         (coef.shape[0], coef.shape[1] - numCoef), Numeric.Float)
     return coef
Beispiel #59
0
    def setSignatures(self, signatures):
        self.signatures = signatures
        self.sigData = []

        # get the values
        self.maxFun = []
        self.minFun = []
        for s in self.signatures:
            x = Numeric.zeros((s.nval, ), 'f')
            s.getFx(x)

            self.minix = mini = min(x)
            if (isinstance(mini, Numeric.ArrayType)) and (mini.shape == ()):
                mini = mini[0]

            maxi = max(x)
            if (isinstance(maxi, Numeric.ArrayType)) and (maxi.shape == ()):
                maxi = maxi[0]

            self.rangex = range = maxi - mini
            if range != 0:
                x = (((x - mini) / range) * self.widthMinusOne).astype('i')

            y = Numeric.zeros((s.nval, ), 'f')
            s.getFy(y)
            self.sigData.append((x, y))
            self.maxFun.append(max(y))
            self.minFun.append(min(y))

        self.setMin(mini)
        self.setMax(maxi)

        # iso value with hightest value in first function
        if len(self.sigData):
            ind = list(self.sigData[0][1]).index(max(self.sigData[0][1]))
            self.setXcursor(ind)
        else:
            self.setXcursor(0.0)

        self.drawSignatures()
Beispiel #60
0
    def getResult( self, mirror=0 ):
        """
        Get result matrix ordered such as input trajectory.

        @param mirror: mirror the matrix at diagonal (default: 1)
                       (only for intra-traj)
        @type  mirror: 1|0

        @return: array( (n_frames, n_frames), 'f'), matrix of pairwise rms
        @rtype: array
        """
        if self.verbose:   self.log.write('assembling result matrix...')

        intra_traj = self.traj_2 is None

        n1 = n2 = len( self.traj_1 )
        if self.traj_2 is not None:
            n2 = len( self.traj_2 )

        a  = N.zeros( (n1,n2), N.Float32 )

        if self.verbose: self.log.write('#')

        for key, value in self.result.items():
            i_start, i_stop = key[0]
            j_start, j_stop = key[1]

            window = N.reshape( value, (i_stop-i_start, j_stop-j_start) )
            window = window.astype(N.Float32)

            a[i_start:i_stop, j_start:j_stop] = window

        if self.verbose: self.log.write('#')

        if intra_traj:
            for i in range( N.shape(a)[0] ):
                for j in range( i, N.shape(a)[1] ):
                    if a[j,i] == 0:
                        a[j,i] = a[i,j]
                    else:
                        a[i,j] = a[j,i]

        if self.verbose: self.log.write('#')

        if intra_traj and not mirror:
            for i in range( N.shape(a)[0] ):
                for j in range( i, N.shape(a)[1] ):
                    a[j,i] = 0.

        if self.verbose:   self.log.add('done')

        return a