Esempio n. 1
0
def bmapToWgt(bmap, type):

    # Local Variables: posmask, Wd, Wc, W, Wa, h, is, h1, L, js, Wgt, bmap, w, pad, type, w1, Wb
    # Function calls: imResample, struct, cleanbmap, max, bmapToWgt, asserteq, LtoW, labelmap, bwdist, mod, size
    #% Wgt = bmapToWgt( bmap, type )
    #%
    #% Input bmap should not be padded, and type
    #% is either 'exact' or 'max' or 'interp'. The
    #% Wgt returned is binary for 'exact' and 'max'.
    #%
    #% The 'max' type seems to work best but has the
    #% disadvantage that the weights don't sum to 1.
    #%
    #% The size of Wgt is the same as the size of
    #% the W returned by indToW when "ind" was built
    #% from the original image padded only to have
    #% height/width divisible by 4 (see imgDemo.m).
    bmap = cleanbmap(bmap)
    posmask = bwdist(bmap)<16./2.
    L = labelmap(bmap, posmask, struct('gtWidth', 16., 'nDists', 15., 'nOrients', 8., 'angleRad', 6.))
    #% All of the index math assumes the original image
    #% was padded to have height/width divisible by 4,
    #% since that is required by edgesChns
    [h, w] = matcompat.size(bmap)
    pad = np.mod((4.-np.mod(np.array(np.hstack((h, w))), 4.)), 4.)
    h = h+pad[0]
    w = w+pad[1]
    _switch_val=type
    if False: # switch 
        pass
    #% Nearest nbor downsampling
    elif _switch_val == 'exact':
        L = L[15:h-18.:2.,15:w-18.:2.]
        Wgt = LtoW(L)
        #% Charless's idea. Works really well
    elif _switch_val == 'max':
        W = LtoW(L)
        is = np.arange(16., (h-18.)+(2.), 2.)
        js = np.arange(16., (w-18.)+(2.), 2.)
        Wa = W[int(is)-1,int(js)-1,:]
        Wb = W[int(is)-1,int((js+1.))-1,:]
        Wc = W[int((is+1.))-1,int(js)-1,:]
        Wd = W[int((is+1.))-1,int((js+1.))-1,:]
        Wgt = matcompat.max(Wa, matcompat.max(Wb, matcompat.max(Wc, Wd)))
        #% Probably shouldn't use this
    elif _switch_val == 'interp':
        Wgt = LtoW(L)
        Wgt = Wgt[15:h-18.,15:w-18.,:]
        Wgt = imResample(Wgt, 0.5, 'bilinear')
    
    h1 = h/1.06.
    w1 = w/1.06.
    asserteq(matcompat.size(Wgt), np.array(np.hstack((h1, w1, 121.))))
    return [Wgt]
Esempio n. 2
0
def AND(C, B):

    # Local Variables: UB0, varargout, numRankSigma, nout, k, Ux, UC0, Wt, tol, C, B, numRankB, numRankC, UtC, Vx, Wgk, W, Sigma, UtB, dim, Sx, CandB, SC, SB, dSB, dSC, UC, UB
    # Function calls: AND, eye, diag, svd, nargout, inv, pinv, max, sum, size
    dim = matcompat.size(C, 1.0)
    tol = 1e-14
    [UC, SC, UtC] = plt.svd(C)
    [UB, SB, UtB] = plt.svd(B)
    dSC = np.diag(SC)
    dSB = np.diag(SB)
    numRankC = np.sum(np.dot(1.0, dSC > tol))
    numRankB = np.sum(np.dot(1.0, dSB > tol))
    UC0 = UC[:, int(numRankC + 1.0) - 1 :]
    UB0 = UB[:, int(numRankB + 1.0) - 1 :]
    [W, Sigma, Wt] = plt.svd((np.dot(UC0, UC0.conj().T) + np.dot(UB0, UB0.conj().T)))
    numRankSigma = np.sum(np.dot(1.0, np.diag(Sigma) > tol))
    Wgk = W[:, int(numRankSigma + 1.0) - 1 :]
    CandB = np.dot(
        np.dot(
            Wgk, linalg.inv(np.dot(np.dot(Wgk.conj().T, linalg.pinv(C, tol) + linalg.pinv(B, tol) - np.eye(dim)), Wgk))
        ),
        Wgk.conj().T,
    )
    nout = matcompat.max(nargout, 1.0) - 1.0
    if nout > 0.0:
        [Ux, Sx, Vx] = plt.svd(CandB)
        for k in np.arange(1.0, (nout) + 1):
            if k == 1.0:
                varargout[int(k) - 1] = cellarray(np.hstack((Ux)))
            elif k == 2.0:
                varargout[int(k) - 1] = cellarray(np.hstack((Sx)))

    return [CandB, varargout]
Esempio n. 3
0
def uniqfilt(seg, k):

    # Local Variables: seg, i, k, nuniq, se
    # Function calls: max, imdilate, uniqfilt, ones, zeros, size
    #% nuniq = uniqfilt(seg,k)
    #%
    #% INPUTS
    #%   seg     groundTruth{j}.Segmentation
    #%   k       filter half width
    #%
    #% ASSUME THAT SEG LABELS ARE {1,2,...,NSEGS}
    #%
    #% This function is a fast version of the following:
    #% [h w] = size(seg);
    #% nuniq = zeros(h,w);
    #% for y = 1:h
    #%   y1 = max(1,y-k);
    #%   y2 = min(h,y+k);
    #%   for x = 1:w
    #%     x1 = max(1,x-k);
    #%     x2 = min(w,x+k);
    #%     patch = seg(y1:y2,x1:x2);
    #%     nuniq(y,x) = numel(unique(patch));
    #%   end
    #% end
    #% How long does it take to run unique(seg)? I tried this for all
    #% groundTruth{j}.Segmentation for all images. It took 0.0123 sec
    #% at most, 0.0027 sec on average, and 0.0022 sec at best.
    se = np.ones((2. * k + 1.))
    nuniq = np.zeros(matcompat.size(seg))
    for i in np.arange(1., (matcompat.max(seg.flatten(1))) + 1):
        nuniq = nuniq + imdilate((seg == i), se)

    return [nuniq]
Esempio n. 4
0
def template_matching_gray(T, I):
    # Local Variables: LocalSumI, Icorr, stdI, Idata, stdT, QSumT, I, I_NCC, I_SSD, LocalQSumI, T_size, outsize, I_size, T, IdataIn, FT, meanIT, FI
    # Function calls: template_matching_gray, real, ifft2, min, max, sum, local_sum, fftn, fft2, nargout, std, length, isempty, sqrt, numel, unpadarray, rot90, rot90_3D, ifftn, size
    # % Calculate correlation output size  = input size + padding template
    T_size = np.shape(T)
    I_size = np.size(I)
    # outsize = I_size + T_size - 1.
    # % calculate correlation in frequency domain

    FT = np.fft.fftn(rot90_3D(T))
    FI = np.fft.fftn(I)
    Icorr = np.real(np.fft.ifftn((FI * FT)))

    # % Calculate Local Quadratic sum of Image and Template
    LocalQSumI = local_sum(np.power(I,2), T)


    LocalSumI = local_sum(I, T)

    # % Standard deviation
    stdI = np.sqrt((LocalQSumI - np.divide(pow(LocalSumI ,2), np.size(T))))

    stdT = np.dot(np.sqrt((np.size(T) - 1.)), np.std(T.flatten(1)))
    # % Mean compensation
    meanIT = np.divide(np.dot(LocalSumI, np.sum(T.flatten())))#, np.size(T))
    I_NCC = 0.5 + (Icorr - meanIT) / np.dot(2. * stdT, max((stdI), np.divide(stdT, 1e5)))
    # % Remove padding
    I_NCC = unpadarray(I_NCC, matcompat.size(I))

    return I_NCC
Esempio n. 5
0
def NormalizeFea(fea, row):

    # Local Variables: nSmp, fea, i, feaNorm, mFea, fea2, row
    # Function calls: max, mynorm, issparse, ones, exist, NormalizeFea, sum, size
    #% if row == 1, normalize each row of fea to have unit norm;
    #% if row == 0, normalize each column of fea to have unit norm;
    if not exist('row', 'var'):
        row = 1.

    #% if row
    #%     nSmp = size(fea,1);
    #%     feaNorm = max(1e-14,full(sum(fea.^2,2)));
    #%     fea = spdiags(feaNorm.^-.5,0,nSmp,nSmp)*fea;
    #% else
    #%     nSmp = size(fea,2);
    #%     feaNorm = max(1e-14,full(sum(fea.^2,1))');
    #%     fea = fea*spdiags(feaNorm.^-.5,0,nSmp,nSmp);
    #% end
    #%
    #% return;
    if row:
        [nSmp, mFea] = matcompat.size(fea)
        if issparse(fea):
            fea2 = fea.conj().T
            feaNorm = mynorm(fea2, 1.)
            for i in np.arange(1., (nSmp) + 1):
                fea2[:, int(i) - 1] = fea2[:, int(i) - 1] / matcompat.max(
                    1e-10, feaNorm[int(i) - 1])

            fea = fea2.conj().T
        else:
            feaNorm = np.sum((fea**2.), 2.)**.5
            fea = fea / feaNorm[:, int(np.ones(1., mFea)) - 1]

    else:
        [mFea, nSmp] = matcompat.size(fea)
        if issparse(fea):
            feaNorm = mynorm(fea, 1.)
            for i in np.arange(1., (nSmp) + 1):
                fea[:, int(i) - 1] = fea[:, int(i) - 1] / matcompat.max(
                    1e-10, feaNorm[int(i) - 1])

        else:
            feaNorm = np.sum((fea**2.), 1.)**.5
            fea = fea / feaNorm[int(np.ones(1., mFea)) - 1, :]

    return [fea]
def aryule(x, p):

    # Local Variables: a, e, k, nx, p, R, x, mx
    # Function calls: aryule, nargchk, min, issparse, nargin, length, isempty, error, levinson, message, xcorr, round, size
    #%ARYULE   AR parameter estimation via Yule-Walker method.
    #%   A = ARYULE(X,ORDER) returns the polynomial A corresponding to the AR
    #%   parametric signal model estimate of vector X using the Yule-Walker
    #%   (autocorrelation) method.  ORDER is the model order of the AR system. 
    #%   This method solves the Yule-Walker equations by means of the Levinson-
    #%   Durbin recursion.
    #%
    #%   [A,E] = ARYULE(...) returns the final prediction error E (the variance
    #%   estimate of the white noise input to the AR model).
    #%
    #%   [A,E,K] = ARYULE(...) returns the vector K of reflection coefficients.
    #%   
    #%   % Example:
    #%   %   Estimate model order using decay of reflection coefficients.
    #%
    #%   rng default;
    #%   y=filter(1,[1 -0.75 0.5],0.2*randn(1024,1));
    #%
    #%   % Create AR(2) process
    #%   [ar_coeffs,NoiseVariance,reflect_coeffs]=aryule(y,10);
    #%
    #%   % Fit AR(10) model
    #%   stem(reflect_coeffs); axis([-0.05 10.5 -1 1]);
    #%   title('Reflection Coefficients by Lag'); xlabel('Lag');
    #%   ylabel('Reflection Coefficent');
    #%
    #%   See also PYULEAR, ARMCOV, ARBURG, ARCOV, LPC, PRONY.
    #%   Ref: S. Orfanidis, OPTIMUM SIGNAL PROCESSING, 2nd Ed.
    #%              Macmillan, 1988, Chapter 5
    #%        M. Hayes, STATISTICAL DIGITAL SIGNAL PROCESSING AND MODELING, 
    #%              John Wiley & Sons, 1996, Chapter 8
    #%   Author(s): R. Losada
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.12.4.6 $  $Date: 2012/10/29 19:30:38 $
    matcompat.error(nargchk(2., 2., nargin, 'struct'))
    #% Check the input data type. Single precision is not supported.
    #%try
    #%    chkinputdatatype(x,p);
    #%catch ME
    #%    throwAsCaller(ME);
    #%end
    [mx, nx] = matcompat.size(x)
    if isempty(x) or length(x)<p or matcompat.max(mx, nx) > 1.:
        matcompat.error(message('signal:aryule:InvalidDimensions'))
    elif isempty(p) or not p == np.round(p):
        matcompat.error(message('signal:aryule:MustBeInteger'))
        
    
    if issparse(x):
        matcompat.error(message('signal:aryule:Sparse'))
    
    
    R = plt.xcorr(x, p, 'biased')
    [a, e, k] = levinson(R[int(p+1.)-1:], p)
    return [a, e, k]
