text
stringlengths
8
6.12M
function [ bs, block ] = Score( s, DNA, n) % s - odkud začíná konsenzus % DNA - typ cell, ve které jsou zadané sekvence % n - jak bude konsenzus dlouhý (jak daleko od začátku je konec konsenzusu) % bs .. to skóre součet maxim (frekvence) % block .. výpis o jaké konsenzy se jednalo for i = 1: length(DNA) block(i,:) = DNA{1, i}(s(i):s(i)+n-1); end for j = 1:length(block) sum_A(j) = length(find(block(:,j)=='A')); sum_C(j) = length(find(block(:,j)=='C')); sum_T(j) = length(find(block(:,j)=='T')); sum_G(j) = length(find(block(:,j)=='G')); end ACTG =[sum_A;sum_C;sum_T;sum_G]; for q=1:length(ACTG) pom(q) = max(ACTG(:,q)); end bs = sum(pom); end
clc clear close all labeltsize=25; fw = 'normal'; %%是否加粗斜体之类 fn='Times New Roman'; linewide1=5; mkft = 15; load 2N.mat figure(1); hold on plot(SNRout,Pd_SGLRT_mc,'k-o','linewidth',linewide1,'MarkerSize',5) plot(SNRout,Pd_SRAO_mc,'r-x','linewidth',linewide1,'MarkerSize',mkft) plot(SNRout,Pd_SWALD_mc,'b-x','linewidth',linewide1,'MarkerSize',mkft) h_leg=legend('GLRT','RAO','WALD'); xlabel('SNR(dB)','FontSize',labeltsize,'FontWeight',fw,'FontName',fn) ylabel('PD','FontSize',labeltsize,'FontWeight',fw,'FontName',fn) set(gca,'FontSize',labeltsize) set(gcf,'Position',[700 0 1300 1000]) set(h_leg,'Location','NorthWest') grid on box on str=['SNR2N.eps']; print(gcf,'-depsc',str) %保存为png格式的图片到当前路径 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% load 10N.mat figure(2); hold on plot(SNRout,Pd_SGLRT_mc,'k-o','linewidth',linewide1,'MarkerSize',5) plot(SNRout,Pd_SRAO_mc,'r-x','linewidth',linewide1,'MarkerSize',mkft) plot(SNRout,Pd_SWALD_mc,'b-x','linewidth',linewide1,'MarkerSize',mkft) h_leg=legend('GLRT','RAO','WALD'); xlabel('SNR(dB)','FontSize',labeltsize,'FontWeight',fw,'FontName',fn) ylabel('PD','FontSize',labeltsize,'FontWeight',fw,'FontName',fn) set(gca,'FontSize',labeltsize) set(gcf,'Position',[700 0 1300 1000]) set(h_leg,'Location','NorthWest') grid on box on str=['SNR10N.eps']; print(gcf,'-depsc',str) %保存为png格式的图片到当前路径 pause(1) close all
% determine the 3dB mainlobe width function res = res(af, delay_delta) s = size(af); res = zeros(s(1),1); % loop across the Doppler axis for jj=1:s(1) % figure out the mainlobe boundary for this slice [~, mid] = max(af(jj,:)); the_max = 0; the_min = 0; for ii=mid:s(2) if af(jj,ii) < 0.5 the_max = ii-1; break; end end for ii=mid-1:-1:1 if af(jj,ii) < 0.5 the_min = ii+1; break; end end res(jj) = (the_max-the_min)*delay_delta; end end
function analyzesim(varargin) % function analyzesim(filename,opts) % or analyzesim() % Runs the standard set of analysis procedures on a file, or in the base workspace. % Calculates center of mass, swimming direction, kinematic parameters, % muscle work, fluid stress and energy. Saves to an output file % ('outfile',filename). opt.curvesmoothcutoff = 0.025; % filter cutoff for curvature % opt.nboundarypts = 30; opt.steadythresh = 0.05; % threshold velocity fluctuation. Less than this is "steady" opt.steadydX = 0.03; % threshold velocity fluctuation. Less than this is "steady" opt.leftsidecurvature = -1; % definition of "left" in terms of curvature opt.leftsidepeak = 1; % definition of "left" in terms of peak direction % peak finding procedure % Look for local max/min. Find points > pkthresh*max. Peak is center % of all neighboring points > pkthresh*max. opt.pkthresh = 0.9; opt.outfile = ''; % output file name opt.samraibasedir = ''; % base directory for all the samrai data files opt.rho = 1; % density in CGS units opt.savepressure = false; opt.savevorticity = false; if ((nargin >= 1) && ischar(varargin{1}) && ... exist(varargin{1},'file')), datafilename = varargin{1}; fprintf('**** File %s\n', varargin{1}); filenameopt = {'-file',varargin{1}}; p = 2; else fprintf('Base workspace\n'); datafilename = ''; filenameopt = {}; p = 1; end; opt = parsevarargin(opt, varargin(p:end), p); % necessary variables disp(' Loading variables...'); if (~getvar(filenameopt{:}, 'actl','actr','fmusPl','fmusPr',... 'fxlmus','fxltot','fxmtot','fxntot','fxrmus','fxrtot',... 'fylmus','fyltot','fymtot','fyntot','fyrmus','fyrtot',... 't','xl','yl','xm','ym','xn','yn','xr','yr',... 'ul','vl','um','vm','un','vn','ur','vr')) error('Could not find necessary variables'); end; if (getvar(filenameopt{:}, 'good')), actl = actl(:,good); actr = actr(:,good); fmusPl = fmusPl(:,good); fmusPr = fmusPr(:,good); fxlmus = fxlmus(:,good); fxrmus = fxrmus(:,good); fylmus = fylmus(:,good); fyrmus = fyrmus(:,good); fxmtot = fxmtot(:,good); fymtot = fymtot(:,good); fxntot = fxntot(:,good); fyntot = fyntot(:,good); fxltot = fxltot(:,good); fyltot = fyltot(:,good); fxrtot = fxrtot(:,good); fyrtot = fyrtot(:,good); t = t(good); xl = xl(:,good); yl = yl(:,good); xm = xm(:,good); ym = ym(:,good); xn = xn(:,good); yn = yn(:,good); xr = xr(:,good); yr = yr(:,good); ur = ur(:,good); vr = vr(:,good); um = um(:,good); vm = vm(:,good); un = un(:,good); vn = vn(:,good); ul = ul(:,good); vl = vl(:,good); end; %optional variables %default values: disp(' Getting the simulation parameters...'); freq = 1; viscosity = 0.01; sfo = 2.56e6; sfo2 = ''; ps = 3; gridres = 32; isforcetaper = 'true'; if (~getvar(filenameopt{:}, 'freq','viscosity','sfo','sfo2','ps','gridres','isforcetaper',... '-keepundef')), prompt = {'freq','viscosity','sfo','sfo2','ps','gridres','isforcetaper'}; def = cellfun(@num2str,{freq,viscosity,sfo,sfo2,ps,gridres,isforcetaper},'UniformOutput',false); if (isempty(sfo2)), def{4} = '0.2*2.56e6'; end; if (isforcetaper), def{7} = 'true'; else def{7} = 'false'; end; vals = inputdlg(prompt,'Simulation constants',1,def); vals = cellfun(@eval,vals,'UniformOutput',false); [freq,viscosity,sfo,sfo2,ps,gridres,isforcetaper] = vals{:}; putvar(filenameopt{:}, 'freq','viscosity','sfo','sfo2','ps','gridres','isforcetaper'); end; nfr = size(xm,2); npt = size(xm,1); s0 = [zeros(1,nfr); cumsum(sqrt(diff(xm).^2 + diff(ym).^2))]; s = nanmean(s0,2); istether = false; disp(' Estimating com speed...'); if (all(abs(xm(1,:) - xm(1,1)) < 1e-3)) disp(' -> appears to be a tethered head simulation'); istether = true; comspeed = zeros(size(t)); if (isempty(opt.samraibasedir)) disp(' ... cannot get flow speed without samrai dirs'); flowspeed = 0; else samraidirs = getdirectorynames(fullfile(opt.samraibasedir,'visit*'))'; [x,y,V] = importsamrai(samraidirs{2},'vars',{'U_0','U_1'}, ... 'interpolaten',[100 50]); flowspeed = mean(V.U_0(x < xm(1,1)-1)); end; end; [width,area,sn, comx,comy,comvelx,comvely] = ... estcomspeed(t,xm,ym,xn,yn,xl,xr,yl,yr); if (isforcetaper), forcetaper = width(:,1) ./ max(width(:,1)); else forcetaper = ones(npt,1); end; if (~istether) comspeed = sqrt(comvelx.^2 + comvely.^2); %unit vector pointing in the direction of the swimming speed, as a cubic %spline in 3 parts, which should get rid of any fluctuation at the level of %the tail beat frequency dt = t(2) - t(1); dur = round(2/dt); %smooth over 2 sec comxsm = runavg(comx, dur); comysm = runavg(comy, dur); swimvecx = deriv(t,comxsm); swimvecy = deriv(t,comysm); mag = sqrt(swimvecx.^2 + swimvecy.^2); swimvecx = swimvecx ./ mag; swimvecy = swimvecy ./ mag; else swimvecx = -1 * ones(size(t)); swimvecy = zeros(size(t)); end; %now average speeds over cycles to look for "steady" %define cycles cycle = t * freq; cycle = cycle - min(floor(cycle)); cyclenum = floor(cycle)+1; cyclenum2 = floor(cycle*2)+1; disp(' Looking for steady speed...'); if (istether) ncycle = max(cyclenum); dt = t(2) - t(1); cycleindlen = round(1/freq/dt); k = 1:length(t)-cycleindlen; dX = NaN(size(t)); dX(k+cycleindlen) = mean(sqrt((xm(:,k+cycleindlen) - xm(:,k)).^2 + ... (ym(:,k+cycleindlen) - ym(:,k)).^2)); dXbycycle = accumarray(cyclenum(:), dX(:), [], @nanmean); steadycycle = length(dXbycycle) - 1; while ((steadycycle >= 1) && all(dXbycycle(steadycycle:end) < opt.steadydX)) steadycycle = steadycycle-1; end; else %average comspeed in each cycle comspeedbycycle = accumarray(cyclenum(:), comspeed(:), [], @nanmean); %and the amount it changes, relative to the current value dcomspeed = diff(comspeedbycycle) ./ comspeedbycycle(1:end-1); %look for those cycles that change less than opt.steadythresh steadycycle = length(comspeedbycycle)-1; while ((steadycycle >= 1) && all(dcomspeed(steadycycle:end) < opt.steadythresh)), steadycycle = steadycycle-1; end; end; if (steadycycle == 1) steadycycle = 2; end issteady = (cyclenum >= steadycycle); %amplitude = displacement relative to the center of mass, perpendicular to the swimming %vector ampcont = -(xm - comx(ones(npt,1),:)) .* swimvecy(ones(npt,1),:) + ... (ym - comy(ones(npt,1),:)) .* swimvecx(ones(npt,1),:); ampsteady = nanmean(range(ampcont(:,issteady))); goodamp = issteady | (range(ampcont) < 2*ampsteady); ampcont(:,~goodamp) = NaN; %track curvature waves %no smoothing in curvature, because we've already smoothed disp(' Estimating curvature...'); curve = curvature(xm,ym, 'discrete','smooth',opt.curvesmoothcutoff); %track zero crossings in curvature disp(' Tracking curvature zero crossings...'); [indzero0,sgnzero0] = ... analyzeKinematics(s,t,xm,ym, 'curve',curve, 'nsmoothcurve',0, ... 'zeros', 'backwnd',0.5, 'returnpeaksign'); %track peaks in amplitude envelope disp(' Tracking amplitude peaks...'); [indpeak0,sgnpeak0,~,~,~,~,~,wavespeed0,wavelen0,~,waven0] = ... analyzeKinematics(s,t,xm,ym, 'curve',ampcont, 'nsmoothcurve',10, ... 'peaks','backwnd',0.5, 'returnpeaksign'); %also track the activation wave disp(' Finding the activation wave...'); [indact,indactoff,isactleft] = findactivationwave(actl,actr); actlen = NaN(size(indact)); for j = 1:size(indact,2)-1, for i = 1:npt, if (isfinite(indact(i,j))), next = last(indact(:,j+1) <= indact(i,j)); if (~isempty(next)), actlen(i,j) = 2*(s(i)-s(next)); end; end; end; end; tact = NaN(size(indact)); good = isfinite(indact); tact(good) = t(indact(good)); actspeed = NaN(1,size(tact,2)); for i = 1:length(actspeed), good = isfinite(tact(:,i)); if (sum(good) > 100), p = polyfit(tact(good,i),s(good), 1); actspeed(i) = p(1); end; end; %early cycles are those with more than three activation starts on frame 1 early = sum(indact == 1) > 3; firstright = first(~isactleft & ~early); t0 = t(first(isfinite(indact(:,firstright)))); %match up the curvature to the activation disp(' Aligning curvature and amplitude peaks to activation wave...'); cyclematchzero = zeros(1,size(indact,2)); cyclematchpeak = zeros(1,size(indact,2)); numincyclezero = zeros(1,size(indact,2)); numincyclepeak = zeros(1,size(indact,2)); for i = 1:size(indact,2), indact1 = first(indact(:,i),isfinite(indact(:,i))); indact2 = last(indactoff(:,i),isfinite(indactoff(:,i))); if (isactleft(i)), sgn1 = opt.leftsidecurvature; else sgn1 = -opt.leftsidecurvature; end; numincycle1 = sum((indzero0 >= indact1) & (indzero0 <= indact2)); numincycle1(sgnzero0 ~= sgn1) = 0; [n1,a] = max(numincycle1); cyclematchzero(i) = a; numincyclezero(i) = n1; if (isactleft(i)), %NB: we want left side activation to correspond to peak right side %excursion, because that's appx when the left side muscle is %*shortest* sgn1 = -opt.leftsidepeak; else sgn1 = opt.leftsidepeak; end; numincycle1 = sum((indpeak0 >= indact1) & (indpeak0 <= indact2)); numincycle1(sgnpeak0 ~= sgn1) = 0; [n1,a] = max(numincycle1); cyclematchpeak(i) = a; numincyclepeak(i) = n1; end; for i = 1:size(indzero0,2), k = find(cyclematchzero == i); if (length(k) > 1), [~,a] = max(numincyclezero(k)); cyclematchzero(k) = 0; cyclematchzero(k(a)) = i; end; end; for i = 1:size(indpeak0,2), k = find(cyclematchpeak == i); if (length(k) > 1), [~,a] = max(numincyclepeak(k)); cyclematchpeak(k) = 0; cyclematchpeak(k(a)) = i; end; end; %rearrange data to match the activation waves indzero = NaN(size(indact)); good = cyclematchzero ~= 0; indzero(:,good) = indzero0(:,cyclematchzero(good)); sgnzero = NaN(1,size(indact,2)); sgnzero(:,good) = sgnzero0(:,cyclematchzero(good)); indpeak = NaN(size(indact)); good = cyclematchpeak ~= 0; indpeak(:,good) = indpeak0(:,cyclematchpeak(good)); sgnpeak = NaN(1,size(indact,2)); sgnpeak(good) = sgnpeak0(cyclematchpeak(good)); %find the peaks of curvature disp(' Looking for curvature peaks...'); indpeakcurve = NaN(size(indzero)); sgnpeakcurve = NaN(size(indzero)); for j = 1:size(indzero,2)-1, for i = 1:size(indzero,1), if (~isnan(indzero(i,j)) && ~isnan(indzero(i,j+1)) && ... (indzero(i,j+1) > indzero(i,j))), k = indzero(i,j):indzero(i,j+1); curve1 = curve(i,k); mx = max(abs(curve1)); ishigh = abs(curve1) >= opt.pkthresh*mx; sgn1 = sign(first(curve1,ishigh)); if (any(sign(curve1(ishigh)) ~= sgn1)), ctr = NaN; else weight = abs(curve1(ishigh)); if (length(weight) > 1), weight = (weight - min(weight))/range(weight); else weight = 1; end; ctr = sum(k(ishigh) .* weight) ./ ... sum(weight); end; indpeakcurve(i,j) = round(ctr); sgnpeakcurve(i,j) = sgn1; end; end; end; good = cyclematchpeak ~= 0; wavespeed = NaN(1,size(indzero,2)); wavespeed(good) = wavespeed0(cyclematchpeak(good)); waven = zeros(1,size(indzero,2)); waven(good) = waven0(cyclematchpeak(good)); wavelen = NaN(size(indzero)); wavelen(:,good) = wavelen0(:,cyclematchpeak(good)); amp = NaN(size(indact)); for c = 1:size(indact,2)-2, if any((cyclenum2 == c) | (cyclenum2 == c+1)) amp(:,c) = range(ampcont(:,(cyclenum2 == c) | (cyclenum2 == c+1)),2)/2; end end; disp(' Calculating work loops...'); [lennorm,worktot,workpos,workneg,workposact,worknegact] = workloop(t, xl,yl,fmusPl,actl, ... xr,yr,fmusPr,actr, ... 'per',1/freq, 'plot',false, 'forcetaper',forcetaper); disp(' Calculating fluid forces...'); Force = fluidforces(t,freq, swimvecx,swimvecy, xm,ym, fxmtot,fymtot, ... xl,yl,fxltot,fyltot, xr,yr,fxrtot,fyrtot); out.freq = freq; out.viscosity = viscosity; out.sfo = sfo; out.sfo2 = sfo2; out.ps = ps; out.gridres = gridres; out.isforcetaper = isforcetaper; out.t = t; out.s = s; out.s0 = s0; out.sn = sn; out.nfr = nfr; out.npt = npt; out.comx = comx; out.comy = comy; out.comvelx = comvelx; out.comvely = comvely; out.swimvecx = swimvecx; out.swimvecy = swimvecy; out.comspeed = comspeed; out.width = width; out.area = area; out.curve = curve; out.ampcont = ampcont; out.amp = amp; out.wavespeed = wavespeed; out.wavelen = wavelen; out.indact = indact; out.indactoff = indactoff; out.isactleft = isactleft; out.actspeed = actspeed; out.actlen = actlen; out.indzero = indzero; out.sgnzero = sgnzero; out.indpeak = indpeak; out.sgnpeak = sgnpeak; out.indpeakcurve = indpeakcurve; out.sgnpeakcurve = sgnpeakcurve; out.issteady = issteady; out.steadycycle = steadycycle; out.cyclenum = cyclenum; out.lennorm = lennorm; out.worktot = worktot; out.workpos = workpos; out.workneg = workneg; out.workposact = workposact; out.worknegact = worknegact; out.Force = Force; out.HGREV = savehgrev([], 'datafile',datafilename); if (~isempty(opt.samraibasedir) && inputyn('Load fluid data? ')) disp(' Calculating fluid quantities...'); samraidirs = getdirectorynames(fullfile(opt.samraibasedir,'visit*'))'; if (isempty(samraidirs)) saveextra = {}; else if (~isempty(opt.outfile)) [pn,fn,ext] = fileparts(opt.outfile); cont = fullfile(pn,[fn 'Continue.mat']); else cont = ''; end; if (~isempty(cont) && exist(cont,'file')) load(cont, 'Stress','samraidirs','fr','Energy'); fr0 = fr; fprintf('Continuing from frame %d...\n', fr0); else fr0 = 1; end; boundx0 = [xm(1,:); xl(2:end-1,:); xm(end,:); xr(end-1:-1:2,:); xm(1,:)]; boundy0 = [ym(1,:); yl(2:end-1,:); ym(end,:); yr(end-1:-1:2,:); ym(1,:)]; boundu0 = [um(1,:); ul(2:end-1,:); um(end,:); ur(end-1:-1:2,:); um(1,:)]; boundv0 = [vm(1,:); vl(2:end-1,:); vm(end,:); vr(end-1:-1:2,:); vm(1,:)]; Energy.totalke = NaN(1,nfr); Energy.dissip = NaN(1,nfr); Energy.boundflux = NaN(4,nfr); opt1.rho = 1; % in g/cm^3 opt1.mu = viscosity; opt1.savepressure = opt.savepressure; opt1.savevorticity = opt.savevorticity; N = min(length(samraidirs)-1, nfr); for fr = fr0:N, fprintf('Importing %s (%d%%)...\n', samraidirs{fr+1}, round((fr+1)/nfr*100)); V = importsamrai(samraidirs{fr+1},'vars',{'U_0','U_1','P'}); V = getsamraipatchedges(V); V = velderivsamrai(V); [totalke1,dissip1,boundflux1] = energybalance1(V,opt1); Energy.totalke(fr) = totalke1; Energy.dissip(fr) = dissip1; Energy.boundflux(:,fr) = boundflux1; S1 = fluidstressnearboundary1(V, boundx0(:,fr),boundy0(:,fr),... boundu0(:,fr),boundv0(:,fr), opt1); Stress.tanx{fr} = S1.tanx; Stress.tany{fr} = S1.tany; Stress.s{fr} = S1.s; Stress.n{fr} = S1.n; Stress.nearboundx{fr} = S1.nearboundx; Stress.nearboundy{fr} = S1.nearboundy; Stress.normstress{fr} = S1.normstress; Stress.tanstress{fr} = S1.tanstress; if (opt.savepressure) Stress.nearboundp{fr} = S1.nearboundp; end; if (opt.savevorticity) Stress.nearboundut{fr} = S1.nearboundut; Stress.nearboundun{fr} = S1.nearboundun; Stress.vorticity{fr} = S1.vorticity; end; if (~isempty(cont) && (mod(fr,10) == 0)) save(cont,'Stress','samraidirs','fr','Energy'); end; end; out.Energy = Energy; out.Stress = Stress; end; end; if (istether) out.flowspeed = flowspeed; end; disp(' Saving data...'); if (~isempty(opt.outfile)), save(opt.outfile, '-struct','out'); else putvar(filenameopt{:}, '-fromstruct','out', '-all'); end;
classdef neighbourhood < handle properties label m % row n % column end properties (Transient) n_selfneighs end methods function obj = neighbourhood(m, n, varargin) if nargin<1 obj.m = 1; obj.n = 1; else obj.m = m; obj.n = n; end end function obj = uplus(obj1) obj = utils.uplus(obj1); end function set_n_selfneighs(obj) obj.n_selfneighs = ones(obj.m*obj.n,1); % preset so as to normalize to one in the next function % count size of neighbourhood of each node obj.n_selfneighs = obj.neigh_avg(ones(obj.m*obj.n,1)); end function neigh_avg(obj, state) % if m or n were changed in the meantime, update n_selfneighs if ~isequal(size(state),size(obj.n_selfneighs)) obj.set_n_selfneighs(); end end end methods(Static) function [m, n] = get_m_n(k, m_seed, n_seed) if nargin<2; m_seed = 1; n_seed = 1; end if m_seed<n_seed m = m_seed*2^ceil((k-1)/2); n = n_seed*2^floor((k-1)/2); else m = m_seed*2^floor((k-1)/2); n = n_seed*2^ceil((k-1)/2); end end function [m, n] = get_m_n_N(N) for m=floor(sqrt(N)):-1:1 if mod(N,m)==0; break; end end n = N/m; end end end
%Nhom 1 %53 %Pham Ba Tung %B15DCDT221 I0=imread('chuoi.jpg'); size(I0) subplot(2,2,1 ) imshow(I0) I=rgb2gray(I0); I1=im2bw(I0); subplot(2,2,2) imshow(I) subplot(2,2,3) imshow(I1) [n m] = size(I); T = 128; for i=1:n for j=1:m if I(i,j) < T I(i,j) = 0; if j<m I(i,j+1) = I(i,j); end else e = 255 - I(i,j); I(i,j) = 255; if j<m I(i,j+1) = e; end end end end subplot(2,2,4) imshow(I)
function tokenList = split(str, delimiter) % SPLIT Split a string based on a given delimiter % Usage: % tokenList = split(str, delimiter) % Roger Jang, 20010324 tokenList = {}; remain = str; i = 1; while ~isempty(remain), [token, remain] = strtok(remain, delimiter); tokenList{i} = token; i = i+1; end
% CLASSIFYRBFN Classify data with radial basis function network. % OUT = CLASSIFYRBFN(X,MODEL) classifies the data in X (N samples-by-D % features) by using a radial basis function network (RBFN), where MODEL is % a structure with the RBFN parameters: centroids, spreads, and weights. % OUT is a structure with both the scores obtained from output units and the % class labels assigned to each sample in X. If OUT.Labels=1 is a benign lesion, % whereas if OUT.Labels=2 is a malignant lesion % % Example: % ------- % load('bcwd.mat'); % ho = crossvalind('HoldOut',Y,0.2); % Hold-out 80-20% % [Xtr,m,s] = softmaxnorm(X(ho,:)); % Training data normalization % Xtt = softmaxnorm(X(~ho,:),[m;s]); % Test data normalization % Ytr = Y(ho,:); % Training targets % Ytt = Y(~ho,:); % Test targets % Model = trainRBFN(Xtr,Ytr); % Train RBFN % Out = classifyRBFN(Xtt,Model); % Test RBFN % perf = classperf(Out.Labels,Ytt); % Evaluate classification performance % % See also AUC CLASSPERF CLASSIFYLDA CLASSIFYSVM CLASSIFYLSVM CLASSIFYRF % % % References: % ---------- % Theodoridis S, Koutroumbas K. Pattern recognition. 4th edition. % Burlington, MA: Academic Press 2009. % % K. L. Priddy, P. E. Keller, Artificial Neural Networks: An Introduction. % Bellingham, WA: SPIE-The Int. Soc. Optical Eng., 2005. % ------------------------------------------------------------------------ % Cinvestav-IPN (Mexico) - LUS/PEB/COPPE/UFRJ (Brazil) % CLASSIFYRBFN Version 1.0 (Matlab R2014a Unix) % November 2016 % Copyright (c) 2016, Wilfrido Gomez Flores % ------------------------------------------------------------------------ function Out = classifyRBFN(Xtt,Model) % Load model Ci = Model.Centroids; Si = Model.Sigmas; W = Model.Weights; % Classify Ntt = size(Xtt,1); DV = eucdist(Xtt,Ci); S = Si(ones(Ntt,1),:); aux2 = exp(-DV./(2*S.^2)); phi2 = cat(2,ones(Ntt,1),aux2); Out.Scores = phi2*W; [~,Out.Labels] = max(Out.Scores,[],2); %******************************************************************* function D = eucdist(A,B) nA = sum(A.*A,2); nB = sum(B.*B,2); D = abs(bsxfun(@plus,nA,nB') - 2*(A*B'));
% this function is to calcaluate and draw 2 dimensional histogram. function samples = twoDbin load PTsampleing.mat; X = chain(:,1); Y = chain(:,2); xbins = -1.5:1:1.5; % xbins(find(xbins==0))=[]; ybins = -1.5:1:1.5; % ybins(find(ybins==0))=[]; xNumBins = numel(xbins); yNumBins = numel(ybins); Xi = round(interp1(xbins,1:xNumBins,X,'linear','extrap')); Yi = round(interp1(ybins,1:yNumBins,Y,'linear','extrap')); Xi = max( min(Xi,xNumBins), 1); Yi = max( min(Yi,yNumBins), 1); H = accumarray([Yi(:) Xi(:)],1,[yNumBins xNumBins]); %figure %imagesc(xbins, ybins, H), axis on %# axis image %colormap hot; colorbar %hold on, plot(X, Y,'b.','MarkerSize',1), hold off H(2,:) = H(2,:)+H(3,:); H(3,:) = []; H(:,2) = H(:,2)+H(:,3); H(:,3) =[] samples = reshape(H,1,[]); samples = samples/sum(samples); return; clear
function [Vstart,Vstop,Xstart,Xstop] = create_goal(fig) cmap = lines(5); F = [1 2 3 4; 5 6 7 8; 1 2 6 5; 2 3 7 6; 3 4 8 7; 1 4 8 5]; % Start x = 130; y = 300; z = 20; w = 20; h = 20; Vx_start = [x x+w x+w x x x+w x+w x]; Vy_start = [y y y+h y+h y y y+h y+h]; Vz_start = [0 0 0 0 z z z z]; Vstart = [Vx_start' Vy_start' Vz_start']; Xstart = [x+w/2 y+h/2 z/2 0 0 0]'; x = 250; y = 100; w = 20; h = 20; z = 20; Vx_stop = [x x+w x+w x x x+w x+w x]; Vy_stop = [y y y+h y+h y y y+h y+h]; Vz_stop = [0 0 0 0 z z z z]; Vstop = [Vx_stop' Vy_stop' Vz_stop']; Xstop = [x+w/2 y+h/2 z/2 0 0 0]; if ~isempty(fig) figure(fig); hold on; patch('Faces',F,'Vertices',Vstart,'FaceColor','None','EdgeColor',cmap(5,:)); patch('Faces',F(1,:),'Vertices',Vstart(1:4,:),'FaceColor',cmap(5,:),'FaceAlpha',0.5); plot3(Xstart(1),Xstart(2),Xstart(3),'*g','MarkerSize',15,'Linewidth',2); patch('Faces',F,'Vertices',Vstop,'FaceColor','None','EdgeColor',cmap(2,:)); patch('Faces',F(1,:),'Vertices',Vstop(1:4,:),'FaceColor',cmap(2,:),'FaceAlpha',0.5); end end
% Enhances the contrast of the image % Adapted from http://imageprocessingblog.com/histogram-adjustments-in-matlab-part-i/ function [out] = enhance_contrast(im) hsvimg = rgb2hsv(im); for ch=2:3 hsvimg(:,:,ch) = imadjust(hsvimg(:,:,ch), ... stretchlim(hsvimg(:,:,ch), 0.01)); end out = hsv2rgb(hsvimg); end
clc clear all close all % % a=input('Enter the Choice') disp('This is a MASK of Median Filter') q1=input('Enter the size of Mask ') g1=[1 1 1;1 1 1;1 1 1] subplot(2,2,3) imshow(g1,[]) title('This is Mask') a1=imread('cameraman.tif'); subplot(2,2,1) a11=double(a1); imshow(a1) title('Original image') [r,c] = size(a11); a2= imnoise(a1,'salt & pepper',0.02); subplot(2,2,2) imshow(a2) title('Input Image with Salt and Pepper Noise') NIm=zeros(r,c); t=(q1-1)/2; xc=t+1; q2=((q1+1)/2)-1 for i=xc:r-1 for j=xc:c-1 temp=0; for k=-t:t for l=-t:t temp(i,j)=(a2(k+i,l+j).*g1(k+xc,l+xc)); temp2(k+2,l+2)=(temp(i,j)); temp3=temp2(:); temp4=sort(temp3'); temp5=temp4(ceil(end/2)); NIm(i+q2-1,j+q2-1)=temp5; end end end end subplot(2,2,4) imshow(NIm,[]) title('Output Image')
%% Params verbose = 0; use_interval = true; solvers = {'mosek' 'mosek_INTPNT_ONLY' 'sedumi' 'sdpt3'}; basis = 'CG_red'; slack = 'slack(z=x+t-1)'; slackcode = 3; %slack = 'slack(z=x-t)'; slackcode = 1; nout = 5; dist_A = low2high_dist('W-type', nout, use_interval, 0);%infea dist_B = low2high_dist('uniform', nout, use_interval, 0);%fea %dist_A = [];dist_B = []; %start_point = 0.035; %stop_point = 0.045; %start_point = 0.05276; %stop_point = 0.05277; %start_point = 0.3333333; %stop_point = 0.33333336; start_point = 0.065;stop_point = 0.075; %start_point = 0.0573;stop_point = 0.05732;%nout4 %start_point = 0.057352;stop_point = 0.057353;%nout3 steps = 10; %% I/O dt = datestr(datetime('now'), 'mmm-dd-yyyy_HH.MM'); results_path = sprintf('results/slack%d_%s_%s.mat', slackcode, basis, dt); data = struct(); data.start_point = start_point; data.stop_point = stop_point; data.steps = steps; data.nout = nout; data.basis = basis; data.slack = slack; %% Trials for solver = solvers lbs =calc_lbound(nout, dist_A, dist_B, solver{1}, basis, slack, start_point, stop_point, steps, verbose, use_interval); if slackcode == 3 data.([solver{1} '_lbs']) = lbs - 1; else data.([solver{1} '_lbs']) = lbs; end end save(results_path, 'data'); %% Call plotting function lb_plot(results_path);
function [ numfluxSolver, surfluxSolver, volumefluxSolver ] = initFluxSolver( obj ) %INITNUMFLUXSOLVER Summary of this function goes here % Detailed explanation goes here if obj.option.isKey('NumFluxType') if obj.option.isKey('nonhydrostaticType') if obj.getOption('NumFluxType') == enumSWENumFlux.HLL &&... obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic % Numerical flux type pointed and non-hydrostatic type pointed numfluxSolver = SWEHLLNumFluxSolver1d( ); surfluxSolver = SWEFaceFluxSolver1d( ); % LF and Roe flux to be added elseif obj.getOption('NumFluxType') == enumSWENumFlux.HLL &&... obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Nonhydrostatic numfluxSolver = SWENonhydroHLLNumFluxSolver1d( ); surfluxSolver = SWENonhydroFaceFluxSolver1d( ); % LF and Roe flux to be added end else % No nonhydrostatic type pointed, and hydrostatic by default if obj.getOption('NumFluxType') == enumSWENumFlux.HLL numfluxSolver = SWEHLLNumFluxSolver1d( ); surfluxSolver = SWEFaceFluxSolver1d( ); % LF and Roe flux to be added end end else % No numerical flux type pointed if obj.option.isKey('nonhydrostaticType') if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic numfluxSolver = SWEHLLNumFluxSolver1d( ); surfluxSolver = SWEFaceFluxSolver1d( ); elseif obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Nonhydrostatic numfluxSolver = SWENonhydroHLLNumFluxSolver1d( ); surfluxSolver = SWENonhydroFaceFluxSolver1d( ); end else % No nonhydrostatic type pointed, and hydrostatic by default numfluxSolver = SWEHLLNumFluxSolver1d( ); surfluxSolver = SWEFaceFluxSolver1d( ); end end parent = metaclass(obj); if strcmp(parent.SuperclassList.Name, 'SWEConventional1d') if obj.option.isKey('nonhydrostaticType') if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic volumefluxSolver = SWEVolumeFluxSolver1d(); else volumefluxSolver = SWENonhydroVolumeFluxSolver1d(); end else volumefluxSolver = SWEVolumeFluxSolver1d(); end elseif strcmp(parent.SuperclassList.Name, 'SWEPreBlanaced1d') % SWEPreBlanaced1d if obj.option.isKey('nonhydrostaticType') if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic volumefluxSolver = SWEPrebalanceVolumeFlux1d(); else volumefluxSolver = SWENonhydroPrebalanceVolumeFluxSolver1d(); end else volumefluxSolver = SWEPrebalanceVolumeFlux1d(); end elseif strcmp(parent.SuperclassList.Name, 'SWEWD1d') if obj.option.isKey('nonhydrostaticType') if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic volumefluxSolver = SWEWDVolumeFlux1d(); else volumefluxSolver = SWENonhydroWDVolumeFluxSolver1d(); end else volumefluxSolver = SWEWDVolumeFlux1d(); end end end
function [ vwillr ] = percentr( vtime,vhigh,vlow,vclose,len ) %PERCENTR 计算willr,根据mc % version 1.0 , luhuaibao, 2013.9.27 [~,id] = sort( -vtime ); % 最近的排在上面 vhigh = vhigh(id); vlow = vlow(id); vclose = vclose(id); var0 = max( vhigh(1:len ) ); var1 = var0 - min( vlow(1:len) ) ; if var1 ~= 0 vwillr = 100 - ( ( var0 - vclose(1) ) / var1 ) * 100 ; else vwillr = 0 ; end end
clear, clc xrng = [100 1000]; yrng = [-350 350]; xdiv = 40; ydiv = 40; % number of x/y divisions hbins = linspace(xrng(1), xrng(2), xdiv); vbins = linspace(yrng(1), yrng(2), xdiv); frmat = zeros(xdiv, ydiv); frtrls = zeros(xdiv, ydiv); targetdir = 'C:\Users\Hrishikesh\Data\krPTBData\'; [filename pathname] = uigetfile([targetdir 'S3*.mat'], 'Load Exp Session File (not sp2)', 'MultiSelect', 'on'); fullpathname = strcat(pathname, filename); % all the files in pathname %% Because I want to combine files and build up the firing rate plots if iscell(fullpathname) numfiles = length(fullpathname); else numfiles = 1; end hasPrintedOnce = false; allwindow = 0.02:0.01:0.2; for wi = 1:length(allwindow) % time back window = allwindow(wi); for dt = 1:numfiles if iscell(fullpathname) thisfilename = fullpathname{dt}; rawname = filename{dt}; else thisfilename = fullpathname; rawname = filename; end % first load the session file load(thisfilename) % this has the locs and successes load(strcat(thisfilename(1:end-4), '_sp2.mat')) eval(['eyeh = ' rawname(1:end-4) '_Ch3.values;']) eval(['eyev = ' rawname(1:end-4) '_Ch4.values;']) eval(['trig = ' rawname(1:end-4) '_Ch5.values;']) eval(['trigTS = ' rawname(1:end-4) '_Ch5.times;']) eval(['photo = ' rawname(1:end-4) '_Ch6.values;']) eval(['photoTS = ' rawname(1:end-4) '_Ch6.times;']) eval(['Allspktimes = ' rawname(1:end-4) '_Ch7.times;']) eval(['spkcodes = ' rawname(1:end-4) '_Ch7.codes;']) eval(['eyeSamplingRate = ' rawname(1:end-4) '_Ch3.interval;']) numIdx1sec = round(1/eyeSamplingRate); %numIdxLittlePost = round(0.5/eyeSamplingRate); clus = 1; spktimes = Allspktimes(spkcodes(:,1) == clus); %seconds if ~hasPrintedOnce, fprintf('Num Clusters: %i, Cluster Plotted: %i \n', length(unique(spkcodes(:,1))), clus), end %% Get data (bookkeeping) % smooth out the photocell idxPhoto = photo > 0.05; photo(idxPhoto) = 0.3; photo(~idxPhoto) = 0; dphoto = diff(photo); dphoto = [0; dphoto]; % to take care of the indexing issue idxOn = find(dphoto == 0.3); % photocell on idxOff = find(dphoto == -0.3); % note, the first one will be due to the PTB syncing routine idxOn(1) = []; idxOff(1) = []; % - also importantly, note that the times that the photo is on/off % photoTS(idxOn(i)) or photoTS(idxOff(i)) % smooth out triggers idxTrig = trig > 0.1; trig(idxTrig) = 0.5; trig(~idxTrig) = 0; dTrig = diff(trig); dTrig = [0; dTrig]; idxTstart = find(dTrig == 0.5); idxTstop = find(dTrig == -0.5); %% just find when the flashes happened in the "storeSuccess" lists timeFlashesStarts = []; timeFlashesEnds = []; nonzeroidx = find(storeSuccess); for ti = 1:length(find(storeSuccess)) trl = storeSuccess(nonzeroidx(ti)); thisIndFlashes = find(idxOn > idxTstart(trl) & idxOn < idxTstop(trl)); thisNumFlashes = length(thisIndFlashes); if thisNumFlashes == 5 tflashes = nan(10,1); tflashes([1,3,5,7,9]) = photoTS(idxOn(thisIndFlashes)); tflashes([2,4,6,8,10]) = photoTS(idxOff(thisIndFlashes)); timeFlashesStarts(end+1:end+10,1) = tflashes; tflashes = nan(10,1); tflashes([1,3,5,7,9]) = photoTS(idxOff(thisIndFlashes)); tflashes([2,4,6,8]) = photoTS(idxOn(thisIndFlashes(2:end))); tflashes(10) = tflashes(9)+nanmean(diff(tflashes)); timeFlashesEnds(end+1:end+10,1) = tflashes; else fprintf('Possible Error with Trial: %i. Num flashes = %i. \n', trl, thisNumFlashes) storeSuccess(ti) = 0; end end if ~hasPrintedOnce, fprintf('Num Flashes Detected: %i. Num storeXlocs: %i. \n', length(timeFlashesStarts), length(storeXlocs)); hasPrintedOnce = true; end %% find every spike and determine what the frame was some time before it % screen resolution 1024x768 ycent = 384; % the yaxis is flipped storeYlocs = -(storeYlocs - ycent); numavgs = 1; for spi = 1:length(spktimes) thisspiketime = spktimes(spi) - window; idxFS = find(timeFlashesStarts < thisspiketime, 1, 'last'); if ~isempty(idxFS) && timeFlashesStarts(idxFS) < thisspiketime && timeFlashesEnds(idxFS) > thisspiketime frmat = frmat.*numavgs; for nf = 1:size(storeXlocs,2) % find out which row/col it goes into and add the appropriate value row = find(hbins > storeXlocs(idxFS,nf), 1, 'first'); col = find(vbins > storeYlocs(idxFS,nf), 1, 'first'); % add 1 to the location of where the stimulus was frmat(row,col) = frmat(row,col) + 1; end% nf % recompute average numavgs = numavgs + 1; frmat = frmat./numavgs; end end end clf, hold on figure(1), heatmap(frmat'); % the data is averaged on the go axis([0.5 xdiv 0.5 ydiv]) title(['Time Back: ' num2str(allwindow(wi))]) colorbar ax = axis; line(ax(1:2),[mean(ax(3:4)) mean(ax(3:4))], 'LineStyle', '--','LineWidth', 2, 'Color', 'k') line([mean(ax(1:2)) mean(ax(1:2))], ax(3:4), 'LineStyle', '--','LineWidth', 2, 'Color', 'k') drawnow end
% Extract pixel pairs from both HSI and RGB images manually and let the % algorithm to pick up some random pixels for manifold alignment. if ~exist('hsiToRgbManifoldDatasetGen', 'var') hsiToRgbManifoldDatasetGen = false; end if hsiToRgbManifoldDatasetGen fb_HSI_Image = RotateHsiImage(hsiCubeData.DataCube, -90); rgbFromHsi = ConstructRgbImage(fb_HSI_Image, 2, 3, 4); else fb_HSI_Image = RotateHsiImage(reflectanceCube.DataCube, -90); rgbFromHsi = GetTriBandRgbImage(fb_HSI_Image); end classesInHsi = 7; noOfSample = 10; % Positions in [height, width] format. extractedHsiPixels = zeros(noOfSample * classesInHsi, 2); extractedHsiVector = zeros(noOfSample, 2); extractedRgbPixels = zeros(noOfSample * classesInHsi, 2); extractedRgbVector = zeros(noOfSample, 2); for nId = 1: classesInHsi [topLeft, btmRight] = PickUpPixelArea(rgbFromHsi); H = (btmRight(1) - topLeft(1)); W = (btmRight(2) - topLeft(2)); totalSamples = H * W; coordList = zeros(totalSamples, 2); for nX = 1:H for nY = 1:W coordList(((nX - 1) * W) + nY, :) = [(topLeft(1) - 1) + nX, (topLeft(2) - 1) + nY]; end end % Randomize the data and pick n number of samples. randIds = randperm(totalSamples); for px = 1: noOfSample extractedHsiVector(px, :) = coordList(randIds(px), :); end extractedHsiPixels((((nId - 1) * noOfSample) + 1): (((nId - 1) * noOfSample) + noOfSample), :) = extractedHsiVector(:,:); % end %% RGB % Positions in [height, width] format. % for nId = 1: classesInHsi [topLeft, btmRight] = PickUpPixelArea(higResRgb); H = (btmRight(1) - topLeft(1)); W = (btmRight(2) - topLeft(2)); totalSamples = H * W; coordList = zeros(totalSamples, 2); for nX = 1:H for nY = 1:W coordList(((nX - 1) * W) + nY, :) = [(topLeft(1) - 1) + nX, (topLeft(2) - 1) + nY]; end end % Randomize the data and pick n number of samples. randIds = randperm(totalSamples); for px = 1: noOfSample extractedRgbVector(px, :) = coordList(randIds(px), :); end extractedRgbPixels((((nId - 1) * noOfSample) + 1): (((nId - 1) * noOfSample) + noOfSample), :) = extractedRgbVector(:,:); close all; end %% Clear variables vars = {'noOfSample', 'nId', 'btmRight', 'classesInHsi', 'coordList',... 'randIds', 'px', 'nX', 'nY', 'H', 'W', 'topLeft', 'totalSamples'}; clear(vars{:});
function [ out ] = nonan_Image( img ) out = zeros(size(img)); for k=1:size(img,3) for i=1:size(img,1) for j=1:size(img,2) if ( isnan(img(i,j,k))) out(i,j,k)=0; else out(i,j,k) = img(i,j,k); end end end end end
function RunBatNew( filename ) %RUNBAT runs a batch file via Windows start menu using Java Robot class %Input: % <filename> batch file (.bat) %CL % Get Windows version winvers = system_dependent('getos'); % Create java robot to generate native system input events import java.awt.Robot; import java.awt.event.*; robot = Robot(); % Open the windows start menu % scrnsize = get(0,'screensize'); % robot.mouseMove(0,scrnsize(4)); % robot.mousePress(InputEvent.BUTTON1_MASK); % robot.mouseRelease(InputEvent.BUTTON1_MASK); % Open Win+R (Run) window instead robot.keyPress(KeyEvent.VK_WINDOWS) robot.keyPress(KeyEvent.VK_R) robot.keyRelease(KeyEvent.VK_WINDOWS) % Execute the batch file by typing the filename if ~isempty(strfind(winvers,'10')) % For Windows 10, batch execution via 'run' pause(1) lang = get(0,'Language'); if strcmp('de',lang(1:2)) typestr('Ausführen') else typestr('run') end robot.keyPress(KeyEvent.VK_ENTER) pause(1) % Type filename typestr(filename) robot.keyPress(KeyEvent.VK_ENTER) else % For Windows 7 and 8, batch execution via 'search' typestr(filename) robot.keyPress(KeyEvent.VK_ENTER) end end function typestr( str ) %TYPESTRING types a given string on the keyboard using the java robot % Create java robot to generate native system input events import java.awt.Robot; import java.awt.event.*; robot = Robot(); pause(0.1) for i = 1:length(str) c = str(i); if isstrprop(c,'punct') % Punctuation character switch c case '-' robot.keyPress(KeyEvent.VK_MINUS) case '.' robot.keyPress(KeyEvent.VK_PERIOD) case ':' robot.keyPress(KeyEvent.VK_SHIFT) robot.keyPress(KeyEvent.VK_PERIOD) robot.keyRelease(KeyEvent.VK_SHIFT) case '\' % ASCII value robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_NUMPAD9); robot.keyPress(KeyEvent.VK_NUMPAD2); robot.keyRelease(KeyEvent.VK_ALT); end elseif isstrprop(c,'wspace') % Space robot.keyPress(KeyEvent.VK_SPACE); elseif isstrprop(c,'digit') % Number eval(strcat('robot.keyPress(KeyEvent.VK_NUMPAD',c,')')); elseif strcmp(c,'ü') robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_NUMPAD1); robot.keyPress(KeyEvent.VK_NUMPAD5); robot.keyPress(KeyEvent.VK_NUMPAD4); robot.keyRelease(KeyEvent.VK_ALT); elseif strcmp(c,'ö') robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_NUMPAD1); robot.keyPress(KeyEvent.VK_NUMPAD5); robot.keyPress(KeyEvent.VK_NUMPAD3); robot.keyRelease(KeyEvent.VK_ALT); elseif strcmp(c,'ä') robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_NUMPAD1); robot.keyPress(KeyEvent.VK_NUMPAD4); robot.keyPress(KeyEvent.VK_NUMPAD2); robot.keyRelease(KeyEvent.VK_ALT); else c = upper(c); % Upper case character eval(strcat('robot.keyPress(KeyEvent.VK_',c,')')); end pause(0.01) end end
clear ; %clears all the variables close all; %closes extra windows clc %clears the screen % =============================================================== Part 1: K MEANS ====================================================== % ----------------------------------------------------------(a)---------------------------------------------------------------- X = load('attr.txt'); y = load('label.txt'); [m n] = size(X); K = 6; %no. of clusters tic idx = randperm(m, K); %generates unique K random integers between 1 to m inclusive. final_cost = k_means(X, K, idx) toc % ----------------------------------------------------------(b)---------------------------------------------------------------- tic J = zeros(10,1); min_cost_idx = zeros(1,K); min_cost = inf; for i = 1 : 10 i idx = randperm(m, K); J(i) = k_means(X, K, idx) if(J(i) < min_cost) min_cost = J(i); min_cost_idx = idx; end end J min_cost toc mu = X(min_cost_idx,:); %taking K random examples as the initial mu J = zeros(60,1); tic for i = 1 : 60 c = best_cluster(X, K, mu); %Expectation Step mu = update_means(X, K, c); %Minimization Step J(i) = computeErrorMetric(X, c, mu); %finding the cost end toc x = [1:60]; figure; plot(x, J, '-', 'LineWidth', 0.7) ylabel('Error'); % Set the y axis label xlabel('No. of iterations'); % Set the x axis label % ----------------------------------------------------------(c)---------------------------------------------------------------- mu = X(min_cost_idx,:); accuracy_vector = zeros(60,1); c_tmp = zeros(m, 1); for iter = 1 : 60 c = best_cluster(X, K, mu); %Expectation Step mu = update_means(X, K, c); %Minimization Step for i = 1 : K idx = find(c == i); c_tmp(idx) = mode(y(idx)); end accuracy_vector(iter) = length(find(c_tmp == y)) * 100 / m ; end figure; plot(x, accuracy_vector, '-', 'LineWidth', 0.7) ylabel('Accuracy'); % Set the y axis label xlabel('No. of iterations'); % Set the x axis label
function [ X, interactionX ] = createAgeGenderSizeRegressionMatrix(groupVector,polynomialDims,varargin) numCovars=length(varargin); % Create a balanced groupVector positiveGroup=find(groupVector > 0); numPositive=length(positiveGroup); negativeGroup=find(groupVector < 0); numNegative=length(negativeGroup); groupVector(positiveGroup)=sum(groupVector(positiveGroup))/numPositive*(numPositive/numNegative); groupVector(negativeGroup)=sum(groupVector(negativeGroup))/numNegative*(numNegative/numPositive); % Create polynomial expansions of the base covariates for c=1:numCovars baseCovar=cell2mat(varargin(c)); subX(1,:)=baseCovar-mean(baseCovar); if polynomialDims(c)>1 for p=2:polynomialDims(c) polyX=subX(1,:).^p; polyX=polyX-mean(polyX); polyX=polyX/max(polyX); [~,~,stats]=glmfit(subX',polyX'); subX(p,:)=stats.resid; end end if c==1 X=subX; else X=[X;subX]; end clear subX end % Create a matrix to test for interactions interactionX=X*0; % Multiply main effect covariates by the group vector to % create the interaction terms for i=1:size(X,1) interactionX(i,:)=X(i,:).*groupVector'; end % Render the interaction terms orthogonal to the main effect for i=1:size(X,1) interaction=interactionX(i,:); mainEffect=X(i,:); [~,~,stats]=glmfit(mainEffect,interaction); interactionX(i,:)=stats.resid; end % detect any interaction terms that are all zeros and remove them goodColumns=ones(size(X,1),1); for i=1:size(X,1) if (max(interactionX(i,:))-min(interactionX(i,:)))<0.01 goodColumns(i)=0; end end interactionX=interactionX(find(goodColumns==1),:); gribble=1; end
function interactive_graph_gui % data showLabels = true; % flag to determine whether to show node labels prevIdx = []; % keeps track of 1st node clicked in creating edges selectIdx = []; % used to highlight node selected in listbox pts = zeros(0,2); % x/y coordinates of vertices adj = sparse([]); % sparse adjacency matrix (undirected) edd=sparse([]); MinXLim=0; MaxXLim=100; MinYLim=0; MaxYLim=100; % create GUI h = initGUI(); function h = initGUI() h.fig = figure('Name','Interactive Graph', 'Resize','off'); h.ax = axes('Parent',h.fig, 'ButtonDownFcn',@onMouseDown, ... 'XLim',[MinXLim MaxXLim], 'YLim',[MinYLim MaxYLim], 'XTick',[], 'YTick',[], 'Box','on', ... 'Units','pixels', 'Position',[160 20 380 380]); h.list = uicontrol('Style','listbox', 'Parent',h.fig, 'String',{}, ... 'Min',1, 'Max',1, 'Value',1, ... 'Position',[20 80 130 320], 'Callback',@onSelect); uicontrol('Style','pushbutton', 'Parent',h.fig, 'String','Clear', ... 'Position',[20 20 60 20], 'Callback',@onClear); uicontrol('Style','pushbutton', 'Parent',h.fig, 'String','Export', ... 'Position',[90 20 60 20], 'Callback',@onExport); uicontrol('Style','pushbutton', 'Parent',h.fig, 'String','Delete', ... 'Position',[50 50 60 20], 'Callback',@onDelete); h.cmenu = uicontextmenu('Parent',h.fig); h.menu = uimenu(h.cmenu, 'Label','Show labels', 'Checked','off', ... 'Callback',@onCMenu); set(h.list, 'UIContextMenu',h.cmenu) h.pts = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ... 'Marker','o', 'MarkerSize',10, 'MarkerFaceColor','b', ... 'LineStyle','none'); h.selected = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ... 'Marker','o', 'MarkerSize',10, 'MarkerFaceColor','y', ... 'LineStyle','none'); h.prev = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ... 'Marker','o', 'MarkerSize',20, 'Color','r', ... 'LineStyle','none', 'LineWidth',2); h.edges = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ... 'LineWidth',2, 'Color','g'); h.txt1 = []; h.txt2 = []; end function onMouseDown(~,~) % get location of mouse click (in data coordinates) p = get(h.ax, 'CurrentPoint'); % determine whether normal left click was used or otherwise if strcmpi(get(h.fig,'SelectionType'), 'Normal') % add a new node pts(end+1,:) = p(1,1:2); adj(end+1,end+1) = 0; else % add a new edge (requires at least 2 nodes) if size(pts,1) < 2, return; end % hit test (find node closest to click location: euclidean distnce) [dst,idx] = min(sum(bsxfun(@minus, pts, p(1,1:2)).^2,2)); % if sqrt(dst) > 0.025, return; end if isempty(prevIdx) % starting node (requires a second click to finish) prevIdx = idx; else % add the new edge adj(prevIdx,idx) =sqrt(((pts(prevIdx,1)-pts(idx,1))^2)+((pts(prevIdx,2)-pts(idx,2))^2)); prevIdx = []; end end % update GUI selectIdx = []; redraw() end function onDelete(~,~) % check that list of nodes is not empty if isempty(pts), return; end % delete selected node idx = get(h.list, 'Value'); pts(idx,:) = []; adj(:,idx) = []; adj(idx,:) = []; % clear previous selections if prevIdx == idx prevIdx = []; end selectIdx = []; % update GUI set(h.list, 'Value',max(min(idx,size(pts,1)),1)) redraw() end function onClear(~,~) % reset everything prevIdx = []; selectIdx = []; pts = zeros(0,2); adj = sparse([]); % update GUI set(h.list, 'Value',1) redraw() end function onExport(~,~) % export nodes and adjacency matrix to base workspace assignin('base', 'adj',adj+adj') % make it symmetric assignin('base', 'xy',pts) end function onSelect(~,~) % update index of currently selected node selectIdx = get(h.list, 'Value'); redraw() end function onCMenu(~,~) % flip state showLabels = ~showLabels; redraw() end function redraw() % edges p = nan(3*nnz(adj),2); [i,j] = find(adj); p(1:3:end,:) = pts(i,:); p(2:3:end,:) = pts(j,:); set(h.edges, 'XData',p(:,1), 'YData',p(:,2)) % nodes set(h.pts, 'XData',pts(:,1), 'YData',pts(:,2)) set(h.prev, 'XData',pts(prevIdx,1), 'YData',pts(prevIdx,2)) set(h.selected, 'XData',pts(selectIdx,1), 'YData',pts(selectIdx,2)) % list of nodes set(h.list, 'String',num2str(pts,'(%.3f,%.3f)')) % node labels if ishghandle(h.txt1) delete(h.txt1); end if ishghandle(h.txt2) delete(h.txt2); end if showLabels set(h.menu, 'Checked','on') h.txt1 = text(pts(:,1)+0.01, pts(:,2)+0.01, ... num2str((1:size(pts,1))'), ... 'HitTest','off', 'FontSize',8, ... 'VerticalAlign','bottom', 'HorizontalAlign','left'); else set(h.menu, 'Checked','off') end if ~isempty(find(adj, 1)) [xi,yi,val]=find(adj); h.txt2 = text((pts(xi,1)+pts(yi,1))/2, (pts(xi,2)+pts(yi,2))/2, ... num2str( val), ... 'HitTest','off', 'FontSize',8, ... 'VerticalAlign','bottom', 'HorizontalAlign','left'); end % force refresh drawnow end end
clear; close all; clc; %% Threshhold, Adaptive Equal % I = imread('fingerprint.png'); % I = double(I); % fingim = otsu(I); % figure('Name','Adaptive Equalization, Fingerprint'); % subplot(1,3,1);imagesc(I); title('Original Image'); % subplot(1,3,2);imagesc(fingim); colormap gray; title('Otsu Threshold'); % adt = AdaptiveEqualize(I); % otAdt = otsu(adt); % subplot(1,3,3); imagesc(otAdt);colormap gray; title('Otsu after Adaptive Equalizatoin'); % %% Gaussain and Bilateral % part a,b,c,d I = imread('lena.png'); I = double(I); subplot(2,3,1);imagesc(I); colormap gray; title('Original Im'); G = GaussianFilter(I,1); subplot(2,3,2);imagesc(G); colormap gray; title('GaussianFltr sigma = 3'); B = BilateralFilter(I,3,10); subplot(2,3,3);imagesc(B); colormap gray; title('BilateralFltr sd = 3 sr = 10'); dG = abs(I-G); subplot(2,3,5);imagesc(dG); colormap gray; title('Original-Gaussian'); dB = abs(I-B); sumdb = sum(sum(dB)); subplot(2,3,6); imagesc(dB); colormap gray;title('Original-Bilateral'); %% Part e I = imread('lena.png'); I = double(I); figure(); subplot(1,3,1);imagesc(I); colormap gray; title('Original Im'); B = BilateralFilter(I,3,100); subplot(1,3,2);imagesc(B); colormap gray; title('BilateralFltr sd = 3 sr = 100'); dB = abs(I-B); sumdb = sum(sum(dB)); subplot(1,3,3); imagesc(dB); colormap gray;title('Original-Bilateral'); %% part f and g % I = imread('lena.png'); % I = double(I); % figure(); % subplot(1,3,1);imagesc(I); colormap gray; title('Original Im'); % % B = BilateralFilter(I,1000,10); % subplot(1,3,2);imagesc(B); colormap gray; title('BilateralFltr sd = 1000 sr = 10'); % % B = BilateralFilter(I,3,1000); % subplot(1,3,3);imagesc(B); colormap gray; title('BilateralFltr sd = 3 sr = 1000'); %% House.png % f = imread('house.png'); % f = double(f); % g = f+20*randn(size(f)); % % G = GaussianFilter(f,1); % mn = size(f,1)*size(f,2); % MSEf = sum(sum(minus(f,G).^2))/mn; % MSEg = sum(sum(minus(f,g).^2))/mn; % mseNoise = sprintf('Noise; MSE = %f',MSEg); % mseFilter = sprintf('GaussianFlter sgm =3; MSE = %f',MSEf); % % subplot(1,3,1);imagesc(f); colormap gray; title('Original'); % subplot(1,3,2);imagesc(g); colormap gray; title(mseNoise); % subplot(1,3,3);imagesc(G); colormap gray; title(mseFilter); % % figure(); % mse = [0,0,0,0,0,0]; % x = [5,10,20,40,60,100]; % B1 = BilateralFilter(g,3,5); % mse(1) = 1./mn.*sum(sum(minus(f,B1).^2)); % mseFilter1 = sprintf('sgm =5; MSE = %f',mse(1)); % subplot(3,2,1);imagesc(B1); colormap gray;title(mseFilter1); % % B2 = BilateralFilter(g,3,10); % mse(2) = 1./mn.*sum(sum(minus(f,B2).^2)); % mseFilter2 = sprintf('sgm =10; MSE = %f',mse(2)); % subplot(3,2,2);imagesc(B2); colormap gray;title(mseFilter2); % % B3 = BilateralFilter(g,3,20); % mse(3) = 1./mn.*sum(sum(minus(f,B3).^2)); % mseFilter3 = sprintf('sgm =20; MSE = %f',mse(3)); % subplot(3,2,3);imagesc(B3); colormap gray;title(mseFilter3); % % B4 = BilateralFilter(g,3,40); % mse(4) = 1./mn.*sum(sum(minus(f,B4).^2)); % mseFilter4 = sprintf('sgm =40; MSE = %f',mse(4)); % subplot(3,2,4);imagesc(B4); colormap gray;title(mseFilter4); % % B5 = BilateralFilter(g,3,60); % mse(5) = 1./mn.*sum(sum(minus(f,B5).^2)); % mseFilter5 = sprintf('sgm =60; MSE = %f',mse(5)); % subplot(3,2,5);imagesc(B5); colormap gray;title(mseFilter5); % % B6 = BilateralFilter(g,3,100); % mse(6) = 1./mn.*sum(sum(minus(f,B6).^2)); % mseFilter6 = sprintf('sgm =100; MSE = %f',mse(6)); % subplot(3,2,6);imagesc(B6); colormap gray;title(mseFilter6); % % figure();plot(x,mse);
%time_score driver % sets paths to kml files and a wrfout, then runs the time_score function kml_path = '/bigdisk/james.haley/wrfcycling/wrf-fire/wrfv2_fire/test/TIFs/doc.kml'; wrfout_path = '/bigdisk/james.haley/wrfcycling/wrf-fire/wrfv2_fire/test/cycling_best_ig_single/wrfout_d01_2013-08-13_00:00:00'; time_score(kml_path,wrfout_path)
function d = mismatch( h1, h2 ) % MISMATCH computes the mismatch distance between the two histograms d = sum ( h1 ~= h2 ); end
clear clc close all A = tf([1.3],[1,1.3]) G = tf([1],[.00303,0,0]) H = tf([1000],[1,1000]) GOL = A*G*H; bode(GOL) margin(GOL) figure() rlocus(GOL) C1 = tf([1,1],[1,650]) C2 = tf([1,5],[1,300]) C = C1*C2; CGOL = C*GOL bode(CGOL) margin(CGOL) figure() rlocus(CGOL) K = 5; GCL = K*CGOL/(1+K*CGOL); figure() step(GCL) figure() pzmap(GCL)
function mtlscale(infile, outfile, factor) %function mtlscale(infile, outfile, factor) [file_type,info_blocks,n_channels,n_lines, sampling_rate,... first_line,last_line,n_directions,comment1, comment2] = mtlrh(infile) if (file_type ~= 2) error('Wrong filetype'); return; end; if (nargin < 3) factor=1; end; index=0; %if direction_matrix if ((info_blocks-2) > 0) direction_matrix=mtlrdir(infile,n_directions); if (index ~= 0) direction_matrix(:) = direction_matrix(:,index); end; % if time_delay exists read time_delay if (( (info_blocks-2)*256 - n_directions*8) == (n_channels*4)) [delay_l,delay_r]=mtlrdel(infile,n_directions,binaural); if (index ~= 0) delay_l = delay_l(index); if (binaural == 1) delay_r = delay_r(index); end; end; end; end; % write output_header mtlwh(outfile,file_type,info_blocks,n_channels,n_lines, sampling_rate,... first_line,last_line,n_directions,... comment1, comment2); % write directions; % write delays; if ((n_channels/n_directions) == 2) binaural=1; end; n_dir=n_directions; if (n_dir > 0) n_byte=n_dir*2*4; sn_del=length(delay_l); if (sn_del > 0) n_byte=n_byte+n_dir*4*(binaural+1); end; n_blocks=ceil(n_byte/256); end; info_blocks=2+n_blocks; comment1 = [comment1 '; after scaling']; mtlwh(outfile,file_type,info_blocks,n_channels,n_lines, sampling_rate,... first_line,last_line,n_directions,... comment1, comment2); [fid,message] = fopen(outfile,'a','ieee-le'); if fid==-1 % file can't be opened disp(message); return; end; if ((n_blocks) > 0) fseek(fid,512,'bof'); fwrite(fid,zeros(n_blocks*256,1),'float32'); fclose(fid); end %if direction_matrix if ((n_blocks) > 0) status=mtlwdir(outfile,direction_matrix) if(length(delay_l) > 0) mtlwdel(outfile, delay_l,delay_r); end; end for n=1:n_channels clc disp(['MTLSCALE: channel ', num2str(n), ' of ', num2str(n_channels)] ); channel=mtlrch(infile,n); status = mtlwch(outfile,channel*factor,n) end; fclose(fid);
function result = xcat(dim,varargin) % Array concatenation with singleton expansion. % Author: Vladimir Golkov if ~isscalar(dim) && ~isempty(dim) % dim not provided, first argument is array varargin(2:end+1) = varargin; % TODO is this fast? varargin{1} = dim; end sizelist = []; for i=1:numel(varargin) siz = size(varargin{i}); sizelist(:,end+1 : numel(siz)) = 1; % in case ndims(varargin{i}) is larger than largest previous ndims sizelist(i,1:numel(siz)) = siz; sizelist(i,numel(siz)+1 : end) = 1; % in case ndims(varargin{i}) is smaller than largest previous ndims end if isempty(dim) dim = size(sizelist,2)+1; % determine dim automatically: choose next higher dimension end sizelist(:,end+1 : dim) = 1; % in case every ndims(varargin{i}) is smaller than concatenation dimension resultsize = max(sizelist,[],1); resultsize(dim) = sum(sizelist(:,dim)); e_dim = false(1,size(resultsize,2)); e_dim(dim) = true; % disregard concatenation dimension when checking dimension consistency if ~all(all(bsxfun(@eq,sizelist,resultsize) | sizelist==1) | e_dim) error('xcat:InsonsistentDimensions','Inconsistent dimensions. For each dimension, array sizes must either match or be equal to one.'); end for i=1:numel(varargin) newsize = resultsize./sizelist(i,:); newsize(dim) = 1; % don't repeat along concatenation dimension varargin{i} = repmat(varargin{i},newsize); % TODO alternative to save working memory: in each loop iteration, do repmat, cat, discard end % prevent "Error using cat: Dimension for sparse matrix concatenation must be <= 2." if dim>2 && any(cellfun(@issparse,varargin)) warning('Converting sparse to full...') varargin = full(varargin); % this uses @cell/full.m end result = cat(dim,varargin{:});
function [T] = makebins(Set,Y,bins) % MAKEBINS divides a given data set into cell bins % -Set is the Data set (usually consisting of alignment identity score % values and their respective sequences % -Y is the result of running MATLAB's discretize function on Set % -bins is the number of bins that the data will be divided into T=cell(bins,1); for i=1:size(Y,1) num=Y(i,1); elt=Set(i,:); T{num,1}=[T{num,1}; elt]; end end
% testing the stereo door corner camera addpath(genpath('../utils/pyr')); addpath(genpath('../corner_cam')); addpath(genpath('../stereo_cam')); close all; clear; npx = 80; width = npx/10; floornpx = 80; nsamples = 80; % door is centered at origin door_corner1 = [-1 0 0]; door_corner2 = [1 0 0]; door_width = abs(door_corner2(1) - door_corner1(1)); % we look at the shadow at the two corners of the door xlocs1 = linspace(door_corner1(1), door_corner1(1)-1, floornpx); xlocs2 = linspace(door_corner2(1), door_corner2(1)+1, floornpx); ylocs = linspace(0, 1, floornpx); % images behind the door imdepths = [-5, -7]; imstarts = [2*width, 7*width]; nims = length(imstarts); imgs = zeros([npx, npx, nims]); scenex = linspace(door_corner1(1), door_corner2(1), npx); sceneys = zeros([nims, npx]); scenez = linspace(0, door_corner2(1), npx); gt_depths = zeros(size(scenex)); obs1 = zeros([floornpx*floornpx, 1]); obs2 = zeros(size(obs1)); figure; for i = 1:nims start = imstarts(i); imgs(:,start:start+width,i) = 1; sceneys(i,:) = ones(size(scenex)) * imdepths(i); subplot(nims,1,i); imagesc(imgs(:,:,i)); axis off; title(sprintf('%d units depth', -imdepths(i))); gt_depths = gt_depths + abs(imgs(1,:,i) .* sceneys(i,:)); % get observations amat1 = cornerAmat(xlocs1, ylocs, scenex, sceneys(i,:)); obs1 = obs1 + amat1 * reshape(imgs(:,:,i), [npx*npx,1]); amat2 = cornerAmat(xlocs2, ylocs, scenex, sceneys(i,:)); obs2 = obs2 + amat2 * reshape(imgs(:,:,i), [npx*npx,1]); end sigma = 0.5; beta = 100; obs1_noisy = obs1 + sigma * randn(size(obs1)); obs2_noisy = obs2 + sigma * randn(size(obs1)); % plotting the shadow observations figure; subplot(211); imagesc(xlocs1, ylocs, reshape(obs1_noisy, [floornpx, floornpx])); subplot(212); imagesc(xlocs2, ylocs, reshape(obs2_noisy, [floornpx, floornpx])); % reconstructing a 1d picture from each door corner thetas1 = [pi, pi/2]; tdir1 = sign(thetas1(2) - thetas1(1)); [amat1_1d, ~, ~] = allPixelAmat(door_corner1, floornpx, nsamples, thetas1); angles1 = linspace(thetas1(1), thetas1(2), nsamples) + tdir1*pi; thetas2 = [0, pi/2]; tdir2 = sign(thetas2(2) - thetas2(1)); [amat2_1d, ~, ~] = allPixelAmat(door_corner2, floornpx, nsamples, thetas2); angles2 = linspace(thetas2(1), thetas2(2), nsamples) + tdir2*pi; % spatial prior bmat = eye(nsamples) - diag(ones([nsamples-1,1]), 1); x1_1d = (amat1_1d'*amat1_1d/sigma^2 + bmat'*bmat*beta)\(amat1_1d'*obs1_noisy/sigma^2); x2_1d = (amat2_1d'*amat2_1d/sigma^2 + bmat'*bmat*beta)\(amat2_1d'*obs2_noisy/sigma^2); % x1_1d(x1_1d<0) = 0; % x1_1d(x1_1d>1) = 1; % x2_1d(x2_1d<0) = 0; % x2_1d(x2_1d>1) = 1; x1_1d = (x1_1d - min(x1_1d))/(max(x1_1d) - min(x1_1d)); x2_1d = (x2_1d - min(x2_1d))/(max(x2_1d) - min(x2_1d)); figure; subplot(211); imagesc(angles1, 1:npx/2, repmat(x1_1d', [npx/2, 1])); subplot(212); imagesc(angles2, 1:npx/2, repmat(x2_1d', [npx/2, 1])); % estimate depth % need to flip one of them; reverse orientations x1_1d = x1_1d(end:-1:1); angles1 = angles1(end:-1:1); % for every window in x1_1d, we find the best matching window in x2_1d winsize = 2; energy = zeros(nsamples-winsize); for i = 1:nsamples-winsize win1 = x1_1d(i:i+winsize); for j = 1:nsamples-winsize win2 = x2_1d(j:j+winsize); % energy(i,j) = -sum((win2-mean(win2)).*(win1-mean(win1)))/(std(win1)*std(win2)); energy(i,j) = sum((win2-win1).^2); end end figure; imagesc(energy); title('energy between two reconstructions'); % the corresponding angles from the door corners, for each point % only positive angles for this calculation door_angle1 = abs(angles1(1:nsamples-winsize)); depths = zeros(size(door_angle1)); for i = 1:length(depths) row = energy(i,:); [val, idx] = min(row); secondbest = row(row > val); val2 = min(secondbest); if val/val2 > 0.6 % too close together, assume we're not resolving to an actual object depths(i) = 1e-2; else % take the angle of corner 2 of the best match a2 = angles2(idx) - tdir2*pi; a1 = door_angle1(i); depths(i) = cot(a1) + cot(a2); end end depths = abs(door_corner1(1) - door_corner2(1)) ./ depths; locs1 = cot(door_angle1) .* depths - 1; angle_ends = abs(angles1(1+winsize:nsamples)); locs2 = cot(angle_ends) .* depths - 1; % [minval, minidx] = min(energy, [], 2); % door_angle2 = angles2(minidx) - tdir2*pi; % for each point, compute depth % depths = abs(door_corner1(1) - door_corner2(1))./(cot(door_angle1) + cot(door_angle2)); figure; subplot(211); plot(locs1(depths < 200), depths(depths < 200), 'ro'); hold on; plot(locs2(depths < 200), depths(depths < 200), 'bo'); xlim([-1, 1]); title('preliminary depth estimation of each point'); subplot(212); plot(scenex(gt_depths > 0), gt_depths(gt_depths > 0), 'bo'); xlim([-1, 1]); title('ground truth depths');
function LoadGamma(CLUT) physicalDisplay = 1; Display.ScreenID = 0; [OriginalGammaTable, dacbits, reallutsize] = Screen('ReadNormalizedGammaTable', Display.ScreenID);%, physicalDisplay); save('OriginalSetup3CLUT.mat', 'OriginalGammaTable'); CLUT = 'NIH_Setup3_ASUS_V27.mat'; load(CLUT); AllScreens = Screen('Screens'); Stereomode = 4; Text.Size = 60; Eye = {'Left buffer (0)','Right buffer (1)'}; %================== IDENTIFY LEFT/RIGHT SCREENS AND BUFFERS =============== [win Rect] = Screen('OpenWindow',0, 128, [],[],[],Stereomode); for s = 1:2 Screen('SelectStereoDrawBuffer', win, s-1); % 0 = left eye buffer; 1 = right eye buffer Screen('TextSize', win, Text.Size); DrawFormattedText(win, Eye{s}, 'center', 'center', [0 0 0], []); Screen('LoadNormalizedGammaTable', AllScreens, inverseCLUT{s}); end Screen('Flip',win); KbWait; sca; %================================== LOAD CLUTS ============================ % for i=1:numel(Lum) % fprintf('CLUT %d for %s\n', i, Lum(i).DisplayName); % end % for Display = 1:2 % Screen('SelectStereoDrawBuffer', AllScreens, Display-1); % Screen('LoadNormalizedGammaTable', AllScreens, inverseCLUT{Display}); % Load the original gamma table % end
% min_angle = minAngle(angles_array, indices_of_min_energy) % This function extracts the angles corresponding to minima in energy; function min_angle = minAngle(energies, indices) min_angle = angles_array(indices_of_min_energy); end
close all clear all clc %% code_folder = '/Users/akira/Documents/GitHub/MN-Model/Test Size'; data_folder = '/Users/akira/Documents/GitHub/MN-Model/MN Parameter'; %% type = 'S'; %% model_folder = '/Users/akira/Documents/GitHub/Twitch-Based-Muscle-Model/Model Parameters/Model_8'; cd(model_folder) load('modelParameter') cd(code_folder) [val,loc] = min(modelParameter.U_th); testMN = loc; MDR_d = modelParameter.MDR(testMN); PDR_d = modelParameter.PDR(testMN); I_max = 100; I_th = 100*val; slope_target = (PDR_d-MDR_d)/(I_max-I_th); %% % find a template MN whose minimal discharge rate is closest to the target % minimal discharge rate cd(data_folder) load([type '_MDR']) cd(code_folder) [~,loc_min] = min(abs(MDR_d-MDR)); nMN = num2str(loc_min); cd(data_folder) load([type '_' nMN]) cd(code_folder) %% count = 1; perturbation_amp = 0.3; %% % Fit the sloe of the f-I relationship by adjusting parameter g_Ks for j = 1:5 j amp_vec = 0:1:100; mean_FR = zeros(1,length(amp_vec)); CoV_FR = zeros(1,length(amp_vec)); for i = 1:length(amp_vec) Fs = 10000; time = 0:1/Fs:5; noise_amp = 0; amp = amp_vec(i); input = zeros(1,length(time)); input(1*Fs+1:end) = amp; inputOpt = 1; pltOpt = 0; %% [binary,V_s,V_d] = Cisi2008_function(param,time,input,Fs,noise_amp,inputOpt,pltOpt); spike_time = find(binary(end-2*Fs+1:end)); ISI = diff(spike_time)/(Fs/1000); mean_FR(i) = mean(1./ISI*1000); CoV_FR(i) = std(1./ISI*1000)/mean_FR(i)*100; end %% index_t = find(~isnan(mean_FR)); amp_th = amp_vec(index_t(1)); min_DR = mean_FR(index_t(1)); p_fit = polyfit(amp_vec(index_t),mean_FR(index_t),1); y1 = polyval(p_fit,amp_vec(index_t)); error = slope_target - p_fit(1); if error > 0 param.g_Ks = param.g_Ks - (param.g_Ks*perturbation_amp)./2.^(count-2); else param.g_Ks = param.g_Ks + (param.g_Ks*perturbation_amp)./2.^(count-2); end count = count + 1; end %% % Fit the recruitment threshold by adjusting parameter I_r mean_FR = zeros(1,length(amp_vec)); CoV_FR = zeros(1,length(amp_vec)); perturbation_amp = 0.3; count = 1; for j = 1:5 j amp_vec = 0:0.1:50; mean_FR = zeros(1,length(amp_vec)); CoV_FR = zeros(1,length(amp_vec)); error = I_th - amp_th; if error > 0 param.I_r = param.I_r + (param.I_r*perturbation_amp)./2.^(count-2); else param.I_r = param.I_r - (param.I_r*perturbation_amp)./2.^(count-2); end for i = 1:length(amp_vec) Fs = 10000; time = 0:1/Fs:5; noise_amp = 0; amp = amp_vec(i); input = zeros(1,length(time)); input(1*Fs+1:end) = amp; inputOpt = 1; pltOpt = 0; [binary,V_s,V_d] = Cisi2008_function(param,time,input,Fs,noise_amp,inputOpt,pltOpt); spike_time = find(binary(end-2*Fs+1:end)); ISI = diff(spike_time)/(Fs/1000); mean_FR(i) = mean(1./ISI*1000); CoV_FR(i) = std(1./ISI*1000)/mean_FR(i)*100; end index_t = find(~isnan(mean_FR)); amp_th = amp_vec(index_t(1)); min_DR = mean_FR(index_t(1)); p_fit = polyfit(amp_vec(index_t),mean_FR(index_t),1); y1 = polyval(p_fit,amp_vec(index_t)); count = count + 1; end %% Plot the result amp_vec = 0:0.1:100; mean_FR = zeros(1,length(amp_vec)); CoV_FR = zeros(1,length(amp_vec)); for i = 1:length(amp_vec) Fs = 10000; time = 0:1/Fs:5; noise_amp = 0; amp = amp_vec(i); input = zeros(1,length(time)); input(1*Fs+1:end) = amp; inputOpt = 1; pltOpt = 0; [binary,V_s,V_d] = Cisi2008_function(param,time,input,Fs,noise_amp,inputOpt,pltOpt); spike_time = find(binary(end-2*Fs+1:end)); ISI = diff(spike_time)/(Fs/1000); mean_FR(i) = mean(1./ISI*1000); CoV_FR(i) = std(1./ISI*1000)/mean_FR(i)*100; end index_t = find(~isnan(mean_FR)); amp_th = amp_vec(index_t(1)); min_DR = mean_FR(index_t(1)); p_fit = polyfit(amp_vec(index_t),mean_FR(index_t),1); y1 = polyval(p_fit,amp_vec(index_t)); figure(1) plot(amp_vec,mean_FR,'LineWidth',2) hold on plot(amp_vec(index_t),y1,'--k','LineWidth',1) plot([min(amp_vec) max(amp_vec)],[MDR_d MDR_d],'--k','LineWidth',1) plot([min(amp_vec) max(amp_vec)],[PDR_d PDR_d],'--k','LineWidth',1) xlabel('Injected Current (nA)','FontSize',14) ylabel('Dischage Rate (Hz)','FontSize',14) set(gca,'TickDir','out'); set(gca,'box','off')
function z = polynomial_probs(data,n,resolution,lim) C = mean(data,1); R = max( vecnorm(data-C,2,2) ); P = @(L) max( 1 - (norm(L-C)/(3*R))^n, 0 ); X = linspace(-lim,lim,resolution); Y = X; [Xg,Yg] = meshgrid(X,Y); Z = zeros(size(Xg)); for i=1:resolution^2 xx = Xg(i); yy = Yg(i); Z(i) = P([xx yy]); end z = Z/sum(sum(Z)); end
% function m = Gaussian(n) clear; clc; close all; n = 10; m = zeros(ceil(6*n),ceil(6*n)); sigma = 3*n; % for i = 1:n % for j = 1:n % top = -(i^2+j^2)/(2*sigma^2) % m(i,j) = 1/(2*pi*sigma^2) * exp(top); % end % end io = floor(size(m,1)/2); jo = floor(size(m,2)/2); for i = 1:size(m,1) for j = 1:size(m,2) top = -((i-io)^2/(2*sigma^2)+(j-jo)^2/(2*sigma^2)); m(i,j) = 1/(2*pi*sigma^2) * exp(top); end end surf(m);
function [ output_args ] = StressPlot( Maps ) %STRESSPLOT Summary of this function goes here % Detailed explanation goes here figure % S11 = Maps.S12_F; % S12 = Maps.S12_F; % S13 = Maps.S13_F; % S22 = Maps.S22_F; % S23 = Maps.S23_F; % S33 = Maps.S33_F; S11 = Maps.crop.S{1,1}; S12 = Maps.crop.S{1,2}; S13 = Maps.crop.S{1,3}; S22 = Maps.crop.S{2,2}; S23 = Maps.crop.S{2,3}; S33 = Maps.crop.S{3,3}; W = Maps.crop.W; GNDs = Maps.crop.GNDs; % Remove extreme values from plot factor = 10; S11(abs(S11)>factor*nanmean(abs(S11(:)))) = NaN; S12(abs(S12)>factor*nanmean(abs(S12(:)))) = NaN; S13(abs(S13)>factor*nanmean(abs(S13(:)))) = NaN; S22(abs(S22)>factor*nanmean(abs(S22(:)))) = NaN; S23(abs(S23)>factor*nanmean(abs(S23(:)))) = NaN; S33(abs(S33)>factor*nanmean(abs(S33(:)))) = NaN; minA = min([min(min(S11)) min(min(S12)) min(min(S13)) min(min(S22)) min(min(S23)) min(min(S33))]); maxA = max([max(max(S11)) max(max(S12)) max(max(S13)) max(max(S22)) max(max(S23)) max(max(S33))]); clim = [minA maxA]; Xvec = Maps.crop.X; Yvec = Maps.crop.Y; colormap jet h1 = subplot(3,3,1); pcolor(Xvec,Yvec,S11);shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colorbar title('\fontsize{16}\sigma\fontsize{10}11') h2 = subplot(3,3,2); pcolor(Xvec,Yvec,S12);shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colorbar title('\fontsize{16}\sigma\fontsize{10}12') h3 = subplot(3,3,3); pcolor(Xvec,Yvec,S13);shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colorbar title('\fontsize{16}\sigma\fontsize{10}13') h4 = subplot(3,3,5); pcolor(Xvec,Yvec,S22);shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colorbar title('\fontsize{16}\sigma\fontsize{10}22') h5 = subplot(3,3,6); pcolor(Xvec,Yvec,S23);shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colorbar title('\fontsize{16}\sigma\fontsize{10}23') h6 = subplot(3,3,9); pcolor(Xvec,Yvec,S33);shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colorbar title('\fontsize{16}\sigma\fontsize{10}33') %should be close to zero h7 = subplot(3,3,4); pcolor(Xvec,Yvec,W);shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colorbar title('W') h8 = subplot(3,3,7); pcolor(Xvec,Yvec,GNDs); ;shading interp; set(gca,'Ydir','normal'); axis equal xlim([min(Xvec) max(Xvec)]) ylim([min(Yvec) max(Yvec)]) colormap(jet(256)); set(gcf,'position',[500,100,950,700]); set(gca,'ColorScale','log'); set(gca,'CLim',[10^13 10^15.5]); c = colorbar; c.Label.String = 'log';%labelling title('GNDs') set(gcf,'position',[800,80,1000,900]) % L = max([abs(minA) abs(maxA)]); % set([h1 h2 h3 h4 h5 h6],'clim',[-L L]); end
function T_new = transform_TFT(T_old,M1,M2,M3,inverse) % Tranformed TFT % % short function to transform the TFT when an algebraic transformation % has been aplied to the image points. % % if inverse==0 : % from a TFT T_old assossiated to P1_old, P2_old, P3_old, find the new TFT % T_new associated to P1_new=M1*P1_old, P2_new=M2*P2_old, P3_new=M3*P3_old. % if inverse==1 : % from a TFT T_old assossiated to P1_old, P2_old, P3 _old, find the new TFT % T_new associated to M1*P1_new=P1_old, M2*P2_new=P2_old, M3*P3_new=P3_old. % % Copyright (c) 2017 Laura F. Julia <laura.fernandez-julia@enpc.fr> % All rights reserved. % % 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<5 inverse=0; end if inverse==0 M1i=inv(M1); T_new=zeros(3,3,3); T_new(:,:,1)=M2*(M1i(1,1)*T_old(:,:,1) + M1i(2,1)*T_old(:,:,2) + M1i(3,1)*T_old(:,:,3) )*M3.'; T_new(:,:,2)=M2*(M1i(1,2)*T_old(:,:,1) + M1i(2,2)*T_old(:,:,2) + M1i(3,2)*T_old(:,:,3) )*M3.'; T_new(:,:,3)=M2*(M1i(1,3)*T_old(:,:,1) + M1i(2,3)*T_old(:,:,2) + M1i(3,3)*T_old(:,:,3) )*M3.'; elseif inverse==1 M2i=inv(M2); M3i=inv(M3); T_new=zeros(3,3,3); T_new(:,:,1)=M2i*(M1(1,1)*T_old(:,:,1) + M1(2,1)*T_old(:,:,2) + M1(3,1)*T_old(:,:,3) )*M3i.'; T_new(:,:,2)=M2i*(M1(1,2)*T_old(:,:,1) + M1(2,2)*T_old(:,:,2) + M1(3,2)*T_old(:,:,3) )*M3i.'; T_new(:,:,3)=M2i*(M1(1,3)*T_old(:,:,1) + M1(2,3)*T_old(:,:,2) + M1(3,3)*T_old(:,:,3) )*M3i.'; end T_new=T_new/norm(T_new(:)); end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 本函数用于下载指定证券代码(多个请用‘,’隔开)相应指定起始和截止日期之间的日 % 行情数据,保存到backtest Cache中,文件名为证券代码。 % 这里的日行情数据格式如下: % 732686 4.460868254 4.48874868 4.419047614 4.453898147 11022101 6.39 215.9386515 % 732687 4.426017721 4.432987827 4.286615588 4.377226974 21426743 6.28 212.2213977 % 732688 4.377226974 4.426017721 4.321466121 4.342376441 9749282 6.23 210.5317369 % 732689 4.328436228 4.377226974 4.314496014 4.377226974 6720529 6.28 212.2213977 % 732690 4.356316654 4.426017721 4.307525908 4.328436228 7996673 6.21 209.8558726 % 日期 前复权开盘 前复权最高 前复权最低 前复权收盘 成交量 不复权收盘 后复权收盘 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tool_download_callback(Path_backtest) % 获取证券代码 prompt = {'证券代码(多个请用‘,’隔开):','StartDate','EndDate'}; dlg_title = '输入下载证券代码'; def ={'000300.SHI,000001.SHI','2012-01-01','2012-06-01'}; num_lines = 1; options.Resize = 'on'; input_arg = inputdlg(prompt,dlg_title,num_lines,def,options); if ~isempty(input_arg) StartDate = input_arg{2}; EndDate = input_arg{3}; s = input_arg{1}; token = cell(1,1); index = 1; [token{index}, remain] = strtok(s,','); % 下载指定证券代码日行情数据并保存到Cache中 writeintocache_backtest(token{index},StartDate,EndDate,Path_backtest); while ~isempty(remain) s = remain; index = index + 1; [token{index}, remain] = strtok(s,','); writeintocache_backtest(token{index},StartDate,EndDate,Path_backtest); end end end
%% Utility functions classdef Util < handle %% methods (Static) %% % Scale and randomize data (matrix or filename). Use for % convenience instead of individual functions. function [data outfile] = scaleAndRandomize(data, numOutputs, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue) if nargin < 2 error('scaleAndRandomize(): Not enough input arguments.'); end outfile = ''; if ischar(data) outfile = Util.appendFilename(data, '_scaled_randomized'); data = xlsread(data); end switch nargin case 2 data = Util.scale(data, numOutputs); case 4 data = Util.scale(data, numOutputs, inputMinValue, inputMaxValue); case 6 data = Util.scale(data, numOutputs, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue); otherwise error('scaleAndRandomize(): Invalid number of arguments.'); end data = Util.randomize(data); if ~isempty(outfile) xlswrite(outfile, data); end end %% % Scale `data` (a matrix or an xls filename) to the given min/max values. % default input limits are [-1, 1] default output limits are [0, 1]. % If data is a filename, filename_scaled.xls will also be written. function [scaled outfile] = scale(data, numOutputs, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue) if nargin < 2 error('scale(): Not enough input arguments.'); end outfile = ''; if ischar(data) outfile = Util.appendFilename(data, '_scaled'); data = xlsread(data); end if isempty(data) error('scale(): Data is empty.'); end if numOutputs < 1 error('scale(): There must be at least one output.'); end numInputs = size(data, 2) - numOutputs; if numInputs < 1 error('scale(): There must be at least one input.'); end numSamples = size(data, 1); if nargin == 3 || nargin == 5 error('scale(): maxValue must be defined if minValue is defined.'); end if nargin == 4 || nargin == 6 if inputMinValue >= inputMaxValue || outputMinValue >= outputMaxValue error('scale(): minValue must be less than maxValue.'); end else inputMinValue = -1; inputMaxValue = 1; outputMinValue = 0; outputMaxValue = 1; end scaled = zeros(size(data)); scaleDiff = inputMaxValue - inputMinValue; for i = 1 : numInputs minval = min(data(:, i)); maxval = max(data(:, i)); dataDiff = maxval - minval; for j = 1 : numSamples scaled(j, i) = inputMinValue + ((data(j, i) - minval) * scaleDiff) / dataDiff; end end scaleDiff = outputMaxValue - outputMinValue; for i = (numInputs + 1) : (numInputs + numOutputs) minval = min(data(:, i)); maxval = max(data(:, i)); dataDiff = maxval - minval; for j = 1 : numSamples scaled(j, i) = outputMinValue + ((data(j, i) - minval) * scaleDiff) / dataDiff; end end if ~isempty(outfile) xlswrite(outfile, scaled); end end %% % Randomize the rows in `data` (a matrix or an xls filename). % If data is a filename, filename_randomized.xls will also be written. function [randomized outfile] = randomize(data) if nargin < 1 error('randomize(): Not enough input arguments.'); end outfile = ''; if ischar(data) outfile = Util.appendFilename(data, '_randomized'); data = xlsread(data); end if isempty(data) error('randomize(): Data is empty.'); end randomized = data(randperm(size(data,1)),:); if ~isempty(outfile) xlswrite(outfile, randomized); end end %% % Insert text between the end of a file's name and the extension. function newname = appendFilename(filename, text) if nargin < 2 || ~ischar(filename) || ~ischar(text) error('appendFilename(): Two string arguments are required.'); end strcat(filename, ''); [~, ~, ext] = fileparts(filename); newname = strcat(filename(1:(length(filename) - length(ext))), text, ext); end end methods (Access = private) end end
function [itrs, w_s, AUCs, timing] = OPAUC(X,y,X_test,y_test,eta,lambda,n_delta,u) % Usage: OPAUC algorithm % nargin < 8: standard OPAUC % nargin == 8: OPAUCr (OPAUC for large scale data) % Author: xzhang % Date: 2017.11.16 % Version: 1.2 tic; 'new~' % Returns AUCs = []; itrs = []; timing = []; w_s = []; y = sparse(y); % parameters [d,n] = size(X); if nargin < 8 || ~u init = @zeros; u = d; std = 1; else disp('large scale and going with sparse setting ...') std = 0; init = @sparse; R_hat_p = init(1,u); R_hat_n = init(1,u); end T_p = 0; T_n = 0; c_p = init(d,1); c_n = init(d,1); w = init(d,1); Gamma_p = init(d,u); Gamma_n = init(d,u); delta = floor(n/n_delta); sample = randsample(n, n, 'false'); for i = 1:n xi = X(:,sample(i)); yi = y(sample(i)); if yi == 1 T_p = T_p+1; c_p = c_p+(xi-c_p)/T_p; if std [Gamma_p,g] = std_update(xi,yi,w,lambda,Gamma_p,c_p,T_p,Gamma_n,c_n); else [Gamma_p,g,R_hat_p] = large_update(xi,yi,w,lambda,u,Gamma_p,R_hat_p,Gamma_n,c_n,R_hat_n,T_n); end else T_n = T_n+1; c_n = c_n+(xi-c_n)/T_n; if std [Gamma_n,g] = std_update(xi,yi,w,lambda,Gamma_n,c_n,T_n,Gamma_p,c_p); else [Gamma_n,g,R_hat_n] = large_update(xi,yi,w,lambda,u,Gamma_n,R_hat_n,Gamma_p,c_p,R_hat_p,T_p); end end w = w-eta*g; % update model % collect intermediate results if mod(i,delta) == 0 [~,~,~,AUC] = perfcurve(y_test,w'*X_test,1); disp(['***OPAUC: itr=', num2str(i), ', AUC=', num2str(AUC)]); AUCs = cat(1, AUCs, AUC); itrs = cat(1, itrs, i); timing = cat(1, timing, toc); w_s = cat(2, w_s, w); end end end function [Gamma,g] = std_update(xi,yi,w,lambda,Gamma,c,T,Gamma_op,c_op) tmp = c; Gamma = Gamma+(xi*xi'-Gamma)/T+tmp*tmp'-c*c'; g = lambda*w-yi*xi+yi*c_op+(xi-c_op)*(xi-c_op)'*w+Gamma_op*w; end function [Gamma,g,R_hat] = large_update(xi,yi,w,lambda,u,Gamma,R_hat,Gamma_op,c_op,R_hat_op,T_op) % ri = randn(u,1); ri = sparse(randn(u,1)); R_hat = R_hat + ri'/u; % update R_hat Gamma = Gamma + xi*ri'/u; % update Z tmp = xi-c_op; g = lambda*w-yi*(tmp)+(tmp)*((tmp)'*w); % if T_op > 0 % c_hat_op = (c_op*R_hat_op)/T_op; g = g + Gamma_op*(Gamma_op'*w)/T_op-(c_op*(R_hat_op*R_hat_op')*(c_op'*w))/(T_op^2); end end
%Name: % getu % %Purpose: % This method will be used to apply the Dirichlet boundary condition. % Where Vbound indicates we need the displacement to be zero. % %Parameters: % A - ((2x#vertices) x (2x#vertices)) stiffness matrix % F - ((2x#vertices) x 1) vector which represent the force value of each % vertex % Vbound (#vertices x 3) - matrix which shows which vertices were chosen % to be Dirichlet boundary points % %Return Values: % u - ((2x#vertices) x 1) vector which represents the displacment each % vertex will recieve (our solution) % %Author: % Shea Yonker % %Date: % 09/18/2017 function [u] = getu(A,F,Vbound) s = size(A,1); u=zeros(s,1); m=1; B=zeros(s); C=zeros(s,1); for j=1:(s/2) if (Vbound(j,3) == 1) else n=1; for i=1:s if (i<=(s/2)) if (Vbound(i,3) == 1) else B(m,n)=A(j,i); n=n+1; end else if (Vbound(i-(s/2),3) == 1) else B(m,n)=A(j,i); n=n+1; end end end C(m)=F(j); m=m+1; end end for j=((s/2)+1):s if (Vbound(j-(s/2),3) == 1) else n=1; for i=1:s if (i<=(s/2)) if (Vbound(i,3) == 1) else B(m,n)=A(j,i); n=n+1; end else if (Vbound(i-(s/2),3) == 1) else B(m,n)=A(j,i); n=n+1; end end end C(m)=F(j); m=m+1; end end Areduced=zeros(m-1); Freduced=zeros(m-1,1); for j=1:m-1 for i=1:m-1 Areduced(j,i)=B(j,i); end Freduced(j)=C(j); end ureduced=Areduced\Freduced; m=1; for j=1:(s/2) if (Vbound(j,3) == 1) u(j)=0; else u(j)=ureduced(m); m=m+1; end end for j=((s/2)+1):s if (Vbound(j-(s/2),3) == 1) u(j)=0; else u(j)=ureduced(m); m=m+1; end end end
clc clear % x = [1,2,3;4,5,6;]; x = double(rgb2gray(imread('/Users/INNOCENTBOY/Documents/MATLAB/pic/256/4.1.01.tiff'))); h = ones(5,5); % h = h/25; M= size(x,1); N= size(x,2); m= size(h,1); n= size(h,2); h2 = fft2(h,M+m-1,N+n-1); x2 = fft2(x,M+m-1,N+n-1); h1 = fft2(h,M,N); x1 = fft2(x,M,N); out = x1.*h1; out = ifft2(out); out1 = x2.*h2; out1 = ifft2(out1); figure subplot(2,2,1),imshow(mat2gray(x)); subplot(2,2,2),imshow(mat2gray(out)); subplot(2,2,3),imshow(mat2gray(out1));
function pixelgrid( h ) % Generates horizontal and vertical pixel grid lines for every pixel in an % open image specified by the handle h. Operates on an already displayed % figure and image. % % Required Input % ============== % h Figure handle correspoding to the open image to operate on % % Reference % ========= % http://blogs.mathworks.com/steve/2011/02/17/pixel-grid/ % h = findobj(h, 'type', 'image'); xdata = get(h, 'XData'); ydata = get(h, 'YData'); M = size(get(h, 'CData'), 1); N = size(get(h, 'CData'), 2); if M > 1 pixel_height = diff(ydata) / (M-1); else pixel_height = 1; end if N > 1 pixel_width = diff(xdata) / (M-1); else pixel_width = 1; end y_top = ydata(1) - (pixel_height / 2); y_bottom = ydata(2) + (pixel_height / 2); y = linspace(y_top, y_bottom, M+1); x_left = xdata(1) - (pixel_width / 2); x_right = xdata(2) + (pixel_width / 2); x = linspace(x_left, x_right, N+1); xv = zeros(1, 2*numel(x)); xv(1:2:end) = x; xv(2:2:end) = x; yv = repmat([y(1) ; y(end)], 1, numel(x)); yv(:,2:2:end) = flipud(yv(:,2:2:end)); xv = xv(:); yv = yv(:); yh = zeros(1, 2*numel(y)); yh(1:2:end) = y; yh(2:2:end) = y; xh = repmat([x(1) ; x(end)], 1, numel(y)); xh(:,2:2:end) = flipud(xh(:,2:2:end)); xh = xh(:); yh = yh(:); dark = [0.3 0.3 0.3]; light = [0.8 0.8 0.8]; hold on; ax = ancestor(h, 'axes'); line('Parent', ax, 'XData', xh, 'YData', yh, 'Color', dark, ... 'LineStyle', '-', 'Clipping', 'off'); line('Parent', ax, 'XData', xh, 'YData', yh, 'Color', light, ... 'LineStyle', '--', 'Clipping', 'off'); line('Parent', ax, 'XData', xv, 'YData', yv, 'Color', dark, ... 'LineStyle', '-', 'Clipping', 'off'); line('Parent', ax, 'XData', xv, 'YData', yv, 'Color', light, ... 'LineStyle', '--', 'Clipping', 'off'); hold off; end
function[nll] = negPopLogLikelihood(motion,f,r,params) % function[nll] = negPopLogLikelihood(motion,f,r,params) % % motion: (e.g., specifies [direction, speed] for xz motion) % f: tuning curve function handle % r: "neural responses" % params: parameters for tuning curves % % nll: negative loglikelihood % % see Graf, Kohn, Jazayeri, & Movshon (2011) % motion(2) = exp(motion(2)); ftemp = f(motion,params); % calculate tuning curve responses to particular motion weights = log(ftemp); ll = bsxfun(@times,weights,r) - ftemp - repmat(logfactorial(r),1,size(motion,1)); nll = -sum(ll);
function [mapout,xgrid] = sz1SM(data,paramstruct) % SZ1SM, Significant derivative Zero crossings % Steve Marron's matlab function % Creates color map (function of location and bandwidth), % showing statistical signicance of slope of smooth % Colored (or gray level) as: % blue (dark) at points where deriv sig > 0 % red (light) at points where deriv sig < 0 % purple (gray) at points where deriv roughly 0 % light gray where "effective sample size" < 5 % % Inputs: % % data - Case 1: density estimation: % either n x 1 column vector of 1-d data % or vector of bincts, when imptyp = -1 % Case 2: regression: % either n x 2 matrix of Xs (1st col) and Ys (2nd col) % or g x 3 matrix of bincts, when imptyp = -1 % (3rd column is wt'd bin avg's of squares) % % paramstruct - a Matlab structure of input parameters % Use: "help struct" and "help datatypes" to % learn about these. % Create one, using commands of the form: % % paramstruct = struct('field1',values1,... % 'field2',values2,... % 'field3',values3) ; % % where any of the following can be used, % these are optional, misspecified values % revert to defaults % % fields values % % vxgp vector of x grid parameters: % 0 (or not specified) - use endpts of data and 401 bins % [le; lr; nb] - le left, re right, and nb bins % % vhgp vector of h (bandwidth) grid parameters: % 0 (or not specified) - use (2*binwidth) to (range), % and 21 h's % [hmin; hmax; nh] - use hmin to hmax and nh h's. % % imptyp flag indicating implementation type: % -1 - binned version, and "data" is assumed to be % bincounts of prebinned data % CAUTION: for regression, also need % to include bincounts of squares % as a third column % 0 (or not specified) - linear binned version % and bin data here % % eptflag endpoint truncation flag (only has effect when imptyp = 0): % 0 (or not specified) - move data outside range to % nearest endpoint % 1 - truncate data outside range % % ibdryadj index of boundary adjustment % 0 (or not specified) - no adjustment % 1 - mirror image adjustment % 2 - circular design % (only has effect for density estimation) % % iregtdist index for using Student's t distribution in regression % 0 (or not specified) - use only Gaussian approximation % 1 - use Student's t distribution quantiles in testing % (only has effect for regression) % % alpha Usual "level of significance". I.e. C.I.s have coverage % probability 1 - alpha. (0.05 when not specified) % % simflag Confidence Interval type (simultaneous vs. ptwise) % 0 - Use Pointwise C.I.'s % 1 (or not specified) - Use Row-wise Simultaneous C.I.'s % 2 - Use Global Simultaneous C.I.'s % 3 - Use Mixture 1 (Bonferroni across rows) Simultaneous C.I.'s % 4 - Use Mixture 2 (Bonferroni across rows) Simultaneous C.I.'s % 5 - 3 times Eff. SS global % 6 - 3 times Eff. SS Row-wise % % icolor 1 (default) full color version of SiZer % 0 fully black and white version % % titlestr string with title (only has effect when plot is made here) % default is empty string, '', for no title % % titlefontsize font size for title % (only has effect when plot is made here, % and when the titlestr is nonempty) % default is empty [], for Matlab default % % xlabelstr string with x axis label % (only has effect when plot is made here) % default is empty string, '', for no xlabel % % ylabelstr string with y axis label % (only has effect when plot is made here) % default is empty string, '', for no ylabel % % labelfontsize font size for axis labels % (only has effect when plot is made here, % and when a label str is nonempty) % default is empty [], for Matlab default % % iplot 1 - plot even when there is numerical output % 0 - (default) only plot when no numerical output % % % Outputs: % (none) - Draws a gray level map (in the current axes) % mapout - output of indices into color map % xgrid - col vector grid of points at which estimate(s) are % evaluted (useful for plotting), unless grid is input, % can also get this from linspace(le,re,nb)' % % Assumes path can find personal functions: % vec2matSM.m % lbinrSM.m % % Copyright (c) J. S. Marron 1997-2001 % First set all parameters to defaults vxgp = 0 ; vhgp = 0 ; imptyp = 0 ; eptflag = 0 ; ibdryadj = 0 ; iregtdist = 0 ; alpha = 0.05 ; simflag = 1 ; icolor = 1 ; titlestr = '' ; titlefontsize = [] ; xlabelstr = '' ; ylabelstr = '' ; labelfontsize = [] ; iplot = 0 ; % Now update parameters as specified, % by parameter structure (if it is used) % if nargin > 1 ; % then paramstruct has been added if isfield(paramstruct,'vxgp') ; % then change to input value vxgp = getfield(paramstruct,'vxgp') ; end ; if isfield(paramstruct,'vhgp') ; % then change to input value vhgp = getfield(paramstruct,'vhgp') ; end ; if isfield(paramstruct,'eptflag') ; % then change to input value eptflag = getfield(paramstruct,'eptflag') ; end ; if isfield(paramstruct,'ibdryadj') ; % then change to input value ibdryadj = getfield(paramstruct,'ibdryadj') ; end ; if isfield(paramstruct,'iregtdist') ; % then change to input value iregtdist = getfield(paramstruct,'iregtdist') ; end ; if isfield(paramstruct,'alpha') ; % then change to input value alpha = getfield(paramstruct,'alpha') ; end ; if isfield(paramstruct,'simflag') ; % then change to input value simflag = getfield(paramstruct,'simflag') ; end ; if isfield(paramstruct,'icolor') ; % then change to input value icolor = getfield(paramstruct,'icolor') ; end ; if isfield(paramstruct,'titlestr') ; % then change to input value titlestr = getfield(paramstruct,'titlestr') ; end ; if isfield(paramstruct,'titlefontsize') ; % then change to input value titlefontsize = getfield(paramstruct,'titlefontsize') ; end ; if isfield(paramstruct,'xlabelstr') ; % then change to input value xlabelstr = getfield(paramstruct,'xlabelstr') ; end ; if isfield(paramstruct,'ylabelstr') ; % then change to input value ylabelstr = getfield(paramstruct,'ylabelstr') ; end ; if isfield(paramstruct,'labelfontsize') ; % then change to input value labelfontsize = getfield(paramstruct,'labelfontsize') ; end ; if isfield(paramstruct,'iplot') ; % then change to input value iplot = getfield(paramstruct,'iplot') ; end ; if isfield(paramstruct,'imptyp') ; % then change to input value imptyp = getfield(paramstruct,'imptyp') ; end ; end ; % of resetting of input parameters % detect whether density or regression data % if size(data,2) == 1 ; % Then is density estimation xdat = data(:,1) ; idatyp = 1 ; itdist = 0 ; % use Gaussian distribution, not t else ; % Then assume regression ; xdat = data(:,1) ; ydat = data(:,2) ; idatyp = 2 ; if iregtdist == 1 ; itdist = 1 ; % use t distribution else ; itdist = 0 ; % use Gaussian distribution, not t end ; end ; % Set x grid stuff % n = length(xdat) ; if vxgp == 0 ; % then use standard default x grid vxgp = [min(xdat),max(xdat),401] ; end ; left = vxgp(1) ; right = vxgp(2) ; ngrid = vxgp(3) ; xgrid = linspace(left,right,ngrid)' ; % col vector to evaluate smooths at cxgrid = xgrid - mean(xgrid) ; % centered version, gives numerical stability % Set h grid stuff % if vhgp == 0 ; % then use standard default h grid range = right - left ; binw = range / (ngrid - 1) ; vhgp = [2 * binw,range,21] ; end ; hmin = vhgp(1) ; hmax = vhgp(2) ; nh = vhgp(3) ; if nh == 1 ; vh = hmax ; else ; if hmin < hmax ; % go ahead with vh construction vh = logspace(log10(hmin),log10(hmax),nh) ; else ; % bad inputs, warn and quit disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') ; disp('!!! Error from sz1SM.m: !!!') ; disp('!!! Bad inputs in vhgp, !!!') ; disp('!!! Reguires vhgp(1) < vhgp(2) !!!') ; disp('!!! Terminating execution !!!') ; disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') ; return ; end ; end ; % Bin the data (if needed) % if idatyp == 1 ; % Treating as density estimation if imptyp == -1 ; % Then data have already been binned bincts = data ; else ; % Then need to bin data bincts = lbinrSM(xdat,vxgp,eptflag) ; end ; elseif idatyp == 2 ; % Treating as regression if imptyp == -1 ; % Then data have already been binned bincts = data(:, [1 2]) ; bincts2 = data(:, [1 3]) ; else ; % Then need to bin data bincts = lbinrSM([xdat ydat],vxgp,eptflag) ; bincts2 = lbinrSM([xdat, ydat.^2],vxgp,eptflag) ; end ; end ; n = sum(bincts(:,1)) ; % put this here in case of truncations during binning % Construct Surfaces % mdsurf = [] ; % Derivative surface mesurf = [] ; % Effective sample size surface mvsurf = [] ; % Estimated Variance of Derivative if itdist == 0 ; vgq = [] ; % Vector of Gaussian Quantiles (for simultaneous CI's) elseif itdist == 1 ; mtq = [] ; % matrix of t Quantiles (for simultaneous CI's) end ; % Create grid for kernel values delta = (right - left) / (ngrid - 1) ; % binwidth k = ngrid - 1 ; % index of last nonzero entry of kernel vector % Loop through bandwidths ihprevcalc = 0 ; % indicator of whether have done the full calculation % (not done when all locations have ESS < 5) for ih = 1:nh ; h = vh(ih) ; % Set common values arg = linspace(0,k * delta / h,k + 1)' ; kvec = exp(-(arg.^2) / 2) ; kvec = [flipud(kvec(2:k+1)); kvec] ; % construct symmetric kernel if idatyp == 1 ; % Doing density estimation % main lines from gpkde.m, via nmsur5.m % do boundary adjustment if needed % if ibdryadj == 1 ; % then do mirror image adjustment babincts = [flipud(bincts); bincts; flipud(bincts)] ; elseif ibdryadj == 2 ; % then do circular design adjustment babincts = [bincts; bincts; bincts] ; else ; babincts = bincts ; end ; % Vector of Effective sample sizes % (notation "s0" is consistent with below) ve = conv(babincts,kvec) ; if ibdryadj == 1 | ibdryadj == 2 ; % then did boundary adjustment ve = ve(ngrid+k+1:k+2*ngrid) ; else ; ve = ve(k+1:k+ngrid) ; end ; % denominator of NW est. % (same as sum for kde) kvecd = -arg .* exp(-(arg.^2) / 2) / sqrt(2 * pi) ; kvecd = [-flipud(kvecd(2:k+1)); kvecd] ; % construct symmetric kernel vd = conv(babincts,kvecd) ; vv = conv(babincts,kvecd.^2) ; if ibdryadj == 1 | ibdryadj == 2 ; % then did boundary adjustment vd = vd(ngrid+k+1:k+2*ngrid) / (n * h^2) ; vv = vv(ngrid+k+1:k+2*ngrid) / (n * h^4) ; else ; vd = vd(k+1:k+ngrid) / (n * h^2) ; vv = vv(k+1:k+ngrid) / (n * h^4) ; end ; vv = vv - vd.^2 ; vv = vv / n ; % did this outsidea loop in nmsur5.m else ; % Doing regression % using modification of lines from gpnpr.m % main lines from gpnpr.m, via szeg4.m % Vector of Effective sample sizes % (notation "s0" is consistent with below) ve = conv(bincts(:,1),kvec) ; ve = ve(k+1:k+ngrid) ; % denominator of NW est. % (same as sum for kde) flag = (ve < 1) ; % locations with effective sample size < 1 ve(flag) = ones(sum(flag),1) ; % replace small sample sizes by 1 to avoid 0 divide % no problem below, since gets grayed out s1 = conv(bincts(:,1) .* cxgrid , kvec) ; s1 = s1(k+1:k+ngrid) ; s2 = conv(bincts(:,1) .* cxgrid.^2 , kvec) ; s2 = s2(k+1:k+ngrid) ; t0 = conv(bincts(:,2),kvec) ; t0 = t0(k+1:k+ngrid) ; % numerator of NW est. xbar = conv(bincts(:,1) .* cxgrid , kvec) ; xbar = xbar(k+1:k+ngrid) ; % Weighted sum of X_i xbar = xbar ./ ve ; % Weighted avg of X_i t1 = conv(bincts(:,2) .* cxgrid , kvec) ; t1 = t1(k+1:k+ngrid) ; numerd = t1 - t0 .* xbar ; % sum(Y_i * (X_i - xbar)) * W (weighted cov(Y,X)) denomd = s2 - 2 * s1 .* xbar + ve .* xbar.^2 ; % sum((X_i - xbar)^2) * W (weighted var(X)) flag2 = denomd < (10^(-10) * mean(denomd)) ; % for local linear, need to also flag locations where this % is small, because could have many observaitons piled up % at one location ve(flag2) = ones(sum(flag2),1) ; % also reset these, because could have more than 5 piled up % at a single point, but nothing else in window flag = flag | flag2 ; % logical "or", which flags both types of locations % to avoid denominator problems denomd(flag) = ones(sum(flag),1) ; % this avoids zero divide problems, OK, since grayed out later mhat = t0 ./ ve ; vd = numerd ./ denomd ; % linear term from local linear fit (which est's deriv). % (sometimes called betahat) sig2 = conv(bincts2(:,2),kvec) ; sig2 = sig2(k+1:k+ngrid) ; sig2 = sig2 ./ ve - mhat.^ 2 ; flag2 = sig2 < (10^(-10) * mean(sig2)) ; ve(flag2) = ones(sum(flag2),1) ; % also reset these flag = flag | flag2 ; % logical "or", which flags both types of locations % to avoid denominator problems sig2(flag) = ones(sum(flag),1) ; % this avoids zero divide problems, OK, since grayed out later rho2 = vd.^2 .* (denomd ./ (sig2 .* ve)) ; sig2res = (1 - rho2) .* sig2 ; % get the residual variance from local linear reg. u0 = conv(bincts(:,1) .* sig2res , kvec.^2) ; u0 = u0(k+1:k+ngrid) ; u1 = conv(bincts(:,1) .* sig2res .* cxgrid , kvec.^2) ; u1 = u1(k+1:k+ngrid) ; u2 = conv(bincts(:,1) .* sig2res .* cxgrid.^2 , kvec.^2) ; u2 = u2(k+1:k+ngrid) ; vv = u2 - 2 * u1 .* xbar + u0 .* xbar.^2 ; vv = vv ./ denomd.^2 ; % vector of variances of slope est. (from local linear) end ; % Get quantiles, for CI's flag = (ve >= 5) ; % locations where effective sample size >= 5 if sum(flag) > 0 ; if simflag == 0 ; % do pt'wise CI's if itdist == 0 ; gquant = norminv(1 - (alpha / 2)) ; elseif itdist == 1 ; vtquant = tinv(1 - (alpha / 2),ve-1) ; end ; elseif simflag == 1 ; % do row-wise simultaneous CI's nxbar = mean(ve(flag)) ; % Crude average effective sample size numind = n / nxbar ; % Effective number of independent groups beta = (1 - alpha)^(1/numind) ; if itdist == 0 ; gquant = -norminv((1 - beta) / 2) ; elseif itdist == 1 ; vtquant = -tinv((1 - beta) / 2,ve-1) ; end ; elseif simflag == 2 ; % do Global Simultaneous C.I.'s if ihprevcalc == 0 ; % then are at finest scale, % where have not done a calculation yet ihprevcalc = 1 ; % turn off this indicator, so won't calculate this again nxbar = mean(ve(flag)) ; % Crude average effective sample size numind = n / nxbar ; % Effective number of independent groups numind = 2 * numind - 1 ; % modify to make global beta = (1 - alpha)^(1/numind) ; end ; % at other scales, continue to use this value if itdist == 0 ; gquant = -norminv((1 - beta) / 2) ; elseif itdist == 1 ; vtquant = -tinv((1 - beta) / 2,ve-1) ; end ; elseif simflag == 3 ; % do Mixture 1 (Bonferroni across rows) Simul. C.I.'s nxbar = mean(ve(flag)) ; % Crude average effective sample size numind = n / nxbar ; % Effective number of independent groups beta = (1 - (alpha / nh))^(1/numind) ; % only change from simflag = 1 above is: alpha ---> alpha / nh % (Bonferroni across rows, calculation) if itdist == 0 ; gquant = -norminv((1 - beta) / 2) ; elseif itdist == 1 ; vtquant = -tinv((1 - beta) / 2,ve-1) ; end ; elseif simflag == 4 ; % do Mixture 2 (Bonferroni across rows) Simul. C.I.'s nxbar = mean(ve(flag)) ; % Crude average effective sample size numind = n / nxbar ; % Effective number of independent groups if itdist == 0 ; gquant = numind ; elseif itdist == 1 ; vtquant = numind ; end ; % store the Effective number of groups, for later processing % CAUTION: in this case, don't return quantiles, but just % numind, for later turning into quantiles elseif simflag == 5 ; % do 3 times Global Simultaneous C.I.'s if ihprevcalc == 0 ; % then are at finest scale, % where have not done a calculation yet ihprevcalc = 1 ; % turn off this indicator, so won't calculate this again nxbar = mean(ve(flag)) ; % Crude average effective sample size numind = n / nxbar ; % Effective number of independent groups numind = 6 * numind - 5 ; % modify to make global beta = (1 - alpha)^(1/numind) ; end ; % at other scales, continue to use this value if itdist == 0 ; gquant = -norminv((1 - beta) / 2) ; elseif itdist == 1 ; vtquant = -tinv((1 - beta) / 2,ve-1) ; end ; elseif simflag == 6 ; % do 3 times row-wise simultaneous CI's nxbar = mean(ve(flag)) ; % Crude average effective sample size numind = n / nxbar ; % Effective number of independent groups numind = 3 * numind - 2 ; beta = (1 - alpha)^(1/numind) ; if itdist == 0 ; gquant = -norminv((1 - beta) / 2) ; elseif itdist == 1 ; vtquant = -tinv((1 - beta) / 2,ve-1) ; end ; end ; else ; if itdist == 0 ; gquant = inf ; elseif itdist == 1 ; vtquant = inf * ones(ngrid,1) ; end ; end ; mdsurf = [mdsurf vd] ; mesurf = [mesurf ve] ; mvsurf = [mvsurf vv] ; if itdist == 0 ; vgq = [vgq gquant] ; elseif itdist == 1 ; mtq = [mtq vtquant] ; end ; end ; % finish vgq calculation (if needed) % (i.e. if only stored numind, instead of quantiles above) % if simflag == 4 ; % do Mixture 2 (Bonferroni across rows) Simul. C.I.'s if itdist == 0 ; vnumind = vgq ; % unpack column vector of number of indep blocks, stored above elseif itdist == 1 ; vnumind = mtq ; % unpack column vector of number of indep blocks, stored above end ; vrowfactor = vnumind .^ (0.5) ; vrowfactor = vrowfactor / sum(vrowfactor) ; vbeta = (1 - (alpha .* vrowfactor)).^ (1 ./ vnumind) ; if itdist == 0 ; vgq = -norminv((1 - vbeta) / 2) ; elseif itdist == 1 ; mtq = -tinv(vec2matSM((1 - vbeta) / 2,ngrid), vec2matSM(ve-1,nh)) ; % note first is an nh x 1 column vector % and second is a 1 x ngrid row vector end ; end ; %vrowfactor %1/nh %vnumind %vgq %pauseSM % Construct scale space CI surfaces % if itdist == 0 ; if nh > 1 ; % then have full matrices mloci = mdsurf - vec2matSM(vgq,ngrid) .* sqrt(mvsurf) ; % Lower confidence (simul.) surface for derivative mhici = mdsurf + vec2matSM(vgq,ngrid) .* sqrt(mvsurf) ; % Upper confidence (simul.) surface for derivative else ; % have only vectors (since only one h) mloci = mdsurf - vgq * sqrt(mvsurf) ; % Lower confidence (simul.) surface for derivative mhici = mdsurf + vgq * sqrt(mvsurf) ; % Upper confidence (simul.) surface for derivative end ; elseif itdist == 1 ; mloci = mdsurf - mtq .* sqrt(mvsurf) ; % Lower confidence (simul.) surface for derivative mhici = mdsurf + mtq .* sqrt(mvsurf) ; % Upper confidence (simul.) surface for derivative end ; % Construct "color map", really assignment % of pixels to integers, with idea: % 1 (very dark) - Deriv. Sig. > 0 % 2 (darker gray) - Eff. SS < 5 % 3 (lighter gray) - Eff. SS >= 5, but CI contains 0 % 4 (very light) - Deriv. Sig. < 0 mapout = 3 * ones(size(mloci)) ; % default is purple (middle lighter gray) flag = (mloci > 0) ; % matrix of ones where lo ci above 0 ssflag = sum(sum(flag)) ; if ssflag > 0 ; mapout(flag) = ones(ssflag,1) ; % put blue (dark grey) where significantly positive end ; flag = (mhici < 0) ; % matrix of ones where hi ci below 0 ssflag = sum(sum(flag)) ; if ssflag > 0 ; mapout(flag) = 4 * ones(ssflag,1) ; % put red (light gray) where significantly negative end ; flag = (mesurf <= 5) ; % matrix of ones where effective np <= 5 ; ssflag = sum(sum(flag)) ; if ssflag > 0 ; mapout(flag) = 2 * ones(ssflag,1) ; % put middle darker gray where effective sample size < 5 end ; % Transpose for graphics purposes mapout = mapout' ; % Make plots if no numerical output requested % if nargout == 0 | ... iplot == 1 ; % Then make a plot if icolor ~= 0 ; % Then go for nice colors in sizer and sicon % Set up colorful color map cocomap = [0, 0, 1; ... .35, .35, .35; ... .5, 0, .5; ... 1, 0, 0; ... 1, .5, 0; ... .35, .35, .35; ... 0, 1, 0; ... 0, 1, 1] ; colormap(cocomap) ; else ; % Then use gray scale maps everywhere % Set up gray level color map comap = [.2, .2, .2; ... .35, .35, .35; ... .5, .5, .5; ... .8, .8, .8] ; colormap(comap) ; end ; image([left,right],[log10(hmin),log10(hmax)],mapout) ; set(gca,'YDir','normal') ; if ~isempty(titlestr) ; if isempty(titlefontsize) ; title(titlestr) ; else ; title(titlestr,'FontSize',titlefontsize) ; end ; end ; if ~isempty(xlabelstr) ; if isempty(labelfontsize) ; xlabel(xlabelstr) ; else ; xlabel(xlabelstr,'FontSize',labelfontsize) ; end ; end ; if ~isempty(ylabelstr) ; if isempty(labelfontsize) ; ylabel(ylabelstr) ; else ; ylabel(ylabelstr,'FontSize',labelfontsize) ; end ; end ; end ;
classdef AbstractAnimator < handle % An abstract animator class % % @author omar @date 2017-06-01 % % Copyright (c) 2017, UMICH Biped Lab % All right reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted only in compliance with the BSD 3-Clause % license, see % http://www.opensource.org/licenses/BSD-3-Clause properties(Access = private) tmr timer end properties (GetAccess = protected, SetAccess = immutable) fig axs end properties (Access = public) currentTime double speed double updateWorldPosition logical end properties (Access = public) isLooping logical pov frost.Animator.AnimatorPointOfView startTime double endTime double end properties (GetAccess = public, SetAccess = immutable) TimerDelta double end properties (Dependent, Access = public) isPlaying logical end properties (Access = private) x_all; t_all; text; ground; end properties (Access = public) display end methods function obj = AbstractAnimator(display, t, x, varargin) % if exist('f', 'var') % obj.fig = f; % obj.axs = axes(obj.fig); % else % obj.fig = figure(); % obj.axs = axes(obj.fig); % end obj.display = display; obj.fig = display.fig; obj.axs = display.axs; obj.t_all = t; obj.x_all = x; obj.startTime = t(1); obj.currentTime = obj.startTime; obj.endTime = t(end); % setup timer obj.speed = 1; obj.TimerDelta = round(1/30,3); obj.pov = frost.Animator.AnimatorPointOfView.Free; obj.tmr = timer; obj.tmr.Period = obj.TimerDelta; obj.tmr.ExecutionMode = 'fixedRate'; obj.tmr.TimerFcn = @(~, ~) obj.Animate(); % Define Terrain if isempty(varargin) [terrain.Tx, terrain.Ty] = meshgrid(-10:1:10, -10:1:10); terrain.Tz = 0.*terrain.Tx; else terrain = varargin{1}; end obj.ground = surf(terrain.Tx,terrain.Ty,terrain.Tz,'FaceColor',[0.5 0.8 0.5]); hold on; end function playing = get.isPlaying(obj) playing = strcmp(obj.tmr.Running, 'on'); end function set.isPlaying(obj, play) if ~obj.isPlaying && play start(obj.tmr); notify(obj, 'playStateChanged'); elseif obj.isPlaying && ~play stop(obj.tmr); notify(obj, 'playStateChanged'); end end function set.currentTime(obj, time) obj.currentTime = time; if obj.currentTime > obj.endTime %#ok<*MCSUP> obj.currentTime = obj.endTime; elseif obj.currentTime < obj.startTime obj.currentTime = obj.startTime; end end end methods (Sealed) function Animate(obj, Freeze) if ~exist('Freeze', 'var') Freeze = false; end if obj.currentTime >= obj.endTime obj.currentTime = obj.endTime; x = GetData(obj, obj.currentTime); notify(obj, 'newTimeStep', frost.Animator.TimeStepData(obj.currentTime, x)); obj.Draw(obj.currentTime, x); obj.HandleAxis(obj.currentTime, x); notify(obj, 'reachedEnd', frost.Animator.TimeStepData(obj.currentTime, x)); if obj.isLooping if ~Freeze obj.currentTime = obj.startTime; end else obj.isPlaying = false; end else x = GetData(obj, obj.currentTime); notify(obj, 'newTimeStep', frost.Animator.TimeStepData(obj.currentTime, x)); obj.Draw(obj.currentTime, x); obj.HandleAxis(obj.currentTime, x); if ~Freeze obj.currentTime = obj.currentTime + obj.TimerDelta*obj.speed; end end end end methods function HandleAxis(obj, t, x) [center, radius, yaw] = GetCenter(obj, t, x); if length(radius) == 1 axis(obj.axs, [center(1)-radius, center(1)+radius, center(2)-radius, center(2)+radius,center(3)-radius/3, center(3)+radius]); else axis(obj.axs, radius); end hAngle = 0; vAngle = 0; switch(obj.pov) case frost.Animator.AnimatorPointOfView.North hAngle = hAngle + 0; case frost.Animator.AnimatorPointOfView.South hAngle = hAngle + 180; case frost.Animator.AnimatorPointOfView.East hAngle = hAngle - 90; case frost.Animator.AnimatorPointOfView.West hAngle = hAngle + 90; case frost.Animator.AnimatorPointOfView.Front hAngle = hAngle + yaw; case frost.Animator.AnimatorPointOfView.Back hAngle = hAngle + 180 + yaw; case frost.Animator.AnimatorPointOfView.Left hAngle = hAngle - 90 + yaw; case frost.Animator.AnimatorPointOfView.Right hAngle = hAngle + 90 + yaw; case frost.Animator.AnimatorPointOfView.TopSouthEast hAngle = hAngle + 225; vAngle = vAngle + 45; case frost.Animator.AnimatorPointOfView.TopFrontLeft hAngle = hAngle + 225 + yaw; vAngle = vAngle + 45; end if obj.pov ~= frost.Animator.AnimatorPointOfView.Free view(obj.axs, hAngle, vAngle); end end function Draw(obj, t, x) obj.display.update(x); [center, radius, ~] = GetCenter(obj, t, x); delete(obj.text); obj.text = text(center(1)-radius/2,center(2),center(3)+radius-0.2,['t = ',sprintf('%.2f',t)]); %#ok<CPROPLC> obj.text.FontSize = 14; obj.text.FontWeight = 'Bold'; obj.text.Color = [0,0,0]; % set(obj.text); drawnow; end function [center, radius, yaw] = GetCenter(obj, t, x) center = [0,0,0]; radius = 3; yaw = 0; end function x = GetData(obj, t) t_start = obj.t_all(1); t_end = obj.t_all(end); delta_t = t_end - t_start; if t < t_start || t > t_end val = floor((t - t_start) / delta_t); t = t - val * delta_t; end if t < t_start t = t_start; elseif t > t_end t = t_end; end n = length(obj.t_all); x = obj.x_all(:, 1); % Default a = 1; b = n; while (a <= b) c = floor((a + b) / 2); if t < obj.t_all(c) x = obj.x_all(:, c); b = c - 1; elseif t > obj.t_all(c) a = c + 1; else x = obj.x_all(:, c); break; end end end end events newTimeStep playStateChanged reachedEnd end end
function pdMat = randPD(n) [u,~,~] = svd(rand(n,n)); pdMat = u * diag(rand(n,1)) * u';
% history points for smoothWavyWall % %-----------------------------------------------------% % points nx=10; % nx=number of x-points ny=100; % ny=number of y points per x-location h=0.50; % height to go up to in Y casename='smoothWavyWall'; %-----------------------------------------------------% % get x locations from maass % fil = 'maass/dat'; xM = zeros(1,nx); for i=1:nx nameM = [fil,num2str(i,'%0.2d')]; xM(i) = dlmread(nameM,'',[0 3 0 3]); end xM(end) = xM(end)-1; x = xM + 2; %-----------------------------------------------------% % geometry [x,y]=meshgrid(x,linspace(0,h,ny)); [x,y,xw,yw] = wavyWall(x,y,casename); x = reshape(x,[nx*ny,1]); y = reshape(y,[nx*ny,1]); z = 0*x; %-----------------------------------------------------% % create file casename.his format long A = [x,y,z]; casename=[casename,'.his']; fID = fopen(casename,'w'); fprintf(fID, [num2str(nx*ny) ' !=number of monitoring points\n']); dlmwrite(casename,A,'delimiter',' ','-append'); type(casename)
% Reads multiple folders recorded on same/different days and produces % matrix with all sessions and folders recorded % % Revision history: % % v1.0 September 1, 2016. Basic script prepared. % Data file is format: % [subjectName_Date_chChannelNumber_uUnitNumber_unitType.mat] % (for example: aq_20161231_ch1_u1_m.mat); function [y] = get_path_spikes_v10 (path1, subject_name) % Determine how many files with the subject name are there index_cur_dir = dir(path1); % Initialize output variables temp_ind_subj = cell(length(index_cur_dir), 1); temp_ind_dates = NaN(length(index_cur_dir), 1); temp_ind_channels = NaN (length(index_cur_dir), 1); temp_ind_units = NaN (length(index_cur_dir), 1); temp_ind_unit_class = cell (length(index_cur_dir), 1); %% Parse the file name % Temporary variables initiated fnames = cell (length(index_cur_dir), 1); % Temporary file name used fdates = cell (length(index_cur_dir), 1); % Dates in string format will be stored here % Extract file names & their sizes for i=1:length(index_cur_dir) fnames{i} = index_cur_dir(i).name; end %============ % Subject names %============ % Extract subject names for i=1:length(fnames) if length(fnames{i}) > length(subject_name) if strcmp(fnames{i}(1:length(subject_name)), subject_name) temp_ind_subj{i} = subject_name; % Save subject name fnames{i}(1:length(subject_name)) = []; else temp_ind_subj{i} = NaN; % Save subject name fnames{i} = NaN; end else temp_ind_subj{i} = NaN; fnames{i}=[]; % Discard if folder doesnt start with subject name end end % If there is a dash, extract it for i=1:length(fnames) if length(fnames{i}) > 1 if strcmp(fnames{i}(1), '_') fnames{i}(1) = []; end end end %=============== % Date detection %=============== % Detect chanel number for i=1:length(fnames) if length(fnames{i}) >= 2 [a,b] = strsplit(fnames{i}, '_'); % Find delimiter if ~isempty(b) % If delimiter exists if str2num(a{1}) temp_ind_dates(i) = str2num(a{1}); fnames{i}(1:length(a{1})) = []; else temp_ind_dates(i)=NaN; fnames{i}=NaN; end else temp_ind_dates(i)=NaN; fnames{i} = NaN; end end end % If there is a dash, extract it for i=1:length(fnames) if length(fnames{i}) > 1 if strcmp(fnames{i}(1), '_') fnames{i}(1) = []; end end end %================= % Channel detection %================= % Detect if next is channel notation for i=1:length(fnames) if length(fnames{i}) >= 2 if strcmp(fnames{i}(1:2), 'ch') fnames{i}(1:2) = []; else fnames{i}=NaN; end else fnames{i} = NaN; end end % Detect chanel number for i=1:length(fnames) if length(fnames{i}) >= 2 [a,b] = strsplit(fnames{i}, '_'); % Find delimiter if ~isempty(b) % If delimiter exists if str2num(a{1}) temp_ind_channels(i) = str2num(a{1}); fnames{i}(1:length(a{1})) = []; else temp_ind_channels(i) = NaN; fnames{i}=NaN; end else temp_ind_channels(i) = NaN; fnames{i} = NaN; end end end % If there is a dash, extract it for i=1:length(fnames) if length(fnames{i}) > 1 if strcmp(fnames{i}(1), '_') fnames{i}(1) = []; end end end %================= % Unit detection %================= % Detect if next is unit number notation for i=1:length(fnames) if length(fnames{i}) >= 1 if strcmp(fnames{i}(1), 'u') fnames{i}(1) = []; else fnames{i}=NaN; end else fnames{i} = NaN; end end % Detect unit number for i=1:length(fnames) if length(fnames{i}) >= 2 [a,b] = strsplit(fnames{i}, '_'); % Find delimiter if ~isempty(b) % If delimiter exists if str2num(a{1}) temp_ind_units(i) = str2num(a{1}); fnames{i}(1:length(a{1})) = []; else temp_ind_units(i) = NaN; fnames{i}=NaN; end else temp_ind_units(i) = NaN; fnames{i} = NaN; end end end % If there is a dash, extract it for i=1:length(fnames) if length(fnames{i}) > 1 if strcmp(fnames{i}(1), '_') fnames{i}(1) = []; end end end %================= % Unit classification detection %================= for i=1:length(fnames) if length(fnames{i}) >= 1 if strcmp(fnames{i}(1), 'u') || strcmp(fnames{i}(1), 's') || strcmp(fnames{i}(1), 'm') temp_ind_unit_class{i}(1) = fnames{i}(1); fnames{i}(1) = []; else temp_ind_unit_class{i}(1) = NaN; fnames{i}=NaN; end else temp_ind_unit_class{i}(1) = NaN; fnames{i} = NaN; end end %% For each date and session prepare a list of paths % Find unique days used unique_dates = unique(temp_ind_dates); ind=isnan(unique_dates); unique_dates(ind)=[]; index_cur_dir; % This is necessary input. Contains all file names and file ordering % Create output matrix file_name1 = cell(1); dates1 = []; subject1 = cell(1); unit1 = []; channel1 = []; unit_class1 = cell(1); path_temp1 = cell(1); for i=1:length(unique_dates) index1 = find(temp_ind_dates == unique_dates(i)); for j=1:length(index1); if length(file_name1)==1 && isempty(file_name1{1}) ind = 1; else ind = ind+1; end file_name1{ind,1} = index_cur_dir(index1(j)).name; dates1(ind,1) = temp_ind_dates(index1(j)); subject1{ind,1} = temp_ind_subj{index1(j)}; unit1(ind,1) = temp_ind_units(index1(j)); channels1(ind,1) = temp_ind_channels(index1(j)); unit_class1{ind,1} = temp_ind_unit_class{index1(j)}; path_temp1{ind,1} = [path1, index_cur_dir(index1(j)).name]; end end %% Output y.index_dates=dates1; y.index_unique_dates = unique_dates; y.index_subjects = subject1; y.index_file_name = file_name1; y.index_unit = unit1; y.index_channel = channels1; y.index_unit_type = unit_class1; y.index_path = path_temp1;
function summary=SG_analyse_bootstrap(N,restricted) if nargin==0 N = 1000 ; end %nDS = numel(dir(sprintf('../results/bootstrap/data*_r%d.mat',restricted)))/45 ; nDS = 100;% %effect_types = {'dynamics','choiceUpdate','successUpdate','forceUpdate'}; % for each random group parfor iB=1:N rng('shuffle'); % draw 18 random subjects dummy_group = randperm(nDS,18); %load data [summary_group]=SG_analyse('bootstrap',restricted,dummy_group); summary_sub(iB) = summary_group ; end summary.all = summary_sub; % for iT=1:numel(effect_types) % % MC = [summary_sub.MC]; % % Ef = struct.extract([MC.(effect_types{iT})],'Ef'); % xp = struct.extract([MC.(effect_types{iT})],'xp'); % % summary.(effect_types{iT}).Ef_mean = mean(Ef); % summary.(effect_types{iT}).Ef_std = std(Ef); % % summary.(effect_types{iT}).xp_mean = mean(xp); % summary.(effect_types{iT}).xp_std = std(xp); % % end % % effect_param = fields(summary_sub(1).BMA.significance); % for iT=1:numel(effect_param) % BMA = [summary_sub.BMA]; % % pp = struct.extract([BMA.significance],effect_param{iT}) ; % summary.(effect_param{iT}).p_mean = mean(pp); % summary.(effect_param{iT}).p_std = std(pp); % % val = struct.extract([BMA.effects],effect_param{iT}) ; % summary.(effect_param{iT}).val_mean = mean(val); % summary.(effect_param{iT}).val_std = std(val); % end
%% *_Branin Function_* % % Syntax: % Y = UQ_BRANIN(X) % Y = UQ_BRANIN(X,P) % % The model contains M=2 (independent) random variables (X=[X_1,X_2]) % and 6 scalar parameters of type double (P=[a,b,c,r,s,t]). % % Input: % X N x M matrix including N samples of M stochastic parameters % P vector including parameters % by default: a = 1; b = 5.1/(2*pi)^2; c = 5/pi; r = 6; s = 10; % t = 1/(8*pi); % % Output/Return: % Y column vector of length N including evaluations using branin % function % %%% function Y = uq_branin(X,P) %% Check % narginchk(1,2) assert(size(X,2)==2,'only 2 input variables allowed') %% Evaluation % % $$f(\mathbf{x}) = a(x_2 - bx_1^2 + cx_1 - r)^2 +s(1-t)\cos(x_1) +s$$ % if nargin==1 % Constants a = 1; b = 5.1/(2*pi)^2; c = 5/pi; r = 6; s = 10; t = 1/(8*pi); Y = a*(X(:,2) - b*X(:,1).^2 + c*X(:,1) - r).^2 + s*(1-t)*cos(X(:,1)) + s; end if nargin==2 Y = P(1)*(X(:,2) - P(2)*X(:,1).^2 + P(3)*X(:,1) - P(4)).^2 + P(5)*(1-P(6))*cos(X(:,1)) + P(5); end end
function varargout = colorSelector(varargin) % COLORSELECTOR MATLAB code for colorSelector.fig % COLORSELECTOR, by itself, creates a new COLORSELECTOR or raises the existing % singleton*. % % H = COLORSELECTOR returns the handle to a new COLORSELECTOR or the handle to % the existing singleton*. % % COLORSELECTOR('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in COLORSELECTOR.M with the given input arguments. % % COLORSELECTOR('Property','Value',...) creates a new COLORSELECTOR or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before colorSelector_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to colorSelector_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help colorSelector % Last Modified by GUIDE v2.5 25-Aug-2019 19:52:32 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @colorSelector_OpeningFcn, ... 'gui_OutputFcn', @colorSelector_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before colorSelector is made visible. function colorSelector_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to colorSelector (see VARARGIN) % Choose default command line output for colorSelector handles.output = hObject; handles.choose = [0, 0, 0]; imshow(ones(500,500,3)) % Update handles structure guidata(hObject, handles); % UIWAIT makes colorSelector wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = colorSelector_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) colorImage =ColorImage(10,10,50,50,[1,1, 0]); colorImage.setChoose(handles.choose); %gca(handles.axes1); colorImage.plot(true); handles.colorImage = colorImage; guidata(hObject, handles); % --- Executes on button press in checkboxRed. function checkboxRed_Callback(hObject, eventdata, handles) % hObject handle to checkboxRed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) choose = handles.choose; choose(1) = get(hObject, 'Value'); handles.colorImage.setChoose(choose); if(any(choose)) handles.colorImage.plot(false); else handles.colorImage.plot(true); end handles.choose = choose; guidata(hObject, handles); % Hint: get(hObject,'Value') returns toggle state of checkboxRed % --- Executes on button press in checkboxGreen. function checkboxGreen_Callback(hObject, eventdata, handles) % hObject handle to checkboxGreen (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) choose = handles.choose; choose(2) = get(hObject, 'Value'); handles.colorImage.setChoose(choose); if(any(choose)) handles.colorImage.plot(false); else handles.colorImage.plot(true); end handles.choose = choose; guidata(hObject, handles); % Hint: get(hObject,'Value') returns toggle state of checkboxGreen % --- Executes on button press in checkboxBlue. function checkboxBlue_Callback(hObject, eventdata, handles) % hObject handle to checkboxBlue (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) choose = handles.choose; choose(3) = get(hObject, 'Value'); handles.colorImage.setChoose(choose); if(any(choose)) handles.colorImage.plot(false); else handles.colorImage.plot(true); end handles.choose = choose; guidata(hObject, handles); % Hint: get(hObject,'Value') returns toggle state of checkboxBlue
ps = ProcessDays(psparse,'IntraGroup','Cells',ndresp.SessionDirs,'AnalysisLevel','AllIntraGroup'); InspectGUI(ps) figure; plot(ps) % compare mean lifetime sparseness and median population sparseness load sparsityobjs % get indices grouped according to site gind = groupDirs(sparseframe); % find sites with more than 1 cell since we need more than 1 cell to % compute population sparseness si = find(sum(~isnan(gind))>1) gind2 = gind(:,si); % get the sparseness data grouped according to site gdata = nanindex(sparseframe.data.sparsity,gind2) % find mean sparseness for each site gm = nanmean(gdata) pm = prctile(ps.data.psparse,50); % compute spree plot % first compute variance for each cell sfv = sparseframe.data.Values; sv = nanstd(sfv).^2; % now get variance for each site vdata = nanindex(sv,gind2); % find maximum variance mv = nanmax(vdata); % normalize by maximum variance vdata2 = flipud(sort(vdata ./ repmat(mv,size(vdata,1),1))); % data for 50 responsive cells plot([nan nan 0 1],vdata2(:,[1 3 4 10 13]),'go-','MarkerSize',16) hold on plot([nan 0 0.5 1],vdata2(:,[2 5 6 7 9 11 12]),'bo-','MarkerSize',16) plot([0 0.33 0.66 1],vdata2(:,8),'ro-','MarkerSize',16) hold off % data for 88 single units subplot(1,6,1) plot([nan nan nan nan nan 0 1],vdata2(:,[2 4 5 11 15 18 20]),'kx-','MarkerSize',16) set(gca,'TickDir','out','Box','off') % hold on subplot(1,6,2) plot([nan nan nan nan 0 0.5 1],vdata2(:,[3 10 12 14 16 21]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,3) plot([nan nan nan 0 0.33 0.66 1],vdata2(:,[1 17 19]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,4) plot([nan nan 0 0.25 0.50 0.75 1],vdata2(:,[6 13]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,5) plot([nan 0 0.2 0.4 0.6 0.8 1],vdata2(:,9),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,6) plot([0 0.16 0.33 0.5 0.66 0.83 1],vdata2(:,[7 8]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') % compute the area for 50 responsive cells vd2 = vdata2(:,[1 3 4 10 13]); vd3 = vdata2(:,[2 5 6 7 9 11 12]); vd4 = vdata2(:,8); a2 = 0.5 * (vd2(4,:) + 1); a3 = 0.5 * repmat(0.5,1,2) * (vd3(2:3,:) + vd3(3:4,:)); a4 = 0.5 * repmat(1/3,1,3) * (vd4(1:3,:) + vd4(2:4,:)); screarea = [a2 a3 a4]; mean(screarea) std(screarea) % compute the area for 88 single units vd2 = vdata2(:,[2 4 5 11 15 18 20]); vd3 = vdata2(:,[3 10 12 14 16 21]); vd4 = vdata2(:,[1 17 19]); vd5 = vdata2(:,[6 13]); vd6 = vdata2(:,9); vd7 = vdata2(:,[7 8]); a2 = 0.5 * (vd2(7,:) + 1); a3 = 0.5 * repmat(0.5,1,2) * (vd3(5:6,:) + vd3(6:7,:)); a4 = 0.5 * repmat(1/3,1,3) * (vd4(4:6,:) + vd4(5:7,:)); a5 = 0.5 * repmat(1/4,1,4) * (vd5(3:6,:) + vd5(4:7,:)); a6 = 0.5 * repmat(1/5,1,5) * (vd6(2:6,:) + vd6(3:7,:)); a7 = 0.5 * repmat(1/6,1,6) * (vd7(1:6,:) + vd7(2:7,:)); screarea = [a2 a3 a4 a5 a6 a7]; mean(screarea) std(screarea) % compute scree plots by first normalizing each cell to its mean so that we % can compare the variances across sites % create normalized scree plot sm = nanmean(sfv); % normalize the spike counts by the mean so the variances % between sites are equivalent sfv2 = sfv ./ repmat(sm,size(sfv,1),1); sv2 = nanstd(sfv2).^2; % now get variance for each site vdata3 = nanindex(sv2,gind2); % find maximum variance mv2 = nanmax(vdata3); % normalize by maximum variance vdata4 = flipud(sort(vdata3 ./ repmat(mv2,size(vdata3,1),1))); % plot for 50 responsive cells plot([nan nan 0 1],vdata4(:,[1 3 4 10 13]),'k:') hold on plot([nan 0 0.5 1],vdata4(:,[2 5 6 7 9 11 12]),'k--') plot([0 0.33 0.66 1],vdata4(:,8),'k-') hold off % plot for 88 single units subplot(1,6,1) plot([nan nan nan nan nan 0 1],vdata4(:,[2 4 5 11 15 18 20]),'kx-','MarkerSize',16) set(gca,'TickDir','out','Box','off') % hold on subplot(1,6,2) plot([nan nan nan nan 0 0.5 1],vdata4(:,[3 10 12 14 16 21]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,3) plot([nan nan nan 0 0.33 0.66 1],vdata4(:,[1 17 19]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,4) plot([nan nan 0 0.25 0.50 0.75 1],vdata4(:,[6 13]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,5) plot([nan 0 0.2 0.4 0.6 0.8 1],vdata4(:,9),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') subplot(1,6,6) plot([0 0.16 0.33 0.5 0.66 0.83 1],vdata4(:,[7 8]),'kx-','MarkerSize',16) set(gca,'YTickLabel','','TickDir','out','Box','off') % compute the area for 50 responsive cells vd2a = vdata4(:,[1 3 4 10 13]); vd3a = vdata4(:,[2 5 6 7 9 11 12]); vd4a = vdata4(:,8); a2a = 0.5 * (vd2a(4,:) + 1); a3a = 0.5 * repmat(0.5,1,2) * (vd3a(2:3,:) + vd3a(3:4,:)) a4a = 0.5 * repmat(1/3,1,3) * (vd4a(1:3,:) + vd4a(2:4,:)) screarea2 = [a2a a3a a4a]; mean(screarea2) std(screarea2) % compute the area for 88 single units vd2a = vdata4(:,[2 4 5 11 15 18 20]); vd3a = vdata4(:,[3 10 12 14 16 21]); vd4a = vdata4(:,[1 17 19]); vd5a = vdata4(:,[6 13]); vd6a = vdata4(:,9); vd7a = vdata4(:,[7 8]); a2a = 0.5 * (vd2a(7,:) + 1); a3a = 0.5 * repmat(0.5,1,2) * (vd3a(5:6,:) + vd3a(6:7,:)); a4a = 0.5 * repmat(1/3,1,3) * (vd4a(4:6,:) + vd4a(5:7,:)); a5a = 0.5 * repmat(1/4,1,4) * (vd5a(3:6,:) + vd5a(4:7,:)); a6a = 0.5 * repmat(1/5,1,5) * (vd6a(2:6,:) + vd6a(3:7,:)); a7a = 0.5 * repmat(1/6,1,6) * (vd7a(1:6,:) + vd7a(2:7,:)); screarea2 = [a2a a3a a4a a5a a6a a7a]; mean(screarea2) std(screarea2)
function [dat] = mainFrequencyAnalysis(dat); %H1 Line -- loop to calculate on frequency analysis on a structure array %Help Text -- %input requirements: dat is a structure array (output of impHYDAT) % %output details: dat, is the same arry entered in output with a filed that % contain the frequency analysis. The analysis is run for % each flow station. %Author: Laurence Chaput-Desrochers %date:august 19th 2013 %************************************************************************** nbFiles = size(dat,1); %compute log-PearsonIII frequency analysis %************************************************************************** for n = 1:nbFiles; [out,tableN] = logPearsonIIIgeV2(dat(n,1).discharges,dat(n,1).year); dat(n,1).freqDataPearson = tableN; dat(n,1).logPearsonIII = out; clear out tableN end%end loop n clear n %************************************************************************** end%end of function mainFrequancyAnalysis
function [ret] = showPossible(i_x, i_y) global board; thisPiece = board(i_x,i_y).possible; thisPiece(isnan(thisPiece)) = 0; ret = thisPiece; end
%Author : Vignesh Waren Sunder %Signal Digitisation and Reconstruction %Coded using MATLAB R2019a- academic use %GitHub: vicky-ML close all clc %Generating Signal t = 0:0.001:2; % set the time domain range (1 to 2 with 1000 steps) f1 = 6; f2 = 9; x = sin(2*pi*f1*t)+sin(2*pi*f2*t); %Sanalog figure subplot(211) plot(t,x); title("Sanalog") xlabel("Time(s)"); Fs = 100; %Our Sampling Frequency Ts = 1/Fs; n = 0:Ts:2; %set the time domain range x_sampled= sin(2*pi*f1*n)+sin(2*pi*f2*n); %Ssam subplot(212) stem(n,x_sampled,'fill'); title("Ssam"); xlabel("Time(s) Fs=100Hz"); %Quantisation maxx= max(x_sampled); %max value of Ssam minn = min(x_sampled); % min value of Ssam range = (maxx-minn)/16; % getting range with appropriate quatisation level %we perform "for" loop to get the y_axis value for each step in x_axis and %then round it to the nearest integer for n1 = 1:length(x_sampled) x_quant=round((x_sampled-minn)/range)*range+minn; end %Signal to quantisation noise ratio powerinsig = x_sampled.^2; %Power in Signal powerinnoise = (x_sampled-x_quant).^2; %Power in Noise sqnr = 10*log10 (powerinsig/powerinnoise); %SQNR figure plot(t,x); hold stairs(n,x_quant) title('Quantised') xlabel("Time(s)"); %fft %The value of Fs changes. Fs=100 for FFT of Ssamp | Fs=1000 for FFT of %Sanalog. Kindly change the value when running the code. xft = fft(x_sampled(1:length(x_sampled)-1)); %perform fft with a point delay(-1) arr=0:Fs/(2*Fs):Fs-Fs/(2*Fs); %To get the range of the frequency spectrum %(arr is 0 to 200 with 2000 steps) gives for one cycle %We generated and plotted Frequency spectrum only for One Cycle so that we %can easily perform FFTShift and extract the required frequency component xabs=abs(xft); %gives the magnitude figure subplot(211) plot(arr,xabs/Fs) title('FFT of Sanalog') xlabel("Frequency(Hz)"); ylabel("Magnitude"); xxftshift = fftshift(xft); %perform FFTShift subplot(212) plot(arr-0.5*Fs, abs(xxftshift)/Fs)%plot fftshift with desired range title("FFTShift of Sanalog"); xlabel("Frequency(Hz)"); ylabel("Magnitude"); %Low Pass Filter lpfilter = zeros (1,length(xxftshift)); %zero magnitude for this range for number1 = 1:length(xxftshift) %magnitude is 1 for these range of points if number1< 0.5*length(xxftshift) lpfilter(number1)=1; end end figure plot(arr,xabs/Fs.*lpfilter) %perform cyclic convolution by using point wise %multiplicaiton in Frequency domain. The required frequency signal is %extracted title("filtered spectrum Sanalog"); xlabel("Frequency(Hz)"); ylabel("Magnitude"); figure iff = ifft(xft/Fs.*lpfilter*2); %perform ifft with extracted signal from %the lpfilter %iff = ifft(xft/Fs); plot(n(1:length(n)-1),iff*Fs, 'r') %Plot the reconstructed Signal hold %stem(n,x_sampled,'fill'); %to get a stemed reconstructed signal output %hold plot(t,x, 'k') title("Reconstructed Signal and Sanalog") xlabel("Time (s)"); ylabel("Amplitude");
clc clear all; close all; global epsilon; global p; %ep = 0.001; eps = linspace(3,3,1); iter = linspace(1,1,1); epsilon = 0.01; op = odeset('reltol',1e-9,'abstol',1e-11); for i=iter figure(i) hold on; p=eps(i); epsilon = 0.1/(p^3) val = epsilon*(p^3) [t,y] = ode45('mms2d',[0,1000],0.01,op); plot(t,y,'DisplayName','p ='+string(p)); mean(y) %[t,y] = ode45('mms2d_avg',[0,400],0.01,op); %plot(t,y,'DisplayName','p_avg ='+string(p),'linewidth',2); %hold off; title('$\epsilon$ = '+string(epsilon),'interpreter','latex') xlabel('t') ylabel('x') legend end
function h = mrpln02b_PlotPairwiseFactorsInFG(fg, values, plot_flags) factor_color = plot_flags.factor_color; factor_line_width = plot_flags.factor_line_width; factor_linestyle = plot_flags.factor_linestyle; h = []; odometryPathXCoords = []; odometryPathYCoords = []; for i=0:double(fg.size)-1 if ~fg.exists(i), continue; end f = fg.at(i); keys = f.keys(); delta = abs(double(gtsam.mrsymbolIndex(keys.front()))-double(gtsam.mrsymbolIndex(keys.back()))); if delta == 1 % continue; % skip odometry factors for better visibility factor_linestyle = '-'; else continue % skip LC factors factor_linestyle = '--'; end edge = mrpln02c_PlotPairwiseFactor(f, values, factor_color, factor_line_width, factor_linestyle); h = [h edge]; if delta == 1 odometryPathXCoords = [odometryPathXCoords edge.XData]; odometryPathYCoords = [odometryPathYCoords edge.YData]; hold on; plot(edge.XData, edge.YData, 'Color', plot_flags.factor_color, 'LineWidth', plot_flags.factor_line_width+2) end end hold on; plot(odometryPathXCoords, odometryPathYCoords, '.', 'Color', plot_flags.factor_color, 'MarkerSize', 30) % mark observation poses
function second = Q_ra(x_1,x_1_r,x_2,x_2_r,P_a,P_b) % Eq. 4 in Ref.[2] second=P_b*(x_2-x_2_r)/((x_1-x_1_r+P_a*(x_2-x_2_r))^2+(P_b*(x_2-x_2_r))^2); end
%NAME: Jadeja Jaydevsinh G. %ROLL NO: 12MEC08 %BATCH: ME-2nd sem,2013 %DEPARTMENT: Electronics & Communication. %SUBJECT: ADC %1.Aim: To verify the nyquist theoram. close all; clear all; t=-10:0.01:10; T=8; fm=1/T; x=sin(2*pi*fm*t); subplot(311);plot(t,x); n=-10:1:10; j=ones(1,length(n)); subplot(312);stem(n,j);axis([-10 10 0 2]); xn=sin(2*pi*n*fm); subplot(313);stem(n,xn);hold on;plot(n,xn);
%% This code is the code of the part 3 %% Calcul of matrix Ks and Ms % function Part3(Samcef) close all run Dimensions run Geometry nElementT = 0; for i = 1 : 45 nElementT = nElementT + element(i,5); end nodeList = zeros(nElementT,3); basic_dofs = zeros(29,6); for i = 1:29 basic_dofs(i,:) = [(i-1)*6+1 (i-1)*6+2 (i-1)*6+3 (i-1)*6+4 (i-1)*6+5 (i-1)*6+6]; end nBeamG = 12; % number of big beams nBeamM = 29; % number of middel beams nBeamP = 4; % number of little beam for i = 1:45 dofList(((i-1)*element(i,5))+1,:) = basic_dofs(element(i,1),:); nodeList(((i-1)*element(i,5))+1,:) = Node(element(i,1),:); for j = 1:element(i,5)-2 dofList((element(i,5)*(i-1))+1+j,:) = (29*6+((i-1)*(element(i,5)-2)+j-1)*6)+(1:6); nodeList((element(i,5)*(i-1))+1+j,:) = Node(element(i,1),:) + ((Node(element(i,2),:)-Node(element(i,1),:))./(element(i,5)-1)*j); end dofList((i*element(i,5)),:) = basic_dofs(element(i,2),:); nodeList((i*element(i,5)),:) = Node(element(i,2),:); end for i = 1:45 for j = 1:element(i,5)-1 Kel(:,:,(i-1)*(element(i,5)-1)+j) = matriceRaideur(element(i,3), element(i,4), nodeList((i-1)*element(i,5)+j,:), nodeList((i-1)*element(i,5)+(j+1),:)); Mel(:,:,(i-1)*(element(i,5)-1)+j) = matriceMasse(element(i,3), element(i,4), nodeList((i-1)*element(i,5)+j,:), nodeList((i-1)*element(i,5)+(j+1),:)); end end % Assembly of the structural and mass matrices nNode = 0; for i = 1 : 45 nNode = nNode + element(i,5) - 2; end nNode = nNode + 29; Ks = zeros(nNode*6,nNode*6); Ms = zeros(nNode*6,nNode*6); for i = 1:45 for j = 1:element(i,5)-1 dofs1 = dofList((i-1)*element(i,5)+j,:); dofs2 = dofList((i-1)*element(i,5)+(j+1),:); locel = [dofs1 dofs2]; for k=1:12 for l=1:12 Ks(locel(k), locel(l)) = Ks(locel(k), locel(l)) + Kel(k,l,(i-1)*(element(i,5)-1)+j); Ms(locel(k), locel(l)) = Ms(locel(k), locel(l)) + Mel(k,l,(i-1)*(element(i,5)-1)+j); end end end end fixedDof = [10*6+1:10*6+6 11*6+1:11*6+6 12*6+1:12*6+6 13*6+1:13*6+6]; Ks(fixedDof, :) = []; Ks(:, fixedDof) = []; Ms(fixedDof, :) = []; Ms(:, fixedDof) = []; nb_vp = 10; % nombre de modes propres et valeurs propres à afficher clear Ms clear Ks Ms = [1 0; 0 1] Ks =[20000 -10000; -10000 20000] C = [3 -1; -1 3]; [V, D]=eigs(Ks, Ms, 2, 'sm'); w = sqrt(diag(D)); % [rad/s] f = w /2/pi; V2 = V; %% Calcul of parameters A = zeros(2, 2); epsR = zeros(2,1); epsR(:,1) = 0.005; result = zeros(2,1); gamma = zeros(2,1); mu = zeros(2,1); V2t = V2'; omega = 2*pi; result = A\epsR; %C = result(1)*Ks + result(2)*Ms; %% Codes run ComparisonStep run ComparisonSamcef run FRF
% Marco Bettiol - 586580 - BATCH SIZE ESTIMATE % % CBT Simple Test % % This script implements a simulation of the estimate obtained % using CBT in a batch of size n. % % Nodes are initially uniformily picked-up in the interval [0,1) clear all; close all; clc; n=16; % batch size disp(['Size :' int2str(n)]); nodes=rand(n,1); % virtual node with value 1 to get easier search algorithm % among the nodes % asc sorting nodes=[sort(nodes); 1]; if (n<2) error('BRA must start with a collision'); end % CBT Simulation % true if we got a success in the last transmission lastwassuccess=false; %false to end CBT waitforconsecutive=true; imax=length(nodes); %index of the first node in the batch imin=1; % index of the first node in the batch xmin=0; % starting interval [0,1/2) xlen=1/2; % we suppose a collision already occurred. while (waitforconsecutive) [e,imin,imax]=cbtsplit(nodes,imin,imax,xmin,xlen); % update next analyzed interval if(e==1) xmin=xmin+xlen; %xlen=xlen; elseif (e==0) xmin=xmin+xlen; xlen=xlen/2; else %xmin=xmin; xlen=xlen/2; end if (lastwassuccess==true && e==1) disp(' '); disp('CBT completed :'); disp(['Estimate :' num2str(1/xlen)]); disp(['Last node transmitting :' int2str(imin-1)]); waitforconsecutive=false; end if(e==1) lastwassuccess=true; else lastwassuccess=false; end end % DEBUG % estimate is given by the first serie of descending differences in the % nodes ID's dif=-1*ones(n-1,1); %negative init for i=1:n-1 dif(i)=nodes(i+1)-nodes(i); end nodes dif
function [A,X,res] = DN_NMF(Y,opts) %function [A,X,res] = nmf_qp_cg(Y,A,X,MaxIter,tol_c,lambda) % The Damped Newton (DN) algorithm developed by % Copyrirght R. Zdunek, A.-H. Phan, and A. Cichocki % % DN %% line 61 is changed defopts = struct('NumOfComp',[],'A0',[],'X0',[],'MaxIter',500,'Tol',1e-6,'lambda',1); % Theta maps checkStep. if ~exist('opts','var') opts = struct; end [r,A,X,MaxIter,tol_c,lambda] ... =scanparam(defopts,opts); if isempty(r) r=size(Y,2); end [I,T] = size(Y); epsil = eps; Y = max(eps,Y); n = 0; k = 0; if isempty(A) A=rand(I,r); end if isempty(X) X=rand(r,T); end % Number of components r = size(A,2); % Scaling da = sqrt(sum(A.^2,1))+eps; A = bsxfun(@rdivide,A,da); X = bsxfun(@times,da',X); k = 0; res = []; c = []; while k < MaxIter k = k + 1; % if ~mod(k,50) % disp(['Iteration: ',num2str(k)]); % end % UPDATES FOR A % ====================================================================== % Memory prelocation M = I*r; Q = spalloc(M,M,M*r); Q_tilde = spalloc(M,M,M*r); B = X*X'; C = X*Y'; Q = kron(speye(I),B); % Hessian of D(Y||AX) with respect to A Qd = zeros(M,1); At = A'; at = At(:); atp = at; GAt = B*A' - C; active = find((at <= epsil) & (GAt(:) > 0)); % active set degradated = find((at <= epsil) & (abs(GAt(:)) < epsil), 1); if ~isempty(degradated) disp(['Degenerate: ',num2str(k)]); end inactive = setdiff(1:length(at),active); % inactive set if ~isempty(active) a_tilde = at; a_tilde(active) = 0; c_tilde = C(:); c_tilde(active) = 0; Q_tilde = Q; Q_tilde(:,active) = 0; Q_tilde(active,:) = 0; Qd(active) = 1; Q_tilde = Q_tilde + spdiags(Qd,0,M,M) + lambda*speye(M); else a_tilde = at; Q_tilde = Q + lambda*speye(M); c_tilde = C(:); end % CGS tol = 1e-6 + exp(-k); at = zeros(M,1); Io = []; Ao = setdiff(1:M,Io); Qd = zeros(M,1); while ~isempty(Ao) [a_tilde,FLAG,RELRES,ITER] = pcg(Q_tilde,c_tilde,tol); Ao = find(a_tilde < 0); Q_tilde(Ao,:) = 0; Q_tilde(:,Ao) = 0; Q_tilde = Q_tilde + spdiags(Qd,0,M,M); c_tilde(Ao) = 0; end at = a_tilde; At = (max(epsil,reshape(at,r,I))); A = At'; da = eps+sqrt(sum(A.^2,1)); A = bsxfun(@rdivide,A,da); X = bsxfun(@times,da',X); % UPDATES FOR X % ====================================================================== HX = A'*A + 1e-12*eye(r); GX = HX*X - A'*Y; I_active = find((X < eps)&(GX > 0)); UX = GX; UX = HX\UX; UX(I_active) = 0; X = max(eps,X - UX); % Normalization % da = eps+sqrt(sum(A.^2,1)); % A = bsxfun(@rdivide,A,da); % X = bsxfun(@times,da',X); % dx = eps+sqrt(sum(X.^2,2)); X = bsxfun(@ldivide,dx,X); A = bsxfun(@times,dx',A); res(k) = norm(Y - A*X,'fro')/norm(Y,'fro'); % Stagnation breaking if k > 3 c(k) = res(k-1) - res(k); if (c(k)) < tol_c lambda = lambda/2; end if k > 30 & c(k) < 0 & c(k-1) < 0 & c(k-2) < 0 break end end end % while k
%clear % ---------------------------------------------------------------------- % % 実験設定。 % クエリ数を変更した際にはデータセットを新しく用意する必要があります。 % ---------------------------------------------------------------------- % %実験名 exName = 'ex1204stl'; %実験日 todaysDate = datetime('now','TimeZone','local','Format','yMMd'); % iExperiment: 何周目の実験か。パラメータ設定以外では使用しない for iExperiment = 1 % ---------------------------------------------------------------------- % %フォルダ(outputフォルダ & mファイル) [filepath, name, ext] = fileparts([mfilename('fullpath'),'.m']); Dir_kume = filepath; % モデルサイズの設定。有効な値は以下の通り。 % 16, 32, 40, 48, 56, 64, 80, 96 ModelSize = 40; % モデルサイズの設定。任意の値が有効。 imgSize = 64; % モデルタイプごとのクエリ数。基本5。 nQuery = 5; % データセットを新しく用意するかどうか。 % true - 用意する/false - 用意しない PrepareDataSet = false; % クエリ・データベースのGeodesic sphereのID。 DatabaseGeodesicID = 6; QueryGeodesicID = 6; % Geodesic: ID(1 〜 7)に対応する投影枚数。 % 例:Geodesic IDが1のとき,投影枚数は12枚。 nProjections = [12, 42, 92, 162, 252, 362, 492]; % ssht: ID(1001 〜 1016) generated by 'makePrjPointList_SSHT(L)' % mirror: ID(20XX) % nProjections = [1, 6, 15, 28, 45, 66, 91, 120, 153, 190, 231, 276, 325, 378, 435, 496] % % 1次元投影: ID に '-(マイナス)' を付ける generated by 'makePrjPointList_projection1d(gdid)' % 作成できた2次元投影を 'Projection1dFromProjection2d.m' に突っ込むと % マイナスを付ける前の ID の頂点に対応した1次元投影を求められる % % クエリ・データベースの部分空間の使用次元数。 rDatabase = 6; rQuery = 6; % 特徴の高周波成分削減回数。 nDivide = 0; % 結果を Excel に出力するためのパラメータ % 【対象のExcelファイルは開じる(開いてると書き込めない)】 % 【MacOS,Linux は非対応, 可能なら代わりにCSVファイルで出力される】 % Excel ファイル名(拡張子 '.xlsx' 忘れずに。上書き注意!) excelFileName = [exName, '_', char(todaysDate), '.xlsx']; % シート番号 sheet = iExperiment; % 書き込みを始めるセル % 例:[5,2] -> 'B5' から書き始める startCell = [1,1]; % 有効数字(Excelへの出力時、複素数のためにString型へ変換) precision = 6; % ---------------------------------------------------------------------- % current_path = pwd; cRetrieval = tic; % モデルタイプの名称とモデルタイプの数。 % 基本的にはClutch, Die, Gearの3種類。 % TypeName = {'Clutch'; 'Die'; 'Gear';}; % TypeName = {'clutch'; 'die'; 'gear';}; TypeName = {'clutch'; 'die'; 'gear'; 'mould'; 'hydraulic';}; % TypeName = {'clutch'; 'die'; 'gear'; 'mould'; 'hydraulic'; 'pvb'; 'steamtrap'; 'swashplate'; 'clutch_die'; 'die_gear'; 'gear_mould'; 'mould_clutch'; 'clutch_8'; 'keo'; 'morton';}; nModelType = length(TypeName); % 投影計算 & 処理時間計測 CulcProcessingTime_forSato(exName, DatabaseGeodesicID, QueryGeodesicID, imgSize, TypeName); % 投影の統合 [QueryProjection,DatabaseProjection] = InteglatePrj_forSato(exName, DatabaseGeodesicID, QueryGeodesicID, imgSize, TypeName); % %{ DatabaseName = fieldnames(DatabaseProjection); QueryName = fieldnames(QueryProjection); cDatabaseExtraction = tic; % データベース側の特徴抽出処理 disp('データベース側の特徴抽出処理を実行中'); for iDatabase = 1 : length(DatabaseName) tDatabaseProjection = DatabaseProjection.(DatabaseName{iDatabase}); % 投影画像の重み付け DatabaseWeightedProjection = ... WeightingProjection(tDatabaseProjection); % 特徴抽出処理 DatabaseFeature.(DatabaseName{iDatabase}) = ... DescriptorForMSM(DatabaseWeightedProjection, nDivide); end ExperimentTime.DatabaseExtraction = toc(cDatabaseExtraction); fprintf('処理時間:%f[s]\n', ExperimentTime.DatabaseExtraction); % データベース側の部分空間の生成 cDatabaseSubspace = tic; disp('データベース側の部分空間生成処理を実行中'); for iDatabase = 1 : length(DatabaseName) tDatabaseFeature = DatabaseFeature.(DatabaseName{iDatabase}); LabelList = fieldnames(tDatabaseFeature); for iLabel = 1 : length(LabelList) [tDatabaseSubspace] = ... EVD(tDatabaseFeature.(LabelList{iLabel}), rDatabase); DatabaseSubspace.(DatabaseName{iDatabase}).(LabelList{iLabel}) = ... tDatabaseSubspace; end end ExperimentTime.DatabaseSubspace = toc(cDatabaseSubspace); fprintf('処理時間:%f[s]\n', ExperimentTime.DatabaseSubspace); cQueryExtraction = tic; % クエリ側の特徴抽出処理 disp('クエリ側の特徴抽出処理を実行中'); for iQuery = 1 : length(QueryName) tQueryProjection = QueryProjection.(QueryName{iQuery}); % 投影画像の重み付け QueryWeightedProjection = ... WeightingProjection(tQueryProjection); % 特徴抽出処理 QueryFeature.(QueryName{iQuery}) = ... DescriptorForMSM(QueryWeightedProjection, nDivide); end ExperimentTime.QueryExtraction = toc(cQueryExtraction); fprintf('処理時間:%f[s]\n', ExperimentTime.QueryExtraction); % クエリ側の部分空間の生成 cQuerySubspace = tic; disp('クエリ側の部分空間生成処理を実行中'); for iQuery = 1 : length(QueryName) tQueryFeature = QueryFeature.(QueryName{iQuery}); LabelList = fieldnames(tQueryFeature); for iLabel = 1 : length(LabelList) [tQuerySubspace] = ... EVD(tQueryFeature.(LabelList{iLabel}), rQuery); QuerySubspace.(QueryName{iQuery}).(LabelList{iLabel}) = ... tQuerySubspace; end end ExperimentTime.QuerySubspace = toc(cQuerySubspace); fprintf('処理時間:%f[s]\n', ExperimentTime.QuerySubspace); Similarity = zeros(length(QueryName), length(DatabaseName)); % 各モデルとクエリとの類似度を格納する配列。 ExperimentTime.Matching = 0; disp('モデル間の距離を相互部分空間法によって計算中'); for iQuery = 1 : length(QueryName) tQuerySubspace = QuerySubspace.(QueryName{iQuery}); for iDatabase = 1 : length(DatabaseName) tDatabaseSubspace = DatabaseSubspace.(DatabaseName{iDatabase}); % データベースモデルとの距離を計算 cMatching = tic; LabelList = fieldnames(tQuerySubspace); % 部分空間による距離計算 tSimilarity = 0; for iLabel = 1 : length(LabelList) U = tQuerySubspace.(LabelList{iLabel}); V = tDatabaseSubspace.(LabelList{iLabel}); tSimilarity = tSimilarity + MSM(U, V); end tSimilarity = tSimilarity / length(LabelList); Similarity(iQuery, iDatabase) = tSimilarity; ExperimentTime.Matching = ExperimentTime.Matching + toc(cMatching); end end fprintf('処理時間:%f[s]\n', ExperimentTime.Matching); % 正解率を算出する。 for iModelType = 1 : nModelType TrueModelIndex = 5 * (iModelType - 1) + (1:5)'; TopIndex = nQuery * (iModelType - 1) + 1; BottomIndex = nQuery * iModelType; tSimilarity = Similarity(TopIndex : BottomIndex, :); [~, MinIndex] = min(tSimilarity, [], 2); Accuracy.(TypeName{iModelType}) = sum(MinIndex == TrueModelIndex) / nQuery; end ExperimentTime.Total = toc(cRetrieval); fprintf('プログラム全体の処理時間:%f[s]\n', ExperimentTime.Total); % 結果を構造体としてまとめる。 ExperimentResult.SimilarityMatrix = Similarity; ExperimentResult.Accuracy = Accuracy; ExperimentResult.ExperimentTime = ExperimentTime; % データセットを構造体としてまとめる。 %DataSet.ShiftVector = ShiftVector; %DataSet.RotateVector = RotateVector; % 結果を保存する。 FileName = sprintf('Result_GDID_D%dQ%d_Query%d_%s', ... DatabaseGeodesicID, QueryGeodesicID, nQuery, exName); % save(FileName, 'ExperimentResult', 'DataSet'); save([Dir_kume, filesep, FileName], 'ExperimentResult'); % 結果を Excel にまとめる bodyStruct = ExperimentResult; % output structure headerStruct = struct; headerStruct.exName = exName; headerStruct.DatabaseGeodesicID = DatabaseGeodesicID; headerStruct.QueryGeodesicID = QueryGeodesicID; headerStruct.nQuery = nQuery; headerStruct.matfile = [FileName,'.mat']; savePath = [Dir_kume, filesep, excelFileName]; saveStructure(savePath,bodyStruct,headerStruct,startCell,sheet,precision); % ---------------------------------------------------------------------- % %} end % for iExpetiment
function [ array_stddev, array_mean ] = my_stddev( one_dim_array ) % pusing bro, ada obat nyamuk? % dapatkan panjang array n_array = length(one_dim_array); % dapatkan nilai mean array_mean = my_mean(one_dim_array); % dapatkan stddev kuadrat stddev_sum = 0; for i = 1:n_array stddev_sum = stddev_sum+((one_dim_array(i)-array_mean)^2); end array_stddev = sqrt(stddev_sum/n_array); end
%% A. Benchmark ngrid=8361; grouprankmtgppv7alls120g8361mars=zeros(ngrid,12); for ns=1:ngrid [transdat,lambda] = boxcox((senscoreMARSgppv7alls120g8361(ns,:)+1)'); Y = pdist(transdat); Z = linkage(Y,'ward'); [~,T] = dendrogram(Z,4); orimax=zeros(4,1); for i=1:4 orimax(i,1)=max(transdat(find(T==i))'); end [stmax,index]=sort(orimax); tT=T; for i=1:4 tT(find(T==index(i)),1)=5-i; end grouprankmtgppv7alls120g8361mars(ns,:)=tT; end % Group rank statistics grouprankfreqgppv7alls120g8361=zeros(4,12); for i=1:4 for j=1:12 for k=1:ngrid if (grouprankmtgppv7alls120g8361mars(k,j)==i) grouprankfreqgppv7alls120g8361(i,j)=grouprankfreqgppv7alls120g8361(i,j)+1; end end end end finalgrouprankgppv7alls120g8361=zeros(1,12); for i=1:12 finalgrouprankgppv7alls120g8361(i)=find(grouprankfreqgppv7alls120g8361(:,i)==max(grouprankfreqgppv7alls120g8361(:,i))); end finalgridportiongppv7alls120g8361=zeros(1,12); for i=1:12 finalgridportiongppv7alls120g8361(i)=grouprankfreqgppv7alls120g8361(finalgrouprankgppv7alls120g8361(i),i)/ngrid; end
%Q6* function [image, correctLabel, predictedLabel] = PredictTest (n) allTrainImages = loadMNISTImages('./train-images.idx3-ubyte'); allTrainLabels = loadMNISTLabels('./train-labels.idx1-ubyte'); mdl = fitcknn(allTrainImages', allTrainLabels); allTestImages = loadMNISTImages('./t10k-images.idx3-ubyte'); allTestLabels = loadMNISTLabels('./t10k-labels.idx1-ubyte'); image = allTestImages(:, n); predictedLabel = predict(mdl, image'); correctLabel = allTestLabels(n); image = reshape(image, 28, 28); end
function s = accuracy(x,y,value) [ m, n ] = size(x); if ( n != 1) error('x is not a column vector'); endif [ m, n ] = size(y); if ( n != 1) error('y is not a column vector'); endif if (length(x) != length(y)) error('inputs column vectors x and y should have the same length'); endif R = x >= value; TP = sum(R.*y); TN = sum((1-R).*(1-y)); s = (TP+TN)/m; endfunction
function [ digit ] = FindDigit( I ) dir = 'letters/'; ext = '.bmp'; max_coeff = -2; for i = 1:10 im = imread([dir sprintf('%d', i-1) ext]); coeff = corr2(im, I); if coeff > max_coeff max_coeff = coeff; digit = i-1; end end end
function saveAsAvi_AI_ratio(matFilesPath, matFilesPrefix, aviFilesPath, aviFilesPrefix, ... radius, nSides) %% saving a video for changing activator/inhibitor levels % in the colony. files = dir([matFilesPath filesep matFilesPrefix '*.mat']); nTimePoints = numel(files); videoPath = [aviFilesPath filesep aviFilesPrefix '_' matFilesPrefix]; %% fig = figure; set(fig, 'Position', [68 800 500 400]); fullVideoPath = [videoPath '.avi']; v = VideoWriter(fullVideoPath); v.FrameRate = 5; open(v); counter = 1; for ii = 1:nTimePoints outputFile = [matFilesPath filesep matFilesPrefix '_t' int2str(ii) '.mat']; load(outputFile, 'storeStates'); if ii == 1 % get the colony boundary nSquares = size(storeStates,1); edgeLength = 1; lattice = false(nSquares); [~, ~, colonyState] = specifyColonyInsideLattice(lattice, radius, nSides); [colonyEdgeIdx] = specifyRegionWithinColony(colonyState, edgeLength); end timeSteps = size(storeStates,4); for kk = [1:timeSteps] % each file has multiple timesteps activator = storeStates(:,:,1,kk); inhibitor = storeStates(:,:,2,kk); values = inhibitor./activator; values(isnan(values)) = 0; values = values.*colonyState; imagesc(values); colorbar; caxis([0 5]); title(['activator/inhibitor' 't=' int2str(counter)]); counter = counter+1; % if component == 1 % caxis([0 1.1]); % elseif component < 3 % caxis([0 2.5]); % else % caxis([0 0.5]); % end hold on; plot(colonyEdgeIdx(:,2), colonyEdgeIdx(:,1), 'k.', 'MarkerSize', 8); axis off; drawnow; pause(0.01); M = getframe(fig); writeVideo(v,M); end end close(v); end
clear % For plotting h = figure; hold on; grid on; title('Earth temperature vs albedo'); xlabel('Temperature (K)'); ylabel('Albedo'); % Variables alpha = 0; % Albedo - describes how much sunlight Earth reflects. sigma = 5.67 * 1e-8; % Stefan-Boltzmann constant - total intensity. I = 344; % Incident - short-wave radiation from the sun. % Base function - balance between amount of emitted/absorbed energy: % (1 - alpha) * I = sigma * T^4 % Case 1: % When temperature on Earth is T1 = 235 K, % then alpha is 0.5 (high albedo - there is ice and clouds reflecting sun). alpha1 = 0.5; T1_mean = nthroot((1-alpha1)*I/sigma, 4); % 234 K line([200 250],[alpha1 alpha1],'LineWidth',1); % Case 2: % When temperature is between 250 and 270 K, then albedo has functional % dependency of (270 - T) / 40. After solving balance equation and summing % temperatures, then mean is 259 K. T2 = 250:1:270; alpha2 = (270 - T2) / 40; syms T; % Define symbol for solving equation eqnLeft = T; % Left side of equation eqnRight = nthroot((1-(270 - T) / 40)*I/sigma, 4); % Right side of equation initialGuess = 300; % Initial guess where solution converges to 260 K. T_mean = vpasolve(eqnLeft == eqnRight, T, initialGuess); % 260 K plot(T2, alpha2); % Case 3: % When temperature on Earth is T3 = 280 K, % then alpha is 0 (low albedo - no ice and clouds reflecting sun). alpha3 = 0; T3_mean = nthroot((1-alpha3)*I/sigma, 4); % 279 K line([270 300],[alpha3 alpha3],'LineWidth',1); % Save plot to file saveas(h, 'ex4','jpg'); % Summary: % In first case average temperature is 234 K, % in second case 259 K % and in third case 279 K.
% lds_switchyard.m (by Andrew Cvitanovich - 5/5/2012) % script with functions to set up Lag Discrimination Suppression Exp't using free field % PDR measurements % Depends: playrecord_LDS (C program that interfaces with the TDT System II DSP) % AlexMenu.m (menu script), AlexMenu.fig (figure) % run_lds_pdr.m (script to "run" the experiment) % Description of Variables: % PDR - Structure containing parameters for the session % including sounds used in the session ... % and speaker filter coefficients! % note: These parameters are set up by the setDefaults() function % vars2pass - variables to pass on to playrecord_LDS % Functions: % lds_switchyard() - calls subfunctions in this file % setDefaults() - sets up default values for all variables % getBBN() - makes a BBN for sound production % AMStim() - makes stimuli for the session % randPlusMinux() - randomly produces +/-1 % note: remember to check that "state" values are the ones you want for % reproducible sounds!!! function [varargout] = lds_switchyard(fcn,varargin) global PDR % Call as: lds_switchyard(fcn); switch fcn case 'run_calibration' quit_flag = feval(fcn); varargout{1} = quit_flag; otherwise feval(fcn); % no special inputs or outputs end function setDefaults() global PDR if(~ispc) code_path='/Users/cvitanovich/Documents/MATLAB/LDS_PDR/'; data_path='/Users/cvitanovich/Documents/MATLAB/data/'; else code_path='c:\alex\code\LDS_PDR\'; data_path='C:\alex\data\'; end cd(code_path); PDR = struct(... % MAIN PARAMETERS: 'DEBUG',1,... 'bird_id',1073,... % bird's id # 'info_pts',2,... % first 2 points in the (decimated) buffer reserved for trial info ... % for example, if testing MAAs a comment should go here 'maa_test_flag',0,... % set to one if testing MAAs 'virtual',0,... % Freefield: virtual = 0, Headphones: virtual = 1 'record',1,... % flag for recording pdr trace 'jitter',2,... % jitter trial occurance (2 bufs = +/- 1.34 s) 'ntrials',[],... % no. of trials in a session 'npretrials',100,... % default # of habituating trials before the 1st test trial 'n_test_trials',15,... % default # of test trials in a session 'buf_pts',32768,... % # points in a buffer - 32768 pts for a 0.671 second buffer (Fs = 48828 Hz) 'buf_dur',[],... % buffer duration in ms 'isi_buf',15,... % number of empty buffers between trials (10 buffers gives an ISI of ~6.71s (+/-1.34 s) using .671 sec sounds) 'isi_time',[],... % time between trial buffers in seconds (calculated) 'decimationfactor',5,... % decimation factor for data collection (using 4 will give 1875Hz sampling rate) 'stim_Fs',48828,... % sampling rate for sound production 'npts_totalplay',[],... % total no. pts in the session 'len_session',[nan nan], ... % length of session (in minutes) 'starttime',[], ... % session start time 'stoptime', [], ... % session stop time 'code_path',code_path,... % path to code 'data_path',data_path,... % flag indicates that AD recording (pupillometer) will be needed 'base_atten',0,... % attenuation value to send to TDT 'filename',[],... % file name for storing session data 'exit_flag',0,... % exit session (quit) flag 'plot_trials_handle',[],... % handles for the menu plots 'plot_sounds_handle',[],... 'outlier_separation',100,... % defines angular separation considered to be "extreme outlier" 'outlier_fraction',[],... % fraction of test trials that are outliers (10% seems fine) 'n_outlier_trials',0,... % fraction of tests that are outliers 'RPs',[],... % store response probabilities (From Nelson AM study) ... ... % LEAD SOUND PARAMETERS: 'LEAD_pos',-60,... % default azimuth (degrees) for lead sound 'LEAD_sounds',[],... % LEAD_sounds sound (to be calculated) 'LEAD_default_scale',0,... % will be set to zero for MAA testing ... % otherwise, lead/lag scales should be identical ... ... % LAG SOUND PARAMETERS: 'LAG_hab_pos',-50,... % default azimuth for lag sound 'LAG_sounds',[],... % lag sound (to be calculated) 'LAG_default_scale',0,... % lead and lag should have same scale (unless testing MAAs) ... ... % TEST SOUND PARAMETERS: 'TEST_azimuths',[-25 -5 5 15 30],... %45 60],... % SHOULD BE IN ORDER FROM SMALLEST TO GREATEST SEPARATION!!!! 'TEST_trial_jitter',5,... % jitter (test trials) 'TEST_trial_freq',30,... % default frequency of test trials (1 out of every X trials) ... ... % SOUND PARAMETERS: 'CARRIERS_SWITCHED',0,... % if the delay is negative this flag will be set to one! (LEAD <-> LAG carriers switched if one) 'SOUNDS_rms',0.5,... % setting envelopes to 0.5 rms amplitude (equalizes sound envelope magnitudes) 'SOUNDS_radius',152,... % the distance from the speakers to the owl's head position (in cm) 'SOUNDS_calib_fname',[],... % filename for speaker calibration parameters 'SOUNDS_SPL',60,... % target decibel level (intraural) for speaker 'SOUNDS_num_speakers',7,... % number of speakers (including lead speaker) available 'SOUNDS_speaker_scales_lead',[],... % list of calibrated scale values for lead speaker (matched to each lag) 'SOUNDS_speaker_scales_lag',[],... % list of calibrated scale values for lag speaker 'SOUNDS_lead_attens',[],... %attens for lead speaker 'SOUNDS_elevations',[0 0 0 0 0 0 0],... %0 0],... 'SOUNDS_speaker_numbers',1:7,... 'SOUNDS_azimuths',[-60 -50 -25 -5 5 15 30],... % 45 60],... % actual speaker azimuths (don't change unless moving speakers) 'SOUNDS_length',100,... % length of sounds in ms 'SOUNDS_carrier_delay',-3,... % ongoing CARRIER disparity between lead/LAG_sound sounds 'SOUNDS_env_delay',0,... % ongoing ENVELOPE disparity (lead/lag) 'SOUNDS_mix',0,... % mix fraction 'SOUNDS_env_correlations',[],... % calculated correlation coefficient (envelopes) 'SOUNDS_states',[795 4932 4584],...% state values for random no generator (to ensure that sounds are reproducible) ... % formatted as such: [env_state decorr_env_state1 decorr_env_state2] 'SOUNDS_carrier_states',[],... % carrier states (to rove the carrier) 'SOUNDS_num_carriers',10,... % number of carriers to rove (should be 10, don't change!) 'SOUNDS_rand_states',[],... % list of random state values (from Caitlin/Brian head saccade exp't) 'SOUNDS_rove_sequence',[],... % random ordering sequence to rove sounds 'SOUNDS_carrier_bandwidth',[2000 11000],... % using 2 - 11 kHz bandwidth for carriers (same as Caitlin/Brian head saccade exp't) 'SOUNDS_env_bandwidth',[1 150],... % bandwidth of envelopes (should be 1 to 150 Hz to replicate Nelson/Baxter study) 'SOUNDS_amplitude',60,... % Keep at 60 (this gives amplitudes suitable for the TDT) 'SOUNDS_env_depth',100,... % depth of envelope modulation 'SOUNDS_ramp',5,... % ramp length for sounds (ms) 'SOUNDS_location_sequence',[]); % sequence of locations for the session (1st row: lead, 2nd row: lag) % Comments box: PDR.comments = cell(3,1); for j=1:length(PDR.comments) PDR.comments{j}=''; end % These are the random SOUNDS_states from Baxter, et al. RandStates = [... 73 167 617 364 662 593 538 194 853 610 294 ... 479 71 105 162 770 143 116 252 101 377 706 ... 273 574 915 661 935 355 530 540 220 232 886 ... 70 65 571 35 339 87 281 795 283 974 248 ... 995 936 769 943 127 224]; PDR.SOUNDS_rand_states=RandStates; % check if testing MAAs if PDR.maa_test_flag PDR.LEAD_default_scale = 0; end % setup cell array for lead/lag sounds PDR.LEAD_sounds=cell(1,PDR.SOUNDS_num_carriers); PDR.LAG_sounds=cell(1,PDR.SOUNDS_num_carriers); q=clock; y=num2str(q(1));y=y(3:4); m=num2str(q(2));if size(m,2)<2;m=['0' m];end d=num2str(q(3));if size(d,2)<2;d=['0' d];end PDR.filename= [num2str(PDR.bird_id) '_LDS_' y m d '_a']; %930=m 929=l 882=d 883=e (a is index to experiment number for that day) calcSessionLen; function calcSessionLen() global PDR % calculate length of session: tmp = (PDR.npretrials + PDR.TEST_trial_freq*PDR.n_test_trials)... *(PDR.isi_buf+1)*(PDR.buf_pts/PDR.stim_Fs); % length in seconds PDR.len_session(1)=floor(tmp/60); % Calculate length of session (in minutes)! PDR.len_session(2)=round(tmp-floor(tmp/60)*60); % seconds function setupTrials() global PDR %disp('Setting up Trial Sequence') % SETUP randomized trial IDs ntrials = PDR.npretrials + PDR.TEST_trial_freq*PDR.n_test_trials; PDR.SOUNDS_location_sequence = NaN*ones(2,ntrials+1); PDR.SOUNDS_location_sequence(1,:) = PDR.LEAD_pos*ones(1,ntrials + 1); % lead positions in first row PDR.SOUNDS_location_sequence(2,:) = PDR.LAG_hab_pos*ones(1,ntrials + 1); % lag positions in second row TEST_trial_jitter = PDR.TEST_trial_jitter; no_angles = length(PDR.TEST_azimuths); % create a trial sequence and convert to location sequence % (2 rows, 1st row= El, 2nd row = Az) %PDR.n_outlier_trials = round(PDR.outlier_fraction*PDR.n_test_trials); separations=PDR.TEST_azimuths - PDR.LAG_hab_pos; outlier_IDs=find(abs(separations)>=PDR.outlier_separation); not_outlier_IDs=find(abs(separations)<PDR.outlier_separation); rep_freq=5; % don't repeat an outlier speaker location less than 7 test trials apart rand_list = randomized_trials(not_outlier_IDs,outlier_IDs,PDR.n_outlier_trials,PDR.n_test_trials,rep_freq); last_test=NaN; if length(rand_list) == 0 return; end % create list of locations with randomized test locs cnt = PDR.npretrials; % skip pretrials id = 0; while cnt < ntrials cnt = cnt + PDR.TEST_trial_freq; id = id + 1; PDR.SOUNDS_location_sequence(2,cnt)=PDR.TEST_azimuths(rand_list(id)); cnt = cnt + round(TEST_trial_jitter*rand); % jitter test trial occurances (if requested) if cnt >= (ntrials-PDR.TEST_trial_freq) break; end end % setup rove sequence: num_snds=PDR.SOUNDS_num_carriers; PDR.SOUNDS_rove_sequence = ceil(num_snds-num_snds*rand(1,ntrials+1)); function [trial_list] = randomized_trials(not_outlier_IDs,outlier_IDs,nOutliers,nTests,rep_limit) outlier_list = []; nOutlierTypes = length(outlier_IDs); if nOutliers >0 for i1=1:ceil(nOutliers/nOutlierTypes) outlier_list((i1-1)*nOutlierTypes+1:i1*nOutlierTypes)=outlier_IDs; end outlier_list = outlier_list(1:nOutliers); end not_outlier_list = []; nNotOutlierTypes = length(not_outlier_IDs); for i2=1:ceil((nTests-nOutliers)/nNotOutlierTypes) not_outlier_list((i2-1)*nNotOutlierTypes+1:i2*nNotOutlierTypes)=not_outlier_IDs; end not_outlier_list = not_outlier_list(1:(nTests-nOutliers)); total_list = [outlier_list not_outlier_list]; chk2=0; cnt=0; IDs = sort(unique(total_list)); while ~chk2 chk2=1; trial_list = total_list(randperm(length(total_list))); for i2=outlier_IDs df_list = diff(find(trial_list==i2)); if find(df_list < rep_limit) chk2=0; end end % check for repeated speakers for i2=IDs df_list = diff(find(trial_list==i2)); if find(df_list == 1) chk2=0; end end cnt=cnt+1; if cnt>10000 hWarn=warndlg('Cannot find a randomized trial list with these parameters!'); uiwait(hWarn); trial_list=[]; return; end end function AMStim() % Note: Noise1 is lead and Noise2 is lag % AMStim (Adapted from Caitlin/Brian's head turn exp't) % Generate stimuli for LDS session global PDR PDR.RPs=[]; %////////////////////////////////////////// % low pass filter design: fc=150; fs=PDR.stim_Fs; order=2; [Bs,As]=filt_butter(fc,fs,order); % Make stimulus or stimuli SR = PDR.stim_Fs; % Increase duration by delay % so that the stimuli can be gated/windowed (see below) StimDur = PDR.SOUNDS_length + PDR.SOUNDS_carrier_delay; % should be in ms, add delay %for sound generation (creates extended BBN that is then curtailed to %the desired duration) % Use PAD = 10 for sounds with less than 250ms total duration! % Otherwise use PAD = 1 if StimDur <= 250 PAD = 10; else PAD = 1; end StimPnts = round((StimDur/1000)*SR); DelayPnts = round((PDR.SOUNDS_carrier_delay/1000)*SR); DelayPnts = max(1,DelayPnts); numsnds=length(PDR.SOUNDS_rand_states); % create a family of sounds the same envelope parameters, but with % different carriers hWait = waitbar(0,'Generating Sounds'); for i0=1:numsnds % Make Noise #1 x = getBBN(PDR.SOUNDS_rand_states(i0), SR, StimDur, PDR.SOUNDS_carrier_bandwidth(1), PDR.SOUNDS_carrier_bandwidth(2)); % scale to RMS = 0.23591 !!!!!!!! x=rms_scale(x,target_rms); Noise1 = x(1:StimPnts)'; % Scale to desired amplitude Noise1 = Noise1 * 50; % scale by 50 so that speaker scaling factors aren't too big (well, small)! Noise1 = Noise1 * 10^(PDR.SOUNDS_amplitude/20)*0.00002; % amplitude re: 20 uPa % copy Noise #1 to make Noise #2 Noise2 = Noise1; % Make Envelope #1 Env1 = getBBN(PDR.SOUNDS_states(1), SR, PAD*StimDur, PDR.SOUNDS_env_bandwidth(1), PDR.SOUNDS_env_bandwidth(2)); Env1 = Env1(1:StimPnts)'; Env1 = Env1 - min(Env1); Env1 = Env1 / max(Env1); % normalize Env1 = Env1 .* (PDR.SOUNDS_env_depth/100); % AM depth (as a percent) Env1 = Env1 + 1 - (PDR.SOUNDS_env_depth/100); % copy Envelope #1 to make Envelope #2 Env2 = Env1; % get de-correlateing envelope #1 DCEnv1 = getBBN(PDR.SOUNDS_states(2), SR, PAD*StimDur, PDR.SOUNDS_env_bandwidth(1), PDR.SOUNDS_env_bandwidth(2)); DCEnv1 = DCEnv1(1:StimPnts); DCEnv1 = DCEnv1 - min(DCEnv1); DCEnv1 = DCEnv1 / max(DCEnv1); % normalize DCEnv1 = DCEnv1 .* (PDR.SOUNDS_env_depth/100); % AM depth (as a percent) DCEnv1 = DCEnv1 + 1 - (PDR.SOUNDS_env_depth/100); % get de-correlateing envelope #2 DCEnv2 = getBBN(PDR.SOUNDS_states(3), SR, PAD*StimDur, PDR.SOUNDS_env_bandwidth(1), PDR.SOUNDS_env_bandwidth(2)); DCEnv2 = DCEnv2(1:StimPnts); DCEnv2 = DCEnv2 - min(DCEnv2); DCEnv2 = DCEnv2 / max(DCEnv2); % normalize DCEnv2 = DCEnv2 .* (PDR.SOUNDS_env_depth/100); % AM depth (as a percent) DCEnv2 = DCEnv2 + 1 - (PDR.SOUNDS_env_depth/100); % ** mix de-correlateing envelopes in with original envelopes ** Env1DC = ((1-PDR.SOUNDS_mix).*DCEnv1) + ((PDR.SOUNDS_mix).*Env1); Env2DC = ((1-PDR.SOUNDS_mix).*DCEnv2) + ((PDR.SOUNDS_mix).*Env2); % !!! re-normalize the envelopes Env1DC = Env1DC - min(Env1DC); Env1DC = Env1DC / max(Env1DC); % normalize Env1DC = Env1DC .* (PDR.SOUNDS_env_depth/100); % AM depth (as a percent) Env1DC = Env1DC + 1 - (PDR.SOUNDS_env_depth/100); Env2DC = Env2DC - min(Env2DC); Env2DC = Env2DC / max(Env2DC); % normalize Env2DC = Env2DC .* (PDR.SOUNDS_env_depth/100); % AM depth (as a percent) Env2DC = Env2DC + 1 - (PDR.SOUNDS_env_depth/100); % Delay to make "lead" and "lag" % DO NOT SHIFT ENVELOPES!!! (only carriers have a delay) Noise1 = [Noise1 zeros(1,DelayPnts)]; Noise2 = [zeros(1,DelayPnts) Noise2]; % window (i.e., gate) out onset/offset time disparity % DO NOT SHIFT ENVELOPES!!! (only carriers have a delay) if(PDR.SOUNDS_carrier_delay>=0) Noise1 = Noise1(DelayPnts:StimPnts); Noise2 = Noise2(DelayPnts:StimPnts); else PDR.CARRIERS_SWITCHED=1; Noise2 = Noise1(DelayPnts:StimPnts); Noise1 = Noise2(DelayPnts:StimPnts); end % Fix envelope points to match carriers! Env1DC = Env1DC(1:length(Noise1)); Env2DC = Env2DC(1:length(Noise2)); % ramp envelopes on/off Env1DC = rampSounds(Env1DC, SR, PDR.SOUNDS_ramp); % stim envelope Env2DC = rampSounds(Env2DC, SR, PDR.SOUNDS_ramp); % stim envelope % set rms amplitude for envelopes: Env1DC=rms_scale(Env1DC,PDR.SOUNDS_rms); Env2DC=rms_scale(Env2DC,PDR.SOUNDS_rms); % CALCULATE CORRELATION COEFFICIENTS (Final LEAD/LAG Envelopes) % get hilbert envelope (lead): env1(i0,:)=abs(hilbert(Noise1 .* Env1DC)); % butterworth lowpass filter (lead): for y0=1:size(Bs,1); env1(i0,:)=filter(Bs(y0,:),As(y0,:),env1(i0,:)); end % get hilbert envelope (lag); env2(i0,:)=abs(hilbert(Noise2 .* Env2DC)); % butterworth lowpass filter (lag): for y1=1:size(Bs,1); env2(i0,:)=filter(Bs(y1,:),As(y1,:),env2(i0,:)); end % calculate correlation coefficient (lead/lag) for filtered hilbert % envelopes (this is the true envelope after convolving with % carrier) R=corrcoef(env1(i0,:),env2(i0,:)); Res(i0)=R(2,1); PDR.SOUNDS_env_correlations{i0} = R(2,1); % correlation coefficients % CALCULATE RP: [leadP, lagP] = SpikeProbAM(env1(i0,:),env2(i0,:),PDR.stim_Fs); PDR.RPs(i0)= leadP/(leadP+lagP); % multiply with envelopes Noise1 = Noise1 .* Env1DC; Noise2 = Noise2 .* Env2DC; LEAD_sounds{i0} = Noise1; LAG_sounds{i0} = Noise2; waitbar(i0/numsnds,hWait); end close(hWait); if(PDR.SOUNDS_carrier_delay<0) h=warndlg('Lead/Lag Carriers Switched!!!'); uiwait(h); end % find the most highly correlated sounds (low pass filtered hilbert % envelopes) clims=[-1 1]; R0=corrcoef(env1'); for q0=1:numsnds R0(q0,q0)=-inf; end tmp=reshape(R0,1,size(R0,1)*size(R0,2)); tmp=sort(tmp); tmp=fliplr(tmp); chk=0; cnt=0; while chk==0 cnt=cnt+1; [i,j]=find(R0>=tmp(cnt)); if length(unique(i)) >= PDR.SOUNDS_num_carriers snds=unique(i); snds=snds(1:PDR.SOUNDS_num_carriers); PDR.SOUNDS_carrier_states=PDR.SOUNDS_rand_states(snds); env_new1=env1(snds,:); env_new2=env2(snds,:); chk=1; break; end end for q1=1:length(snds) % zero out LEAD sounds if testing MAAs if PDR.maa_test_flag PDR.LEAD_sounds{q1}=zeros(size(LEAD_sounds{snds(q1)})); else PDR.LEAD_sounds{q1}=LEAD_sounds{snds(q1)}; end PDR.LAG_sounds{q1}=LAG_sounds{snds(q1)}; end scrn=get(0,'ScreenSize'); hTemp=figure('name','hist','Position',[0.1*scrn(3) 0.1*scrn(4) 0.8*scrn(3) 0.8*scrn(4)]); hold on; if PDR.SOUNDS_num_carriers > 1 % correlations of sound tokens subplot(3,2,1); Rnew1=corrcoef(env_new1'); Rnew2=corrcoef(env_new2'); Ravg=(Rnew1+Rnew2)./2; imagesc(Ravg,[min(min(Ravg)) max(max(Ravg))]); colormap bone; colorbar axis square title('Avg. Correlations Between Sound Tokens'); end if PDR.SOUNDS_num_carriers > 1 if ~PDR.maa_test_flag % plot histogram of calculated lead/lag correlations % (Just the ones that will be used) subplot(3,2,3); hold on; binz=(min(Res(snds))-0.05):0.01:(max(Res(snds))+0.05); out=hist(Res(snds),binz); bar(binz,out); xlabel('Correlation Coefficient') ylabel('Frequency') title('Histogram of Lead/Lag Correlations (low pass filtered envelopes)') h = findobj(gca,'Type','patch'); set(h,'FaceColor','w','EdgeColor','none') axis([-1 1 0 ceil(1.1*max(out))]); %axis([(min(Res(snds))-0.05) (max(Res(snds))+0.05) 0 ceil(1.1*max(out))]) set(gca,'Color',[0 0 0]); % hist of RPs subplot(3,2,5); hold on; binz=0:0.01:1; out=hist(PDR.RPs,binz); bar(binz,out); xlabel('RP'); ylabel('Frequency'); title('Histogram of Response Probabilities (low pass filtered envelopes)'); h = findobj(gca,'Type','patch'); set(h,'FaceColor','r','EdgeColor','none') axis([0 1 0 ceil(1.1*max(out))]) set(gca,'Color',[0 0 0]); else subplot(3,2,3); axis off text(0.15,0.35,'MAA EXPERIMENT','FontSize',30,'Color',[1 0 0]) end end % lead and lag envelopes subplot(3,2,2); hold on; for q2=1:length(snds) % do not plot leads if just testing MAAs if ~PDR.maa_test_flag A=PDR.LEAD_sounds{q2}; A_env=abs(hilbert(A)); for y0=1:size(Bs,1); A_env=filter(Bs(y0,:),As(y0,:),A_env); end plot(A_env,'Color',[q2/length(snds) 0 1-q2/length(snds)],'LineWidth',2); end % plot low pass filtered lag envelopes: B=PDR.LAG_sounds{q2}; B_env=abs(hilbert(B)); for y0=1:size(Bs,1); B_env=filter(Bs(y0,:),As(y0,:),B_env); end plot(B_env,'Color',[q2/length(snds) 0 1-q2/length(snds)],'LineWidth',1,'LineStyle',':'); end title('Low Pass Filtered Envelopes (lead/lag)'); set(gca,'Color',[0 0 0]); % wait for user uicontrol('Style', 'pushbutton', 'String', 'Close and Continue',... 'Units','Normalized','Position', [0.6 0.1 0.25 0.1],... 'BackgroundColor','g','Callback', 'close(''hist'')'); uiwait(hTemp) function soundBufferSetup global PDR for i0=1:PDR.SOUNDS_num_carriers len_buf = PDR.buf_pts; len_stim = length(PDR.LEAD_sounds{i0}); lead_stim=zeros(1,len_buf); lag_stim=lead_stim; pad = PDR.buf_pts-len_stim; %ceil(len_buf-len_stim); lead_stim = [zeros(1,2) PDR.LEAD_sounds{i0} zeros(1,pad)]; lag_stim = [zeros(1,2) PDR.LAG_sounds{i0} zeros(1,pad)]; PDR.LEAD_sounds{i0} = lead_stim(1:PDR.buf_pts); PDR.LAG_sounds{i0} = lag_stim(1:PDR.buf_pts); end function [leadP, lagP] = SpikeProbAM(Env1, Env2,Fs) % Adapted from B.S. Nelson's AM study % leadP = lead spike probability (cummulative) % lagP = lag spike probability (cummulative) % Env1 = lead envelope % Env2 = lag envelope SR = Fs; % may need to adjust derivative function if SR is changed % set separately in function filteredstimuliAM !!! % get amplitude difference Env1(find(Env1==0)) = 0.00000000001; Env1_dB = 20*log10(Env1); Env2(find(Env2==0)) = 0.00000000001; Env2_dB = 20*log10(Env2); Env1_dBDiff = Env1_dB - Env2_dB; Env2_dBDiff = Env2_dB - Env1_dB;%-Env1_dBDiff; Env1_dBDiff_wt = 3.0207 ./(1 + exp(-(Env1_dBDiff(:) - 3.2497) ./ 2.3835)); Env2_dBDiff_wt = 3.0207 ./(1 + exp(-(Env2_dBDiff(:) - 3.2497) ./ 2.3835)); %Env1_dBDiff = max(-24, Env1_dBDiff); % limit range %Env2_dBDiff = min(24, Env2_dBDiff); % limit range % derivative if 1 % use average envelope to measure d/dt -- as in Nelson & Takahashi 2010 % calculate average envlope Env1_dt = diff((Env1 + Env2)/2) * (SR/1000); % units are per ms... from AM paper Env2_dt = diff((Env1 + Env2)/2) * (SR/1000); Env1_dt_wt = 2.2082 ./(1 + exp(-(Env1_dt(:) - 0.014001) ./ 0.065264)); Env2_dt_wt = 2.2082 ./(1 + exp(-(Env2_dt(:) - 0.014001) ./ 0.065264)); spikeProb_1 = (Env1_dt_wt) .* (Env1_dBDiff_wt(2:end)); spikeProb_2 = (Env2_dt_wt) .* (Env2_dBDiff_wt(2:end)); else % calulate d/dt separately for each sound -- as in human model % This doesn't work (here) unless we get signals spatialized in % each ear. The derivavite would then be calulated from the % signals in each ear. % Also cannot use functions from Nelson & Takahashi 2010 Env1_dt = diff((Env1)/2) * (SR/1000); % units are per ms... from AM paper Env2_dt = diff((Env2)/2) * (SR/1000); Env1_dt_wt = 2.2082 ./(1 + exp(-(Env1_dt(:) - 0.014001) ./ 0.065264)); Env2_dt_wt = 2.2082 ./(1 + exp(-(Env2_dt(:) - 0.014001) ./ 0.065264)); Env_dt_wt = Env1_dt_wt .* Env2_dt_wt; % multiply weights Env1_dt_wt = Env_dt_wt; Env2_dt_wt = Env_dt_wt; spikeProb_1 = (Env_dt_wt) .* (Env1_dBDiff_wt(2:end)); spikeProb_2 = (Env_dt_wt) .* (Env2_dBDiff_wt(2:end)); end if 1 % entire stimulus leadP = sum(spikeProb_1) / (SR/1000) / 34; % 34=duration of stimuli used to estimate sensitivity functions? lagP = sum(spikeProb_2) / (SR/1000) / 34; else % skip onset and offset firstpnt = round(0.003*SR); lastpnt = round(length(spikeProb_1)-(0.003*SR)); leadP = sum(spikeProb_1(firstpnt:lastpnt)) / (SR/1000) / 34; lagP = sum(spikeProb_2(firstpnt:lastpnt)) / (SR/1000) / 34; end function readCalibFiles global PDR % function to read calibration data and select appropriate scales and % atten values for each speaker % calibration data file selection: pth = 'C:\alex\calib_data\'; PDR.SOUNDS_calib_pname = pth; switch PDR.bird_id case 925 nfiles = 1; PDR.SOUNDS_calib_fnames = cell(nfiles,1); PDR.SOUNDS_calib_fnames{1} = ['intraural_calib_130322_925D.mat']; %PDR.SOUNDS_calib_fnames = {'intraural_calib_130309_925A.mat';... % 'intraural_calib_130318_925F.mat'}; %PDR.SOUNDS_calib_fnames = ['intraural_calib_130222_925B.mat']; case 924 nfiles = 1; PDR.SOUNDS_calib_fnames = cell(nfiles,1); PDR.SOUNDS_calib_fnames{1} = 'intraural_calib_130309_924B.mat'; %PDR.SOUNDS_calib_fnames = ['intraural_calib_130221_924A.mat']; case 1073 nfiles = 1; PDR.SOUNDS_calib_fnames = cell(nfiles,1); PDR.SOUNDS_calib_fnames{1} = ['intraural_calib_130322_1073A.mat']; %PDR.SOUNDS_calib_fnames{1} = ['intraural_calib_130309_1073A.mat']; %PDR.SOUNDS_calib_fnames = ['intraural_calib_130219_1073A.mat']; otherwise PDR.SOUNDS_calib_fnames = cell(1,1); PDR.SOUNDS_calib_fnames{1}='ERROR'; warndlg('No calibration data for this bird!!!','!! Warning !!'); return; end tmp = NaN*ones(1,PDR.SOUNDS_num_speakers-1); PDR.SOUNDS_lead_attens = tmp; PDR.SOUNDS_speaker_scales_lead = tmp; PDR.SOUNDS_speaker_scales_lag = tmp; expt_locs = [PDR.SOUNDS_elevations; PDR.SOUNDS_azimuths]; spkr_list = PDR.SOUNDS_speaker_numbers; spkr_list = spkr_list(find(spkr_list ~= 1)); % remove lead speaker % go through each calibration file and grab speaker calibration data for j = 1:size(PDR.SOUNDS_calib_fnames,1) % load calibration data load([pth PDR.SOUNDS_calib_fnames{j}]); calib_locs = CALIB_PDR.locations(:,2:end); % get all locations except lead % get speaker attenuations & scales spkr_IDs = CALIB_PDR.equalized_lead_attens{1,2}; attens = CALIB_PDR.equalized_lead_attens{2,2}; speaker_data = CALIB_PDR.speaker_data; for i0 = spkr_list % check if calibration file has calibration data for this speaker idx=find(spkr_IDs == i0); if length(idx) % check if calib data is for same location el = expt_locs(1,i0); az = expt_locs(2,i0); if el == calib_locs(1,idx) && az == calib_locs(2,idx) % store attenuation for this speaker PDR.SOUNDS_lead_attens(i0-1) = attens(idx); % store scales for this speaker lead_coeffs=speaker_data(idx).coeffs_both_fit_lead_scales; m_lead=lead_coeffs(1,1); b_lead=lead_coeffs(2,1); PDR.SOUNDS_speaker_scales_lead(i0-1) = round(10^((PDR.SOUNDS_SPL-b_lead)/m_lead)); lag_coeffs=speaker_data(idx).coeffs_both_fit_lag_scales; m_lag=lag_coeffs(1,1); b_lag=lag_coeffs(2,1); PDR.SOUNDS_speaker_scales_lag(i0-1) = round(10^((PDR.SOUNDS_SPL-b_lag)/m_lag)); spkr_list = spkr_list(find(spkr_list ~= i0)); % done with this speaker! end end end end if length(spkr_list) warndlg(['Could not find calib data for speaker numbers: ' num2str(spkr_list)],'!! Warning !!'); PDR.SOUNDS_calib_fname='ERROR'; end % check speaker scales to be in range for TDT scales=[PDR.SOUNDS_speaker_scales_lead PDR.SOUNDS_speaker_scales_lag]; if ~isempty(find((scales>32760)==1)) warndlg('Some of the scales are too LARGE for the TDT!!!','!! Warning !!'); PDR.SOUNDS_calib_fname='ERROR'; end if ~isempty(find((scales<=0)==1)) warndlg('Some of the scales are too SMALL for the TDT!!!','!! Warning !!'); PDR.SOUNDS_calib_fname='ERROR'; end function speakerTestSetup global PDR % PARAMS PDR.filename = 'speaker_test'; cd(PDR.data_path); if exist([PDR.filename '.mat']) delete([PDR.filename '.mat']); end PDR.comments = 'Testing Equipment!'; PDR.record = 1; PDR.isi_buf = 5; % ORDERED LIST OF SPEAKER LOCATIONS PDR.npretrials = 1; PDR.TEST_trial_freq = 1; PDR.n_test_trials = 2*length(PDR.TEST_azimuths); ntrials = PDR.npretrials + PDR.TEST_trial_freq*PDR.n_test_trials; PDR.SOUNDS_location_sequence = NaN*ones(2,ntrials+1); PDR.SOUNDS_location_sequence(1,:) = PDR.LEAD_pos*ones(1,ntrials + 1); % lead positions in first row PDR.SOUNDS_location_sequence(2,:) = PDR.LAG_hab_pos*ones(1,ntrials + 1); % lag positions in second row PDR.TEST_trial_jitter=0; TEST_trial_jitter = PDR.TEST_trial_jitter; no_angles = length(PDR.TEST_azimuths); % create a trial sequence and convert to location sequence % (2 rows, 1st row= El, 2nd row = Az) last_test=NaN; % create list of locations with randomized test locs cnt = PDR.npretrials; % skip pretrials id = 0; while cnt < ntrials cnt = cnt + PDR.TEST_trial_freq; id = id + 1; PDR.SOUNDS_location_sequence(2,cnt)=PDR.TEST_azimuths(mod(id,length(PDR.TEST_azimuths))+1); cnt = cnt + round(TEST_trial_jitter*rand); % jitter test trial occurances (if requested) if cnt >= (ntrials-PDR.TEST_trial_freq) break; end end % setup rove sequence: num_snds=PDR.SOUNDS_num_carriers; PDR.SOUNDS_rove_sequence = ceil(num_snds-num_snds*rand(1,ntrials+1)); lds_switchyard('calcSessionLen'); sec=num2str(PDR.len_session(2)); if length(sec)==1 sec=['0' sec]; end minutes=num2str(PDR.len_session(1)); if length(minutes)==1 minutes=['0' minutes]; end % TELL USER HOW LONG EQUIPMENT TESTING WILL TAKE! h=msgbox(['Testing equipment will take: ' minutes ' minutes & ' sec ' seconds']); uiwait(h); % MAKE SOUND TOKENS: lds_switchyard('AMStim'); % calculate lead lag sounds using correlation and state values (for reproducible sounds) lds_switchyard('soundBufferSetup'); % SETUP CALIBRATED SCALES & ATTENS: lds_switchyard('readCalibFiles');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Multimodal Analysis of Emotions % Version : 1.0 % Date : 04.6.2016 % Author : Mehdi Ghayoumi %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function central_mmt = CentralMoment(img, ord_x, ord_y) img = double(img); mmt_0_0 = Moment(img, 0, 0); mmt_1_0 = Moment(img, 1, 0); mmt_0_1 = Moment(img, 0, 1); center_x = floor(mmt_1_0/mmt_0_0); center_y = floor(mmt_0_1/mmt_0_0); central_mmt =0; for i = 1:1:size(img,1) for j = 1:1:size(img,2) central_mmt = central_mmt + double(img(i,j) * ... (i - center_x)^ord_x * (j - center_y)^ord_y); end end end
function [fpForces,fpMoments] = getFPdata(structData, iFP) % Get the raw forces and moments from the forceplate. forceNames = fieldnames(structData.fp_data.FP_data(iFP).channels); if structData.fp_data.FP_data(iFP).type == 3 fx12=structData.fp_data.FP_data(iFP).channels.(forceNames{1}); fx34=structData.fp_data.FP_data(iFP).channels.(forceNames{2}); fy14=structData.fp_data.FP_data(iFP).channels.(forceNames{3}); fy23=structData.fp_data.FP_data(iFP).channels.(forceNames{4}); fz1=structData.fp_data.FP_data(iFP).channels.(forceNames{5}); fz2=structData.fp_data.FP_data(iFP).channels.(forceNames{6}); fz3=structData.fp_data.FP_data(iFP).channels.(forceNames{7}); fz4=structData.fp_data.FP_data(iFP).channels.(forceNames{8}); % get the origin of the forceplate xo = structData.fp_data.FP_data(iFP).origin(1,:); %x yo = structData.fp_data.FP_data(iFP).origin(2,:); %y % calculate the forces fx = fx12 + fx34; fy = fy14 + fy23; fz = fz1 + fz2 + fz3 + fz4; % calculate the moments mx = yo*(fz1+fz2-fz3-fz4); my = xo*(-fz1+fz2+fz3-fz4); mz = yo*(-fx12+fx34)+xo*(fy14-fy23); fpForces = [fx fy fz]; fpMoments=[mx my mz]; else fx = structData.fp_data.FP_data(iFP).channels.(forceNames{1}); fy = structData.fp_data.FP_data(iFP).channels.(forceNames{2}); fz = structData.fp_data.FP_data(iFP).channels.(forceNames{3}); mx = structData.fp_data.FP_data(iFP).channels.(forceNames{4}); my = structData.fp_data.FP_data(iFP).channels.(forceNames{5}); mz = structData.fp_data.FP_data(iFP).channels.(forceNames{6}); fpForces = [fx fy fz]; fpMoments = [mx my mz]; end
function printGAresult( parameters ) filename = fopen('result.txt','a'); fprintf(filename, '%3.5f\t %3.5f\t %3.5f\t %3.5f\t %3.5f\t %3.5f\n',parameters(1), parameters(2), ... parameters(3), parameters(4), parameters(5), parameters(6)); fclose(filename); end
function position = genposition(number, range) % stream = RandStream.getGlobalStream; % savedState = stream.State; % rng(26,'twister'); position = [[1:number]',rand(number,2)*range - range/2]; end
load('under_sampling.mat'); % load('matlab.mat'); % train_data = final_features_1; % train_class = final_Class_1; times = 10; recall = zeros(1,times); accuracy = zeros(1,times); train_time = zeros(1,times); testing_time = zeros(1,times); true_positive_rate= zeros(1,times); for i= 1:times [training_D,training_class,testing_D,testing_class] = randSample(train_data,train_class,length(train_data)/2); % Neural Network % hiddenLayerSize = 2; % net = fitnet(hiddenLayerSize); % inputs = data1'; % targets = class1'; % [net,tr] = train(net,inputs,targets); % testX = inputs(:,tr.testInd); % testT = targets(:,tr.testInd); % testY = net(testX); % testing_class = testT; % predict_class = testY; % Logistic Regression % tic; % bHat = glmfit(training_D,training_class,'binomial'); % train_time(i) = toc; % tic % testing_Hat = glmval(bHat, testing_D, 'logit'); % testing_time(i) = toc; % predict_class = (testing_Hat > 0.5)+0; % since this is a binomial distribution, +0 means convert logical value to double values % Decision Tree % tic; % model_decision_tree = fitctree(training_D, training_class); % train_time(i) = toc; % view(model_decision_tree, 'Mode', 'graph'); % tic % [predict_class, ~, ~] = predict(model_decision_tree, testing_D); % testing_time(i) = toc; % Random Forest tic; numTrees = 12; bagger_model = TreeBagger(numTrees, training_D,training_class,'OOBPred','On'); train_time(i) = toc; % view(bagger_model.Trees{1},'mode','graph'); % view(bagger_model.Trees{2},'mode','graph'); % view(bagger_model.Trees{3},'mode','graph'); % view(bagger_model.Trees{4},'mode','graph'); % view(bagger_model.Trees{5},'mode','graph'); % view(bagger_model.Trees{6},'mode','graph'); % view(bagger_model.Trees{7},'mode','graph'); % view(bagger_model.Trees{8},'mode','graph'); oobErrorBaggedEnsemble = oobError(bagger_model); figure; plot(oobErrorBaggedEnsemble) xlabel 'Number of grown trees'; ylabel 'Out-of-bag classification error'; tic predict_class = str2double(bagger_model.predict(testing_D)); testing_time(i) = toc; C = confusionmat(testing_class, predict_class); % plotroc(testing_class', predict_class'); plotconfusion(testing_class', predict_class'); recall(i) = C(2,2) / (C(2,1) + C(2,2)); accuracy(i) = (C(1,1)+C(2,2))/sum(C(:)); true_positive_rate(i) = C(2,1)/sum(C(2,:)); % rate that we missed, here is the risk, indicating how many frauds that we can't detect end mean_recall = mean(recall) mean_accuracy = mean(accuracy) mean_true_positive_rate = mean(true_positive_rate) mean_train_time = mean(train_time) mean_testing_time = mean(testing_time)
function Grf_c2 = Grf_c2(in1,us) %GRF_C2 % GRF_C2 = GRF_C2(IN1,US) % This function was generated by the Symbolic Math Toolbox version 8.4. % 18-Jul-2020 23:08:00 Fx = in1(:,1); Fy = in1(:,2); Grf_c2 = Fx.^2-Fy.^2.*us.^2;
function [C M]= AMIGO_commentStruct(A,B) % AMIGO_commentStruct returns struct A, the values replaced by the corresponding fields from B. % recursively checks the fields of struct A and B. % if A has a field, that B does not have, the default value: 'missing comment' is assigned. % M is a structure containing only missing elements. % % EXAMPLES: % % we have struct a with values: % a = struct('field1',rand(5),'field2', 5,'field3','some text',... % 'field4',struct('field11','apple'),'field5',struct('field51','some text2','field52',999,'field53',magic(8))) % % % struct b contains the corresponding comments: % b = struct('field1','this is field1','field3','this is field3',... % 'field4',struct('field11','this is field11'),'field5',struct('field50','this is field50','field52','this is field52','field53','this is field53'),'field6','this is field6') % % % note that, we were lazy and field2 does not exists in b. --> the % % missing comment is indicated in c using the missing_value % % variable. % % C = AMIGO_commentStruct(a,b); % % % display C: % AMIGO_displayStruct(C); missing_value = '#RED #MISSING'; if ~isstruct(A) C = []; disp('A is not a struct. ') return; end [C M]= intersect(A,B); function [c m] = intersect(a,b) % returns a if a and b are not structures. Otherwise, c contains the % common fields. c = struct; m = struct; fn = fieldnames(a); for i = 1:length(fn) if ~isstruct(a.(fn{i})) % the field is not a struct, so take the documentation: if isfield(b,fn{i}) c.(fn{i}) = b.(fn{i}); else % no existing comment for this field. c.(fn{i}) = missing_value; m.(fn{i}) = ''; end else % the field is a struct --> go deeper. if ~isfield(b,fn{i}) || ~isstruct(b.(fn{i})) % if b does not have this field or the field is not a % struct, create and empty entry b.(fn{i}) = struct(); end [tmp tmpm]= intersect(a.(fn{i}),b.(fn{i})); if ~isempty(fieldnames(tmp)) c.(fn{i}) = tmp; m.(fn{i}) = tmpm; end end end end end
function relations = MakeRandomDISEQV( h ) relations=cell(2,h); for i=1:2:length(relations) relations{1,i}=i; relations{1,i+1}=i; relations{2,i}='DIS'; relations{2,i+1}='EQV'; % relations{2,i}=i; % relations{3,i}=i; end end
function [bs, ns, ms, logb] = bootstrap_fun (data, Nboot, n, m) % call function, depending on whether or not m and n are specified if nargin == 4 bhat = bootstrp(Nboot, @(x) bootstrap_nmr_called(x, n, m), data); % n,m can vary elseif nargin == 3 bhat = bootstrp(Nboot, @(x) bootstrap_nmr_called(x, n), data); % m can vary elseif nargin == 2 bhat = bootstrp(Nboot, @(x) bootstrap_nmr_called(x), data); % m = 0, n = 2 else error('Not enough input arguments') end [~, bbb] = size(bhat); if bbb > 3 bhat = bhat'; [~, bbb] = size(bhat); end if bbb == 3 bs = bhat(:,1); ns = bhat(:,2); ms = bhat(:,3); elseif bbb == 2 bs = bhat(:,1); ns = bhat(:,2); ms = []; else bs = bhat; ns = []; ms = []; end % transform back into log space logb = bs; bs = 10.^logb; end
function [T,vr_a] = OpenVideoAndWriterFiles() Template = imread('mask_template.jpg'); T = rgb2gray(Template); % figure(300); % imshow(T); % Arthoscope_File = 'KneeGap10L11Clip' Arthoscope_File = 'KneeGap100L10Clip' vr_arthroscope_file = strcat(Arthoscope_File,'.mp4') %Opens the video of the knee athroscopy vr_a = VideoReader(vr_arthroscope_file);
function protocol = ProtocolInitialize(xfilename,quiet) % ProtocolInitialize initializes a protocol data structure % % protocol = ProtocolInitialize % % protocol = ProtocolInitialize(xfilename) % % protocol = ProtocolInitialize(xfilename,'quiet') suppresses any text % output (important e.g. when called from a Visual Basic program). % part of Spikes % % 2000-09 Matteo Carandini % 2006-08 MC updated and extended so one can declare an xfile % To see what is in a Protocol, do load('Z:\Data\trodes\CATZ009\19\1\Protocol'); if nargin<2 quiet = 'loud'; end if nargin< 1 xfilename = []; end protocol.xfile = ''; protocol.adapt.flag = 0; protocol.nstim = []; protocol.npfilestimuli = []; protocol.npars = []; protocol.pars = []; protocol.parnames = {}; protocol.pardefs = {}; protocol.animal = ''; protocol.iseries = []; protocol.iexp = []; protocol.nrepeats = 0; protocol.seqnums = 0; % These are not key attributes of the Protocol file: % protocol.blankstims = []; % protocol.blankpars = []; % protocol.activepars = []; % protocol.description = []; if isempty(xfilename) return end % read the xfile x = XFileLoad( xfilename, quiet ); protocol.xfile = x.name; protocol.parnames = x.parnames; protocol.pardefs = x.pardefs; protocol.npars = x.npars;
function C= calc_covariance(y) [m,n,s]=size(y);%m:variabel,n:length,s:segments or trials C=reshape(cell2mat(arrayfun(@(i) (squeeze(y(:,:,i))*squeeze(y(:,:,i).'))/n,1:s,'UniformOutput',false)),m,m,s); C=mean(C,3); end
clear all; clc;close all;clc; addpath Yall1; TrainPath = 'SABS\Train\NoForegroundDay\'; numTrain = 800; VideoPath = 'SABS\Test\Bootstrap\'; videolength = 300; nrow = 120; ncol = nrow * 160/120;% frame dimension addpath(TrainPath); addpath(VideoPath); %% Reading the files %Background srcFiles = dir(strcat(TrainPath,'*.png')); if length(srcFiles) > numTrain srcFiles = srcFiles(1:numTrain); end DataTrain = zeros([nrow*ncol length(srcFiles)]); tensorDataTrain = zeros(nrow,ncol,numTrain); tensorMTrain = zeros(nrow,ncol,numTrain); tensorM = zeros(nrow,ncol,numTrain); for i = 1 : length(srcFiles) filename = strcat(TrainPath,srcFiles(i).name); I1 = double(rgb2gray(imread(filename))); I1 = imresize(I1, [nrow NaN]); %imshow(I); title('Image ',i); DataTrain(:,i) = reshape(I1,[nrow*ncol 1]); tensorDataTrain(:,:,i) = I1; end b = 0.95; mu0 = mean(DataTrain,2); mu0_tensor = mean(tensorDataTrain,3); MTrain = DataTrain-repmat(mu0,1,numTrain); for t=1:numTrain tensorMTrain(:,:,t)= tensorDataTrain(:,:,t) - mu0_tensor; end %% SVD [Usvd, Sig, Vsvd] = svd(1/sqrt(numTrain)*MTrain,0); %Keeping b% energy evals1 = diag(Sig).^2; energy1 = sum(evals1); cum_evals1 = cumsum(evals1); ind01 = find(cum_evals1 < b*energy1); rhat1 = min(length(ind01),round(numTrain/10)); lambda_min1 = evals1(rhat1); U1 = Usvd(:, 1:rhat1); V1 = Vsvd(1:rhat1 , :); Sig1 = Sig(1:rhat1,1:rhat1); Mtrain_lowrank_reprocs = U1 * Sig1 * V1; %% HOSVD (Higher Order SVD) [S, U_cell, SD_cell] = hosvd((1/sqrt(numTrain)).*tensorMTrain); %Keeping b% energy for unf = 1:3 evals{unf} = SD_cell{unf}.^2; energy(unf) = sum(evals{unf}); cum_evals{unf} = cumsum(evals{unf}); ind0{unf} = find(cum_evals{unf} < b*energy(unf)); rhat{unf} = min(length(ind0{unf}),round(numTrain/10)); lambda_min{unf} = evals{unf}(rhat{unf}); U_cell0{unf} = U_cell{unf}(:, 1:rhat{unf}); SD_cell0{unf} = SD_cell{unf}(1:rhat{unf}); T{unf} = U_cell0{unf} * (U_cell0{unf})'; end U2 = kron(T{1},T{2}); U = U2*U1; S0 = S(1:rhat{1},1:rhat{2},1:rhat{3}); MTrain_lowrank_tensor = nmode_product(S0,U_cell0{1},1); MTrain_lowrank_tensor = nmode_product(MTrain_lowrank_tensor,U_cell0{2},2); MTrain_lowrank_tensor = nmode_product(MTrain_lowrank_tensor,U_cell0{3},3); %% Displaying Backgrounds after low-rank approximation close all; figure; set(gcf, 'units','normalized','outerposition',[0 0 1 1]); % Full screen. for t=1:videolength Mtrain_lowrank_reprocs(:,t) = Mtrain_lowrank_reprocs(:,t) + mu0; for i = 1 : ncol reprocs(:,i) = uint8(Mtrain_lowrank_reprocs((i-1)*nrow+1:i*nrow,t)); end original = uint8(tensorDataTrain(:,:,t)); tensor = uint8(MTrain_lowrank_tensor(:,:,t) + mu0_tensor ); subplot(221); imshow(original); caption = sprintf('Original Training Background'); subplot(222); imshow(reprocs); caption = sprintf('ReProCS Low rank Training Frame %4d', t); title(caption); subplot(223); imshow(tensor); caption = sprintf('Tensor Low rank Training Frame %4d', t); title(caption); pause(0.04); end
## Copyright (C) 2020 damon ## ## 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 ## <https://www.gnu.org/licenses/>. ## -*- texinfo -*- ## @deftypefn {} {@var{retval} =} q_calc (@var{input1}, @var{input2}) ## ## @seealso{} ## @end deftypefn ## Author: damon <damon@FUNRIG> ## Created: 2020-03-06 % dynamic pressure assist calculator % select a planet, input altitude Alt (m) and speed vel(m/s) % outputs dynamic pressure q (Pa/m^2), mach number M and speed of sound a (m/s) function [q,M,a] = q_calc(alt,vel,planet) % get atmospheric conditions on the planet [T,p,rho,gam,R] = atmosphere(alt,planet); % get speed of sound a = sqrt(gam*R.*T); % get mach number M = vel./a; % get dynamic pressure q = 0.5*gam.*p.*M.^2; endfunction
%identifier global units = 'Metric '; global U; %read in common base values UnitsDef; %MetricBaseUnits U.kg = U.DefinedUnit; U.m = U.DefinedUnit; U.degK = U.DefinedUnit; U.kgmole = U.DefinedUnit; %U.AvNo = 6.0248600e026/U.kgmole; %U.Rbar = 8316.96*U.kg*U.m*U.m/(U.sec*U.sec*U.degK*U.kgmole); %U.G = 9.80665*U.m/(U.sec*U.sec); U.Gc = 1.0; %U.RhoH2O = 999.9973*U.kg/(U.m*U.m*U.m); U.lbm = 0.45359305*U.kg; U.lbf = 4.4482216*U.kg*U.m/(U.sec*U.sec); U.ft = 3.0480000e-001*U.m; U.degR = U.degK/1.8; U.lbmole = U.lbm*U.kgmole/U.kg; %calculate units for base UnitsCommon;
t = pi*(-2:0.0001:2); x = sin(t); y = cos(t); plot(x,y)
clc,clear, close all; font_size=15; file_path = 'D:\zm_documents\LAMMPS\hBN_defects\hBN_antisite_1pc_cvg\tersoff&ectep\nobackfire'; %MD模拟参数 %metal单位 ev ps bar A num_blocks = 80; % 块的个数 Lx = 188.5610; % 输运方向长度 Ly = 49.4844; %宽度 Lz = 1.44586 ; %厚度 dt = 0.5e-3; %时间步长 dE = 2; %交换能量功率 timesteps = 900000; %时间步数 ave_timesteps = 100000; %计算平均温度的步数 block = 40; %计算一些参数 file = [file_path,'\',num2str(num_blocks),'.temp']; num_outputs = timesteps/ave_timesteps; % 输出块温度的次数 dx = Lx / num_blocks; % 每个块的长度 power = dE * 1.6e-7; % 功率 eV/ps -> W A = Ly*Lz * 1.0e-20; % 横截面积 A^2 -> m^2 Q = power / A / 2; % 热流密度 W/m^2 t0 =ave_timesteps*dt; % 每次输出数据增加的模拟时间 % 非平衡模拟时间 t= t0 * (1 : num_outputs); % 块坐标 x = (1 : num_blocks) * dx; % 一行 x = x.'; % 一列 %从LAMMPS输出文件中提取块温度 [Chunk Coord1 Ncount v_TEMP] ... = textread(file, '%n%n%n%n', 'headerlines', 3, 'emptyvalue', 0); temp = [Chunk Coord1 Ncount v_TEMP]; nall = length(temp) / (num_blocks+1); clear Chunk Coord1 Ncount v_TEMP; for i =1:nall temp((i-1)*num_blocks+1,:)=[]; end temp = reshape(temp(:, end), num_blocks, num_outputs); % 对输出次数作循环,计算温度梯度和热导率 for n = 1 : num_outputs % 确定拟合区间(具体问题具体分析) index_1 = num_blocks/block*4+1 : num_blocks/2; % 左边除去热源后的块指标 index_2 = num_blocks/2+num_blocks/block*4 : num_blocks; % 右边除去热汇后的块指标 % 拟合温度分布 p1 = fminsearch(@(p) ... norm(temp(index_1, n) - (p(1)-p(2)*x(index_1)) ), [60, -1]); p2 = fminsearch(@(p) ... norm(temp(index_2, n) - (p(1)+p(2)*x(index_2)) ), [60, 1]); % 得到温度梯度 gradient_1 = p1(2) * 1.0e10; % K/A -> K/m gradient_2 = p2(2) * 1.0e10; % K/A -> K/m % 得到热导率 kappa_1(n) = -Q / gradient_1; kappa_2(n) = -Q / gradient_2; % 画温度分布以及拟合曲线 figure(n) plot(x, temp(:, n), 'bo', 'linewidth', 2); hold on; x1=x(index_1(1)) : 0.1 : x(index_1(end)); x2=x(index_2(1)) : 0.1 : x(index_2(end)); plot(x1, p1(1)-p1(2)*x1, 'r-', 'linewidth', 2); plot(x2, p2(1)+p2(2)*x2, 'g--', 'linewidth', 2); legend('MD', 'fit-left', 'fit-right','location','best'); set(gca, 'fontsize', font_size); title (['t = ', num2str(t0 * n), ' ps']); xlabel('x (nm)'); ylabel('T (K)'); end % 热导率的时间收敛测试 kappa = (kappa_1 + kappa_2) / 2; figure(n+1); plot(t, kappa_1, ' rd', 'linewidth', 2); hold on; plot(t, kappa_2, ' bs', 'linewidth', 2); plot(t, kappa, ' ko', 'linewidth', 2); set(gca, 'fontsize', font_size); xlabel('t (ps)'); ylabel('\kappa (W/mK)'); legend('left', 'right', 'average'); % 报道结果(具体问题具体分析) kappa_average = mean( kappa(1:end) ) kappa_error = mean( 0.5*abs( kappa_1(1:end)-kappa_2(1:end) ) ) text(120,39,['\kappa_{ave} =',num2str(kappa_average)],'fontsize',20); text(120,38.5,['\kappa_{error} =',num2str(kappa_error)],'fontsize',20,'color','red'); figure(n+2) boxplot(temp','PlotStyle','compact') xlabel('x (nm)'); ylabel('T (K)');
% linear regression and then compare shrinkage factor and decide probe offset EphysLabelFolder = cd; EphysLabelLists = dir('*.csv'); savepath = 'I:\NP histology\probe revise\figure'; load('I:\NP histology\shrinkF.mat'); load('I:\NP histology\histoLengthTip.mat'); load('I:\NP histology\insertLengthTip.mat'); revisedLength = zeros(size(insertLengthMat)); revisedLength(:,1) = insertLengthMat(:,1); insertLengthMat(insertLengthMat > 3840) = 3840; for tableIdx = 1:length(EphysLabelLists) C = strsplit(EphysLabelLists(tableIdx).name,'.'); meta = strsplit(C{1},'-'); miceId = meta{1}; probeId = meta{2}; insertLength = insertLengthMat(shrinkageMat(:,1) == str2double(miceId),str2double(probeId)+1); shrinkage_factor = shrinkageMat(shrinkageMat(:,1) == str2double(miceId),str2double(probeId)+1); probe_histo_length_tip = histoLengthMat(shrinkageMat(:,1) == str2double(miceId),str2double(probeId)+1); histo_active_length = insertLength*shrinkage_factor; depthListPx = readtable(EphysLabelLists(tableIdx).name); histoRanges = [range(depthListPx.zha_y_histo_probe) range(depthListPx.xd_y_histo_probe)]; ephysRanges = [range(depthListPx.zha_y_ephys),range(depthListPx.xd_y_ephys)]; if range(depthListPx.zha_y_histo_probe) > 0 && range(depthListPx.xd_y_histo_probe) > 0 px2um_histo_psudo = insertLength / mean([range(depthListPx.zha_y_histo_probe),range(depthListPx.xd_y_histo_probe)]); px2um_histo = histo_active_length / mean([range(depthListPx.zha_y_histo_probe),range(depthListPx.xd_y_histo_probe)]); px2um_ephys = 3840 / mean([range(depthListPx.zha_y_ephys),range(depthListPx.xd_y_ephys)]); else px2um_histo_psudo = insertLength / histoRanges(histoRanges > 0); px2um_histo = histo_active_length / histoRanges(histoRanges > 0); px2um_ephys = 3840 / ephysRanges(ephysRanges > 0); end try depth_histo_zha_px = sort(depthListPx.zha_y_histo_probe(depthListPx.zha_y_histo_probe ~= 0)); depth_histo_zha = px2um_histo_psudo * (depth_histo_zha_px(2:end-1) - depth_histo_zha_px(1)); catch depth_histo_zha = []; end try depth_histo_xd_px = sort(depthListPx.xd_y_histo_probe(depthListPx.xd_y_histo_probe ~= 0)); depth_histo_xd = px2um_histo_psudo * (depth_histo_xd_px(2:end-1) - depth_histo_xd_px(1)); catch depth_histo_xd = []; end try depth_ephys_zha_px = sort(depthListPx.zha_y_ephys(depthListPx.zha_y_ephys ~= 0)); depth_ephys_zha = px2um_ephys * (depth_ephys_zha_px(2:end-1) - depth_ephys_zha_px(1)); catch depth_ephys_zha = []; end try depth_ephys_xd_px = sort(depthListPx.xd_y_ephys(depthListPx.xd_y_ephys ~= 0)); depth_ephys_xd = px2um_ephys * (depth_ephys_xd_px(2:end-1) - depth_ephys_xd_px(1)); catch depth_ephys_xd = []; end plot(depth_histo_zha,depth_ephys_zha,'r*',depth_histo_xd,depth_ephys_xd,'b*'); hold on; X = [depth_histo_zha;depth_histo_xd]; X = [ones(size(X)) X]; Y = [depth_ephys_zha;depth_ephys_xd]; b = regress(Y,X); y = b(2)*X(:,2) + b(1); plot(X(:,2),y,'linewidth',2); hold on; line([0 3840],[0,3840*shrinkage_factor],'Color',[0.2,0.2,0.2],'LineStyle','--'); ax = gca; set(gca,'XLim',[0 3840],'YLim',[0 3840]); saveas(gcf,[savepath '\' C{1} '.png']); pause(0.05); close; estimated_max_depth = probe_histo_length_tip + 3840 - histo_active_length - b(1); revisedLength(revisedLength(:,1) == str2double(miceId),str2double(probeId)+1) = estimated_max_depth; save('I:\NP histology\reviseLengthTip.mat','revisedLength'); end
function conjugate(lamda) load trainSet.txt; siz=size(trainSet); dim=siz(1)-1;%%计算维度 num=siz(2);%%计算实例数目 Y=trainSet(dim+1,1:num); X=zeros(dim+1,num); X(1,1:num)=1; X(2:dim+1,1:num)=trainSet(1:dim,1:num); w=zeros(1,dim+1); g=(Y-exp(w*X)./(1+exp(w*X)))*X'-lamda*w;%%起始点梯度 old_g=inf; alpha=0.001; e=1e-7; d=zeros(1,dim+1); while norm(g)>e beta=norm(g)/norm(old_g); d=g+beta*d; w=w+alpha*d; old_g=g; g=(Y-exp(w*X)./(1+exp(w*X)))*X'-lamda*w; end; validate(w); end
clc; clearvars; close all; Length = 120; Hann1_1Width = 29; Hann1_1Position = 20; Hann1_2Width = 29; Hann1_2Position = 40; Hann1_3Width = 49; Hann1_3Position = 70; Signal1 = ones(1,Length); Hann1_1 = hann(Hann1_1Width); TempIndex = 1; for i = (Hann1_1Position - floor(Hann1_1Width/2)):(Hann1_1Position + floor(Hann1_1Width/2)) Signal1(i) = Signal1(i) - 0.2 * Hann1_1(TempIndex); TempIndex = TempIndex + 1; end Hann1_2 = hann(Hann1_2Width); TempIndex = 1; for i = (Hann1_2Position - floor(Hann1_2Width/2)):(Hann1_2Position + floor(Hann1_2Width/2)) Signal1(i) = Signal1(i) + 0.1 * Hann1_2(TempIndex); TempIndex = TempIndex + 1; end Hann1_3 = hann(Hann1_3Width); TempIndex = 1; for i = (Hann1_3Position - floor(Hann1_3Width/2)):(Hann1_3Position + floor(Hann1_3Width/2)) Signal1(i) = Signal1(i) - 0.1 * Hann1_3(TempIndex); TempIndex = TempIndex + 1; end plot(Signal1); Hann2_1Width = 39; Hann2_1Position = 35; Hann2_2Width = 59; Hann2_2Position = 60; Hann2_3Width = 39; Hann2_3Position = 85; Signal2 = ones(1,Length); Hann2_1 = hann(Hann2_1Width); TempIndex = 1; for i = (Hann2_1Position - floor(Hann2_1Width/2)):(Hann2_1Position + floor(Hann2_1Width/2)) Signal2(i) = Signal2(i) - 0.2 * Hann2_1(TempIndex); TempIndex = TempIndex + 1; end Hann2_2 = hann(Hann2_2Width); TempIndex = 1; for i = (Hann2_2Position - floor(Hann2_2Width/2)):(Hann2_2Position + floor(Hann2_2Width/2)) Signal2(i) = Signal2(i) + 0.1 * Hann2_2(TempIndex); TempIndex = TempIndex + 1; end Hann2_3 = hann(Hann2_3Width); TempIndex = 1; for i = (Hann2_3Position - floor(Hann2_3Width/2)):(Hann2_3Position + floor(Hann2_3Width/2)) Signal2(i) = Signal2(i) - 0.1 * Hann2_3(TempIndex); TempIndex = TempIndex + 1; end hold on; plot(Signal2, 'r'); Figure1 = figure(1); set(Figure1, 'Position', [100, 100, 600, 200]); subaxis(1, 2, 1, 'SpacingVertical', 0.1, 'SpacingHorizontal', 0.1, 'Padding', 0, 'PaddingTop', 0.1, 'Margin', 0.1); PlotAlignment(Signal1, Signal2, [(1:Length)' (1:Length)'], 200, 540, 0, 5); title('A. Vertical alignment'); subaxis(1, 2, 2, 'SpacingVertical', 0.1, 'SpacingHorizontal', 0.1, 'Padding', 0, 'PaddingTop', 0.1, 'Margin', 0.1); [Distance RDTWPath] = RDTW(Signal1', Signal2', 1, 0); PlotAlignment(Signal1, Signal2, RDTWPath, 200, 540, 0, 5); title('B. DTW alignment'); set(gcf, 'Color', 'w'); set(findall(gcf,'type','text'),'FontSize',13); export_fig( gcf, ... % figure handle 'DTWConcept',... % name of output file without extension '-painters', ... % renderer '-jpg', ... % file format '-r72' ); % resolution in dpi
function d = double(q) % DOUBLE Convert quaternion to double precision (obsolete). % (Quaternion overloading of standard Matlab function.) % Copyright © 2006 Stephen J. Sangwine and Nicolas Le Bihan. % See the file : Copyright.m for further details. error(['Conversion to double from quaternion is not possible. ',... 'Try cast(q, ''double'')']) % Note: this function was replaced from version 0.9 with the convert % function, because it is incorrect to provide a conversion function % that returns a quaternion result. The convert function provides the % same functionality, but will not be called implicitly by Matlab to % implement an assignment like X(1,2) = quaternion(1,2,3,4) which gave % erroneous results prior to version 0.9 and now raises an error. % $Id: double.m,v 1.4 2009/02/08 18:35:21 sangwine Exp $
function [tka ecc] = getlaskar2010(option, varargin) % [tka ecc] = getlaskar2010(option) % % Open Laskar2010 eccentricity solution data files. % Downloaded from http://vo.imcce.fr/insola/earth/online/earth/La2010/index.html % % Input % ===== % % option = 1 La2010a (solution a) % option = 2 La2010b (solution b) % option = 3 La2010c (solution c) % option = 4 La2010d (solution d) % % Output % ====== % % tka = time in ka BP (negative years = future) % ecc = eccentricity % % Optional % ======== % 'slice',[tmin tmax] % Specify desired time interval (in ka BP) % % Cite: % ===== % Laskar, J., Fienga, A., Gastineau, M., Manche, H., 2011. % La2010: a new orbital solution for the long-term motion of the Earth. % A&A 532, A89. https://doi.org/10.1051/0004-6361/201116836 % % ----------------------------------------- % B.C. Lougheed / May 4, 2020 / Matlab2019a % stupidly long way that matlab processes optional vargin p = inputParser; p.KeepUnmatched = true; p.CaseSensitive = false; p.FunctionName='getlaskar2010'; defaultslice = [-inf inf]; if exist('OCTAVE_VERSION', 'builtin') ~= 0 addParamValue(p,'slice',defaultslice,@isnumeric); else if datenum(version('-date'))>datenum('May 19, 2013') addParameter(p,'slice',defaultslice,@isnumeric); else addParamValue(p,'slice',defaultslice,@isnumeric); end end parse(p,varargin{:}); slice = p.Results.slice; % load data if option == 1 d = load('La2010a_ecc3L.dat'); elseif option == 2 d = load('La2010b_ecc3L.dat'); elseif option == 3 d = load('La2010c_ecc3L.dat'); elseif option == 4 d = load('La2010d_ecc3L.dat'); end d(:,1) = (d(:,1)*-1)-(50/1000); % ka 1950 d = sortrows(d,1,'descend'); if min(slice) == max(slice) d = d(d(:,1) == slice(1),:); else d = d(d(:,1) >= min(slice) & d(:,1) <= max(slice),:); end tka = d(:,1); ecc = d(:,2);
%% Solutions based on Kekatpure's paper on three layer waveguides clear all; la0 = 1550e-9; % ef = 3.5^2; % es = 1.45^2; % ef = 3.3^2; % es = 3.256^2; %% Kekatpure MDM % es = -95.92-1i*10.97; % ef = 2.1025; % ec = -143.49 - 1i*9.52; % h = 3e-6; % h = 300e-9; %% Kekatpure MDM % ec = 1; es = 2.1025; ef = -143.49 - 1i*9.52; ec = 2.1025; h = 100e-9; % h = 300e-9; %% Definitions k0 = 2*pi./la0; p = ef/ec; q = ef/es; Kc = k0*sqrt(ef - ec); Ks = k0*sqrt(ef - es); % Qc = k0*sqrt(ec - ef); % Qs = k0*sqrt(es - ef); ac = @(k) sqrt(Kc.^2 + k.^2); as = @(k) sqrt(Ks.^2 + k.^2); gc = @(k) sqrt(Kc.^2 - k.^2); gs = @(k) sqrt(Ks.^2 - k.^2); Gc = @(k) sqrt(k.^2 + p^2*gc(k).^2); Gs = @(k) sqrt(k.^2 + q^2*gs(k).^2); S = @(k) (p*ac(k) + q*as(k))/2; % Kekatpuere defnition (10) and (9) % f = @(k) tan(k*h/2) - ((p*q*gc(k) .* gs(k) - k.^2) - Gc(k).*Gs(k))./(k.*(p*gc(k) + q*gs(k))); % Kekatpure MDM % Plasmonic % fp = @(k) (k.^2 + 2*S(k).*k.*coth(k*h) + p*q*ac(k).*as(k))/k0; % Kekatpure DMD % Plasmonic fp = @(k) (tanh(k*h) + (k.*(p*ac(k) + q*as(k)))./(k.^2 + p*q*ac(k).*as(k)))/k0; % Dielectric f1 = @(k) (tan(k*h) - (k.*(p*gc(k) + q*gs(k)))./(k.^2 - p*q*gc(k).*gs(k))); % % Orfanidis definition % la0 = 632.8; % ef = (0.0657 - 4i)^2; % es = 1.5^2; % ec = 1.55^2; % p = ef/ec; % q = ef/es; % a = 20/2; % k0 = 2*pi/la0; % kp = @(beta) sqrt(beta.^2 - ef); % ac = @(beta) sqrt(beta.^2 - ec); % as = @(beta) sqrt(beta.^2 - es); % f2 = @(beta) tanh(2*kp(beta)*a) + (kp(beta).*(p*ac(beta) + q*as(beta)))./(kp(beta).^2 + p*q*ac(beta).*as(beta)); % f2 = @(x) sin(x) + x - 1; % r = newtzero(f2,1) % initial_guess = k0; % p = linspace(lxlim,uxlim,num); r = newtzero(f1,Ks); root = r neff = sqrt(ef - (r/k0).^2) % kp = kp(r)/k0
%% function that performs automatic time stepping function[delta_t_1] = time_stepping(P_n_1, P_n, simulation) po_n_k = P_n_1(1:2:size(P_n_1)); po_n = P_n(1:2:size(P_n)); sat_n_k =P_n_1(2:2:size(P_n_1)); sat_n = P_n(2:2:size(P_n)); delta_t_n = simulation.time_step; omega = 0.1; % tuning parameter eta_p = 50; % maximum desired change for pressure eta_s = 0.05; % maximum desired change for gas saturation min_po = min((1+omega)*eta_p./(abs(po_n_k-po_n)+omega*eta_p)); min_sat = min((1+omega)*eta_s./(abs(sat_n_k-sat_n)+omega*eta_s)); min_x = min(min_po, min_sat); delta_t_1 = delta_t_n * min_x; if delta_t_1 > simulation.max_step delta_t_1 = simulation.max_step; end if (delta_t_1 + simulation.cur_time) > simulation.tot_time delta_t_1 = simulation.tot_time - simulation.cur_time; end end
function best_class = CS6640_Bayes(x,class_probs,class_models) % CS6640_Bayes - Bayes classifier % On input: % x (mx1 vector): feature vector % class_pros (1xn vector): probabilities of n classes (sums to 1) % class_models (1xn vector struct): class models: means and % variances % (k).mean (mx1 vector): k_th class mean vector % (k).var (mxm array): k_th class covariance matrix % On output: % best_class (int): index of best class for x % Call: % c = CS6640_Bayes(x,cp,cm); % Author: % Rohit Singh % UU % Fall 2018 % no_of_classes=size(class_models,2); n = length(x); best_class=0; p_last=-inf; for class_no=1:no_of_classes m=class_models(class_no).mean; C=class_models(class_no).var; %term1 = ((2*pi)^(n/2))*((det(C))^(1/2)); %term2 = -(((x-m)')*(inv(C))*(x-m))/2; term1=-(1/2)*(log(det(C))); term2 = -(((x-m)')*... (inv(C))*(x-m))/2; p = log(class_probs(class_no))+term1+term2; if (p>p_last) best_class=class_no; p_last=p; end end
function [edge_set] = Local_Dead_End_Detector (input_val,cn_val_FW,cn_val_BW) %% Local_Dead_End_Detector %% % input_val=output_pt(3,:); smooth_val=input_val; input_len=length(smooth_val); forward_diff_smooth_val=[0,diff(smooth_val)]; backward_diff_smooth_val=fliplr([0,diff(fliplr(smooth_val))]); qual_flag=find(forward_diff_smooth_val==backward_diff_smooth_val); zero_flag1=find(forward_diff_smooth_val==0); zero_flag2=find(backward_diff_smooth_val==0); repeat_flag=setdiff(qual_flag,union(zero_flag1,zero_flag2)); if ~isempty(repeat_flag) while ~isempty(repeat_flag) for ind_i=2:input_len-1 pre_val=smooth_val(ind_i-1); cur_val=smooth_val(ind_i); nex_val=smooth_val(ind_i+1); if cur_val ~= pre_val && cur_val ~= nex_val && pre_val == nex_val smooth_val(ind_i)=max(pre_val,nex_val); end end forward_diff_smooth_val=[0,diff(smooth_val)]; backward_diff_smooth_val=fliplr([0,diff(fliplr(smooth_val))]); qual_flag=find(forward_diff_smooth_val==backward_diff_smooth_val); zero_flag1=find(forward_diff_smooth_val==0); zero_flag2=find(backward_diff_smooth_val==0); repeat_flag=setdiff(qual_flag,union(zero_flag1,zero_flag2)); end else end forward_diff_smooth_val=[0,diff(smooth_val)]; backward_diff_smooth_val=fliplr([0,diff(fliplr(smooth_val))]); edge1=intersect(find(forward_diff_smooth_val==cn_val_FW),find(backward_diff_smooth_val==-cn_val_FW)+1); % edge 0 to 125 edge2=intersect(find(forward_diff_smooth_val==cn_val_BW-cn_val_FW),find(backward_diff_smooth_val==cn_val_FW-cn_val_BW)+1); % edge 125 to 255 edge3=intersect(find(forward_diff_smooth_val==-cn_val_BW),find(backward_diff_smooth_val==cn_val_BW)+1); % edge 255 to 0 if isempty(edge2) || isempty(edge1) || isempty(edge3) edge_set=[]; else edge_set=[min(edge1),round(mean(edge2)),max(edge3)]; end % % figure (50) % plot(smooth_val,'b'); % hold; % plot(forward_diff_smooth_val,'ro'); % plot(backward_diff_smooth_val,'gs'); % hold;
% Copyright 2014 % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % http://www.apache.org/licenses/LICENSE-2.0 % % Unless required by applicable law or agreed to in writing, dx % distributed under the License is distributed on an "AS IS" BASIS, % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. % Input: nsim, id, iq; % Output: % - vector of the solutions SOL (nsim x 6); % - Temp\sim_gamma_numerosimulazione.fem; % - Temp\sim_gamma.mat (memorizza SOL) % The nsim x 6 matrix is organized by columns as folows: % SOL(1,:) = gamma, % SOL(2,:) = id, % SOL(3,:) = iq, % SOL(4,:) = fd, % SOL(5,:) = fq, % SOL(6,:) = torque; function [SOL] = simulate_xdeg(geo,io,gamma_in,eval_type) % number of simulation that must be done respect to eval type switch eval_type case 'MO_OA' gamma = gamma_in; nsim = geo.nsim_MOOA; xdeg = geo.delta_sim_MOOA; case 'MO_GA' gamma = gamma_in; nsim = geo.nsim_MOOA; xdeg = geo.delta_sim_MOOA; case 'singt' nsim = geo.nsim_singt; xdeg = geo.delta_sim_singt;gamma = gamma_in; case 'singm' nsim = geo.nsim_singt; xdeg = geo.delta_sim_singt;gamma = gamma_in; end % pathname = geo.pathname; pathname = cd; th0 = geo.th0; p = geo.p; r = geo.r; gap = geo.g; ns = geo.ns; pc = 360/(ns*p)/2; ps = geo.ps; % l = geo.l; %% simulation angle gradi_da_sim=180/p*ps; id = io * cos(gamma * pi/180); iq = io * sin(gamma * pi/180); Hc = geo.Hc; SOL = []; % rotor positions if strcmp(eval_type,'MO_OA')||strcmp(eval_type,'MO_GA') % during optimization, random position offset sim_step=xdeg/(nsim+0.5); offset=1*sim_step*rand; isOpen=0; %Disable parFor during optimization else % during re-evaluation, regular position steps sim_step=xdeg/(nsim); offset=0; isOpen=1; %Enable parFor during optimization end teta=offset:sim_step:xdeg+offset; % disregard the last position th=th0+[teta(1:nsim) teta(1)]; % evaluation of the phase current values for all positions to be simulated i1_tmp = zeros(1,nsim); i2_tmp = i1_tmp; i3_tmp = i1_tmp; for ij=1:nsim i123 = dq2abc(id,iq,th(ij)*pi/180); i1_tmp(ij) = i123(1); i2_tmp(ij) = i123(2); i3_tmp(ij) = i123(3); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% ciclo for %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for jj = 1:nsim th_m = (th(jj) - th0)/p; openfemm opendocument([pathname,'\mot0.fem']); % assign the phase current values to the FEMM circuits i1 = i1_tmp(jj); i2 = i2_tmp(jj); i3 = i3_tmp(jj); mi_modifycircprop('fase1',1,i1); mi_modifycircprop('fase1n',1,-i1); mi_modifycircprop('fase2',1,i2); mi_modifycircprop('fase2n',1,-i2); mi_modifycircprop('fase3',1,i3); mi_modifycircprop('fase3n',1,-i3); % assign the Hc property to the bonded magnets mi_modifymaterial('Bonded-Magnet',3,Hc); % delete the airgap arc prior to moving the rotor mi_selectgroup(20), mi_deleteselectedarcsegments; % rotate the rotor mi_selectgroup(2), mi_moverotate(0,0,th_m); % redraw the airgap arc draw_airgap_arc_with_mesh(geo,th_m,geo.fem) mi_saveas([pathname,'\mot_temp.fem']); mi_analyze(1); mi_loadsolution; post_proc; mo_close, mi_close closefemm SOL = [SOL; sol]; end % Effective value of flux and current, simulation are done with one turns % in slot and consequently, current in fem simulation is increase by the number of conductors in slot Nbob.... SOL(:,2)=SOL(:,2)/geo.Nbob; SOL(:,3)=SOL(:,3)/geo.Nbob; SOL(:,4)=SOL(:,4)*geo.Nbob; SOL(:,5)=SOL(:,5)*geo.Nbob; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FINE VECCHIO CICLO FOR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % end %% VERIFICA CHE I DUE CICLI FOR E PARFOR DIANO LO STESSO RISULTATO %% % ERROR = SOL-SOL_PARFOR_temp
function x=mixrand(x) % MIXRAND resorts the elements in vector x in a random way. % x=MIXRAND(x) % (c) Lehrstuhl fuer allgemeine Elektrotechnik und Akustik % Ruhr-Universitaet Bochum % (p) 13.06.1994 A. Raab L=length(x); ri=round((L-1)*rand(1,L+1)+1); % random index to vector x for i=1:L t=x(ri(i)); % exchange two elements x(ri(i))=x(ri(i+1)); % at random position x(ri(i+1))=t; end;