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]
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]
def mfreq_simulate2(frequency): # Local Variables: nfreq, remainder2, i, frequencies, j, stri, sampling, nsampl, cam_fps, frequency, prime1, freq, remainder, sampling_option # Function calls: disp, rand, floor, fprintf, min, fclose, sort, s, num2str, mfreq_simulate2, input, mod nfreq = 4. nsampl = 33. sampling_option = 0. cam_fps = 15. prime1 freq = np.random.rand(1., nfreq) #% frequencies=100+ceil(freq*900); frequencies = np.array(np.hstack((70., 100., 170., 230.))) if sampling_option == 1.: for i in np.arange(1., (nsampl)+1): stri = np.array(np.hstack(('give ', num2str(i), 'th frequency of strobe'))) np.disp(stri) sampling[int(i)-1] = input(\') else: sampling[0:nsampl] = prime1[0:nsampl] sampling for j in np.arange(1., (nsampl)+1): for i in np.arange(1., (nfreq)+1): if np.mod(np.floor(matdiv(matcompat.max(np.mod(frequencies[int(i)-1], sampling[int(j)-1]), (sampling[int(j)-1]-np.mod(frequencies[int(i)-1], sampling[int(j)-1]))), cam_fps)), 2.) == 0.: remainder[int(i)-1,int(j)-1] = np.mod(matcompat.max(np.mod(frequencies[int(i)-1], sampling[int(j)-1]), (sampling[int(j)-1]-np.mod(frequencies[int(i)-1], sampling[int(j)-1]))), cam_fps) else: remainder[int(i)-1,int(j)-1] = 15.-np.mod(matcompat.max(np.mod(frequencies[int(i)-1], sampling[int(j)-1]), (sampling[int(j)-1]-np.mod(frequencies[int(i)-1], sampling[int(j)-1]))), cam_fps) remainder2[:,int(j)-1] = np.sort(remainder[:,int(j)-1]) #%remainder #%remainder2 fprintf(s, '%f\n', nfreq) fprintf(s, '%f\n', nsampl) for j in np.arange(1., (nsampl)+1): fprintf(s, '%f ', sampling[int(j)-1]) fprintf(s, '\n') for i in np.arange(1., (nfreq)+1): for j in np.arange(1., (nsampl)+1): fprintf(s, '%8.2f ', remainder2[int(i)-1,int(j)-1]) fprintf(s, '\n') fclose(s) #%status=0; return [frequencies, sampling]
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]
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]
def collapse_orient(Ws, theta, opts): # Local Variables: W, xx, Ws, Yq, theta, nDists, shrink, cen, yy, dx, dy, Y, X, d, i, k, m, p, r, dists, Xq, opts # Function calls: interpW_faster, cosd, imPad, abs, h, collapse_orient, ceil, meshgrid, linspace, w, max, sind nDists = opts.nDists shrink = opts.shrink #% pad chns and define central pixel grid k = (nDists-1.)/2. cen = k+1. r = opts.gtWidth/1.0. p = np.ceil(matdiv(r, shrink)) Ws = imPad(Ws, p, 'replicate') xx = np.arange(1.+p, (w-p)+1) yy = np.arange(1.+p, (h-p)+1) [X, Y] = matcompat.meshgrid(xx, yy) W = Ws[int(yy)-1,int(xx)-1,int(cen)-1] #% make step vector in orthog direction dx = cosd(theta) dy = sind(theta) m = matcompat.max(np.abs(np.array(np.hstack((dx, dy))))) dx = matdiv(dx, m) dy = matdiv(dy, m) #% translate d~=0 channels to line up with d=0 dists = np.linspace((-r), r, nDists) for i in np.arange(1., (nDists)+1): d = dists[int(i)-1] if d == 0.: continue Xq = X+matdiv(np.dot(dx, d), shrink) Yq = Y-matdiv(np.dot(dy, d), shrink) W = W+interpW_faster(Ws[:,:,int(i)-1], Xq, Yq) return [W]
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]
def process_event_emg(task, event, runIndex, totalTaskTime, sessionNumber): # Local Variables: runIndex, task, val, totalTaskTime, sessionNumber, record_length, ix0, event # Function calls: disp, set, process_event_emg, min, char, str2double, strfind, strcmp #% handle events for this paradigm _switch_val = task.cue_type[int(event) - 1] if False: # switch pass elif _switch_val == 'start_trial': set((task.bar), 'Visible', 'off') #% set(task.text,'String',task.cue{event}); set((task.text), 'String', 'Prepare') if strcmp(np.char((task.cue_type[1])), 'text:bar'): record_length = 10. else: record_length = totalTaskTime #%[status,cmdout] = system('record_length'); #% [status,cmdout] = system(char(trial_data)); #% current_time = num2str(clock); #% for ii = length(current_time) #% ending = strcat(ending,'-',current_time(ii)) #% end #% dataFileName = ['emg_trial_' num2str(trialIndex) '_' ending '.dat']; #% [status,cmdout] = system(dataFileName); elif _switch_val == 'ISI': set((task.bar), 'Visible', 'off') set((task.text), 'String', 'ISI') elif _switch_val == 'text': set((task.text), 'String', (task.cue.cell[int(event) - 1])) set((task.bar), 'Visible', 'off') elif _switch_val == 'text:bar': ix0 = strfind((task.cue.cell[int(event) - 1]), ':') val = str2double( (task.cue.cell[int(event) - 1, int(ix0 + 1.) - 1:]())) / 100. val = matcompat.max(val, 0.9) set((task.text), 'String', (task.cue.cell[int(event) - 1])) if strfind((task.cue.cell[int(event) - 1]), 'Left'): set((task.bar), 'Position', np.array(np.hstack((-val - .1, -.1, val, .2))), 'FaceColor', 'g', 'Visible', 'on') if strfind((task.cue.cell[int(event) - 1]), 'Right'): set((task.bar), 'Position', np.array(np.hstack( (.1, -.1, val, .2))), 'FaceColor', 'r', 'Visible', 'on') elif _switch_val == 'audio': np.disp('play audio here') return
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]
def stackstoroi(save_fld, sd): # Local Variables: I_bw2, I_cum, I_bw1, I, I_overlay, locs, CC, i, # j, img_content, I_edge, m_bloc, I_mean, marks, save_fld, sd # Function calls: save, stackstoroi, mad, findpeaks, cat, bwareaopen, # length, edge, bwconncomp, importdata, max, threshold, mode, cd, dir, mean #% STACKSTOROI(image_fld,sd) loads *I*.mat from save_fld for image #% segmentation. sd is how many standard deviations above the mean the #% threshold is set for segmentation. Outputs: #% CC: connected components found in I_bw2 #% I_mean: averaged image of *I*.mat #% I_bw2: binary image containing image segementation of *I*.mat #% I_overlay: overlay of identified ROI over I_mean #%Example: #% [CC,I_mean,I_bw2,I_overlay] = stackstoroi(save_fld,sd); chdir(save_fld) m_bloc = listdir('*I*.mat*') i_cum = np.array([]) img_content = np.array([]) if length(m_bloc) == 11: for i in np.arange(1, 12.0): i_cum = cat(3, i_cum, importdata((m_bloc[int(i)-1].name))) else: I_cum = importdata((m_bloc[0].name)) for j in np.arange(1., (length(I_cum))+1): I = I_cum[:,:,int(j)-1] img_content[int(j)-1] = np.mean(I.flatten(1)) [marks, locs] = findpeaks(img_content, 'minpeakdistance', 100.) I_mean = np.mean(I_cum[:,:,int(locs)-1], 3.) #%I_bw1 = bwspecial(otsu(I_mean,3)); I_bw1 = threshold(I_mean, (mode(I_mean.flatten(1))+np.dot(sd, mad(I_mean.flatten(1), 1.)))) I_bw2 = bwareaopen(I_bw1, 20., 4.) CC = bwconncomp(I_bw2) I_edge = edge(I_bw2) I_overlay = I_mean I_overlay[int(I_edge)-1] = 10.*matcompat.max(I_mean.flatten(1))/9. plt.save('CC.mat', 'CC') return [CC, I_mean, I_bw2, I_overlay]
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]
plt.xlabel('ndown') plt.subplot(2., 2., 3.) plt.plot(nup[1:], events_up_diff) plt.ylabel('dEvents') plt.xlabel('nup') plt.subplot(2., 2., 4.) plt.plot(ndown[1:], events_down_diff) plt.ylabel('dEvents') plt.xlabel('nup') #% METHOD A - Find local maxima #%{ nupconv = nonzero((np.diff(np.sign(events_up_diff)) == -2.))+1. ndownconv = nonzero((np.diff(np.sign(events_down_diff)) == -2.))+1. if length(nupconv) > 1.: #% in case there is more than one point found nupconv = nonzero((events_up == matcompat.max(events_up[int(nupconv)-1]))) if length(ndownconv) > 1.: ndownconv = nonzero((events_down == matcompat.max(events_down[int(ndownconv)-1]))) plt.figure(2.) plt.subplot(2., 2., 1.) plt.hold(on) plt.scatter(nup[int(nupconv)-1], events_up[int(nupconv)-1], 'ro') plt.subplot(2., 2., 2.) plt.hold(on) plt.scatter(ndown[int(ndownconv)-1], events_down[int(ndownconv)-1], 'ro') #%} #% METHOD B - Find local minima, method 1 nupconv = nonzero((np.diff(np.sign(events_up_diff)) == 2.))+1.
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]
def prony(h, nb, na): # Local Variables: a, c, b, h1, h, nb, H1, M, N, H2, H, na, H2_minus, K # Function calls: max, length, prony, zeros, toeplitz #%PRONY Prony's method for time-domain IIR filter design. #% [B,A] = PRONY(H, NB, NA) finds a filter with numerator order #% NB, denominator order NA, and having the impulse response in #% vector H. The IIR filter coefficients are returned in #% length NB+1 and NA+1 row vectors B and A, ordered in #% descending powers of Z. H may be real or complex. #% #% If the largest order specified is greater than the length of H, #% H is padded with zeros. #% #% % Example: #% % Fit an IIR model to an impulse response of a lowpass filter. #% #% [b,a] = butter(4,0.2); #% impulseResp = impz(b,a); % obtain impulse response #% denOrder=4; numOrder=4; % system function of order 4 #% [Num,Den]=prony(impulseResp,numOrder,denOrder); #% subplot(211); % impulse response and input #% stem(impz(Num,Den,length(impulseResp))); #% title('Impulse Response with Prony Design'); #% subplot(212); #% stem(impulseResp); title('Input Impulse Response'); #% #% See also STMCB, LPC, BUTTER, CHEBY1, CHEBY2, ELLIP, INVFREQZ. #% Author(s): L. Shure, 47-88 #% L. Shure, 117-90, revised #% Copyright 1988-2012 The MathWorks, Inc. #% $Revision: 1.7.4.1.2.1 $ $Date: 2013/01/02 17:47:48 $ #% References: #% [1] T.W. Parks and C.S. Burrus, Digital Filter Design, #% John Wiley and Sons, 1987, p226. K = length(h)-1. M = nb N = na if K<=matcompat.max(M, N): #% zero-pad input if necessary K = matcompat.max(M, N)+1. h[int((K+1.))-1] = 0. c = h[0] if c == 0.: #% avoid divide by zero c = 1. H = toeplitz(matdiv(h, c), np.array(np.hstack((1., np.zeros(1., K))))) #% K+1 by N+1 if K > N: H[:,int(N+2.)-1:K+1.] = np.array([]) #% Partition H matrix H1 = H[0:M+1.,:] #% M+1 by N+1 h1 = H[int(M+2.)-1:K+1.,0] #% K-M by 1 H2 = H[int(M+2.)-1:K+1.,1:N+1.] #% K-M by N H2_minus = -H2 a = np.array(np.vstack((np.hstack((1.)), np.hstack((linalg.solve(H2_minus, h1)))))).T b = np.dot(np.dot(c, a), H1.T) return [b, a]
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]
def RemoveCurveKnot(n, p, U, Pw, u, r, s, num, d): # Local Variables: Pw, alfi, alfj, ii, num, remflag, fout, Pmax, U, jj, off, ord, d, last, temp, TOL, i, k, j, m, n, p, s, r, u, t, w, first # Function calls: min, max, sum, floor, sqrt, zeros, RemoveCurveKnot, norm, mod #% see algorithm A5.8 NURBS Book (pag183) w = matcompat.max(Pw[3,:]) Pmax = matcompat.max(np.sqrt(np.sum((Pw**2.), 1.))) TOL = matdiv(np.dot(d, w), 1.+Pmax) m = n+p+1. ord = p+1. fout = (2.*r-s-p)/2. #% first control point out last = r-s first = r-p temp = np.zeros(4., (2.*p+1.)) for t in np.arange(0., (num-1.)+1): off = first-1. #% diff in index between temp and P temp[:,0] = Pw[:,int(off)-1] temp[:,int((last+1.-off+1.))-1] = Pw[:,int((last+1.))-1] i = first j = last ii = 1. jj = last-off remflag = 0. while j-i > t: #% compute new control points for one removal step if j-i<=t: #% check if knot removable if linalg.norm((temp[:,int((ii-1.+1.))-1]-temp[:,int((jj+1.+1.))-1]))<=TOL: remflag = 1. else: alfi = matdiv(u-U[int(i)-1], U[int((i+ord+t))-1]-U[int(i)-1]) if linalg.norm((Pw[:,int(i)-1]-alfi*temp[:,int((ii+t+1.+1.))-1]+(1.-alfi)*temp[:,int((ii-1.+1.))-1]))<=TOL: remflag = 1. #%if #%if #%if if remflag == 0.: break #% cannot remove any more knots -> get out of for loop else: #% successful removal -> save new control points i = first j = last while j-i > t: Pw[:,int(i)-1] = temp[:,int((i-off+1.))-1] Pw[:,int(j)-1] = temp[:,int((j-off+1.))-1] i = i+1. j = j-1. #%if first = first-1. last = last+1. t = t+1. #% end of for loop if t == 0.: return [[rcrv, t]] #%if #% shift knots for k in np.arange(r+1., (m)+1): U[int((k-t))-1] = U[int(k)-1] U = U[0:0-t] j = np.floor(fout) i = j for k in np.arange(1., (t-1.)+1): if np.mod(k, 2.) == 1.: i = i+1. else: j = j-1. #%if #% shift points for k in np.arange(i+1., (n)+1): Pw[:,int(j)-1] = Pw[:,int(k)-1] j = j+1. Pw = Pw[:,0:0-t] return [[rcrv, t]] return [U, Pw, t]
def findpeak(x, y, npeaks): # Local Variables: best_index, no_width, this_max, increment, ymin, yd2, half_height, ymax, width, wh_cross, fwhm, ysupport, n_crossings, ny, npeaks, elevation, F, full_height, yd, xsupport, y, value_sign, max_index, b, incrementr, g, i, no_widthl, n, p, no_widthr, indices, x, diff_sign, incrementl, xpeaks # Function calls: min, interp1, max, sgolay, length, abs, zeros, floor, diff, findpeak, find clear(p) #%This is a program that finds the positions and FWHMs in a set of #%data specified by x and y. The user supplies the number of peaks and #%the program returns an array p, where the first entries are the positions of #%the peaks and the next set are the FWHMs of the corresponding peaks #%The program is adapted from a routine written by Rob Dimeo at NIST and #%relies on using a Savit-Golay filtering technique to obtain the derivative #%without losing narrow peaks. The parameter F is the frame size for the smoothing #%and is set to 11 pts. The order of the polynomial for making interpolations to better #%approximate the derivate is 4. I have improved on Dimeo's program by also calculating second #%derivate information to better handle close peaks. If peaks are too close together, there are #%still problems because the derivative may not turn over. I have also added a refinement of going #%down both the left and right sides of the peak to determine the FWHMs because of the issue of peaks that #%are close together. #%William Ratcliff F = 11. [b, g] = sgolay(4., F) #%original #%g=sgolay(4,F); yd = np.zeros(1., length(x)) yd2 = np.zeros(1., length(x)) for n in np.arange((F+1.)/2., (length(x)-(F+1.)/2.)+1): yd[int(n)-1] = np.dot(g[:,1].conj().T, y[int(n-(F+1.)/2.+1.)-1:n+(F+1.)/1.0.].conj().T) yd2[int(n)-1] = np.dot(g[:,2].conj().T, y[int(n-(F+1.)/2.+1.)-1:n+(F+1.)/1.0.].conj().T) n_crossings = 0. #%npeaks=3; ny = length(yd) value_sign = 2.*(yd > 0.)-1. indices = 0. #% Determine the number of zero crossings #%diff_sign = value_sign(2:ny)-value_sign(1:ny-1); diff_sign = np.array(np.hstack((0., np.diff(value_sign)))) wh_cross = nonzero(np.logical_and(np.logical_or(diff_sign == 2., diff_sign == -2.), yd2<0.)) n_crossings = length(wh_cross) indices = np.dot(0.5, 2.*wh_cross-1.) no_width = 0. if n_crossings > 0.: #% Ok, now which ones of these are peaks? ysupport = np.arange(1., (length(y))+1) ymax = interp1(ysupport, y, indices) #% ymax = interpolate(y,indices) ymin = matcompat.max(ymax) for i in np.arange(0., (npeaks-1.)+1): #%this_max = max(ymax,max_index) indices = best_index xsupport = np.arange(1., (length(x))+1) xpeaks = interp1(xsupport, x, indices) xpeaks = xpeaks[0:npeaks] for i in np.arange(1., (npeaks)+1): full_height = y[int(np.floor(indices[int(i)-1]))-1] half_height = np.dot(0.5, full_height) #% Descend down the peak until you get lower than the half height elevation = full_height incrementr = 0. while elevation > half_height: #% go down the right side of the peak #%now go to the left side of the peak #% Descend down the peak until you get lower than the half height elevation = full_height incrementl = 0. while elevation > half_height: #% go down the right side of the peak no_width = matcompat.max(no_widthl, no_widthr) increment = matcompat.max(np.abs(incrementl), incrementr) #% no_width_found: if no_width: width = np.dot(2.0, x[int(ny)-1]-xpeaks[int(i)-1]) else: width = np.dot(2.0, x[int((np.floor(indices[int(i)-1])+increment))-1]-xpeaks[int(i)-1]) if i == 1.: fwhm = width else: fwhm = np.array(np.hstack((fwhm, width))) #%plot([(xpeaks(i)-fwhm(i)/2) (xpeaks(i)+fwhm(i)/2)],[half_height half_height]); hold on; #%hold off; #%b=length(fwhm); #%fwhm=fwhm(b); p = np.array(np.hstack((xpeaks, np.abs(fwhm)))) return [] return [p] def fp_gaussian(x, area, center, fwhm): # Local Variables: center, area, sig, y, x, fwhm # Function calls: pi, exp, sqrt, fp_gaussian sig = matdiv(fwhm, 2.354) y = np.dot(matdiv(area, np.sqrt(np.dot(np.dot(2.0, np.pi), sig**2.))), np.exp(np.dot(-0.5, matdiv(x-center, sig)**2.))) return [[p]] return [y]
fs = 18. for p in np.arange(1., (Np)+1): plt.subplot(2., 2., p) line(np.log10(allPhis[int(p)-1,:]), normGrads[int(p)-1,:], 'Color', 'k', 'LineWidth', 2.) set(plt.gca, 'FontSize', fs, 'XTickLabel', np.array([]), 'XLim', np.array(np.hstack((-2.5, 6.5)))) if p == 3.: plt.xlabel('log10 aperture', 'FontSize', fs) plt.ylabel('norm^2 gradient', 'FontSize', fs) if p > 2.: set(plt.gca, 'YLim', np.array(np.hstack((-.5, 1.5)))) ax1 = plt.gca ax2 = plt.axes('Position', plt.get(ax1, 'Position'), 'XAxisLocation', 'top', 'YAxisLocation', 'right', 'Color', 'none', 'YLim', np.array(np.hstack((np.floor(matcompat.max(np.log10(allNRMSEs[int(p)-1,:]))), 1.))), 'XLim', np.array(np.hstack((-2.5, 6.5))), 'XColor', 'k', 'YColor', np.dot(0.5, np.array(np.hstack((1., 1., 1.)))), 'FontSize', fs, 'Box', 'on') line(np.log10(allPhis[int(p)-1,:]), np.log10(allNRMSEs[int(p)-1,:]), 'Color', np.dot(0.6, np.array(np.hstack((1., 1., 1.)))), 'LineWidth', 6., 'Parent', ax2) if p == 4.: plt.ylabel('log10 NRMSE') #%% allDZengys = np.array(np.hstack((allZengys[:,1], -allZengys[:,0], np.dot(0.5, allZengys[:,2:]-allZengys[:,0:0-2.]), allZengys[:,int(0)-1], -allZengys[:,int((0-1.))-1]))) #%% plt.figure(1.) plt.clf set(plt.gcf, 'WindowStyle', 'normal') set(plt.gcf, 'Position', np.array(np.hstack((900., 200., 600., 400.)))) fs = 18. for p in np.arange(1., (Np)+1):
def mfreq_solve12(): # Local Variables: il_all, num_freq, sampling, nsampl, one_frequency, freq_all, nfreq, nsampl_orig, freq_all_all1, rand_start, i1, frequencies, probable_mod1, freq_all_all, count, nfreq_orig, i, k, j, i_num, s, margin # Function calls: sort, rand, unique, floor, mfreq_solve12, fclose, find_frequency, fscanf, min, numel, fopen s = fopen('strobe_file.txt', 'r') nfreq = fscanf(s, '%f', 1.) nsampl = fscanf(s, '%f', 1.) for j in np.arange(1., (nsampl)+1): frequencies[int(j)-1] = fscanf(s, '%f', 1.) for i in np.arange(1., (nfreq)+1): for j in np.arange(1., (nsampl)+1): sampling[int(i)-1,int(j)-1] = fscanf(s, '%f', 1.) fclose(s) nfreq_orig = nfreq nsampl_orig = nsampl for i1 in np.arange(1., (nfreq_orig)+1): il_all = 1. one_frequency = -1. while one_frequency<0.: if nfreq<8.: nsampl = matcompat.max((nfreq*3.), nsampl) margin = nsampl_orig-nsampl if margin > 0.: rand_start = np.floor(np.dot(np.random.rand(1., 1.), margin-1.))+1. else: rand_start = 1. [one_frequency, probable_mod1] = find_frequency(nfreq, nsampl, nsampl_orig, frequencies, sampling, sampling[0:nfreq,int(rand_start)-1:rand_start-1.+nsampl]) num_freq = numel(one_frequency) for i_num in np.arange(1., (num_freq)+1): if one_frequency[int(i_num)-1] > 0.: freq_all[int(i1)-1] = one_frequency[int(i_num)-1] freq_all_all1[int(il_all)-1] = one_frequency[int(i_num)-1] il_all = il_all+1. np.sort(freq_all) #%pause; #%probable_mod; for j in np.arange(1., (nsampl_orig)+1): count = 0. for k in np.arange(1., (nfreq-1.)+1): if count == 1. or sampling[int(k)-1,int(j)-1] == probable_mod1[int(j)-1]: count = 1. sampling[int(k)-1,int(j)-1] = sampling[int((k+1.))-1,int(j)-1] #%sampling; nfreq = nfreq-1. #%sampling #%pause; #%freq_all; #%nfreq; #% for j=1:nsampl_orig #% for i=1:nfreq_orig #% remainder(i,j)=mod(freq_all(i),frequencies(j)); #% end #% remainder2(:,j)=sort(remainder(:,j)); #% end np.sort(freq_all) freq_all_all = np.unique(np.sort(freq_all_all1)) return [freq_all, freq_all_all]
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]
def kntrefine(knots, n_sub, degree, regularity): # Local Variables: knots, old_mult, degree, insk, nz, varargout, regularity, aux_knots, n_sub, idim, new_knots, ik, min_mult, zeta, z, rknots, mult, deg # Function calls: repmat, max, sum, kntrefine, nargout, ones, linspace, numel, error, iscell, unique, vec if iscell(knots): if numel(n_sub) != numel(degree) or numel(n_sub) != numel(regularity) or numel(n_sub) != numel(knots): matcompat.error('kntrefine: n_sub, degree and regularity must have the same length as the number of knot vectors') aux_knots = knots else: if numel(n_sub) != numel(degree) or numel(n_sub) != numel(regularity) or numel(n_sub) != 1.: matcompat.error('kntrefine: n_sub, degree and regularity must have the same length as the number of knot vectors') aux_knots = cellarray(np.hstack((knots))) if nargout == 3.: for idim in np.arange(1., (numel(n_sub))+1): if degree[int(idim)-1]+1. != np.sum((aux_knots.cell[int(idim)-1] == aux_knots.cell[int(idim)-1,0]())): matcompat.error('kntrefine: new_knots is only computed when the degree is maintained') for idim in np.arange(1., (numel(n_sub))+1): min_mult = degree[int(idim)-1]-regularity[int(idim)-1] z = np.unique(aux_knots.cell[int(idim)-1]) nz = numel(z) deg = np.sum((aux_knots.cell[int(idim)-1] == z[0]))-1. rknots.cell[int(idim)-1] = z[int(np.ones(1., (degree[int(idim)-1]+1.)))-1] new_knots.cell[int(idim)-1] = np.array([]) for ik in np.arange(2., (nz)+1): insk = np.linspace(z[int((ik-1.))-1], z[int(ik)-1], (n_sub[int(idim)-1]+2.)) insk = vec(matcompat.repmat(insk[1:0-1.], min_mult, 1.)).conj().T old_mult = np.sum((aux_knots.cell[int(idim)-1] == z[int(ik)-1])) mult = matcompat.max(min_mult, (degree[int(idim)-1]-deg+old_mult)) rknots.cell[int(idim)-1] = np.array(np.hstack((rknots.cell[int(idim)-1], insk, z[int(np.dot(ik, np.ones(1., mult)))-1]))) new_knots.cell[int(idim)-1] = np.array(np.hstack((new_knots.cell[int(idim)-1], insk, z[int(np.dot(ik, np.ones(1., (mult-old_mult))))-1]))) zeta.cell[int(idim)-1] = np.unique(rknots.cell[int(idim)-1]) if not iscell(knots): rknots = rknots.cell[0] zeta = zeta.cell[0] new_knots = new_knots.cell[0] varargout.cell[0] = rknots varargout.cell[1] = zeta varargout.cell[2] = new_knots else: for idim in np.arange(1., (numel(n_sub))+1): min_mult = degree[int(idim)-1]-regularity[int(idim)-1] z = np.unique(aux_knots.cell[int(idim)-1]) nz = numel(z) deg = np.sum((aux_knots.cell[int(idim)-1] == z[0]))-1. rknots.cell[int(idim)-1] = z[int(np.ones(1., (degree[int(idim)-1]+1.)))-1] for ik in np.arange(2., (nz)+1): insk = np.linspace(z[int((ik-1.))-1], z[int(ik)-1], (n_sub[int(idim)-1]+2.)) insk = vec(matcompat.repmat(insk[1:0-1.], min_mult, 1.)).conj().T old_mult = np.sum((aux_knots.cell[int(idim)-1] == z[int(ik)-1])) mult = matcompat.max(min_mult, (degree[int(idim)-1]-deg+old_mult)) rknots.cell[int(idim)-1] = np.array(np.hstack((rknots.cell[int(idim)-1], insk, z[int(np.dot(ik, np.ones(1., mult)))-1]))) zeta.cell[int(idim)-1] = np.unique(rknots.cell[int(idim)-1]) if not iscell(knots): rknots = rknots.cell[0] zeta = zeta.cell[0] varargout.cell[0] = rknots if nargout == 2.: varargout.cell[1] = zeta return [varargout]
def curvederiveval(n, p, U, P, u, d): # Local Variables: ck, span, d, P, ip, k, j, n, p, N, U, pk, u, du # Function calls: curvederivcpts, min, curvederiveval, zeros, basisfun, findspan #% #% CURVEDERIVEVAL: Compute the derivatives of a B-spline curve. #% #% usage: ck = curvederiveval (n, p, U, P, u, d) #% #% INPUT: #% #% n+1 = number of control points #% p = spline order #% U = knots #% P = control points #% u = evaluation point #% d = derivative order #% #% OUTPUT: #% #% ck (k+1) = curve differentiated k times #% #% Adaptation of algorithm A3.4 from the NURBS book, pg99 #% #% Copyright (C) 2009 Carlo de Falco #% 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/>. ck = np.zeros((d + 1.), 1.) du = matcompat.max(d, p) span = findspan(n, p, u, U) N = np.zeros((p + 1.), (p + 1.)) for ip in np.arange(0., (p) + 1): N[0:ip + 1., int((ip + 1.)) - 1] = basisfun(span, u, ip, U).conj().T pk = curvederivcpts(n, p, U, P, du, (span - p), span) for k in np.arange(0., (du) + 1): for j in np.arange(0., (p - k) + 1): ck[int((k + 1.)) - 1] = ck[int((k + 1.)) - 1] + np.dot( N[int((j + 1.)) - 1, int((p - k + 1.)) - 1], pk[int( (k + 1.)) - 1, int((j + 1.)) - 1]) #%!test #%! k = [0 0 0 1 1 1]; #%! coefs(:,1) = [0;0;0;1]; #%! coefs(:,2) = [1;0;1;1]; #%! coefs(:,3) = [1;1;1;1]; #%! crv = nrbmak (coefs, k); #%! ck = curvederiveval (crv.number-1, crv.order-1, crv.knots, squeeze (crv.coefs(1,:,:)), 0.5, 2); #%! assert(ck, [0.75; 1; -2]); #%! ck = curvederiveval (crv.number-1, crv.order-1, crv.knots, squeeze (crv.coefs(2,:,:)), 0.5, 2); #%! assert(ck, [0.25; 1; 2]); #%! ck = curvederiveval (crv.number-1, crv.order-1, crv.knots, squeeze (crv.coefs(3,:,:)), 0.5, 2); #%! assert(ck, [0.75; 1; -2]); return [ck]
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]); #% set(gcf, 'WindowStyle','normal'); #% #% set(gcf,'Position', [600 100 1000 800]); #% for p = 1:Np #% if p <= 8 #% thispanel = (p-1)*4+2;
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]