def aryule(x, p):

    # Local Variables: a, e, k, nx, p, R, x, mx
    # Function calls: aryule, nargchk, min, issparse, nargin, length, isempty, error, levinson, message, xcorr, round, size
    #%ARYULE   AR parameter estimation via Yule-Walker method.
    #%   A = ARYULE(X,ORDER) returns the polynomial A corresponding to the AR
    #%   parametric signal model estimate of vector X using the Yule-Walker
    #%   (autocorrelation) method.  ORDER is the model order of the AR system.
    #%   This method solves the Yule-Walker equations by means of the Levinson-
    #%   Durbin recursion.
    #%
    #%   [A,E] = ARYULE(...) returns the final prediction error E (the variance
    #%   estimate of the white noise input to the AR model).
    #%
    #%   [A,E,K] = ARYULE(...) returns the vector K of reflection coefficients.
    #%
    #%   % Example:
    #%   %   Estimate model order using decay of reflection coefficients.
    #%
    #%   rng default;
    #%   y=filter(1,[1 -0.75 0.5],0.2*randn(1024,1));
    #%
    #%   % Create AR(2) process
    #%   [ar_coeffs,NoiseVariance,reflect_coeffs]=aryule(y,10);
    #%
    #%   % Fit AR(10) model
    #%   stem(reflect_coeffs); axis([-0.05 10.5 -1 1]);
    #%   title('Reflection Coefficients by Lag'); xlabel('Lag');
    #%   ylabel('Reflection Coefficent');
    #%
    #%   See also PYULEAR, ARMCOV, ARBURG, ARCOV, LPC, PRONY.
    #%   Ref: S. Orfanidis, OPTIMUM SIGNAL PROCESSING, 2nd Ed.
    #%              Macmillan, 1988, Chapter 5
    #%        M. Hayes, STATISTICAL DIGITAL SIGNAL PROCESSING AND MODELING,
    #%              John Wiley & Sons, 1996, Chapter 8
    #%   Author(s): R. Losada
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.12.4.6 $  $Date: 2012/10/29 19:30:38 $
    matcompat.error(nargchk(2., 2., nargin, 'struct'))
    #% Check the input data type. Single precision is not supported.
    #%try
    #%    chkinputdatatype(x,p);
    #%catch ME
    #%    throwAsCaller(ME);
    #%end
    [mx, nx] = matcompat.size(x)
    if isempty(x) or length(x) < p or matcompat.max(mx, nx) > 1.:
        matcompat.error(message('signal:aryule:InvalidDimensions'))
    elif isempty(p) or not p == np.round(p):
        matcompat.error(message('signal:aryule:MustBeInteger'))

    if issparse(x):
        matcompat.error(message('signal:aryule:Sparse'))

    R = plt.xcorr(x, p, 'biased')
    [a, e, k] = levinson(R[int(p + 1.) - 1:], p)
    return [a, e, k]
Esempio n. 8
0
def ncc(seg, width):

    # Local Variables: B, hash, y, i, siz, s, N, seg, width, S, cacheDir, u, x, Nu, xs, ys, uniq, o2, o1
    # Function calls: load, hashMat, unique, false, floor, sum, nan, uint8, ceil, uniqfilt, length, save, ncc, find, bwlabel, size
    #% N = ncc( seg, w )
    #%
    #% N(i,j) = number of connected components in the
    #%   w-by-w window centered on location (i,j) of seg
    #%
    #% What do I mean by "number of connected components"?
    #% Here are some example segmentation patches:
    #%
    #%   1 1 2 2 1 1
    #%   1 1 2 2 1 1      this patch has THREE segments, even
    #%   1 1 2 2 1 1      though unique() only returns [1;2].
    #%   1 1 2 2 1 1
    #%
    #%   3 3 7 7 7 7
    #%   3 3 7 7 7 7      this patch has FOUR segments, even
    #%   7 7 3 3 3 3      though unique() is simply [3;7].
    #%   7 7 3 3 3 3
    #%
    #% THIS CODE IS VERY SLOW, hence all results are cached.
    cacheDir = '/home/ashishmenon/labpc/oef/cache/clust/nccCache/'
    hash = hashMat(
        np.array(np.vstack((np.hstack((seg.flatten(1))), np.hstack((width))))))
    try:
        np.load(np.array(np.hstack((cacheDir, hash))), 'N')
    except:
        siz = matcompat.size(seg)
        o1 = np.floor(((width - 1.) / 2.))
        o2 = np.ceil(((width - 1.) / 2.))
        #% This takes ~80 seconds per image
        N = np.nan(siz)
        B = false(siz)
        B[int(o1 + 1.) - 1:0 - o2, int(o1 + 1.) - 1:0 - o2] = 1.
        Nu = uniqfilt(seg, o2)
        N[int(np.logical_and(B, Nu == 1.)) - 1] = 1.
        [ys, xs] = nonzero(np.logical_and(B, Nu > 1.))
        for i in np.arange(1., (length(ys)) + 1):
            y = ys[int(i) - 1]
            x = xs[int(i) - 1]
            S = seg[int(y - o1) - 1:y + o2, int(x - o1) - 1:x + o2]
            uniq = np.unique(S)
            N[int(y) - 1, int(x) - 1] = 0.
            for s in uniq.flatten(0).conj():
                u = np.unique(bwlabel((S == s), 4.))
                N[int(y) - 1,
                  int(x) - 1] = N[int(y) - 1, int(x) - 1] + np.sum((u != 0.))

        #% convert to uint8 to save disk space
        #% (but this converts NaNs to 0s..)
        N = np.uint8(N)
        plt.save(np.array(np.hstack((cacheDir, hash))), 'N')

    return [N]
Esempio n. 9
0
def unpadarray(A, Bsize):
    # Local Variables: A, Bsize, B, Bstart, Bend
    # Function calls: unpadarray, ndims, size, ceil
    Bstart = np.ceil(((matcompat.size(A) - Bsize) / 2.)) + 1.
    Bend = Bstart + Bsize - 1.
    if matcompat.ndim(A) == 2.:
        B = A[int(Bstart[0]) - 1:Bend[0], int(Bstart[1]) - 1:Bend[1]]
    elif matcompat.ndim(A) == 3.:
        B = A[int(Bstart[0]) - 1:Bend[0], int(Bstart[1]) - 1:Bend[1], int(Bstart[2]) - 1:Bend[2]]

    return B
Esempio n. 10
0
def cleanbmap(bmap):

    # Local Variables: list, bmap
    # Function calls: cleanedgelist, cleanbmap, bwmorph, edgelink, edgelist2image, inf, size
    list = edgelink(bmap)
    list = cleanedgelist(list, 7.)
    bmap = edgelist2image(list, matcompat.size(bmap))
    bmap = bwmorph(bwmorph(bmap, 'fill'), 'thin', np.inf)
    #% [update 17 Sep 2014]
    #% If the output bmap has a single, isolated 'on' pixel
    #% then edgelink will not find it, which leads to bugs
    bmap = bwmorph(bmap, 'clean')
    return [bmap]
Esempio n. 11
0
def edgesChns(I, opts):

    # Local Variables: I1, simSm, Ishrink, chnsSim, I, H, k, M, chnsReg, O, chns, i, s, chnSm, cs, shrink, opts
    # Function calls: rgbConvert, convTri, imResample, max, cat, cell, edgesChns, gradientHist, round, gradientMag, size
    #% Compute feature channels
    #% [chnsReg,chnsSim] = edgesChns( I, opts )
    #%
    #% This is a slightly modified version of the edgesChns
    #% file from Piotr Dollar's Structured Edge Detection
    #% Toolbox, https://github.com/pdollar/edges.
    shrink = opts.shrink
    chns = cell(1., (opts.nChns))
    k = 0.
    if matcompat.size(I, 3.) == 1.:
        cs = 'gray'
    else:
        cs = 'luv'

    I = rgbConvert(I, cs)
    Ishrink = imResample(I, (1. / shrink))
    k = k + 1.
    chns.cell[int(k) - 1] = Ishrink
    for i in np.arange(1., 3.0):
        s = 2.**(i - 1.)
        if s == shrink:
            I1 = Ishrink
        else:
            I1 = imResample(I, (1. / s))

        I1 = convTri(I1, (opts.grdSmooth))
        [M, O] = gradientMag(I1, 0., (opts.normRad), .01)
        H = gradientHist(M, O, matcompat.max(1., matdiv(shrink, s)),
                         (opts.nHistBins), 0.)
        k = k + 1.
        chns.cell[int(k) - 1] = imResample(M, matdiv(s, shrink))
        k = k + 1.
        chns.cell[int(k) - 1] = imResample(
            H, matcompat.max(1., matdiv(s, shrink)))

    chns = cat(3., chns.cell[0:k])
    chnSm = matdiv(opts.chnSmooth, shrink)
    if chnSm > 1.:
        chnSm = np.round(chnSm)

    simSm = matdiv(opts.simSmooth, shrink)
    if simSm > 1.:
        simSm = np.round(simSm)

    chnsReg = convTri(chns, chnSm)
    chnsSim = convTri(chns, simSm)
    return [chnsReg, chnsSim]
Esempio n. 12
0
def WeakTextureMask(img, th, patchsize):

    # Local Variables: cha, Xh, imgh, Xtr, img, Xv, kh, m, col, p, s, msk, kv, th, ind, patchsize, imgv, row
    # Function calls: WeakTextureMask, im2col, sum, imfilter, vertcat, zeros, exist, size
    if not exist('patchsize', 'var'):
        patchsize = 7.
    
    
    kh = np.array(np.hstack((-1./2., 0., 1./2.)))
    imgh = imfilter(img, kh, 'replicate')
    imgh = imgh[:,1:matcompat.size(imgh, 2.)-1.,:]
    imgh = imgh*imgh
    kv = kh.conj().T
    imgv = imfilter(img, kv, 'replicate')
    imgv = imgv[1:matcompat.size(imgv, 1.)-1.,:,:]
    imgv = imgv*imgv
    s = matcompat.size(img)
    msk = np.zeros(s)
    for cha in np.arange(1., (s[2])+1):
        m = im2col(img[:,:,int(cha)-1], np.array(np.hstack((patchsize, patchsize))))
        m = np.zeros(matcompat.size(m))
        Xh = im2col(imgh[:,:,int(cha)-1], np.array(np.hstack((patchsize, patchsize-2.))))
        Xv = im2col(imgv[:,:,int(cha)-1], np.array(np.hstack((patchsize-2., patchsize))))
        Xtr = np.sum(vertcat(Xh, Xv))
        p = Xtr<th[int(cha)-1]
        ind = 1.
        for col in np.arange(1., (s[1]-patchsize+1.)+1):
            for row in np.arange(1., (s[0]-patchsize+1.)+1):
                if p[int(ind)-1] > 0.:
                    msk[int(row)-1:row+patchsize-1.,int(col)-1:col+patchsize-1.,int(cha)-1] = 1.
                
                
                ind = ind+1.
                
            
        
    return [msk]
def velocityPendCenter(pend_centers):

    # Local Variables: c, i, pend_centers, r, VelocityMarker, time
    # Function calls: velocityPendCenter, size
    time = 1. / 30.
    [r, c] = matcompat.size(pend_centers)
    for i in np.arange(2., (r) + 1):
        VelocityMarker[int(i) - 1, int((c - 1.)) - 1] = matdiv(
            pend_centers[int(i) - 1, int((c - 1.)) - 1] - pend_centers[int(
                (i - 1.)) - 1, int((c - 1.)) - 1], time)
        VelocityMarker[int(i) - 1, int(c) - 1] = matdiv(
            pend_centers[int(i) - 1, int(c) - 1] - pend_centers[int(
                (i - 1.)) - 1, int(c) - 1], time)

    return [VelocityMarker]
Esempio n. 14
0
def interpW(W, x, y):

    # Local Variables: h, dy0, dy1, dx1, dx0, y1, W, y0, y, x, x0, x1
    # Function calls: size, interpW, floor
    x0 = np.floor(x)
    x1 = x0+1.
    dx0 = x-x0
    dx1 = 1.-dx0
    y0 = np.floor(y)
    y1 = y0+1.
    dy0 = y-y0
    dy1 = 1.-dy0
    h = matcompat.size(W, 1.)
    W = W[int((np.dot(x-1., h)+y0))-1]*dx1*dy1+W[int((np.dot(x0., h)+y0))-1]*dx0*dy1+W[int((np.dot(x-1., h)+y1))-1]*dx1*dy0+W[int((np.dot(x0., h)+y1))-1]*dx0*dy0
    return [W]
Esempio n. 15
0
def labelmap(bmap, mask, opts):

    # Local Variables: nearest, dist, thetaBin, V, locs, ind, Theta, nOrients, bmap, Dx, Dy, theta, nDists, gtWidth, C, labels, nLabels, I, J, step, R, U, T, dx, dy, Nearest, Dist, h, k, Labels, mask, edges, w, opts
    # Function calls: binangles360, angleimage, cosd, distBin, all, double, cross, sign, labelmap, meshgrid, ind2sub, bwdist, sind, repmat, find, size
    #% [Labels,Dist,Theta] = labelmap( bmap, mask, opts )
    #% It is assumed that bmap was already cleaned (cleanbmap.m)
    gtWidth = opts.gtWidth
    nOrients = opts.nOrients
    nDists = opts.nDists
    nLabels = np.dot(nOrients, nDists)
    #% calculate distances and angles
    [h, w] = matcompat.size(bmap)
    [Dist, Nearest] = bwdist(bmap)
    Nearest = np.double(Nearest)
    Theta = angleimage(bmap, (opts.angleRad))
    [R, C] = ind2sub(np.array(np.hstack((h, w))), Nearest)
    [J, I] = matcompat.meshgrid(np.arange(1., (w)+1), np.arange(1., (h)+1))
    Dx = C-J
    Dy = -(R-I)
    #% focus on locations indicated by mask
    locs = nonzero(mask)
    dx = Dx[int(locs)-1]
    dy = Dy[int(locs)-1]
    nearest = Nearest[int(locs)-1]
    theta = Theta[int(nearest)-1]
    thetaBin = binangles360(theta, (nOrients*2.))
    T = np.array(np.hstack((sind(theta), cosd(theta), 0.*theta)))
    V = np.array(np.hstack((dy, dx, 0.*dx)))
    U = np.cross(T, V)
    dist = Dist[int(locs)-1]*np.sign((-U[:,2]))
    #% standardize
    ind = thetaBin > nOrients
    dist[int(ind)-1] = -dist[int(ind)-1]
    thetaBin[int(ind)-1] = thetaBin[int(ind)-1]-nOrients
    #% bin distance
    k = (nDists-1.)/2.
    step = matdiv(gtWidth-2., nDists-1.)
    edges = np.array(np.hstack((np.dot(step, np.array(np.hstack((np.arange(1., (k)+1)))))-step/2., gtWidth/2.)))
    labels = np.dot(thetaBin-1., nDists)+distBin.conj().T
    #% IMPORTANT assertion that has caught MANY bugs
    #% write result images
    Labels = matcompat.repmat((nLabels+1.), np.array(np.hstack((h, w))))
    Dist = Labels
    Theta = Labels
    Labels[int(locs)-1] = labels
    Dist[int(locs)-1] = distBin
    Theta[int(locs)-1] = thetaBin
    return [Labels, Dist, Theta]
Esempio n. 16
0
def myfun(beta, X):

    # Local Variables: D, F, J, N, beta, X
    # Function calls: myfun, double, nargout, exp, repmat, size
    #% size( beta )   = [D 1] 
    #% size(  X   )   = [N D]
    #% size( X*beta ) = [N 1]
    [N, D] = matcompat.size(X)
    F = 1.-np.exp(np.dot(-X, beta))
    F = np.double(F)
    if nargout > 1.:
        J = matcompat.repmat((1.-F), np.array(np.hstack((1., D))))*X
        J = np.double(J)
    
    
    return [F, J]
Esempio n. 17
0
def interpW_faster(W, x, y):

    # Local Variables: h, dy0, dy1, dx1, dx0, y1, W, y0, y, x, x0, x1, inty, intx
    # Function calls: interpW_faster, all, size, floor
    #% avoid expensive interp math for integer input
    x0 = np.floor(x)
    intx = np.all(np.all((x == x0)))
    y0 = np.floor(y)
    inty = np.all(np.all((y == y0)))
    h = matcompat.size(W, 1.)
    dx1 = 1.-dx0
    y1 = y0+1.
    dy0 = y-y0
    dy1 = 1.-dy0
    W = W[int((np.dot(x-1., h)+y0))-1]*dx1*dy1+W[int((np.dot(x0., h)+y0))-1]*dx0*dy1+W[int((np.dot(x-1., h)+y1))-1]*dx1*dy0+W[int((np.dot(x0., h)+y1))-1]*dx0*dy0
    return [W]
def convmtx(v, n):

    # Local Variables: cidx, c, x_left, ridx, m, n, x_right, mv, t, v, x, r, nv
    # Function calls: convmtx, length, ones, zeros, size, toeplitz
    #%CONVMTX Convolution matrix.
    #%   CONVMTX(C,N) returns the convolution matrix for vector C.
    #%   If C is a column vector and X is a column vector of length N,
    #%   then CONVMTX(C,N)*X is the same as CONV(C,X).
    #%   If R is a row vector and X is a row vector of length N,
    #%   then X*CONVMTX(R,N) is the same as CONV(R,X).
    #%
    #%   % Example:
    #%   %   Generate a simple convolution matrix.
    #%
    #%   h = [1 2 3 2 1];
    #%   convmtx(h,7)        % Convolution matrix
    #%
    #%   See also CONV.
    #%   Author(s): L. Shure, 47-88
    #%   	   T. Krauss, 3-30-93, removed dependence on toeplitz
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.6.4.3 $  $Date: 2012/10/29 19:30:54 $
    [mv, nv] = matcompat.size(v)
    v = v.flatten(1)
    #% make v a column vector
    #t = toeplitz(np.array(np.vstack((np.hstack((v)), np.hstack((np.zeros((n-1.), 1.)))))), np.zeros(n, 1.))
    c = np.array(np.vstack((np.hstack((v)), np.hstack((np.zeros((n-1.), 1.))))))
    r = np.zeros(n, 1.)
    m = length(c)
    x_left = r[int(n)-1:2.:-1.]
    x_right = c.flatten(1)
    x = np.array(np.vstack((np.hstack((x_left)), np.hstack((x_right)))))
    #%x = [r(n:-1:2) ; c(:)];                 % build vector of user data
    cidx = np.arange(0., (m-1.)+1).conj().T
    ridx = np.arange(n, (1.)+(-1.), -1.)
    t = cidx[:,int(np.ones(n, 1.))-1]+ridx[int(np.ones(m, 1.))-1,:]
    #% Toeplitz subscripts
    t[:] = x[int(t)-1]
    #% actual data
    #% end of toeplitz code
    if mv<nv:
        t = t.T
    
    
    return [t]
def convmtx(v, n):

    # Local Variables: cidx, c, x_left, ridx, m, n, x_right, mv, t, v, x, r, nv
    # Function calls: convmtx, length, ones, zeros, size, toeplitz
    #%CONVMTX Convolution matrix.
    #%   CONVMTX(C,N) returns the convolution matrix for vector C.
    #%   If C is a column vector and X is a column vector of length N,
    #%   then CONVMTX(C,N)*X is the same as CONV(C,X).
    #%   If R is a row vector and X is a row vector of length N,
    #%   then X*CONVMTX(R,N) is the same as CONV(R,X).
    #%
    #%   % Example:
    #%   %   Generate a simple convolution matrix.
    #%
    #%   h = [1 2 3 2 1];
    #%   convmtx(h,7)        % Convolution matrix
    #%
    #%   See also CONV.
    #%   Author(s): L. Shure, 47-88
    #%   	   T. Krauss, 3-30-93, removed dependence on toeplitz
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.6.4.3 $  $Date: 2012/10/29 19:30:54 $
    [mv, nv] = matcompat.size(v)
    v = v.flatten(1)
    #% make v a column vector
    #t = toeplitz(np.array(np.vstack((np.hstack((v)), np.hstack((np.zeros((n-1.), 1.)))))), np.zeros(n, 1.))
    c = np.array(
        np.vstack((np.hstack((v)), np.hstack((np.zeros((n - 1.), 1.))))))
    r = np.zeros(n, 1.)
    m = length(c)
    x_left = r[int(n) - 1:2.:-1.]
    x_right = c.flatten(1)
    x = np.array(np.vstack((np.hstack((x_left)), np.hstack((x_right)))))
    #%x = [r(n:-1:2) ; c(:)];                 % build vector of user data
    cidx = np.arange(0., (m - 1.) + 1).conj().T
    ridx = np.arange(n, (1.) + (-1.), -1.)
    t = cidx[:, int(np.ones(n, 1.)) - 1] + ridx[int(np.ones(m, 1.)) - 1, :]
    #% Toeplitz subscripts
    t[:] = x[int(t) - 1]
    #% actual data
    #% end of toeplitz code
    if mv < nv:
        t = t.T

    return [t]
Esempio n. 20
0
def AND(C, B):

    # Local Variables: UB0, varargout, numRankSigma, nout, k, Ux, UC0, Wt, tol, C, B, numRankB, numRankC, UtC, Vx, Wgk, W, Sigma, UtB, dim, Sx, CandB, SC, SB, dSB, dSC, UC, UB
    # Function calls: AND, eye, diag, svd, nargout, inv, pinv, max, sum, size
    dim = matcompat.size(C, 1.)
    tol = 1e-14
    [UC, SC, UtC] = plt.svd(C)
    [UB, SB, UtB] = plt.svd(B)
    dSC = np.diag(SC)
    dSB = np.diag(SB)
    numRankC = np.sum(np.dot(1.0, dSC > tol))
    numRankB = np.sum(np.dot(1.0, dSB > tol))
    UC0 = UC[:, int(numRankC + 1.) - 1:]
    UB0 = UB[:, int(numRankB + 1.) - 1:]
    [W, Sigma, Wt] = plt.svd((np.dot(UC0,
                                     UC0.conj().T) + np.dot(UB0,
                                                            UB0.conj().T)))
    numRankSigma = np.sum(np.dot(1.0, np.diag(Sigma) > tol))
    Wgk = W[:, int(numRankSigma + 1.) - 1:]
    CandB = np.dot(
        np.dot(
            Wgk,
            linalg.inv(
                np.dot(
                    np.dot(
                        Wgk.conj().T,
                        linalg.pinv(C, tol) + linalg.pinv(B, tol) -
                        np.eye(dim)), Wgk))),
        Wgk.conj().T)
    nout = matcompat.max(nargout, 1.) - 1.
    if nout > 0.:
        [Ux, Sx, Vx] = plt.svd(CandB)
        for k in np.arange(1., (nout) + 1):
            if k == 1.:
                varargout[int(k) - 1] = cellarray(np.hstack((Ux)))
            elif k == 2.:
                varargout[int(k) - 1] = cellarray(np.hstack((Sx)))

    return [CandB, varargout]
Esempio n. 21
0
def clustMasks(opts):

    # Local Variables: gtWidth, E, zz, i, k, j, xx, yy, S, t, w, theta, dist, nDists, nOrients, K, opts
    # Function calls: all, cosd, sum, rem, nargout, single, meshgrid, zeros, linspace, error, sind, clustMasks, gradientMag, size
    gtWidth = opts.gtWidth
    nDists = opts.nDists
    nOrients = opts.nOrients
    if plt.rem(gtWidth, 2.) != 0.:
        matcompat.error('gtWidth should be even')
    
    
    #% define gtWidth x gtWidth grid
    [xx, yy] = matcompat.meshgrid(np.arange(-gtWidth/2.+1., (gtWidth/2.)+1))
    #% define the distances and orientations
    k = gtWidth/1.0.
    dist = np.linspace(k, (-k), nDists)
    theta = np.arange(0., (180.-.01)+(180./nOrients), 180./nOrients)
    #% render seg masks for each cluster
    K = np.dot(nDists, nOrients)
    S = np.zeros(gtWidth, gtWidth, K)
    for i in np.arange(1., (nOrients)+1):
        t = theta[int(i)-1]
        w = np.array(np.vstack((np.hstack((cosd(t))), np.hstack((sind(t))))))
        zz = np.dot(w[0], xx)+np.dot(w[1], yy)
        for j in np.arange(1., (nDists)+1):
            k = np.dot(i-1., nDists)+j
            S[:,:,int(k)-1] = zz > dist[int(j)-1]
            
        
    #% check for bugs
    #% demonstrate how to convert segs S to edges E
    if nargout > 1.:
        E = np.zeros(matcompat.size(S))
        for k in np.arange(1., (K)+1):
            E[:,:,int(k)-1] = gradientMag(np.single(S[:,:,int(k)-1])) > .01
            
    
    
    return [S, E]
Esempio n. 22
0
def nms(Es, alpha, tol, nThreads):

    # Local Variables: E, nThreads, outlier, Oe, Ye, O, Xe, Xt, tol, X, Y, alpha, Ot, nOrients, Yt, Es
    # Function calls: convTri, nms, edgeOrient, atan, sum, cos, edgesNmsMex, nargin, single, abs, pi, sin, size
    #% E = nms( Es, alpha, tol, nThreads )
    if nargin < 2.:
        alpha = 1.

    if nargin < 3.:
        tol = 80.

    if nargin < 4.:
        nThreads = 4.

    nOrients = matcompat.size(Es, 3.)
    tol = np.dot(tol, np.pi) / 180.
    #% Flatten and smooth slightly (it helps)
    E = np.sum(Es, 3.)
    E = convTri(E, 1.)
    #% Compute orientation map
    np.array([])
    Ot = np.dot(matdiv(np.single((Ot - 1.)), nOrients), np.pi)
    Oe = edgeOrient(E, 4.)
    if tol > 0.:
        outlier = np.abs((Oe - Ot)) > tol
        Oe[int(outlier) - 1] = Ot[int(outlier) - 1]

    Xt = np.cos(Ot)
    Yt = np.sin(Ot)
    Xe = np.cos(Oe)
    Ye = np.sin(Oe)
    X = Xt + np.dot(alpha, Xe - Xt)
    Y = Yt + np.dot(alpha, Ye - Yt)
    O = atan((Y / X))
    #% Use those orientations to do nms
    E = edgesNmsMex(E, O, 1., 5., 1.01, nThreads)
    return [E]
Esempio n. 23
0
def mirrorhistc(x, e):

    # Local Variables: b, lastBin, nn, bn, n, bp, np, x, e
    # Function calls: all, mirrorhistc, max, min, histc, length, abs, error, diff, ndims, any, size
    #% [N,B] = mirrorhistc( X, E )
    #%
    #% Suppose E = [a b]. Then the binning
    #% used is (-b,-a] (-a,a) [a,b).
    #%
    #% Suppose E = [a b c]. Then the binning
    #% used is (-c,-b] (-b,-a] (-a,a) [a,b) [b,c).
    #%
    #% ...and so on.
    if np.any((e <= 0.)) or not np.all((np.diff(e) > 0.)):
        matcompat.error('invalid bin edges')

    if np.abs(matcompat.max(x)) >= e[int(0) - 1]:
        matcompat.error('data is out of bounds')

    if matcompat.ndim(x) > 2. or matcompat.max(matcompat.size(x)) > 1.:
        matcompat.error('data should be a vector')

    x = x.flatten(0).conj()
    e = e.flatten(0).conj()
    e = np.array(np.hstack((0., e)))
    lastBin = length(e) - 1.
    [nn, bn] = histc((-x[int((x < 0.)) - 1]), e)
    bn = lastBin - bn + 1.
    nn = nn[int(0 - 1.) - 1:1.:-1.]
    [np, bp] = histc(x[int((x >= 0.)) - 1], e)
    bp = bp + lastBin - 1.
    np = np[0:0 - 1.]
    b = 0. * x
    b[int((x < 0.)) - 1] = bn
    b[int((x >= 0.)) - 1] = bp
    n = np.array(np.hstack((nn[0:0 - 1.], nn[int(0) - 1] + np[0], np[1:])))
    return [n, b]
Esempio n. 24
0
def LtoW(L):

    # Local Variables: W, h, L, w, y, x, z
    # Function calls: meshgrid, zeros, LtoW, size
    #% W = LtoW( L )
    [h, w] = matcompat.size(L)
    W = np.zeros(h, w, 121.)
    if 1.:
        #% simple version
    for y in np.arange(1., (h)+1):
        for x in np.arange(1., (w)+1):
            W[int(y)-1,int(x)-1,int(L[int(y)-1,int(x)-1])-1] = 1.
            
        
    else:
        #% harder to read but faster
        [x, y] = matcompat.meshgrid(np.arange(1., (w)+1), np.arange(1., (h)+1))
        x = x.flatten(1)
        y = y.flatten(1)
        z = L.flatten(1)
        W[int((y+np.dot(x-1., h)+np.dot(np.dot(z-1., h), w)))-1] = 1.
        
    
    return [W]
        
        
        
    
#%% plot
#% optimally align C-reconstructed readouts with drivers for nice plots
test_pAligned_PL = cell(1., Np)
test_xAligned_PL = cell(1., Np)
NRMSEsAligned = np.zeros(1., Np)
for p in np.arange(1., (Np)+1):
    intRate = 20.
    thisDriver = pPL.cell[0,int(p)-1]
    thisOut = p_TestPL[0,:,int(p)-1]
    thisDriverInt = interp1(np.arange(1., (signalPlotLength)+1).conj().T, thisDriver.conj().T, np.arange(1., (signalPlotLength)+(1./intRate), 1./intRate).conj().T, 'spline').conj().T
    thisOutInt = interp1(np.arange(1., (testLength)+1).conj().T, thisOut.conj().T, np.arange(1., (testLength)+(1./intRate), 1./intRate).conj().T, 'spline').conj().T
    L = matcompat.size(thisOutInt, 2.)
    M = matcompat.size(thisDriverInt, 2.)
    phasematches = np.zeros(1., (L-M))
    for phaseshift in np.arange(1., (L-M)+1):
        phasematches[0,int(phaseshift)-1] = linalg.norm((thisDriverInt-thisOutInt[0,int(phaseshift)-1:phaseshift+M-1.]))
        
    [maxVal, maxInd] = matcompat.max((-phasematches))
    test_pAligned_PL.cell[0,int(p)-1] = thisOutInt[0,int(maxInd)-1:maxInd+np.dot(intRate, signalPlotLength)-1.:intRate]
    coarseMaxInd = np.ceil(matdiv(maxInd, intRate))
    test_xAligned_PL.cell[0,int(p)-1] = x_TestPL[:,int(coarseMaxInd)-1:coarseMaxInd+signalPlotLength-1.,int(p)-1]
    NRMSEsAligned[0,int(p)-1] = nrmse(test_pAligned_PL.cell[0,int(p)-1], pPL.cell[0,int(p)-1])
    
#%%
#% figure(1); clf;
#% fs = 18; fstext = 18;
#% % set(gcf,'DefaultAxesColorOrder',[0  0.4 0.65 0.8]'*[1 1 1]);
Esempio n. 26
0
def bspderiv(d, c, k):

    # Local Variables: tmp, c, nk, d, mc, i, k, nc, dc, dk
    # Function calls: zeros, bspderiv, numel, size
    #% BSPDERIV:  B-Spline derivative.
    #% 
    #%  MATLAB SYNTAX:
    #% 
    #%         [dc,dk] = bspderiv(d,c,k)
    #%  
    #%  INPUT:
    #% 
    #%    d - degree of the B-Spline
    #%    c - control points          double  matrix(mc,nc)
    #%    k - knot sequence           double  vector(nk)
    #% 
    #%  OUTPUT:
    #% 
    #%    dc - control points of the derivative     double  matrix(mc,nc)
    #%    dk - knot sequence of the derivative      double  vector(nk)
    #% 
    #%  Modified version of Algorithm A3.3 from 'The NURBS BOOK' pg98.
    #%
    #%    Copyright (C) 2000 Mark Spink, 2007 Daniel Claxton
    #%
    #%    This program is free software: you can redistribute it and/or modify
    #%    it under the terms of the GNU General Public License as published by
    #%    the Free Software Foundation, either version 3 of the License, or
    #%    (at your option) any later version.
    #%    This program is distributed in the hope that it will be useful,
    #%    but WITHOUT ANY WARRANTY; without even the implied warranty of
    #%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #%    GNU General Public License for more details.
    #%
    #%    You should have received a copy of the GNU General Public License
    #%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    [mc, nc] = matcompat.size(c)
    nk = numel(k)
    #%
    #% int bspderiv(int d, double *c, int mc, int nc, double *k, int nk, double *dc,
    #%              double *dk)
    #% {
    #%   int ierr = 0;
    #%   int i, j, tmp;
    #%
    #%   // control points
    #%   double **ctrl = vec2mat(c,mc,nc);
    #%
    #%   // control points of the derivative
    dc = np.zeros(mc, (nc-1.))
    #%   double **dctrl = vec2mat(dc,mc,nc-1);
    #%
    for i in np.arange(0., (nc-2.)+1):
        #%   for (i = 0; i < nc-1; i++) {
        
    #%     }
    #%   }
    #%
    dk = np.zeros(1., (nk-2.))
    #%   j = 0;
    dk[0:nk-2.] = k[1:nk-1.]
    #%   for (i = 1; i < nk-1; i++)
    #%     dk[j++] = k[i];
    #%
    #%   freevec2mat(dctrl);
    #%   freevec2mat(ctrl);
    #%
    #%   return ierr;
    #% }
    return [dc, dk]
def InterpolateCrossCorrelation(FirstSignal, SecondSignal, Delays, SamplingPeriod, MaxDelay):

    # Local Variables: SecondPolynomialCoefficients, FirstPolynomialCoefficients, MaxDelay, SecondSignal, MaxLag, PCCC, Delays, Curvature, SamplingPeriod, CrossCorrelation, FirstSignal, Derivative, dd
    # Function calls: disp, PolynomialCoefficientsCrossCorrelation, numel, PolynomialInterpolationCoefficients, ceil, nargin, zeros, InterpolateCrossCorrelation, error, size
    #%InterpolatieCrossCorrelation interpolates the cross-correlation function 
    #%of two discrete signals
    #%
    #% USAGE: [CrossCorrelation Derivative Curvature] = 
    #%   InterpolateCrossCorrelation(FirstSignal,SecondSignal,Delays,SamplingPeriod)
    #%
    #% PARAMETERS:
    #%   FirstSignal ~ values of the first signal
    #%   SecondSignal ~ values of the second signal
    #%   Delays ~ delays in which we want to evaluate the cross-correlation function
    #%   SamplingPeriod ~ sampling period of the signals
    #%
    #% RETURN VALUE:
    #%   CrossCorrelation ~ values of the cross-correlation function at delays
    #%   Derivatives ~ values of its derivative at delays
    #%   Curvature ~ values of its second derivative at delays
    #% 
    #% DESCRIPTION:
    #%   This function interpolates the cross-correlation function at times Delays
    #%   of the signals FirstSignal and SecondSignal (sampled at SamplingPeriod). 
    #%   It does that assuming some polynomial interpolation at each time interval.
    #% 
    #%   This function will then compute:
    #%   1) The sequence of coefficients of each polynomial interpolation.
    #%   2) The cross-correlation of these sequences of coefficients.
    #%   3) The interpolation of the cross-correlation function at each of the Delays.
    #%
    #% REFERENCES:
    #%     X. Alameda-Pineda and R. Horaud. Geometrically-constrained time delay
    #%     estimation-based sound source localisation (gTDESSL). Research Report 
    #%     RR-7988, INRIA, June 2012.
    #%
    #%   see also PolynomialInterpolationCoefficients, PolynomialCoefficientsCrossCorrelation and performCCInterpolation
    #% Copyright 2012, Xavier Alameda-Pineda
    #% INRIA Grenoble Rhone-Alpes
    #% E-mail: [email protected]
    #% 
    #% This is part of the gtde program.
    #% 
    #% gtde is free software: you can redistribute it and/or modify
    #% it under the terms of the GNU General Public License as published by
    #% the Free Software Foundation, either version 3 of the License, or
    #% (at your option) any later version.
    #% 
    #% This program is distributed in the hope that it will be useful,
    #% but WITHOUT ANY WARRANTY; without even the implied warranty of
    #% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #% GNU General Public License for more details.
    #% 
    #% You should have received a copy of the GNU General Public License
    #% along with this program.  If not, see <http://www.gnu.org/licenses/>.
    #%%% Input check
    if nargin<4.:
        matcompat.error('Usage: [CrossCorrelation Derivative] = Interpolation(FirstSignal,SecondSignal,Delays,SamplingPeriod[,MaxDelay]')
    
    
    #%%% Compute the interpolation polynomial coefficients of the signals
    [FirstPolynomialCoefficients] = PolynomialInterpolationCoefficients(FirstSignal, SamplingPeriod)
    [SecondPolynomialCoefficients] = PolynomialInterpolationCoefficients(SecondSignal, SamplingPeriod)
    #%%% Compute the cross-correlation of the coefficients
    if nargin<5.:
        [PCCC] = PolynomialCoefficientsCrossCorrelation(FirstPolynomialCoefficients, SecondPolynomialCoefficients)
    else:
        MaxLag = np.ceil(matdiv(MaxDelay, SamplingPeriod))
        [PCCC] = PolynomialCoefficientsCrossCorrelation(FirstPolynomialCoefficients, SecondPolynomialCoefficients, MaxLag)
        
    
    #%%% Interpolate the cross-correlation at "Delays"
    CrossCorrelation = np.zeros(matcompat.size(Delays))
    Derivative = np.zeros(matcompat.size(Delays))
    Curvature = np.zeros(matcompat.size(Delays))
    for dd in np.arange(1., (numel(Delays))+1):
        if dd == 2651.:
            np.disp('stop')
        
        
        Delays[int(dd)-1]
        
    return [CrossCorrelation, Derivative, Curvature]
Esempio n. 28
0
def NoiseLevel(img, patchsize=7, decim=0, conf=1-(1E-6), itr=3):
    # Image has a single channel?
    if len(img.shape) == 2:
        new_shape = list(img.shape) + [1]
        img = img.reshape(tuple(new_shape))

    img = img.astype(np.float64)
    nlevel, th, num = [], [], []
    
    kernel = [-0.5, 0, 0.5]
    imgh = imfilter_h(img, kernel)
    imgh = imgh[:,1:matcompat.size(imgh, 2.)-1.,:]
    imgh = imgh*imgh

    # imgv = imfilter(img, kv, 'replicate')
    # imgv = scipy.ndimage.correlate(img, kv, mode='nearest')
    imgv = imfilter_v(img, kernel)
    imgv = imgv[1:matcompat.size(imgv, 1.)-1.,:,:]
    imgv = imgv*imgv

    kh = np.array([[-1./2.], [0.], [1./2.]])
    kv = kh.T
    Dh = my_convmtx2(kh, patchsize)
    Dv = my_convmtx2(kv, patchsize)

    DD = np.dot(Dh.conj().T, Dh)+np.dot(Dv.conj().T, Dv)
    r = np.linalg.matrix_rank(DD)
    Dtr = np.trace(DD)

    tau0 = scipy.stats.gamma.ppf(
        conf,
        (np.double(r)/2.),
        scale=(2.0 * Dtr / np.double(r)))

    for cha in np.arange(1., (matcompat.size(img, 3.))+1):
        X = im2col(img[:, :, int(cha) - 1], (patchsize, patchsize))
        Xh = im2col(imgh[:, :, int(cha) - 1], (patchsize, patchsize - 2))
        Xv = im2col(imgv[:, :, int(cha) - 1], (patchsize - 2, patchsize))
        
        # Sum columns
        Xtr = np.sum(np.vstack((Xh, Xv)), 0)
        # import pdb; pdb.set_trace()

        if decim > 0:
            # This is not executed by default
            XtrX = vertcat(Xtr, X)
            XtrX = sortrows(XtrX.conj().T).conj().T
            p = np.floor(matdiv(matcompat.size(XtrX, 2.), decim+1.))
            p = np.dot(np.array(np.hstack((np.arange(1., (p)+1)))), decim+1.)
            Xtr = XtrX[0,int(p)-1]
            X = XtrX[1:matcompat.size(XtrX, 1.),int(p)-1]
        

        #%%%%% noise level estimation %%%%%
        tau = float('inf')
        if matcompat.size(X, 2.)<matcompat.size(X, 1.):
            sig2 = 0.
        else:
            cov = np.dot(X, X.T) / (matcompat.size(X, 2.)-1.)
            d = np.linalg.eigvals(cov)
            # MATLAB's 'eig' sorts values in asc order!
            # sig2 = d[0]
            sig2 = sorted(d)[0]
        
        for i in np.arange(2., (itr)+1):
            tau=sig2 * tau0
            p=(Xtr < tau)
            Xtr = Xtr[p]
            X = X.T[p].T
            if (matcompat.size(X,2) < matcompat.size(X,1)):
                break
            cov=np.dot(X, X.T) / (matcompat.size(X,2) - 1)
            d=np.linalg.eigvals(cov)
            sig2 = sorted(d)[0]

        nlevel.append(np.sqrt(sig2))
        th.append(tau)
        num.append(matcompat.size(X, 2.))

    return nlevel, th, num
Esempio n. 29
0
def entropy_estC(f):

    f = np.asanyarray(f).reshape(-1, 1).T
    k = 30000

    gridFactor = 1.05

    xLPmin = 1 / float(np.dot(k, __builtin__.max(10, k)))

    min_i = min(find(f > 0))
    if min_i > 1:
        xLPmin = min_i / k

    maxLPIters = 1000
    x = 0
    histx = 0

    fLP = f.copy()  # BADA COMMENTs

    fmax = max(find(fLP > 0))
    if min(size(fmax)) == 0:
        x = x(np.arange(1, end()))
        histx = histx(np.arange(1, end()))
        return histx, x

    LPmass = 1 - np.dot(x, np.transpose(histx))
    fLP = np.append(fLP, (zeros(1, int(ceil(sqrt(fmax))))))
    szLPf = max(size(fLP))
    xLPmax = fmax / float(k)

    xLP = dot(
        xLPmin,
        gridFactor**(arange(0, ceil(log(xLPmax / xLPmin) / log(gridFactor)))))
    szLPx = max(size(xLP))

    i = szLPx + dot(2, szLPf)
    i = np.array(i)

    objf = [0 for _ in range(i[0][0])]

    t = fLP.copy()
    for j in range(len(fLP)):
        t[j] = 1. / sqrt(t[j] + 1)
    m = 0
    for j in range(szLPx, len(objf), 2):
        objf[j] = t[m]
        m += 1
    m = 0
    for j in range(szLPx + 1, len(objf), 2):
        objf[j] = t[m]
        m += 1

    m = np.dot(2, szLPf)
    n = szLPx + np.dot(2, szLPf)
    n = np.array(n)
    A = [[0.0 for i in range(n[0][0])] for j in range(m)]
    b = [[0.0 for i in range(1)] for j in range(np.dot(2, szLPf))]

    for i in range(szLPf):
        t = np.dot(k, xLP)
        t = np.array(t)[0]
        t = poisson.pmf(i + 1, t)
        A[2 * i][:szLPx] = t[:]
        A[2 * i + 1][:szLPx] = -t[:]
        t = szLPx + 2 * i
        t = np.asarray(t)[0][0]
        A[2 * i][t] = -1
        t = szLPx + 2 * i + 1
        t = np.asarray(t)[0][0]
        A[2 * i + 1][t] = -1
        b[2 * i][0] = fLP[i]
        b[2 * i + 1][0] = -fLP[i]

    n = szLPx + dot(2, szLPf)
    n = np.array(n)[0][0]
    Aeq = [0 for _ in range(n)]
    t = xLP.copy()
    t = np.asarray(t)[0]
    Aeq[:szLPx] = t[:]
    beq = LPmass
    options = {'maxiter': maxLPIters, 'disp': False}
    for j in range(len(t)):
        for x in range(len(A)):
            A[x][j] = A[x][j] / t[j]
        Aeq[j] = Aeq[j] / t[j]
    lb = 0.0
    ub = float("Inf")
    objf = np.array([objf]).T
    A = np.array(A)
    b = np.array(b)
    cobj = objf.flatten()
    x = 0

    res = linprog(c=cobj,
                  A_ub=A,
                  b_ub=b,
                  A_eq=np.array([Aeq]),
                  b_eq=np.array([beq]),
                  bounds=(lb, ub),
                  options=options,
                  method='interior-point')
    sol2 = res['x']

    if not res['success']:
        print(res['message'])

    for j in range(szLPx):
        sol2[j] = sol2[j] / xLP[j]
    if max(matcompat.size(find((x > 0.)))) == 0.:
        t = np.asarray(xLP)[0]
        for j in range(len(t)):
            t[j] = t[j] * log(t[j])
        ent = np.dot(-sol2[0:szLPx].T, t.T)

    return ent
def stmcb(x, u_in, q, p, niter, a_in):

    # Local Variables: T_sub2, T_sub1, T_minus, C2, C1, a_in, N, u_in, T, a, niter, c, b, i, q, p, u, v, x, T_left, T_right, C1_minus
    # Function calls: convmtx, filter, prony, nargchk, stmcb, nargin, length, zeros, error, message, size
    #%STMCB Compute linear model via Steiglitz-McBride iteration
    #%   [B,A] = stmcb(H,NB,NA) finds the coefficients of the system 
    #%   B(z)/A(z) with approximate impulse response H, NA poles and 
    #%   NB zeros.
    #%
    #%   [B,A] = stmcb(H,NB,NA,N) uses N iterations.  N defaults to 5.
    #%
    #%   [B,A] = stmcb(H,NB,NA,N,Ai) uses the vector Ai as the initial 
    #%   guess at the denominator coefficients.  If you don't specify Ai, 
    #%   STMCB uses [B,Ai] = PRONY(H,0,NA) as the initial conditions.
    #%
    #%   [B,A] = STMCB(Y,X,NB,NA,N,Ai) finds the system coefficients B and 
    #%   A of the system which, given X as input, has Y as output.  N and Ai
    #%   are again optional with default values of N = 5, [B,Ai] = PRONY(Y,0,NA).
    #%   Y and X must be the same length.
    #%
    #%   % Example:
    #%   %   Approximate the impulse response of a Butterworth filter with a 
    #%   %   system of lower order.
    #%
    #%   [b,a] = butter(6,0.2);              % Butterworth filter design
    #%   h = filter(b,a,[1 zeros(1,100)]);   % Filter data using above filter
    #%   freqz(b,a,128)                      % Frequency response 
    #%   [bb,aa] = stmcb(h,4,4);                  
    #%   figure; freqz(bb,aa,128)
    #%
    #%   See also PRONY, LEVINSON, LPC, ARYULE.
    #%   Author(s): Jim McClellan, 2-89
    #%   	       T. Krauss, 4-22-93, new help and options
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.8.4.6 $  $Date: 2012/10/29 19:32:10 $
    matcompat.error(nargchk(3., 6., nargin, 'struct'))
    if length(u_in) == 1.:
        if nargin == 3.:
            niter = 5.
            p = q
            q = u_in
            a_in = prony(x, 0., p)
        elif nargin == 4.:
            niter = p
            p = q
            q = u_in
            a_in = prony(x, 0., p)
            
        elif nargin == 5.:
            a_in = niter
            niter = p
            p = q
            q = u_in
            
        
        u_in = np.zeros(matcompat.size(x))
        u_in[0] = 1.
        #% make a unit impulse whose length is same as x
    else:
        if length(u_in) != length(x):
            matcompat.error(message('signal:stmcb:InvalidDimensions'))
        
        
        if nargin<6.:
            [b, a_in] = prony(x, 0., p)
        
        
        if nargin<5.:
            niter = 5.
        
        
        
    
    a = a_in
    N = length(x)
    for i in np.arange(1., (niter)+1):
        u = filter(1., a, x)
        v = filter(1., a, u_in)
        C1 = convmtx(u.flatten(1), (p+1.))
        C2 = convmtx(v.flatten(1), (q+1.))
        C1_minus = -C1
        T_sub1 = C1_minus[0:N,:]
        T_sub2 = C2[0:N,:]
        T = np.array(np.hstack((T_sub1, T_sub2)))
        #%T = [ C1_minus(1:N,:) C2(1:N,:) ];
        T_minus = -T
        T_left = T[:,1:p+q+2.]
        T_right = T_minus[:,0]
        c = linalg.solve(T_left, T_right)
        #%    c = T(:,2:p+q+2)\(T_minus(:,1));   % move 1st column to RHS and do least-squares
        a = np.array(np.vstack((np.hstack((1.)), np.hstack((c[0:p])))))
        #% denominator coefficients
        b = c[int(p+1.)-1:p+q+1.]
        #% numerator coefficients
        
    a = a.T
    b = b.T
    return [b, a]
Esempio n. 31
0
def bspeval(d, c, k, u):

    # Local Variables: c, d, mc, i, k, nc, N, p, s, u, tmp1, nu
    # Function calls: bspeval, zeros, numel, basisfun, repmat, findspan, size
    #% BSPEVAL:  Evaluate B-Spline at parametric points.
    #% 
    #% Calling Sequence:
    #% 
    #%   p = bspeval(d,c,k,u)
    #% 
    #%    INPUT:
    #% 
    #%       d - Degree of the B-Spline.
    #%       c - Control Points, matrix of size (dim,nc).
    #%       k - Knot sequence, row vector of size nk.
    #%       u - Parametric evaluation points, row vector of size nu.
    #% 
    #%    OUTPUT:
    #%
    #%       p - Evaluated points, matrix of size (dim,nu)
    #% 
    #%    Copyright (C) 2000 Mark Spink, 2007 Daniel Claxton, 2010 C. de Falco
    #%
    #%    This program is free software: you can redistribute it and/or modify
    #%    it under the terms of the GNU General Public License as published by
    #%    the Free Software Foundation, either version 3 of the License, or
    #%    (at your option) any later version.
    #%    This program is distributed in the hope that it will be useful,
    #%    but WITHOUT ANY WARRANTY; without even the implied warranty of
    #%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #%    GNU General Public License for more details.
    #%
    #%    You should have received a copy of the GNU General Public License
    #%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    nu = numel(u)
    [mc, nc] = matcompat.size(c)
    #%   int bspeval(int d, double *c, int mc, int nc, double *k, int nk, double *u,int nu, double *p){
    #%   int ierr = 0;
    #%   int i, s, tmp1, row, col;
    #%   double tmp2;
    #%
    #%   // Construct the control points
    #%   double **ctrl = vec2mat(c,mc,nc);
    #%
    #%   // Contruct the evaluated points
    #%   double **pnt = vec2mat(p,mc,nu);
    #%
    #%   // space for the basis functions
    #%N = zeros(d+1,1);                               %   double *N = (double*) mxMalloc((d+1)*sizeof(double));
    #%
    #%   // for each parametric point i
    #%for col=1:nu                                    %   for (col = 0; col < nu; col++) {
    #%     // find the span of u[col]
    s = findspan((nc-1.), d, u.flatten(1), k)
    #%     s = findspan(nc-1, d, u[col], k);
    N = basisfun(s, u.flatten(1), d, k)
    #%     basisfun(s, u[col], d, k, N);
    #%
    tmp1 = s-d+1.
    #%     tmp1 = s - d;
    #%for row=1:mc                                %     for (row = 0; row < mc; row++)  {
    p = np.zeros(mc, nu)
    #%       tmp2 = 0.0;
    for i in np.arange(0., (d)+1):
        #%       for (i = 0; i <= d; i++)
        
    #%
    #%p(row,:) = tmp2;                      %       pnt[col][row] = tmp2;
    #%end                                         %     }
    #%end                                             %   }
    #%
    #%   mxFree(N);
    #%   freevec2mat(pnt);
    #%   freevec2mat(ctrl);
    #%
    #%   return ierr;
    #%   }
    return [p]
Esempio n. 32
0
def find_frequency(nfreq, nsampl, nsampl_orig, frequencies, sampling_all, sampling):

    # Local Variables: i_nom, pmr, mm1, sampling, nsampl, one_frequency, num_of_mod, pmc, nfreq, nsampl_orig, cardinality, test_set, i_sampln, probable_mod, tempfkm, field_common1, field, fields_to_check, fps, field_common, frequencies, probable_mod1, sampling_all, mm2, num_fps, i, k, j, m, eta, search_limit, common, k_fps
    # Function calls: size, rand, intersect, floor, min, find_frequency, zeros, numel, unique, mod
    fps = 15.
    eta = np.floor(matdiv(nsampl, nfreq))
    for j in np.arange(1., (nsampl)+1):
        test_set[int(j)-1] = sampling[0,int(j)-1]
        
    if eta == 1.:
        eta = 2.
    
    
    fields_to_check = np.zeros(eta)
    #% fields_to_check=[1 2];
    #% end;
    #% fields_to_check=fields_to_check-1;
    while numel(np.unique(fields_to_check))<eta:
        fields_to_check = np.floor(np.dot(np.random.rand(1., eta), nsampl))+1.
        
    #%eta
    #%fields_to_check
    #%pause;
    search_limit = 1.
    for k in np.arange(1., (eta)+1):
        search_limit = np.dot(search_limit, frequencies[int(fields_to_check[int(k)-1])-1])
        
    if search_limit > 2000.:
        search_limit = 2000.
    
    
    for k in np.arange(1., (eta)+1):
        m = 2.
        field[int(k)-1,1] = test_set[int(fields_to_check[int(k)-1])-1]
        #%pause
        num_fps[int(k)-1] = np.floor(matdiv(frequencies[int(fields_to_check[int(k)-1])-1]/2., fps))
        #%frequencies(fields_to_check(k))
        #%num_fps(k)
        #%pause;
        for k_fps in np.arange(1., (num_fps[int(k)-1]+3.)+1):
            if np.mod(k_fps, 2.) == 0.:
                tempfkm = np.dot(k_fps-1., fps)+fps-field[int(k)-1,1]
                if tempfkm<frequencies[int(fields_to_check[int(k)-1])-1]/2.:
                    field[int(k)-1,int(m)-1] = tempfkm
                
                
            else:
                tempfkm = np.dot(k_fps-1., fps)+field[int(k)-1,1]
                if tempfkm<frequencies[int(fields_to_check[int(k)-1])-1]/2.:
                    field[int(k)-1,int(m)-1] = tempfkm
                
                
                
            
            #%tempfkm
            #%pause
            mm1 = 1.
            mm2 = 0.
            while -tempfkm+np.dot(mm1, frequencies[int(fields_to_check[int(k)-1])-1])<search_limit:
                field[int(k)-1,int((m+1.))-1] = -tempfkm+np.dot(mm1, frequencies[int(fields_to_check[int(k)-1])-1])
                mm1 = mm1+1.
                m = m+1.
                
            while tempfkm+np.dot(mm2, frequencies[int(fields_to_check[int(k)-1])-1])<search_limit:
                field[int(k)-1,int((m+1.))-1] = tempfkm+np.dot(mm2, frequencies[int(fields_to_check[int(k)-1])-1])
                mm2 = mm2+1.
                m = m+1.
                
            
        field[int(k)-1,0] = m-2.
        
    #%field
    #%search_limit
    #%pause;
    field_common1[0,0] = 0.
    for i in np.arange(1., (eta-1.)+1):
        cardinality = numel(intersect(field[int(i)-1,1:field[int(i)-1,0]+1.], field[int((i+1.))-1,1:field[int((i+1.))-1,0]+1.]))
        field_common1[0:cardinality] = intersect(field[int(i)-1,1:field[int(i)-1,0]+1.], field[int((i+1.))-1,1:field[int((i+1.))-1,0]+1.])
        field_common1.flatten(1)
        if numel(field_common1) > 0.:
            field[int((i+1.))-1,0] = numel(field_common1.flatten(1))
            field[int((i+1.))-1,1:numel[field_common1[:]]+1.] = field_common1.flatten(1)
        else:
            break
            
        
        
    if numel(field_common1)<1.:
        field_common = 0.
    else:
        field_common = field_common1.flatten(1)
        
    
    #%field_common
    #%pause;
    #%frequencies
    fps
    #%pause
    num_of_mod = numel(field_common)
    for i_nom in np.arange(1., (num_of_mod)+1):
        for i_sampln in np.arange(1., (nsampl_orig)+1):
            if np.mod(np.floor(matdiv(matcompat.max(np.mod(field_common[int(i_nom)-1], frequencies[int(i_sampln)-1]), (frequencies[int(i_sampln)-1]-np.mod(field_common[int(i_nom)-1], frequencies[int(i_sampln)-1]))), fps)), 2.) == 0.:
                probable_mod[int(i_nom)-1,int(i_sampln)-1] = np.mod(matcompat.max(np.mod(field_common[int(i_nom)-1], frequencies[int(i_sampln)-1]), (frequencies[int(i_sampln)-1]-np.mod(field_common[int(i_nom)-1], frequencies[int(i_sampln)-1]))), fps)
            else:
                probable_mod[int(i_nom)-1,int(i_sampln)-1] = 15.-np.mod(matcompat.max(np.mod(field_common[int(i_nom)-1], frequencies[int(i_sampln)-1]), (frequencies[int(i_sampln)-1]-np.mod(field_common[int(i_nom)-1], frequencies[int(i_sampln)-1]))), fps)
                
            
            
        
    #%probable_mod
    #%pause;
    [pmr, pmc] = matcompat.size(probable_mod)
    probable_mod1 = np.zeros(pmc)
    #%frequencies
    common = np.zeros(num_of_mod)
    #%fps
    field_common
    #%frequencies
    #%probable_mod
    for i_nom in np.arange(1., (num_of_mod)+1):
        for j in np.arange(1., (nsampl_orig)+1):
            common[int(i_nom)-1] = common[int(i_nom)-1]+numel(intersect(probable_mod[int(i_nom)-1,int(j)-1], sampling_all[:,int(j)-1]))
            
        common[int(i_nom)-1]
        if common[int(i_nom)-1] >= 1.*nsampl_orig:
            one_frequency[int(i_nom)-1] = field_common[int(i_nom)-1]
            field_common[int(i_nom)-1]
            probable_mod1[0:pmc] = probable_mod[int(i_nom)-1,0:pmc]
            #%     disp('The Vibration Frequency of the machine:::::::::::::::');
            #%one_frequency
            #%pause;
        else:
            #%   [pmr,pmc]=size(probable_mod);
            one_frequency[int(i_nom)-1] = -1.
            #%disp('hi')
            #%  probable_mod1=zeros(pmc);
            
        
        
    return [one_frequency, probable_mod1]
Esempio n. 33
0
def arparest(x, p, method):

    # Local Variables: a, msgobj, XM, Xc, a_left, a_right, minlength_x, mx, nx, p, x, msg, e, Xc_minus, X1, method, Cz
    # Function calls: real, corrmtx, nargchk, getString, min, strcmp, issparse, nargin, length, abs, isempty, error, arparest, message, round, size
    #%ARPAREST   AR parameter estimation via a specified method.
    #%   A = ARPAREST(X,ORDER,METHOD) returns the polynomial A corresponding to 
    #%   the AR parametric signal model estimate of vector X using the specified
    #%   METHOD.  ORDER is the model order of the AR system.
    #%
    #%   Supported methods are: 'covariance' and 'modified' although all of the
    #%   methods of CORRMTX will work. In particular if 'autocorrelation' is
    #%   used, the results should be the same as those of ARYULE (but slower).
    #%
    #%   [A,E] = ARPAREST(...) returns the variance estimate E of the white noise
    #%   input to the AR model.
    #%   Ref: S. Kay, MODERN SPECTRAL ESTIMATION,
    #%              Prentice-Hall, 1988, Chapter 7
    #%        S. Marple, DIGITAL SPECTRAL ANALYSIS WITH APPLICATION,
    #%              Prentice-Hall, 1987, Chapter 8.
    #%        P. Stoica and R. Moses, INTRODUCTION TO SPECTRAL ANALYSIS,
    #%              Prentice-Hall, 1997, Chapter 3
    #%   Author(s): R. Losada and P. Pacheco
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.5.4.3 $  $Date: 2011/05/13 18:13:56 $
    matcompat.error(nargchk(3., 3., nargin, 'struct'))
    [mx, nx] = matcompat.size(x)
    #% Initialize in case we return early
    a = np.array([])
    e = np.array([])
    #% Assign msg in case there are no errors
    msg = \'
    msgobj = np.array([])
    #% Set up necessary but not sufficient conditions for the correlation
    #% matrix to be nonsingular. From (Marple)
    _switch_val=method
    if False: # switch 
        pass
    elif _switch_val == 'covariance':
        minlength_x = 2.*p
    elif _switch_val == 'modified':
        minlength_x = 3.*p/2.
    else:
        msgobj = message('signal:arparest:UnknMethod')
        msg = getString(msgobj)
        return []
    
    #% Do some data sanity testing
    if isempty(x) or length(x)<minlength_x or matcompat.max(mx, nx) > 1.:
        if strcmp(method, 'modified'):
            msgobj = message('signal:arparest:TooSmallForModel', 'X', '3/2')
            msg = getString(msgobj)
        else:
            msgobj = message('signal:arparest:TooSmallForModel', 'X', '2')
            msg = getString(msgobj)
            
        
        return []
    
    
    if issparse(x):
        msgobj = message('signal:arparest:InputSignalCannotBeSparse')
        msg = getString(msgobj)
        return []
    
    
    if isempty(p) or p != np.round(p):
        msgobj = message('signal:arparest:ModelOrderMustBeInteger')
        msg = getString(msgobj)
        return []
    
    
    x = x.flatten(1)
    #% Generate the appropriate data matrix
    XM = corrmtx(x, p, method)
    Xc = XM[:,1:]
    X1 = XM[:,0]
    #% Coefficients estimated via the covariance method
    a_left = np.array(np.hstack((1.)))
    Xc_minus = -Xc
    a_right = linalg.solve(Xc_minus, X1)
    a = np.array(np.vstack((np.hstack((a_left)), np.hstack((a_right)))))
    #%a = [1; -Xc\X1];
    #% Estimate the input white noise variance
    Cz = np.dot(X1.conj().T, Xc)
    e = np.dot(X1.conj().T, X1)+np.dot(Cz, a[1:])
    #% Ignore the possible imaginary part due to numerical errors and force
    #% the variance estimate of the white noise to be positive
    e = np.abs(np.real(e))
    a = a.flatten(0)
    #% By convention all polynomials are row vectors
    #% [EOF] arparest.m
    return [a, e, msg, msgobj]
def findspan(n, p, u, U):

    # Local Variables: j, n, p, s, u, U
    # Function calls: min, max, find, zeros, numel, error, findspan, size
    #% FINDSPAN  Find the span of a B-Spline knot vector at a parametric point
    #%
    #% Calling Sequence:
    #%
    #%   s = findspan(n,p,u,U)
    #%
    #%  INPUT:
    #%
    #%    n - number of control points - 1
    #%    p - spline degree
    #%    u - parametric point
    #%    U - knot sequence
    #%
    #%  OUTPUT:
    #%
    #%    s - knot span index
    #%
    #%  Modification of Algorithm A2.1 from 'The NURBS BOOK' pg68
    #%
    #%    Copyright (C) 2010 Rafael Vazquez
    #%
    #%    This program is free software: you can redistribute it and/or modify
    #%    it under the terms of the GNU General Public License as published by
    #%    the Free Software Foundation, either version 3 of the License, or
    #%    (at your option) any later version.
    #%    This program is distributed in the hope that it will be useful,
    #%    but WITHOUT ANY WARRANTY; without even the implied warranty of
    #%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #%    GNU General Public License for more details.
    #%
    #%    You should have received a copy of the GNU General Public License
    #%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    if matcompat.max(u.flatten(1)) > U[int(0) - 1] or matcompat.max(
            u.flatten(1)) < U[0]:
        matcompat.error('Some value is outside the knot span')

    s = np.zeros(matcompat.size(u))
    for j in np.arange(1., (numel(u)) + 1):
        if u[int(j) - 1] == U[int((n + 2.)) - 1]:
            s[int(j) - 1] = n
            continue

        s[int(j) - 1] = nonzero((u[int(j) - 1] >= U), 1., 'last') - 1.

    #%!test
    #%!  n = 3;
    #%!  U = [0 0 0 1/2 1 1 1];
    #%!  p = 2;
    #%!  u = linspace(0, 1, 10);
    #%!  s = findspan (n, p, u, U);
    #%!  assert (s, [2*ones(1, 5) 3*ones(1, 5)]);
    #%!test
    #%! p = 2; m = 7; n = m - p - 1;
    #%! U = [zeros(1,p)  linspace(0,1,m+1-2*p) ones(1,p)];
    #%! u = [ 0   0.11880   0.55118   0.93141   0.40068   0.35492 0.44392   0.88360   0.35414   0.92186   0.83085   1];
    #%! s = [2   2   3   4   3   3   3   4   3   4   4   4];
    #%! assert (findspan (n, p, u, U), s, 1e-10);
    return [s]
Esempio n. 35
0
Nalphas = 2.*halfPlotNumber+1.
allAlphas = np.zeros(4., Nalphas)
allQuotas = np.zeros(4., Nalphas)
allNorms = np.zeros(4., Nalphas)
attenuationPL = np.zeros(4., Nalphas)
diffPL = np.zeros(4., Nalphas)
zsPL = np.zeros(4., Nalphas)
for i in np.arange(1., (Nalphas)+1):
    allAlphas[:,int(i)-1] = bestAlphas.conj().T*factors.conj().T**exponents[int(i)-1]
    
for p in np.arange(1., 5.0):
    C = Cs.cell[0,int(p)-1]
    testLength = testLengthesAtt[int(p)-1]
    delay = delays[int(p)-1]
    alphas = allAlphas[int(p)-1,:]
    Nalphas = matcompat.size(alphas, 2.)
    sigmaPL = np.zeros(Nalphas, Netsize)
    for i in np.arange(1., (Nalphas)+1):
        alpha = alphas[int(i)-1]
        Calpha = PHI(C, alpha)
        allQuotas[int(p)-1,int(i)-1] = matdiv(np.trace(Calpha), Netsize)
        allNorms[int(p)-1,int(i)-1] = linalg.norm(Calpha, 'fro')**2.
        [U, S, V] = plt.svd(Calpha)
        sigmaPL[int(i)-1,:] = np.diag(S).conj().T
        x = startXs[:,int(p)-1]
        att = 0.
        diff = 0.
        zs = 0.
        for n in np.arange(1., (testLength)+1):
            z = np.tanh((np.dot(W, x)+Wbias))
            x = np.dot(Calpha, z)
def invfreqz(g, w, varargin):

    # Local Variables: realFlag, cg, realStr, D31, gndir, t1, cw, rw, nm, na, nb, Vcap, V1, rg, pf, tol, maxiter, varargin, cwf, wf, ll, D, rwf, D32, Dva, Dvb, gaussFlag, verb, GC, T, e, th, nk, a, OM, b, Vd, g, k, l, st, indg, R, t, w, indb, D3
    # Function calls: disp, polystab, deal, ischar, int2str, all, warning, home, message, size, getString, sqrt, clc, zeros, invfreqz, norm, real, nargchk, max, nargin, ones, isempty, lower, length, num2str, exp, error, strcmp
    #%INVFREQZ  Discrete filter least squares fit to frequency response data.
    #%   [B,A] = INVFREQZ(H,W,NB,NA) gives real numerator and denominator 
    #%   coefficients B and A of orders NB and NA respectively, where
    #%   H is the desired complex frequency response of the system at frequency
    #%   points W, and W contains the normalized frequency values within the 
    #%   interval [0, Pi] (W is in units of radians/sample).
    #%
    #%   INVFREQZ yields a filter with real coefficients.  This means that it is 
    #%   sufficient to specify positive frequencies only; the filter fits the data 
    #%   conj(H) at -W, ensuring the proper frequency domain symmetry for a real 
    #%   filter.
    #%
    #%   [B,A] = INVFREQZ(H,W,NB,NA,Wt) allows the fit-errors to be weighted
    #%   versus frequency.  LENGTH(Wt)=LENGTH(W)=LENGTH(H).
    #%   Determined by minimization of sum |B-H*A|^2*Wt over the freqs in W.
    #%
    #%   [B,A] = INVFREQZ(H,W,NB,NA,Wt,ITER) does another type of fit:
    #%   Sum |B/A-H|^2*Wt is minimized with respect to the coefficients in B and
    #%   A by numerical search in at most ITER iterations.  The A-polynomial is 
    #%   then constrained to be stable.  [B,A]=INVFREQZ(H,W,NB,NA,Wt,ITER,TOL)
    #%   stops the iterations when the norm of the gradient is less than TOL.
    #%   The default value of TOL is 0.01.  The default value of Wt is all ones.
    #%   This default value is also obtained by Wt=[].
    #%
    #%   [B,A] = INVFREQZ(H,W,NB,NA,Wt,ITER,TOL,'trace') provides a textual
    #%   progress report of the iteration.
    #%
    #%   [B,A] = INVFREQZ(H,W,'complex',NB,NA,...) creates a complex filter.  In 
    #%   this case, no symmetry is enforced and W contains normalized frequency
    #%   values within the interval [-Pi, Pi].
    #%
    #%   % Example:
    #%   %   Convert a simple transfer function to frequency response data and 
    #%   %   then back to the original filter coefficients. If the system is
    #%   %   unstable, use invfreqs's iterative algorithm to find a stable 
    #%   %   approximation to the system.
    #%
    #%   b = [1 2 3 2 3];            % Numerator coefficients
    #%   a = [1 2 3 2 1 4];          % Denominator coefficients
    #%   [h,w] = freqz(b,a,64);
    #%   [bb,aa] = invfreqz(h,w,4,5) % aa has poles in the right half-plane.
    #%   [z,p,k] = tf2zp(bb,aa);     % Get Zero-Pole form
    #%   fprintf('Stable Approximation to the system:')
    #%   [bbb,aaa] = invfreqz(h,w,4,5,[],30) % Stable approximation to system
    #%   subplot(2,1,1); zplane(bb,aa); title('PZ plot - Unstable system')
    #%   subplot(2,1,2); zplane(bbb,aaa); title('PZ plot of stable system')
    #%
    #%   See also FREQZ, FREQS, INVFREQS.
    #%   Author(s): J.O. Smith and J.N. Little, 4-23-86
    #%              J.N. Little, 4-27-88, revised 
    #%              Lennart Ljung, 9-21-92, rewritten
    #%              T. Krauss, 99-92, trace mode made optional
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.8.4.8 $  $Date: 2012/10/29 19:31:23 $
    #% calling sequence is
    #%function [b,a]=invfreqz(g,w,nb,na,wf,maxiter,tol,pf)
    #% OR
    #%function [b,a]=invfreqz(g,w,'complex',nb,na,wf,maxiter,tol,pf)
    matcompat.error(nargchk(4., 9., nargin, 'struct'))
    if ischar(varargin.cell[0]):
        realStr = lower(varargin.cell[0])
        varargin[0] = np.array([])
    else:
        realStr = 'real'
        
    
    gaussFlag = length(varargin) > 3.
    #% run Gauss-Newton algorithm or not?
    if length(varargin)<6.:
        varargin.cell[5] = np.array([])
        #% pad varargin with []'s
    
    
    [nb, na, wf, maxiter, tol, pf] = deal(varargin.cell[:])
    _switch_val=realStr
    if False: # switch 
        pass
    elif _switch_val == 'real':
        realFlag = 1.
    elif _switch_val == 'complex':
        realFlag = 0.
    else:
        matcompat.warning(message('signal:invfreqz:InvalidParam', realStr))
        realFlag = 0.
    
    nk = 0.
    T = 1.
    #% The code is prepared for arbitrary sampling interval T and for
    #% constraining the numerator to begin with nk zeros.
    nb = nb+nk+1.
    if isempty(pf):
        verb = 0.
    elif strcmp(pf, 'trace'):
        verb = 1.
        
    else:
        matcompat.error(message('signal:invfreqz:NotSupported', pf))
        
    
    if isempty(wf):
        wf = np.ones(length(w), 1.)
    
    
    wf = np.sqrt(wf)
    if length(g) != length(w):
        matcompat.error(message('signal:invfreqz:InvalidDimensions', 'H', 'W'))
    
    
    if length(wf) != length(w):
        matcompat.error(message('signal:invfreqz:InvalidDimensions', 'Wt', 'W'))
    
    
    #% if any( (w>pi) | (w<0) ) && realFlag 
    #%    warning(message('signal:invfreqz:InvalidRegion', 'W', 'INVFREQZ', '''complex''')) 
    #% end
    [rw, cw] = matcompat.size(w)
    if rw > cw:
        w = w.conj().T
    
    
    [rg, cg] = matcompat.size(g)
    if cg > rg:
        g = g.T
    
    
    [rwf, cwf] = matcompat.size(wf)
    if cwf > rwf:
        wf = wf.conj().T
    
    
    nm = matcompat.max(na, (nb+nk-1.))
    OM = np.exp(np.dot(np.dot(np.dot(-1i., np.arange(0., (nm)+1).conj().T), w), T))
    #%
    #% Estimation in the least squares case:
    #%
    Dva = OM[1:na+1.,:].T*np.dot(g, np.ones(1., na))
    Dvb = -OM[int(nk+1.)-1:nk+nb,:].T
    D = np.array(np.hstack((Dva, Dvb)))*np.dot(wf, np.ones(1., (na+nb)))
    if realFlag:
        R = np.real(np.dot(D.conj().T, D))
        Vd = np.real(np.dot(D.conj().T, -g*wf))
    else:
        R = np.dot(D.conj().T, D)
        Vd = np.dot(D.conj().T, -g*wf)
        
    
    th = linalg.solve(R, Vd)
    a = np.array(np.hstack((1., th[0:na].T)))
    b = np.array(np.hstack((np.zeros(1., nk), th[int(na+1.)-1:na+nb].T)))
    if not gaussFlag:
        return []
    
    
    #% Now for the iterative minimization
    if isempty(maxiter):
        maxiter = 30.
    
    
    if isempty(tol):
        tol = 0.01
    
    
    indb = np.arange(1., (length(b))+1)
    indg = np.arange(1., (length(a))+1)
    a = polystab(a)
    #% Stabilizing the denominator
    #% The initial estimate:
    GC = (np.dot(b, OM[int(indb)-1,:])/np.dot(a, OM[int(indg)-1,:])).T
    e = (GC-g)*wf
    Vcap = np.dot(e.conj().T, e)
    t = np.array(np.hstack((a[1:na+1.], b[int(nk+1.)-1:nk+nb]))).T
    if verb:
        #%messages similar to invfreqs
    clc
    np.disp(np.array(np.hstack(('  ', getString(message('signal:invfreqs:INITIALESTIMATE'))))))
    np.disp(np.array(np.hstack((getString(message('signal:invfreqs:CurrentFit')), num2str(Vcap)))))
    np.disp(getString(message('signal:invfreqs:Parvector')))
    np.disp(t)
    
    #%
    #% ** the minimization loop **
    #%
    gndir = 2.*tol+1.
    l = 0.
    st = 0.
    while np.all(np.array(np.hstack((linalg.norm(gndir) > tol, l<maxiter, st != 1.)))):
        l = l+1.
        #%     * compute gradient *
        D31 = OM[1:na+1.,:].T*np.dot(-GC/np.dot(a, OM[0:na+1.,:]).T, np.ones(1., na))
        D32 = OM[int(nk+1.)-1:nk+nb,:].T/np.dot(np.dot(a, OM[0:na+1.,:]).T, np.ones(1., nb))
        D3 = np.array(np.hstack((D31, D32)))*np.dot(wf, np.ones(1., (na+nb)))
        #%     * compute Gauss-Newton search direction *
        e = (GC-g)*wf
        if realFlag:
            R = np.real(np.dot(D3.conj().T, D3))
            Vd = np.real(np.dot(D3.conj().T, e))
        else:
            R = np.dot(D3.conj().T, D3)
            Vd = np.dot(D3.conj().T, e)
            
        
        gndir = linalg.solve(R, Vd)
        #%     * search along the gndir-direction *
        ll = 0.
        k = 1.
        V1 = Vcap+1.
        while np.all(np.array(np.hstack((V1, ll<20.)))):
            t1 = t-np.dot(k, gndir)
            if ll == 19.:
                t1 = t
            
            
            a = polystab(np.array(np.hstack((1., t1[0:na].T))))
            t1[0:na] = a[1:na+1.].T
            #%Stabilizing denominator
            b = np.array(np.hstack((np.zeros(1., nk), t1[int(na+1.)-1:na+nb].T)))
            GC = (np.dot(b, OM[int(indb)-1,:])/np.dot(a, OM[int(indg)-1,:])).T
            V1 = np.dot(((GC-g)*wf).conj().T, (GC-g)*wf)
            t1 = np.array(np.hstack((a[1:na+1.], b[int(nk+1.)-1:nk+nb]))).T
            if verb:
                home
                np.disp(int2str(ll))
            
            
            k = k/2.
            ll = ll+1.
            if ll == 20.:
                st = 1.
            
            
            if ll == 10.:
                gndir = np.dot(matdiv(Vd, linalg.norm(R)), length(R))
                k = 1.
            
            
            
        if verb:
            home
            np.disp(np.array(np.hstack(('      ', getString(message('signal:invfreqs:ITERATION')), int2str(l)))))
            np.disp(np.array(np.hstack((getString(message('signal:invfreqs:CurrentFit')), num2str(V1), getString(message('signal:invfreqs:PreviousFit')), num2str(Vcap)))))
            np.disp(getString(message('signal:invfreqs:CurrentParPrevparGNdir')))
            np.disp(np.array(np.hstack((t1, t, gndir))))
            np.disp(np.array(np.hstack((getString(message('signal:invfreqs:NormOfGNvector')), num2str(linalg.norm(gndir))))))
            if st == 1.:
                np.disp(getString(message('signal:invfreqs:NoImprovement')))
                np.disp(getString(message('signal:invfreqs:IterationsThereforeTerminated')))
            
            
        
        
        t = t1
        Vcap = V1
        
    return [b, a]
Esempio n. 37
0
def bspinterpcrv(Q, p, method):

    # Local Variables: A, ii, crv, d, n, Q, p, u, pnts, jj, x, y, span, z, knts, method
    # Function calls: basisfun, nrbmak, cumsum, sum, error, sqrt, nargin, ones, isempty, linspace, zeros, diff, size, bspinterpcrv, findspan, strcmpi
    #%
    #% BSPINTERPCRV: B-Spline interpolation of a 3d curve.
    #%
    #% Calling Sequence:
    #%
    #%   crv = bspinterpcrv (Q, p);
    #%   crv = bspinterpcrv (Q, p, method);
    #%   [crv, u] = bspinterpcrv (Q, p);
    #%   [crv, u] = bspinterpcrv (Q, p, method);
    #%
    #%    INPUT:
    #%
    #%      Q      - points to be interpolated in the form [x_coord; y_coord; z_coord].
    #%      p      - degree of the interpolating curve.
    #%      method - parametrization method. The available choices are:
    #%               'equally_spaced'
    #%               'chord_length'
    #%               'centripetal' (Default)
    #%
    #%    OUTPUT:
    #%
    #%      crv - the B-Spline curve.
    #%      u   - the parametric points corresponding to the interpolation ones.
    #%
    #%    See The NURBS book pag. 364 for more information.
    #%
    #%
    #% Copyright (C) 2015 Jacopo Corno
    #%
    #%    This program is free software: you can redistribute it and/or modify
    #%    it under the terms of the GNU General Public License as published by
    #%    the Free Software Foundation, either version 3 of the License, or
    #%    (at your option) any later version.
    #%    This program is distributed in the hope that it will be useful,
    #%    but WITHOUT ANY WARRANTY; without even the implied warranty of
    #%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #%    GNU General Public License for more details.
    #%
    #%    You should have received a copy of the GNU General Public License
    #%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    #%
    if nargin<3. or isempty(method):
        method = 'centripetal'
    
    
    n = matcompat.size(Q, 2.)
    if strcmpi(method, 'equally_spaced'):
        u = np.linspace(0., 1., n)
    elif strcmpi(method, 'chord_length'):
        d = np.sum(np.sqrt(np.sum((np.diff(Q.conj().T).conj().T**2.), 1.)))
        u = np.zeros(1., n)
        u[1:n] = matdiv(np.cumsum(np.sqrt(np.sum((np.diff(Q, np.array([]), 2.)**2.), 1.))), d)
        #%    for ii = 2:n-1
        #%      u(ii) = u(ii-1) + norm (Q(:,ii) - Q(:,ii-1)) / d;
        #%    end
        u[int(0)-1] = 1.
        
    elif strcmpi(method, 'centripetal'):
        d = np.sum(np.sqrt(np.sqrt(np.sum((np.diff(Q.conj().T).conj().T**2.), 1.))))
        u = np.zeros(1., n)
        u[1:n] = matdiv(np.cumsum(np.sqrt(np.sqrt(np.sum((np.diff(Q, np.array([]), 2.)**2.), 1.)))), d)
        #%    for ii = 2:n-1
        #%      u(ii) = u(ii-1) + sqrt (norm (Q(:,ii) - Q(:,ii-1))) / d;
        #%    end
        u[int(0)-1] = 1.
        
    else:
        matcompat.error('BSPINTERPCRV: unrecognized parametrization method.')
        
    
    knts = np.zeros(1., (n+p+1.))
    for jj in np.arange(2., (n-p)+1):
        knts[int((jj+p))-1] = np.dot(1./p, np.sum(u[int(jj)-1:jj+p-1.]))
        
    knts[int(0-p)-1:] = np.ones(1., (p+1.))
    A = np.zeros(n, n)
    A[0,0] = 1.
    A[int(n)-1,int(n)-1] = 1.
    for ii in np.arange(2., (n-1.)+1):
        span = findspan(n, p, u[int(ii)-1], knts)
        A[int(ii)-1,int(span-p+1.)-1:span+1.] = basisfun(span, u[int(ii)-1], p, knts)
        
    x = linalg.solve(A, Q[0,:].conj().T)
    y = linalg.solve(A, Q[1,:].conj().T)
    z = linalg.solve(A, Q[2,:].conj().T)
    pnts = np.array(np.vstack((np.hstack((x.conj().T)), np.hstack((y.conj().T)), np.hstack((z.conj().T)), np.hstack((np.ones(matcompat.size(x.conj().T)))))))
    crv = nrbmak(pnts, knts)
    #%!demo
    #%! Q = [1 0 -1 -1 -2 -3;
    #%!      0 1  0 -1 -1 0;
    #%!      0 0  0  0  0 0];
    #%! p = 2;
    #%! crv = bspinterpcrv (Q, p);
    #%! 
    #%! plot (Q(1,:), Q(2,:), 'xk');
    #%! hold on; grid on;
    #%! nrbkntplot (crv);
    return [crv, u]
def bspkntins(d, c, k, u):

    # Local Variables: alfa, ii, ik, ind, ic, tmp, nk, nc, nu, C, jj, a, c, b, d, mc, ss, k, m, l, n, r, u
    # Function calls: sort, bspkntins, abs, zeros, numel, findspan, size
    #% BSPKNTINS:  Insert knots into a B-Spline
    #%
    #% Calling Sequence:
    #% 
    #%   [ic,ik] = bspkntins(d,c,k,u)
    #%
    #%  INPUT:
    #% 
    #%    d - spline degree             integer
    #%    c - control points            double  matrix(mc,nc)      
    #%    k - knot sequence             double  vector(nk) 
    #%    u - new knots                 double  vector(nu)               
    #% 
    #%  OUTPUT:
    #% 
    #%    ic - new control points double  matrix(mc,nc+nu) 
    #%    ik - new knot sequence  double  vector(nk+nu)
    #% 
    #%  Modified version of Algorithm A5.4 from 'The NURBS BOOK' pg164.
    #% 
    #%    Copyright (C) 2000 Mark Spink, 2007 Daniel Claxton, 2010-2016 Rafael Vazquez
    #%
    #%    This program is free software: you can redistribute it and/or modify
    #%    it under the terms of the GNU General Public License as published by
    #%    the Free Software Foundation, either version 3 of the License, or
    #%    (at your option) any later version.
    #%    This program is distributed in the hope that it will be useful,
    #%    but WITHOUT ANY WARRANTY; without even the implied warranty of
    #%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #%    GNU General Public License for more details.
    #%
    #%    You should have received a copy of the GNU General Public License
    #%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    [mc, nc] = matcompat.size(c)
    u = np.sort(u)
    nu = numel(u)
    nk = numel(k)
    #% 
    #% int bspkntins(int d, double *c, int mc, int nc, double *k, int nk,
    #%               double *u, int nu, double *ic, double *ik)
    #% {
    #%   int ierr = 0;
    #%   int a, b, r, l, i, j, m, n, s, q, ind;
    #%   double alfa;
    #%
    #%   double **ctrl  = vec2mat(c, mc, nc);
    ic = np.zeros(mc, (nc+nu))
    #%   double **ictrl = vec2mat(ic, mc, nc+nu);
    ik = np.zeros(1., (nk+nu))
    #%
    n = nc-1.
    #%   n = nc - 1;
    r = nu-1.
    #%   r = nu - 1;
    #%
    m = n+d+1.
    #%   m = n + d + 1;
    a = findspan(n, d, u[0], k)
    #%   a = findspan(n, d, u[0], k);
    b = findspan(n, d, u[int((r+1.))-1], k)
    #%   b = findspan(n, d, u[r], k);
    b = b+1.
    #%   ++b;
    #%
    #%   for (q = 0; q < mc; q++)  {
    ic[:,0:a-d+1.] = c[:,0:a-d+1.]
    #%     for (j = 0; j <= a-d; j++) ictrl[j][q] = ctrl[j][q];
    ic[:,int(b+nu)-1:nc+nu] = c[:,int(b)-1:nc]
    #%     for (j = b-1; j <= n; j++) ictrl[j+r+1][q] = ctrl[j][q];
    #%   }
    ik[0:a+1.] = k[0:a+1.]
    #%   for (j = 0; j <= a; j++)   ik[j] = k[j];
    ik[int(b+d+nu+1.)-1:m+nu+1.] = k[int(b+d+1.)-1:m+1.]
    #%   for (j = b+d; j <= m; j++) ik[j+r+1] = k[j];
    #%
    ii = b+d-1.
    #%   i = b + d - 1;
    ss = ii+nu
    #%   s = b + d + r;
    for jj in np.arange(r, (0.)+(-1.), -1.):
        #%   for (j = r; j >= 0; j--) {
        
    #%   }
    #%
    #%   freevec2mat(ctrl);
    #%   freevec2mat(ictrl);
    #%
    #%   return ierr;
    #% }
    return [ic, ik, C]
Esempio n. 39
0
def calculateTripleFrequency(remainder, strobe):

    # Local Variables: a, est_fre, remainder1, remainder2, i, k, j, freq_minus, iter, t, freq_plus, fre_11, frequency1, frequency2, freq_plus_shift_negative2, fre_1, remainder_1, remainder, freq_plus_shift_negative1, strobe
    # Function calls: calculateTripleFrequency, floor, cat, length, round, size
    #% clear all
    #% clc
    #%
    #% load('9950.mat');
    #% strobe = [61 67 71 73 79 83 89 97 101 103 107 109 113 127 131];
    #% %  strobe = [61 67 71];
    #% remainder = [2.8457 8.9 13.14 11.86;2.90 14.5312 13.017 10.35;1.6348 11.3848 9.99 7.45;3.45 13.8 10.11 7.08;10.35 9.38 11.62 13.44;10.47 12.29 13.5 14.34;10.9 0.61 12.3 1.63;2.48 10.41 7.75 1.33;1.57 10.71 0.42 9.38;3.75 14.9 11.08 6.84;12.83 7.81 10.35 11.62;10.41 11.8 1.08 12.71;6.72 14.04 10.35 3.69;7.93 14.59 10.05 10.65;12.04 10.83 9.86 13.19];
    #% % remainder = [2.8457 8.9 13.14 11.86;2.90 14.5312 13.017 10.35;1.6348 11.3848 9.99 7.45];
    a = np.array(np.hstack((1., 2., 3.)))
    remainder1 = remainder
    remainder2 = remainder1 - 0.6
    for i in np.arange(1., (length(strobe)) + 1):
        for j in np.arange(1., (length(a)) + 1):
            fre_1[int(i) - 1, int(j) - 1] = np.dot(strobe[int(i) - 1],
                                                   a[int(j) - 1])

    t = matcompat.size(fre_1)
    iter = 1.
    for i in np.arange(1., (t[0, 0]) + 1):
        for j in np.arange(1., (t[0, 1]) + 1):
            fre_11 = fre_1[int(i) - 1, int(j) - 1]
            remainder_1 = remainder2[int(i) - 1, :]
            for k in np.arange(1., (length(remainder_1)) + 1):
                if remainder_1[0, int(k) - 1] > 0.:
                    freq_plus[int(iter) - 1, int(k) -
                              1] = fre_11 + remainder_1[0, int(k) - 1]
                    freq_minus[int(iter) - 1, int(k) -
                               1] = fre_11 - remainder_1[0, int(k) - 1]
                    #%         freq_plus_shift_positive1(iter,k) = fre_11 + (30 + remainder_1(1,k));
                    #%         freq_plus_shift_positive2(iter,k) = fre_11 - (30 + remainder_1(1,k));
                    freq_plus_shift_negative1[
                        int(iter) - 1, int(k) -
                        1] = fre_11 + 30. - remainder_1[0, int(k) - 1]
                    freq_plus_shift_negative2[
                        int(iter) - 1, int(k) -
                        1] = fre_11 - 30. - remainder_1[0, int(k) - 1]

            iter = iter + 1.

    est_fre = cat(1., freq_plus, freq_minus, freq_plus_shift_negative1,
                  freq_plus_shift_negative2)
    frequency1 = np.round(est_fre)
    frequency2 = np.floor(est_fre)
    #% freq_plus_shift_positive1
    #% freq_plus_shift_positive2,
    #% disp('done');
    #% t = size(fre_1);
    #% k = 1;
    #% dr = [];
    #%
    #% est_fre = 0;
    #%
    #% for count = 1:length(fre_1)
    #% fre_11 = fre_1(count,:);
    #% for j = 1:t(:,2)-1
    #% remainder_1 = remainder(1,j);
    #% for i = 1:length(fre_11)
    #%
    #%     freq_plus(k,i) = fre_11(1,i) + remainder_1;
    #%
    #%     freq_minus(k,i) = fre_11(1,i) - remainder_1;
    #%
    #%     freq_plus_shift_positive1(k,i) = fre_11(1,i) + (30 + remainder_1);
    #%
    #%     freq_plus_shift_positive2(k,i) = fre_11(1,i) - (30 + remainder_1);
    #%
    #%     freq_plus_shift_negative1(k,i) = fre_11(1,i) + (30 - remainder_1);
    #%
    #%     freq_plus_shift_negative2(k,i) = fre_11(1,i) - (30 - remainder_1);
    #%
    #% end
    #% if(k < 4)
    #%     k = k + 1;
    #% else
    #%     k = 1;
    #%     est_fre = cat(1,freq_plus,freq_minus,freq_plus_shift_positive1,freq_plus_shift_positive2,freq_plus_shift_negative1,freq_plus_shift_negative2);
    #%     if(count == 1)
    #%         dr = est_fre;
    #%     else
    #%         dr = vertcat(dr,est_fre);
    #%     end
    #%
    #%
    #% end
    #% end
    #% end
    #%
    #% frequency1 = round(dr);
    #% frequency2 = floor(dr);
    return [frequency1, frequency2]