plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
UMN-Hydro/GSFLOW_pre-processor-master
write_lpf_MOD2_f2.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_lpf_MOD2_f2.m
5,547
utf_8
7123a8788999fc93894d61afd875da5e
% write_lpf_MOD % 11/17/16 function write_lpf_MOD2_f2(GSFLOW_indir, infile_pre, surfz_fil, NLAY) % % =========== TO RUN AS SCRIPT =========================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % % for sfr % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; % % ==================================================================== % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % lpf_file = 'test.lpf'; lpf_file = [infile_pre, '.lpf']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 2; % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); fclose(fid); % -- Base hydcond, Ss (all layers), and Sy (top layer only) on data from files % (temp place-holder) hydcond = ones(NROW,NCOL,NLAY)*2; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.5; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,1) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,1) = 0.01; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,2) = 0.01; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) Ss = ones(NROW,NCOL,NLAY)* 2e-6; % constant 2e-6 /m for Sagehen Sy = ones(NROW,NCOL,NLAY)*0.15; % 0.08-0.15 in Sagehen (lower Sy under ridges for volcanic rocks) WETDRY = Sy; % = Sy in Sagehen (lower Sy under ridges for volcanic rocks) % -- assumed input values flow_filunit = 34; % make sure this matches namefile!! hdry = 1e30; % head assigned to dry cells nplpf = 0; % number of LPF parameters (if >0, key words would follow) laytyp = zeros(NLAY,1); laytyp(1) = 1; % flag, top>0: "covertible", rest=0: "confined" layave = zeros(NLAY,1); % flag, layave=1: harmonic mean for interblock transmissivity chani = ones(NLAY,1); % flag, chani=1: constant horiz anisotropy mult factor (for each layer) layvka = zeros(NLAY,1); % flag, layvka=0: vka is vert K; >0 is vertK/horK ratio VKA = hydcond; laywet = zeros(NLAY,1); laywet(1)=1; % flag, 1: wetting on for top convertible cells, 0: off for confined fl_Tr = 1; % flag, 1 for at least 1 transient stress period (for Ss and Sy) WETFCT = 1.001; % 1.001 for Sagehen, wetting (convert dry cells to wet) IWETIT = 4; % number itermations for wetting IHDWET = 0; % wetting scheme, 0: equation 5-32A is used: h = BOT + WETFCT (hn - BOT) %% ------------------------------------------------------------------------ fmt1 = repmat('%2d ', 1, NLAY); fil_lpf_0 = [GSFLOW_indir, slashstr, lpf_file]; fid = fopen(fil_lpf_0, 'wt'); fprintf(fid, '# LPF package inputs\n'); fprintf(fid, '%d %g %d ILPFCB,HDRY,NPLPF\n', flow_filunit, hdry, nplpf); fprintf(fid, [fmt1, ' LAYTYP\n'], laytyp); fprintf(fid, [fmt1, ' LAYAVE\n'], layave); fprintf(fid, [fmt1, ' CHANI \n'], chani); fprintf(fid, [fmt1, ' LAYVKA\n'], layvka); fprintf(fid, [fmt1, ' LAYWET\n'], laywet); if ~isempty(find(laywet,1)) fprintf(fid, '%g %d %d WETFCT, IWETIT, IHDWET\n', WETFCT, IWETIT, IHDWET); end % -- Write HKSAT and Ss, Sy (if Tr) in .lpf file format0 = [repmat(' %4.2f ', 1, NCOL), '\n']; format1 = [repmat(' %4.2e ', 1, NCOL), '\n']; % loop thru layers (different entry for each layer) for lay = 1: NLAY fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 HY layer %d\n', lay); % horizontal hyd cond fprintf(fid, format1, hydcond(:,:,lay)'); fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 VKA layer %d\n', lay); % vertical hyd cond fprintf(fid, format1, VKA(:,:,lay)'); if fl_Tr fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Ss layer %d\n', lay); fprintf(fid, format1, Ss(:,:,lay)'); if laytyp(lay) > 0 % convertible, i.e. unconfined fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Sy layer %d\n', lay); fprintf(fid, format1, Sy(:,:,lay)'); if laywet(lay) > 0 fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 WETDRY layer %d\n', lay); fprintf(fid, format0, WETDRY(:,:,lay)'); end end end end fprintf(fid, '\n'); fclose(fid);
github
UMN-Hydro/GSFLOW_pre-processor-master
write_ba6_MOD3.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_ba6_MOD3.m
6,046
utf_8
c967103aeca207643dcd775bdb4760b4
% write_ba6_MOD % 11/17/16 function write_ba6_MOD3(GSFLOW_indir, infile_pre, mask_fil) % % ==== TO RUN AS SCRIPT =================================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % ========================================================================= %% % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; ba6_file = [infile_pre, '.ba6']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 1; % NROW = 50; % NCOL = 50; % -- IBOUND(NROW,NCOL,NLAY): <0 const head, 0 no flow, >0 variable head % use basin mask (set IBOUND>0 within watershed, =0 outside watershed, <0 at discharge point and 2 neighboring pixels) % mask_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/basinmask_dischargept.asc'; fid = fopen(mask_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); D = textscan(fid, '%f'); IBOUND = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL D = textscan(fid, '%s %s %f %s %f'); dischargePt_rowi = D{3}; dischargePt_coli = D{5}; fclose(fid); % - force some cells to be active to correspond to stream reaches IBOUND(14,33) = 1; IBOUND(11,35) = 1; IBOUND(12,34) = 1; IBOUND(7,43) = 1; % find boundary cells IBOUNDin = IBOUND(2:end-1,2:end-1); IBOUNDu = IBOUND(1:end-2,2:end-1); % up IBOUNDd = IBOUND(3:end,2:end-1); % down IBOUNDl = IBOUND(2:end-1,1:end-2); % left IBOUNDr = IBOUND(2:end-1,3:end); % right % - inner boundary is constant head ind_bound = IBOUNDin==1 & (IBOUNDin-IBOUNDu==1 | IBOUNDin-IBOUNDd==1 | ... IBOUNDin-IBOUNDl==1 | IBOUNDin-IBOUNDr==1); % - outer boundary is constant head % ind_bound = IBOUNDin==0 & (IBOUNDin-IBOUNDu==-1 | IBOUNDin-IBOUNDd==-1 | ... % IBOUNDin-IBOUNDl==-1 | IBOUNDin-IBOUNDr==-1); % -- init head: base on TOP and BOTM dis_file = [GSFLOW_indir, '/', infile_pre, '.dis']; fid = fopen(dis_file); for ii = 1:2, cmt = fgets(fid); end line0 = fgets(fid); D = textscan(line0, '%d', 6); NLAY = D{1}(1); NROW = D{1}(2); NCOL = D{1}(3); NPER = D{1}(4); ITMUNI = D{1}(5); LENUNI = D{1}(6); line0 = fgets(fid); D = textscan(line0, '%d'); LAYCBD = D{1}; % 1xNLAY (0 if no confining layer) line0 = fgets(fid); D = textscan(line0, '%s %d'); DELR = D{2}; % width of column line0 = fgets(fid); D = textscan(line0, '%s %d'); DELC = D{2}; % height of row TOP = nan(NROW,NCOL); line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); TOP(irow,:) = D{1}(1:NCOL); end BOTM = nan(NROW, NCOL, NLAY); for ilay = 1: NLAY line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); BOTM(irow,:,ilay) = D{1}(1:NCOL); end end fclose(fid); % - make boundary cells constant head above a certain elevation % IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 4500) = -1; IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 3500) = -1; IBOUND(2:end-1,2:end-1,1) = IBOUNDin; % - make discharge point and neighboring cells constant head IBOUND(dischargePt_rowi,dischargePt_coli,1) = -2; % downgrad of discharge pt % IBOUND(dischargePt_rowi-1,dischargePt_coli,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli+1,1) = -2; % downgrad of discharge pt IBOUND(dischargePt_rowi-1,dischargePt_coli+1,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli+1,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli,1) = 1; % downgrad of discharge pt IBOUND = repmat(IBOUND, [1 1 NLAY]); % - initHead(NROW,NCOL,NLAY) initHead = BOTM(:,:,1) + (TOP-BOTM(:,:,1))*0.9; % within top layer % % (no more than 10m below top): % Y = nan(NROW,NCOL,2); Y(:,:,1) = initHead; Y(:,:,2) = TOP-10; % initHead = max(Y,[],3); initHead = repmat(initHead, [1, 1, NLAY]); % - assumed values HNOFLO = -999.99; %% ------------------------------------------------------------------------ % -- Write ba6 file fil_ba6_0 = [GSFLOW_indir, slashstr, ba6_file]; fmt1 = [repmat('%4d ', 1, NCOL), '\n']; % for IBOUND fmt2 = [repmat('%7g ', 1, NCOL), '\n']; % for initHead fid = fopen(fil_ba6_0, 'wt'); fprintf(fid, '# basic package file --- %d layers, %d rows, %d columns\n', NLAY, NROW, NCOL); fprintf(fid, 'FREE\n'); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 IBOUND for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt1, IBOUND(:,:,ilay)'); end fprintf(fid, ' %f HNOFLO\n', HNOFLO); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 init head for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt2, initHead(:,:,ilay)'); end fclose(fid); % -- Plot basics for ii = 1:2 if ii == 1, X0 = IBOUND; ti0 = 'IBOUND'; elseif ii == 2 X0 = initHead; ti0 = 'init head'; end figure for ilay = 1:NLAY subplot(2,2,double(ilay)) X = X0(:,:,ilay); m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; % cm(1,:) = [1 1 1]; colormap(cm); colorbar title([ti0, ' lay', num2str(ilay)]); end end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_ba6_MOD2_bu.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_ba6_MOD2_bu.m
5,863
utf_8
1f12d52d0b1416b1514618c0791f04d0
% write_ba6_MOD % 11/17/16 function write_ba6_MOD2(GSFLOW_indir, infile_pre, surfz_fil, mask_fil, NLAY, DZ) % % ==== TO RUN AS SCRIPT =================================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % ========================================================================= %% % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; ba6_file = [infile_pre, '.ba6']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 1; % NROW = 50; % NCOL = 50; % -- IBOUND(NROW,NCOL,NLAY): <0 const head, 0 no flow, >0 variable head % use basin mask (set IBOUND>0 within watershed, =0 outside watershed, <0 at discharge point and 2 neighboring pixels) % mask_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/basinmask_dischargept.asc'; fid = fopen(mask_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); D = textscan(fid, '%f'); IBOUND = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL D = textscan(fid, '%s %s %f %s %f'); dischargePt_rowi = D{3}; dischargePt_coli = D{5}; fclose(fid); % - force some cells to be active to correspond to stream reaches IBOUND(14,33) = 1; IBOUND(11,35) = 1; IBOUND(12,34) = 1; IBOUND(7,43) = 1; % find boundary cells IBOUNDin = IBOUND(2:end-1,2:end-1); IBOUNDu = IBOUND(1:end-2,2:end-1); % up IBOUNDd = IBOUND(3:end,2:end-1); % down IBOUNDl = IBOUND(2:end-1,1:end-2); % left IBOUNDr = IBOUND(2:end-1,3:end); % right ind_bound = IBOUNDin==1 & (IBOUNDin-IBOUNDu==1 | IBOUNDin-IBOUNDd==1 | ... IBOUNDin-IBOUNDl==1 | IBOUNDin-IBOUNDr==1); % IBOUNDin(ind) = -1; % IBOUND(2:end-1,2:end-1) = IBOUNDin; % -- init head: base on TOP and BOTM % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); if ~isempty(find(NSEW ~= D{2}(1:4),1)) || NROW ~= D{2}(5) || NCOL ~= D{2}(6); fprintf('Error!! NSEW, NROW, or NCOL in data files do not match!\n'); fprintf(' (files: %d and %d\n', mask_fil, surfz_fil); fprintf('exiting...\n'); return end % - space discretization DELR = (NSEW(3)-NSEW(4))/NCOL; % width of column [m] DELC = (NSEW(1)-NSEW(2))/NROW; % height of row [m] % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % DZ = [5; 5]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % - set TOP to surface elevation [m] D = textscan(fid, '%f'); fclose(fid); TOP = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL BOTM = zeros(NROW, NCOL, NLAY); BOTM(:,:,1) = TOP-DZ(1); for ilay = 2:NLAY BOTM(:,:,ilay) = BOTM(:,:,ilay-1)-DZ(ilay); end % - make boundary cells constant head above a certain elevation % IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 4500) = -1; IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 3500) = -1; IBOUND(2:end-1,2:end-1,1) = IBOUNDin; % - make discharge point and neighboring cells constant head IBOUND(dischargePt_rowi,dischargePt_coli,1) = -2; % downgrad of discharge pt % IBOUND(dischargePt_rowi-1,dischargePt_coli,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli+1,1) = -2; % downgrad of discharge pt IBOUND(dischargePt_rowi-1,dischargePt_coli+1,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli+1,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli,1) = 1; % downgrad of discharge pt IBOUND = repmat(IBOUND, [1 1 NLAY]); % - initHead(NROW,NCOL,NLAY) initHead = BOTM(:,:,1) + (TOP-BOTM(:,:,1))*0.9; % within top layer initHead = repmat(initHead, [1, 1, NLAY]); % - assumed values HNOFLO = -999.99; %% ------------------------------------------------------------------------ % -- Write ba6 file fil_ba6_0 = [GSFLOW_indir, slashstr, ba6_file]; fmt1 = [repmat('%4d ', 1, NCOL), '\n']; % for IBOUND fmt2 = [repmat('%7g ', 1, NCOL), '\n']; % for initHead fid = fopen(fil_ba6_0, 'wt'); fprintf(fid, '# basic package file --- %d layers, %d rows, %d columns\n', NLAY, NROW, NCOL); fprintf(fid, 'FREE\n'); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 IBOUND for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt1, IBOUND(:,:,ilay)'); end fprintf(fid, ' %f HNOFLO\n', HNOFLO); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 init head for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt2, initHead(:,:,ilay)'); end fclose(fid); % -- Plot basics for ii = 1:2 if ii == 1, X0 = IBOUND; ti0 = 'IBOUND'; elseif ii == 2 X0 = initHead; ti0 = 'init head'; end figure for ilay = 1:NLAY subplot(2,2,double(ilay)) X = X0(:,:,ilay); m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; % cm(1,:) = [1 1 1]; colormap(cm); colorbar title([ti0, ' lay', num2str(ilay)]); end end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_lpf_MOD2_f2_2.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_lpf_MOD2_f2_2.m
7,349
utf_8
1987d3c8d54b48bd223a82357bdba31d
% write_lpf_MOD % 11/17/16 function write_lpf_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY) % % =========== TO RUN AS SCRIPT =========================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % % for sfr % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; buffer_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/segments_buffer2.asc'; % % ==================================================================== % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % lpf_file = 'test.lpf'; lpf_file = [infile_pre, '.lpf']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 2; % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); % - space discretization DELR = (NSEW(3)-NSEW(4))/NCOL; % width of column [m] DELC = (NSEW(1)-NSEW(2))/NROW; % height of row [m] % - set TOP to surface elevation [m] D = textscan(fid, '%f'); fclose(fid); fprintf('Done reading...\n'); TOP = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL % get buffer info fid = fopen(buffer_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); D = textscan(fid, '%f'); buffer = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL fclose(fid); % -- Base hydcond, Ss (all layers), and Sy (top layer only) on data from files % (temp place-holder) hydcond = ones(NROW,NCOL,NLAY)*2; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.5; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,1) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,1) = 0.01; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,2) = 0.01; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) Ss = ones(NROW,NCOL,NLAY)* 2e-6; % constant 2e-6 /m for Sagehen Sy = ones(NROW,NCOL,NLAY)*0.15; % 0.08-0.15 in Sagehen (lower Sy under ridges for volcanic rocks) WETDRY = Sy; % = Sy in Sagehen (lower Sy under ridges for volcanic rocks) % % use buffer (and elev?) % K = buffer; % 0: very far from stream, 5: farthest from stream in buffer, 1: closest to stream % K(buffer==0) = 0.04; % very far from streams % K(buffer==0 & TOP>5000) = 0.03; % very far from streams % K(buffer>=1) = 0.5; % close to streams % K(buffer>=2) = 0.4; % K(buffer>=3) = 0.3; % K(buffer>=4) = 0.15; % K(buffer==5) = 0.08; % farthest from stream and high % hydcond(:,:,1) = K; % hydcond(:,:,2) = 0.01; % use buffer (and elev?) K = buffer; % 0: very far from stream, 5: farthest from stream in buffer, 1: closest to stream K(buffer==0) = 0.04; % very far from streams K(buffer==0 & TOP>5000) = 0.03; % very far from streams % K(buffer>=1) = 0.5; % close to streams K(buffer>=1) = 0.25; % close to streams K(buffer>=2) = 0.15; K(buffer>=3) = 0.08; K(buffer>=4) = 0.08; K(buffer==5) = 0.08; % farthest from stream and high hydcond(:,:,1) = K; hydcond(:,:,2) = 0.01; % -- assumed input values flow_filunit = 34; % make sure this matches namefile!! hdry = 1e30; % head assigned to dry cells nplpf = 0; % number of LPF parameters (if >0, key words would follow) laytyp = zeros(NLAY,1); laytyp(1) = 1; % flag, top>0: "covertible", rest=0: "confined" layave = zeros(NLAY,1); % flag, layave=1: harmonic mean for interblock transmissivity chani = ones(NLAY,1); % flag, chani=1: constant horiz anisotropy mult factor (for each layer) layvka = zeros(NLAY,1); % flag, layvka=0: vka is vert K; >0 is vertK/horK ratio VKA = hydcond; laywet = zeros(NLAY,1); laywet(1)=1; % flag, 1: wetting on for top convertible cells, 0: off for confined fl_Tr = 1; % flag, 1 for at least 1 transient stress period (for Ss and Sy) WETFCT = 1.001; % 1.001 for Sagehen, wetting (convert dry cells to wet) IWETIT = 4; % number itermations for wetting IHDWET = 0; % wetting scheme, 0: equation 5-32A is used: h = BOT + WETFCT (hn - BOT) %% ------------------------------------------------------------------------ fmt1 = repmat('%2d ', 1, NLAY); fil_lpf_0 = [GSFLOW_indir, slashstr, lpf_file]; fid = fopen(fil_lpf_0, 'wt'); fprintf(fid, '# LPF package inputs\n'); fprintf(fid, '%d %g %d ILPFCB,HDRY,NPLPF\n', flow_filunit, hdry, nplpf); fprintf(fid, [fmt1, ' LAYTYP\n'], laytyp); fprintf(fid, [fmt1, ' LAYAVE\n'], layave); fprintf(fid, [fmt1, ' CHANI \n'], chani); fprintf(fid, [fmt1, ' LAYVKA\n'], layvka); fprintf(fid, [fmt1, ' LAYWET\n'], laywet); if ~isempty(find(laywet,1)) fprintf(fid, '%g %d %d WETFCT, IWETIT, IHDWET\n', WETFCT, IWETIT, IHDWET); end % -- Write HKSAT and Ss, Sy (if Tr) in .lpf file format0 = [repmat(' %4.2f ', 1, NCOL), '\n']; format1 = [repmat(' %4.2e ', 1, NCOL), '\n']; % loop thru layers (different entry for each layer) for lay = 1: NLAY fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 HY layer %d\n', lay); % horizontal hyd cond fprintf(fid, format1, hydcond(:,:,lay)'); fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 VKA layer %d\n', lay); % vertical hyd cond fprintf(fid, format1, VKA(:,:,lay)'); if fl_Tr fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Ss layer %d\n', lay); fprintf(fid, format1, Ss(:,:,lay)'); if laytyp(lay) > 0 % convertible, i.e. unconfined fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Sy layer %d\n', lay); fprintf(fid, format1, Sy(:,:,lay)'); if laywet(lay) > 0 fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 WETDRY layer %d\n', lay); fprintf(fid, format0, WETDRY(:,:,lay)'); end end end end fprintf(fid, '\n'); fclose(fid); figure for ilay = 1:NLAY subplot(2,2,double(ilay)) X = hydcond(:,:,ilay); m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; % cm(1,:) = [1 1 1]; caxis([0 max(X(:))]) colormap(cm); colorbar title(['hydcond', num2str(ilay)]); end
github
UMN-Hydro/GSFLOW_pre-processor-master
make_sfr2_f_Mannings.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/make_sfr2_f_Mannings.m
17,011
utf_8
e13e86b33d9983c53be1b54cc3a79c20
% make_sfr.m % 1/8/16 % Leila Saberi % % 2 - gcng function make_sfr2_f_Mannings(GSFLOW_indir, infile_pre, reach_fil, segment_fil_all) % Note: assume .dis file already created!! (reads in TOP for setting STRTOP) % % ======== TO RUN AS SCRIPT =============================================== % % clear all, close all, fclose all; % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % infile_pre = 'test2lay'; % % % for sfr % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; % % ========================================================================= %% sfr_file = [infile_pre, '.sfr']; % -- Refer to GSFLOW manual p.202, SFR1 manual, and SFR2 manual % - Refer to Fig. 1 of SFR1 documentation for segment vs. reach numbering % You need the following inputs (with corresponding structures) % the followings are used to write item 1 fl_nstrm = -1; % flag for stream reaches, <0: include unsaturated zone below (sagehen: >0) nsfrpar = 0; %Always Zero nparseg = 0; %Always Zero const = 86400.; %Conversion factor used in calculating depth for a stream reach (86400 in sagehen example) dleak = 0.0001; %Tolerance level of stream depth used in computing leakage between each stream (0.0001 in sagehen example) istcb1 = -1; %Flag for writing stream-aquifer leakage values (>0: file unit, <0: write to listing file) istcb2 = 0; %Flag for writing to a seperate formatted file information on inflows&outflows isfropt = 3; %defines input structure; saturated or non-saturated zone (1: No UZ; 3: UZ, unsat prop at start of simulation), sagehen uses 3 nstrail = 10; %Number of trailing-waive increments, incr for better mass balance (10-20 rec'd, sagehen uses 8) isuzn = 1; %Maximum number of vertical cells used to define the unsaturated zone beneath a stream reach (for icalc=1 (Mannings for depth): use isuzn=1) nsfrsets = 40; %Maximum number of different sets of trailing waves used to allocate arrays. irtflg = 0; %Flag whether transient streamflow routing is active project_name = 'TestProject'; % used to name the output file (.sfr) % data_indir = '/home/gcng/workspace/matlab_files/GSFLOW_pre-processor/MODFLOW_scripts/sfr_final/data/'; % data_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % items reach_data_all = importdata(reach_fil); % used to write item 2: assumes NPER = 2; % used for item 3 % items 4a: # NSEG ICALC OUTSEG IUPSEG IPRIOR NSTRPTS FLOW RUNOFF ETSW PPTSW ROUGHCH ROUGHBK CDPTH FDPTH AWDTH BWDTH segment_data_4A = importdata(segment_fil_all{1}); % used to write items 4a segment_data_4B = importdata(segment_fil_all{2}); % used to write items 4b (ignored for ICALC=3 in 4a) segment_data_4C = importdata(segment_fil_all{3}); % used to write items 4c (ignored for ICALC=3 in 4a) % ------------------------------------------------------------------------- % In case the input text files (e.g. reach_data.txt) contain header lines (comments) if isstruct(reach_data_all) reach_data_all0 = reach_data_all.data; nstrm = size(reach_data_all0,1); if fl_nstrm < 0, nstrm = -nstrm; end % sort rows according to increasing segment numbers [~, ind] = sort(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')), 'ascend'); reach_data_all0 = reach_data_all0(ind,:); nss = max(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG'))); % sort rows according to increasing reach numbers for ii = 1: nss ind1 = find(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')) == ii); [~, ind2] = sort(reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')), 'ascend'); reach_data_all0(ind1,:) = reach_data_all0(ind1(ind2),:); % renumber IREACH to start at 1 for each segment reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')) = [1:length(ind1)]; end X = mat2cell(reach_data_all0, abs(nstrm), ones(size(reach_data_all0,2),1)); [KRCH,IRCH,JRCH,ISEG,IREACH,RCHLEN,STRTOP,SLOPE,STRTHICK,STRHC1,THTS,THTI,EPS,UHC] = X{:}; % -- make sure STRTOP is within 1st layer % - read in TOP and BOTM from .dis file dis_file = [GSFLOW_indir, '/', infile_pre, '.dis']; fid = fopen(dis_file); for ii = 1:2, cmt = fgets(fid); end line0 = fgets(fid); D = textscan(line0, '%d', 6); NLAY = D{1}(1); NROW = D{1}(2); NCOL = D{1}(3); NPER = D{1}(4); ITMUNI = D{1}(5); LENUNI = D{1}(6); line0 = fgets(fid); D = textscan(line0, '%d'); LAYCBD = D{1}; % 1xNLAY (0 if no confining layer) line0 = fgets(fid); D = textscan(line0, '%s %d'); DELR = D{2}; % width of column line0 = fgets(fid); D = textscan(line0, '%s %d'); DELC = D{2}; % height of row TOP = nan(NROW,NCOL); line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); TOP(irow,:) = D{1}(1:NCOL); end BOTM = nan(NROW, NCOL, NLAY); for ilay = 1: NLAY line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); BOTM(irow,:,ilay) = D{1}(1:NCOL); end end fclose(fid); % TOP for cells corresponding to reaches TOP_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), TOP_RCH(ii) = TOP(IRCH(ii),JRCH(ii)); end % BOTM for cells corresponding to reaches BOTM_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), BOTM_RCH(ii) = BOTM(IRCH(ii),JRCH(ii),KRCH(ii)); end % - set STRTOP to be just below TOP STRTOP = TOP_RCH - 2; if ~isempty(find(STRTOP-STRTHICK < BOTM_RCH,1)) fprintf('Error! STRTOP is below BOTM of the corresponding layer! Exiting...\n'); end reach_data_all0(:,strcmp(reach_data_all.colheaders, 'STRTOP')) = STRTOP; % -- plot stream reaches RCH_mask = TOP; for ii = 1:abs(nstrm), RCH_mask(IRCH(ii),JRCH(ii)) = max(TOP(:))*2; end figure subplot(2,2,1) imagesc(TOP), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); subplot(2,2,2) imagesc(RCH_mask), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); for ii = 1:abs(nstrm), RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); end for ii = 1:abs(nstrm), SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); end figure imagesc(RCH_NUM), colorbar, colormap(jet(1+max(IREACH))); caxis([-0.5 max(IREACH)+0.5]) figure imagesc(SEG_NUM), colorbar, colormap(jet(1+max(ISEG))); caxis([-0.5 max(ISEG)+0.5]) % % when running as script: to visualize segments one at a time % for j = 1: max(ISEG) % RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); % ind = find(ISEG==j); % for ii = ind(:)' % RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); % SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); % end % % figure(100) % imagesc(RCH_NUM), colorbar, % colormap(jet(1+max(RCH_NUM(:)))); % caxis([-0.5 max(RCH_NUM(:))+0.5]) % title(['reaches for seg ', num2str(j)]); % figure(101) % imagesc(SEG_NUM), colorbar, % colormap(jet(1+max(SEG_NUM(:)))); % caxis([-0.5 max(SEG_NUM(:))+0.5]) % title(['seg ', num2str(j)]); % pause % end % -- threshold slope at minimum 0.001 ind = reach_data_all0(:,strcmp(reach_data_all.colheaders, 'SLOPE')) < 0.001; reach_data_all0(ind,strcmp(reach_data_all.colheaders, 'SLOPE')) = 0.001; % -- set streambed thickness (Sagehen uses constant 1m) ind = strcmp(reach_data_all.colheaders, 'STRTHICK'); reach_data_all0(:,ind) = 1; % [m] % -- set streambed hydraulic conductivity (Sagehen example: 5 m/d) ind = strcmp(reach_data_all.colheaders, 'STRHC1'); reach_data_all0(:,ind) = 5; % set streambed theta_s ind = strcmp(reach_data_all.colheaders, 'THTS'); reach_data_all0(:,ind) = 0.35; % set streambed initial theta ind = strcmp(reach_data_all.colheaders, 'THTI'); reach_data_all0(:,ind) = 0.3; % set streambed Brooks-Corey exp (sagehen example is 3.5) ind = strcmp(reach_data_all.colheaders, 'EPS'); reach_data_all0(:,ind) = 3.5; % set streambed unsaturated zone saturated hydraulic conductivity % (sagehen example is 0.3 m/d) ind = strcmp(reach_data_all.colheaders, 'UHC'); reach_data_all0(:,ind) = 0.3; reach_data_all = reach_data_all0; end if isstruct(segment_data_4A) segment_data_4A = segment_data_4A.data; nss = size(segment_data_4A,1); %Number of stream segments end if isstruct(segment_data_4B) segment_data_4B = segment_data_4B.data; end if isstruct(segment_data_4C) segment_data_4C = segment_data_4C.data; end % if isstruct(stress_periods) % stress_periods = stress_periods.data; % end % - specify only for 2 stress periods: stress_periods = zeros(NPER, 3); % itmp, irdflg, iptflg (latter 2 are set to 0) stress_periods(1,1) = nss; if NPER > 1, stress_periods(2:end,1) = -1; end % ------------------------------------------------------------------------- % First put 4A, 4B and 4C data all together in a cell array % size(cell) = nitems x 1 x nperiods % In this case, nitems is 3 (i.e. 4A, 4B and 4C) nitems = 3; nperiods = size(stress_periods, 1); segment_data_all = cell(nitems, 1, nperiods); segment_data_all{1, 1, 1} = segment_data_4A; segment_data_all{2, 1, 1} = segment_data_4B; segment_data_all{3, 1, 1} = segment_data_4C; % ------------------------------------------------------------------------- % validate some of the input data msg_invalidISFROPT = ['Error: ISFROPT should be set to an integer of', ... '1, 2, 3, 4 or 5.']; if (nstrm < 0) if ~ismember(isfropt, [1, 2, 3, 4, 5]) error(msg_invalidISFROPT); end end msg_notSupport = ['Error: %s: this variable must be zero because ', ... 'parameters are not supported in GSFLOW.']; if (nsfrpar ~= 0) error(msg_notSupport, 'NSFRPAR'); end if (nparseg ~= 0) error(msg_notSupport, 'NPARSEG'); end % ------------------------------------------------------------------------- % Ouput file fid = fopen([GSFLOW_indir, '/', sfr_file], 'wt'); % Write header lines (item 0) heading = '# Streamflow-Routing (SFR7) input file.\n'; fprintf(fid, heading); fprintf(fid, '# %s simulation -- created on %s.\n', upper(project_name), date); % Item 1 fprintf(fid, ' %5d %5d %5d %5d %8.2f %8.4f %5d %5d', ... nstrm, nss, nsfrpar, nparseg, const, dleak, istcb1, istcb2); if (isfropt >= 1) fprintf(fid, ' %5d', isfropt); if (isfropt == 1) fprintf(fid, ' %5d\n', irtflg); elseif (isfropt > 1) fprintf(fid, ' %5d %5d %5d %5d\n', nstrail, isuzn, nsfrsets, irtflg); end else fprintf(fid, '\n'); end % Item 2 if (isfropt == 1) ncols_reach = 10; elseif (isfropt == 2) ncols_reach = 13; elseif (isfropt == 3) ncols_reach = 14; else ncols_reach = 6; end reach_data_copy = reach_data_all(:, 1:ncols_reach); p = ncols_reach - 5; fmt_reach = [repmat(' %5d', 1, 5), repmat(' %8.3f', 1, p), '\n']; for istrm=1:abs(nstrm) dummy = reach_data_copy(istrm, :); fprintf(fid, fmt_reach, dummy); end % Item 3 and 4 nper = size(stress_periods, 1); for iper=1:nper % write item 3 to the file dummy3 = num2cell(stress_periods(iper, :)); [itmp, irdflg, iptflg] = dummy3{:}; fprintf(fid, ' %5d %5d %5d\n', itmp, irdflg, iptflg); if (itmp > 0) seg_inf_4a = segment_data_all{1, 1, iper}; seg_inf_4b = segment_data_all{2, 1, iper}; seg_inf_4c = segment_data_all{3, 1, iper}; for iitmp=1:itmp % start loop over itmp (num_segments) % write item 4a to the file dummy4a = num2cell(seg_inf_4a(iitmp, :)); [nseg, icalc, outseg, iupseg, iprior, nstrpts, ... flow, runoff, etsw, pptsw, roughch, roughbk, ... cdpth, fdpth, awdth, bwdth] = dummy4a{:}; fmt = [' ', repmat(' %5d', 1, 4)]; fprintf(fid, fmt, nseg, icalc, outseg, iupseg); if (iupseg > 0) fprintf(fid, ' %5d', iprior); end if (icalc == 4) fprintf(fid, ' %5d', nstrpts); end fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, flow, runoff, etsw, pptsw); if ((icalc == 1) || (icalc == 2)) fprintf(fid, ' %8.3f', roughch); end if (icalc == 2) fprintf(fid, ' %8.3f', roughbk); end if (icalc == 3) fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, cdpth, fdpth, awdth, bwdth); end fprintf(fid, '\n'); % write items 4b and 4c to the file suffixes = 'bc'; for i=1:2 % start loop over i suffix = suffixes(i); var_str = ['seg_inf_4', suffix]; var = eval(var_str); dummy4bc = num2cell(var(iitmp, :)); [hcond, thickm, elevupdn, width, ... depth, thts, thti, eps, uhc] = dummy4bc{:}; fl_no_4bc = 0; if (ismember(isfropt, [0, 4, 5]) && (icalc <= 0)) fmt = [' ', repmat(' %8.3f', 1, 5)]; fprintf(fid, fmt, hcond, thickm, elevupdn, width, depth); elseif (ismember(isfropt, [0, 4, 5]) && (icalc == 1)) fprintf(fid, ' %8.3f', hcond); if (iper == 1) % only for the first period fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); if ((isfropt == 4) || (isfropt == 5)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); end if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end elseif ((iper > 1) && (isfropt == 0)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); end elseif (ismember(isfropt, [0, 4, 5]) && (icalc >= 2)) fprintf(fid, ' %8.3f', hcond); if ~(ismember(isfropt, [4, 5]) && (iper > 1) && (icalc == 2)) fprintf(fid, ' %8.3f %8.3f', thickm, elevupdn); if (ismember(isfropt, [4, 5]) && (iper == 1) && (icalc == 2)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end end end elseif ((isfropt == 1) && (icalc <= 1)) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end elseif (ismember(isfropt, [2, 3]) && (icalc <= 1)) if (iper == 1) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end end else fl_no_4bc = 1; end if ~fl_no_4bc fprintf(fid, '\n'); end end % terminate loop over i (4b and 4c, respectively) end % terminate loop over itmp (num_segments) end % enf if (itmp > 0) end % terminate loop over iper (num_periods) fclose(fid); % ------------------------------------------------------------------------- % End of the script
github
UMN-Hydro/GSFLOW_pre-processor-master
make_sfr2_f.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/make_sfr2_f.m
16,998
utf_8
0ad0153cb953fb0dc4dfac073cf5d6b4
% make_sfr.m % 1/8/16 % Leila Saberi % % 2 - gcng function make_sfr2_f(GSFLOW_indir, infile_pre, reach_fil, segment_fil_all) % Note: assume .dis file already created!! (reads in TOP for setting STRTOP) % % ======== TO RUN AS SCRIPT =============================================== % clear all, close all, fclose all; % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % infile_pre = 'test2lay'; % % % for sfr % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; % % ========================================================================= %% sfr_file = [infile_pre, '.sfr']; % -- Refer to GSFLOW manual p.202, SFR1 manual, and SFR2 manual % - Refer to Fig. 1 of SFR1 documentation for segment vs. reach numbering % You need the following inputs (with corresponding structures) % the followings are used to write item 1 fl_nstrm = -1; % flag for stream reaches, <0: include unsaturated zone below (sagehen: >0) nsfrpar = 0; %Always Zero nparseg = 0; %Always Zero const = 86400.; %Conversion factor used in calculating depth for a stream reach (86400 in sagehen example) dleak = 0.0001; %Tolerance level of stream depth used in computing leakage between each stream (0.0001 in sagehen example) istcb1 = -1; %Flag for writing stream-aquifer leakage values (>0: file unit, <0: write to listing file) istcb2 = 0; %Flag for writing to a seperate formatted file information on inflows&outflows isfropt = 3; %defines input structure; saturated or non-saturated zone (1: No UZ; 3: UZ, unsat prop at start of simulation), sagehen uses 3 nstrail = 10; %Number of trailing-waive increments, incr for better mass balance (10-20 rec'd, sagehen uses 8) isuzn = 1; %Maximum number of vertical cells used to define the unsaturated zone beneath a stream reach (for icalc=1 (Mannings for depth): use isuzn=1) nsfrsets = 40; %Maximum number of different sets of trailing waves used to allocate arrays. irtflg = 0; %Flag whether transient streamflow routing is active project_name = 'TestProject'; % used to name the output file (.sfr) % data_indir = '/home/gcng/workspace/matlab_files/GSFLOW_pre-processor/MODFLOW_scripts/sfr_final/data/'; data_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % items reach_data_all = importdata(reach_fil); % used to write item 2: assumes NPER = 2; % used for item 3 % items 4a: # NSEG ICALC OUTSEG IUPSEG IPRIOR NSTRPTS FLOW RUNOFF ETSW PPTSW ROUGHCH ROUGHBK CDPTH FDPTH AWDTH BWDTH segment_data_4A = importdata(segment_fil_all{1}); % used to write items 4a segment_data_4B = importdata(segment_fil_all{2}); % used to write items 4b (ignored for ICALC=3 in 4a) segment_data_4C = importdata(segment_fil_all{3}); % used to write items 4c (ignored for ICALC=3 in 4a) % ------------------------------------------------------------------------- % In case the input text files (e.g. reach_data.txt) contain header lines (comments) if isstruct(reach_data_all) reach_data_all0 = reach_data_all.data; nstrm = size(reach_data_all0,1); if fl_nstrm < 0, nstrm = -nstrm; end % sort rows according to increasing segment numbers [~, ind] = sort(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')), 'ascend'); reach_data_all0 = reach_data_all0(ind,:); nss = max(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG'))); % sort rows according to increasing reach numbers for ii = 1: nss ind1 = find(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')) == ii); [~, ind2] = sort(reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')), 'ascend'); reach_data_all0(ind1,:) = reach_data_all0(ind1(ind2),:); % renumber IREACH to start at 1 for each segment reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')) = [1:length(ind1)]; end X = mat2cell(reach_data_all0, abs(nstrm), ones(size(reach_data_all0,2),1)); [KRCH,IRCH,JRCH,ISEG,IREACH,RCHLEN,STRTOP,SLOPE,STRTHICK,STRHC1,THTS,THTI,EPS,UHC] = X{:}; % -- make sure STRTOP is within 1st layer % - read in TOP and BOTM from .dis file dis_file = [GSFLOW_indir, '/', infile_pre, '.dis']; fid = fopen(dis_file); for ii = 1:2, cmt = fgets(fid); end line0 = fgets(fid); D = textscan(line0, '%d', 6); NLAY = D{1}(1); NROW = D{1}(2); NCOL = D{1}(3); NPER = D{1}(4); ITMUNI = D{1}(5); LENUNI = D{1}(6); line0 = fgets(fid); D = textscan(line0, '%d'); LAYCBD = D{1}; % 1xNLAY (0 if no confining layer) line0 = fgets(fid); D = textscan(line0, '%s %d'); DELR = D{2}; % width of column line0 = fgets(fid); D = textscan(line0, '%s %d'); DELC = D{2}; % height of row TOP = nan(NROW,NCOL); line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); TOP(irow,:) = D{1}(1:NCOL); end BOTM = nan(NROW, NCOL, NLAY); for ilay = 1: NLAY line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); BOTM(irow,:,ilay) = D{1}(1:NCOL); end end fclose(fid); % TOP for cells corresponding to reaches TOP_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), TOP_RCH(ii) = TOP(IRCH(ii),JRCH(ii)); end % BOTM for cells corresponding to reaches BOTM_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), BOTM_RCH(ii) = BOTM(IRCH(ii),JRCH(ii),KRCH(ii)); end % - set STRTOP to be just below TOP STRTOP = TOP_RCH - 2; if ~isempty(find(STRTOP-STRTHICK < BOTM_RCH,1)) fprintf('Error! STRTOP is below BOTM of the corresponding layer! Exiting...\n'); end reach_data_all0(:,strcmp(reach_data_all.colheaders, 'STRTOP')) = STRTOP; % -- plot stream reaches RCH_mask = TOP; for ii = 1:abs(nstrm), RCH_mask(IRCH(ii),JRCH(ii)) = max(TOP(:))*2; end figure subplot(2,2,1) imagesc(TOP), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); subplot(2,2,2) imagesc(RCH_mask), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); for ii = 1:abs(nstrm), RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); end for ii = 1:abs(nstrm), SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); end figure imagesc(RCH_NUM), colorbar, colormap(jet(1+max(IREACH))); caxis([-0.5 max(IREACH)+0.5]) figure imagesc(SEG_NUM), colorbar, colormap(jet(1+max(ISEG))); caxis([-0.5 max(ISEG)+0.5]) % % when running as script: to visualize segments one at a time % for j = 1: max(ISEG) % RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); % ind = find(ISEG==j); % for ii = ind(:)' % RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); % SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); % end % % figure(100) % imagesc(RCH_NUM), colorbar, % colormap(jet(1+max(RCH_NUM(:)))); % caxis([-0.5 max(RCH_NUM(:))+0.5]) % title(['reaches for seg ', num2str(j)]); % figure(101) % imagesc(SEG_NUM), colorbar, % colormap(jet(1+max(SEG_NUM(:)))); % caxis([-0.5 max(SEG_NUM(:))+0.5]) % title(['seg ', num2str(j)]); % pause % end % -- threshold slope at minimum 0.001 ind = reach_data_all0(:,strcmp(reach_data_all.colheaders, 'SLOPE')) < 0.001; reach_data_all0(ind,strcmp(reach_data_all.colheaders, 'SLOPE')) = 0.001; % -- set streambed thickness (Sagehen uses constant 1m) ind = strcmp(reach_data_all.colheaders, 'STRTHICK'); reach_data_all0(:,ind) = 1; % [m] % -- set streambed hydraulic conductivity (Sagehen example: 5 m/d) ind = strcmp(reach_data_all.colheaders, 'STRHC1'); reach_data_all0(:,ind) = 5; % set streambed theta_s ind = strcmp(reach_data_all.colheaders, 'THTS'); reach_data_all0(:,ind) = 0.35; % set streambed initial theta ind = strcmp(reach_data_all.colheaders, 'THTI'); reach_data_all0(:,ind) = 0.3; % set streambed Brooks-Corey exp (sagehen example is 3.5) ind = strcmp(reach_data_all.colheaders, 'EPS'); reach_data_all0(:,ind) = 3.5; % set streambed unsaturated zone saturated hydraulic conductivity % (sagehen example is 0.3 m/d) ind = strcmp(reach_data_all.colheaders, 'UHC'); reach_data_all0(:,ind) = 0.3; reach_data_all = reach_data_all0; end if isstruct(segment_data_4A) segment_data_4A = segment_data_4A.data; nss = size(segment_data_4A,1); %Number of stream segments end if isstruct(segment_data_4B) segment_data_4B = segment_data_4B.data; end if isstruct(segment_data_4C) segment_data_4C = segment_data_4C.data; end % if isstruct(stress_periods) % stress_periods = stress_periods.data; % end % - specify only for 2 stress periods: stress_periods = zeros(NPER, 3); % itmp, irdflg, iptflg (latter 2 are set to 0) stress_periods(1,1) = nss; if NPER > 1, stress_periods(2:end,1) = -1; end % ------------------------------------------------------------------------- % First put 4A, 4B and 4C data all together in a cell array % size(cell) = nitems x 1 x nperiods % In this case, nitems is 3 (i.e. 4A, 4B and 4C) nitems = 3; nperiods = size(stress_periods, 1); segment_data_all = cell(nitems, 1, nperiods); segment_data_all{1, 1, 1} = segment_data_4A; segment_data_all{2, 1, 1} = segment_data_4B; segment_data_all{3, 1, 1} = segment_data_4C; % ------------------------------------------------------------------------- % validate some of the input data msg_invalidISFROPT = ['Error: ISFROPT should be set to an integer of', ... '1, 2, 3, 4 or 5.']; if (nstrm < 0) if ~ismember(isfropt, [1, 2, 3, 4, 5]) error(msg_invalidISFROPT); end end msg_notSupport = ['Error: %s: this variable must be zero because ', ... 'parameters are not supported in GSFLOW.']; if (nsfrpar ~= 0) error(msg_notSupport, 'NSFRPAR'); end if (nparseg ~= 0) error(msg_notSupport, 'NPARSEG'); end % ------------------------------------------------------------------------- % Ouput file fid = fopen([GSFLOW_indir, '/', sfr_file], 'wt'); % Write header lines (item 0) heading = '# Streamflow-Routing (SFR7) input file.\n'; fprintf(fid, heading); fprintf(fid, '# %s simulation -- created on %s.\n', upper(project_name), date); % Item 1 fprintf(fid, ' %5d %5d %5d %5d %8.2f %8.4f %5d %5d', ... nstrm, nss, nsfrpar, nparseg, const, dleak, istcb1, istcb2); if (isfropt >= 1) fprintf(fid, ' %5d', isfropt); if (isfropt == 1) fprintf(fid, ' %5d\n', irtflg); elseif (isfropt > 1) fprintf(fid, ' %5d %5d %5d %5d\n', nstrail, isuzn, nsfrsets, irtflg); end else fprintf(fid, '\n'); end % Item 2 if (isfropt == 1) ncols_reach = 10; elseif (isfropt == 2) ncols_reach = 13; elseif (isfropt == 3) ncols_reach = 14; else ncols_reach = 6; end reach_data_copy = reach_data_all(:, 1:ncols_reach); p = ncols_reach - 5; fmt_reach = [repmat(' %5d', 1, 5), repmat(' %8.3f', 1, p), '\n']; for istrm=1:abs(nstrm) dummy = reach_data_copy(istrm, :); fprintf(fid, fmt_reach, dummy); end % Item 3 and 4 nper = size(stress_periods, 1); for iper=1:nper % write item 3 to the file dummy3 = num2cell(stress_periods(iper, :)); [itmp, irdflg, iptflg] = dummy3{:}; fprintf(fid, ' %5d %5d %5d\n', itmp, irdflg, iptflg); if (itmp > 0) seg_inf_4a = segment_data_all{1, 1, iper}; seg_inf_4b = segment_data_all{2, 1, iper}; seg_inf_4c = segment_data_all{3, 1, iper}; for iitmp=1:itmp % start loop over itmp (num_segments) % write item 4a to the file dummy4a = num2cell(seg_inf_4a(iitmp, :)); [nseg, icalc, outseg, iupseg, iprior, nstrpts, ... flow, runoff, etsw, pptsw, roughch, roughbk, ... cdpth, fdpth, awdth, bwdth] = dummy4a{:}; fmt = [' ', repmat(' %5d', 1, 4)]; fprintf(fid, fmt, nseg, icalc, outseg, iupseg); if (iupseg > 0) fprintf(fid, ' %5d', iprior); end if (icalc == 4) fprintf(fid, ' %5d', nstrpts); end fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, flow, runoff, etsw, pptsw); if ((icalc == 1) || (icalc == 2)) fprintf(fid, ' %8.3f', roughch); end if (icalc == 2) fprintf(fid, ' %8.3f', roughbk); end if (icalc == 3) fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, cdpth, fdpth, awdth, bwdth); end fprintf(fid, '\n'); % write items 4b and 4c to the file suffixes = 'bc'; for i=1:2 % start loop over i suffix = suffixes(i); var_str = ['seg_inf_4', suffix]; var = eval(var_str); dummy4bc = num2cell(var(iitmp, :)); [hcond, thickm, elevupdn, width, ... depth, thts, thti, eps, uhc] = dummy4bc{:}; fl_no_4bc = 0; if (ismember(isfropt, [0, 4, 5]) && (icalc <= 0)) fmt = [' ', repmat(' %8.3f', 1, 5)]; fprintf(fid, fmt, hcond, thickm, elevupdn, width, depth); elseif (ismember(isfropt, [0, 4, 5]) && (icalc == 1)) fprintf(fid, ' %8.3f', hcond); if (iper == 1) % only for the first period fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); if ((isfropt == 4) || (isfropt == 5)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); end if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end elseif ((iper > 1) && (isfropt == 0)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); end elseif (ismember(isfropt, [0, 4, 5]) && (icalc >= 2)) fprintf(fid, ' %8.3f', hcond); if ~(ismember(isfropt, [4, 5]) && (iper > 1) && (icalc == 2)) fprintf(fid, ' %8.3f %8.3f', thickm, elevupdn); if (ismember(isfropt, [4, 5]) && (iper == 1) && (icalc == 2)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end end end elseif ((isfropt == 1) && (icalc <= 1)) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end elseif (ismember(isfropt, [2, 3]) && (icalc <= 1)) if (iper == 1) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end end else fl_no_4bc = 1; end if ~fl_no_4bc fprintf(fid, '\n'); end end % terminate loop over i (4b and 4c, respectively) end % terminate loop over itmp (num_segments) end % enf if (itmp > 0) end % terminate loop over iper (num_periods) fclose(fid); % ------------------------------------------------------------------------- % End of the script
github
UMN-Hydro/GSFLOW_pre-processor-master
write_ba6_MOD2_ok.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_ba6_MOD2_ok.m
5,863
utf_8
1f12d52d0b1416b1514618c0791f04d0
% write_ba6_MOD % 11/17/16 function write_ba6_MOD2(GSFLOW_indir, infile_pre, surfz_fil, mask_fil, NLAY, DZ) % % ==== TO RUN AS SCRIPT =================================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % ========================================================================= %% % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; ba6_file = [infile_pre, '.ba6']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 1; % NROW = 50; % NCOL = 50; % -- IBOUND(NROW,NCOL,NLAY): <0 const head, 0 no flow, >0 variable head % use basin mask (set IBOUND>0 within watershed, =0 outside watershed, <0 at discharge point and 2 neighboring pixels) % mask_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/basinmask_dischargept.asc'; fid = fopen(mask_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); D = textscan(fid, '%f'); IBOUND = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL D = textscan(fid, '%s %s %f %s %f'); dischargePt_rowi = D{3}; dischargePt_coli = D{5}; fclose(fid); % - force some cells to be active to correspond to stream reaches IBOUND(14,33) = 1; IBOUND(11,35) = 1; IBOUND(12,34) = 1; IBOUND(7,43) = 1; % find boundary cells IBOUNDin = IBOUND(2:end-1,2:end-1); IBOUNDu = IBOUND(1:end-2,2:end-1); % up IBOUNDd = IBOUND(3:end,2:end-1); % down IBOUNDl = IBOUND(2:end-1,1:end-2); % left IBOUNDr = IBOUND(2:end-1,3:end); % right ind_bound = IBOUNDin==1 & (IBOUNDin-IBOUNDu==1 | IBOUNDin-IBOUNDd==1 | ... IBOUNDin-IBOUNDl==1 | IBOUNDin-IBOUNDr==1); % IBOUNDin(ind) = -1; % IBOUND(2:end-1,2:end-1) = IBOUNDin; % -- init head: base on TOP and BOTM % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); if ~isempty(find(NSEW ~= D{2}(1:4),1)) || NROW ~= D{2}(5) || NCOL ~= D{2}(6); fprintf('Error!! NSEW, NROW, or NCOL in data files do not match!\n'); fprintf(' (files: %d and %d\n', mask_fil, surfz_fil); fprintf('exiting...\n'); return end % - space discretization DELR = (NSEW(3)-NSEW(4))/NCOL; % width of column [m] DELC = (NSEW(1)-NSEW(2))/NROW; % height of row [m] % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % DZ = [5; 5]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % - set TOP to surface elevation [m] D = textscan(fid, '%f'); fclose(fid); TOP = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL BOTM = zeros(NROW, NCOL, NLAY); BOTM(:,:,1) = TOP-DZ(1); for ilay = 2:NLAY BOTM(:,:,ilay) = BOTM(:,:,ilay-1)-DZ(ilay); end % - make boundary cells constant head above a certain elevation % IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 4500) = -1; IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 3500) = -1; IBOUND(2:end-1,2:end-1,1) = IBOUNDin; % - make discharge point and neighboring cells constant head IBOUND(dischargePt_rowi,dischargePt_coli,1) = -2; % downgrad of discharge pt % IBOUND(dischargePt_rowi-1,dischargePt_coli,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli+1,1) = -2; % downgrad of discharge pt IBOUND(dischargePt_rowi-1,dischargePt_coli+1,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli+1,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli,1) = 1; % downgrad of discharge pt IBOUND = repmat(IBOUND, [1 1 NLAY]); % - initHead(NROW,NCOL,NLAY) initHead = BOTM(:,:,1) + (TOP-BOTM(:,:,1))*0.9; % within top layer initHead = repmat(initHead, [1, 1, NLAY]); % - assumed values HNOFLO = -999.99; %% ------------------------------------------------------------------------ % -- Write ba6 file fil_ba6_0 = [GSFLOW_indir, slashstr, ba6_file]; fmt1 = [repmat('%4d ', 1, NCOL), '\n']; % for IBOUND fmt2 = [repmat('%7g ', 1, NCOL), '\n']; % for initHead fid = fopen(fil_ba6_0, 'wt'); fprintf(fid, '# basic package file --- %d layers, %d rows, %d columns\n', NLAY, NROW, NCOL); fprintf(fid, 'FREE\n'); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 IBOUND for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt1, IBOUND(:,:,ilay)'); end fprintf(fid, ' %f HNOFLO\n', HNOFLO); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 init head for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt2, initHead(:,:,ilay)'); end fclose(fid); % -- Plot basics for ii = 1:2 if ii == 1, X0 = IBOUND; ti0 = 'IBOUND'; elseif ii == 2 X0 = initHead; ti0 = 'init head'; end figure for ilay = 1:NLAY subplot(2,2,double(ilay)) X = X0(:,:,ilay); m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; % cm(1,:) = [1 1 1]; colormap(cm); colorbar title([ti0, ' lay', num2str(ilay)]); end end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_OC_PCG_MOD_f_ok.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_OC_PCG_MOD_f_ok.m
2,464
utf_8
1d9ed9195d98acdaca000e193ada7d77
% write_OC_PCG_MOD.m % 11/20/16 function write_OC_PCG_MOD_f(GSFLOW_indir, infile_pre) % clear all, close all, fclose all; % - write to this file % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; fil_pcg = [infile_pre, '.pcg']; fil_oc = [infile_pre, '.oc']; slashstr = '/'; % -- shoud match .dis NPER = 2; % 1 SS then 1 transient PERLEN = [1; 365]; % 2 periods: 1-day steady-state and multi-day transient NSTP = PERLEN; % -- pcg and oc files are not changed with this script % fil_pcg_0 = fullfile(MODtest_dir0, fil_pcg); fil_pcg_0 = [GSFLOW_indir, slashstr, fil_pcg]; fid = fopen(fil_pcg_0, 'wt'); % fprintf(fid, '# Preconditioned conjugate-gradient package\n'); % fprintf(fid, ' 50 30 1 MXITER, ITER1, NPCOND\n'); % fprintf(fid, ' 0000.001 .001 1. 2 1 1 1.00\n'); % fprintf(fid, ' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n'); % % sagehen example: % fprintf(fid, '# Preconditioned conjugate-gradient package\n'); % fprintf(fid, ' 1000 450 1 MXITER, ITER1, NPCOND\n'); % fprintf(fid, ' 0.001 0.08 1.0 2 1 0 -0.05 0.70\n'); % fprintf(fid, ' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n'); % sagehen example: fprintf(fid, '# Preconditioned conjugate-gradient package\n'); fprintf(fid, ' 5000 450 1 MXITER, ITER1, NPCOND\n'); fprintf(fid, ' 0.001 0.08 1.0 2 1 0 -0.05 0.70\n'); fprintf(fid, ' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n'); fclose(fid); % fil_oc_0 = (MODtest_dir0, fil_oc); % "PRINT": to listing file % "SAVE": to file with unit number in name file fil_oc_0 = [GSFLOW_indir, slashstr, fil_oc]; fid = fopen(fil_oc_0, 'wt'); fprintf(fid, 'HEAD PRINT FORMAT 20\n'); fprintf(fid, 'HEAD SAVE UNIT 51\n'); fprintf(fid, 'COMPACT BUDGET AUX\n'); fprintf(fid, 'IBOUND SAVE UNIT 52\n'); for per_i = 1:NPER for stp_i = 1:30:NSTP(per_i) fprintf(fid, 'PERIOD %d STEP %d\n', per_i, stp_i); if stp_i == NSTP(per_i) % only at end of stress period fprintf(fid, ' PRINT HEAD\n'); fprintf(fid, ' SAVE IBOUND\n'); fprintf(fid, ' PRINT BUDGET\n'); end fprintf(fid, ' SAVE HEAD\n'); fprintf(fid, ' SAVE BUDGET\n'); end end fclose(fid);
github
UMN-Hydro/GSFLOW_pre-processor-master
write_nam_MOD_f2.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_nam_MOD_f2.m
2,336
utf_8
b3ca150a14dec00616051b95a14ea82c
% write_nam_MOD % 11/20/16 function write_nam_MOD_f2(GSFLOW_indir, GSFLOW_outdir, infile_pre, fil_res_in) % v2 - allows for restart option (init) % clear all, close all, fclose all; % % - directories % % MODFLOW input filesfil_res_in % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % - write to this file (within indir) fil_nam = [infile_pre, '.nam']; slashstr = '/'; % all assumed to be in GSFLOW_dir fil_ba6 = [infile_pre, '.ba6']; fil_lpf = [infile_pre, '.lpf']; fil_pcg = [infile_pre, '.pcg']; fil_oc = [infile_pre, '.oc']; fil_dis = [infile_pre, '.dis']; fil_uzf = [infile_pre, '.uzf']; fil_sfr = [infile_pre, '.sfr']; fil_res_out = [infile_pre, '.out']; % write to restart file %% ------------------------------------------------------------------------ % -- .nam file with full paths % fil_nam_0 = fullfile(MODtest_dir0, fil_nam); fil_nam_0 = [GSFLOW_indir, slashstr, fil_nam]; fid = fopen(fil_nam_0, 'wt'); fprintf(fid, 'LIST 7 %s \n', [GSFLOW_outdir, slashstr, 'test.lst']); % MODFLOW output file fprintf(fid, 'BAS6 8 %s \n', [GSFLOW_indir, slashstr, fil_ba6]); fprintf(fid, 'LPF 11 %s \n', [GSFLOW_indir, slashstr, fil_lpf]); fprintf(fid, 'PCG 19 %s \n', [GSFLOW_indir, slashstr, fil_pcg]); fprintf(fid, 'OC 22 %s \n', [GSFLOW_indir, slashstr, fil_oc]); fprintf(fid, 'DIS 10 %s \n', [GSFLOW_indir, slashstr, fil_dis]); fprintf(fid, 'UZF 12 %s \n', [GSFLOW_indir, slashstr, fil_uzf]); fprintf(fid, 'SFR 13 %s \n', [GSFLOW_indir, slashstr, fil_sfr]); if ~isempty(fil_res_in) fprintf(fid, 'IRED 90 %s \n', fil_res_in); end fprintf(fid, 'IWRT 91 %s \n', [GSFLOW_outdir, slashstr, fil_res_out]); fprintf(fid, 'DATA(BINARY) 34 %s \n', fullfile(GSFLOW_outdir, 'test.bud')); % MODFLOW LPF output file, make sure 34 is unit listed in lpf file!! fprintf(fid, 'DATA(BINARY) 51 %s \n', [GSFLOW_outdir, slashstr, 'testhead.dat']); % MODFLOW output file fprintf(fid, 'DATA(BINARY) 61 %s \n', [GSFLOW_outdir, slashstr, 'uzf.dat']); % MODFLOW output file fprintf(fid, 'DATA 52 %s \n', [GSFLOW_outdir, slashstr, 'ibound.dat']); % MODFLOW output file fclose(fid);
github
UMN-Hydro/GSFLOW_pre-processor-master
write_ba6_MOD3_2.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_ba6_MOD3_2.m
6,046
utf_8
c967103aeca207643dcd775bdb4760b4
% write_ba6_MOD % 11/17/16 function write_ba6_MOD3(GSFLOW_indir, infile_pre, mask_fil) % % ==== TO RUN AS SCRIPT =================================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % ========================================================================= %% % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; ba6_file = [infile_pre, '.ba6']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 1; % NROW = 50; % NCOL = 50; % -- IBOUND(NROW,NCOL,NLAY): <0 const head, 0 no flow, >0 variable head % use basin mask (set IBOUND>0 within watershed, =0 outside watershed, <0 at discharge point and 2 neighboring pixels) % mask_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/basinmask_dischargept.asc'; fid = fopen(mask_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); D = textscan(fid, '%f'); IBOUND = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL D = textscan(fid, '%s %s %f %s %f'); dischargePt_rowi = D{3}; dischargePt_coli = D{5}; fclose(fid); % - force some cells to be active to correspond to stream reaches IBOUND(14,33) = 1; IBOUND(11,35) = 1; IBOUND(12,34) = 1; IBOUND(7,43) = 1; % find boundary cells IBOUNDin = IBOUND(2:end-1,2:end-1); IBOUNDu = IBOUND(1:end-2,2:end-1); % up IBOUNDd = IBOUND(3:end,2:end-1); % down IBOUNDl = IBOUND(2:end-1,1:end-2); % left IBOUNDr = IBOUND(2:end-1,3:end); % right % - inner boundary is constant head ind_bound = IBOUNDin==1 & (IBOUNDin-IBOUNDu==1 | IBOUNDin-IBOUNDd==1 | ... IBOUNDin-IBOUNDl==1 | IBOUNDin-IBOUNDr==1); % - outer boundary is constant head % ind_bound = IBOUNDin==0 & (IBOUNDin-IBOUNDu==-1 | IBOUNDin-IBOUNDd==-1 | ... % IBOUNDin-IBOUNDl==-1 | IBOUNDin-IBOUNDr==-1); % -- init head: base on TOP and BOTM dis_file = [GSFLOW_indir, '/', infile_pre, '.dis']; fid = fopen(dis_file); for ii = 1:2, cmt = fgets(fid); end line0 = fgets(fid); D = textscan(line0, '%d', 6); NLAY = D{1}(1); NROW = D{1}(2); NCOL = D{1}(3); NPER = D{1}(4); ITMUNI = D{1}(5); LENUNI = D{1}(6); line0 = fgets(fid); D = textscan(line0, '%d'); LAYCBD = D{1}; % 1xNLAY (0 if no confining layer) line0 = fgets(fid); D = textscan(line0, '%s %d'); DELR = D{2}; % width of column line0 = fgets(fid); D = textscan(line0, '%s %d'); DELC = D{2}; % height of row TOP = nan(NROW,NCOL); line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); TOP(irow,:) = D{1}(1:NCOL); end BOTM = nan(NROW, NCOL, NLAY); for ilay = 1: NLAY line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); BOTM(irow,:,ilay) = D{1}(1:NCOL); end end fclose(fid); % - make boundary cells constant head above a certain elevation % IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 4500) = -1; IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 3500) = -1; IBOUND(2:end-1,2:end-1,1) = IBOUNDin; % - make discharge point and neighboring cells constant head IBOUND(dischargePt_rowi,dischargePt_coli,1) = -2; % downgrad of discharge pt % IBOUND(dischargePt_rowi-1,dischargePt_coli,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli+1,1) = -2; % downgrad of discharge pt IBOUND(dischargePt_rowi-1,dischargePt_coli+1,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli+1,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli,1) = 1; % downgrad of discharge pt IBOUND = repmat(IBOUND, [1 1 NLAY]); % - initHead(NROW,NCOL,NLAY) initHead = BOTM(:,:,1) + (TOP-BOTM(:,:,1))*0.9; % within top layer % % (no more than 10m below top): % Y = nan(NROW,NCOL,2); Y(:,:,1) = initHead; Y(:,:,2) = TOP-10; % initHead = max(Y,[],3); initHead = repmat(initHead, [1, 1, NLAY]); % - assumed values HNOFLO = -999.99; %% ------------------------------------------------------------------------ % -- Write ba6 file fil_ba6_0 = [GSFLOW_indir, slashstr, ba6_file]; fmt1 = [repmat('%4d ', 1, NCOL), '\n']; % for IBOUND fmt2 = [repmat('%7g ', 1, NCOL), '\n']; % for initHead fid = fopen(fil_ba6_0, 'wt'); fprintf(fid, '# basic package file --- %d layers, %d rows, %d columns\n', NLAY, NROW, NCOL); fprintf(fid, 'FREE\n'); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 IBOUND for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt1, IBOUND(:,:,ilay)'); end fprintf(fid, ' %f HNOFLO\n', HNOFLO); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 init head for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt2, initHead(:,:,ilay)'); end fclose(fid); % -- Plot basics for ii = 1:2 if ii == 1, X0 = IBOUND; ti0 = 'IBOUND'; elseif ii == 2 X0 = initHead; ti0 = 'init head'; end figure for ilay = 1:NLAY subplot(2,2,double(ilay)) X = X0(:,:,ilay); m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; % cm(1,:) = [1 1 1]; colormap(cm); colorbar title([ti0, ' lay', num2str(ilay)]); end end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_dis_MOD2_f.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_dis_MOD2_f.m
5,326
utf_8
2a486d8aebe770037a17329382652f18
% write_dis_MOD (for 3D domains) % 11/17/16 % % v1 - 11/30/16 start to include GIS data for Chimborazo's Gavilan Machay % watershed; topo.asc for surface elevation (fill in bottom elevation % based on uniform thickness of single aquifer) function write_dis_MOD2_f(GSFLOW_indir, infile_pre, surfz_fil, NLAY, DZ, perlen_tr) % % ==== TO RUN AS SCRIPT =================================================== % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % perlen_tr = 365; % ok if too long % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % % surfz_fil = [GIS_indir, 'topo.asc']; % surfz_fil = [GIS_indir, 'SRTM_new_20161208.asc']; % % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % ========================================================================= %% % clear all, close all, fclose all; % - write to this file % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; dis_file = [infile_pre, '.dis']; % - read in this file for surface elevation (for TOP(NROW,NCOL)) % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; % - read in this file for elevation of layer bottoms (for BOTM(NROW,NCOL,NLAY)) % (layer 1 is top layer) botmz_fil = ''; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 1; % NROW = 1058; % NCOL = 1996; % % - domain boundary (UTM zone 17S, outer boundaries) % north = 9841200; % south = 9835900; % east = 751500; % west = 741500; % % - space discretization % DELR = (east-west)/NCOL; % width of column [m] % DELC = (north-south)/NROW; % height of row [m] % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % DZ = [5; 5]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % - time discretization PERLEN = [1; perlen_tr]; % 2 periods: 1-day steady-state and multi-day transient comment1 = '# test file for Gavilan Machay'; comment2 = '# test file'; % - The following will be assumed: LAYCBD = zeros(NLAY,1); % no confining layer below layer ITMUNI = 4; % [d] LENUNI = 2; % [m] NPER = 2; % 1 SS then 1 transient NSTP = PERLEN; TSMULT = 1; % must have daily time step to correspond with PRMS SsTr_flag = ['ss'; 'tr']; %% ------------------------------------------------------------------------ % -- Read in data from files fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); % - space discretization DELR = (NSEW(3)-NSEW(4))/NCOL; % width of column [m] DELC = (NSEW(1)-NSEW(2))/NROW; % height of row [m] % - set TOP to surface elevation [m] D = textscan(fid, '%f'); fclose(fid); fprintf('Done reading...\n'); TOP = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL BOTM = zeros(NROW, NCOL, NLAY); BOTM(:,:,1) = TOP-DZ(1); for ilay = 2:NLAY BOTM(:,:,ilay) = BOTM(:,:,ilay-1)-DZ(ilay); end % -- Discretization file: fmt1 = [repmat('%4d ', 1, NCOL), '\n']; % fmt2 = [repmat('%10g ', 1, NCOL), '\n']; % fid = fopen([GSFLOW_indir, '/', dis_file], 'wt'); fmt3 = [repmat(' %d', 1, NLAY), '\n']; % for LAYCBD fprintf(fid, '%s\n', comment1); fprintf(fid, '%s\n', comment2); fprintf(fid, ' %d %d %d %d %d %d ', NLAY, NROW, NCOL, NPER, ITMUNI, LENUNI); fprintf(fid, ' NLAY,NROW,NCOL,NPER,ITMUNI,LENUNI\n'); fprintf(fid, fmt3, LAYCBD); fprintf(fid, 'CONSTANT %14g DELR\n', DELR); fprintf(fid, 'CONSTANT %14g DELC\n', DELC); fprintf(fid, 'INTERNAL 1.0 (FREE) 0 TOP ELEVATION OF LAYER 1 \n'); fprintf(fid, fmt2, TOP'); for ii = 1: NLAY fprintf(fid, 'INTERNAL 1.0 (FREE) 0 BOTM ELEVATION OF LAYER %d \n', ii); fprintf(fid, fmt2, BOTM(:,:,ii)'); end for ii = 1: NPER fprintf(fid, ' %g %d %g %c%c PERLEN, NSTP, TSMULT, Ss/Tr (stress period %4d)\n', ... PERLEN(ii), NSTP(ii), TSMULT, SsTr_flag(ii,:), ii); end fclose(fid); % -- plot domain discretization figure subplot(2,2,1) imagesc(TOP), m = TOP(TOP>0); m = min(m(:)); caxis([m*0.9, max(TOP(:))]), cm = colormap; cm(1,:) = [1 1 1]; colormap(cm); colorbar title('TOP') for ilay = 1:NLAY subplot(2,2,1+double(ilay)) m = BOTM(BOTM>0); m = min(m(:)); imagesc(BOTM(:,:,ilay)), caxis([m*0.9, max(BOTM(:))]), cm = colormap; cm(1,:) = [1 1 1]; colormap(cm); colorbar title(['BOTM', ' lay', num2str(ilay)]); end figure for ilay = 1:NLAY subplot(2,2,double(ilay)) if ilay == 1 X = TOP - BOTM(:,:,ilay); else X = BOTM(:,:,ilay-1)-BOTM(:,:,ilay); end % m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; cm(1,:) = [1 1 1]; colormap(cm); colorbar title(['DZ', ' lay', num2str(ilay)]); end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_lpf_MOD2_f2_ok.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_lpf_MOD2_f2_ok.m
5,446
utf_8
78b4bbbf2eb4c445215734e7c60a624a
% write_lpf_MOD % 11/17/16 function write_lpf_MOD2_f2(GSFLOW_indir, infile_pre, surfz_fil, NLAY) % % =========== TO RUN AS SCRIPT =========================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % % for sfr % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; % % ==================================================================== % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % lpf_file = 'test.lpf'; lpf_file = [infile_pre, '.lpf']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 2; % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); fclose(fid); % -- Base hydcond, Ss (all layers), and Sy (top layer only) on data from files % (temp place-holder) hydcond = ones(NROW,NCOL,NLAY)*2; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.5; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,1) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,2) = 0.01; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) Ss = ones(NROW,NCOL,NLAY)* 2e-6; % constant 2e-6 /m for Sagehen Sy = ones(NROW,NCOL,NLAY)*0.15; % 0.08-0.15 in Sagehen (lower Sy under ridges for volcanic rocks) WETDRY = Sy; % = Sy in Sagehen (lower Sy under ridges for volcanic rocks) % -- assumed input values flow_filunit = 34; % make sure this matches namefile!! hdry = 1e30; % head assigned to dry cells nplpf = 0; % number of LPF parameters (if >0, key words would follow) laytyp = zeros(NLAY,1); laytyp(1) = 1; % flag, top>0: "covertible", rest=0: "confined" layave = zeros(NLAY,1); % flag, layave=1: harmonic mean for interblock transmissivity chani = ones(NLAY,1); % flag, chani=1: constant horiz anisotropy mult factor (for each layer) layvka = zeros(NLAY,1); % flag, layvka=0: vka is vert K; >0 is vertK/horK ratio VKA = hydcond; laywet = zeros(NLAY,1); laywet(1)=1; % flag, 1: wetting on for top convertible cells, 0: off for confined fl_Tr = 1; % flag, 1 for at least 1 transient stress period (for Ss and Sy) WETFCT = 1.001; % 1.001 for Sagehen, wetting (convert dry cells to wet) IWETIT = 4; % number itermations for wetting IHDWET = 0; % wetting scheme, 0: equation 5-32A is used: h = BOT + WETFCT (hn - BOT) %% ------------------------------------------------------------------------ fmt1 = repmat('%2d ', 1, NLAY); fil_lpf_0 = [GSFLOW_indir, slashstr, lpf_file]; fid = fopen(fil_lpf_0, 'wt'); fprintf(fid, '# LPF package inputs\n'); fprintf(fid, '%d %g %d ILPFCB,HDRY,NPLPF\n', flow_filunit, hdry, nplpf); fprintf(fid, [fmt1, ' LAYTYP\n'], laytyp); fprintf(fid, [fmt1, ' LAYAVE\n'], layave); fprintf(fid, [fmt1, ' CHANI \n'], chani); fprintf(fid, [fmt1, ' LAYVKA\n'], layvka); fprintf(fid, [fmt1, ' LAYWET\n'], laywet); if ~isempty(find(laywet,1)) fprintf(fid, '%g %d %d WETFCT, IWETIT, IHDWET\n', WETFCT, IWETIT, IHDWET); end % -- Write HKSAT and Ss, Sy (if Tr) in .lpf file format0 = [repmat(' %4.2f ', 1, NCOL), '\n']; format1 = [repmat(' %4.2e ', 1, NCOL), '\n']; % loop thru layers (different entry for each layer) for lay = 1: NLAY fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 HY layer %d\n', lay); % horizontal hyd cond fprintf(fid, format1, hydcond(:,:,lay)'); fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 VKA layer %d\n', lay); % vertical hyd cond fprintf(fid, format1, VKA(:,:,lay)'); if fl_Tr fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Ss layer %d\n', lay); fprintf(fid, format1, Ss(:,:,lay)'); if laytyp(lay) > 0 % convertible, i.e. unconfined fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Sy layer %d\n', lay); fprintf(fid, format1, Sy(:,:,lay)'); if laywet(lay) > 0 fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 WETDRY layer %d\n', lay); fprintf(fid, format0, WETDRY(:,:,lay)'); end end end end fprintf(fid, '\n'); fclose(fid);
github
victorlei/libermate-master
fox_rabbit.m
.m
libermate-master/Tests/fox_rabbit.m
1,178
utf_8
602c5dee8301607688c2500a9c52510e
function fox_rabbit %FOX_RABBIT Fox-rabbit pursuit simulation. % Uses relative speed parameter, K. k = 1.1; tspan = [0 10]; yzero = [3;0]; options = odeset('RelTol',1e-6,'AbsTol',1e-6,'Events',@events); [tfox,yfox,te,ye,ie] = ode45(@fox2,tspan,yzero,options); plot(yfox(:,1),yfox(:,2)), hold on plot(sqrt(1+tfox).*cos(tfox),sqrt(1+tfox).*sin(tfox),'--') plot([3 1],[0 0],'o'), plot(yfox(end,1),yfox(end,2),'*') axis equal, axis([-3.5 3.5 -2.5 3.1]) legend('Fox','Rabbit'), hold off function yprime = fox2(t,y) %FOX2 Fox-rabbit pursuit simulation ODE. r = sqrt(1+t)*[cos(t); sin(t)]; r_p = (0.5/sqrt(1+t)) * [cos(t)-2*(1+t)*sin(t); sin(t)+2*(1+t)*cos(t)]; dist = max(norm(r-y),1e-6); factor = k*norm(r_p)/dist; yprime = factor*(r-y); end end function [value,isterminal,direction] = events(t,y) %EVENTS Events function for FOX2. % Locate when fox is close to rabbit. r = sqrt(1+t)*[cos(t); sin(t)]; value = norm(r-y) - 1e-4; % Fox close to rabbit. isterminal = 1; % Stop integration. direction = -1; % Value must be decreasing through zero. end
github
victorlei/libermate-master
functiontest2.m
.m
libermate-master/Tests/functiontest2.m
50
utf_8
e53e67b09926ff991d5a1ee2224940c2
% Comment function ret=myfunction(a,b,c) ret=a
github
victorlei/libermate-master
lcrun.m
.m
libermate-master/Tests/lcrun.m
1,252
utf_8
5a6e1f2365db43e3c78240595f9dcd04
function lcrun %LCRUN Liquid crystal BVP. % Solves the liquid crystal BVP for four different lambda values. lambda_vals = [2.4, 2.5, 3, 10]; lambda_vals = lambda_vals(end:-1:1); % Necessary order for continuation. solinit = bvpinit(linspace(-1,1,20),@lcinit); lambda = lambda_vals(1); sola = bvp4c(@lc,@lcbc,solinit); lambda = lambda_vals(2); solb = bvp4c(@lc,@lcbc,sola); lambda = lambda_vals(3); solc = bvp4c(@lc,@lcbc,solb); lambda = lambda_vals(4); sold = bvp4c(@lc,@lcbc,solc); plot(sola.x,sola.y(1,:),'-', 'LineWidth',4), hold on plot(solb.x,solb.y(1,:),'--','LineWidth',2) plot(solc.x,solc.y(1,:),'--','LineWidth',4) plot(sold.x,sold.y(1,:),'--','LineWidth',6), hold off legend([repmat('\lambda = ',4,1) num2str(lambda_vals')]) xlabel('x','FontSize',16) ylabel('\theta','Rotation',0,'FontSize',16) ylim([-0.1 1.5]) function yprime = lc(x,y) %LC ODE/BVP liquid crystal system. yprime = [y(2); -lambda*sin(y(1))*cos(y(1))]; end end function res = lcbc(ya,yb) %LCBC ODE/BVP liquid crystal boundary conditions. res = [ya(1); yb(1)]; end function yinit = lcinit(x) %LCINIT ODE/BVP liquid crystal initial guess. yinit = [sin(0.5*(x+1)*pi); 0.5*pi*cos(0.5*(x+1)*pi)]; end
github
victorlei/libermate-master
neural.m
.m
libermate-master/Tests/neural.m
1,142
utf_8
230a2509d261ffe4bdba2ce6d3856ba1
function neural %NEURAL Neural network model with delays. tspan = [0 40]; sol = dde23(@f,[0.2,0.5],@history,tspan); subplot(2,2,1) plot(sol.x,sol.y(1,:),'r-', sol.x,sol.y(2,:),'g--', 'LineWidth',2) legend('y_1','y_2') title('\tau_1 = 0.2, \tau_2 = 0.5','FontSize',12) xlabel t, ylabel('y','Rotation',0), ylim([-0.2,0.2]) subplot(2,2,3) plot(sol.y(1,:),sol.y(2,:),'r-') xlabel y_1, ylabel('y_2','Rotation',0) xlim([-0.2,0.2]), ylim([-0.1,0.1]) sol = dde23(@f,[0.325,0.525],@history,tspan); subplot(2,2,2) plot(sol.x,sol.y(1,:),'r-', sol.x,sol.y(2,:),'g--', 'LineWidth',2) legend('y_1','y_2') title('\tau_1 = 0.325, \tau_2 = 0.525','FontSize',12) xlabel t, ylabel('y','Rotation',0), ylim([-0.2,0.2]) subplot(2,2,4) plot(sol.y(1,:),sol.y(2,:),'r-') xlabel y_1, ylabel('y_2','Rotation',0) xlim([-0.2,0.2]), ylim([-0.1,0.1]) function v = f(t,y,Z) %F Neural network differential equation. ylag1 = Z(:,1); ylag2 = Z(:,2); v = [-y(1) + 2*tanh(ylag2(2)) -y(2) - 1.5*tanh(ylag1(1))]; function v = history(t) %HISTORY Initial function for neural network model v = 0.1*[sin(t/10);cos(t/10)];
github
victorlei/libermate-master
poly1err.m
.m
libermate-master/Tests/poly1err.m
530
utf_8
af1e12065da2b7d0735699f20a6e0022
function max_err = poly1err(n) %POLY1ERR Error in linear interpolating polynomial. % POLY1ERR(N) is an approximation based on N sample points % to the maximum difference between subfunction F and its % linear interpolating polynomial at 0 and 1. max_err = 0; f0 = f(0); f1 = f(1); for x = linspace(0,1,n) p = x*f1 + (x-1)*f0; err = abs(f(x)-p); max_err = max(max_err,err); end % Subfunction. function y = f(x) %F Function to be interpolated, F(X). y = sin(x);
github
victorlei/libermate-master
rosy.m
.m
libermate-master/Tests/rosy.m
694
utf_8
779115362bc6de592272293c187aff40
function rosy(a, b) %ROSY "Rose" figures. % ROSY(A, B) plots the curve % X = R*COS(A*theta), Y = R*SIN(A*theta), where % R = SIN(A*B*theta) and 0 <= theta <= 2*PI (360 values). % Suggestions: ROSY(97, 5); ROSY(43, 4); ROSY(79, n9), n a digit. % P. M. Maurer, A rose is a rose..., Amer. Math. Monthly, 94 (1987), % pp. 631-645. if nargin < 2, b = 1; end if nargin < 1, a = 1; end c = 0; d = 1; p = a*b; [x, y] = spiro(a, a, c, d, p, .5); plot(x,y) axis square, axis off % Subfunction. function [x, y] = spiro(a, b, c, d, p, k) h = k*2*pi/180; t = (0:h:2*pi)'; r = c + d*sin(t*p); x = r.*cos(a*t); y = r.*sin(b*t);
github
victorlei/libermate-master
rossler_ex0.m
.m
libermate-master/Tests/rossler_ex0.m
947
utf_8
5a8cb634db4f93b743a6d06be24b133c
function rossler_ex0 %ROSSLER_EX0 Run Rossler example. % This is the recommended approach for MATLAB 6.5 and earlier. % ROSSLER_EX0 runs in MATLAB 7, but ROSSLER_EX1 illustrates the style of % coding now recommended for MATLAB 7. tspan = [0 100]; yzero = [1;1;1]; options = odeset('AbsTol',1e-7,'RelTol',1e-4); a = 0.2; b = 0.2; c = 2.5; [t,y] = ode45(@rossler,tspan,yzero,options,a,b,c); subplot(221), plot3(y(:,1),y(:,2),y(:,3)), mytitle(c), zlabel y_3(t), grid subplot(223), plot(y(:,1),y(:,2)), mytitle(c) c = 5; [t,y] = ode45(@rossler,tspan,yzero,options,a,b,c); subplot(222), plot3(y(:,1),y(:,2),y(:,3)), mytitle(c), zlabel y_3(t), grid subplot(224), plot(y(:,1),y(:,2)), mytitle(c) function yprime = rossler(t,y,a,b,c) %ROSSLER Rossler system, parameterized. yprime = [-y(2)-y(3); y(1)+a*y(2); b+y(3)*(y(1)-c)]; function mytitle(c) title(sprintf('c = %2.1f',c),'FontSize',14) xlabel y_1(t), ylabel y_2(t)
github
victorlei/libermate-master
skiprun.m
.m
libermate-master/Tests/skiprun.m
851
utf_8
029ef542f0f4a4b7f1a4396178755b86
function sol = skiprun %SKIPRUN Skipping rope BVP/eigenvalue example. solinit = bvpinit(linspace(0,1,10),@skipinit,5); sol = bvp4c(@skip,@skipbc,solinit); plot(sol.x,sol.y(1,:),'-', sol.x,sol.yp(1,:),'--', 'LineWidth',4) xlabel('x','FontSize',12) legend('y_1','y_2') % ------------------------ Subfunctions ------------------------ function yprime = skip(x,y,mu) %SKIP ODE/BVP skipping rope example. % YPRIME = SKIP(X,Y,MU) evaluates derivative. yprime = [y(2); -mu*y(1)]; function res = skipbc(ya,yb,mu) %SKIPBC ODE/BVP skipping rope boundary conditions. % RES = SKIPBC(YA,YB,MU) evaluates residual. res = [ya(1); ya(2)-1; yb(1)+yb(2)]; function yinit = skipinit(x) %SKIPINIT ODE/BVP skipping rope initial guess. % YINIT = SKIPINIT(X) evaluates initial guess at X. yinit = [sin(x); cos(x)];
github
victorlei/libermate-master
fisher.m
.m
libermate-master/Tests/fisher.m
1,812
utf_8
e0e4fe550562f2bce6a2895fc2219ea4
function fisher %FISHER Displays solutions to Fisher PDE. m = 0; a = -50; b = 50; t0 = 0; tf = 20; xvals = linspace(a,b,101); tvals = linspace(t0,tf,51); [xmesh, tmesh] = meshgrid(xvals,tvals); figure(1), subplot(2,2,1) sol = pdepe(m,@fpde,@fica,@fbc,xvals,tvals); ua = sol(:,:,1); mesh(xmesh,tmesh,ua) xlabel('x'), ylabel('t'), zlabel('u','Rotation',0), title('u(x,t)') text_set, view(30,30) subplot(2,2,2), contour(xmesh,tmesh,ua,[0.2:0.2:0.8]) xlabel('x'), ylabel('t','Rotation',0), title('Contour Plot') text_set, hold on plot([10,20,20,10],[8,13,8,8],'r--'), text(0,6,'Ref. slope = 2') hold off subplot(2,2,3), sol = pdepe(m,@fpde,@ficb,@fbc,xvals,tvals); ub = sol(:,:,1); mesh(xmesh,tmesh,ub) xlabel('x'), ylabel('t'), zlabel('u','Rotation',0), title('u(x,t)') text_set, view(30,30) subplot(2,2,4), contour(xmesh,tmesh,ub,[0.2:0.2:0.8]) xlabel('x'), ylabel('t','Rotation',0), title('Contour Plot') text_set, hold on plot([25,35,35,25],[5,10,5,5],'r--'), text(15,3,'Ref. slope = 2') hold off figure(2), zmesh = xmesh - 2*diag(tvals)*ones(size(xmesh)); waterfall(zmesh,tmesh,ua) xlabel('x-2t'), ylabel('t'), zlabel('u','Rotation',0), title('u(x-2t,t)') zlim([0 1]), text_set, view(15,30) %-------------------------- Subfunctions ------------------------------% function [c,f,s] = fpde(x,t,u,DuDx) %FDE Fisher PDE. c = 1; f = DuDx; s = u*(1-u); function u0 = fica(x) %FIC Fisher initial condition: 1st case. u0 = 0.99*(x<=-20); function [pa,qa,pb,qb] = fbc(xa,ua,xb,ub,t) %FBC Fisher boundary conditions. pa = 0; qa = 1; pb = 0; qb = 1; function u0 = ficb(x) %FIC2 Fisher initial condition: 2nd case. u0 = 0.25*(cos(0.1*pi*x).^2).*(abs(x)<=5); function text_set h = findall(gca,'type','text'); set(h,'FontSize',12,'FontWeight','Bold')
github
victorlei/libermate-master
ode_pp.m
.m
libermate-master/Tests/ode_pp.m
2,537
utf_8
2556cbfbbd3a419a06d408a4f2038dce
function T = ode_pp %ODE_PP Performance profile of three ODE solvers. solvers = {@ode23, @ode45, @ode113}; nsolvers = length(solvers); nproblems = 6; nruns = 5; % Number of times to run solver to get more reliable timing. for j = 1:nsolvers code = solvers{j} for i = 1:nproblems options = []; switch i case 1 fun = @fox1; tspan = [0 10]; yzero = [3;0]; case 2 fun = @rossler; tspan = [0 100]; yzero = [1;1;1]; options = odeset('AbsTol',1e-7,'RelTol',1e-4); case 3 fun = @fvdpol; tspan = [0 20]; yzero = [2;1]; mu = 10; case 4 fun = @fvdpol; tspan = [0 20]; yzero = [2;1]; mu = 1000; case 5 fun = @drug_transport; tspan = [0 6]; yzero = [0;0]; case 6 fun = @knee; tspan = [0 2]; yzero = 1; end t0 = clock; for k = 1:nruns [t,y] = code(fun,tspan,yzero,options); end T(i,j) = etime(clock,t0)/nruns; end end perfprof(T); ylim([0 1.05]), grid yvals = 0:1/nproblems:1; set(gca,'YTick',yvals) set(gca,'YTickLabel',[' 0 ';num2str(yvals(2:end-1)','%4.2f ');' 1 ']) f = findall(gcf,'type','line'); % Handles of the three lines. legend('ode23','ode45','ode113','Location','SE') set(f,{'Marker'},{'*','s','o'}') % Vectorized set. set(f,'MarkerSize',10) set(f,'MarkerFaceColor','auto') % Make marker interiors non-transparent. set(f,{'LineStyle'},{'-',':','--'}') % Vectorized set. set(f,'LineWidth',2) set(gca,'FontSize',14) function yprime = fvdpol(x,y) %FVDPOL Van der Pol equation written as first order system. % Parameter MU. yprime = [y(2); mu*y(2)*(1-y(1)^2)-y(1)]; end end function yprime = rossler(t,y) %ROSSLER Rossler system, parameterized. a = 0.2; b = 0.2; c = 2.5; yprime = [-y(2)-y(3); y(1)+a*y(2); b+y(3)*(y(1)-c)]; end function yprime = drug_transport(t,y) %DRUG_TRANSPORT Two-compartment pharmacokinetics example. % Reference: Shampine (1994, p. 105). yprime = [-5.6*y(1) + 48*pulse(t,1/48,0.5); 5.6*y(1) - 0.7*y(2)]; function pls = pulse(t,w,p) %PULSE Pulse of height 1, width W, period P. pls = (rem(t,p) <= w); end end function yprime = knee(t,y) %KNEE Knee problem. % Reference: Shampine (1994, p. 115). epsilon = 1e-4; yprime = (1/epsilon)*((1-t)*y - y^2); end
github
victorlei/libermate-master
functiontest3.m
.m
libermate-master/Tests/functiontest3.m
189
utf_8
0a3c2f15e8b5f4c945982a4e1f9e1938
% Comment function ret=myfunction(a,b,c) ret=a % Comment function [ret,b]=myfunction1(a,b,c) ret=a % Comment function [ret,ret2,ret3]=myfunction1(a,b,c) if(1) return end ret=a
github
victorlei/libermate-master
mbiol.m
.m
libermate-master/Tests/mbiol.m
1,110
utf_8
e2c5cb177e5361aaeaa8bc6ebfcf5b23
function mbiol %MBIOL Reaction-diffusion system from mathematical biology. % Solves the PDE and tests the energy decay condition. m = 0; xmesh = linspace(0,1,15); tspan = linspace(0,0.2,10); sol = pdepe(m,@mbpde,@mbic,@mbbc,xmesh,tspan); u1 = sol(:,:,1); u2 = sol(:,:,2); subplot(221) surf(xmesh,tspan,u1) xlabel('x','FontSize',12) ylabel('t','FontSize',12) title('u_1','FontSize',16) subplot(222) surf(xmesh,tspan,u2) xlabel('x','FontSize',12) ylabel('t','FontSize',12) title('u_2','FontSize',16) % Estimate energy integral. dx = xmesh(2) - xmesh(1); % Constant spacing. energy = 0.5*sum( (diff(u1,1,2)).^2 + (diff(u2,1,2)).^2, 2)/dx; subplot(212) plot(tspan',energy) xlabel('t','FontSize',12) title('Energy','FontSize',16) % ----------------------- Subfunctions ----------------------- function [c,f,s] = mbpde(x,t,u,DuDx) c = [1; 1]; f = DuDx/2; s = [1/(1+u(2)^2); 1/(1+u(1)^2)]; function u0 = mbic(x); u0 = [1+0.5*cos(2*pi*x); 1-0.5*cos(2*pi*x)]; function [pa,qa,pb,qb] = mbbc(xa,ua,xb,ub,t) pa = [0; 0]; qa = [1; 1]; pb = [0; 0]; qb = [1; 1];
github
joe-of-all-trades/ImageM-master
ImageM.m
.m
ImageM-master/ImageM.m
2,264
utf_8
c8b4371869f9375fa52c9346bcf8ee99
function ImageM % ImageM is a GUI program that aims to provide ImageJ-like experience in % MATLAB. % % In this very first version, the only usable function is to allow drag and % drop display of image file. Users can drage a file from file explorer and % drop it over the text area. If the file is an image file supported by % MATLAB, it'll be displayed in a new figure. % % Copyright, Chao-Yuan Yeh, 2016 hFig = figure('Name','ImageM', 'NumberTitle', 'off', 'position', ... [300 600 500 20], 'MenuBar', 'None'); tbh = uitoolbar(hFig); a = .20:.05:0.95; img1(:,:,1) = repmat(a,16,1)'; img1(:,:,2) = repmat(a,16,1); img1(:,:,3) = repmat(flip(a),16,1); pth = uipushtool(tbh,'CData',img1, 'TooltipString','My push tool',... 'HandleVisibility','off','ClickedCallBack', 'disp(''clicked'')'); f = uimenu('Label','File'); uimenu(f,'Label','Open','Callback','disp(''Open'')'); uimenu(f,'Label','Save','Callback','disp(''Save'')'); uimenu(f,'Label','Quit','Callback','disp(''Exit'')',... 'Separator','on','Accelerator','Q'); dndcontrol.initJava(); % Create figure % Create Java Swing JTextArea jTextArea = javaObjectEDT('javax.swing.JTextArea', ... sprintf('ImageM version 1.0')); % Create Java Swing JScrollPane % jScrollPane = javaObjectEDT('javax.swing.JScrollPane', jTextArea); % jScrollPane.setVerticalScrollBarPolicy(jScrollPane.VERTICAL_SCROLLBAR_ALWAYS); % Add Scrollpane to figure [~,hContainer] = javacomponent(jTextArea,[],hFig); set(hContainer,'Units','normalized','Position',[0 0 1 1]); % Create dndcontrol for the JTextArea object dndobj = dndcontrol(jTextArea); % Set Drop callback functions dndobj.DropFileFcn = @demoDropFcn; dndobj.DropStringFcn = @demoDropFcn; % Callback function function demoDropFcn(~,evt) txt = ''; switch evt.DropType case 'file' % jTextArea.setText('ImageM version 1.0') for n = 1:numel(evt.Data) jTextArea.setText(['Opening ', evt.Data{n}]); figure; imshow(evt.Data{1}) end case 'string' jTextArea.append(sprintf('Dropped text:\n%s\n',evt.Data)); end jTextArea.append(sprintf('\n')); end end
github
pfrommerd/tag-tracking-matlab-master
algorithm.m
.m
tag-tracking-matlab-master/algorithm.m
3,064
utf_8
b6b1b580d072f2db73a6da2e9f86f8b3
function algorithm(tracker, detector, images, initial_skip, skip_rate, save_images, save_poses) disp('Initializing figures'); fig1 = sfigure(1); fig2 = sfigure(2); fig3 = sfigure(3); fig4 = sfigure(4); fig5 = sfigure(5); fig6 = sfigure(6); figure(1); disp('Entering main loop'); counter = initial_skip; pose_history = []; while images.hasImage() if mod(counter, 10) == 0 %clc; end fprintf('------------------------------\n'); fprintf(':: Reading image\n'); tic(); img = images.readImage(); fprintf('// Took %f\n', toc()); fprintf(':: Processing image'); [detector_tags] = detector.process(img); [tags, x] = tracker.process(img, detector_tags); x fprintf(':: Clearing figures\n'); tic(); clf(fig1); clf(fig2); clf(fig3); clf(fig4); clf(fig5); clf(fig6); fprintf('// Took %f\n', toc()); fprintf(':: Displaying result\n'); tic(); sfigure(1); colormap(gray(255)); image(img); hold on; % project the tags, will be stored in the % tags array tags = project_tags(tracker.tagParams.K, tags); %drawTags(detector_tags, 'symbol', 'x'); %drawTags(reproj_tags, 'symbol', 'o'); drawTags(tags); sfigure(2); fprintf('// Took %f\n', toc()); fprintf(':: Displaying debug stuff\n'); tic(); tracker.debug(img, x, fig2, fig3, fig4, fig5, fig6); % Draw the pose history sfigure(7); pose_history = [pose_history x]; visualize_poses(pose_history); sfigure(1); fprintf('// Took %f\n', toc()); drawnow; if ~(counter == initial_skip && initial_skip > 0) if save_images img = getframe(fig1); file = sprintf('../tmp/images/frame_%04d.png', counter); fprintf('Saving image to file %s\n', file); imwrite(img.cdata, file); end if save_poses % Save the poses file = sprintf('../tmp/poses/poses_%04d.mat', counter); fprintf('Saving pose to file %s\n', file); save(file, 'x'); end end counter = counter + skip_rate; end end function drawTags(tags, varargin) for i=1:length(tags) drawTag(tags{i}, varargin); end end % Draws a (projected!) tag function drawTag(tag, vars) symbol = '.-'; for i=1:length(vars) if strcmp(vars{i},'symbol') symbol = vars{i + 1}; end end if max(size(tag)) < 1 return end color = tag.color; points = tag.corners'; x = points(1, :); y = points(2, :); plot([x x(1)], [y y(1)], symbol, 'Color', color); end
github
pfrommerd/tag-tracking-matlab-master
measure_patch_error.m
.m
tag-tracking-matlab-master/utils/measure_patch_error.m
1,003
utf_8
314720b90b8acc0540c992f1399e9e55
% Use squared error %{ function [ err ] = measure_patch_error(patchA, patchB) if ((size(patchA, 1) ~= size(patchB,1)) || ... (size(patchA, 2) ~= size(patchB,2)) || ... (size(patchA,1) == 0 || size(patchA,2) == 0)) err = 1; return; else [M, N] = size(patchA); diff = double(patchA) - double(patchB); %err = sum(sum(diff) .* diff)) / (M * N); % Divide by 255^2 to get the error from 0-1 err = sum(sum(diff .* diff)) / (M * N * 255 * 255); return; end end %} % Use correlation %%{ function [ err ] = measure_patch_error(patchA, patchB, default) if (size(patchA) ~= size(patchB)) err = default; return; else a = double(patchA); b = double(patchB); correlation = min(max(corr2(a, b), 0.0001), 1); err = -log(correlation); if isnan(err) % Some crazy value, like -Inf, Inf, NaN err = default; end end end %}
github
pfrommerd/tag-tracking-matlab-master
homography_project.m
.m
tag-tracking-matlab-master/utils/homography_project.m
253
utf_8
94e504b39cf3c7350ec41941a3627707
function [ x ] = homography_project(H, X) t = H * X; if any(t(3,:) <= 0) x = ones([2 size(t,2)]) * -1; end % Divide by the last row x_x = t(1, :) ./ t(3, :); x_y = t(2, :) ./ t(3, :); x = [x_x; x_y]; end
github
pfrommerd/tag-tracking-matlab-master
homography_solve.m
.m
tag-tracking-matlab-master/utils/homography_solve.m
2,397
utf_8
af74ae155f6fd32916b4660743d84634
%{ function v = homography_solve(pin, pout) % HOMOGRAPHY_SOLVE finds a homography from point pairs % V = HOMOGRAPHY_SOLVE(PIN, POUT) takes a 2xN matrix of input vectors and % a 2xN matrix of output vectors, and returns the homogeneous % transformation matrix that maps the inputs to the outputs, to some % approximation if there is noise. % % This uses the SVD method of % http://www.robots.ox.ac.uk/%7Evgg/presentations/bmvc97/criminispaper/node3.html % David Young, University of Sussex, February 2008 pin = pin'; pout = pout'; if ~isequal(size(pin), size(pout)) error('Points matrices different sizes'); end if size(pin, 1) ~= 2 error('Points matrices must have two rows'); end n = size(pin, 2); if n < 4 error('Need at least 4 matching points'); end % Solve equations using SVD x = pout(1, :); y = pout(2,:); X = pin(1,:); Y = pin(2,:); rows0 = zeros(3, n); rowsXY = -[X; Y; ones(1,n)]; hx = [rowsXY; rows0; x.*X; x.*Y; x]; hy = [rows0; rowsXY; y.*X; y.*Y; y]; h = [hx hy]; if n == 4 [U, ~, ~] = svd(h); else [U, ~, ~] = svd(h, 'econ'); end v = (reshape(U(:,9), 3, 3)).'; end %} %%{ function [ H ] = homography_solve(in_pts, out_pts) % est_homography estimates the homography to transform each of the % in_pts to out_pts % Inputs: % in_pts % out_pts % Outputs: % H: a 3x3 homography matrix such that outpts ~ H*video_pts % Scale the out_pts to prevent problems with small numbers %{ out_mean = mean(out_pts, 1); out_pts = out_pts - out_mean(ones(size(out_pts,1),1),:); out_scale = max(abs(out_pts(:))); out_pts = out_pts ./ out_scale; %} A = []; for p=1:size(in_pts, 1) i = in_pts(p,:); o = out_pts(p,:); a_x = [ -i(1) -i(2) -1 0 0 0 i(1) * o(1) i(2) * o(1) o(1) ]; a_y = [ 0 0 0 -i(1) -i(2) -1 i(1) * o(2) i(2) * o(2) o(2) ]; A = [A; a_x; a_y]; end [U, S, V] = svd(A); H = V(:, end); H = transpose(reshape(H, 3, 3)); % Redo the scaling that we did before %{ S = [out_scale 0 out_mean(1); ... 0 out_scale out_mean(2); 0 0 1]; H = S * H; %} % H33 (Tz) must be positive % if it is negative, take the negative of the matrix % as H is only known up to a scale if H(3, 3) < 0 H = -1 * H; end end %%}
github
pfrommerd/tag-tracking-matlab-master
cosyvio_pose_to_std.m
.m
tag-tracking-matlab-master/cs_conv/cosyvio_pose_to_std.m
796
utf_8
49be4974100959a1218ccf1d72bcbb30
% Converts a cosyvio pose (where x = z_std, y = -x_std, z = -y_std) to a % standard pose with the conversion % A = [0 -1 0; 0 0 -1; 1 0 0]; % X_std_cam = A * X_cosyvio_cam % X_std_world = B * X_cosyvio_world % The cosyvio dataset uses the form % X_c = R * X_w + T % We use % R * X_c + T = X_w % it can be solved that therefore % R_std = B * inv(R_cosyvio) * inv(A) % and % T_std = -B * inv(R_cosyvio) * T_cosyvio function [ std ] = cosyvio_pose_to_std(cosvio) A = [1 0 0; 0 1 0; 0 0 1]; B = [0 -1 0; 0 0 -1 ; 1 0 0]; R_cos = [quat_to_rotm(cosvio(4:7))]; T_cos = [cosvio(1); cosvio(2); cosvio(3)]; R_std = B * inv(R_cos) * inv(A); T_std = - B * inv(R_cos) * T_cos; quat = rotm_to_quat(R_std); std = [T_std(1); T_std(2); T_std(3); quat']; end
github
Nekooeimehr/MATLAB-Source-Code-Oversampling-Methods-master
Safe_Level_SMOTE.m
.m
MATLAB-Source-Code-Oversampling-Methods-master/Safe_Level_SMOTE.m
2,224
utf_8
7bcc91902154ffd812e529eb4bb2ec0c
function [final_features ,final_mark] = Safe_Level_SMOTE(original_features, original_mark, KNN) ind = find(original_mark == -1); Min_ins = original_features(ind,:); KNN = KNN + 1; final_features = original_features; Limit = size(Min_ins,1); Num_Ov = ceil(max(size(find(original_mark == -1),1) - size(find(original_mark == 1),1),size(find(original_mark == 1),1) - size(find(original_mark == -1),1))); j2 = 1; Safe_Level = safe_level_Finder(Min_ins, original_features, original_mark, KNN); while j2 <= Num_Ov %find nearest K samples from S2(i,:) [FirstCand idx] = datasample(Min_ins,1); Safe_Level_cand1 = Safe_Level(idx); Condidates = nearestneighbour(FirstCand', Min_ins', 'NumberOfNeighbours', min(KNN,Limit)); Condidates(:,1) = [] ; rn=ceil(rand(1)*(size(Condidates,2))); Sel_index = Condidates(:,rn); SecondCand = Min_ins(Sel_index,:); Safe_Level_cand2 = Safe_Level(Sel_index); if Safe_Level_cand2 ~= 0 Safe_level_ratio = Safe_Level_cand1/Safe_Level_cand2; else Safe_level_ratio = inf; end if (Safe_level_ratio == inf && Safe_Level_cand1 == 0) else if (Safe_level_ratio == inf && Safe_Level_cand1 ~= 0) gap = 0; else if Safe_level_ratio == 1 gap = rand(1); else if Safe_level_ratio > 1 gap = rand(1)*(1/Safe_level_ratio); else if Safe_level_ratio < 1 gap = rand(1) * Safe_level_ratio + 1 - Safe_level_ratio; end end end end snew = FirstCand(1,:) + gap.*(SecondCand - FirstCand(1,:)); final_features = [final_features;snew]; j2=j2+1; end end mark = -1 * ones(Num_Ov,1); final_mark = [original_mark; mark]; end function Safe_Level = safe_level_Finder(Minority_features, WholeDataInst, WholeDataLable, KNN) Ins_neighbors = nearestneighbour(Minority_features', WholeDataInst', 'NumberOfNeighbours', KNN); Safe_Level = zeros(1,size(Minority_features,1)); for i = 1:size(Minority_features,1) for j = 2:KNN if(WholeDataLable(Ins_neighbors(j,i),1)== -1) Safe_Level(1,i) = Safe_Level(1,i) + 1; end end end end
github
Nekooeimehr/MATLAB-Source-Code-Oversampling-Methods-master
Orig_agg_cluster.m
.m
MATLAB-Source-Code-Oversampling-Methods-master/Orig_agg_cluster.m
1,763
utf_8
bcf7eb3c45362da02adbfe1337455cfa
function labels = Orig_agg_cluster(data, CThresh) N = size(data,2); % Clusters is a cell array of vectors. Each vector contains the % indicies of the points belonging to that cluster. % Initially, each point is in it's own cluster. clusters = cell(N,1); for cc = 1:length(clusters) clusters{cc} = [cc]; end % the distance between each pair of points % point_dist = point_distance(data); D = pdist(data,'euclidean'); point_dist = squareform(D); point_dist2 = point_dist; for i=1:N point_dist2(i,i) = 100; end thresh = mean(median(point_dist2)).* CThresh; Z = linkage(D,'complete'); labels = cluster(Z,'cutoff',thresh, 'criterion', 'distance'); function d = point_distance(X) N = size(X,2); d = sum(X.^2,1); d = ones(N,1)*d + d'*ones(1,N) - 2*X'*X; %////////////////////////////////////////////////////////// % d = cluster_distance(c1,c2,point_dist,linkage) % Computes the pairwise distances between clusters c1 % and c2, using the point distance info in point_dist. %---------------------------------------------------------- function d = cluster_distance(c1,c2,point_dist,version) M1 = length(c1); M2 = length(c2); MaxM = max([M1,M2]); d = point_dist(c1,c2); if version == 1 d = min(d(:))*MaxM^0; else if version == 2 d = mean(d(:))*MaxM^0; else d = max(d(:))*MaxM^0; end end %////////////////////////////////////////////////////////// % clusters = merge_clusters(clusters, indicies) % Merge the clusters indicated by the entries indicies(1) % and indicies(2) of cell array 'clusters'. %---------------------------------------------------------- function clusters = merge_clusters(clusters, indicies) clusters{indicies(1)} = [clusters{indicies(1)} clusters{indicies(2)}]; clusters(indicies(2)) = [];
github
Nekooeimehr/MATLAB-Source-Code-Oversampling-Methods-master
nearestneighbour.m
.m
MATLAB-Source-Code-Oversampling-Methods-master/nearestneighbour.m
13,779
utf_8
8156790f42c7c9e5eba34274cd7ccbaa
function [idx, tri] = nearestneighbour(varargin) %NEARESTNEIGHBOUR find nearest neighbours % IDX = NEARESTNEIGHBOUR(X) finds the nearest neighbour by Euclidean % distance to each point (column) in X from X. X is a matrix with points % as columns. IDX is a vector of indices into X, such that X(:, IDX) are % the nearest neighbours to X. e.g. the nearest neighbour to X(:, 2) is % X(:, IDX(2)) % % IDX = NEARESTNEIGHBOUR(P, X) finds the nearest neighbour by Euclidean % distance to each point in P from X. P and X are both matrices with the % same number of rows, and points are the columns of the matrices. Output % is a vector of indices into X such that X(:, IDX) are the nearest % neighbours to P % % IDX = NEARESTNEIGHBOUR(I, X) where I is a logical vector or vector of % indices, and X has at least two rows, finds the nearest neighbour in X % to each of the points X(:, I). % I must be a row vector to distinguish it from a single point. % If X has only one row, the first input is treated as a set of 1D points % rather than a vector of indices % % IDX = NEARESTNEIGHBOUR(..., Property, Value) % Calls NEARESTNEIGHBOUR with the indicated parameters set. Property % names can be supplied as just the first letters of the property name if % this is unambiguous, e.g. NEARESTNEIGHBOUR(..., 'num', 5) is equivalent % to NEARESTNEIGHBOUR(..., 'NumberOfNeighbours', 5). Properties are case % insensitive, and are as follows: % Property: Value: % --------- ------ % NumberOfNeighbours natural number, default 1 % NEARESTNEIGHBOUR(..., 'NumberOfNeighbours', K) finds the closest % K points in ascending order to each point, rather than the % closest point. If Radius is specified and there are not % sufficient numbers, fewer than K neighbours may be returned % % Radius positive, default +inf % NEARESTNEIGHBOUR(..., 'Radius', R) finds neighbours within % radius R. If NumberOfNeighbours is not set, it will find all % neighbours within R, otherwise it will find at most % NumberOfNeighbours. The IDX matrix is padded with zeros if not % all points have the same number of neighbours returned. Note % that specifying a radius means that the Delaunay method will % not be used. % % DelaunayMode {'on', 'off', |'auto'|} % DelaunayMode being set to 'on' means NEARESTNEIGHBOUR uses the % a Delaunay triangulation with dsearchn to find the points, if % possible. Setting it to 'auto' means NEARESTNEIGHBOUR decides % whether to use the triangulation, based on efficiency. Note % that the Delaunay triangulation will not be used if a radius % is specified. % % Triangulation Valid triangulation produced by % delaunay or delaunayn % If a triangulation is supplied, NEARESTNEIGHBOUR will attempt % to use it (in conjunction with dsearchn) to find the % neighbours. % % [IDX, TRI] = NEARESTNEIGHBOUR( ... ) % If the Delaunay Triangulation is used, TRI is the triangulation of X'. % Otherwise, TRI is an empty matrix % % Example: % % % Find the nearest neighbour in X to each column of X % x = rand(2, 10); % idx = nearestneighbour(x); % % % Find the nearest neighbours to each point in p % p = rand(2, 5); % x = rand(2, 20); % idx = nearestneighbour(p, x) % % % Find the five nearest neighbours to points x(:, [1 6 20]) in x % x = rand(4, 1000) % idx = nearestneighbour([1 6 20], x, 'NumberOfNeighbours', 5) % % % Find all neighbours within radius of 0.1 of the points in p % p = rand(2, 10); % x = rand(2, 100); % idx = nearestneighbour(p, x, 'r', 0.1) % % % Find at most 10 nearest neighbours to point p from x within a % % radius of 0.2 % p = rand(1, 2); % x = rand(2, 30); % idx = nearestneighbour(p, x, 'n', 10, 'r', 0.2) % % % See also DELAUNAYN, DSEARCHN, TSEARCH %TODO Allow other metrics than Euclidean distance %TODO Implement the Delaunay mode for multiple neighbours % Copyright 2006 Richard Brown. This code may be freely used and % distributed, so long as it maintains this copyright line error(nargchk(1, Inf, nargin, 'struct')); % Default parameters userParams.NumberOfNeighbours = [] ; % Finds one userParams.DelaunayMode = 'auto'; % {'on', 'off', |'auto'|} userParams.Triangulation = [] ; userParams.Radius = inf ; % Parse inputs [P, X, fIndexed, userParams] = parseinputs(userParams, varargin{:}); % Special case uses Delaunay triangulation for speed. % Determine whether to use Delaunay - set fDelaunay true or false nX = size(X, 2); nP = size(P, 2); dim = size(X, 1); switch lower(userParams.DelaunayMode) case 'on' %TODO Delaunay can't currently be used for finding more than one %neighbour fDelaunay = userParams.NumberOfNeighbours == 1 && ... size(X, 2) > size(X, 1) && ... ~fIndexed && ... userParams.Radius == inf; case 'off' fDelaunay = false; case 'auto' fDelaunay = userParams.NumberOfNeighbours == 1 && ... ~fIndexed && ... size(X, 2) > size(X, 1) && ... userParams.Radius == inf && ... ( ~isempty(userParams.Triangulation) || delaunaytest(nX, nP, dim) ); end % Try doing Delaunay, if fDelaunay. fDone = false; if fDelaunay tri = userParams.Triangulation; if isempty(tri) try tri = delaunayn(X'); catch msgId = 'NearestNeighbour:DelaunayFail'; msg = ['Unable to compute delaunay triangulation, not using it. ',... 'Set the DelaunayMode parameter to ''off''']; warning(msgId, msg); end end if ~isempty(tri) try idx = dsearchn(X', tri, P')'; fDone = true; catch warning('NearestNeighbour:DSearchFail', ... 'dsearchn failed on triangulation, not using Delaunay'); end end else % if fDelaunay tri = []; end % If it didn't use Delaunay triangulation, find the neighbours directly by % finding minimum distances if ~fDone idx = zeros(userParams.NumberOfNeighbours, size(P, 2)); % Loop through the set of points P, finding the neighbours Y = zeros(size(X)); for iPoint = 1:size(P, 2) x = P(:, iPoint); % This is the faster than using repmat based techniques such as % Y = X - repmat(x, 1, size(X, 2)) for i = 1:size(Y, 1) Y(i, :) = X(i, :) - x(i); end % Find the closest points, and remove matches beneath a radius dSq = sum(abs(Y).^2, 1); iRad = find(dSq < userParams.Radius^2); if ~fIndexed iSorted = iRad(minn(dSq(iRad), userParams.NumberOfNeighbours)); else iSorted = iRad(minn(dSq(iRad), userParams.NumberOfNeighbours + 1)); iSorted = iSorted(2:end); end % Remove any bad ones idx(1:length(iSorted), iPoint) = iSorted'; end %while ~isempty(idx) && isequal(idx(end, :), zeros(1, size(idx, 2))) % idx(end, :) = []; %end idx( all(idx == 0, 2), :) = []; end % if ~fDone if isvector(idx) idx = idx(:)'; end end % nearestneighbour %DELAUNAYTEST Work out whether the combination of dimensions makes %fastest to use a Delaunay triangulation in conjunction with dsearchn. %These parameters have been determined empirically on a Pentium M 1.6G / %WinXP / 512MB / Matlab R14SP3 platform. Their precision is not %particularly important function tf = delaunaytest(nx, np, dim) switch dim case 2 tf = np > min(1.5 * nx, 400); case 3 tf = np > min(4 * nx , 1200); case 4 tf = np > min(40 * nx , 5000); % if the dimension is higher than 4, it is almost invariably better not % to try to use the Delaunay triangulation otherwise tf = false; end % switch end % delaunaytest %MINN find the n most negative elements in x, and return their indices % in ascending order function I = minn(x, n) % Make sure n is no larger than length(x) n = min(n, length(x)); % Sort the first n [xsn, I] = sort(x(1:n)); % Go through the rest of the entries, and insert them into the sorted block % if they are negative enough for i = (n+1):length(x) j = n; while j > 0 && x(i) < xsn(j) j = j - 1; end if j < n % x(i) should go into the (j+1) position xsn = [xsn(1:j), x(i), xsn((j+1):(n-1))]; I = [I(1:j), i, I((j+1):(n-1))]; end end end %minn %PARSEINPUTS Support function for nearestneighbour function [P, X, fIndexed, userParams] = parseinputs(userParams, varargin) if length(varargin) == 1 || ~isnumeric(varargin{2}) P = varargin{1}; X = varargin{1}; fIndexed = true; varargin(1) = []; else P = varargin{1}; X = varargin{2}; varargin(1:2) = []; % Check the dimensions of X and P if size(X, 1) ~= 1 % Check to see whether P is in fact a vector of indices if size(P, 1) == 1 try P = X(:, P); catch error('NearestNeighbour:InvalidIndexVector', ... 'Unable to index matrix using index vector'); end fIndexed = true; else fIndexed = false; end % if size(P, 1) == 1 else % if size(X, 1) ~= 1 fIndexed = false; end if ~fIndexed && size(P, 1) ~= size(X, 1) error('NearestNeighbour:DimensionMismatch', ... 'No. of rows of input arrays doesn''t match'); end end % Parse the Property/Value pairs if rem(length(varargin), 2) ~= 0 error('NearestNeighbour:propertyValueNotPair', ... 'Additional arguments must take the form of Property/Value pairs'); end propertyNames = {'numberofneighbours', 'delaunaymode', 'triangulation', ... 'radius'}; while length(varargin) ~= 0 property = varargin{1}; value = varargin{2}; % If the property has been supplied in a shortened form, lengthen it iProperty = find(strncmpi(property, propertyNames, length(property))); if isempty(iProperty) error('NearestNeighbour:InvalidProperty', 'Invalid Property'); elseif length(iProperty) > 1 error('NearestNeighbour:AmbiguousProperty', ... 'Supplied shortened property name is ambiguous'); end property = propertyNames{iProperty}; switch property case 'numberofneighbours' if rem(value, 1) ~= 0 || ... value > length(X) - double(fIndexed) || ... value < 1 error('NearestNeighbour:InvalidNumberOfNeighbours', ... 'Number of Neighbours must be an integer, and smaller than the no. of points in X'); end userParams.NumberOfNeighbours = value; case 'delaunaymode' fOn = strcmpi(value, 'on'); if strcmpi(value, 'off') userParams.DelaunayMode = 'off'; elseif fOn || strcmpi(value, 'auto') if userParams.NumberOfNeighbours ~= 1 if fOn warning('NearestNeighbour:TooMuchForDelaunay', ... 'Delaunay Triangulation method works only for one neighbour'); end userParams.DelaunayMode = 'off'; elseif size(X, 2) < size(X, 1) + 1 if fOn warning('NearestNeighbour:TooFewDelaunayPoints', ... 'Insufficient points to compute Delaunay triangulation'); end userParams.DelaunayMode = 'off'; elseif size(X, 1) == 1 if fOn warning('NearestNeighbour:DelaunayDimensionOne', ... 'Cannot compute Delaunay triangulation for 1D input'); end userParams.DelaunayMode = 'off'; else userParams.DelaunayMode = value; end else warning('NearestNeighbour:InvalidOption', ... 'Invalid Option'); end % if strcmpi(value, 'off') case 'radius' if isscalar(value) && isnumeric(value) && isreal(value) && value > 0 userParams.Radius = value; if isempty(userParams.NumberOfNeighbours) userParams.NumberOfNeighbours = size(X, 2) - double(fIndexed); end else error('NearestNeighbour:InvalidRadius', ... 'Radius must be a positive real number'); end case 'triangulation' if isnumeric(value) && size(value, 2) == size(X, 1) + 1 && ... all(ismember(1:size(X, 2), value)) userParams.Triangulation = value; else error('NearestNeighbour:InvalidTriangulation', ... 'Triangulation not a valid Delaunay Triangulation'); end end % switch property varargin(1:2) = []; end % while if isempty(userParams.NumberOfNeighbours) userParams.NumberOfNeighbours = 1; end end %parseinputs
github
Nekooeimehr/MATLAB-Source-Code-Oversampling-Methods-master
Mod_AggCluster.m
.m
MATLAB-Source-Code-Oversampling-Methods-master/Mod_AggCluster.m
4,951
utf_8
5625c0e6a852c1dc8f6c1ddf39c5f24b
function [min_clusters] = Mod_AggCluster(Majority_features, Minority_features ,CThresh) % This code is a modification of the source code for Hierachical Clustering % implemented by David Ross % The source code for the original Hierachical Clustering can be found in: % http://www.cs.toronto.edu/~dross/code/ SizeMin = size(Minority_features,1); min_clusters = (1:SizeMin)'; %% Clustering the majority class using Hierachical Clustering maj_clusters = Orig_agg_cluster(Majority_features, CThresh); % Kmaj = size(unique(maj_clusters),1); % m_each_maj = histc(maj_clusters,1:Kmaj); Whole_data_min = [Minority_features; Majority_features]; D = pdist(Whole_data_min,'euclidean'); point_dist_min = squareform(D); %% Clustering the Minority instances using majority clusters min_clusters = inside_AggCluster(Minority_features', min_clusters, maj_clusters, point_dist_min, CThresh); function labels = inside_AggCluster(data, same_clusters, other_clusters, point_dist_whole, CThresh) Num_Reject = 0; N = size(data,2); Exist_Clus = unique(same_clusters); M = size(Exist_Clus ,1); % the distance between each pair of points point_dist = point_dist_whole(1:N,1:N); point_dist2 = point_dist; for i=1:N point_dist2(i,i) = 100; end % Measuring the threshold thresh = mean(median(point_dist2)).* CThresh; % Clusters is a cell array of vectors. Each vector contains the % indicies of the points belonging to that cluster. % Initially, each point is in it's own cluster. clusters = cell(M,1); for cc = 1:M clusters{cc} = find(same_clusters == Exist_Clus(cc))'; end % until the termination condition is met mm = 0; while mm < thresh % compute the distances between all pairs of clusters cluster_dist = inf*ones(length(clusters)); for c1 = 1:length(clusters) for c2 = (c1+1):length(clusters) cluster_dist(c1,c2) = cluster_distance(clusters{c1}, clusters{c2}, point_dist, 3); end end % merge the two nearest clusters [mm ii] = min(cluster_dist(:)); [ii(1) ii(2)] = ind2sub(size(cluster_dist), ii(1)); if mm > thresh || length(clusters) < 3, break end % find the distance of nearest clusters to other class clusters: Unique_Other = unique(other_clusters); num_clus = size(Unique_Other,1); for k = 1:num_clus MN2other(k) = cluster_distance_maj(clusters{ii(1)}, N + find(other_clusters == Unique_Other(k)), point_dist_whole, 3); end flag = 1; Distr = histc(other_clusters,1:max(other_clusters)); Distr(Distr == 0) = [] ; near_other_ind = find(MN2other < mm & Distr' > 3); for t = 1:length(near_other_ind) check_dis = cluster_distance_maj(clusters{ii(2)}, N + find(other_clusters == Unique_Other(near_other_ind(t))) , point_dist_whole, 3); if check_dis <mm flag = 0; Num_Reject = Num_Reject + 1; A = clusters{ii(1)}; B = clusters{ii(2)}; point_dist (A(1,1),B(1,1)) = inf; point_dist (B(1,1),A(1,1)) = inf; end end % Place the if condition if there exist a majority cluster between them or not if flag == 1; clusters = merge_clusters(clusters, ii); end end % assign labels to the points, based on their cluster membership Num_Reject labels = zeros(N,1); for cc = 1:length(clusters) labels(clusters{cc}) = cc; end %////////////////////////////////////////////////////////// % d = point_distance(X) % Computes the pairwise distances between columns of X. %---------------------------------------------------------- function d = Point_Distance(X) N = size(X,2); d = sum(X.^2,1); d = ones(N,1)*d + d'*ones(1,N) - 2*X'*X; %////////////////////////////////////////////////////////// % d = cluster_distance(c1,c2,point_dist,linkage) % Computes the pairwise distances between clusters c1 % and c2, using the point distance info in point_dist. %---------------------------------------------------------- function d = cluster_distance(c1,c2,point_dist,version) M1 = length(c1); M2 = length(c2); MaxM = max([M1,M2]); d = point_dist(c1,c2); if version == 1 d = min(d(:))*MaxM^0.04; else if version == 2 d = mean(d(:))*MaxM^0.04; else d = max(d(:))*MaxM^0.04; end end function d = cluster_distance_maj(c1,c2,point_dist,version) d = point_dist(c1,c2); if version == 1 d = min(d(:)); else if version == 2 d = mean(d(:)); else d = max(d(:)); end end %////////////////////////////////////////////////////////// % clusters = merge_clusters(clusters, indicies) % Merge the clusters indicated by the entries indicies(1) % and indicies(2) of cell array 'clusters'. %---------------------------------------------------------- function clusters = merge_clusters(clusters, indicies) clusters{indicies(1)} = [clusters{indicies(1)} clusters{indicies(2)}]; clusters(indicies(2)) = [];
github
snoopyisadog/Chinese_Stroke_Extraction-master
extract_rho.m
.m
Chinese_Stroke_Extraction-master/extract_rho.m
1,538
utf_8
5f36bbd40f6c0289fa94fec6621dfdd0
function [ pics ] = extract_rho( rho, pts ) global map img space hei wid ang space = rho; [ hei, wid, ang] = size( rho); map = zeros( hei, wid, ang); P = size(pts,1); pics = zeros( 1, hei, wid); for i = 1:P x = pts(i,1); y = pts(i,2); for k = 1:ang if ( rho( x, y, k) == 1 ) & ( map( x, y, k) == 0 ) img = ones( hei, wid); DFS(x,y,k); %fprintf('pic=%d\n',hei*wid - sum(sum(img))); if hei*wid - sum(sum(img)) > 50 % a stroke should bigger than 50 pixels pics(end+1,:,:) = img; end end end end end function DFS( x, y, z) global map img space hei wid ang img( x, y) = 0; map( x, y, z) = 1; for i = x-1 : 1 : x+1 for j = y-1 : 1 : y+1 for k = z-1 : 1 : z+1 a = i; b = j; c = k; if i <1 a = 1; elseif i>hei a = hei; end if j <1 b = 1; elseif j>wid b = wid; end if k<1 c = ang; % wrap elseif k>ang c = 1; end %fprintf('i=%djy=%d,k=%d,a=%d,b=%d,c=%d\n',i,j,k,a,b,c); if ( space( a, b, c) == 1 ) & ( map( a, b, c) == 0 ) DFS(a,b,c); end end end end end
github
snoopyisadog/Chinese_Stroke_Extraction-master
get_PBOD.m
.m
Chinese_Stroke_Extraction-master/get_PBOD.m
1,139
utf_8
e89aa1e17b4707bfa9945b0ed62b909b
function [ ret, pt ] = get_PBOD( im ) global pic hei wid pic = im; [ hei, wid ] = size(im); gap = 3; range = 360/gap; ang = linspace(0,2*pi,360/gap); ret = zeros(hei, wid, 360/gap); pt = zeros(1,2) for i = 1:hei for j = 1:wid if im(i,j) == 0 % if this pixel is black pt(end+1,1:2) = [ i j ]; for k = 1:size(ang,2) ret(i,j,k) = distance2boundary(i,j,ang(k)); %fprintf('ret(%d,%d,%d) = %f\n',i,j,k,ret(i,j,k)); end end %{ for k = 1:range % start from deg 1 because MATLAB ret(i,j,k) = distance2boundary(i,j,k*gap); end %} end end pt(1,:) = []; end function ret = distance2boundary(i,j,deg) global pic hei wid for d = 1:hei %fprintf('deg=%f\n',deg); x = round( i + d * cos(deg) ); y = round( j + d * sin(deg) ); %fprintf('i=%d,j=%d,deg=%f\n',i,j,deg); %fprintf('d=%d,x=%f,y=%f,deg=%f\n',d,x,y,deg); if pic(x,y) == 1 break; end end ret = d; end
github
mainster/matlabCodes-master
EMW_d.m
.m
matlabCodes-master/EMW_d.m
5,530
utf_8
f71f44e53bfe2723a3d6a621d63e3e06
function varargout = EMW_d(varargin) % EMW_D M-file for EMW_d.fig % EMW_D, by itself, creates a new EMW_D or raises the existing % singleton*. % % H = EMW_D returns the handle to a new EMW_D or the handle to % the existing singleton*. % % EMW_D('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in EMW_D.M with the given input arguments. % % EMW_D('Property','Value',...) creates a new EMW_D or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before EMW_d_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to EMW_d_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 EMW_d % Wellengleichung, elektromagnetische welle 05-11-2015 @@@MDB % % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @EMW_d_OpeningFcn, ... 'gui_OutputFcn', @EMW_d_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 EMW_d is made visible. function EMW_d_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 EMW_d (see VARARGIN) % Choose default command line output for EMW_d handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes EMW_d wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = EMW_d_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) x = -400:400; t = 0:10000; lambda =100; T = 50; w = 2*pi/T; k = 2*pi/lambda; c = lambda/T; phi0 = 180; for l = 1:length(t) % E(1:400) = sin(w*t(l) + k*x(1:400) + phi0); % E(401:801) = sin(w*t(l) - k*x(401:801) + phi0); % E = sin(w*t(l) - sign((1:801)-400.5).*k.*x + phi0); %Welle von Mitte E1(1:801) = sin(w*t(l) - k*x(1:801) + phi0); %Welle nach rechts E2(1:801) = sin(w*t(l) + k*x(1:801) + phi0); %Welle nach links E3 = E1+ E2; % plot(x,E3, 'b'); plot(x, E1, 'g', x, E2, 'r',x,E3, 'b'); % grid on xlim([-400 400]) % Bereich für x Achse set(gca, 'xtick', min(xlim):100:max(xlim)); % Bestimme die Einteilung der x Achse ylim([-2.4 2.4]) % Bereich für y Achse set(gca, 'ytick', min(xlim):0.5:max(xlim)); % Bestimme die Einteilung der y Achse % xlabel('this goes across') % ylabel('this goes up') pause(0.1); end % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) pause; % --- Executes on button press in pushbutton3. function pushbutton3_Callback(hObject, eventdata, handles) % hObject handle to pushbutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) exit; % --- Executes on slider movement. function slider1_Callback(hObject, eventdata, handles) % hObject handle to slider1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function slider1_CreateFcn(hObject, eventdata, handles) % hObject handle to slider1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end
github
mainster/matlabCodes-master
BodePlotGui.m
.m
matlabCodes-master/BodePlotGui.m
51,136
utf_8
857358906042b6788eef8bf402d2758f
function varargout = BodePlotGui(varargin) % BODEPLOTGUI Application M-file for BodePlotGui.fig % FIG = BODEPLOTGUI launch BodePlotGui GUI. % BODEPLOTGUI('callback_name', ...) invoke the named callback. % Last Modified by GUIDE v2.5 18-Oct-2011 14:11:08 %Written by Erik Cheever (Copyright 2002) %Contact: [email protected] % Erik Cheever % Dept. of Engineering % Swarthmore College % 500 College Avenue % Swarthmore, PA 19081 USA %This function acts as a switchyard for several callbacks. It also intializes %the variables used by the GUI. Note that all variables are initialized here to %default values. A brief description of each variable is included. if (nargin == 0) || (isa(varargin{1},'tf')) %If no arguments, or first fig = openfig(mfilename,'new'); handles = guihandles(fig); %Get handles structure. initBodePlotGui(handles); handles=guidata(handles.AsymBodePlot); %Reload handles after function call. if nargout > 0 %If output argument is used, set it to figure. varargout{1} = fig; end if ((nargin~=0) && (isa(varargin{1},'tf'))), %Transfer function chosen. handles.Sys=varargin{1}; %The variable Sys is the transfer function. doBodeGUI(handles); end elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK try [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard catch disp(lasterr); end end end % ------------------End of function BodePlotGui ---------------------- function initBodePlotGui(handles) handles.IncludeString=[]; %An array of strings representing terms to include in the plot. handles.ExcludeString=[]; %An array of strings representing terms to exclude from plot. handles.IncElem=[]; %An array of indices of terms corresponding to their % location in the IncludeString array. handles.ExcElem=[]; %An array of indices of terms corresponding to their % location in the ExcludeString array. handles.FirstPlot=1; %This term is 1 the first time a plot is made. This lets % Matlab do the original autoscaling. The scales are then % saved and reused. handles.MagLims=[]; %The limits on the magnitude plot determined by MatLab autoscaling. handles.PhaseLims=[]; %The limits on the phase plot determined by MatLab autoscaling. handles.LnWdth=2; set(handles.LineWidth,'String',num2str(handles.LnWdth)); %Set the color of lines used in gray scale. The plotting functions %cycle through these colors (and then cycle through the linestyles). handles.Gray=[0.75 0.75 0.75; 0.5 0.5 0.5; 0.25 0.25 0.25]; handles.GrayZero=[0.9 0.9 0.9]; %This is the color used for the zero reference. %Set the color of lines used in color plots. The plotting functions %cycle through these colors (and then cycle through the linestyles). handles.Color=[0 1 1; 0 0 1; 0 1 0; 1 0 0; 1 0 1;1 0.52 0.40]; handles.ColorZero=[1 1 0]; %Yellow, this is the color used for the zero reference. %Sets order of linestyles used. handles.linestyle={':','--','-.'}; %This sets the default scheme to color (GUI can set them to gray scale). handles.colors=handles.Color; handles.zrefColor=handles.ColorZero; handles.exactColor=[0 0 0]; %Black handles.Sys=[]; handles.SysInc=[]; handles.Terms=[]; %The structure "Term" has three elements. % type: this can be any of the 7 types listed below. % 1) The multiplicative constant. % 2) Real poles % 3) Real zeros % 4) Complex poles % 5) Complex zeros % 6) Poles at the origin % 7) Zeros at the origin % value: this is the location of the pole or zero (or in the case % of the multiplicative constant, its value). % multiplicity: this gives the multiplicity of the pole or zero. It has % no meaning in the case of the multiplicative constant. %The variable "Acc" is a relative accuracy used to determine whether or not %two poles (or zeros) are the same. Because Matlab uses an approximate %technique to find roots of an equation, it is likely to give slightly %different locations to identical roots. handles.Acc=1E-3; set(handles.TransferFunctionText,'String',... {' ','No transfer function chosen',' '}); guidata(handles.AsymBodePlot, handles); %save changes to handles. loadSystems(handles); handles=guidata(handles.AsymBodePlot); %Reload handles after function call. guidata(handles.AsymBodePlot, handles); %save changes to handles. end function simpleTF = makeSimple(origTF) simpleTF=minreal(origTF); %Get minimum realization. % Get numerator and denominator of two realizations. If their % lengths are unequal, it means that there were poles and zeros that % cancelled. [n1,d1]=tfdata(simpleTF,'v'); [n2,d2]=tfdata(origTF,'v'); if (length(n1)~=length(n2)), disp(' '); disp(' '); disp(' '); disp('************Warning******************'); disp('Original transfer function was:'); origTF disp('Some poles and zeros were equal. After cancellation:'); simpleTF disp('The simplified transfer function is the one that will be used.'); disp('*************************************'); disp(' '); beep; waitfor(warndlg('System has poles and zeros that cancel. See Command Window for caveats.')); end end function doBodeGUI(handles) handles.Sys=makeSimple(handles.Sys); handles.SysInc=handles.Sys; %The variable sysInc is that part of the transfer % function that will be plotted (with no poles or zeros excluded). Start with % it equal to Sys. This variable is modified in BodePlotSys %The function BodePlotTerms separates the transfer function into its consituent parts. % The variable DoQuit will come back as non-zero if there was a problem. DoQuit=BodePlotTerms(handles); handles=guidata(handles.AsymBodePlot); %Reload handles after function call. %if DoQuit is zero, there were no problems and we may continue. if ~DoQuit, BodePlotter(handles); %Make plot handles=guidata(handles.AsymBodePlot); %Reload handles after function call. %DoQuit was non-zero, so there was a problem. Quit program. else CloseButton_Callback(fig,'',handles,''); end end %| ABOUT CALLBACKS: %| GUIDE automatically appends subfunction prototypes to this file, and %| sets objects' callback properties to call them through the FEVAL %| switchyard above. This comment describes that mechanism. %| %| Each callback subfunction declaration has the following form: %| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN) %| %| The subfunction name is composed using the object's Tag and the %| callback type separated by '_', e.g. 'slider2_Callback', %| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'. %| %| H is the callback object's handle (obtained using GCBO). %| %| EVENTDATA is empty, but reserved for future use. %| %| HANDLES is a structure containing handles of components in GUI using %| tags as fieldnames, e.g. handles.figure1, handles.slider2. This %| structure is created at GUI startup using GUIHANDLES and stored in %| the figure's application data using GUIDATA. A copy of the structure %| is passed to each callback. You can store additional information in %| this structure at GUI startup, and you can change the structure %| during callbacks. Call guidata(h, handles) after changing your %| copy to replace the stored original so that subsequent callbacks see %| the updates. Type "help guihandles" and "help guidata" for more %| information. %| %| VARARGIN contains any extra arguments you have passed to the %| callback. Specify the extra arguments by editing the callback %| property in the inspector. By default, GUIDE sets the property to: %| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo)) %| Add any extra arguments after the last argument, before the final %| closing parenthesis. % -------------------------------------------------------------------- function varargout = IncludedElements_Callback(~, ~, handles, varargin) % Stub for Callback of the uicontrol handles.IncludedElements. % If a term in the "Included Elements" box is clicked, this callback is invoked. %Get index of element in box that is chosen.%If the index corresponds to one of the terms of the transfer function, deal with it. i=get(handles.IncludedElements,'Value'); % The alternative is that it corresponds to another string in the box (there is a blank % line, a line with dashes "----" and a line instructing the user to click on an element % to include it). if i<=length(handles.IncElem) TermsInd=handles.IncElem(i); %Get the index of the included element. handles.Terms(TermsInd).display=0; %Set display to 0 (to exclude it) guidata(handles.AsymBodePlot, handles); %save changes to handles. BodePlotter(handles); %Plot the Transfer function. handles=guidata(handles.AsymBodePlot); %Reload handles after function call. end end % ------------------End of function IncludedElements_Callback -------- % -------------------------------------------------------------------- function varargout = ExcludedElements_Callback(~, ~, handles, varargin) % Callback of the uicontrol handles.ExcludedElements. % If a term in the "Excluded Elements" box is clicked, this callback is invoked. i=get(handles.ExcludedElements,'Value'); %Get index of element in box that is chosen. %If the index corresponds to one of the terms of the transfer function, deal with it. % The alternative is that it corresponds to another string in the box (there is a blank % line, a line with dashes "----" and a line instructing the user to click on an element % to exclude it). if i<=length(handles.ExcElem) TermsInd=handles.ExcElem(i); %Get the index of the excluded element. handles.Terms(TermsInd).display=1; %Set display to 1 (to include it) guidata(handles.AsymBodePlot, handles); %save changes to handles. BodePlotter(handles); %Plot the Transfer function. handles=guidata(handles.AsymBodePlot); %Reload handles after function call. end end % ------------------End of function ExcludedElements_Callback -------- % -------------------------------------------------------------------- function varargout = CloseButton_Callback(~, ~, handles, varargin) % Callback for the uicontrol handles.CloseButton. %This function closes the window, and displays a message. disp(' '); disp('Asymptotic Bode Plotter closed.'); disp(' '); disp(' '); delete(handles.AsymBodePlot); end % ------------------End of function CloseButton_Callback ------------- % -------------------------------------------------------------------- function DoQuit=BodePlotTerms(handles) %This function takes a system and splits it up into terms that are plotted %individually when making a Bode plot by hand (it finds %1) The multiplicative constant. %2) All real poles %3) All real zeros %4) All complex poles %5) All complex zeros %6) All poles at the origin %7) All zeros at the origin % %In addition to finding the poles and zeros, it determines their multiplicity. %If two poles or zeros are very close they are determined to be the same pole %or zero. sys=handles.Sys; Acc=handles.Acc; %Relative accuracy. [z,p,k]=zpkdata(sys,'v'); %Get pole and zero data. %Find gain term. [n,d]=tfdata(sys,'v'); k=n(max(find(n~=0)))/d(max(find(d~=0))); term(1).type='Constant'; term(1).value=k; term(1).multiplicity=1; %Get all poles. j=length(term); for i=1:length(p), term(j+i).value=p(i); term(j+i).multiplicity=1; term(j+i).type='Pole'; end %Get all zeros. j=length(term); for i=1:length(z), term(j+i).value=z(i); term(j+i).multiplicity=1; term(j+i).type='Zero'; end %Check for multiplicity for i=2:length(term), for k=(i+1):length(term), %Handle pole or zero at origin as special case. if (term(i).value==0), %Multiple pole or zero at origin. if (term(k).value==0), term(i).multiplicity=term(i).multiplicity+term(k).multiplicity; %Set multiplicity of kth term to 0 to signify that it has been % subsumed by term(i) (by increasing the ith term's multiplicity). term(k).multiplicity=0; end %We know term is not at origin, so check for (approximate) equality % Since we know this term is not at origin, we can divide by value. elseif (abs((term(i).value-term(k).value)/term(i).value) < Acc), term(i).multiplicity=term(i).multiplicity+term(k).multiplicity; %Set multiplicity of kth term to 0 to signify that it has been % subsumed by term(i) (by increasing the ith term's multiplicity). term(k).multiplicity=0; end end end %Check for location of poles and zeros (and remove complex conjugates). i=2; while (i<=length(term)), %If root is at origin, handle it separately if (term(i).value==0), term(i).type=['Origin' term(i).type]; %If imaginary part is sufficiently small... elseif (abs(imag(term(i).value)/term(i).value)<Acc), term(i).type=['Real' term(i).type]; %...Add "Real" to type term(i).value=real(term(i).value); %...And set imaginary part=0 %If imaginary part is *not* small... else term(i).type=['Complex' term(i).type]; %...Add "Complex" to type term(i+1).multiplicity=0; %...Remove complex conjugate i=i+1; %...And skip conjugate. end i=i+1; %Go to next root. end %Remove all terms with multiplicity 0. j=0; for i=1:length(term), if (term(i).multiplicity~=0) j=j+1; term(j)=term(i); term(j).display=1; end end term=term(1:j); DoQuit=0; %Check for poles or zeros in right half plane, % or on imaginary axis. Poles and zeros at origin are OK. if any(real(p)>0), %Poles in RHP. beep; waitfor(errordlg('System has poles with positive real part, cannot make plot.')); DoQuit=1; return; end if any(real(z)>0), %Zeros in RHP. disp(' '); disp(' '); disp(' '); disp('************Warning******************'); handles.Sys disp('is a nonminimum phase system (zeros in right half plane).'); disp('The standard rules for phase do not apply.'); disp(' '); disp('Also - The plots produced may be different than the Matlab Bode plot'); disp(' by a factor of 360 degrees. So though the graphs don''t look'); disp(' the same, they are equivalent'); disp(' '); disp('Location(s) of zero(s):'); disp(z); disp('*************************************'); disp(' '); beep; waitfor(warndlg('System has zeros with positive real part. See Command Window for caveats.')); end %Check for terms near imaginary axis, or multiple poles or zeros at origin. for i=2:length(term), if (term(i).value~=0), if (abs(real(term(i).value)/term(i).value)<Acc), disp(' '); disp(' '); disp(' '); disp('************Warning******************'); handles.Sys disp('has a pole or zero near, or on, the imaginary axis.'); disp('The plots may be inaccurate near that frequency.') disp(' '); disp('--------'); disp('Pole(s):'); disp(p) disp('--------'); disp('Zero(s):'); disp(z); disp('*************************************'); disp(' '); disp(' '); disp(' '); beep; waitfor(warndlg('System has poles or zeros with real part near zero. See Command Window.')); end elseif (term(i).multiplicity>1), disp(' '); disp(' '); disp(' '); disp('************Warning******************'); handles.Sys disp('has multiple poles or zeros at the origin.'); disp('Components of the phase plot may appear to disagree.'); disp('This is because the phase of a complex number is'); disp('not unique; the phase of -1 could be +180 degrees'); disp('or -180 or +/-540... Likewise the phase of 1/s^2'); disp('could be +180 degrees, or -180 degrees (or +/-540'); disp('Keep this in mind when looking at the phase plots.'); disp('*************************************'); disp(' '); beep; waitfor(warndlg('System has multiple poles or zeros at origin. See Command Window.')); end end handles.Terms=term; guidata(handles.AsymBodePlot, handles); %save changes to handles. end % ------------------End of function BodePlotTerms -------------------- % -------------------------------------------------------------------- function BodePlotter(handles) %Get the constituent terms and the system itself. Terms=handles.Terms; sys=handles.Sys; %Call function to get a system with only included poles and zeros. BodePlotSys(handles); handles=guidata(handles.AsymBodePlot); %Reload handles after function call. %Get systems with included poles and zeros. sysInc=handles.SysInc; %Find min and max freq. MinF=realmax; MaxF=-realmax; for i=2:length(Terms), if Terms(i).value~=0, MinF=min(MinF,abs(Terms(i).value)); MaxF=max(MaxF,abs(Terms(i).value)); end end %If there is exclusively a pole or zero at origin, MinF and MaxF will % not have changed. So set them arbitrarily to be near unity. if MaxF==-realmax, MinF=0.9; MaxF=1.1; end %MinFreq is a bit more than an order of magnitude below lowest break. MinFreq=10^(floor(log10(MinF)-1.01)); %MaxFreq is a bit more than an order of magnitude above highest break. MaxFreq=10^(ceil(log10(MaxF)+1.01)); %Calculate 500 frequency points for plotting. w=logspace(log10(MinFreq),log10(MaxFreq),1000); %%%%%%%%%%%%%%%%%%%% Start Magnitude Plot %%%%%%%%%% axes(handles.MagPlot); cla; %Plot line at 0 dB for reference. semilogx([MinFreq MaxFreq],[0 0],... 'Color',handles.zrefColor,... 'LineWidth',1.5); hold on; %For each term, plot the magnitude accordingly. %The variable mag_a has the combined asymptotic magnitude. mag_a=zeros(size(w)); %The variable peakinds holds the indices at which peaks in underdamped %responses occur. peakinds=[]; for i=1:length(Terms), if Terms(i).display, switch Terms(i).type, case 'Constant', %A constant term is unchanging from beginning to end. f=[MinFreq MaxFreq]; m=20*log10(abs([Terms(i).value Terms(i).value])); semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. case 'RealPole', %A real pole has a single break frequency and then %decreases at 20 dB per decade (Or more if pole is multiple). wo=-Terms(i).value; f=[MinFreq wo MaxFreq]; m=-20*log10([1 1 MaxFreq/wo])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. case 'RealZero', %Similar to real pole, but increases instead of decreasing. wo=abs(Terms(i).value); f=[MinFreq wo MaxFreq]; m=20*log10([1 1 MaxFreq/wo])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. case 'ComplexPole', %A complex pole has a single break frequency and then %decreases at 40 dB per decade (Or more if pole is multiple). %There is also a peak value whose height and location are %determined by the natural frequency and damping coefficient. %We will plot a circle ('o') at the location of the peak. wn=abs(Terms(i).value); theta=atan(abs(imag(Terms(i).value)/real(Terms(i).value))); zeta=cos(theta); if (zeta < 0.5), %Show peaking if zeta<0.5 peak=2*zeta; f=[MinFreq wn wn wn MaxFreq]; m=-20*log10([1 1 peak 1 (MaxFreq/wn)^2])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); semilogx(wn,-20*log10(peak),'o','Color',GetLineColor(i,handles)); % Set up for interpolation (w/o peak) f=[MinFreq wn MaxFreq]; m=-20*log10([1 1 (MaxFreq/wn)^2])*Terms(i).multiplicity; mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. %Find location closest to peak, and adjust its amplitude. index=find(w>=wn,1,'first'); mag_a(index)=mag_a(index)-20*log10(peak); peakinds=[peakinds index]; %Save this index. else f=[MinFreq wn MaxFreq]; m=-20*log10([1 1 (MaxFreq/wn)^2])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); % Set up for interpolation (w/o peak) mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. end case 'ComplexZero', %Similar to complex pole, but increases instead of decreasing. wn=abs(Terms(i).value); theta=atan(abs(imag(Terms(i).value)/real(Terms(i).value))); zeta=cos(theta); if (zeta < 0.5), %Show peaking if zeta<0.5 peak=2*zeta; f=[MinFreq wn wn wn MaxFreq]; m=20*log10([1 1 peak 1 (MaxFreq/wn)^2])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); semilogx(wn,20*log10(peak),'o','Color',GetLineColor(i,handles)); % Set up for interpolation (w/o peak) f=[MinFreq wn MaxFreq]; m=20*log10([1 1 (MaxFreq/wn)^2])*Terms(i).multiplicity; mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. %Find location closest to peak, and adjust its amplitude. index=find(w>=wn,1,'first'); mag_a(index)=mag_a(index)+20*log10(peak); peakinds=[peakinds index]; %Save this index. else f=[MinFreq wn MaxFreq]; m=20*log10([1 1 (MaxFreq/wn)^2])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); % Set up for interpolation (w/o peak) mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. end case 'OriginPole', %A pole at the origin is a monotonically decreasing straigh line. f=[MinFreq MaxFreq]; m=-20*log10([MinFreq MaxFreq])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. case 'OriginZero', %Similar to pole at origin, but increases instead of decreasing. f=[MinFreq MaxFreq]; m=20*log10([MinFreq MaxFreq])*Terms(i).multiplicity; semilogx(f,m,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); mag_a=mag_a+interp1(log(f),m,log(w)); %Build up asymptotic approx. end end end %Set the x-axis limits to the minimum and maximum frequency. set(gca,'XLim',[MinFreq MaxFreq]); [mg,ph,w]=bode(sysInc,w); %Calculate the exact bode plot. semilogx(w,20*log10(mg(:)),... 'Color',handles.exactColor,... 'LineWidth',handles.LnWdth/2); %Plot it. if (get(handles.ShowAsymptoticCheckBox,'Value')~=0), semilogx(w,mag_a,... 'Color',handles.exactColor,... 'LineStyle',':',... 'LineWidth',handles.LnWdth); %Plot asymptotic approx. semilogx(w(peakinds),mag_a(peakinds),'o','Color',handles.exactColor); end if handles.FirstPlot, %If this is the first time, let Matlab do autoscaling, but save %the y-axis limits so that they will be unchanged as the plot changes. ylims=get(gca,'YLim')/20; ylims(1)=min(-20,ceil(ylims(1))*20); ylims(2)=max(20,floor(ylims(2))*20); handles.MagLims=ylims; else %If this is not the first time, retrieve the old y-axis limits. ylims=handles.MagLims; end set(gca,'YLim',ylims); set(gca,'YTick',ylims(1):20:ylims(2)); %Make ticks every 20 dB. ylabel('Magnitude - dB'); xlabel('Frequency - \omega, rad-sec^{-1}') title('Magnitude Plot','color','b','FontWeight','bold'); if get(handles.GridCheckBox,'Value')==1, grid on end hold off; %%%%%%%%%%%%%%%%%%%% End Magnitude Plot %%%%%%%%%% %%%%%%%%%%%%%%%%%%%% Start Phase Plot %%%%%%%%%% %Much of this section mirrors the previous section and is not commented. %One difference is that phase is calculated explicitly, rather than use %Matlab's "bode" command. Since phase is not unique (you can add or %subtract multiples of 360 degrees) There were sometimes discrepancies %between Matlab's phase calculations and mine axes(handles.PhasePlot); cla; %Plot line at 0 degrees for reference. semilogx([MinFreq MaxFreq],[0 0],... 'Color',handles.zrefColor,... 'LineWidth',1.5); hold on; %The variable phs_a has the combined asymptotic phase. phs_a=zeros(size(w)); for i=1:length(Terms), if Terms(i).display, switch Terms(i).type, case 'Constant', f=[MinFreq MaxFreq]; if Terms(i).value>0, p=[0 0]; else p=[180 180]; end if get(handles.RadianCheckBox,'Value')==1, p=p/180; end semilogx(f,p,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); case 'RealPole', wo=-Terms(i).value; f=[MinFreq wo/10 wo*10 MaxFreq]; p=[0 0 -90 -90]*Terms(i).multiplicity; if get(handles.RadianCheckBox,'Value')==1, p=p/180; end semilogx(f,p,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); case 'RealZero', if Terms(i).value>0, %Non-minimum phase wo=Terms(i).value; %Uncomment the next section to get agreement with Matlab plots. %if Terms(1).value>0, %Choose 0 or 360 to agree with MatLab plots % p=[0 0 0 0]; % (based on sign of constant term). % else % p=[360 360 360 360]; %end p=[0 0 -90 -90]*Terms(i).multiplicity; else %Minimum phase wo=-Terms(i).value; p=[0 0 90 90]*Terms(i).multiplicity; end f=[MinFreq wo/10 wo*10 MaxFreq]; if get(handles.RadianCheckBox,'Value')==1, p=p/180; end semilogx(f,p,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); case 'ComplexPole', wo=abs(Terms(i).value); bf=0.2^zeta; f=[MinFreq wo*bf wo/bf MaxFreq]; p=[0 0 -180 -180]*Terms(i).multiplicity; if get(handles.RadianCheckBox,'Value')==1, p=p/180; end semilogx(f,p,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); case 'ComplexZero', wo=abs(Terms(i).value); bf=0.2^zeta; f=[MinFreq wo*bf wo/bf MaxFreq]; if real(Terms(i).value)>0, %Non-minimum phase p=[0 0 -180 -180]*Terms(i).multiplicity; else p=[0 0 180 180]*Terms(i).multiplicity; end if get(handles.RadianCheckBox,'Value')==1, p=p/180; end semilogx(f,p,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); case 'OriginPole', f=[MinFreq MaxFreq]; p=[-90 -90]*Terms(i).multiplicity; if get(handles.RadianCheckBox,'Value')==1, p=p/180; end semilogx(f,p,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); case 'OriginZero', f=[MinFreq MaxFreq]; p=[90 90]*Terms(i).multiplicity; if get(handles.RadianCheckBox,'Value')==1, p=p/180; end semilogx(f,p,... 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); end phs_a=phs_a+interp1(log(f),p,log(w)); %Build up asymptotic approx. end end if get(handles.RadianCheckBox,'Value')==1, ph=ph/180; end semilogx(w,ph(:),... 'Color',handles.exactColor,... 'LineWidth',handles.LnWdth/2); %Plot it. if (get(handles.ShowAsymptoticCheckBox,'Value')~=0), % There can be discrepancies between Matlabs calculation of phase and % the quantity "phs_a." This is because phase is not unique (you can % add or subtract multiples of 360 degrees). The next line shifts the % value of phs_a so that phs_a(1)=ph(1). Ensuring they are the same % at the beginning of the plot ensures that they align elsewhere. Note % that if the plots are already aligned (ph(1)=phs_a(1)), that the next % line does nothing. phs_a=phs_a+(ph(1)-phs_a(1)); semilogx(w,phs_a,... 'Color',handles.exactColor,... 'LineStyle',':',... 'LineWidth',handles.LnWdth); %Plot asymptotic approx. end set(gca,'XLim',[MinFreq MaxFreq]); if handles.FirstPlot, ylims=get(gca,'YLim')/45; ylims(1)=ceil(ylims(1)-1)*45; ylims(2)=floor(ylims(2)+1)*45; handles.DPhaseLims=ylims; %Find phase limits in degrees handles.RPhaseLims=ylims/180; %Find phase limits in radians/pi else if get(handles.RadianCheckBox,'Value')==1, ylims=handles.RPhaseLims; else ylims=handles.DPhaseLims; end end if get(handles.RadianCheckBox,'Value')==1, set(gca,'YLim',ylims); set(gca,'YTick',ylims(1):0.25:ylims(2)) ylabel('Phase - radians/\pi'); else set(gca,'YLim',ylims); set(gca,'YTick',ylims(1):45:ylims(2)) ylabel('Phase - degrees'); end xlabel('Frequency - \omega, rad-sec^{-1}'); title('Phase Plot','color','b','FontWeight','bold'); if get(handles.GridCheckBox,'Value')==1, grid on end hold off; %%%%%%%%%%%%%%%%%%%% End Phase Plot %%%%%%%%%% BodePlotDispTF(handles); %Display the transfer function BodePlotLegend(handles); %Display the legend. handles=guidata(handles.AsymBodePlot); %Reload handles after function call. %Set first plot to zero (so Matlab won't autoscale on subsequent calls). handles.FirstPlot=0; guidata(handles.AsymBodePlot, handles); %save changes to handles. end % ----------------- End of function BodePlotter ---------------------- % -------------------------------------------------------------------- function BodePlotSys(handles) %This function makes up a transfer function of all the terms that are not in %the "Excluded Elements" box in the GUI. Terms=handles.Terms; %Get all terms from original transfer function. p=[]; %Start with no poles, or zeros, and a constant of 1 z=[]; k=1; for i=1:length(Terms), %For each term. %If the term is not in "Excluded Elements". then we want to display it. if Terms(i).display, switch Terms(i).type, case 'Constant', k=Terms(i).value; %This is the constant. case 'RealPole', for j=1:Terms(i).multiplicity, p=[p Terms(i).value]; %Add poles. end case 'RealZero', for j=1:Terms(i).multiplicity, z=[z Terms(i).value]; %Add zeros. end case 'ComplexPole', for j=1:Terms(i).multiplicity, p=[p Terms(i).value]; %Add poles. p=[p conj(Terms(i).value)]; end case 'ComplexZero', for j=1:Terms(i).multiplicity, z=[z Terms(i).value]; %Add zeros. z=[z conj(Terms(i).value)]; end case 'OriginPole', for j=1:Terms(i).multiplicity, p=[p 0]; %Add poles. end case 'OriginZero', for j=1:Terms(i).multiplicity, z=[z 0]; %Add zeros. end end end end %Determine multiplicative constant in standard Bode Plot form. for i=1:length(p), if p(i)~=0 k=-k*p(i); end end for i=1:length(z), if z(i)~=0 k=-k/z(i); end end %If poles and/or zeros were complex conjugate pairs, there may be %some residual imaginary part due to finite precision. Remove it. k=real(k); handles.SysInc=zpk(z,p,k); guidata(handles.AsymBodePlot, handles); %save changes to handles. end % ------------------End of function BodePlotSys ---------------------- % -------------------------------------------------------------------- function BodePlotDispTF(handles) % This function displays a tranfer function that is a helper function for the % BodePlotGui routine. It takes the transfer function of the numerator and % splits it into three lines so that it can be displayed nicely. For example: % " s + 1" % "H(s) = ---------------" % " s^2 + 2 s + 1" % % The numerator string is in the variable nStr, % the second line is in divStr, % and the denominator string is in dStr. % Get numerator and denominator. [n,d]=tfdata(handles.SysInc,'v'); % Get string representations of numerator and denominator nStr=poly2str(n,'s'); dStr=poly2str(d,'s'); % Find length of strings. LnStr=length(nStr); LdStr=length(dStr); if LnStr>LdStr, %the numerator is longer than denominator string, so pad denominator. n=LnStr; %n is the length of the longer string. nStr=[' ' nStr]; %add spaces for characters at beginning of divStr. dStr=[' ' blanks(floor((LnStr-LdStr)/2)) dStr]; %pad denominator. else %the demoninator is longer than numerator, pad numerator. n=LdStr; nStr=[' ' blanks(floor((LdStr-LnStr)/2)) nStr]; dStr=[' ' dStr]; end divStr=[]; for i=1:n, divStr=[divStr '-']; end divStr=['H(s) = ' divStr]; set(handles.TransferFunctionText,'String',strvcat(nStr,divStr,dStr)); %Change type font and size. set(handles.TransferFunctionText,'FontName','Courier New') %set(handles.TransferFunctionText,'FontSize',10) guidata(handles.AsymBodePlot, handles); %save changes to handles. end % ------------------End of function BodePlotDispTF ------------------- % -------------------------------------------------------------------- function BodePlotLegend(handles) %This function creates the legends for the Bode plot being displayed. %It also makes four changes to the "handles" structure. % 1) It updates the array "IncElem" that holds the indices that determine % which elements are included in the Bode plot. % 2) It updates the sring array "IncStr" that hold the description of % each included elements. % 3) Updates ExcElem that holds indices of excluded elements. % 4) Updates ExcStr that hold descriptions of excluded elements. %Load the terms and the plotting strings into local variables for convenience. Terms=handles.Terms; axes(handles.LegendPlot); %Set axes to the legend widow, cla; % and clear it. Xleg=[0 0.1]; %Xleg holds start and end of line segment for legend. XlegText=0.125; %XlegText is location of text. FntSz=8; %Font Size of text. y=1-1/(length(Terms)+6); %Vertical location of first text item plot(Xleg,[y y],... 'Color',handles.exactColor,... 'LineWidth',handles.LnWdth/2); %Plot line for legend. text(XlegText,y,'Exact Bode Plot','FontSize',FntSz); %Place text hold on; if (get(handles.ShowAsymptoticCheckBox,'Value')~=0), y=1-2/(length(Terms)+6); %Vertical location of second item plot(Xleg,[y y],... 'Color',handles.exactColor,... 'LineStyle',':',... 'LineWidth',handles.LnWdth); %Plot line for legend. text(XlegText,y,'Asymptotic Plot','FontSize',FntSz); %Place text end y=1-3/(length(Terms)+6); %Vertical location of third item. plot(Xleg,[y y],... %Line. 'Color',handles.zrefColor,... 'LineWidth',2); text(XlegText,y,'Zero Value (for reference only)','FontSize',FntSz); %Text. IncElem=[]; %The indices of elements to be included in plot. ExcElem=[]; %The indices of elements to be excluded from plot. IncStr=''; %An array of strings describing included elements. ExcStr=''; %An array of strings describing excluded elements. %These variables are used as local counters later. Here they are initialized. i1=1; i2=1; for i=1:length(Terms), %For each term, %Tv is a local variable representing the pole location. It is used solely % for convenience. Tv=Terms(i).value; %Tm is a local variable representing the pole multiplicity. It is used solely % for convenience. Tm=Terms(i).multiplicity; %S2 is a blank string to be added to later in the loop. S2=''; %The next section of code ("switch" statement) plus a few lines, creates %a string that describes the pole or zero, its location, muliplicity... %The variable "DescStr" hold a Descriptive String for the pole or zero. The %string "S2" is a Second String that holds additional information (if needed) switch Terms(i).type, case 'Constant', %If the term is a consant, print its value in a string. DescStr=sprintf('Constant = %0.2g (%0.2g dB)',Tv,20*log10(abs(Tv))); if Tv>=0, DescStr=[DescStr ' phi=0']; else DescStr=[DescStr ' phi=180 (pi/2)']; end; case 'RealPole', %If the term is a real pole, print its value in string. DescStr=sprintf('Real Pole at %0.2g',Tv); case 'RealZero', %If the term is a real zero, print its value in string. DescStr=sprintf('Real Zero at %0.2g',Tv); if real(Tv)>0, DescStr=[DescStr ' RHP (Non-min phase)']; end; case 'ComplexPole', %If the term is a complex pole, print its value in string. %However, do this in terms of natural frequency and damping, as %well as the actual location of the pole (in S2). wn=abs(Tv); theta=atan(abs(imag(Tv)/real(Tv))); zeta=cos(theta); DescStr=sprintf('Complex Pole at wn=%0.2g, zeta=%0.2g',wn,zeta); if (zeta < 0.5), %peaking only if zeta<0.5 S2=sprintf('(%0.2g +/- %0.2gj) Circle shows peak height.',real(Tv),imag(Tv)); else S2=sprintf('(%0.2g +/- %0.2gj) (no peaking shown, zeta>0.5)',real(Tv),imag(Tv)); end case 'ComplexZero', %If the term is a complex zero, print its value in string. %However, do this in terms of natural frequency and damping, as %well as the actual location of the zero (in S2). %Also note if it is a non-minimum phase zero. wn=abs(Tv); theta=atan(abs(imag(Tv)/real(Tv))); zeta=cos(theta); DescStr=sprintf('Complex Zero at wn=%0.2g, zeta=%0.2g',wn,zeta); if real(Tv)>0, DescStr=[DescStr ' (RHP, Non-min phase)']; end; if (zeta < 0.5), %peaking only if zeta<0.5 S2=sprintf('(%0.2g +/- %0.2gj) Circle shows peak height.',real(Tv),imag(Tv)); else S2=sprintf('(%0.2g +/- %0.2gj) (no peaking shown, zeta>0.5)',real(Tv),imag(Tv)); end case 'OriginPole', %If pole is at origin, not this. DescStr=sprintf('Pole at origin'); case 'OriginZero', %If zero is at origin, not this. DescStr=sprintf('Zero at origin'); end %If multiplicity is greater than one, not this as well. if Tm>1, DescStr=[DescStr sprintf(', mult=%d',Tm)]; end %At this point we have a string (in "DescStr" and "S2"). if Terms(i).display, %If the term is to be included in plot.... IncStr=strvcat(IncStr,DescStr); %Add the Desriptive String to IncStr IncElem(i1)=i; %Add the appropriate index to the Included Elements list. i1=i1+1; %Increment the index counter y=1-(i1+2)/(length(Terms)+6); %Calculate the vertical position. plot(Xleg,[y y],... %Plot the line. 'LineWidth',handles.LnWdth,... 'LineStyle',GetLineStyle(i,handles),... 'Color',GetLineColor(i,handles)); text(XlegText,y,strvcat(DescStr,S2),'FontSize',FntSz); %Add the text. else %The term is *not* to be included in plot, so... ExcStr=strvcat(ExcStr,DescStr); %Add its Desriptive String to ExcStr ExcElem(i2)=i; %Add the appropriate index to the Excluded Elements list. i2=i2+1; %Increment the index counter. end end hold off; %Get rid of ticks around plot. axis([0 1 0 1]); set(gca,'Xtick',[]); set(gca,'Ytick',[]); %At this point the legend is completed. Next we will make up the strings %for the boxes that separately list included and excluded elements. IncStr=strvcat(IncStr,' '); %Add a blank line to IncStr. IncStr=strvcat(IncStr,'-------'); %Add a series of dashes. %If there are any included elements, we can click on box to exclude it. if i1~=1 IncStr=strvcat(IncStr,'Select element to exclude from plot'); end ExcStr=strvcat(ExcStr,' '); %Add a blank line to ExcStr ExcStr=strvcat(ExcStr,'-------'); %Add a series of dashes. %If there are any excluded elements, we can click on box to include it. if i2~=1 ExcStr=strvcat(ExcStr,'Select element to include in plot'); end %Set the strings for included and excluded elements. set(handles.IncludedElements,'String',IncStr); set(handles.ExcludedElements,'String',ExcStr); %Change the arrays holding included and excluded elements in the handles array. handles.IncElem=IncElem; handles.ExcElem=ExcElem; guidata(handles.AsymBodePlot, handles); %save changes to handles. end % ------------------End of function BodePlotLegend -------- % -------------------------------------------------------------------- % --- Executes during object creation, after setting all properties. function LineWidth_CreateFcn(hObject, ~, ~) % hObject handle to LineWidth (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end end % ------------------End of function BodePlotLegend -------- % -------------------------------------------------------------------- % Set the width of the lines used in plots. function LineWidth_Callback(~, ~, handles) % hObject handle to LineWidth (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.LnWdth=str2num(get(handles.LineWidth,'String')); guidata(handles.AsymBodePlot, handles); %save changes to handles. BodePlotter(handles); %Plot the Transfer function. handles=guidata(handles.AsymBodePlot); %Reload handles after function call. end % ------------------End of function BodePlotLegend -------- % -------------------------------------------------------------------- % Determines the line color of the ith plot. function linecolor=GetLineColor(i,handles) numColors=size(handles.colors,1); %Cycle through colors by using mod operator. linecolor=handles.colors(mod(i-1,numColors)+1,:); end % ------------------End of function GetLineColor -------- % -------------------------------------------------------------------- % Determines the line style of the ith plot. function linestyle=GetLineStyle(i,handles) numColors=size(handles.colors,1); numLnStl=size(handles.linestyle,2); %Cycle through line styles, incrementing after all colors are used. linestyle=handles.linestyle{mod(ceil(i/numColors)-1,numLnStl)+1}; end % ------------------End of function GetLineStyle -------- % -------------------------------------------------------------------- % --- Executes on button press in GrayCheckBox. % This function sets the sequence of colors used in plotting to gray scales. function GrayCheckBox_Callback(~, ~, handles) if get(handles.GrayCheckBox,'Value')==1, %If button is not set, handles.colors=handles.Gray; %and set colors to gray scale handles.zrefColor=handles.GrayZero; else handles.colors=handles.Color; %and set colors to RGB handles.zrefColor=handles.ColorZero; end guidata(handles.AsymBodePlot, handles); %save changes to handles. BodePlotter(handles); %Plot the Transfer function. handles=guidata(handles.AsymBodePlot); %Reload handles after function call. end % ------------------End of function BodePlotLegend -------- % --- Executes on button press in GridCheckBox. function GridCheckBox_Callback(~, ~, handles) BodePlotter(handles); %Plot the Transfer function. end % --- Executes on button press in RadianCheckBox. function RadianCheckBox_Callback(~, ~, handles) BodePlotter(handles); %Plot the Transfer function. end % --- Executes on button press in WebButton. function WebButton_Callback(~, ~, ~) web('http://lpsa.swarthmore.edu/Bode/Bode.html','-browser') end % --- Executes on button press in ShowAsymptoticCheckBox. function ShowAsymptoticCheckBox_Callback(~, ~, handles) BodePlotter(handles); %Plot the Transfer function. end % --- Executes on button press in limitButton. function limitButton_Callback(~, ~, ~) s{1}='Restrictions on systems:'; s{2}=' 1) SISO (Single Input Single Output);'; s{3}=' 2) Proper systems (order of num <= order of den);'; s{4}=' 4) System must be a transfer function (i.e., not state space...)'; s{5}=' 5) Time delays are ignored.'; helpdlg(s,'Valid Systems'); end % --- Executes on selection change in popupSystems. function popupSystems_Callback(hObject, ~, handles) i=get(hObject,'Value'); if i ~= 1, %If this is not the "User Systems" choice if i==2, %This is the refresh choice loadSystems(handles); handles=guidata(handles.AsymBodePlot); %Reload handles after function call. else %THis is a valid choice, pick transfer function. initBodePlotGui(handles); handles=guidata(handles.AsymBodePlot); %Reload handles after function call. handles.Sys=handles.WorkSpaceTFs{i}; doBodeGUI(handles); handles=guidata(handles.AsymBodePlot); %Reload handles after function call. end end guidata(hObject, handles); end % --- Executes during object creation, after setting all properties. function popupSystems_CreateFcn(hObject, ~, ~) % hObject handle to popupSystems (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end function loadSystems(handles) [v_name, v_tf]=getBaseTFs; set(handles.popupSystems,'String',v_name); handles.WorkSpaceTFs=v_tf; guidata(handles.AsymBodePlot, handles); %save changes to handles. end function [varName, varTF]=getBaseTFs % Find all valid transfer functions in workspace s=evalin('base','whos(''*'')'); tfs=strvcat(s.class); %x=class of all variable tfs=strcmp(cellstr(tfs),'tf'); %Convert to cell array and find tf's s=s(tfs); %Get just tf's vname=strvcat(s.name); varName{1}='User Systems'; varTF{1}=[]; varName{2}='Refresh Systems'; varTF{2}=[]; j=2; for i=1:length(s) myTF=evalin('base',vname(i,:)); if (size(myTF.num)==[1 1]), %Check for siso j=j+1; varName{j}=vname(i,:); varTF{j}=myTF; end end end
github
mainster/matlabCodes-master
CustomMDBdistribution.m
.m
matlabCodes-master/CustomMDBdistribution.m
14,354
utf_8
e0b9947e4c6d31e4383fdd19d958129b
classdef CustomMDBdistribution < prob.ToolboxFittableParametricDistribution % This is a sample implementation of the Laplace distribution. You can use % this template as a model to implement your own distribution. Create a % directory called '+prob' somewhere on your path, and save this file in % that directory using a name that matches your distribution name. % % An object of the LaplaceDistribution class represents a Laplace % probability distribution with a specific location parameter MU and % scale parameter SIGMA. This distribution object can be created directly % using the MAKEDIST function or fit to data using the FITDIST function. % % LaplaceDistribution methods: % cdf - Cumulative distribution function % fit - Fit distribution to data % icdf - Inverse cumulative distribution function % iqr - Interquartile range % mean - Mean % median - Median % paramci - Confidence intervals for parameters % pdf - Probability density function % proflik - Profile likelihood function % random - Random number generation % std - Standard deviation % truncate - Truncation distribution to an interval % var - Variance % % LaplaceDistribution properties: % DistributionName - Name of the distribution % mu - Value of the mu parameter % sigma - Value of the sigma parameter % NumParameters - Number of parameters % ParameterNames - Names of parameters % ParameterDescription - Descriptions of parameters % ParameterValues - Vector of values of parameters % Truncation - Two-element vector indicating truncation limits % IsTruncated - Boolean flag indicating if distribution is truncated % ParameterCovariance - Covariance matrix of estimated parameters % ParameterIsFixed - Two-element boolean vector indicating fixed parameters % InputData - Structure containing data used to fit the distribution % NegativeLogLikelihood - Value of negative log likelihood function % % See also fitdist, makedist. % All ProbabilityDistribution objects must specify a DistributionName properties(Constant) %DistributionName Name of distribution % DistributionName is the name of this distribution. DistributionName = 'laplace'; end % Optionally add your own properties here. For this distribution it's convenient % to be able to refer to the mu and sigma parameters by name, and have them % connected to the proper element of the ParameterValues property. These are % dependent properties because they depend on ParameterValues. properties(Dependent=true) %MU Location parameter % MU is the location parameter for this distribution. mu %SIGMA Scale parameter % SIGMA is the scale parameter for this distribution. sigma end % All ParametricDistribution objects must specify values for the following % constant properties (they are the same for all instances of this class). properties(Constant) %NumParameters Number of parameters % NumParameters is the number of parameters in this distribution. NumParameters = 2; %ParameterName Name of parameter % ParameterName is a two-element cell array containing names % of the parameters of this distribution. ParameterNames = {'mu' 'sigma'}; %ParameterDescription Description of parameter % ParameterDescription is a two-element cell array containing % descriptions of the parameters of this distribution. ParameterDescription = {'location' 'scale'}; end % All ParametricDistribution objects must include a ParameterValues property % whose value is a vector of the parameter values, in the same order as % given in the ParameterNames property above. properties(GetAccess='public',SetAccess='protected') %ParameterValues Values of the distribution parameters % ParameterValues is a two-element vector containing the mu and sigma % values of this distribution. ParameterValues end methods % The constructor for this class can be called with a set of parameter % values or it can supply default values. These values should be % checked to make sure they are valid. They should be stored in the % ParameterValues property. function pd = LaplaceDistribution(mu,sigma) if nargin==0 mu = 0; sigma = 1; end checkargs(mu,sigma); pd.ParameterValues = [mu sigma]; % All FittableParametricDistribution objects must assign values % to the following two properties. When an object is created by % the constructor, all parameters are fixed and the covariance % matrix is entirely zero. pd.ParameterIsFixed = [true true]; pd.ParameterCovariance = zeros(pd.NumParameters); end % Implement methods to compute the mean, variance, and standard % deviation. function m = mean(this) m = this.mu; end function s = std(this) s = sqrt(2)*this.sigma; end function v = var(this) v = 2*this.sigma^2; end end methods % If this class defines dependent properties to represent parameter % values, their get and set methods must be defined. The set method % should mark the distribution as no longer fitted, because any % old results such as the covariance matrix are not valid when the % parameters are changed from their estimated values. function this = set.mu(this,mu) checkargs(mu,this.sigma); this.ParameterValues(1) = mu; this = invalidateFit(this); end function this = set.sigma(this,sigma) checkargs(this.mu,sigma); this.ParameterValues(2) = sigma; this = invalidateFit(this); end function mu = get.mu(this) mu = this.ParameterValues(1); end function sigma = get.sigma(this) sigma = this.ParameterValues(2); end end methods(Static) % All FittableDistribution classes must implement a fit method to fit % the distribution from data. This method is called by the FITDIST % function, and is not intended to be called directly function pd = fit(x,varargin) %FIT Fit from data % P = prob.LaplaceDistribution.fit(x) % P = prob.LaplaceDistribution.fit(x, NAME1,VAL1, NAME2,VAL2, ...) % with the following optional parameter name/value pairs: % % 'censoring' Boolean vector indicating censored x values % 'frequency' Vector indicating frequencies of corresponding % x values % 'options' Options structure for fitting, as create by % the STATSET function % Get the optional arguments. The fourth output would be the % options structure, but this function doesn't use that. [x,cens,freq] = prob.ToolboxFittableParametricDistribution.processFitArgs(x,varargin{:}); % This distribution was not written to support censoring or to process % a frequency vector. The following utility expands x by the frequency % vector, and displays an error message if there is censoring. x = prob.ToolboxFittableParametricDistribution.removeCensoring(x,cens,freq,'laplace'); freq = ones(size(x)); % Estimate the parameters from the data. If this is an iterative procedure, % use the values in the opt argument. m = median(x); s = mean(abs(x-m)); % Create the distribution by calling the constructor. pd = prob.LaplaceDistribution(m,s); % Fill in remaining properties defined above pd.ParameterIsFixed = [false false]; [nll,acov] = prob.CustomMDBdistribution.likefunc([m s],x); pd.ParameterCovariance = acov; % Assign properties required for the FittableDistribution class pd.NegativeLogLikelihood = nll; pd.InputData = struct('data',x,'cens',[],'freq',freq); end % The following static methods are required for the % ToolboxParametricDistribution class and are used by various % Statistics and Machine Learning Toolbox functions. These functions operate on % parameter values supplied as input arguments, not on the % parameter values stored in a CustomMDBdistribution object. For % example, the cdf method implemented in a parent class invokes the % cdffunc static method and provides it with the parameter values. function [nll,acov] = likefunc(params,x) % likelihood function n = length(x); mu = params(1); sigma = params(2); nll = -sum(log(prob.CustomMDBdistribution.pdffunc(x,mu,sigma))); acov = (sigma^2/n) * eye(2); end function y = cdffunc(x,mu,sigma) % cumulative distribution function if sigma==0 y = double(x>=mu); else z = (x-mu) ./ sigma; y = 0.5 + sign(z).*(1-exp(-abs(z)))/2; end y(isnan(x)) = NaN; end function y = pdffunc(x,mu,sigma) % probability density function y = exp(-abs(x - mu)/sigma) / (2*sigma); end function y = invfunc(p,mu,sigma) % inverse cdf if nargin<2, mu = 0; end if nargin<2, sigma = 1; end if sigma==0 y = mu + zeros(size(p)); else u = p-0.5; y = mu - sigma.*sign(u).*log(1-2*abs(u)); end y(p < 0 | 1 < p) = NaN; end function y = randfunc(mu,sigma,varargin) % random number generator y = prob.CustomMDBdistribution.invfunc(rand(varargin{:}),mu,sigma); end end methods(Static,Hidden) % All ToolboxDistributions must implement a getInfo static method % so that Statistics and Machine Learning Toolbox functions can get information about % the distribution. function info = getInfo % First get default info from parent class info = [email protected]('prob.CustomMDBdistribution'); % Then override fields as necessary info.name = 'MDBdistribution'; info.code = 'MDBdistribution'; % info.pnames is obtained from the ParameterNames property % info.pdescription is obtained from the ParameterDescription property % info.prequired = [false false] % Change if any parameter must % be specified before fitting. % An example would be the N % parameter of the binomial % distribution. % info.hasconfbounds = false % Set to true if the cdf and % icdf methods can return % lower and upper bounds as % their 2nd and 3rd outputs. % censoring = false % Set to true if the fit % method supports censoring. % info.support = [-Inf, Inf] % Set to other lower and upper % bounds if the distribution % doesn't cover the whole real % line. For example, for a % distribution on positive % values use [0, Inf]. % info.closedbound = [false false] % Set the Jth value to % true if the distribution % allows x to be equal to the % Jth element of the support % vector. % info.iscontinuous = true % Set to false if x can take % only integer values. info.islocscale = true; % Set to true if this is a % location/scale distribution % (no other parameters). % info.uselogpp = false % Set to true if a probability % plot should be drawn on the % log scale. % info.optimopts = false % Set to true if the fit % method can be called with an % options structure. info.logci = [false true]; % Set to true for a parameter % that should have its Wald % confidence interval computed % using a normal approximation % on the log scale. end end end % classdef % The following utilities check for valid parameter values function checkargs(mu,sigma) if ~(isscalar(mu) && isnumeric(mu) && isreal(mu) && isfinite(mu)) error('MU must be a real finite numeric scalar.') end if ~(isscalar(sigma) && isnumeric(sigma) && isreal(sigma) && sigma>=0 && isfinite(sigma)) error('SIGMA must be a positive finite numeric scalar.') end end
github
mainster/matlabCodes-master
LTspiceParamImport.m
.m
matlabCodes-master/LTspiceParamImport.m
9,811
utf_8
31cb370f57cc42db4b4d21a689e367bb
function varargout = LTspiceParamImport (ascfile, varargin) % LTSPICEPARAMIMPORT Scan and import parameters from LTspice *.asc files. % Place pattern ".param MATLAB_PARAM=1" at the beginning of '+ (...)' extended % parameter list as spice directive, for example: % % .param MATLAB_PARAM=1 % + Ve = 5V % + Rc = 1k % + R1 = 2u % + R2 = 2m % % LTSPICEPARAMIMPORT(ASCFILE) scan file 'ASCFILE' and evaluate params in % "base" workspace. % % LTSPICEPARAMIMPORT(___ 'strucnam', STRUCNAM) scan file 'ASCFILE' % and evaluate params in "base" workspace using 'STRUCNAM' as a structure % name prefix. % % STRUC_OUT = LTSPICEPARAMIMPORT(___ ['strucnam', STRUCNAM]) scan file % 'ASCFILE' and evaluate params in "base" workspace using 'STRUC_OUT' as a % structure name prefix, ignoring 'strucnam', STRUCNAM if given. % % [STRUC_OUT, STRUC_ORIG] = LTSPICEPARAMIMPORT(___) scan file % 'ASCFILE' and evaluate params in "base" workspace using 'STRUC_OUT' as a % structure name prefix, ignoring 'strucnam', STRUCNAM if given. Retrun % original spice param strings in STRUC_OUT % % LTSPICEPARAMIMPORT(___ 'evalin', EVALIN) ... and evaluate params in % workspace EVALIN using 'STRUCNAM' as a structure name prefix. % % EVALIN: 'base' Default, eval param set in base workspace. % 'none' Do not evaluate param set in base workspace. Return % structure containing the unevaluated param strings. % % ------------------------------------------------------------------------------ % Check function arguments by inputParser % ------------------------------------------------------------------------------ p = inputParser; vEvalin = { 'base','global','caller','local'}; valEvalin = @(x) ischar(x) && any(validatestring(x,vEvalin)); addRequired(p,'ascfile', @checkpath); addParameter(p,'strucnam', '', @ischar); addParameter(p,'evalin', 'base', valEvalin); parse(p, ascfile, varargin{:}); P = p.Results; P.argout = false; if nargout > 0 % If outarg is sourced AND param value pair 'strucnam' is not an empty % string, throw warning that 'strucnam' gets ignored if ~strcmpi(P.strucnam, '') warning(['nargout > 0\nThis means that param value pair "strucnam",',... ' %s is beeing ignored!\n', P.strucnam]); P.strucnam = ''; end P.argout = true; varargout{1}=[]; end % ------------------------------------------------------------------------------ % Read lines from input file fid = fopen(P.ascfile, 'r'); Cin = textscan(fid, '%s', 'Delimiter', '\n'); fclose(fid); % search pattern is MATLAB_PARAM=1 C1 = strfind(Cin{1}, 'MATLAB_PARAM=1'); % find index and create cell containing all lines that matches MATLAB... lines = ~cellfun('isempty', C1); cp=Cin{1}(lines); if isempty(cp) error('Keywords "MATLAB_PARAM=1" no where found!\n'); else % cast cp to datatype cell if only one param set found if ~iscell(cp) cp{1}=cp; disp('Single parameter set found...'); else disp('Cell array of parameter set found...'); cp end end % parse each param set into cell cpk={zeros(1,length(cp))}; for k=1:length(cp) cpk{k} = strsplit(cp{k},'\\n+')'; % remove first cell entry due its the search pattern cpk{k}(1,:)=[]; % cpk holds k subcells with n cellstrings like 'R1 = 1k' for n=1:length(cpk{k}) % remove all whitespaces cpk{k}{n} = cpk{k}{n}(cpk{k}{n} ~= ' '); try pset{k}{1, n} = strsplit(cpk{k}{n},'='); % psets.([f num2str(n)]) = strtrim( strsplit(cpk{k}{n},'=') ); % pset{k}{1, n-1} catch err disp (err.message) disp ([k, n]) end end end % Create delimiter cell array delims = repmat({'='},length(cpk{1}),1); tmp1 = cellfun(@strsplit, cpk{1}, delims,'UniformOutput',false); % malloc parn=cell(length(tmp1), 2*length(tmp1{k})+1 ); % cell ENUMS enpar.EQ = 2; % idx of equality '=' signs enpar.ORIG = 3; % idx of original param strings enpar.EE = 4; % idx of EE non-calc evaluations enpar.EECLC = 5; % idx of calc and non-calc evaluations enpar.COL = 6; % idx of semicolons for k=1:length(tmp1) try parn(k, [1 enpar.ORIG]) = tmp1{k}; catch erra disp(erra.message) end end % Parse different LTspice notations like % 'Ve=5V' 'Ve=5' 'Ve=5.' % 'I0 = 1mA' 'I0 = 1m' 'I0 = .001A' 'I0 = .001' % % Search rhs cell fields for physical extensions like 'V' (Volt) or 'A' % cpk{1} % % 'Ve = 5V' % 'Rc = 1k' % 'R2 = 4.7k' % 'Vbe0 = .65V' % 'Ic0 = 3.88mA' % % find indices of numeric char 0-9 or \. followed by patterns_A % % idx=regexp(cpk{1},'[0-9\.][VAva]') % extA = { 'fF' ,'pP' ,'nN' ,'uU' ,'mM' ,'kK','[mM]eg','gG','tT' }; % ext = {'[fF]','[pP]','[nN]','[uU]','[mM]','[kK]','[[mM]eg]','[gG]','[tT]'}; % EE = { 'e-15','e-12','e-9','e-6','e-3','e3','e6' ,'e9','e12' }; % Store index of faulty params here and remove them from the evaluation string % cell idxFaulty = []; %% EE ={'[fF]', 'e-15';... '[pP]','e-12';... '[nN]','e-09';... '[uU]','e-06';... '([mM]eg)','e06';... '[mM]','e-03';... '[kK]','e03';... '[gG]','e09';... '[tT]','e12';... '[vVaA]','' }; % remove physical V (Volt) and A (Ampere) extensions c = parn(:, enpar.ORIG); % find index of non-calc LTspice parameters, this means all members that are NOT % of type {...} try idxNonCalc = cellfun(@isempty,strfind(c,'{')); c(idxNonCalc) = regexprep( c(idxNonCalc), EE(:,1)', EE(:,2)'); parn(:, [enpar.EE, enpar.EECLC]) = [c, c]; catch err disp(err.message) end % Construct CALLER evaluation string. Evaluate non-calc params locally, eg. in % CALLER workspace. This is necessary because there might be some LTspice calc % params defined inside spice command ".param" For example: % .param MATLAB .... % + Ve = 5V % + Ve2 = {Ve/2} parn(:,[enpar.EQ, enpar.COL]) = [repmat({'='}, size(parn(:,2))),... repmat({'; '}, size(parn(:,2))) ]; % Eval non-calc params locally try eval( strjoin(parn( idxNonCalc, [1, enpar.EQ, enpar.EE, enpar.COL] )','')); catch err0 disp(err0.message) end % index of calc params iCalc = find(~idxNonCalc); parn{end-2,3}((parn{end-2,3}~='{')' & (parn{end-2,3}~='}')'); % Normaly, logical indexing should be preferred. In this case, the eval command % could only be processed if there are no calc-params which are function off % other calc-params. % Solve this problem by sequentially try to eval one calc param after the other % % Try to localy evaluate calc param eg. 'alpha = {beta/(beta+1)}' for KK=1:length(iCalc) try % parn{iCalc(KK), enpar.EECLC } = num2str(eval( parn{iCalc(KK),3}(2:end-1) )); % idxt2 = ((parn{iCalc(KK),enpar.EECLC}~='{')' & (parn{iCalc(KK),enpar.EECLC}~='}')'); parn{iCalc(KK), enpar.EECLC} = ... regexprep(parn{iCalc(KK), enpar.EECLC},'(\*\*)', '^'); parn{iCalc(KK), enpar.EECLC} = ... regexprep(parn{iCalc(KK), enpar.EECLC},'[{}]', ''); % { parn{ iCalc(KK),enpar.EECLC }(idxt2) }; eval( [strjoin(parn( iCalc(KK), [1, enpar.EQ, enpar.EECLC] )','') ';']); % evalin('base',strjoin(parn( iCalc(KK), [1, enpar.EQ, enpar.EECLC] )','')); parn{ iCalc(KK),enpar.EECLC } = ... num2str( eval([parn{ iCalc(KK),enpar.EECLC } ';']) ); catch err; disp(err.message) % If err message contains substring 'Undefined function or variable', % then display "Remove all..." error message string. if ~isempty(strfind(err.message,'Undefined function or variable')) % Find the "undefined" variable. [~, B] = strtok(err.message,'\'''); undef = B(B~='''' & B~='.'); % Add index to faulty param entrys index storage. idxFaulty = [idxFaulty iCalc(KK)]; end % Insert 'NaN' into faulty EECLC-row using index variable 'idxFaulty' parn{iCalc(KK), enpar.EECLC} = 'nan'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Base workspace evaluation | return struct generation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% evLogic = logical( strcmpi( P.evalin, {'base','global'} )); if evLogic(1) || evLogic(2) % this means evalin('base','...) if ~strcmpi( P.strucnam, '' ) pparn = [ repmat({[P.strucnam '.']}, size(parn(:,2))),... parn(:, [1, enpar.EQ, enpar.EECLC, enpar.COL]) ]; else pparn = parn(:, [1, enpar.EQ, enpar.EECLC, enpar.COL]); end if (P.argout == false) evalin('base', strjoin(pparn(1:end,:)','') ); else for k=1:length(pparn) outA.(pparn{k,1}) = str2double(pparn{k,3}); end end if nargout == 1 varargout{1} = outA; return; end if nargout == 2 for k=1:length(pparn) outB.(pparn{k,1}) = parn{k, enpar.ORIG}; end varargout{1} = outA; varargout{2} = outB; return; end else warning('Not implemented yet...\n') end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Callback functions for input parser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function TF = checkpath (x) TF = false; if ~ischar(x) error(['\n"ascfile" must be a string containing a relative or absolut',... 'path to a LTspice *.asc file']); end if exist(x,'file') == 0 error( '\nFile %s not found!', x ); else if exist(x,'file') ~= 2 error( '\nReturn value of exist( %s ,''file'') = %g ~= 2 \n',... x, exist(x,'file')); else TF = true; end end
github
mainster/matlabCodes-master
AudioDisplay.m
.m
matlabCodes-master/AudioDisplay.m
5,016
utf_8
e8de62c2d879c6dcbd6204046ee00ab2
function varargout = AudioDisplay(varargin) % AUDIODISPLAY M-file for AudioDisplay.fig % AUDIODISPLAY, by itself, creates a new AUDIODISPLAY or raises the existing % singleton*. % % H = AUDIODISPLAY returns the handle to a new AUDIODISPLAY or the handle to % the existing singleton*. % % AUDIODISPLAY('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in AUDIODISPLAY.M with the given input arguments. % % AUDIODISPLAY('Property','Value',...) creates a new AUDIODISPLAY or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before AudioDisplay_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to AudioDisplay_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 AudioDisplay % Last Modified by GUIDE v2.5 10-May-2010 17:37:29 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @AudioDisplay_OpeningFcn, ... 'gui_OutputFcn', @AudioDisplay_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 AudioDisplay is made visible. function AudioDisplay_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 AudioDisplay (see VARARGIN) % Choose default command line output for AudioDisplay handles.output = hObject; handles.r = hObject; backgroundImage = importdata('leaf.jpg'); axes(handles.axes2); image(backgroundImage) % Update handles structure guidata(hObject, handles); global flag; global FClose; flag = 1; % UIWAIT makes AudioDisplay wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = AudioDisplay_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) global flag; global FClose; handles.r = audiorecorder(8000,16,1); flag = 1; FClose = 1; StopExe = 0; buffSize = 100000; buffer1(1:buffSize,1) = 0; while(1) while(~flag); pause(0.1); if(~FClose) pause(0.01) close AudioDisplay; StopExe = 1; break; else break; end end if(flag) recordblocking(handles.r,0.1); buff = getaudiodata(handles.r,'int16'); [n m] = size(buff); % buff = buff(1:n-mod(n,64)); % a(:,1) = 1:3; % [n m] = size(a); % b(:,1) = buffSize:-1:1 % b(1 : n,1 ) = a(1 : n,1) % b(n + 1 : buffSize,1) = b(1 : buffSize - n,1) buffer1(1:n,1) = buff(1:n,1); buffer1(n + 1 : buffSize,1) = buffer1(1 : (buffSize) - n,1); axes(handles.axes1) plot(buffer1); guidata(hObject,handles); if(~FClose) pause(.1); close AudioDisplay; break; end end if(StopExe) break; end end % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global flag; flag = 0; % --- Executes on button press in pushbutton3. function pushbutton3_Callback(hObject, eventdata, handles) % hObject handle to pushbutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global FClose; FClose = 0;
github
mainster/matlabCodes-master
GalvoBIGMatlab_cortex_Link.m
.m
matlabCodes-master/RT_projects/GalvoProjekt/GalvoBIGMatlab_cortex_Link.m
8,877
utf_8
c230be7a86d7cc7b8fae1c6406a24707
function GalvoMatlab_cortex_Link uicontrol('Style', 'pushbutton', 'String', 'OpenPort',... 'Position', [20 20 70 30],... 'Callback', @MDBopenPort); %% uicontrol('Style', 'slider',... 'Min',1,'Max',50,'Value',41,... 'Position', [400 20 120 20],... 'Callback', {@surfzlim,hax}); % Uses cell array function handle callback % Implemented as a local function with an argument uicontrol('Style','text',... 'Position',[400 45 120 20],... 'String','Vertical Exaggeration') return function MDBopenPort() availableDevices = ls('/dev/ttyUSB*') USBport = availableDevices; USBport = '/dev/ttyUSB0'; obj=serial(USBport); obj.BaudRate=115200; % Termination character for data sequences obj.Terminator='CR'; % The byte order is important for interpreting binary data obj.ByteOrder='bigEndian'; % % The serial port object must be opened for communication try if strcmp(obj.Status,'closed'), fopen(obj); end catch err s = instrfind; delete(s); if strcmp(obj.Status,'closed'), fopen(obj); end end return function dummy () %% 1. Identify the serial port availableDevices = ls('/dev/ttyUSB*') USBport = availableDevices; USBport = '/dev/ttyUSB0'; obj=serial(USBport); obj.BaudRate=115200; % Termination character for data sequences obj.Terminator='CR'; % The byte order is important for interpreting binary data obj.ByteOrder='bigEndian'; % % The serial port object must be opened for communication try if strcmp(obj.Status,'closed'), fopen(obj); end catch err s = instrfind; delete(s); if strcmp(obj.Status,'closed'), fopen(obj); end end %% % Send a command. The terminator character set above will be appended. for k=1:25 str = input('$:','s'); fprintf(obj, [str '\r\n']); flushoutput(obj) flushoutput(obj) end %% fclose(obj); delete(obj); %% zo=instrfind; delete(zo) %% %% Read serial port objects from memory to MATLAB workspace % out = instrfind % out = instrfind('PropertyName',PropertyValue,...) % out = instrfind(S) % out = instrfind(obj,'PropertyName',PropertyValue,...) %% spz=instrfind %% % clear (serial) % Remove serial port object from MATLAB workspace % s = serial('COM1'); % scopy = s; % clear s % s = instrfind; % isequal(scopy,s) s = serial('/dev/ttyUSB1'); scopy = s; clear s s = instrfind isequal(scopy,s) %% obj.InputBufferSize=2^18; % in bytes % The serial port object must be opened for communication if strcmp(obj.Status,'closed'), fopen(obj); end response = fscanf(obj) prompt = {'Enter matrix size:','Enter colormap name:'}; dlg_title = 'Input'; num_lines = 1; def = {'20','hsv'}; % Send a command. The terminator character set above will be appended. for k=1:5 str = input('$:','s'); fprintf(obj, str); end % Read the response response = fscanf(obj); %% 2. Create the serial object % The serial port object represents the connection to the device. In the % MATLB documentation, this variable is typically called "obj". You will % read and write data from your USB device through the serial port object. % You will have to set the serial port settings according to your device % requirements. Some common settings are shown here. See the MATLAB % Documentation for all possibilities for your device. % % The baudrate is the data transmission rate in bytes per second % Most USB devices can support a baudrate of up to 1.5e6, but some % operating systems do not support "nonstandard" baudrates for serial ports. % "standard" baud rates include: % 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200, 128000, 230400, 460800, 921600 %% 3. Setup your device % Your USB device may require some setup through interface commands. To % send and receive commands, use fprintf(obj) and fscanf(obj). % obj=s1; obj.InputBufferSize=2^18; % in bytes % The serial port object must be opened for communication if strcmp(obj.Status,'closed'), fopen(obj); end response = fscanf(obj) prompt = {'Enter matrix size:','Enter colormap name:'}; dlg_title = 'Input'; num_lines = 1; def = {'20','hsv'}; % Send a command. The terminator character set above will be appended. for k=1:5 fprintf(obj,'!EnableBeam~~~~~~~~~~~~'); answer = inputdlg(prompt,dlg_title,num_lines,def); fprintf(obj,'!DisableBeam~~~~~~~~~~~'); answer = inputdlg(prompt,dlg_title,num_lines,def); end % Read the response response = fscanf(obj); %% 4. Prepare for the data stream % The data arriving from the USB device will be handled by a serial port % function which is called automatically when a certain number of bytes % have been received in the input buffer. Your serial port function will % remove the data from the buffer and process it. Adjust the buffer size % and the function byte count to suit your application. % The input buffer must be large enough to accomodate the amount of data % that will be received while your program is busy processing previously % received chunks of data. Having a buffer that is too large is not a % problem for most modern computers. % The "BytesAvailableFcn" function will be called whenever % BytesAvailableFcnCount number of bytes have been received from the USB % device. obj.BytesAvailableFcnMode='byte'; obj.BytesAvailableFcnCount=2^10; % 1 kB of data % The name of the BytesAvailableFcn function in this example is % "getNewData", and it has one additional input argument ("arg1"). obj.BytesAvailableFcn = {@getNewData,arg1}; % Use the serial port object to pass data between your main function % and the serial port function ("getNewData"). % You could include things like total number of data points read, % timestamps, etc, here as well. obj.UserData.newData=[]; obj.UserData.isNew=0; %% 5. Process the incoming data % In this example, we use a loop to plot the data stream that is sent by % the USB device. % A global variable is used to exit the loop global PLOTLOOP; PLOTLOOP=1; % Initialize data for plotting. "plotWindow" will be the length of the % x-axis in the data plot. plotData=zeros(plotWindow); newData=[]; % Create figure for plotting pfig = figure; % This allows us to stop the test by pressing a key set(pfig,'KeyPressFcn', @stopStream); % Send commands to the device to start the data stream. fprintf(obj,'START'); while PLOTLOOP % wait until we have new data if obj.UserData.isNew==1 % get the data from serial port object (data will be row-oriented) newData=mr.UserData.newData'; % indicate that data has been read mr.UserData.isNew=0; % concatenate new data for plotting plotData=[plotData(size(newData,1)+1:end,:); newData]; % plot the data plot(pfig,plotData); drawnow; end % The loop will exit when the user presses return, using the % KeyPressFcn of the plot window end %% 6. Finish & Cleanup % Add whatever commands are required for closing your device. % Send commands to the device stop the data transmission fprintf(obj,'STOP'); % flush the input buffer ba=get(obj,'BytesAvailable'); if ba > 0, fread(mr,ba); end % Close the serial port fclose(obj); delete(obj); return %% Data Processing Function function getNewData(obj,event,arg1) % GETNEWDATA processes data that arrives at the serial port. % GETNEWDATA is the "BytesAvailableFcn" for the serial port object, so it % is called automatically when BytesAvailableFcnCount bytes of data have % been received at the serial port. % Read the data from the port. % For binary data, use fread. You will have to supply the number of bytes % to read and the format for the data. See the MATLAB documentation. % For ASCII data, you might still use fread with format of 'char', so that % you do not have to handle the termination characters. [Dnew, Dcount, Dmsg]=fread(obj); % You can do some initial processing of the data here in this function. % However, I recommend keeping processing here to a minimum and doing % most of the work in the main loop for best performance. % Return the data to the main loop for plotting/processing if obj.UserData.isNew==0 % indicate that we have new data obj.UserData.isNew=1; obj.UserData.newData=Dnew; else % If the main loop has not had a chance to process the previous batch % of data, then append this new data to the previous "new" data obj.UserData.newData=[obj.UserData.newData Dnew]; end return %% Loop Control Function function [] = stopStream(src,evnt) % STOPSTREAM is a local function that stops the main loop by setting the % global variable to 0 when the user presses return. global PLOTLOOP; if strcmp(evnt.Key,'return') PLOTLOOP = 0; fprintf(1,'Return key pressed.'); end return % % % %
github
mainster/matlabCodes-master
GalvoMatlab_cortex_Link.m
.m
matlabCodes-master/RT_projects/GalvoProjekt/GalvoMatlab_cortex_Link.m
3,199
utf_8
25abb87130f441e60e5c75f49348e4ed
function GalvoMatlab_cortex_Link() % GalvoMatlab_cortex_Link Link handling to cortex_m4 serial interface. % % See also SUM, PLUS. global s; evalin('base','global s'); uicontrol('Style', 'pushbutton', 'String', 'OpenPort',... 'Position', [20 20 70 30],... 'Callback', {@clf}); uicontrol('Style', 'pushbutton', 'String', 'OpenPort',... 'Position', [120 120 70 30],... 'Callback', {@MdbOpenPortSub}); s = MdbOpenPort(); MdbSerialGets(s) end %% function [varargout] = MdbDeleteAllPorts() delete(instrfind); if (nargout > 0) varargout{1}=1; end end %% function MdbSerialGets (obj) while (1) if obj.BytesAvailable str = fscanf(obj); disp(str) end end end function [openPortHandle] = MdbOpenPort() % [openPortHandle] = MdbOpenPort Open a serial port. % MdbOpenPort() Error, senseless function call. % [openPortHandle] = MdbOpenPort returns a opened port object. % % See also SUM, PLUS. %% Read serial port objects from memory to MATLAB workspace % out = instrfind % out = instrfind('PropertyName',PropertyValue,...) % out = instrfind(S) % out = instrfind(obj,'PropertyName',PropertyValue,...) %% global obj; evalin('base','global obj') spz=instrfind if ~isempty(spz) delete(spz); clear spz; end %% availableDevices = ls('/dev/ttyUSB*') ; USBports = strsplit(availableDevices, ' '); USBport = USBports{1} obj=serial(USBport); obj.BaudRate=115200 % Termination character for data sequences obj.Terminator='LF'; % The byte order is important for interpreting binary data obj.ByteOrder='bigEndian'; disp(obj.Status) %% % The serial port object must be opened for communication try if strcmp(obj.Status,'closed'), fopen(obj); end printf('opened'); catch err if strcmp(obj.Status,'closed'), fopen(obj); end end if ~nargout warning('Too much Output, serial port object destroyed\n!') else disp(obj.Status) openPortHandle = obj; end end function MdbOpenPortSub() disp('Sub!!!\n'); end % %% % global in % fd=fopen('/media/storage/kabelBW_longtimeSpeedtest/analysed'); % in=textscan(fd,'%f %s %s %s'); % fclose(fd); % f1=figure(1); clf; % ax=axes; % br=bar(in{1}) % %% % startDate = datenum(in{3}(1)); % endDate = datenum(in{3}(end)); % xData = linspace(startDate,endDate,10); % set(ax,'XTick',xData) % % datetick(ax,'x','mm/dd','keepticks') % % %% % function GalvoMatlab_cortex_Link () % % MDBopenPort(); % % uicontrol('Style', 'pushbutton', 'String', 'OpenPort',... % 'Position', [20 20 70 30],... % 'Callback', @MDBopenPort); % %% % % % uicontrol('Style', 'slider',... % % 'Min',1,'Max',50,'Value',41,... % % 'Position', [400 20 120 20],... % % 'Callback', {@surfzlim,hax}); % % Uses cell array function handle callback % % Implemented as a local function with an argument % % uicontrol('Style','text',... % 'Position',[400 45 120 20],... % 'String','Vertical Exaggeration') % return %
github
mainster/matlabCodes-master
RootRaisedCosShaper.m
.m
matlabCodes-master/NT_projects/RootRaisedCosShaper.m
887
utf_8
ebc26eb85cefc0ff1dfae5bcc57f49ad
% Root Raised-Cosine Filter / Pulsform % % t: timevector % Ts: Symbol time % r: Role- off faktor % dom: Domain, Time or Frequency % function [res] = RootRaisedCosShaper(x,Ts,r,dom) jump=@(xx) (0.5*sign(xx)+0.5); if dom=='time' fs=1/Ts; fn=fs; % sig=@(x) 2*fn*sinc(2*pi*fn*x).*cos(2*pi*r*fn*x)./(1-(4*r*fn*x).^1); sig=@(x) ( 4*r/(pi*sqrt(Ts))* (cos((1+r)*pi*x/Ts)+Ts./(4*r*x).*sin((1-r)*pi*x/Ts))./(1-(4*r*x/Ts).^2) ) res = sig(x); else res=-1; end if dom=='freq' fs=1/Ts; fn=fs/2 % Nyquist frequency --> fn=fs/2 (half the symbol frequency) % Hrc= @(x) (cos(pi/4*(abs(x)-(1-r)*fn)/(r*fn))).^2 .* (jump(x+(1+r)*fn)-jump(x-(1+r)*fn)); % Hrc2= @(x) -( ((cos(pi/4*(abs(x)-(1-r)*fn)/(r*fn))).^2 -1).* (jump(x+(1-r)*fn)-jump(x-(1-r)*fn))); res= 0; end end
github
mainster/matlabCodes-master
RaisedCosShaper.m
.m
matlabCodes-master/NT_projects/RaisedCosShaper.m
954
utf_8
e476fe526ad6bbf8fba7c051cdef1139
% Raised-Cosine Filter / Pulsform % % t: timevector % Ts: Symbol time % r: Role- off faktor % dom: Domain, Time or Frequency % function [res] = RaisedCosShaper(x,Ts,r,dom) % syms n k; % step = abs(abs(x(2))-abs(x(1))); jump=@(xx) (0.5*sign(xx)+0.5); k=1; res=[1:length(x)]; if dom=='time' fs=1/Ts; fn=fs; %// sig=@(x) 2*fn*sinc(2*pi*fn*x).*cos(2*pi*r*fn*x)./(1-(4*r*fn*x).^1); sig=@(x) ( sinc(x*fn).*(cos(pi*r*x*fn))./(1-4*(r*x*fn).^2) ); res = sig(x); else res=-1; end if dom=='freq' fs=1/Ts; fn=fs/2 % Nyquist frequency --> fn=fs/2 (half the symbol frequency) Hrc= @(x) (cos(pi/4*(abs(x)-(1-r)*fn)/(r*fn))).^2 .* (jump(x+(1+r)*fn)-jump(x-(1+r)*fn)); Hrc2= @(x) -( ((cos(pi/4*(abs(x)-(1-r)*fn)/(r*fn))).^2 -1).* (jump(x+(1-r)*fn)-jump(x-(1-r)*fn))); res= Hrc(x)+Hrc2(x); end end
github
mainster/matlabCodes-master
genComplSinFS.m
.m
matlabCodes-master/NT_projects/genComplSinFS.m
1,045
ibm852
af9fbb8c127b618397e63c583decf164
% Function generate Complex Sinusodial % % fc: Frequenz der Schwingung % n: n Perioden von 1/fc werden gesamplt?? % Are: Amplitude Re % Aim: Amplitude Im % phi: Phase zwischen Re und Im % DCre: Gleichanteil von Re % DCim: Gleichanteil von Im % % [time,fsam,res]: % time: ... ist der Zeitvektor der erzeugt wurde unter einhaltung von % - n*Tc mit n el. Integers+ % - length(t) modulo 32 = 0 % fsam: ... ist Rückgabewert der Samplefrequenz % res: ... vektor mit den erzeugten Funktionswerten % % function [time,res] = genComplSin(fc,fs,Are,Aim,phideg,DCre,DCim) % Tc=1/fc; % Ts=1/fs; % n=20; % % phi=phideg*pi/180; % % t=[0:Ts:n*Tc-Ts]; % time=t; % % sig=DCre+Are*cos(2*pi*fc*t) + i*(DCim+Aim*sin(2*pi*fc*t+phi)); % res=sig.'; % % end function [time,res] = genComplSin(fc,fs,n,Are,Aim,phideg,DCre,DCim) Tc=1/fc; Ts=1/fs; phi=phideg*pi/180; t=[0:Ts:(n-1)*Ts]; time=t; sig=DCre+Are*cos(2*pi*fc*t) + i*(DCim+Aim*sin(2*pi*fc*t+phi)); res=sig.'; end
github
mainster/matlabCodes-master
zbb.m
.m
matlabCodes-master/NT_projects/zbb.m
736
utf_8
da2f47bee8c3d37db2c3ea0ddbb392fe
% Get complex Baseband in time domain % % t: time- vector % M: M- valued PSK % Ts: Symbol- Time in[s] --> 1/Ts = Baudrate % symbolBits: mapped symbol vector --> sizeof(symbol) = 1 % Ampl: Baseband Amplitude % function [res] = zbb(t,M,Ts,symbolBits,Ampl) rect=@(t) (0.5*sign(t)+0.5); % Baseband- Pulse: For M-PSK g(t)=cos(2*pi/(2*Ts))*(sigma(t+Ts)-sigma(t-Ts)) g=@(t) cos((pi*t)/(2*Ts)).*(rect(t+Ts)-rect(t-Ts)); % Summing complex I-Q pointer res=0; for k=0:M-1 res=res + g(t-k*Ts)*( cos(pi/M*(2*(symbolBits)-1)) + i*sin(pi/M*(2*(symbolBits)-1)) ); end; res=Ampl*res; if real(res)==0 warndlg('No Real signal part') elseif imag(res)==0 warndlg('No Imaginary signal part') end end
github
mainster/matlabCodes-master
genComplSin.m
.m
matlabCodes-master/NT_projects/genComplSin.m
1,130
ibm852
639178c2b3b60daf8c549f7dc096b24b
% Function generate Complex Sinusodial % % fc: Frequenz der Schwingung % n: n Perioden von 1/fc werden gesamplt?? % Are: Amplitude Re % Aim: Amplitude Im % phi: Phase zwischen Re und Im % DCre: Gleichanteil von Re % DCim: Gleichanteil von Im % % [time,fsam,res]: % time: ... ist der Zeitvektor der erzeugt wurde unter einhaltung von % - n*Tc mit n el. Integers+ % - length(t) modulo 32 = 0 % fsam: ... ist Rückgabewert der Samplefrequenz % res: ... vektor mit den erzeugten Funktionswerten % % function [time,res] = genComplSin(fc,fs,Are,Aim,phideg,DCre,DCim) % Tc=1/fc; % Ts=1/fs; % n=20; % % phi=phideg*pi/180; % % t=[0:Ts:n*Tc-Ts]; % time=t; % % sig=DCre+Are*cos(2*pi*fc*t) + i*(DCim+Aim*sin(2*pi*fc*t+phi)); % res=sig.'; % % end function [time,fsam,res] = genComplSin(fc,n,Are,Aim,phideg,DCre,DCim) Tc=1/fc; fs=(fc*(32*8-1))/n; % über Abtastfreq lenth(t)%32=0 einhalten %fs=160e6; Ts=1/fs; phi=phideg*pi/180; t=[0:Ts:n*Tc]; time=t; fsam=fs; sig=DCre+Are*cos(2*pi*fc*t) + i*(DCim+Aim*sin(2*pi*fc*t+phi)); res=sig.'; end
github
mainster/matlabCodes-master
zbbBPSK.m
.m
matlabCodes-master/NT_projects/zbbBPSK.m
813
utf_8
173bec77a32a45d39d22488412bc1d46
% Get complex Baseband in time domain % % t: time- vector % Ts: Symbol- Time in[s] --> 1/Ts = Baudrate % dk: mapped symbol vector % Ampl: Baseband Amplitude % function [res] = zbbBPSK(t,Ts,dk,Ampl,shape,rolloff) rect=@(t) (0.5*sign(t)+0.5); % Baseband- Pulse: For M-PSK g(t)=cos(2*pi/(2*Ts))*(sigma(t+Ts)-sigma(t-Ts)) if shape=='rect' g=@(t) (rect(t)-rect(t-1)); elseif shape=='rcos' g=@(t) RaisedCosShaper(t,Ts,rolloff,'time'); else errordlg('Unknown shape format') g=@(t) -1; end % Summing complex I-Q pointer res=0; for k=0:size(dk,2)-1 res=res + dk(k+1)*g(t-k*Ts); end; res=Ampl*res; % if real(res)==0 % warndlg('No Real signal part') % elseif imag(res)==0 % warndlg('No Imaginary signal part') % end end
github
mainster/matlabCodes-master
NyquistGui.m
.m
matlabCodes-master/NyquistGui/NyquistGui.m
26,670
utf_8
020bca963b04660214fdac5ea9e1a183
function varargout = NyquistGui(varargin) % Doesn't handle multiple poles on axes (except at origin). % Rounds to nearest 0.001 (if near origin or axis % % NYQUISTGUI MATLAB code for NyquistGui.fig % NYQUISTGUI, by itself, creates a new NYQUISTGUI or raises the existing % singleton*. % % H = NYQUISTGUI returns the handle to a new NYQUISTGUI or the handle to % the existing singleton*. % % NYQUISTGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in NYQUISTGUI.M with the given input arguments. % % NYQUISTGUI('Property','Value',...) creates a new NYQUISTGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before NyquistGui_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to NyquistGui_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 NyquistGui % Last Modified by GUIDE v2.5 10-Oct-2011 17:58:14 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @NyquistGui_OpeningFcn, ... 'gui_OutputFcn', @NyquistGui_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 NyquistGui is made visible. function NyquistGui_OpeningFcn(hObject, ~, 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 NyquistGui (see VARARGIN) % Choose default command line output for NyquistGui handles.output = hObject; handles.axNumLim=10; %limit for axes handles.axDelt=2; %spacing on grid handles.axInf=12; %"Infinity" on graphs handles.circRad=5; %radius of circle for plot set(handles.pauseTButton,'Value',0); set(handles.pauseTButton,'String','Pause'); handles.tf=[]; dispTF(handles); %Clear TF handles.BItfs=[]; handles.nth=32; %number of points for circular s-domain plot set(handles.pathDrawPanel,'Visible','off'); %Disable plotting set(handles.expPanel,'Visible','off'); set(handles.zoomButton,'String','Zoom out'); initSysLists(handles); % Initialize lists of systems handles=guidata(hObject); % Reload handles (changed in getTFInfor) guidata(hObject, handles); % Update handles structure initAxes(handles); % UIWAIT makes NyquistGui wait for user response (see UIRESUME) % uiwait(handles.NyqGuiFig); % --- Outputs from this function are returned to the command line. function varargout = NyquistGui_OutputFcn(~, ~, 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; function initAxes(handles) myGrid(handles.sDomAx, handles); %Initialize axes axes(handles.sDomAx); title('s-domain plot (w/ poles and zeros of L(s))'); ylabel('imag(s)'); xlabel('real(s)'); myGrid(handles.ghDomAx, handles); %Initialize axes ylabel('imag( L(s) )'); xlabel('real( L(s) )'); if get(handles.NyqPathRButt,'Value'), title('L(s)-domain plot (w/ the point -1 shown)); L(s)=G(s)H(s)'); text(-1,0,'+','HorizontalAlignment','Center',... 'FontSize',14,'FontWeight','demi'); thet=linspace(0,2*pi,32); plot(cos(thet),sin(thet),':','Color',0.8*[1 1 1]); else title('L(s)-domain plot'); end % --- Initialize graph function myGrid(myAx, handles) axes(myAx); lm=handles.axNumLim; %limit for axes delt=handles.axDelt; %spacing on grid lmi=handles.axInf; %"infinity" g=0.8*[1 1 1]; %Color for grid. cla; set(gca,'XLim',[-lmi lmi]); set(gca,'YLim',[-lmi lmi]); set(gca,'XTick',-lmi:delt:lmi); set(gca,'XTickLabel',{'-inf';-lm:delt:lm;'+inf'}); set(gca,'YTick',-lmi:delt:lmi); set(gca,'YTickLabel',{'-inf';-lm:delt:lm;'+inf'}); box on; hold on; thet = 0:0.01:2*pi; x=lmi*cos(thet); y=lmi*sin(thet); %patch(x,y,'w'); patch([x lmi lmi -lmi -lmi lmi],[y -lmi lmi lmi -lmi -lmi],... g+0.5*(1-g),'EdgeColor',g); plot(lm*sin(thet),lm*cos(thet),':','Color',g); for x=delt:delt:lm, % Make grid isct=sqrt(lm*lm-x*x); %intersect of line an circle plot([x x],[-isct isct],':','Color',g); plot([-isct isct],[-x -x],':','Color',g); plot([-isct isct],[x x],':','Color',g); plot([-x -x],[-isct isct],':','Color',g); end plot([-lm lm],[0 0],':','Color',0.8*g); %axis at zero is darker plot([0 0],[-lm lm],':','Color',0.8*g); plot([-lm -lmi],[0 0],':','Color',0.5*g); %axis out to infinity plot([0 0],[-lm -lmi],':','Color',0.5*g); plot([lm lmi],[0 0],':','Color',0.5*g); plot([0 0],[lm lmi],':','Color',0.5*g); zoomButton_Callback([], [], handles); %Zoom gh plot % --- Executes on button press in StartButton. function StartButton_Callback(~, ~, handles) sPath(handles, 0); %Circular path, fast function SlowButton_Callback(~, ~, handles) sPath(handles, 0.1); %Circular path, slow % --- Executes on selection change in BISysMenu. function BISysMenu_Callback(~, ~, handles) % hObject handle to BISysMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) tfNum=get(handles.BISysMenu,'value'); myTF=handles.BItfs{tfNum}; if (tfNum==1), set(handles.pathDrawPanel,'Visible','off'); set(handles.expPanel,'Visible','off'); warndlg('No transfer function chosen'); else initAxes(handles); axes(handles.sDomAx); mappz(myTF); set(handles.pathDrawPanel,'Visible','on'); set(handles.userSysMenu,'value',1); end handles.tf=myTF; dispTF(handles); guidata(handles.NyqGuiFig, handles); % Update handles structure % --- Executes during object creation, after setting all properties. function BISysMenu_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in limitationButton. function limitationButton_Callback(~, ~, ~) s={ '* Time delays are ignored. (You can add them by altering the',... ' code in function ''pathInterp'', but do so at your own risk.)',... '* The drawing of the angle subtended by the path in "L(s)"',... ' is not meaningful in the case of marginally stable systems).',... ' (i.e., marginally stable systems.',... '* The imaginary part of poles very near the imaginary axis are ',... ' rounded to zero (i.e., the poles are placed on the axis).',... '* User-defined functions are loaded when program starts. Any ',... ' functions added while program runs do not appear in the list.',... ' ',... '* Axes are fixed; poles, zeros and gains must be chosen',... ' accordingly.',... ' This is not meant to be a general tool for plotting Nyquist',... ' diagrams, but rather a tool for learning the associated',... ' concepts.'}; helpdlg(s,'Program Limitations'); function initSysLists(handles) % Builtins x={ 'Built-in Systems',[];... 'PoleOrig',tf(10,[1 0]);... 'ZeroOrig',tf([1 0],1);... 'PoleNeg4',tf(10,[1 4]);... 'ZeroNeg4',tf([1 4],1);... 'PoleNeg6',tf(10,[1 6]);... 'ZeroNeg6',tf([1 6],1);... 'PolesConj',tf(100,[1 4 20]);... 'PolesP6M4',tf(48,[1 -2 -24]);... 'Pole4_8',tf(10,[1 4.8]);... 'PZ',tf([1 -2],[1 4]);... 'Polesjw',tf(16,[1 0 16]);... 'DoubleInt',zpk([],[0 0],1);... 'CondStable',zpk([],[-1 -2 -3],30);... 'SlightlyUnstable',zpk(-3,[2j -2j -2],10);... 'BarelyStable',zpk(-2,[2j -2j -3],10);... 'Example 1',tf(90,[1 9 18]);... 'Example 2',tf(20,[1 5 6]);... 'Example 2b',tf(100,[1 5 6]);... 'Example 3',tf(10*[1 3],[1 0 -4]);... 'Example 4',tf(50*[1 3],[1 -1 11 -51]);... 'Example 5',tf(10*[1 2],[1 3 0 0]);... 'Example 5b',tf(10*[1 4],[1 3 0 0])}; set(handles.BISysMenu,'String',x(:,1)); handles.BItfs=x(:,2); set(handles.BISysMenu,'Value',1); % Put top value in menu s=evalin('base','whos(''*'')'); tfs=char(s.class); %x=class of all variable tfs=strcmp(cellstr(tfs),'tf'); %Convert to cell array and find tf's s=s(tfs); %Get just tf's vname=char(s.name); x=cell(length(s)+1,2); j=1; x{j,1}='User Systems'; for i=1:length(s) myTF=evalin('base',vname(i,:)); if (size(myTF.num,1)==1), j=j+1; x{j,1}=vname(i,:); x{j,2}=myTF; end end set(handles.userSysMenu,'String',x(1:j,1)); handles.Usertfs=x(1:j,2); set(handles.userSysMenu,'Value',1); % Put top value in menu guidata(handles.NyqGuiFig, handles); % Update handles structure function dispTF(handles) % This function displays a tranfer function that is a helper function. % It takes the transfer function of the and splits it % into three lines so that it can be displayed nicely. For example: % " s + 1" % "H(s) = ---------------" % " s^2 + 2 s + 1" % The numerator string is in the variable nStr, % the second line is in divStr, % and the denominator string is in dStr. if isempty(handles.tf), nStr=blanks(50); dStr=blanks(50); divStr='No system to display, choose one'; else % Get numerator and denominator. [n,d]=tfdata(handles.tf,'v'); % Set very small values to zero n=n.*(abs(n)>1e-6); d=d.*(abs(d)>1e-6); % Get string representations of numerator and denominator nStr=poly2str(n,'s'); dStr=poly2str(d,'s'); % Find length of strings. LnStr=length(nStr); LdStr=length(dStr); if LnStr>LdStr, %the numerator is longer than denominator string, so pad denominator. n=LnStr; %n is the length of the longer string. nStr=[' ' nStr]; %add spaces for characters at start of divStr. dStr=[' ' blanks(floor((LnStr-LdStr)/n)) dStr]; %pad denominator. else %the demoninator is longer than numerator, pad numerator. n=LdStr; nStr=[' ' blanks(floor((LdStr-LnStr)/n)) nStr]; dStr=[' ' dStr]; end divStr='L(s)= '; divStr=[divStr strrep(blanks(n),' ','-')]; end set(handles.tfText,'String',{nStr,divStr,dStr}); %Change type font and size. set(handles.tfText,'FontName','Courier New') set(handles.tfText,'FontSize',10) function mappz(myTF) [z,p]=zpkdata(myTF,'v'); plot(real(z),imag(z),'bo','Markersize',8) plot(real(p),imag(p),'bx','Markersize',10); % --- Executes on button press in zoomButton. function zoomButton_Callback(~, ~, handles) % hObject handle to zoomButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) axes(handles.ghDomAx); if get(handles.zoomButton, 'Value')==0 axis((handles.axInf)*[-1 1 -1 1]); set(handles.zoomButton,'String','Zoom in'); else axis(handles.axNumLim/5*[-1 1 -1 1]); set(handles.zoomButton,'String','Zoom out'); end guidata(handles.NyqGuiFig, handles); % Update handles structure % --- Executes on selection change in userSysMenu. function userSysMenu_Callback(~, ~, handles) tfNum=get(handles.userSysMenu,'value'); myTF=handles.Usertfs{tfNum}; if (tfNum==1), set(handles.pathDrawPanel,'Visible','off'); set(handles.expPanel,'Visible','off'); warndlg('No transfer function chosen'); else initAxes(handles); axes(handles.sDomAx); mappz(myTF); set(handles.pathDrawPanel,'Visible','on'); set(handles.BISysMenu,'value',1); end handles.tf=myTF; dispTF(handles); guidata(handles.NyqGuiFig, handles); % Update handles structure % --- Executes during object creation, after setting all properties. function userSysMenu_CreateFcn(hObject, ~, ~) % hObject handle to userSysMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sPath(handles, del) rinf=1000; rDetour=0.4; % This is the drawn radius of a detour around a pole. epsln = 0.001; % This is the precision for rounding location of any % poles near jw axis (imag part of pole must be greater % than epsln). set(handles.pauseTButton,'Value',0); set(handles.pauseTButton,'String','Pause'); axis((handles.axInf)*[-1 1 -1 1]); set(handles.expPanel,'Visible','off'); [z,p,k]=zpkdata(handles.tf,'v'); % If pole is near imag axis, put it on the axis (set real part=0) is_onaxis=abs(real(p))<epsln; % is_onaxis=1 if pole is near axis. p=complex(real(p).*(~is_onaxis),imag(p)); %If on axis, make p pure imaginary. handles.tf=zpk(z,p,k); dispTF(handles); handles.gh_path_inf=0; %path in gh gets to inf? guidata(handles.NyqGuiFig, handles); % Update handles structure initAxes(handles); axes(handles.sDomAx); mappz(handles.tf); n=handles.nth; hold on; if get(handles.NyqPathRButt,'Value') % The Nyquist path is the hardest to create, because we must accomodate % detours around poles on the jw axis. To make the plot look right % the detours will be large enough to see on the s-domain plot. % However, we'll keep track of when the path is on the detour and use % this information in the plot (we'll simply extend the radius of the % GH domain plot to infinity. p_at_origin=sum(abs(p)<epsln)~=0; %See if we have poles at origin. p_gt_0=p(imag(p(is_onaxis))>=epsln); %find all positive poles on axis. p_onax=sort(p_gt_0); %sort all of the poles. n_onax=length(p_onax); %number on axis. % If there is a pole at the origin, put detour on path. if p_at_origin, theta=linspace(0,pi/2,n/4); x=rDetour*cos(theta); %Plot detour (large) y=rDetour*sin(theta); ondet=ones(size(x)); %This variable indicates we are %on detour. else x=0; %else start path at origin (for both plot and calc) y=0; ondet=zeros(size(x)); %We are not on detour. end % Path now goes up the imag axis thet=linspace(-pi/2,pi/2,n); for i=1:n_onax, %Loop through poles on axis %First extend path up to the current pole (plot), ynew = linspace(y(end), imag(p_onax(i))-rDetour, n/(n_onax+1)); y=[y ynew]; x=[x zeros(size(ynew))]; ondet=[ondet zeros(size(ynew))]; %Not on detour %Now make detour y=[y imag(p_onax(i))+rDetour*sin(thet)]; x=[x rDetour*cos(thet)]; ondet=[ondet ones(size(thet))]; %On detour end % Now complete path up ro the top of the axis. ynew = linspace(y(end),2*handles.axNumLim,2*n); y=[y ynew]; x=[x zeros(size(ynew))]; ondet=[ondet zeros(size(ynew))]; % Now make entire path - add quarter of circle at infinity (to get path % back to real axis, thereby completing the path on the upper half of % the s plane. We then complete path by extending the path with its % complex conjugate to get lower half of s-plane. thet=linspace(pi/2,0,n/2); % Angles for quarter circle. x=[x rinf*cos(thet)]; % Add quarter circle. y=[y rinf*sin(thet)]; % x=[x fliplr(x)]; % Add lower half of s-plane. % y=[y -fliplr(y)]; % We know the rest of the path won't have detours, so extend array % that indicates detours with zeros. % ondet = [ondet zeros(size(thet))]; ondet=[ondet fliplr(ondet)]; ondet=[ondet zeros(size(thet))]; pathInterp(x,y,ondet,del,handles); axes(handles.ghDomAx); text(-1,0,'+','HorizontalAlignment','Center',... 'FontSize',14,'FontWeight','demi'); if(~get(handles.pauseTButton,'Value')), nyqPathExplain(handles); end elseif get(handles.circPathRButt,'Value') r=handles.circRad; thet=linspace(0,pi,n+1); x0=r*cos(-thet); y0=r*sin(-thet); pathInterp(x0,y0,zeros(size(x0)),del,handles); if(~get(handles.pauseTButton,'Value')), nyqCircExplain(handles); end else beep; errordlg('One radio button must be pushed.'); end function pathInterp(x0,y0,ondet0,del,handles) maxlen=10000; x=zeros(1,maxlen); y=zeros(1,maxlen); ondet=zeros(1,maxlen); j=1; %Counter for x0,y0 i=1; %Counter for x,y x(1)=x0(1); y(1)=y0(1); ondet(1)=ondet0(1); dx=x0(2)-x0(1); dy=y0(2)-y0(1); dx0=abs(dx); dy0=abs(dy); s=complex(x(1),y(1)); %If you want a time delay, uncomment the next line and add desired delay. %handles.tf=handles.tf*tf(1,1,'InputDelay',0.5); gh_old=freqresp(handles.tf,s); %gha_old=angle(gh_old); while ( (i<maxlen) && (j<(length(x0))) ), x_nxt=x(i)+dx; y_nxt=y(i)+dy; s=complex(x_nxt,y_nxt); gh=freqresp(handles.tf,s); %gha=angle(gh); % diffAngle=abs(gha-gha_old); % if diffAngle>1.5*pi, % diffAngle=abs(diffAngle-2*pi); % end % diffAngle=0; if abs(gh)<handles.axInf, maxDiff=0.05; else maxDiff=0.2; end % if (((abs((gh-gh_old)/gh)>maxDiff) || (diffAngle>0.001)) && (abs(gh)>0.02)), if ((abs((gh-gh_old)/gh)>maxDiff) && (abs(gh)>0.02)), dx=dx/2; dy=dy/2; else if ( (abs(x_nxt-x0(j))>=dx0) || (abs(y_nxt-y0(j))>=dy0) ), j=j+1; x_nxt=x0(j); y_nxt=y0(j); s=complex(x_nxt,y_nxt); gh=freqresp(handles.tf,s); % gha=angle(gh); if j~=length(x0), dx=x0(j+1)-x0(j); dy=y0(j+1)-y0(j); dx0=abs(dx); dy0=abs(dy); end end i=i+1; x(i)=x_nxt; y(i)=y_nxt; % Here we assign the values of x and y ondet(i)=ondet0(j); gh_old=gh; %gha_old=gha; dx=dx*1.4; dy=dy*1.4; end end if i==maxlen, warndlg('Large changes in L(s), plot inaccurate.'); end ondet=ondet(1:i); s=complex(x(1:i),y(1:i)); gh=freqresp(handles.tf,s); gh=transpose(gh(:)); mltp = 1+999*ondet; %multiplier array - if ondet, multiply by 1000 gh=gh.*mltp; s(end+1)=s(end); gh(end+1)=gh(end); plotPath(handles,s,gh,del); %Make plot handles=guidata(handles.NyqGuiFig); % Reload handles function plotPath(handles,s,gh,del) alph=0.25; %Colors (and transparency) used in plots zcol=[1 0 0]; pcol=[0 0 1]; gcol=[1 1 1]*0.25; arr=zeros(size(s)); arr([10 floor((1:4)*(length(s)/5)) end-12 end-4])=1; s=[s fliplr(conj(s)) s(1)]; gh=[gh fliplr(conj(gh)) gh(1)]; arr=[arr fliplr(arr) 0]; % Get real and imaginary parts of s, and truncate large values. r_s=abs(s); i=find(r_s>(handles.axInf)); % too large s(i)=s(i)*(handles.axInf)./r_s(i); sr=real(s); si=imag(s); % Get real and imaginary parts of gh, and truncate large values. r_gh=abs(gh); i=find(r_gh>(handles.axInf)); % too large gh(i)=gh(i)*(handles.axInf)./r_gh(i); if ~isempty(i), handles.gh_path_inf=1; %path in gh gets to inf? guidata(handles.NyqGuiFig, handles); % Update handles structure end gr=real(gh); gi=imag(gh); % % Calculate the cummulative arclength (while s<inf) % arclen=[0 sqrt(cumsum((diff(sr).^2+diff(si).^2).*... % ((r_s(2:end)<handles.axInf))))]; arclen=[0 cumsum(abs(diff(s))+abs(diff(gh)))]; maxarclen=max(arclen); c=hsv2rgb([arclen/maxarclen; ones(2,length(arclen))]'); %colormap if get(handles.NyqPathRButt,'Value') ghx0=-1; else ghx0=0; end %Get poles and zeros [z,p]=zpkdata(handles.tf,'v'); % Create patches for showing angle of zeros (s domain) and precalculate % angles. azs=zeros(length(z),length(s)); %za=zeros(length(z),length(s)-1); zp=zeros(length(z)); zl=zeros(length(z)); axes(handles.sDomAx); for j=1:length(z), azs(j,:)=unwrap(angle(s(:)-z(j))); %angle from s to z(j) % za(j,:)=cumsum(diff(azs(j,:))); % zp is patch showhing cumulative angle from zero to s. It is defined % here but not used until later. % zl is a line from origin to s. zp(j)=patch([0 0 ],[0 0],zcol,... 'FaceColor',zcol,'FaceAlpha',alph,... 'EdgeColor',zcol,'EdgeAlpha',alph*0.5); zl(j)=line([0 0],[0 0],'Color',zcol,'Linestyle',':'); end % Create patches for showing angle of poles (s domain), and precalculate % angles. aps=zeros(length(p),length(s)); %pa=zeros(length(p),length(s)-1); pp=zeros(length(p)); pl=zeros(length(p)); for j=1:length(p), aps(j,:)=unwrap(angle(s(:)-p(j))); % pa(j,:)=cumsum(diff(aps(j,:))); pp(j)=patch([0 0 ],[0 0],pcol,... 'FaceColor',pcol,'FaceAlpha',alph,... 'EdgeColor',pcol,'EdgeAlpha',alph*0.5); pl(j)=line([0 0],[0 0],'Color',pcol,'Linestyle',':'); end % Create patches for showing angle of gh path axes(handles.ghDomAx); agh=unwrap(angle(gh-ghx0)); %ga=cumsum(diff(agh)); gp=patch([0 0 ],[0 0],gcol,'FaceAlpha',alph,'EdgeAlpha',alph*0.5); gl=line([0 0],[0 0],'Color',gcol,'Linestyle',':'); zr=real(z); zi=imag(z); pr=real(p); pi=imag(p); i=1; while i<(length(s)-1), if get(handles.pauseTButton,'Value'), pause(0.5); else axes(handles.sDomAx); % Plot s path (changing color as we go) plot([sr(i) sr(i+1)],[si(i) si(i+1)],'Color',c(i,:),'Linewidth',1.5); % Draw lines from z(j) to s, and fill in patch showing subtended angle. for j=1:length(z), %th=azs(j,1)+linspace(0,za(j,i),20); th=linspace(azs(j,1),azs(j,i+1),20); set(zp(j),'XData',[zr(j) zr(j)+cos(th)],'YData',[zi(j) zi(j)+sin(th)]) set(zl(j),'XData',[zr(j) sr(i+1)],'YData',[zi(j) si(i+1)]); end for j=1:length(p), %th=aps(j,1)+linspace(0,pa(j,i),20); th=linspace(aps(j,1),aps(j,i+1),20); set(pp(j),'XData',[pr(j) pr(j)+cos(th)],'YData',[pi(j) pi(j)+sin(th)]) set(pl(j),'XData',[pr(j) sr(i+1)],'YData',[pi(j) si(i+1)]); end axes(handles.ghDomAx); plot([gr(i) gr(i+1)],[gi(i) gi(i+1)],'Color',c(i,:),'Linewidth',2); %th=agh(1)+linspace(0,ga(i),abs(ga(i))*2+20); th=linspace(agh(1),agh(i+1),abs(agh(i+1)-agh(1))*2+20); if (agh(i+1)>0), gcol=pcol; else gcol=zcol; end set(gp,'XData',ghx0+[0 cos(th)],'YData',[0 sin(th)],... 'EdgeColor',gcol,'FaceColor',gcol); set(gl,'XData',[ghx0 gr(i+1)],'YData',[0 gi(i+1)],... 'Color',gcol); if arr(i)~=0, sarr_a=atan2(si(i+1)-si(i),sr(i+1)-sr(i)); garr_a=atan2(gi(i+1)-gi(i),gr(i+1)-gr(i)); axes(handles.sDomAx); angleArrow(sr(i), si(i), sarr_a, c(i,:)); axes(handles.ghDomAx); angleArrow(gr(i), gi(i), garr_a, c(i,:)); end pause(del); i=i+1; end end function angleArrow(tx,ty,thet,c) x=0.5*[-0.75 1 -0.75]; y=0.3*[-1 0 1]; pts=[ cos(thet) -sin(thet) tx; sin(thet) cos(thet) ty; 0 0 1;]*[x; y; ones(size(x))]; x=pts(1,:); y=pts(2,:); patch(x,y,c,'EdgeColor',c,'FaceAlpha',0.5,'EdgeAlpha',0.5); % --- Executes on button press in pauseTButton. function pauseTButton_Callback(~, ~, handles) % hObject handle to pauseTButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if get(handles.pauseTButton,'Value'), set(handles.pauseTButton,'String','Play'); else set(handles.pauseTButton,'String','Pause'); end function nyqCircExplain(handles) r=handles.circRad; [z,p]=zpkdata(handles.tf,'v'); nz=length(z); nzi=sum(abs(z)<r); np=length(p); npi=sum(abs(p)<r); N=nzi-npi; s1=['The transfer function has ' num2str(nz) ' zero(s) and '... num2str(np) ' pole(s).']; s2=['The s-domain path encircles ' num2str(nzi) ' zero(s) and '... num2str(npi) ' pole(s) in a CW direction.']; s3=['Z=' num2str(nzi) ', P=' num2str(npi) ', and N=Z-P=' num2str(N)]; s4=' '; s5=['Thus the path in GH encirles the origin ' num2str(N) ' time(s) '... ' CW, or ' num2str(-N) ' time(s) CCW.']; if handles.gh_path_inf~=0 s6=' '; s7=['Note: GH was large enought that it had to be shown at '... 'infinity for part of the path.']; s={s1;s2;s3;s4;s5;s6;s7}; else s={s1;s2;s3;s4;s5}; end set(handles.expText,'String',s); set(handles.expPanel,'Visible','on'); function nyqPathExplain(handles) r=handles.circRad; [z,p]=zpkdata(handles.tf,'v'); % Assume poles very near jw axis are on jw axis p_offax=abs(real(p))>1e-5; p=complex(real(p).*p_offax,imag(p)); P=sum(real(p)>0); tfcl=minreal(feedback(handles.tf,1)); %System with feedback. [zcl,pcl]=zpkdata(tfcl,'v'); % Assume poles very near jw axis are on jw axis p_offax=abs(real(pcl))>1e-5; p_onax=~p_offax; pcl=complex(real(pcl).*p_offax,imag(pcl)); Z=sum(real(pcl)>0); N=Z-P; s1=['The open-loop transfer function, L(s), has P=' num2str(P)... ' pole(s) in the RHP.']; s2=['The s-domain path encircles the origin N=' num2str(N) ' time(s) '... 'in a CW direction.']; s3=['Therefore the closed loop transfer function has Z=N+P='... num2str(Z) ' pole(s) in the RHP (' num2str(Z)... ' zero(s) of c.e. in RHP)']; if (Z>0) s4 = 'The system is unstable.'; else s4 = 'The system is stable.'; end s5=' '; if sum(p_onax)~=0, s6=['"L(s)" path goes through -1+j0, so there are some closed ',... 'loop poles on jw axis.']; s7='The angles drawn on the "L(s)" plot may be inaccurate!'; s={s1;s2;s3;s4;s5;s6;s7}; else s={s1;s2;s3;s4}; end set(handles.expText,'String',s); set(handles.expPanel,'Visible','on'); % --- Executes on button press in clearPButton. function clearPButton_Callback(~, ~, handles) initAxes(handles); axes(handles.sDomAx); mappz(handles.tf); % --- Executes on button press in webPB. function webPB_Callback(hObject, eventdata, handles) web('http://lpsa.swarthmore.edu/Nyquist/Nyquist.html','-browser')
github
mainster/matlabCodes-master
gershband.m
.m
matlabCodes-master/CUSTOM_LIBRARY/Mimotools/gershband.m
3,076
utf_8
1fc6d3bb4118fc7975d6ebd6fee3f398
function gershband(a,b,c,d,e) %GERSHBAND - Finds the Gershorin Bands of a nxn LTI MIMO SYS model % The use of the Gershorin Bands along the Nyquist plot is helpful for % finding the coupling grade of a MIMO system. % % Syntax: gershband(SYS) - computes the Gershgorin bands of SYS % gershband(SYS,'v') - computes the Gershgorin bands and the % Nyquist array of SYS % Inputs: % SYS - LTI MIMO system, either in State Space or Transfer Function % representation. % % Example: % g11=tf(2,[1 3 2]); % g12=tf(0.1,[1 1]); % g21=tf(0.1,[1 2 1]); % g22=tf(6,[1 5 6]); % G=[g11 g12; g21 g22]; % gershband(G); % % Other m-files required: sym2tf, ss2sym % Subfunctions: center, radio % See also: rga % % Author: Oskar Vivero Osornio % email: [email protected] % Created: February 2006; % Last revision: 11-May-2006; % May be distributed freely for non-commercial use, % but please leave the above info unchanged, for % credit and feedback purposes %------------- BEGIN CODE -------------- %--------- Determines Syntax ----------- ni=nargin; switch ni case 1 %Transfer Function Syntax switch class(a) case 'tf' %Numeric Transfer Function Syntax g=a; case 'sym' %Symbolic Transfer Function Syntax g=sym2tf(a); end e=0; case 2 %Transfer Function Syntax with Nyquist Array switch class(a) case 'tf' %Numeric Transfer Function Syntax g=a; case 'sym' %Symbolic Transfer Function Syntax g=sym2tf(a); end e=1; case 4 %State Space Syntax g=ss2sym(a,b,c,d); g=sym2tf(g); e=0; case 5 %State Space Syntax g=ss2sym(a,b,c,d); g=sym2tf(g); e=1; end %--------------------------------------- [n,m]=size(g); w=logspace(-1,6,200); q=0:(pi/50):(2*pi); for i=1:n for j=1:m if i==j figure(i) nyquist(g(i,i)); grid on title(['Nyquist Diagram of G(',num2str(i),',',num2str(j),')']) for iest=1:n for jest=1:m if iest~=jest hold on C=center(g(i,j),w); R=radio(g(iest,jest),w); for k=1:length(C) plot((R(k)*cos(q))+real(C(k)),(R(k)*sin(q))+imag(C(k)),'g-') end hold off end end end end end end if e==1 figure(n+1) nyquist(g); grid on end %------------ Subfunction -------------- function C = center(g,w) g=tf2sym(g); C=subs(g,complex(0,w)); function R = radio(g,w) g=tf2sym(g); R=abs(subs(g,complex(0,w))); %------------- END OF CODE --------------
github
mainster/matlabCodes-master
arrowh.m
.m
matlabCodes-master/CUSTOM_LIBRARY/Mimotools/arrowh.m
6,921
utf_8
a6ac3ee76572ce60d5bd4be9dd7ee4c0
% ARROWH Draws a solid 2D arrow head in current plot. % ARROWH(X,Y,COLOR,SIZE,LOCATION) draws a solid arrow head into % the current plot to indicate a direction. X and Y must contain % a pair of x and y coordinates ([x1 x2],[y1 y2]) of two points: % % The first point is only used to tell (in conjunction with the % second one) the direction and orientation of the arrow -- it % will point from the first towards the second. % % The head of the arrow will be located in the second point. An % example of use is plot([0 2],[0 4]); ARROWH([0 1],[0 2],'b') % % You may also give two vectors of same length > 2. The routine % will then choose two consecutive points from "about" the middle % of each vectors. Useful if you don't want to worry each time % about where to put the arrows on a trajectory. If x1 and x2 % are the vectors x1(t) and x2(t), simply put ARROWH(x1,x2,'r') % to have the right direction indicated in your x2 = f(x1) phase % plane. % % (x2,y2) % --o % \ | % \| % % % o % (x1,y1) % % Please note that the following optional arguments need -- if % you want to use them -- to be given in that exact order. % % The COLOR argument is exactely the same as for plots, eg. 'r'; % if not given, blue is default. % % The SIZE argument allows you to tune the size of the arrows. % % The LOCAITON argument only applies, if entire solution vectors % have been passed on. With this argument you can indicate where % abouts inside those vectors to take the two points from. % Can be a vector, if you want to have more than one arrow drawn. % % Both arguments, SIZE and LOCATION must be given in percent, % where 100 means standard size, 50 means half size, respectively % 100 means end of the vector, 48 means about middle, 0 beginning. % Note that those "locations" correspond to the cardinal position % "inside" the vector, say "index-wise". % % This routine is mainely intended to be used for indicating % "directions" on trajectories -- just give two consecutive times % and the corresponding values of a flux and the proper direction % of the trajectory will be shown on the plot. You may also pass % on two solution vectors, as described above. % % Note, that the arrow only looks good on the specific axis % settings when the routine was actually started. If you zoom in % afterwards, the triangle gets distorted. % % Examples of use: % x1 = [0:.2:2]; x2 = [0:.2:2]; plot(x1,x2); hold on; % arrowh(x1,x2,'r',100,20); % passing on entire vectors % arrowh([0 1],[0 1],'g',300); % passing on 2 points % Author: Florian Knorn % Email: [email protected] % Version: 1.10 % Filedate: Dec 1st, 2005 % % History: 1.10 - Buxfix % 1.09 - Possibility to chose *several* locations % 1.08 - Possibility to chose location % 1.07 - Choice of color % 1.06 - Bug fixes % 1.00 - Release % % ToDos: - More specific shaping-possibilities, % - Keep proportions when zooming or resizing; % has to be done with callback functions, I guess. % % Bugs: None discovered yet, those discovered were fixed % % Thanks: I haven't used the function in ages, but the % last time I modified something in a hurry, I % introduced a stupid bug, which Kesh Ikum was so % kind to point out ;-) Thanks! % % If you have suggestions for this program, if it doesn't work for % your "situation" or if you change something in it - please send % me an email! This is my very first "public" program and I'd like % to improve it where I can -- your help is kindely appreciated! % Thank you! function arrowh(x,y,clr,ArSize,Where) %-- errors if nargin < 2 error('Please give enough coordinates !'); end if (length(x) < 2) || (length(y) < 2), error('X and Y vectors must each have "length" >= 2 !'); end if (x(1) == x(2)) && (y(1) == y(2)), error('Points superimposed - cannot determine direction !'); end if nargin < 3 clr = 'b'; end if nargin < 4 ArSize = 100 / 10000; %-- 10000 is an arbitrary value... else ArSize = ArSize / 10000; end if nargin < 5 Where = 50; end %-- determine and remember the hold status, toggle if necessary if ishold, WasHold = 1; else WasHold = 0; hold on; end %-- start for-loop in case several arrows are wanted for Loop = 1:length(Where), %-- if vectors "longer" then 2 are given we're dealing with time series if (length(x) == length(y)) && (length(x) > 2), j = floor(length(x)*Where(Loop)/100); %-- determine that location if j >= length(x), j = length(x) - 1; end if j == 0, j = 1; end x1 = x(j); x2 = x(j+1); y1 = y(j); y2 = y(j+1); else %-- just two points given - take those x1 = x(1); x2 = x(2); y1 = y(1); y2 = y(2); end %-- get axe ranges and their norm OriginalAxis = axis; Xextend = abs(OriginalAxis(2)-OriginalAxis(1)); Yextend = abs(OriginalAxis(4)-OriginalAxis(3)); %-- determine angle for the rotation of the triangle if x2 == x1, %-- line vertical, no need to calculate slope if y2 > y1, p = pi/2; else p= -pi/2; end else %-- line not vertical, go ahead and calculate slope %-- using normed differences (looks better like that) m = ( (y2 - y1)/Yextend ) / ( (x2 - x1)/Xextend ); if x2 > x1, %-- now calculate the resulting angle p = atan(m); else p = atan(m) + pi; end end %-- the arrow is made of a transformed "template triangle". %-- it will be created, rotated, moved, resized and shifted. %-- the template triangle (it points "east", centered in (0,0)): xt = [1 -sin(pi/6) -sin(pi/6)]; yt = [0 cos(pi/6) -cos(pi/6)]; %-- rotate it by the angle determined above: xd=[]; yd=[]; for i=1:3, xd(i) = cos(p)*xt(i) - sin(p)*yt(i); yd(i) = sin(p)*xt(i) + cos(p)*yt(i); end %-- move the triangle so that its "head" lays in (0,0): xd = xd - cos(p); yd = yd - sin(p); %-- stretch/deform the triangle to look good on the current axes: xd = xd*Xextend*ArSize; yd = yd*Yextend*ArSize; %-- move the triangle to the location where it's needed xd = xd + x2; yd = yd + y2; %-- draw the actual triangle patch(xd,yd,clr,'EdgeColor',clr); end % Loops %-- restore original axe ranges and hold status axis(OriginalAxis); if ~WasHold, hold off end %-- work done. good bye.
github
mainster/matlabCodes-master
icdtool.m
.m
matlabCodes-master/CUSTOM_LIBRARY/Mimotools/icdtool.m
19,918
utf_8
44e8f0f1d83bf6807bdfacc3078fd998
function varargout = icdtool(varargin) %ICDTOOL - Individual Channel Design utility for 2x2 MIMO systems % % Syntax: % icdtool(G) - Starts icdtool for G, where G is a transfer function matrix % % Example: % g11=tf(2,[1 3 2]); % g12=tf(-2,[1 1]); % g21=tf(-1,[1 2 1]); % g22=tf(6,[1 5 6]); % G=[g11 g12; g21 g22]; % % Other m-files required: nyqmimo % % Author: Oskar Vivero Osornio % email: [email protected] % Created: February 2006; % Last revision: 12-April-2006; % May be distributed freely for non-commercial use, % but please leave the above info unchanged, for % credit and feedback purposes % Last Modified by GUIDE v2.5 20-Apr-2006 00:42:51 %------------- BEGIN CODE -------------- % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @icdtool_OpeningFcn, ... 'gui_OutputFcn', @icdtool_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 icdtool is made visible. function icdtool_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 icdtool (see VARARGIN) % Determining Input ni=nargin; switch ni case 4 %Input is a matrix transfer function G=varargin{1}; end g11=G(1,1); g12=G(1,2); g21=G(2,1); g22=G(2,2); gamma=minreal((g12*g21)/(g11*g22)); setappdata(0,'hMainGui',gcf); setappdata(gcf,'G',G); setappdata(gcf,'gamma',gamma); % Choose default command line output for icdtool handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes icdtool wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = icdtool_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; function gain_K1_Callback(hObject, eventdata, handles) % hObject handle to gain_K1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of gain_K1 as text % str2double(get(hObject,'String')) returns contents of gain_K1 as a double % --- Executes during object creation, after setting all properties. function gain_K1_CreateFcn(hObject, eventdata, handles) % hObject handle to gain_K1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function poles_K1_Callback(hObject, eventdata, handles) % hObject handle to poles_K1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of poles_K1 as text % str2double(get(hObject,'String')) returns contents of poles_K1 as a double % --- Executes during object creation, after setting all properties. function poles_K1_CreateFcn(hObject, eventdata, handles) % hObject handle to poles_K1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function zeros_K1_Callback(hObject, eventdata, handles) % hObject handle to zeros_K1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of zeros_K1 as text % str2double(get(hObject,'String')) returns contents of zeros_K1 as a double % --- Executes during object creation, after setting all properties. function zeros_K1_CreateFcn(hObject, eventdata, handles) % hObject handle to zeros_K1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function gain_K2_Callback(hObject, eventdata, handles) % hObject handle to gain_K2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of gain_K2 as text % str2double(get(hObject,'String')) returns contents of gain_K2 as a double % --- Executes during object creation, after setting all properties. function gain_K2_CreateFcn(hObject, eventdata, handles) % hObject handle to gain_K2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function poles_K2_Callback(hObject, eventdata, handles) % hObject handle to poles_K2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of poles_K2 as text % str2double(get(hObject,'String')) returns contents of poles_K2 as a double % --- Executes during object creation, after setting all properties. function poles_K2_CreateFcn(hObject, eventdata, handles) % hObject handle to poles_K2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function zeros_K2_Callback(hObject, eventdata, handles) % hObject handle to zeros_K2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of zeros_K2 as text % str2double(get(hObject,'String')) returns contents of zeros_K2 as a double % --- Executes during object creation, after setting all properties. function zeros_K2_CreateFcn(hObject, eventdata, handles) % hObject handle to zeros_K2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popupmenu_C1. function popupmenu_C1_Callback(hObject, eventdata, handles) % hObject handle to popupmenu_C1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns popupmenu_C1 contents as cell array % contents{get(hObject,'Value')} returns selected item from popupmenu_C1 % Get user input from GUI % System data hMainGui = getappdata(0,'hMainGui'); G = getappdata(hMainGui,'G'); gamma = getappdata(hMainGui,'gamma'); g11 = G(1,1); g12 = G(1,2); g21 = G(2,1); g22 = G(2,2); val = get(hObject,'Value'); str = get(hObject, 'String'); figure(1) switch str{val}; case 'Nyquist of Gamma' % User selects peaks % Status window [num11,den11]=tfdata(g11,'v'); [num22,den22]=tfdata(g22,'v'); zeros11=roots(num11); zeros22=roots(num22); RHPP11=0; RHPP22=0; for i=1:length(zeros11) if sign(real(zeros(i)))==1 RHPP11=RHPP11+1; end end for i=1:length(zeros22) if sign(real(zeros22(i)))==1 RHPP22=RHPP22+1; end end s1=sprintf('%-d RHPP in g11',RHPP11); s2=sprintf('%-d RHPP in g22',RHPP22); vars{1}='RHPP of Gamma'; vars{2}=s1; vars{3}=s2; set(handles.status_window,'String',vars) % Plot syms p g=tf2sym(gamma); nyqmimo(gamma); title('Nyquist Diagram of Gamma') case 'Bode k1*g11' % User selects membrane k1=getappdata(hMainGui,'k1'); margin(k1*g11); case 'Bode h1' h1=getappdata(hMainGui,'h1'); % Status Window [num,den]=tfdata(h1,'v'); den=roots(den); RHPP=0; for i=1:length(den) if sign(real(den))==1 RHPP=RHPP+1; end end vars{1}=sprintf('%-d RHPP in h1',RHPP); set(handles.status_window,'String',vars) % Plot bode(h1); title('Bode Diagram h1') case 'Nyquist Gamma*h1' % User selects sinc h1=getappdata(hMainGui,'h1'); syms p g=tf2sym(gamma*h1); nyqmimo(gamma*h1); title('Nyquist Diagram of Gamma*h1') case 'Bode Gamma*h1' h1=getappdata(hMainGui,'h1'); margin(minreal(gamma*h1)) case 'Nyquist C1' C1=getappdata(hMainGui,'C1'); % Status Window [num,den]=tfdata(C1,'v'); den=roots(den); RHPP=0; for i=1:length(den) if sign(real(den))==1 RHPP=RHPP+1; end end vars{1}=sprintf('%-d RHPP in C1',RHPP); set(handles.status_window,'String',vars) % Plot syms p g=tf2sym(C1); nyqmimo(C1); title('Nyquist Diagram of C1') case 'Bode C1' C1=getappdata(hMainGui,'C1'); margin(C1); case 'Step of C1->R1' C1=getappdata(hMainGui,'C1'); C1cl=C1/(1+C1); step(C1cl); grid on title('Step Response of C1->R1') case 'Step of C1->R2' h2=getappdata(hMainGui,'h2'); S1=getappdata(hMainGui,'S1'); Pref1=minreal(((g12/g22)*h2)*S1); step(Pref1); grid on title('Step Response of C1->R2') end % --- Executes during object creation, after setting all properties. function popupmenu_C1_CreateFcn(hObject, eventdata, handles) % hObject handle to popupmenu_C1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popupmenu_C2. function popupmenu_C2_Callback(hObject, eventdata, handles) % hObject handle to popupmenu_C2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns popupmenu_C2 contents as cell array % contents{get(hObject,'Value')} returns selected item from popupmenu_C2 hMainGui = getappdata(0,'hMainGui'); G = getappdata(hMainGui,'G'); gamma = getappdata(hMainGui,'gamma'); g11 = G(1,1); g12 = G(1,2); g21 = G(2,1); g22 = G(2,2); val = get(hObject,'Value'); str = get(hObject, 'String'); figure(2) switch str{val}; case 'Nyquist of Gamma' % User selects peaks % Status window [num11,den11]=tfdata(g11,'v'); [num22,den22]=tfdata(g22,'v'); zeros11=roots(num11); zeros22=roots(num22); RHPP11=0; RHPP22=0; for i=1:length(zeros11) if sign(real(zeros(i)))==1 RHPP11=RHPP11+1; end end for i=1:length(zeros22) if sign(real(zeros22(i)))==1 RHPP22=RHPP22+1; end end s1=sprintf('%-d RHPP in g11',RHPP11); s2=sprintf('%-d RHPP in g22',RHPP22); vars{1}='RHPP of Gamma'; vars{2}=s1; vars{3}=s2; set(handles.status_window,'String',vars) %Plot syms p g=tf2sym(gamma); nyqmimo(gamma); title('Nyquist Diagram of Gamma') case 'Bode k2*g22' % User selects membrane k2=getappdata(hMainGui,'k2'); margin(k2*g22); case 'Bode h2' h2=getappdata(hMainGui,'h2'); % Status Window [num,den]=tfdata(h2,'v'); den=roots(den); RHPP=0; for i=1:length(den) if sign(real(den))==1 RHPP=RHPP+1; end end vars{1}=sprintf('%-d RHPP in h2',RHPP); set(handles.status_window,'String',vars) % Plot bode(h2); title('Bode Diagram h2') case 'Nyquist Gamma*h2' % User selects sinc h2=getappdata(hMainGui,'h2'); syms p g=tf2sym(gamma*h2); nyqmimo(gamma*h2); title('Nyquist Diagram of Gamma*h2') case 'Bode Gamma*h2' h2=getappdata(hMainGui,'h2'); margin(minreal(gamma*h2)) case 'Nyquist C2' C2=getappdata(hMainGui,'C2'); % Status Window [num,den]=tfdata(C2,'v'); den=roots(den); RHPP=0; for i=1:length(den) if sign(real(den))==1 RHPP=RHPP+1; end end vars{1}=sprintf('%-d RHPP in C2',RHPP); set(handles.status_window,'String',vars) % Plot syms p g=tf2sym(C2); nyqmimo(C2); title('Nyquist Diagram of C2') case 'Bode C2' C2=getappdata(hMainGui,'C2'); margin(C2); case 'Step of C2->R2' C2=getappdata(hMainGui,'C2'); C2cl=C2/(1+C2); step(C2cl); grid on title('Step response of C2->R2') case 'Step of C2->R1' h1=getappdata(hMainGui,'h1'); S2=getappdata(hMainGui,'S2'); Pref2=minreal(((g21/g11)*h1)*S2); step(Pref2); grid on title('Step response of C2->R1') end % --- Executes during object creation, after setting all properties. function popupmenu_C2_CreateFcn(hObject, eventdata, handles) % hObject handle to popupmenu_C2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in updatebutton. function updatebutton_Callback(hObject, eventdata, handles) % hObject handle to updatebutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get user input from GUI % System data hMainGui = getappdata(0,'hMainGui'); G = getappdata(hMainGui,'G'); gamma = getappdata(hMainGui,'gamma'); g11 = G(1,1); g12 = G(1,2); g21 = G(2,1); g22 = G(2,2); % K1 CONTROLLER gain_k1 = str2double(get(handles.gain_K1,'String')); poles_k1 = strread(get(handles.poles_K1,'String')); zeros_k1 = strread(get(handles.zeros_K1,'String')); % K2 CONTROLLER gain_k2 = str2double(get(handles.gain_K2,'String')); poles_k2 = strread(get(handles.poles_K2,'String')); zeros_k2 = strread(get(handles.zeros_K2,'String')); % Calculating data % C1 num_k1=poly(zeros_k1); den_k1=poly(poles_k1); k1=tf(gain_k1*num_k1,den_k1); % C2 num_k2=poly(zeros_k2); den_k2=poly(poles_k2); k2=tf(gain_k2*num_k2,den_k2); % Subsystems and channels h1=minreal((k1*g11)/(1+k1*g11)); h2=minreal((k2*g22)/(1+k2*g22)); C1=minreal((k1*g11)*(1-(gamma*h2))); C2=minreal((k2*g22)*(1-(gamma*h1))); % C1cl=C1/(1+C1); % C2cl=C2/(1+C2); % Sensibility channels S1=minreal(1/(1+C1)); T1=minreal(C1/(1+C1)); S2=minreal(1/(1+C2)); T2=minreal(C2/(1+C2)); % Exporting data setappdata(hMainGui,'k1',k1); setappdata(hMainGui,'k2',k2); setappdata(hMainGui,'h1',h1); setappdata(hMainGui,'h2',h2); setappdata(hMainGui,'C1',C1); setappdata(hMainGui,'C2',C2); setappdata(hMainGui,'S1',S1); setappdata(hMainGui,'S2',S2); setappdata(hMainGui,'T1',T1); setappdata(hMainGui,'T2',T2); % --- Executes on selection change in status_window. function status_window_Callback(hObject, eventdata, handles) % hObject handle to status_window (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns status_window contents as cell array % contents{get(hObject,'Value')} returns selected item from status_window % --- Executes during object creation, after setting all properties. function status_window_CreateFcn(hObject, eventdata, handles) % hObject handle to status_window (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
github
mainster/matlabCodes-master
LiveRecording.m
.m
matlabCodes-master/LiveRecordingWave/LiveRecording.m
10,220
utf_8
abbd8965ff6e8ea28c0d4966d99778fd
function LiveRecording %Syntax: LiveRecording % Run LiveRecording by typing "LiveRecording" in your command line % % Marcus Vollmer % alpha 13.06.2014 % Initialize and hide the GUI as it is being constructed. aud = audiodevinfo; if isempty(ver('Signal')) errordlg('Signal Processing Toolbox required','!! Error !!') elseif isempty(aud.input) errordlg('No input device found for audio recording. After plugged in you have to restart Matlab.' ,'!! Error !!') else f=figure('Visible','off','Position',[0,0,900,600],'Units','normalized','Toolbar','figure');%,'PaperSize',[20,13] hp1 = uipanel('Title','Length of record','FontSize',14,'BackgroundColor','white','Units','normalized','Position',[0.1 0.5 .6 .2],'FontUnits','normalized','visible','on'); hp2 = uipanel('Title','Display length','FontSize',14,'BackgroundColor','white','Units','normalized','Position',[0.1 0.25 .6 .2],'FontUnits','normalized','visible','on'); hp3 = uipanel('Title','Frequency window','FontSize',14,'BackgroundColor','white','Units','normalized','Position',[0.1 0.1 .25 .1],'FontUnits','normalized','visible','on'); % Construct the components. %Text htext=uicontrol('Parent',hp3,'Style','text','String','-','FontSize',10,'Units','normalized','Position',[.4,.1,.1,.6],'FontUnits','normalized','HorizontalAlignment','center'); htextHz=uicontrol('Parent',hp3,'Style','text','String','Hz','FontSize',10,'Units','normalized','Position',[.9,.1,.1,.6],'FontUnits','normalized','HorizontalAlignment','center'); %Button hbuttonStart = uicontrol('String','Start recording','FontSize',14,'Units','normalized','Position',[.75,.25,.2,.2],'FontUnits','normalized','Callback', @buttonStart_Callback); hbuttonStartAgain = uicontrol('String','new record','FontSize',10,'Units','normalized','Position',[.85,.01,.125,.05],'FontUnits','normalized','visible','off','Callback', @buttonStartAgain_Callback); hbuttonSave = uicontrol('String','save','FontSize',10,'Units','normalized','Position',[.65,.01,.1,.05],'FontUnits','normalized','visible','off','Callback', @buttonSave_Callback); hbuttonSaveAs = uicontrol('String','save as','FontSize',10,'Units','normalized','Position',[.75,.01,.1,.05],'FontUnits','normalized','visible','off','Callback', @buttonSaveAs_Callback); hbuttonPlay = uicontrol('String','play','FontSize',10,'Units','normalized','Position',[.05,.01,.1,.05],'FontUnits','normalized','visible','off','Callback', @buttonPlay_Callback); hbuttonPlayAll = uicontrol('String','play all','FontSize',10,'Units','normalized','Position',[.15,.01,.1,.05],'FontUnits','normalized','visible','off','Callback', @buttonPlayAll_Callback); hbuttonShowFigures = uicontrol('String','open figures','FontSize',10,'Units','normalized','Position',[.3,.01,.125,.05],'FontUnits','normalized','visible','off','Callback', @buttonShowFigures_Callback); %Slider hsliderRecordLength = uicontrol('Parent',hp1,'Style','slider','Min',1,'Max',30,'SliderStep',[1 1]./29,'Value',10,'Units','normalized','Position',[.1 .5 .8 .3],'FontUnits','normalized','Callback',@sliderRecordLength_Callback); hsliderShowLength = uicontrol('Parent',hp2,'Style','slider','Min',1,'Max',30,'SliderStep',[1 1]./29,'Value',5,'Units','normalized','Position',[.1 .5 .8 .3],'FontUnits','normalized','Callback',@sliderShowLength_Callback); %Edit fields heditRecordLength=uicontrol('Parent',hp1,'Style','edit','String',10,'Units','normalized','Position',[.5 .2 .4 .3],'FontUnits','normalized','Callback',@editRecordLength_Callback); heditShowLength=uicontrol('Parent',hp2,'Style','edit','String',5,'Units','normalized','Position',[.5 .2 .4 .3],'FontUnits','normalized','Callback',@editShowLength_Callback); heditFrequencyWindow1=uicontrol('Parent',hp3,'Style','edit','String',0,'Units','normalized','Position',[.1 .1 .3 .8],'FontUnits','normalized','Callback',@editFrequencyWindow1_Callback); heditFrequencyWindow2=uicontrol('Parent',hp3,'Style','edit','String',3000,'Units','normalized','Position',[.5 .1 .4 .8],'FontUnits','normalized','Callback',@editFrequencyWindow2_Callback); ha1=axes('Units','Pixels','Position',[100,300,750,250],'Units','normalized','FontUnits','normalized','Layer','top','visible','off'); ha2=axes('Units','Pixels','Position',[100,50,750,200],'Units','normalized','FontUnits','normalized','Layer','top','visible','off'); % Global variables global RecordLength ShowLength FrequencyWindow1 FrequencyWindow2 myRecording fs mag; %Initialisation RecordLength = str2double(get(heditRecordLength,'String')); ShowLength = str2double(get(heditShowLength,'String')); FrequencyWindow1 = str2double(get(heditFrequencyWindow1,'String')); FrequencyWindow2 = str2double(get(heditFrequencyWindow2,'String')); % Initialize the GUI. set(f,'Name','Audio recording and live visualisation') % Assign the GUI a name to appear in the window title. movegui(f,'center') % Move the GUI to the center of the screen. set(f,'Visible','on'); % Make the GUI visible. end %% BUTTONS % Push button callbacks. Each callback plots current_data in the % specified plot type. function buttonStart_Callback(~,~) RecordLength = str2double(get(heditRecordLength,'String')); ShowLength = str2double(get(heditShowLength,'String')); FrequencyWindow1 = str2double(get(heditFrequencyWindow1,'String')); FrequencyWindow2 = str2double(get(heditFrequencyWindow2,'String')); set(hp1,'visible','off'); set(hp2,'visible','off'); set(hp3,'visible','off'); set(ha1,'visible','on'); set(ha2,'visible','on'); set(hbuttonStart,'visible','off') set(hbuttonPlay,'visible','off') set(hbuttonPlayAll,'visible','off') set(hbuttonShowFigures,'visible','off') set(hbuttonSave,'visible','off') set(hbuttonSaveAs,'visible','off') set(hbuttonStartAgain,'visible','on') liverecording end function buttonStartAgain_Callback(~,~) set(ha1,'visible','off'); set(ha2,'visible','off'); cla(ha1) cla(ha2) set(hp1,'visible','on'); set(hp2,'visible','on'); set(hp3,'visible','on'); set(hbuttonStart,'visible','on') set(hbuttonPlay,'visible','off') set(hbuttonPlayAll,'visible','off') set(hbuttonShowFigures,'visible','off') set(hbuttonSave,'visible','off') set(hbuttonSaveAs,'visible','off') set(hbuttonStartAgain,'visible','off') end function buttonSave_Callback(~,~) [y,m,d,h,min,sec]=datevec(now); audiowrite([num2str(y,'%04.0f') num2str(m,'%02.0f') num2str(d,'%02.0f') '-' num2str(h,'%02.0f') '''' num2str(min,'%02.0f') '''''' num2str(floor(sec),'%02.0f') '.wav'],myRecording,fs); end function buttonSaveAs_Callback(~,~) [y,m,d,h,min,sec]=datevec(now); [file,path] = uiputfile([num2str(y,'%04.0f') num2str(m,'%02.0f') num2str(d,'%02.0f') '-' num2str(h,'%02.0f') '''' num2str(min,'%02.0f') '''''' num2str(floor(sec),'%02.0f') '.wav'],'Save record'); audiowrite([path file],myRecording,fs); end function buttonPlay_Callback(~,~) xx = round(get(ha1,'Xlim')*fs); sound(myRecording(max(1,xx(1)):min(xx(2),size(myRecording,1))), fs); end function buttonPlayAll_Callback(~,~) sound(myRecording, fs); end function buttonShowFigures_Callback(~,~) figure plot((1:size(myRecording,1))./fs,myRecording) ylim([-1.2 1.2]*mag) xlim([0 max(size(myRecording,1)/fs,ShowLength)]) figure spectrogram(myRecording,2^9,2^7,2^12,fs) xlim([FrequencyWindow1 FrequencyWindow2]) view(-90,90) set(gca,'ydir','reverse') set(gca, 'YTick', []); ylim([0 max(size(myRecording,1)/fs,ShowLength)]) end %% EDITFIELDS function editRecordLength_Callback(~,~) RecordLength = str2double(get(heditRecordLength,'String')); set(hsliderRecordLength,'value',RecordLength); end function editShowLength_Callback(~,~) ShowLength = str2double(get(heditShowLength,'String')); set(hsliderShowLength,'value',ShowLength); end function editFrequencyWindow1_Callback(~,~) FrequencyWindow1 = str2double(get(heditFrequencyWindow1,'String')); end function editFrequencyWindow2_Callback(~,~) FrequencyWindow2 = str2double(get(heditFrequencyWindow2,'String')); end %% SLIDER function sliderRecordLength_Callback(~,~) RecordLength = round(get(hsliderRecordLength,'value')); set(heditRecordLength,'string',num2str(RecordLength)); end function sliderShowLength_Callback(~,~) ShowLength = round(get(hsliderShowLength,'value')); set(heditShowLength,'string',num2str(ShowLength)); end %% GENERAL FUNCTIONS function liverecording fs = 44100; nBits = 16; mag = 1.05; plot(ha1,0,0); ylim(ha1,[-mag mag]) xlim(ha1,[0 RecordLength]) xlabel(ha1,'Time [s]') idx_last = 1; recObj = audiorecorder(fs,nBits,1); record(recObj,RecordLength); tic while toc<.1 end tic bit = 2; while toc<RecordLength myRecording = getaudiodata(recObj); idx = round(toc*fs); while idx-idx_last<.1*fs idx = round(toc*fs); end plot(ha1,(max(1,size(myRecording,1)-fs*ShowLength):(2^bit):size(myRecording,1))./fs,myRecording(max(1,size(myRecording,1)-fs*ShowLength):(2^bit):end)) mag = max(abs(myRecording)); ylim(ha1,[-1.2 1.2]*mag) xlim(ha1,[max(0,size(myRecording,1)/fs-ShowLength) max(size(myRecording,1)/fs,ShowLength)]) spectrogram(myRecording(max(1,size(myRecording,1)-fs*ShowLength):(2^bit):end),2^9/(2^bit),2^7/(2^bit),2^12/(2^bit),fs/(2^bit)) xlim(ha2,[FrequencyWindow1 FrequencyWindow2]) ylim(ha2,[0 ShowLength]) view(ha2,-90,90) set(gca,'ydir','reverse') set(gca, 'YTick', []); drawnow idx_last = idx; end endrecording end function endrecording set(hbuttonPlay,'visible','on') set(hbuttonPlayAll,'visible','on') set(hbuttonShowFigures,'visible','on') set(hbuttonSave,'visible','on') set(hbuttonSaveAs,'visible','on') end end
github
terejanu/AdaptiveGaussianSumFilter-master
error_ellipse.m
.m
AdaptiveGaussianSumFilter-master/error_ellipse.m
8,394
utf_8
89c9afde8aeb5b09c8a1fa777a9a8b9b
function h=error_ellipse(varargin) % ERROR_ELLIPSE - plot an error ellipse, or ellipsoid, defining confidence region % ERROR_ELLIPSE(C22) - Given a 2x2 covariance matrix, plot the % associated error ellipse, at the origin. It returns a graphics handle % of the ellipse that was drawn. % % ERROR_ELLIPSE(C33) - Given a 3x3 covariance matrix, plot the % associated error ellipsoid, at the origin, as well as its projections % onto the three axes. Returns a vector of 4 graphics handles, for the % three ellipses (in the X-Y, Y-Z, and Z-X planes, respectively) and for % the ellipsoid. % % ERROR_ELLIPSE(C,MU) - Plot the ellipse, or ellipsoid, centered at MU, % a vector whose length should match that of C (which is 2x2 or 3x3). % % ERROR_ELLIPSE(...,'Property1',Value1,'Name2',Value2,...) sets the % values of specified properties, including: % 'C' - Alternate method of specifying the covariance matrix % 'mu' - Alternate method of specifying the ellipse (-oid) center % 'conf' - A value betwen 0 and 1 specifying the confidence interval. % the default is .5 which is the 50% error ellipse. % 'scale' - Allow the plot the be scaled to difference units. % 'style' - A plotting style used to format ellipses. % 'clip' - specifies a clipping radius. Portions of the ellipse, -oid, % outside the radius will not be shown. % % NOTES: C must be positive definite for this function to work properly. default_properties = struct(... 'C', [], ... % The covaraince matrix (required) 'mu', [], ... % Center of ellipse (optional) 'conf', .5, ... % Percent confidence/100 'scale', 1, ... % Scale factor, e.g. 1e-3 to plot m as km 'style', '', ... % Plot style 'clip', inf); % Clipping radius if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.C = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.mu = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.conf = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.scale = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & ~ischar(varargin{1}) error('Invalid parameter/value pair arguments.') end prop = getopt(default_properties, varargin{:}); C = prop.C; if isempty(prop.mu) mu = zeros(length(C),1); else mu = prop.mu; end conf = prop.conf; scale = prop.scale; style = prop.style; if conf <= 0 | conf >= 1 error('conf parameter must be in range 0 to 1, exclusive') end [r,c] = size(C); if r ~= c | (r ~= 2 & r ~= 3) error(['Don''t know what to do with ',num2str(r),'x',num2str(c),' matrix']) end x0=mu(1); y0=mu(2); % Compute quantile for the desired percentile %k = sqrt(qchisq(conf,r)); % r is the number of dimensions (degrees of freedom) %%%%%%%%%%%%%%%% k = 1; % GT %%%%%%%%%%%%%%%%% hold_state = get(gca,'nextplot'); if r==3 & c==3 z0=mu(3); % Make the matrix has positive eigenvalues - else it's not a valid covariance matrix! if any(eig(C) <=0) error('The covariance matrix must be positive definite (it has non-positive eigenvalues)') end % C is 3x3; extract the 2x2 matricies, and plot the associated error % ellipses. They are drawn in space, around the ellipsoid; it may be % preferable to draw them on the axes. Cxy = C(1:2,1:2); Cyz = C(2:3,2:3); Czx = C([3 1],[3 1]); [x,y,z] = getpoints(Cxy,prop.clip); h1=plot3(x0+k*x,y0+k*y,z0+k*z,prop.style);hold on [y,z,x] = getpoints(Cyz,prop.clip); h2=plot3(x0+k*x,y0+k*y,z0+k*z,prop.style);hold on [z,x,y] = getpoints(Czx,prop.clip); h3=plot3(x0+k*x,y0+k*y,z0+k*z,prop.style);hold on [eigvec,eigval] = eig(C); [X,Y,Z] = ellipsoid(0,0,0,1,1,1); XYZ = [X(:),Y(:),Z(:)]*sqrt(eigval)*eigvec'; X(:) = scale*(k*XYZ(:,1)+x0); Y(:) = scale*(k*XYZ(:,2)+y0); Z(:) = scale*(k*XYZ(:,3)+z0); h4=surf(X,Y,Z); colormap gray alpha(0.3) camlight if nargout h=[h1 h2 h3 h4]; end elseif r==2 & c==2 % Make the matrix has positive eigenvalues - else it's not a valid covariance matrix! if any(eig(C) <=0) error('The covariance matrix must be positive definite (it has non-positive eigenvalues)') end [x,y,z] = getpoints(C,prop.clip); h1=plot(scale*(x0+k*x),scale*(y0+k*y),prop.style); set(h1,'zdata',z+1) if nargout h=h1; end else error('C (covaraince matrix) must be specified as a 2x2 or 3x3 matrix)') end %axis equal set(gca,'nextplot',hold_state); %--------------------------------------------------------------- % getpoints - Generate x and y points that define an ellipse, given a 2x2 % covariance matrix, C. z, if requested, is all zeros with same shape as % x and y. function [x,y,z] = getpoints(C,clipping_radius) n=100; % Number of points around ellipse p=0:pi/n:2*pi; % angles around a circle [eigvec,eigval] = eig(C); % Compute eigen-stuff xy = [cos(p'),sin(p')] * sqrt(eigval) * eigvec'; % Transformation x = xy(:,1); y = xy(:,2); z = zeros(size(x)); % Clip data to a bounding radius if nargin >= 2 r = sqrt(sum(xy.^2,2)); % Euclidian distance (distance from center) x(r > clipping_radius) = nan; y(r > clipping_radius) = nan; z(r > clipping_radius) = nan; end %--------------------------------------------------------------- function x=qchisq(P,n) % QCHISQ(P,N) - quantile of the chi-square distribution. if nargin<2 n=1; end s0 = P==0; s1 = P==1; s = P>0 & P<1; x = 0.5*ones(size(P)); x(s0) = -inf; x(s1) = inf; x(~(s0|s1|s))=nan; for ii=1:14 dx = -(pchisq(x(s),n)-P(s))./dchisq(x(s),n); x(s) = x(s)+dx; if all(abs(dx) < 1e-6) break; end end %--------------------------------------------------------------- function F=pchisq(x,n) % PCHISQ(X,N) - Probability function of the chi-square distribution. if nargin<2 n=1; end F=zeros(size(x)); if rem(n,2) == 0 s = x>0; k = 0; for jj = 0:n/2-1; k = k + (x(s)/2).^jj/factorial(jj); end F(s) = 1-exp(-x(s)/2).*k; else for ii=1:numel(x) if x(ii) > 0 F(ii) = quadl(@dchisq,0,x(ii),1e-6,0,n); else F(ii) = 0; end end end %--------------------------------------------------------------- function f=dchisq(x,n) % DCHISQ(X,N) - Density function of the chi-square distribution. if nargin<2 n=1; end f=zeros(size(x)); s = x>=0; f(s) = x(s).^(n/2-1).*exp(-x(s)/2)./(2^(n/2)*gamma(n/2)); %--------------------------------------------------------------- function properties = getopt(properties,varargin) %GETOPT - Process paired optional arguments as 'prop1',val1,'prop2',val2,... % % getopt(properties,varargin) returns a modified properties structure, % given an initial properties structure, and a list of paired arguments. % Each argumnet pair should be of the form property_name,val where % property_name is the name of one of the field in properties, and val is % the value to be assigned to that structure field. % % No validation of the values is performed. % % EXAMPLE: % properties = struct('zoom',1.0,'aspect',1.0,'gamma',1.0,'file',[],'bg',[]); % properties = getopt(properties,'aspect',0.76,'file','mydata.dat') % would return: % properties = % zoom: 1 % aspect: 0.7600 % gamma: 1 % file: 'mydata.dat' % bg: [] % % Typical usage in a function: % properties = getopt(properties,varargin{:}) % Process the properties (optional input arguments) prop_names = fieldnames(properties); TargetField = []; for ii=1:length(varargin) arg = varargin{ii}; if isempty(TargetField) if ~ischar(arg) error('Propery names must be character strings'); end f = find(strcmp(prop_names, arg)); if length(f) == 0 error('%s ',['invalid property ''',arg,'''; must be one of:'],prop_names{:}); end TargetField = arg; else % properties.(TargetField) = arg; % Ver 6.5 and later only properties = setfield(properties, TargetField, arg); % Ver 6.1 friendly TargetField = ''; end end if ~isempty(TargetField) error('Property names and values must be specified in pairs.'); end
github
masumhabib/quest-master
importBandResult.m
.m
quest-master/utils/matlab/importBandResult.m
899
utf_8
7ff4feab1a9082e50da7c2b663fd9af9
% % Copyright (C) 2014 K M Masum Habib <[email protected]> % function out = importBandResult(fileName) fid = fopen(fileName, 'rt'); out = []; while (~feof(fid)) type = fscanf(fid, '%s[^\n]'); if strfind(type, 'EK') == 1 out.EK = scan(); elseif strfind(type, 'EIGENVECTOR') == 1 out.DOS = scan(); end end fclose(fid); function M = scan() Nk = fscanf(fid, '%d[^\n]'); data = fscanf(fid, '%d %d[^\n]'); m = data(1); n = data(2); for ik = 1:Nk M.k(ik,:) = fscanf(fid, '%f %f %f[^\n]'); M.M{ik} = zeros(m,n); for ii = 1:m for jj = 1:n data = fscanf(fid, '%*[ \n\t]%e', 1); M.M{ik}(ii,jj) = data(1); end end end end end
github
masumhabib/quest-master
importTransResult.m
.m
quest-master/utils/matlab/importTransResult.m
1,603
utf_8
fcadd5373709cc91cec1eed7e966bb96
% % Copyright (C) 2014 K M Masum Habib <[email protected]> % function out = importTransResult(fileName) fid = fopen(fileName, 'rt'); out = []; ibIE = 1; ibn = 1; ibneq = 1; while (~feof(fid)) type = fscanf(fid, '%s[^\n]'); if strfind(type, 'ENERGY') == 1 [out.NE, out.E] = scanE(); elseif strfind(type, 'TRANSMISSION') == 1 out.TE = scan(); elseif strfind(type, 'CURRENT') == 1 out.IE{ibIE} = scan(); ibIE = ibIE + 1; elseif strfind(type, 'DOS') == 1 out.DOS = scan(); elseif strfind(type, 'n') == 1 out.n{ibn} = scan(); ibn = ibn + 1; elseif strfind(type, 'neq') == 1 out.neq{ibneq} = scan(); ibneq = ibneq + 1; end end fclose(fid); function M = scan() NE = fscanf(fid, '%d[^\n]'); %M.NE = NE; tmp = fscanf(fid, '%d %d[^\n]'); M.ib = tmp(1); M.jb = tmp(2); N = fscanf(fid, '%d[^\n]'); %M.N = N; for iE = 1:NE %M.E(iE) = fscanf(fid, '%f[^\n]'); M.M{iE} = zeros(N,N); for ii = 1:N for jj = 1:N data = fscanf(fid, '%*[ \n\t](%e,%e)', 2); M.M{iE}(ii,jj) = data(1) + 1i*data(2); end end end end function [NE, EE] = scanE() NE = fscanf(fid, '%d[^\n]'); EE = zeros(NE, 1); for iE = 1:NE EE(iE) = fscanf(fid, '%f[^\n]'); end end end
github
masumhabib/quest-master
importPotential.m
.m
quest-master/utils/matlab/importPotential.m
334
utf_8
bcd8483c35f0173a6b1605c72bd0258f
% % Copyright (C) 2014 K M Masum Habib <[email protected]> % function [X, Y, Z, V] = importPotential(fileName) fid = fopen(fileName, 'rt'); X = []; Y = []; Z = []; V = []; data = load(fileName); X = data(:,1); Y = data(:,2); Z = data(:,3); V = data(:,4); fclose(fid); end
github
NYU-DiffusionMRI/mppca_denoise-master
MPdenoising.m
.m
mppca_denoise-master/MPdenoising.m
8,173
utf_8
e486f43bc82b9c4a0ebf3bd3a095b504
function [Signal, Sigma] = MPdenoising(data, mask, kernel, sampling, centering) % % "MPPCA": 4d image denoising and noise map estimation by exploiting data redundancy in the PCA domain using universal properties of the eigenspectrum of % random covariance matrices, i.e. Marchenko Pastur distribution % % [Signal, Sigma] = MPdenoising(data, mask, kernel, sampling) % output: % - Signal: [x, y, z, M] denoised data matrix % - Sigma: [x, y, z] noise map % input: % - data: [x, y, z, M] data matrix % - mask: (optional) region-of-interest [boolean] % - kernel: (optional) window size, typically in order of [5 x 5 x 5] % - sampling: % 1. full: sliding window (default for noise map estimation, i.e. [Signal, Sigma] = MPdenoising(...) ) % 2. fast: block processing (default for denoising, i.e. [Signal] = MPdenoising(...)) % % Authors: Jelle Veraart ([email protected]) % Copyright (c) 2016 New York Universit and University of Antwerp % % Permission is hereby granted, free of charge, to any non-commercial entity % ('Recipient') obtaining a copy of this software and associated % documentation files (the 'Software'), to the Software solely for % non-commercial research, including the rights to use, copy and modify the % Software, subject to the following conditions: % % 1. The above copyright notice and this permission notice shall be % included by Recipient in all copies or substantial portions of the % Software. % % 2. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIESOF % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN % NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, % DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR % OTHERWISE, ARISING FROM, OUT OF ORIN CONNECTION WITH THE SOFTWARE OR THE % USE OR OTHER DEALINGS IN THE SOFTWARE. % % 3. In no event shall NYU be liable for direct, indirect, special, % incidental or consequential damages in connection with the Software. % Recipient will defend, indemnify and hold NYU harmless from any claims or % liability resulting from the use of the Software by recipient. % % 4. Neither anything contained herein nor the delivery of the Software to % recipient shall be deemed to grant the Recipient any right or licenses % under any patents or patent application owned by NYU. % % 5. The Software may only be used for non-commercial research and may not % be used for clinical care. % % 6. Any publication by Recipient of research involving the Software shall % cite the references listed below. % % REFERENCES % Veraart, J.; Fieremans, E. & Novikov, D.S. Diffusion MRI noise mapping % using random matrix theory Magn. Res. Med., 2016, early view, doi: % 10.1002/mrm.26059 if isa(data,'integer') data = single(data); end [sx, sy, sz, M] = size(data); if ~exist('mask', 'var') || isempty(mask) mask = true([sx, sy, sz]); end if ~isa(mask,'boolean') mask = mask>0; end if ~exist('kernel', 'var') || isempty(kernel) kernel = [5 5 5]; end if isscalar(kernel) kernel = [kernel, kernel, kernel]; end kernel = kernel + (mod(kernel, 2)-1); % needs to be odd. k = (kernel-1)/2; kx = k(1); ky = k(2); kz = k(3); N = prod(kernel); if ~exist('sampling', 'var') || isempty(sampling) if nargout > 1 sampling = 'full'; else sampling = 'fast'; end end % create mask if ~exist('mask', 'var') || isempty(mask) mask = true(sx, sy, sz); end if ~exist('centering', 'var') || isempty(centering) centering = false; end if strcmp(sampling, 'fast') if nargout>1 warning('undersampled noise map will be returned') end % compute center points of patches stats = regionprops(mask, 'BoundingBox'); n = ceil(stats.BoundingBox(4:6) ./ kernel); x = linspace(ceil(stats.BoundingBox(1))+k(1), floor(stats.BoundingBox(1))-k(1) + stats.BoundingBox(4), n(1)); x = round(x); y = linspace(ceil(stats.BoundingBox(2))+k(2), floor(stats.BoundingBox(2))-k(2) + stats.BoundingBox(5), n(2)); y = round(y); z = linspace(ceil(stats.BoundingBox(3))+k(3), floor(stats.BoundingBox(3))-k(3) + stats.BoundingBox(6), n(3)); z = round(z); [y, x, z] = meshgrid(x, y, z); x = x(:); y = y(:); z = z(:); end if strcmp(sampling, 'full') warning('image bounderies are not processed.') mask(1:k(1), :, :) = 0; mask(sx-k(1)+1:sx, :, :) = 0; mask(:, 1:k(2), :) = 0; mask(:, sy-k(2)+1:sy, :, :) = 0; mask(:,:,1:k(3)) = 0; mask(:,:,sz-k(3)+1:sz) = 0; x = []; y = []; z = []; for i = k(3)+1:sz-k(3) [x_, y_] = find(mask(:,:,i) == 1); x = [x; x_]; y = [y; y_]; z = [z; i*ones(size(y_))]; end x = x(:); y = y(:); z = z(:); end % Declare variables: sigma = zeros(1, numel(x), 'like', data); npars = zeros(1, numel(x), 'like', data); signal = zeros(M, prod(kernel), numel(x), 'like', data); Sigma = zeros(sx, sy, sz, 'like', data); Npars = zeros(sx, sy, sz, 'like', data); Signal = zeros(sx, sy, sz, M, 'like', data); % compute scaling factor for in case N<M R = min(M, N); scaling = (max(M, N) - (0:R-centering-1)) / N; scaling = scaling(:); % start denoising for nn = 1:numel(x) % create data matrix X = data(x(nn)-kx:x(nn)+kx, y(nn)-ky:y(nn)+ky, z(nn)-kz:z(nn)+kz, :); X = reshape(X, N, M); X = X'; if centering colmean = mean(X, 1); X = X - repmat(colmean, [M, 1]); end % compute PCA eigenvalues [u, vals, v] = svd(X, 'econ'); vals = diag(vals).^2 / N; % First estimation of Sigma^2; Eq 1 from ISMRM presentation csum = cumsum(vals(R-centering:-1:1)); cmean = csum(R-centering:-1:1)./(R-centering:-1:1)'; sigmasq_1 = cmean./scaling; % Second estimation of Sigma^2; Eq 2 from ISMRM presentation gamma = (M - (0:R-centering-1)) / N; rangeMP = 4*sqrt(gamma(:)); rangeData = vals(1:R-centering) - vals(R-centering); sigmasq_2 = rangeData./rangeMP; % sigmasq_2 > sigma_sq1 if signal-components are represented in the % eigenvalues t = find(sigmasq_2 < sigmasq_1, 1); if isempty(t) sigma(nn) = NaN; signal(:, :, nn) = X; t = R+1; else sigma(nn) = sqrt(sigmasq_1(t)); vals(t:R) = 0; s = u*diag(sqrt(N*vals))*v'; if centering s = s + repmat(colmean, [M, 1]); end signal(:, :, nn) = s; end npars(nn) = t-1; end for nn = 1:numel(x) Sigma(x(nn), y(nn), z(nn)) = sigma(nn); Npars(x(nn), y(nn), z(nn)) = npars(nn); if strcmp(sampling, 'fast') Signal(x(nn)-k(1):x(nn)+k(1),y(nn)-k(2):y(nn)+k(2),z(nn)-k(3):z(nn)+k(3), :) = unpatch(signal(:,:,nn), k); elseif strcmp(sampling, 'full') Signal(x(nn), y(nn),z(nn), :) = signal(:,ceil(prod(kernel)/ 2),nn); end end end function data = unpatch(X, k) kernel=k+k+1; data = zeros([kernel, size(X, 1)]); tmp = zeros(kernel); for i = 1:size(X, 1); tmp(:) = X(i, :); data(:,:,:,i) = tmp; end end
github
NYU-DiffusionMRI/mppca_denoise-master
MP.m
.m
mppca_denoise-master/MP.m
5,946
utf_8
3b5355d0743ba9e04980fb6755227d1d
function [Xdn, sigma, npars] = MP(X, nbins, centering) % "MP": matrix denoising and noiseestimation by exploiting data redundancy in the PCA domain using universal properties of the eigenspectrum of % random covariance matrices, i.e. Marchenko Pastur distribution % % [Xdn, Sigma, npars] = MP(X, nbins) % output: % - Xdn: [MxN] denoised data matrix % - sigma: [1x1] noise level % - npars: [1x1] number of significant components % input: % - X: [MxN] data matrix % - nbins: number of histogram bins for visualization. If % empty or not provided, no graphs will be shown. % % Author: Jelle Veraart ([email protected]) % Copyright (c) 2016 New York University % % Permission is hereby granted, free of charge, to any non-commercial entity % ('Recipient') obtaining a copy of this software and associated % documentation files (the 'Software'), to the Software solely for % non-commercial research, including the rights to use, copy and modify the % Software, subject to the following conditions: % % 1. The above copyright notice and this permission notice shall be % included by Recipient in all copies or substantial portions of the % Software. % % 2. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIESOF % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN % NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, % DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR % OTHERWISE, ARISING FROM, OUT OF ORIN CONNECTION WITH THE SOFTWARE OR THE % USE OR OTHER DEALINGS IN THE SOFTWARE. % % 3. In no event shall NYU be liable for direct, indirect, special, % incidental or consequential damages in connection with the Software. % Recipient will defend, indemnify and hold NYU harmless from any claims or % liability resulting from the use of the Software by recipient. % % 4. Neither anything contained herein nor the delivery of the Software to % recipient shall be deemed to grant the Recipient any right or licenses % under any patents or patent application owned by NYU. % % 5. The Software may only be used for non-commercial research and may not % be used for clinical care. % % 6. Any publication by Recipient of research involving the Software shall % cite the references listed below. % % REFERENCES % Veraart, J.; Fieremans, E. & Novikov, D.S. Diffusion MRI noise mapping % using random matrix theory Magn. Res. Med., 2016, early view, doi: % 10.1002/mrm.26059 % Veraart, J.; Novikov, D.S.; Christiaens, D.; Ades-Aron, B.; Sijbers, J. & Fieremans, E. % Denoising of diffusion MRI using random matrix theory, NeuroImage, Magn. Res. Med., 2016, early view, % DOI: 10.1016/j.neuroimage.2016.08.016 if ~exist('nbins', 'var') || isempty(nbins) nbins=0; end [M, N] = size(X); if ~exist('centering', 'var') || isempty(centering) centering = false; end if centering colmean = mean(X, 1); X = X - repmat(colmean, [M, 1]); end R = min(M, N); scaling = ones(R-centering, 1); if M>N %scaling = M/N; scaling = (M - (0:R-centering-1)) / N; scaling(scaling<1) = 1; scaling = scaling(:); end [u, vals, v] = svd(X, 'econ'); vals = diag(vals).^2 / N; csum = cumsum(vals(R-centering:-1:1)); cmean = csum(R-centering:-1:1)./(R-centering:-1:1)'; sigmasq_1 = cmean./scaling; gamma = (M - (0:R-centering-1)) / N; rangeMP = 4*sqrt(gamma(:)); rangeData = vals(1:R-centering) - vals(R-centering); sigmasq_2 = rangeData./rangeMP; t = find(sigmasq_2 < sigmasq_1, 1); sigma = sqrt(sigmasq_1(t)); npars = t-1; if nbins>0 [~, range] = MarchenkoPasturDistribution(rand(), sigma, M-npars, N); [p, ~] = MarchenkoPasturDistribution([range(1):diff(range)/100:range(2)], sigma, M-npars, N); figure; hold on range_ = [vals(R-centering), vals(npars+1)]; binwidth = diff(range_)/nbins; % Finds the width of each bin. scale = M * binwidth; x = histc(vals(1:R-centering), [range_(1):diff(range_)/(nbins-1):range_(2)]); bar([range_(1):diff(range_)/(nbins-1):range_(2)], x/nansum(p)) plot([range(1):diff(range)/100:range(2)], real(p)*scale/nansum(p), 'r', 'LineWidth', 3) xlabel('$\lambda$', 'FontName', 'Times', 'FontSize', 20, 'Interpreter', 'Latex') ylabel('$p(\lambda$)', 'FontName', 'Times', 'FontSize', 20, 'Interpreter', 'Latex') set(gca, 'FontSize', 20, 'box', 'on', 'LineWidth', 2, 'FontSize', 20); title(['sigma = ', num2str(sigma), ' and npars = ', num2str(npars)]) end vals(t:R) = 0; Xdn = u*diag(sqrt(N*vals))*v'; if centering Xdn = Xdn + repmat(colmean, [M, 1]); end end function [p, range] = MarchenkoPasturDistribution(lambda, sigma, M, N) Q = M/N; lambda_p = sigma^2*(1 + sqrt(Q)).^2; lambda_m = sigma^2*(1 - sqrt(Q)).^2; p = sqrt((lambda_p - lambda).*(lambda-lambda_m))./(2*pi*Q*lambda*sigma.^2); p(lambda < lambda_m) = 0; p(lambda > lambda_p) = 0; range = [lambda_m, lambda_p]; end
github
NYU-DiffusionMRI/mppca_denoise-master
MPnonlocal.m
.m
mppca_denoise-master/MPnonlocal.m
12,883
utf_8
9df62ed192b176dcf7fa65ac94b73ddb
function [Signal, varargout] = MPnonlocal(data, varargin) % MPnonlocal Denoise 4d magnitude data (x, y, z, dirs) or 5d complex data % (x, y, z, coils, dirs) and estimate 3d noise maps and significant % parameter maps using nonlocal patching and eigenvalue shrinkage in % the MPPCA framework % % [Signal, Sigma, Nparams] = MPnonlocal(data, kernel, patchsize, norm) % output: % - Signal: [x, y, z, N] for 4d (real or complex) [x, y, z, C, N] for 5d % (complex) % - Sigma: [x, y, z] noise map % - Npars: [x, y, z] map of the number of signal carrying % components % - Sigma_after: [x, y, z] noise map (sigma after denoiosing) estimated using Jespersen et al % method % input: % - data: [x, y, z, N] for 4d (real or complex) [x, y, z, C, N] for 5d % (complex) % - kernel: (optional) default smallest isotropic box window where prod(kernel) > n volumes. Must be odd. % - patchtype: (optional) default is 'box'. Can alternatively be % set to 'nonlocal' % - patchsize: (optional) Number of voxels to include in nonlocal % patch. For nonlocal denoising only. n volumes < patch size < % prod(kernel). If it is not set a default option of a nonlocal % patch 20% smaller than prod(kernel) will be used. % - shrink: (optional) default 'threshold'. Can be set to 'threshold' for hard % thresholding of eigenvalues or 'frob' to implement eigenvalue % shrinkage using the frobenius norm. % - exp: (optional) default is 1. Options are 1, 2 and 3 % correspoinding to Veraart 2016, Cordero-Grande, and the % "in-between method" respectively. % % usage: % - box patch denoising: % [Signal, Sigma, Npars] = MPnonlocal(data, [5,5,5]) % - shrinkage denoisng: % [Signal, Sigma, Npars] = MPnonlocal(data, [5,5,5], 'patchtype','box','shrink','frob') % - nonlocal denoisng: % [Signal, Sigma, Npars] = MPnonlocal(data, [5,5,5], 'patchtype','nonlocal','patchsize',100) % % Authors: Benjamin Ades-Aron ([email protected]) % Jelle Veraart ([email protected]) % Gregory Lemberskiy ([email protected]) % Copyright (c) 2020 New York University % % Permission is hereby granted, free of charge, to any non-commercial entity % ('Recipient') obtaining a copy of this software and associated % documentation files (the 'Software'), to the Software solely for % non-commercial research, including the rights to use, copy and modify the % Software, subject to the following conditions: % % 1. The above copyright notice and this permission notice shall be % included by Recipient in all copies or substantial portions of the % Software. % % 2. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIESOF % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN % NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, % DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR % OTHERWISE, ARISING FROM, OUT OF ORIN CONNECTION WITH THE SOFTWARE OR THE % USE OR OTHER DEALINGS IN THE SOFTWARE. % % 3. In no event shall NYU be liable for direct, indirect, special, % incidental or consequential damages in connection with the Software. % Recipient will defend, indemnify and hold NYU harmless from any claims or % liability resulting from the use of the Software by recipient. % % 4. Neither anything contained herein nor the delivery of the Software to % recipient shall be deemed to grant the Recipient any right or licenses % under any patents or patent application owned by NYU. % % 5. The Software may only be used for non-commercial research and may not % be used for clinical care. % % 6. Any publication by Recipient of research involving the Software shall % cite the references listed below. % % REFERENCES % Veraart, J.; Fieremans, E. & Novikov, D.S. Diffusion MRI noise mapping % using random matrix theory Magn. Res. Med., 2016, early view, doi: % 10.1002/mrm.26059 % set defaults if isreal(data) data = single(data); else data = complex(single(data)); end if ndims(data) > 4 coil = true; else coil = false; end defaultShrink = 'threshold'; defaultExp = 1; nvols = size(data, ndims(data)); p_ = (1:2:nvols); pf_ = find(p_.^3 >= nvols, 1); defaultKernel = p_(pf_); defaultPatchtype = 'box'; defaultPatchsize = defaultKernel^3; defaultCrop = 0; % parse input arguments p = inputParser; addRequired(p,'data'); addOptional(p,'kernel', defaultKernel); addOptional(p,'patchtype', defaultPatchtype); addOptional(p,'patchsize', defaultPatchsize); addOptional(p,'shrink', defaultShrink); addOptional(p,'exp', defaultExp); addOptional(p,'crop',defaultCrop); parse(p, data, varargin{:}); if isscalar(p.Results.kernel) kernel = [p.Results.kernel, p.Results.kernel, p.Results.kernel]; else kernel = p.Results.kernel; end kernel = kernel + (mod(kernel, 2)-1); if any(kernel > [size(data,1),size(data,2),size(data,3)]) error(['kernel size of ',num2str(kernel), ' exceeds data size along dimention ',... num2str(find(kernel>size(data,[1,2,3]))),', specify a smaller kernel extent']); end if strcmp(p.Results.patchtype,'box') psize = prod(kernel); nonlocal = false; center_idx = ceil(prod(kernel)/2); pos_img = []; elseif strcmp(p.Results.patchtype,'nonlocal') if p.Results.patchsize >= prod(kernel) warning('selecting sane default nonlocal patch size') psize = floor(prod(kernel) - 0.2*prod(kernel)); if psize <= nvols psize = nvols + 1; end else psize = p.Results.patchsize; end nonlocal = true; center_idx = 1; else error('patchtype options are "box" or "nonlocal"'); end nrm = p.Results.shrink; exp = p.Results.exp; cropdist = p.Results.crop; if p.Results.patchsize ~= prod(kernel) && strcmp(p.Results.patchtype,'box') warning('patchsize argument does not affect box kernel'); end disp('Denoising data using parameters:') disp(['kernel = [',num2str(kernel),']']) disp(['patch type = ',p.Results.patchtype]); disp(['patch size = ',num2str(psize)]); disp(['shrinkage = ',p.Results.shrink]); disp(['algorithm = ',num2str(exp)]); disp(['cropdist = ',num2str(cropdist)]); % begin processing here k = (kernel-1)/2; kx = k(1); ky = k(2); kz = k(3); % pad the data in first 3 dimentions if coil data = padarray(data, [kx, ky, kz, 0, 0], 'circular'); [sx, sy, sz, sc, N] = size(data); M = psize*sc; else data = padarray(data, [kx, ky, kz, 0], 'circular'); [sx, sy, sz, N] = size(data); M = psize; sc = 1; end % define a mask that excludes padded values and extract coordinates [x,y,z] = get_voxel_coords(sx,sy,sz,kx,ky,kz); if nonlocal [pi, pj, pk] = ind2sub(kernel, find(ones(kernel))); patchcoords = cat(2,pi,pj,pk); pos_img = 1/prod(kernel) * sum((patchcoords - ceil(kernel/2)).^2, 2); end % Declare variables: sigma = zeros(1, numel(x), 'like', data); sigma_after = zeros(1, numel(x), 'like', data); npars = zeros(1, numel(x), 'like', data); Sigma = zeros(sx, sy, sz, 'like', data); Sigma_after = zeros(sx, sy, sz, 'like', data); Npars = zeros(sx, sy, sz, 'like', data); if coil signal = zeros(sc, N, numel(x), 'like', data); Signal = zeros(sx, sy, sz, sc, N, 'like', data); else signal = zeros(1, N, numel(x), 'like', data); Signal = zeros(sx, sy, sz, N, 'like', data); end % start denoising %xi = floor(4*length(x)/7); parfor nn = 1:numel(x) X = data(x(nn)-kx:x(nn)+kx, y(nn)-ky:y(nn)+ky, z(nn)-kz:z(nn)+kz, :, :); if coil X = reshape(X, prod(kernel), sc, N); else X = reshape(X, prod(kernel), N); end if nonlocal Xn = normalize(X); min_idx = refine_patch(Xn, kernel, psize, pos_img, coil); X = X(min_idx,:,:); end X = reshape(X,[M, N]); [s, sigma(nn), npars(nn), sigma_after(nn)] = denoise(X, nrm, exp, cropdist); if coil signal(:,:,nn) = s(center_idx:psize:end,:); else signal(:,:,nn) = s(center_idx,:); end end for nn = 1:numel(x) Sigma(x(nn), y(nn), z(nn)) = sigma(nn); Sigma_after(x(nn), y(nn), z(nn)) = sigma_after(nn); Npars(x(nn), y(nn), z(nn)) = npars(nn); Signal(x(nn), y(nn),z(nn), :, :) = signal(:,:,nn); end Sigma = unpad(Sigma,kernel); Sigma_after = unpad(Sigma_after,kernel); Npars = unpad(Npars,kernel); Signal = unpad(Signal,kernel); varargout{1} = Sigma; varargout{2} = Npars; varargout{3} = Sigma_after; end function [min_idx] = refine_patch(data, kernel, M, pos_img, coil) refval = data(ceil(prod(kernel)/2),:,:); if coil refval = repmat(refval,[prod(kernel),1,1]); int_img = 1/(size(data,2)*size(data,3)) * sum((data - refval).^2, [2,3]); else refval = repmat(refval,[prod(kernel),1]); %int_img = 1/size(data,2) * sum((data(:,1) - refval(1)).^2, [2]); int_img = 1/size(data,2) * sum((data - refval).^2, [2]); end wdists = (pos_img .* int_img); [~,min_idx] = mink(wdists, M); end function data_norm = normalize(data) data_norm = zeros(size(data)); for i = 1:size(data,4) data_ = data(:,:,:,i); data_norm(:,:,:,i) = abs(data_./max(data_(:))); end end function [x,y,z] = get_voxel_coords(sx,sy,sz,kx,ky,kz) mask = true([sx, sy, sz]); mask(1:kx, :, :) = 0; mask(:, 1:ky, :) = 0; mask(:, :, 1:kz) = 0; mask(sx-kx+1:sx, :, :) = 0; mask(:, sy-ky+1:sy, :) = 0; mask(:, :, sz-kz+1:sz) = 0; maskinds = find(mask); [x,y,z] = ind2sub(size(mask),maskinds); end function data = unpad(data,kernel) k = (kernel-1)/2; data = data(k(1)+1:end-k(1),k(2)+1:end-k(2),k(3)+1:end-k(3),:,:); end function s = shrink(y, gamma) % Frobenius norm optimal shrinkage % Gavish & Donoho IEEE 63, 2137 (2017) % DOI: 10.1109/TIT.2017.2653801 % Eq (7) t = 1 + sqrt(gamma); s = zeros(size(y)); x = y(y > t); s(y > t) = sqrt((x.^2-gamma-1).^2 - 4*gamma)./x; end function [s, sigma, npars, sigma_after] = denoise(X, nrm, exp, tn) N = size(X,2); M = size(X,1); Mp = min(M,N); Np = max(M,N); if M < N X = X.'; end % compute PCA eigenvalues [u, vals, v] = svd(X, 'econ'); vals = diag(vals).^2; [vals, order] = sort(vals,'descend'); u = u(:,order); v = v(:,order); ptn = (0:Mp-1-tn)'; p = (0:Mp-1)'; csum = cumsum(vals,'reverse'); if exp == 1 % veraart 2016 sigmasq_1 = csum./((Mp-p).*Np); rangeMP = 4*sqrt((Mp-ptn).*(Np-tn)); elseif exp == 2 % cordero-grande sigmasq_1 = csum./((Mp-p).*(Np-p)); rangeMP = 4*sqrt((Mp-ptn).*(Np-ptn)); elseif exp == 3 % jespersen sigmasq_1 = csum./((Mp-p).*(Np-p)); rangeMP = 4*sqrt((Np-tn).*(Mp)); end rangeData = vals(1:Mp-tn) - vals(Mp-tn); sigmasq_2 = rangeData./rangeMP; t = find(sigmasq_2 < sigmasq_1(1:end-tn),1); if isempty(t) sigma = NaN; npars = NaN; s = X; sigma_after = NaN; else sigma = sqrt(sigmasq_1(t)); npars = t-1; if strcmp(nrm,'threshold') vals(t:end) = 0; s = u*diag(sqrt(vals))*v'; elseif strcmp(nrm,'frob') vals_frob= sqrt(Mp)*sigma * shrink(sqrt(vals)./(sqrt(Mp)*sigma), Np/Mp); s = u*(diag(vals_frob))*v'; end s2_after = sigma.^2 - csum(t)/(Mp*Np); sigma_after = sqrt(s2_after); end if M < N s = s.'; end end
github
CUAir/ardupilot-master
RotToQuat.m
.m
ardupilot-master/libraries/AP_NavEKF/Models/Common/RotToQuat.m
288
utf_8
9239706354267c8f5f2a29f992c07de9
% convert froma rotation vector in radians to a quaternion function quaternion = RotToQuat(rotVec) vecLength = sqrt(rotVec(1)^2 + rotVec(2)^2 + rotVec(3)^2); if vecLength < 1e-6 quaternion = [1;0;0;0]; else quaternion = [cos(0.5*vecLength); rotVec/vecLength*sin(0.5*vecLength)]; end
github
CUAir/ardupilot-master
NormQuat.m
.m
ardupilot-master/libraries/AP_NavEKF/Models/Common/NormQuat.m
198
utf_8
ed913e87efc9194a2c52b266fced8da7
% normalise the quaternion function quaternion = normQuat(quaternion) quatMag = sqrt(quaternion(1)^2 + quaternion(2)^2 + quaternion(3)^2 + quaternion(4)^2); quaternion(1:4) = quaternion / quatMag;
github
CUAir/ardupilot-master
QuatToEul.m
.m
ardupilot-master/libraries/AP_NavEKF/Models/Common/QuatToEul.m
436
utf_8
c19c9235052d99b8b943a7157e83fc94
% Convert from a quaternion to a 321 Euler rotation sequence in radians function Euler = QuatToEul(quat) Euler = zeros(3,1); Euler(1) = atan2(2*(quat(3)*quat(4)+quat(1)*quat(2)), quat(1)*quat(1) - quat(2)*quat(2) - quat(3)*quat(3) + quat(4)*quat(4)); Euler(2) = -asin(2*(quat(2)*quat(4)-quat(1)*quat(3))); Euler(3) = atan2(2*(quat(2)*quat(3)+quat(1)*quat(4)), quat(1)*quat(1) + quat(2)*quat(2) - quat(3)*quat(3) - quat(4)*quat(4));
github
skulumani/foucault-master
load_constants.m
.m
foucault-master/matlab/load_constants.m
1,176
utf_8
14da85c48f205f137f1fb2e74e55db1f
% load constants for Foucault pendulum function [constants] = load_constants() %% define constants constants.eom = 'full'; % full or len or rot for simplifications % constants.Omega = 7.2921158553e-5; % rad/sec earth angular velocity constants.Omega = 7.2921158553e-5; constants.mu = 3.986004418e14; % m^3/sec % % original Foucault Pendulum % constants.L = 67; % meters % constants.m = 28; % kilograms % constants.beta = 48.846222*pi/180; % Latitude for the Pantheon, Paris constants.L = 100; constants.m = 100; constants.beta = 40*pi/180; % latitude of pivot location on Earth constants.Re = 6378.137 * 1e3; % meters radius of the Earth % constants.g = 9.7976432222; % mean g at equator in meters/sec^2 constants.g = 9.7976432222; constants.Cbeta = [cos(constants.beta)^2 0 -sin(constants.beta)*cos(constants.beta);... 0 1 0 ;... -sin(constants.beta)*cos(constants.beta) 0 sin(constants.beta)^2]; constants.S = hat_map(constants.Omega*(ROT2(-constants.beta)'*[0;0;1])); constants.ode_options = odeset('RelTol',1e-13,'AbsTol',1e-13);
github
skulumani/foucault-master
hat_map.m
.m
foucault-master/matlab/hat_map.m
246
utf_8
a1515ff3e5d34892df65ff78d2340d60
% 8 June 15 % skew symmetric operator function mat = hat_map(vec) % maps a 3-vec to a skew symmetric matrix mat = zeros(3,3); mat(1,2) = -vec(3); mat(1,3) = vec(2); mat(2,1) = vec(3); mat(2,3) = -vec(1); mat(3,1) = -vec(2); mat(3,2) = vec(1);
github
skulumani/foucault-master
ROT2.m
.m
foucault-master/matlab/ROT2.m
594
utf_8
cc21aff60c155554ebcbed98170a584e
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Rotation matrix about second axis % b = dcm*a % % Inputs: % - beta - rotation angle (rad) % % Outpus: % - rot2 - rotation matrix (3x3) % % Dependencies: % - none % % Author: Shankar Kulumani 23 September 2016 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rot2 = ROT2(beta) cos_beta = cos(beta); sin_beta = sin(beta); rot2 = [cos_beta 0 sin_beta; ... 0 1 0 ; ... -sin_beta 0 cos_beta ]; end
github
skulumani/foucault-master
body_animation.m
.m
foucault-master/matlab/body_animation.m
3,976
utf_8
bde6196a4c3f3ae7ea82c2b5fb05d57c
% 23 September 2016 % animation for foucault pendulum function body_animation(t,q,qd,constants,type,filename) % draw position of pendulum in the body frame % body frame reference frame % Rotate body frame to match matlab figure (gravity is downward -z % direction) b1 = constants.L*[1;0;0]; b2 = constants.L*[0;1;0]; b3 = constants.L*[0;0;1]; b1 = ROT3(-pi/2)*ROT2(-pi/2)*b1; b2 = ROT3(-pi/2)*ROT2(-pi/2)*b2; b3 = ROT3(-pi/2)*ROT2(-pi/2)*b3; fig_handle = figure(); range=1.1*(constants.L); axis([-range range -range range -range range]); axis square; grid on,hold on, title('Foucault Pendulum - Body-fixed frame') xlabel('b_2') ylabel('b_3') zlabel('b_1') traj = constants.L*q; % draw the inertial frame axis_data = get(gca); xmin = axis_data.XLim(1); xmax = axis_data.XLim(2); ymin = axis_data.YLim(1); ymax = axis_data.YLim(2); zmin = axis_data.ZLim(1); zmax = axis_data.ZLim(2); switch type case 'gif' f = getframe; [im,map] = rgb2ind(f.cdata,256,'nodither'); case 'movie' % M(1:length(tspan))= struct('cdata',[],'colormap',[]); nFrames = length(t); vidObj = VideoWriter([filename '.avi']); vidObj.Quality = 100; vidObj.FrameRate = 60; open(vidObj); end % loop over time for ii = 1:1:length(t) cla % compute the position of the pendulum mass (L q) pos = traj(ii,:); xcoord = pos(2); ycoord = pos(3); zcoord = pos(1); % draw the rotating frame line([0 b1(1)],[0 b1(2)],[0 b1(3)],'color','r','linewidth',1) text(b1(1),b1(2),b1(3),'$\hat{b}_1$','interpreter','latex') line([0 b2(1)],[0 b2(2)],[0 b2(3)],'color','g','linewidth',1) text(b2(1),b2(2),b2(3),'$\hat{b}_2$','interpreter','latex') line([0 b3(1)],[0 b3(2)],[0 b3(3)],'color','b','linewidth',1) text(b3(1),b3(2),b3(3),'$\hat{b}_3$','interpreter','Latex') % arrow head plot3(b1(1),b1(2),b1(3),'r>','Linewidth',1.5) plot3(b2(1),b2(2),b2(3),'g>','Linewidth',1.5) plot3(b3(1),b3(2),b3(3),'b^','Linewidth',1.5) % inertial frame % plot3([xmin,xmax],[0 0],[0 0],'red','Linewidth',1); plot3(xmax,0,0,'r>','Linewidth',1.5); % plot3([0 0],[ymin,ymax],[0 0],'green','Linewidth',1); plot3(0,ymax,0,'g>','Linewidth',1.5); % plot3([0 0],[0 0],[zmin,zmax],'blue','Linewidth',1); plot3(0,0,zmax,'b^','Linewidth',1.5); % plot trajectory through space if ii < 100 ind = 1:1:ii; else ind = ii-100+1:1:ii; end % pendulum mass plot3([0 xcoord],[0 ycoord],[0 zcoord],'MarkerSize',20,'Marker','.','LineWidth',1,'Color','b'); plot3(traj(ind,2),traj(ind,3),traj(ind,1),'Marker','.','MarkerSize',1,'color','k'); % ground trace plot3(traj(1:ii,2),traj(1:ii,3),(-constants.L-0.1*constants.L)*ones(ii,1),'Marker','.','color','g','MarkerSize',1); % add the current simulation time to a window someplace text(-1*constants.L,1*constants.L,1*constants.L,sprintf('%5.2f s',t(ii))) drawnow; % save animation switch type case 'gif' frame = getframe(1); im = frame2im(frame); [imind,cm] = rgb2ind(im,256); outfile = [filename '.gif']; % On the first loop, create the file. In subsequent loops, append. if ii==1 imwrite(imind,cm,outfile,'gif','DelayTime',0,'loopcount',inf); else imwrite(imind,cm,outfile,'gif','DelayTime',0,'writemode','append'); end case 'movie' % M(ii)=getframe(gcf,[0 0 560 420]); % leaving gcf out crops the frame in the movie. writeVideo(vidObj,getframe(gca)); otherwise end end % Output the movie as an avi file switch type case 'gif' fprintf('Finished animation\n') case 'movie' %movie2avi(M,[filename '.avi']); close(vidObj); fprintf('Finished animation - movie saved\n') otherwise end
github
skulumani/foucault-master
inertial_animation.m
.m
foucault-master/matlab/inertial_animation.m
3,766
utf_8
59d22cc3a33cf76d7a8d9577cd3512c9
% 23 September 2016 % animation for foucault pendulum expressed in inertial frame function inertial_animation(t,q,qd,constants,type,filename) % draw position of pendulum in the body frame fig_handle = figure(); range=1.1*(constants.L); axis([-range range -range range -range range]); axis square; grid on,hold on, title('Foucault Pendulum - Inertial Frame') xlabel('e_1') ylabel('e_2') zlabel('e_3') % body frame reference frame e1 = constants.L*[1;0;0]; e2 = constants.L*[0;1;0]; e3 = constants.L*[0;0;1]; traj = constants.L*q; traj_inertial = zeros(size(traj)); % draw the inertial frame axis_data = get(gca); xmin = axis_data.XLim(1); xmax = axis_data.XLim(2); ymin = axis_data.YLim(1); ymax = axis_data.YLim(2); zmin = axis_data.ZLim(1); zmax = axis_data.ZLim(2); switch type case 'gif' f = getframe; [im,map] = rgb2ind(f.cdata,256,'nodither'); case 'movie' % M(1:length(tspan))= struct('cdata',[],'colormap',[]); nFrames = length(tspan); vidObj = VideoWriter([filename '.avi']); vidObj.Quality = 100; vidObj.FrameRate = 8; open(vidObj); end % loop over time for ii = 1:1:length(t) cla % compute the rotation from body frame to inertial frame R_i2b = ROT3(constants.Omega*t(ii))*ROT2(-constants.beta); R_b2i = R_i2b'; % compute the position of the pendulum mass (L q) pos = R_b2i'*traj(ii,:)'; traj_inertial(ii,:) = pos'; xcoord = pos(2); ycoord = pos(3); zcoord = pos(1); % rotate the body frame axes and plot b1 = R_i2b*e1; b2 = R_i2b*e2; b3 = R_i2b*e3; % draw the rotating frame line([0 b1(1)],[0 b1(2)],[0 b1(3)],'color','r','linewidth',1) text(b1(1),b1(2),b1(3),'$\hat{b}_1$','interpreter','latex') line([0 b2(1)],[0 b2(2)],[0 b2(3)],'color','g','linewidth',1) text(b2(1),b2(2),b2(3),'$\hat{b}_2$','interpreter','latex') line([0 b3(1)],[0 b3(2)],[0 b3(3)],'color','b','linewidth',1) text(b3(1),b3(2),b3(3),'$\hat{b}_3$','interpreter','Latex') % inertial frame plot3([xmin,xmax],[0 0],[0 0],'red','Linewidth',1); plot3(xmax,0,0,'r>','Linewidth',1.5); plot3([0 0],[ymin,ymax],[0 0],'green','Linewidth',1); plot3(0,ymax,0,'g>','Linewidth',1.5); plot3([0 0],[0 0],[zmin,zmax],'blue','Linewidth',1); plot3(0,0,zmax,'b^','Linewidth',1.5); % draw the pendulum mass in the inertial frame plot3([0 pos(1)],[0 pos(2)],[0 pos(3)],'MarkerSize',20,'Marker','.','LineWidth',1,'Color','b') % plot trajectory through space if ii < 100 ind = 1:1:ii; else ind = ii-100+1:1:ii; end plot3(traj_inertial(ind,1),traj_inertial(ind,2),traj_inertial(ind,3),'Marker','.','MarkerSize',1,'color','k'); drawnow; % save animation switch type case 'gif' frame = getframe(1); im = frame2im(frame); [imind,cm] = rgb2ind(im,256); outfile = [filename '.gif']; % On the first loop, create the file. In subsequent loops, append. if ii==1 imwrite(imind,cm,outfile,'gif','DelayTime',0,'loopcount',inf); else imwrite(imind,cm,outfile,'gif','DelayTime',0,'writemode','append'); end case 'movie' % M(ii)=getframe(gcf,[0 0 560 420]); % leaving gcf out crops the frame in the movie. writeVideo(vidObj,getframe(gca)); otherwise end end % Output the movie as an avi file switch type case 'gif' fprintf('Finished animation\n') case 'movie' %movie2avi(M,[filename '.avi']); close(vidObj); fprintf('Finished animation - movie saved\n') otherwise end
github
skulumani/foucault-master
plot_outputs.m
.m
foucault-master/matlab/plot_outputs.m
2,708
utf_8
35bb5bdc3d3fc9f4b3011e76dba4f584
% 23 September 2016 % plot simulation function plot_outputs(t,q,qd,constants) % extract constants Cbeta = constants.Cbeta; S = constants.S; Omega = constants.Omega; Len = constants.L; m = constants.m; % calculate the total energy of the pendulum and make sure it's consistent T = zeros(length(t),1); V = zeros(length(t),1); L = zeros(length(t),1); E = zeros(length(t),1); pend_pos = constants.L*q; % calculate total energy for ii = 1:length(t) body_pos = constants.Re*[1;0;0]+constants.L*q(ii,:)'; % need the kinetic energy in the inertial frame switch constants.eom case 'full' T(ii) = 1/2*m*Len^2*norm(qd(ii,:))^2 + ... m*Len*qd(ii,:)*S*body_pos + ... 1/2*m*Omega^2*body_pos'*Cbeta*body_pos; case 'rot' T(ii) = 1/2*m*Len^2*norm(qd(ii,:))^2; case 'len' T(ii) = 1/2*m*Len^2*norm(qd(ii,:))^2 + ... m*Len*qd(ii,:)*S*body_pos + ... 1/2*m*Omega^2*body_pos'*Cbeta*body_pos; end V(ii) = - constants.m*constants.g*constants.Re^2 / norm(body_pos); L(ii) = T(ii)-V(ii); E(ii) = T(ii)+V(ii); end % energy variation E_diff = abs(E - E(1)); %% plot outputs fontsize = 18; fontname = 'Times'; e_fig = figure; grid on;hold on plot(t,abs(E_diff./E)) title('Relative Energy Difference','interpreter','latex','FontName',fontname,'FontSize',fontsize); xlabel('Time (sec)','interpreter','latex','FontName',fontname,'FontSize',fontsize); ylabel('$\Delta E / E$','interpreter','latex','FontName',fontname,'FontSize',fontsize); set(gca,'FontName',fontname,'FontSize',fontsize); % 2-D projections pos_fig = figure; % ground track of pendulum (b2 vs b3 frame) subplot(2,2,1) grid on;hold all plot(pend_pos(:,2),pend_pos(:,3)) title('$b_2$ vs $b_3$','interpreter','latex','FontName',fontname,'FontSize',fontsize); set(gca,'FontName',fontname,'FontSize',fontsize); % vertical frame subplot(2,2,3) grid on;hold all plot(pend_pos(:,2),pend_pos(:,1)) title('$b_2$ vs $b_1$','interpreter','latex','FontName',fontname,'FontSize',fontsize); set(gca,'FontName',fontname,'FontSize',fontsize); subplot(2,2,4) grid on;hold all plot(pend_pos(:,3),pend_pos(:,1)) title('$b_3$ vs $b_1$','interpreter','latex','FontName',fontname,'FontSize',fontsize); set(gca,'FontName',fontname,'FontSize',fontsize); % plot the norm of the position vector norm_plot = figure; grid on hold on norm_q = sqrt(sum(q.^2,2)); plot(t,norm_q) title('$||q||$','interpreter','latex','FontName',fontname,'FontSize',fontsize); xlabel('Time (sec)','interpreter','latex','FontName',fontname,'FontSize',fontsize); ylabel('$||q||$','interpreter','latex','FontName',fontname,'FontSize',fontsize);
github
skulumani/foucault-master
vee_map.m
.m
foucault-master/matlab/vee_map.m
217
utf_8
03c2d87aa5e1f2a683080adf744e0e27
% 11 June 15 % vee map function to take a skew symmetric matrix and map it to a 3 vector function [vec] = vee_map(mat) x1 = mat(3,2)-mat(2,3); x2 = mat(1,3) - mat(3,1); x3 = mat(2,1)-mat(1,2); vec = 1/2*[x1;x2;x3];
github
skulumani/foucault-master
foucault_ode_rot.m
.m
foucault-master/matlab/foucault_ode_rot.m
648
utf_8
39743fd03e852988bf26ffb954f37a1d
% 8 September 2016 % Assuming length of pendulum is much less than the Earth and that the % rotation coriolis force is negligible r \Omega^@ << g function [state_dot] = foucault_ode_rot(t,state,constants) % extract constants Omega = constants.Omega; L = constants.L; m = constants.m; Re = constants.Re; g = constants.g; Cbeta = constants.Cbeta; S = constants.S; % redefine the state pos = state(1:3,1); vel = state(4:6,1); proj_mat = eye(3,3) - pos*pos'; pos_dot = vel; vel_dot = -1/m/L^2 * (m*L^2*norm(vel)^2*pos + 2*m*L^2*proj_mat*S*vel ... + m*g*L*proj_mat*[1;0;0]); state_dot = [pos_dot;vel_dot];
github
skulumani/foucault-master
foucault_ode.m
.m
foucault-master/matlab/foucault_ode.m
692
utf_8
3c2f639b066df7d1619969e89d260f42
% 8 September 2016 % Full NL ODE function for foucault pendulum function [state_dot] = foucault_ode(t,state,constants) % extract constants Omega = constants.Omega; L = constants.L; m = constants.m; Re = constants.Re; g = constants.g; Cbeta = constants.Cbeta; S = constants.S; % redefine the state pos = state(1:3,1); vel = state(4:6,1); proj_mat = eye(3,3) - pos*pos'; body_pos = Re*[1;0;0]+L*pos; % position of pendulum in body frame pos_dot = vel; vel_dot = -1/m/L^2 * (m*L^2*norm(vel)^2*pos + 2*m*L^2*proj_mat*S*vel - m*L*Omega^2*proj_mat*Cbeta*body_pos ... + m*g*Re^2*L*proj_mat*body_pos/norm(body_pos)^3); state_dot = [pos_dot;vel_dot];
github
skulumani/foucault-master
ROT3.m
.m
foucault-master/matlab/ROT3.m
611
utf_8
72379dd4a63db93ef3483a5b142b68c3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Rotation matrix about thrid axis % b = dcm*a % % Inputs: % - gamma - rotation angle (rad) % % Outpus: % - rot3 - rotation matrix (3x3) % % Dependencies: % - none % % Author: Shankar Kulumani 23 September 2016 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rot3 = ROT3(gamma) cos_gamma = cos(gamma); sin_gamma = sin(gamma); rot3 = [ cos_gamma -sin_gamma 0 ; ... sin_gamma cos_gamma 0 ; ... 0 0 1 ]; end
github
skulumani/foucault-master
ROT1.m
.m
foucault-master/matlab/ROT1.m
606
utf_8
8f5386316502a83577c44e5d15de58e8
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Purpose: Rotation matrix about first axis % b = dcm*a % % Inputs: % - alpha - rotation angle (rad) % % Outpus: % - rot1 - rotation matrix (3x3) % % Dependencies: % - none % % Author: Shankar Kulumani 23 September 2016 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rot1 = ROT1(alpha) cos_alpha = cos(alpha); sin_alpha = sin(alpha); rot1 = [1 0 0 ; ... 0 cos_alpha -sin_alpha ; ... 0 sin_alpha cos_alpha ]; end
github
skulumani/foucault-master
foucault_ode_length.m
.m
foucault-master/matlab/foucault_ode_length.m
620
utf_8
45cffa2ccb1d9618df1ebb10cf953ee3
% 8 September 2016 % Assuming length of pendulum is much less than the Earth function [state_dot] = foucault_ode_length(t,state,constants) % extract constants Omega = constants.Omega; L = constants.L; m = constants.m; Re = constants.Re; g = constants.g; Cbeta = constants.Cbeta; S = constants.S; % redefine the state pos = state(1:3,1); vel = state(4:6,1); proj_mat = eye(3,3) - pos*pos'; pos_dot = vel; vel_dot = -1/m/L^2 * (m*L^2*norm(vel)^2*pos + 2*m*L^2*proj_mat*S*vel ... - m*L*Re*Omega^2*proj_mat*Cbeta*[1;0;0] + m*g*L*proj_mat*[1;0;0]); state_dot = [pos_dot;vel_dot];
github
CALFEM/calfem-matlab-iga-master
bspdegelev.m
.m
calfem-matlab-iga-master/NURBS/bspdegelev.m
20,513
utf_8
5a7638accd22f943a5ac4278ab8176b6
function [ic,ik] = bspdegelev(d,c,k,t) % BSPDEGELEV: Degree elevate a univariate B-Spline. % % Calling Sequence: % % [ic,ik] = bspdegelev(d,c,k,t) % % INPUT: % % d - Degree of the B-Spline. % c - Control points, matrix of size (dim,nc). % k - Knot sequence, row vector of size nk. % t - Raise the B-Spline degree t times. % % OUTPUT: % % ic - Control points of the new B-Spline. % ik - Knot vector of the new B-Spline. % % Copyright (C) 2000 Mark Spink, 2007 Daniel Claxton % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 2 of the License, or % (at your option) any later version. % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. [mc,nc] = size(c); % % int bspdegelev(int d, double *c, int mc, int nc, double *k, int nk, % int t, int *nh, double *ic, double *ik) % { % int row,col; % % int ierr = 0; % int i, j, q, s, m, ph, ph2, mpi, mh, r, a, b, cind, oldr, mul; % int n, lbz, rbz, save, tr, kj, first, kind, last, bet, ii; % double inv, ua, ub, numer, den, alf, gam; % double **bezalfs, **bpts, **ebpts, **Nextbpts, *alfs; % % double **ctrl = vec2mat(c, mc, nc); % ic = zeros(mc,nc*(t)); % double **ictrl = vec2mat(ic, mc, nc*(t+1)); % n = nc - 1; % n = nc - 1; % bezalfs = zeros(d+1,d+t+1); % bezalfs = matrix(d+1,d+t+1); bpts = zeros(mc,d+1); % bpts = matrix(mc,d+1); ebpts = zeros(mc,d+t+1); % ebpts = matrix(mc,d+t+1); Nextbpts = zeros(mc,d+1); % Nextbpts = matrix(mc,d+1); alfs = zeros(d,1); % alfs = (double *) mxMalloc(d*sizeof(double)); % m = n + d + 1; % m = n + d + 1; ph = d + t; % ph = d + t; ph2 = floor(ph / 2); % ph2 = ph / 2; % % // compute bezier degree elevation coefficeients bezalfs(1,1) = 1; % bezalfs[0][0] = bezalfs[ph][d] = 1.0; bezalfs(d+1,ph+1) = 1; % for i=1:ph2 % for (i = 1; i <= ph2; i++) { inv = 1/bincoeff(ph,i); % inv = 1.0 / bincoeff(ph,i); mpi = min(d,i); % mpi = min(d,i); % for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) bezalfs(j+1,i+1) = inv*bincoeff(d,j)*bincoeff(t,i-j); % bezalfs[i][j] = inv * bincoeff(d,j) * bincoeff(t,i-j); end end % } % for i=ph2+1:ph-1 % for (i = ph2+1; i <= ph-1; i++) { mpi = min(d,i); % mpi = min(d, i); for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) bezalfs(j+1,i+1) = bezalfs(d-j+1,ph-i+1); % bezalfs[i][j] = bezalfs[ph-i][d-j]; end end % } % mh = ph; % mh = ph; kind = ph+1; % kind = ph+1; r = -1; % r = -1; a = d; % a = d; b = d+1; % b = d+1; cind = 1; % cind = 1; ua = k(1); % ua = k[0]; % for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) ic(ii+1,1) = c(ii+1,1); % ictrl[0][ii] = ctrl[0][ii]; end % for i=0:ph % for (i = 0; i <= ph; i++) ik(i+1) = ua; % ik[i] = ua; end % % // initialise first bezier seg for i=0:d % for (i = 0; i <= d; i++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) bpts(ii+1,i+1) = c(ii+1,i+1); % bpts[i][ii] = ctrl[i][ii]; end end % % // big loop thru knot vector while b < m % while (b < m) { i = b; % i = b; while b < m && k(b+1) == k(b+2) % while (b < m && k[b] == k[b+1]) b = b + 1; % b++; end % mul = b - i + 1; % mul = b - i + 1; mh = mh + mul + t; % mh += mul + t; ub = k(b+1); % ub = k[b]; oldr = r; % oldr = r; r = d - mul; % r = d - mul; % % // insert knot u(b) r times if oldr > 0 % if (oldr > 0) lbz = floor((oldr+2)/2); % lbz = (oldr+2) / 2; else % else lbz = 1; % lbz = 1; end % if r > 0 % if (r > 0) rbz = ph - floor((r+1)/2); % rbz = ph - (r+1)/2; else % else rbz = ph; % rbz = ph; end % if r > 0 % if (r > 0) { % // insert knot to get bezier segment numer = ub - ua; % numer = ub - ua; for q=d:-1:mul+1 % for (q = d; q > mul; q--) alfs(q-mul) = numer / (k(a+q+1)-ua); % alfs[q-mul-1] = numer / (k[a+q]-ua); end for j=1:r % for (j = 1; j <= r; j++) { save = r - j; % save = r - j; s = mul + j; % s = mul + j; % for q=d:-1:s % for (q = d; q >= s; q--) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = alfs(q-s+1)*bpts(ii+1,q+1); tmp2 = (1-alfs(q-s+1))*bpts(ii+1,q); bpts(ii+1,q+1) = tmp1 + tmp2; % bpts[q][ii] = alfs[q-s]*bpts[q][ii]+(1.0-alfs[q-s])*bpts[q-1][ii]; end end % for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) Nextbpts(ii+1,save+1) = bpts(ii+1,d+1); % Nextbpts[save][ii] = bpts[d][ii]; end end % } end % } % // end of insert knot % % // degree elevate bezier for i=lbz:ph % for (i = lbz; i <= ph; i++) { for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) ebpts(ii+1,i+1) = 0; % ebpts[i][ii] = 0.0; end mpi = min(d, i); % mpi = min(d, i); for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = ebpts(ii+1,i+1); tmp2 = bezalfs(j+1,i+1)*bpts(ii+1,j+1); ebpts(ii+1,i+1) = tmp1 + tmp2; % ebpts[i][ii] = ebpts[i][ii] + bezalfs[i][j]*bpts[j][ii]; end end end % } % // end of degree elevating bezier % if oldr > 1 % if (oldr > 1) { % // must remove knot u=k[a] oldr times first = kind - 2; % first = kind - 2; last = kind; % last = kind; den = ub - ua; % den = ub - ua; bet = floor((ub-ik(kind)) / den); % bet = (ub-ik[kind-1]) / den; % % // knot removal loop for tr=1:oldr-1 % for (tr = 1; tr < oldr; tr++) { i = first; % i = first; j = last; % j = last; kj = j - kind + 1; % kj = j - kind + 1; while j-i > tr % while (j - i > tr) { % // loop and compute the new control points % // for one removal step if i < cind % if (i < cind) { alf = (ub-ik(i+1))/(ua-ik(i+1)); % alf = (ub-ik[i])/(ua-ik[i]); for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = alf*ic(ii+1,i+1); tmp2 = (1-alf)*ic(ii+1,i); ic(ii+1,i+1) = tmp1 + tmp2; % ictrl[i][ii] = alf * ictrl[i][ii] + (1.0-alf) * ictrl[i-1][ii]; end end % } if j >= lbz % if (j >= lbz) { if j-tr <= kind-ph+oldr % if (j-tr <= kind-ph+oldr) { gam = (ub-ik(j-tr+1)) / den; % gam = (ub-ik[j-tr]) / den; for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = gam*ebpts(ii+1,kj+1); tmp2 = (1-gam)*ebpts(ii+1,kj+2); ebpts(ii+1,kj+1) = tmp1 + tmp2; % ebpts[kj][ii] = gam*ebpts[kj][ii] + (1.0-gam)*ebpts[kj+1][ii]; end % } else % else { for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = bet*ebpts(ii+1,kj+1); tmp2 = (1-bet)*ebpts(ii+1,kj+2); ebpts(ii+1,kj+1) = tmp1 + tmp2; % ebpts[kj][ii] = bet*ebpts[kj][ii] + (1.0-bet)*ebpts[kj+1][ii]; end end % } end % } i = i + 1; % i++; j = j - 1; % j--; kj = kj - 1; % kj--; end % } % first = first - 1; % first--; last = last + 1; % last++; end % } end % } % // end of removing knot n=k[a] % % // load the knot ua if a ~= d % if (a != d) for i=0:ph-oldr-1 % for (i = 0; i < ph-oldr; i++) { ik(kind+1) = ua; % ik[kind] = ua; kind = kind + 1; % kind++; end end % } % % // load ctrl pts into ic for j=lbz:rbz % for (j = lbz; j <= rbz; j++) { for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) ic(ii+1,cind+1) = ebpts(ii+1,j+1); % ictrl[cind][ii] = ebpts[j][ii]; end cind = cind + 1; % cind++; end % } % if b < m % if (b < m) { % // setup for next pass thru loop for j=0:r-1 % for (j = 0; j < r; j++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) bpts(ii+1,j+1) = Nextbpts(ii+1,j+1); % bpts[j][ii] = Nextbpts[j][ii]; end end for j=r:d % for (j = r; j <= d; j++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) bpts(ii+1,j+1) = c(ii+1,b-d+j+1); % bpts[j][ii] = ctrl[b-d+j][ii]; end end a = b; % a = b; b = b+1; % b++; ua = ub; % ua = ub; % } else % else % // end knot for i=0:ph % for (i = 0; i <= ph; i++) ik(kind+i+1) = ub; % ik[kind+i] = ub; end end end % } % End big while loop % // end while loop % % *nh = mh - ph - 1; % % freevec2mat(ctrl); % freevec2mat(ictrl); % freematrix(bezalfs); % freematrix(bpts); % freematrix(ebpts); % freematrix(Nextbpts); % mxFree(alfs); % % return(ierr); end % } function b = bincoeff(n,k) % Computes the binomial coefficient. % % ( n ) n! % ( ) = -------- % ( k ) k!(n-k)! % % b = bincoeff(n,k) % % Algorithm from 'Numerical Recipes in C, 2nd Edition' pg215. % double bincoeff(int n, int k) % { b = floor(0.5+exp(factln(n)-factln(k)-factln(n-k))); % return floor(0.5+exp(factln(n)-factln(k)-factln(n-k))); end % } function f = factln(n) % computes ln(n!) if n <= 1, f = 0; return, end f = gammaln(n+1); %log(factorial(n)); end
github
otroblogdetecno/matlabExamples-master
spatial_calibration_demo.m
.m
matlabExamples-master/caracteristicas/spatial_calibration_demo.m
10,512
utf_8
f6a8ac89a25e8f0720bdadb7a30c016a
function spatial_calibration_demo() % spatial_calibration_demo This demo allows you to % spatially calibrate your image and then % make distance or area measurements. global originalImage; % Check that user has the Image Processing Toolbox installed. clc; % Clear the command window. close all; % Close all figures (except those of imtool.) workspace; % Make sure the workspace panel is showing. format long g; format compact; fontSize = 20; hasIPT = license('test', 'image_toolbox'); if ~hasIPT % User does not have the toolbox installed. message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?'); reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes'); if strcmpi(reply, 'No') % User said No, so exit. return; end end % Read in a standard MATLAB gray scale demo image. folder = fullfile(matlabroot, '\toolbox\images\imdemos'); button = menu('Use which demo image?', 'CameraMan', 'Moon', 'Eight', 'Coins', 'Peppers', 'My own...', 'Exit'); switch button case 1 baseFileName = 'cameraman.tif'; case 2 baseFileName = 'moon.tif'; case 3 baseFileName = 'eight.tif'; case 4 baseFileName = 'coins.png'; case 5 baseFileName = 'peppers.png'; case 6 % Get the name of the file that the user wants to use. defaultFileName = fullfile(cd, '*.*'); [baseFileName, folder] = uigetfile(defaultFileName, 'Select an image file'); if baseFileName == 0 % User clicked the Cancel button. return; end case 7 return; end % Get the full filename, with path prepended. fullFileName = fullfile(folder, baseFileName); % Check if file exists. if ~exist(fullFileName, 'file') % File doesn't exist -- didn't find it there. Check the search path for it. fullFileName = baseFileName; % No path this time. if ~exist(fullFileName, 'file') % Still didn't find it. Alert user. errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName); uiwait(warndlg(errorMessage)); return; end end % Read in the chosen standard MATLAB demo image. originalImage = imread(fullFileName); % Get the dimensions of the image. % numberOfColorBands should be = 1. [rows columns numberOfColorBands] = size(originalImage); % Display the original gray scale image. figureHandle = figure; subplot(1,2, 1); imshow(originalImage, []); axis on; title('Original Grayscale Image', 'FontSize', fontSize); % Enlarge figure to full screen. set(gcf, 'units','normalized','outerposition',[0 0 1 1]); % Give a name to the title bar. set(gcf,'name','Demo by ImageAnalyst','numbertitle','off') message = sprintf('First you will be doing spatial calibration.'); reply = questdlg(message, 'Calibrate spatially', 'OK', 'Cancel', 'OK'); if strcmpi(reply, 'Cancel') % User said Cancel, so exit. return; end button = 1; % Allow it to enter loop. while button ~= 4 if button > 1 % Let them choose the task, once they have calibrated. button = menu('Select a task', 'Calibrate', 'Measure Distance', 'Measure Area', 'Exit Demo'); end switch button case 1 success = Calibrate(); % Keep trying if they didn't click properly. while ~success success = Calibrate(); end % If they get to here, they clicked properly % Change to something else so it will ask them % for the task on the next time through the loop. button = 99; case 2 DrawLine(); case 3 DrawArea(); otherwise close(figureHandle); break; end end end %===================================================================== function success = Calibrate() global lastDrawnHandle; global calibration; try success = false; instructions = sprintf('Left click to anchor first endpoint of line.\nRight-click or double-left-click to anchor second endpoint of line.\n\nAfter that I will ask for the real-world distance of the line.'); title(instructions); msgboxw(instructions); [cx, cy, rgbValues, xi,yi] = improfile(1000); % rgbValues is 1000x1x3. Call Squeeze to get rid of the singleton dimension and make it 1000x3. rgbValues = squeeze(rgbValues); distanceInPixels = sqrt( (xi(2)-xi(1)).^2 + (yi(2)-yi(1)).^2); if length(xi) < 2 return; end % Plot the line. hold on; lastDrawnHandle = plot(xi, yi, 'y-', 'LineWidth', 2); % Ask the user for the real-world distance. userPrompt = {'Enter real world units (e.g. microns):','Enter distance in those units:'}; dialogTitle = 'Specify calibration information'; numberOfLines = 1; def = {'microns', '500'}; answer = inputdlg(userPrompt, dialogTitle, numberOfLines, def); if isempty(answer) return; end calibration.units = answer{1}; calibration.distanceInPixels = distanceInPixels; calibration.distanceInUnits = str2double(answer{2}); calibration.distancePerPixel = calibration.distanceInUnits / distanceInPixels; success = true; message = sprintf('The distance you drew is %.2f pixels = %f %s.\nThe number of %s per pixel is %f.\nThe number of pixels per %s is %f',... distanceInPixels, calibration.distanceInUnits, calibration.units, ... calibration.units, calibration.distancePerPixel, ... calibration.units, 1/calibration.distancePerPixel); uiwait(msgbox(message)); catch ME errorMessage = sprintf('Error in function Calibrate().\nDid you first left click and then right click?\n\nError Message:\n%s', ME.message); fprintf(1, '%s\n', errorMessage); WarnUser(errorMessage); end return; % from Calibrate() end %===================================================================== % --- Executes on button press in DrawLine. function success = DrawLine() try global lastDrawnHandle; global calibration; fontSize = 14; instructions = sprintf('Draw a line.\nFirst, left-click to anchor first endpoint of line.\nRight-click or double-left-click to anchor second endpoint of line.\n\nAfter that I will ask for the real-world distance of the line.'); title(instructions); msgboxw(instructions); subplot(1,2, 1); % Switch to image axes. [cx,cy, rgbValues, xi,yi] = improfile(1000); % Get the profile again but spaced at the number of pixels instead of 1000 samples. hImage = findobj(gca,'Type','image'); theImage = get(hImage, 'CData'); lineLength = round(sqrt((xi(1)-xi(2))^2 + (yi(1)-yi(2))^2)) [cx,cy, rgbValues] = improfile(theImage, xi, yi, lineLength); % rgbValues is 1000x1x3. Call Squeeze to get rid of the singleton dimension and make it 1000x3. rgbValues = squeeze(rgbValues); distanceInPixels = sqrt( (xi(2)-xi(1)).^2 + (yi(2)-yi(1)).^2); distanceInRealUnits = distanceInPixels * calibration.distancePerPixel; if length(xi) < 2 return; end % Plot the line. hold on; lastDrawnHandle = plot(xi, yi, 'y-', 'LineWidth', 2); % Plot profiles along the line of the red, green, and blue components. subplot(1,2,2); [rows, columns] = size(rgbValues); if columns == 3 % It's an RGB image. plot(rgbValues(:, 1), 'r-', 'LineWidth', 2); hold on; plot(rgbValues(:, 2), 'g-', 'LineWidth', 2); plot(rgbValues(:, 3), 'b-', 'LineWidth', 2); title('Red, Green, and Blue Profiles along the line you just drew.', 'FontSize', 14); else % It's a gray scale image. plot(rgbValues, 'k-', 'LineWidth', 2); end xlabel('X', 'FontSize', fontSize); ylabel('Gray Level', 'FontSize', fontSize); title('Intensity Profile', 'FontSize', fontSize); grid on; % Inform use via a dialog box. txtInfo = sprintf('Distance = %.1f %s, which = %.1f pixels.', ... distanceInRealUnits, calibration.units, distanceInPixels); msgboxw(txtInfo); % Print the values out to the command window. fprintf(1, '%\n', txtInfo); catch ME errorMessage = sprintf('Error in function DrawLine().\n\nError Message:\n%s', ME.message); fprintf(1, '%s\n', errorMessage); WarnUser(errorMessage); end end % from DrawLine() %===================================================================== function DrawArea() global originalImage; global lastDrawnHandle; global calibration; try txtInfo = sprintf('Left click to anchor vertices.\nDouble left click to anchor final point of polygon.'); title(txtInfo); msgboxw(txtInfo); % Get size information. [rows, columns, numberOfColorBands] = size(originalImage); % Get a gray scale version. if numberOfColorBands > 1 grayImage = rgb2gray(originalImage); else grayImage = originalImage; end subplot(1,2, 1); % Switch to image axes. % Ask user to draw a polygon. [maskImage, xi, yi] = roipolyold(); % Draw the polygon over the image on the main screen. hold on; lastDrawnHandle = plot(xi, yi, 'r-', 'LineWidth', 2); numberOfPixels = sum(maskImage(:)); area = numberOfPixels * calibration.distancePerPixel^2; % Get the mean gray level of the gray scale image. mean_GL = mean(grayImage(maskImage)); % Of the gray scale version. % Print the area values out to the command window. txtInfo = sprintf('Area = %8.1f square %s.\nMean gray level = %.2f.', ... area, calibration.units, mean_GL); fprintf(1,'%s\n', txtInfo); title(txtInfo, 'FontSize', 14); % Done with measurement of area. % Now, just for fun, get the mean value and display the histogram. if numberOfColorBands >= 3 % It's a color image. Get the mean RGB Values. redPlane = double(originalImage(:, :, 1)); greenPlane = double(originalImage(:, :, 2)); bluePlane = double(originalImage(:, :, 3)); mean_RGB_GL(1) = mean(redPlane(maskImage)); mean_RGB_GL(2) = mean(greenPlane(maskImage)); mean_RGB_GL(3) = mean(bluePlane(maskImage)); fprintf('%s\nRed mean = %.2f\nGreen mean = %.2f\nBlue mean = %.2f', ... txtInfo, mean_RGB_GL(1), mean_RGB_GL(2), mean_RGB_GL(3)); end % Just for fun, let's get its histogram within the masked region. [pixelCount, grayLevels] = imhist(grayImage(maskImage)); subplot(1,2, 2); % Switch to plot axes. cla; bar(pixelCount); grid on; caption = sprintf('Histogram within area. Mean gray level = %.2f', mean_GL); title(caption, 'FontSize', 14); xlim([0 grayLevels(end)]); % Scale x axis manually. % Show the mean as a vertical red bar on the histogram. hold on; maxYValue = ylim; line([mean_GL, mean_GL], [0 maxYValue(2)], 'Color', 'r', 'linewidth', 2); catch ME errorMessage = sprintf('Error in function DrawArea().\n\nError Message:\n%s', ME.message); fprintf(1, '%s\n', errorMessage); WarnUser(errorMessage); end end % od DrawArea() %===================================================================== function msgboxw(message) uiwait(msgbox(message)); end %===================================================================== function WarnUser(message) uiwait(msgbox(message)); end
github
otroblogdetecno/matlabExamples-master
DeltaE.m
.m
matlabExamples-master/DeltaE/DeltaE.m
20,283
utf_8
117e2bac667be64d3a0c96dac4c7b853
% Demo macro to very, very simple color detection in LAB color space. % The RGB image is converted to LAB color space and then the user draws % some freehand-drawn irregularly shaped region to identify a color. % The Delta E (the color difference in LAB color space) is then calculated % for every pixel in the image between that pixel's color and the average % LAB color of the drawn region. The user can then specify a number that % says how close to that color would they like to be. The software will % then find all pixels within that specified Delta E of the color of the drawn region. % % Note: This demo differs from my demo on color detection by thresholding in the % hsv color space because with that one you are essentially extracting out a % pie-shaped sector out of the LAB color space gamut while in this demo % we're extracting out a sphere centered at the mean LAB color of the user-drawn region. % by ImageAnalyst, Ph.D. function DeltaE() clc; % Clear command window. clear; % Delete all variables. close all; % Close all figure windows except those created by imtool. % imtool close all; % Close all figure windows created by imtool. workspace; % Make sure the workspace panel is showing. % Change the current folder to the folder of this m-file. if(~isdeployed) cd(fileparts(which(mfilename))); % From Brett end try % Check that user has the Image Processing Toolbox installed. hasIPT = license('test', 'image_toolbox'); if ~hasIPT % User does not have the toolbox installed. message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?'); reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes'); if strcmpi(reply, 'No') % User said No, so exit. return; end end % Continue with the demo. Do some initialization stuff. close all; fontSize = 14; figure; % Maximize the figure. set(gcf, 'Position', get(0, 'ScreenSize')); set(gcf,'name','Color Matching Demo by ImageAnalyst','numbertitle','off') % Change the current folder to the folder of this m-file. % (The line of code below is from Brett Shoelson of The Mathworks.) if(~isdeployed) cd(fileparts(which(mfilename))); end % Ask user if they want to use a demo image or their own image. message = sprintf('Do you want use a standard demo image,\nOr pick one of your own?'); reply2 = questdlg(message, 'Which Image?', 'Demo','My Own', 'Demo'); % Open an image. if strcmpi(reply2, 'Demo') % Read standard MATLAB demo image. message = sprintf('Which demo image do you want to use?'); selectedImage = questdlg(message, 'Which Demo Image?', 'Onions', 'Peppers', 'Stained Fabric', 'Onions'); if strcmp(selectedImage, 'Onions') fullImageFileName = 'onion.png'; elseif strcmp(selectedImage, 'Peppers') fullImageFileName = 'peppers.png'; else fullImageFileName = 'fabric.png'; end else % They want to pick their own. % Change default directory to the one containing the standard demo images for the MATLAB Image Processing Toolbox. originalFolder = pwd; folder = fullfile(matlabroot, '\toolbox\images\imdemos'); if ~exist(folder, 'dir') folder = pwd; end cd(folder); % Browse for the image file. [baseFileName, folder] = uigetfile('*.*', 'Specify an image file'); fullImageFileName = fullfile(folder, baseFileName); % Set current folder back to the original one. cd(originalFolder); selectedImage = 'My own image'; % Need for the if threshold selection statement later. end % Check to see that the image exists. (Mainly to check on the demo images.) if ~exist(fullImageFileName, 'file') message = sprintf('This file does not exist:\n%s', fullImageFileName); WarnUser(message); return; end % Read in image into an array. [rgbImage storedColorMap] = imread(fullImageFileName); [rows columns numberOfColorBands] = size(rgbImage); % If it's monochrome (indexed), convert it to color. % Check to see if it's an 8-bit image needed later for scaling). if strcmpi(class(rgbImage), 'uint8') % Flag for 256 gray levels. eightBit = true; else eightBit = false; end if numberOfColorBands == 1 if isempty(storedColorMap) % Just a simple gray level image, not indexed with a stored color map. % Create a 3D true color image where we copy the monochrome image into all 3 (R, G, & B) color planes. rgbImage = cat(3, rgbImage, rgbImage, rgbImage); else % It's an indexed image. rgbImage = ind2rgb(rgbImage, storedColorMap); % ind2rgb() will convert it to double and normalize it to the range 0-1. % Convert back to uint8 in the range 0-255, if needed. if eightBit rgbImage = uint8(255 * rgbImage); end end end % Display the original image. h1 = subplot(3, 4, 1); imshow(rgbImage); drawnow; % Make it display immediately. if numberOfColorBands > 1 title('Original Color Image', 'FontSize', fontSize); else caption = sprintf('Original Indexed Image\n(converted to true color with its stored colormap)'); title(caption, 'FontSize', fontSize); end % Let user outline region over rgb image. % [xCoords, yCoords, roiPosition] = DrawBoxRegion(h1); % Draw a box. mask = DrawFreehandRegion(h1, rgbImage); % Draw a freehand, irregularly-shaped region. % Mask the image. maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, class(rgbImage))); % Display it. subplot(3, 4, 5); imshow(maskedRgbImage); title('The Region You Drew', 'FontSize', fontSize); % Convert image from RGB colorspace to lab color space. cform = makecform('srgb2lab'); lab_Image = applycform(im2double(rgbImage),cform); % Extract out the color bands from the original image % into 3 separate 2D arrays, one for each color component. LChannel = lab_Image(:, :, 1); aChannel = lab_Image(:, :, 2); bChannel = lab_Image(:, :, 3); % Display the lab images. subplot(3, 4, 2); imshow(LChannel, []); title('L Channel', 'FontSize', fontSize); subplot(3, 4, 3); imshow(aChannel, []); title('a Channel', 'FontSize', fontSize); subplot(3, 4, 4); imshow(bChannel, []); title('b Channel', 'FontSize', fontSize); % Get the average lab color value. [LMean, aMean, bMean] = GetMeanLABValues(LChannel, aChannel, bChannel, mask); % Get box coordinates and get mean within the box. % x1 = round(roiPosition(1)); % x2 = round(roiPosition(1) + roiPosition(3) - 1); % y1 = round(roiPosition(2)); % y2 = round(roiPosition(2) + roiPosition(4) - 1); % % LMean = mean2(LChannel(y1:y2, x1:x2)) % aMean = mean2(aChannel(y1:y2, x1:x2)) % bMean = mean2(bChannel(y1:y2, x1:x2)) % Make uniform images of only that one single LAB color. LStandard = LMean * ones(rows, columns); aStandard = aMean * ones(rows, columns); bStandard = bMean * ones(rows, columns); % Create the delta images: delta L, delta A, and delta B. deltaL = LChannel - LStandard; deltaa = aChannel - aStandard; deltab = bChannel - bStandard; % Create the Delta E image. % This is an image that represents the color difference. % Delta E is the square root of the sum of the squares of the delta images. deltaE = sqrt(deltaL .^ 2 + deltaa .^ 2 + deltab .^ 2); % Mask it to get the Delta E in the mask region only. maskedDeltaE = deltaE .* mask; % Get the mean delta E in the mask region % Note: deltaE(mask) is a 1D vector of ONLY the pixel values within the masked area. meanMaskedDeltaE = mean(deltaE(mask)); % Get the standard deviation of the delta E in the mask region stDevMaskedDeltaE = std(deltaE(mask)); message = sprintf('The mean LAB = (%.2f, %.2f, %.2f).\nThe mean Delta E in the masked region is %.2f +/- %.2f',... LMean, aMean, bMean, meanMaskedDeltaE, stDevMaskedDeltaE); % Display the masked Delta E image - the delta E within the masked region only. subplot(3, 4, 6); imshow(maskedDeltaE, []); caption = sprintf('Delta E between image within masked region\nand mean color within masked region.\n(With amplified intensity)'); title(caption, 'FontSize', fontSize); % Display the Delta E image - the delta E over the entire image. subplot(3, 4, 7); imshow(deltaE, []); caption = sprintf('Delta E Image\n(Darker = Better Match)'); title(caption, 'FontSize', fontSize); % Plot the histograms of the Delta E color difference image, % both within the masked region, and for the entire image. PlotHistogram(deltaE(mask), deltaE, [3 4 8], 'Histograms of the 2 Delta E Images'); message = sprintf('%s\n\nRegions close in color to the color you picked\nwill be dark in the Delta E image.\n', message); msgboxw(message); % Find out how close the user wants to match the colors. prompt = {sprintf('First, examine the histogram.\nThen find pixels within this Delta E (from the average color in the region you drew):')}; dialogTitle = 'Enter Delta E Tolerance'; numberOfLines = 1; % Set the default tolerance to be the mean delta E in the masked region plus two standard deviations. strTolerance = sprintf('%.1f', meanMaskedDeltaE + 3 * stDevMaskedDeltaE); defaultAnswer = {strTolerance}; % Suggest this number to the user. response = inputdlg(prompt, dialogTitle, numberOfLines, defaultAnswer); % Update tolerance with user's response. tolerance = str2double(cell2mat(response)); % Let them interactively select the threshold with the threshold() m-file. % (Note: This is a separate function in a separate file in my File Exchange.) % threshold(deltaE); % Place a vertical bar at the threshold location. handleToSubPlot8 = subplot(3, 4, 8); % Get the handle to the plot. PlaceVerticalBarOnPlot(handleToSubPlot8, tolerance, [0 .5 0]); % Put a vertical red line there. % Find pixels within that delta E. binaryImage = deltaE <= tolerance; subplot(3, 4, 9); imshow(binaryImage, []); title('Matching Colors Mask', 'FontSize', fontSize); % Mask the image with the matching colors and extract those pixels. matchingColors = bsxfun(@times, rgbImage, cast(binaryImage, class(rgbImage))); subplot(3, 4, 10); imshow(matchingColors); caption = sprintf('Matching Colors (Delta E <= %.1f)', tolerance); title(caption, 'FontSize', fontSize); % Mask the image with the NON-matching colors and extract those pixels. nonMatchingColors = bsxfun(@times, rgbImage, cast(~binaryImage, class(rgbImage))); subplot(3, 4, 11); imshow(nonMatchingColors); caption = sprintf('Non-Matching Colors (Delta E > %.1f)', tolerance); title(caption, 'FontSize', fontSize); % Display credits: the MATLAB logo and my name. ShowCredits(); % Display logo in plot position #12. % Alert user that the demo has finished. message = sprintf('Done!\n\nThe demo has finished.\nRegions close in color to the color you picked\nwill be dark in the Delta E image.\n'); msgbox(message); catch ME errorMessage = sprintf('Error running this m-file:\n%s\n\nThe error message is:\n%s', ... mfilename('fullpath'), ME.message); errordlg(errorMessage); end return; % from SimpleColorDetection() % ---------- End of main function --------------------------------- %---------------------------------------------------------------------------- % Display the MATLAB logo. function ShowCredits() try % xpklein; % surf(peaks(30)); logoFig = subplot(3, 4, 12); caption = sprintf('A MATLAB Demo\nby ImageAnalyst'); text(0.5,1.15, caption, 'Color','r', 'FontSize', 18, 'FontWeight','b', 'HorizontalAlignment', 'Center') ; positionOfLowerRightPlot = get(logoFig, 'position'); L = 40*membrane(1,25); logoax = axes('CameraPosition', [-193.4013 -265.1546 220.4819],... 'CameraTarget',[26 26 10], ... 'CameraUpVector',[0 0 1], ... 'CameraViewAngle',9.5, ... 'DataAspectRatio', [1 1 .9],... 'Position', positionOfLowerRightPlot, ... 'Visible','off', ... 'XLim',[1 51], ... 'YLim',[1 51], ... 'ZLim',[-13 40], ... 'parent',gcf); s = surface(L, ... 'EdgeColor','none', ... 'FaceColor',[0.9 0.2 0.2], ... 'FaceLighting','phong', ... 'AmbientStrength',0.3, ... 'DiffuseStrength',0.6, ... 'Clipping','off',... 'BackFaceLighting','lit', ... 'SpecularStrength',1.1, ... 'SpecularColorReflectance',1, ... 'SpecularExponent',7, ... 'Tag','TheMathWorksLogo', ... 'parent',logoax); l1 = light('Position',[40 100 20], ... 'Style','local', ... 'Color',[0 0.8 0.8], ... 'parent',logoax); l2 = light('Position',[.5 -1 .4], ... 'Color',[0.8 0.8 0], ... 'parent',logoax); catch ME errorMessage = sprintf('Error running ShowCredits().\n\nThe error message is:\n%s', ... ME.message); errordlg(errorMessage); end return; % from ShowCredits() %----------------------------------------------------------------------------- function [xCoords, yCoords, roiPosition] = DrawBoxRegion(handleToImage) try % Open a temporary full-screen figure if requested. enlargeForDrawing = true; axes(handleToImage); if enlargeForDrawing hImage = findobj(gca,'Type','image'); numberOfImagesInside = length(hImage); if numberOfImagesInside > 1 imageInside = get(hImage(1), 'CData'); else imageInside = get(hImage, 'CData'); end hTemp = figure; hImage2 = imshow(imageInside, []); [rows columns NumberOfColorBands] = size(imageInside); set(gcf, 'Position', get(0,'Screensize')); % Maximize figure. end txtInfo = sprintf('Draw a box over the unstained fabric by clicking and dragging over the image.\nDouble click inside the box to finish drawing.'); text(10, 40, txtInfo, 'color', 'r', 'FontSize', 24); % Prompt user to draw a region on the image. msgboxw(txtInfo); % Erase all previous lines. if ~enlargeForDrawing axes(handleToImage); % ClearLinesFromAxes(handles); end hBox = imrect; roiPosition = wait(hBox); roiPosition % Erase all previous lines. if ~enlargeForDrawing axes(handleToImage); % ClearLinesFromAxes(handles); end xCoords = [roiPosition(1), roiPosition(1)+roiPosition(3), roiPosition(1)+roiPosition(3), roiPosition(1), roiPosition(1)]; yCoords = [roiPosition(2), roiPosition(2), roiPosition(2)+roiPosition(4), roiPosition(2)+roiPosition(4), roiPosition(2)]; % Plot the mask as an outline over the image. hold on; plot(xCoords, yCoords, 'linewidth', 2); close(hTemp); catch ME errorMessage = sprintf('Error running DrawRegion:\n\n\nThe error message is:\n%s', ... ME.message); WarnUser(errorMessage); end return; % from DrawRegion %----------------------------------------------------------------------------- function [mask] = DrawFreehandRegion(handleToImage, rgbImage) try fontSize = 14; % Open a temporary full-screen figure if requested. enlargeForDrawing = true; axes(handleToImage); if enlargeForDrawing hImage = findobj(gca,'Type','image'); numberOfImagesInside = length(hImage); if numberOfImagesInside > 1 imageInside = get(hImage(1), 'CData'); else imageInside = get(hImage, 'CData'); end hTemp = figure; hImage2 = imshow(imageInside, []); [rows columns NumberOfColorBands] = size(imageInside); set(gcf, 'Position', get(0,'Screensize')); % Maximize figure. end message = sprintf('Left click and hold to begin drawing.\nSimply lift the mouse button to finish'); text(10, 40, message, 'color', 'r', 'FontSize', fontSize); % Prompt user to draw a region on the image. uiwait(msgbox(message)); % Now, finally, have the user freehand draw the mask in the image. hFH = imfreehand(); % Once we get here, the user has finished drawing the region. % Create a binary image ("mask") from the ROI object. mask = hFH.createMask(); % Close the maximized figure because we're done with it. close(hTemp); % Display the freehand mask. subplot(3, 4, 5); imshow(mask); title('Binary mask of the region', 'FontSize', fontSize); % Mask the image. maskedRgbImage = bsxfun(@times, rgbImage, cast(mask,class(rgbImage))); % Display it. subplot(3, 4, 6); imshow(maskedRgbImage); catch ME errorMessage = sprintf('Error running DrawFreehandRegion:\n\n\nThe error message is:\n%s', ... ME.message); WarnUser(errorMessage); end return; % from DrawFreehandRegion %----------------------------------------------------------------------------- % Get the average lab within the mask region. function [LMean, aMean, bMean] = GetMeanLABValues(LChannel, aChannel, bChannel, mask) try LVector = LChannel(mask); % 1D vector of only the pixels within the masked area. LMean = mean(LVector); aVector = aChannel(mask); % 1D vector of only the pixels within the masked area. aMean = mean(aVector); bVector = bChannel(mask); % 1D vector of only the pixels within the masked area. bMean = mean(bVector); catch ME errorMessage = sprintf('Error running GetMeanLABValues:\n\n\nThe error message is:\n%s', ... ME.message); WarnUser(errorMessage); end return; % from GetMeanLABValues %========================================================================================================================== function WarnUser(warningMessage) uiwait(warndlg(warningMessage)); return; % from WarnUser() %========================================================================================================================== function msgboxw(message) uiwait(msgbox(message)); return; % from msgboxw() %========================================================================================================================== % Plots the histograms of the pixels in both the masked region and the entire image. function PlotHistogram(maskedRegion, doubleImage, plotNumber, caption) try fontSize = 14; subplot(plotNumber(1), plotNumber(2), plotNumber(3)); % Find out where the edges of the histogram bins should be. maxValue1 = max(maskedRegion(:)); maxValue2 = max(doubleImage(:)); maxOverallValue = max([maxValue1 maxValue2]); edges = linspace(0, maxOverallValue, 100); % Get the histogram of the masked region into 100 bins. pixelCount1 = histc(maskedRegion(:), edges); % Get the histogram of the entire image into 100 bins. pixelCount2 = histc(doubleImage(:), edges); % Plot the histogram of the entire image. plot(edges, pixelCount2, 'b-'); % Now plot the histogram of the masked region. % However there will likely be so few pixels that this plot will be so low and flat compared to the histogram of the entire % image that you probably won't be able to see it. To get around this, let's scale it to make it higher so we can see it. gainFactor = 1.0; maxValue3 = max(max(pixelCount2)); pixelCount3 = gainFactor * maxValue3 * pixelCount1 / max(pixelCount1); hold on; plot(edges, pixelCount3, 'r-'); title(caption, 'FontSize', fontSize); % Scale x axis manually. xlim([0 edges(end)]); legend('Entire', 'Masked'); catch ME errorMessage = sprintf('Error running PlotHistogram:\n\n\nThe error message is:\n%s', ... ME.message); WarnUser(errorMessage); end return; % from PlotHistogram %===================================================================== % Shows vertical lines going up from the X axis to the curve on the plot. function lineHandle = PlaceVerticalBarOnPlot(handleToPlot, x, lineColor) try % If the plot is visible, plot the line. if get(handleToPlot, 'visible') axes(handleToPlot); % makes existing axes handles.axesPlot the current axes. % Make sure x location is in the valid range along the horizontal X axis. XRange = get(handleToPlot, 'XLim'); maxXValue = XRange(2); if x > maxXValue x = maxXValue; end % Erase the old line. %hOldBar=findobj('type', 'hggroup'); %delete(hOldBar); % Draw a vertical line at the X location. hold on; yLimits = ylim; lineHandle = line([x x], [yLimits(1) yLimits(2)], 'Color', lineColor, 'LineWidth', 3); hold off; end catch ME errorMessage = sprintf('Error running PlaceVerticalBarOnPlot:\n\n\nThe error message is:\n%s', ... ME.message); WarnUser(errorMessage); end return; % End of PlaceVerticalBarOnPlot
github
kartik-nighania/ardupilot-master
RotToQuat.m
.m
ardupilot-master/libraries/AP_NavEKF/Models/Common/RotToQuat.m
288
utf_8
9239706354267c8f5f2a29f992c07de9
% convert froma rotation vector in radians to a quaternion function quaternion = RotToQuat(rotVec) vecLength = sqrt(rotVec(1)^2 + rotVec(2)^2 + rotVec(3)^2); if vecLength < 1e-6 quaternion = [1;0;0;0]; else quaternion = [cos(0.5*vecLength); rotVec/vecLength*sin(0.5*vecLength)]; end
github
kartik-nighania/ardupilot-master
NormQuat.m
.m
ardupilot-master/libraries/AP_NavEKF/Models/Common/NormQuat.m
198
utf_8
ed913e87efc9194a2c52b266fced8da7
% normalise the quaternion function quaternion = normQuat(quaternion) quatMag = sqrt(quaternion(1)^2 + quaternion(2)^2 + quaternion(3)^2 + quaternion(4)^2); quaternion(1:4) = quaternion / quatMag;
github
kartik-nighania/ardupilot-master
QuatToEul.m
.m
ardupilot-master/libraries/AP_NavEKF/Models/Common/QuatToEul.m
436
utf_8
c19c9235052d99b8b943a7157e83fc94
% Convert from a quaternion to a 321 Euler rotation sequence in radians function Euler = QuatToEul(quat) Euler = zeros(3,1); Euler(1) = atan2(2*(quat(3)*quat(4)+quat(1)*quat(2)), quat(1)*quat(1) - quat(2)*quat(2) - quat(3)*quat(3) + quat(4)*quat(4)); Euler(2) = -asin(2*(quat(2)*quat(4)-quat(1)*quat(3))); Euler(3) = atan2(2*(quat(2)*quat(3)+quat(1)*quat(4)), quat(1)*quat(1) + quat(2)*quat(2) - quat(3)*quat(3) - quat(4)*quat(4));
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
initParamDist.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/toolbox/initParamDist.m
1,393
utf_8
f5c0d7c880e1e6a811cc0157eb7fd94a
function prob_bij = initParamDist(edgeD, edge_pairs, samples) % Initialize tree parameters using distances adjmat = logical(edgeD); Ntotal = size(adjmat,1); Nobserved = size(samples,1); Nsamples = size(samples,2); prob_bi = zeros(Ntotal,2); prob_bi(1:Nobserved,2) = sum(samples-1,2)/Nsamples; for i=Nobserved+1:Ntotal neighbors = find(adjmat(i,1:Nobserved)); if(length(neighbors) > 3) votes = sum(samples(neighbors,:)-1,1); prob_bi(i,2) = max(sum((votes > length(neighbors)/2))/Nsamples,0.05); else prob_bi(i,2) = rand(1); end end prob_bi(:,1) = 1 - prob_bi(:,2); prob_bij = sparse(2*Ntotal,2*Ntotal); for e=1:size(edge_pairs,1) u = edge_pairs(e,1); v = edge_pairs(e,2); prob_bij(2*u-1:2*u,2*v-1:2*v) = findJointProb(edgeD(u,v),prob_bi(u,2),prob_bi(v,2)); end prob_bi = prob_bi'; prob_bij = prob_bij + prob_bij' + diag(prob_bi(:)); %%%%%% function jointProb = findJointProb(edge_dist,a,b) detJoint = exp(-edge_dist + 0.5*sum(log([1-a a 1-b b]))); p11 = detJoint + a*b; jointProb = [1+p11-a-b, b-p11; a-p11, p11]; if(all(jointProb(:)>=0) && all(jointProb(:) <= 1)) return; end p11 = a*b - detJoint; jointProb = [1+p11-a-b, b-p11; a-p11, p11]; if(all(jointProb(:)>=0) && all(jointProb(:) <= 1)) return; end minP = max(0,a+b-1); maxP = min(a,b); p11 = (maxP-minP)*rand(1)+minP; jointProb = [1+p11-a-b, b-p11; a-p11, p11];
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
makeModel.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/toolbox/makeModel.m
2,836
utf_8
577899ddcf8258afdccd0c8bc94a1aca
function [adjmat, level_m] = makeModel(graph, m) % Generate the adjacency matrix for the given graph with m observed % variables. level_m = m; switch graph case 'star' M = m+1; adjmat = sparse(M,M); adjmat(1:m,end) = 1; case 'doubleStar' M = m+2; adjmat = sparse(M,M); adjmat(1:ceil(m/2),end-1)=1; adjmat(ceil(m/2)+1:end-1,end)=1; case 'hmm' M = 2*m-2; adjmat = sparse(M,M); adjmat(1,m+1) = 1; adjmat(m,end) = 1; adjmat(2:m-1,m+1:M) = speye(m-2); adjmat(m+1:M-1,m+2:M) = speye(m-3); case 'regular' adjmat = sparse(m,m); num_nodes = m; while(num_nodes > 2) num_p = floor(num_nodes/3); new_adjmat = sparse(kron(eye(num_p),[1 1 1])); res_node = num_nodes - 3*num_p; if(res_node == 1) new_adjmat = [new_adjmat, [zeros(num_p-1,1); 1]]; elseif(res_node == 2) new_adjmat = [new_adjmat, [zeros(num_p-1,2); 1 1]]; end adjmat = [adjmat; zeros(num_p,size(adjmat,2)-size(new_adjmat,2)), new_adjmat]; adjmat = [adjmat, zeros(size(adjmat,1),num_p)]; num_nodes = num_p; level_m = [level_m; size(adjmat,1)]; end if(num_nodes == 2) adjmat(end-1,end) = 1; end M = size(adjmat,1); case '3cayley' adjmat = sparse(m,m); num_nodes = m; while(num_nodes > 2) num_p = floor(num_nodes/2); new_adjmat = sparse(kron(eye(num_p),[1 1])); res_node = num_nodes - 2*num_p; if(res_node == 1) new_adjmat = [new_adjmat, [zeros(num_p-1,1); 1]]; end adjmat = [adjmat; zeros(num_p,size(adjmat,2)-size(new_adjmat,2)), new_adjmat]; adjmat = [adjmat, zeros(size(adjmat,1),num_p)]; num_nodes = num_p; level_m = [level_m; size(adjmat,1)]; end if(num_nodes == 2) adjmat(end-1,end) = 1; end M = size(adjmat,1); case '5cayley' [adjmat,level_m] = makeCayleyTree(m,4); end adjmat = adjmat + adjmat'; function [adjmat,level_m] = makeCayleyTree(m,d) level_m = m; adjmat = sparse(m,m); num_nodes = m; while(num_nodes > 2); num_p = floor(num_nodes/d); new_adjmat = sparse(kron(eye(num_p),repmat(1,1,d))); res_node = num_nodes - d*num_p; if(res_node > 0) new_adjmat = [new_adjmat, [zeros(num_p-1,res_node); repmat(1,1,res_node)]]; end adjmat = [adjmat; zeros(num_p,size(adjmat,2)-size(new_adjmat,2)), new_adjmat]; adjmat = [adjmat, zeros(size(adjmat,1),num_p)]; num_nodes = num_p; level_m = [level_m; size(adjmat,1)]; end if(num_nodes == 2) adjmat(end-1,end) = 1; end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
drawWeightedGraph.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/toolbox/drawWeightedGraph.m
8,290
utf_8
136465d2b59b2a3dbd583c773e6f79a7
function [x, y, h] = drawWeightedGraph(adj, labels, root, edge_weight, node_t, varargin) % DRAW_LAYOUT Draws a layout for a graph % % [X, Y, H] = DRAW_LAYOUT(ADJ, <LABELS, ISBOX, X, Y>) % % Inputs : % ADJ : Adjacency matrix (source, sink) % LABELS : Cell array containing labels <Default : '1':'N'> % ISBOX : 1 if node is a box, 0 if oval <Default : zeros> % X, Y, : Coordinates of nodes on the unit square <Default : calls make_layout> % % Outputs : % X, Y : Coordinates of nodes on the unit square % H : Object handles % % Usage Example : [x, y] = draw_layout([0 1;0 0], {'Hidden','Visible'}, [1 0]'); % % h(i,1) is the text handle - color % h(i,2) is the circle handle - facecolor % % See also MAKE_LAYOUT % Change History : % Date Time Prog Note % 13-Apr-2000 9:06 PM ATC Created under MATLAB 5.3.1.29215a (R11.1) % 16-Sep-2009 Jin Choi Modified to draw a weighted tree % % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] adj = double(adj); N = size(adj,1); if nargin<2, labels = cellstr(int2str((1:N)')); end if nargin<3 root = 1; end if nargin < 5 node_t = zeros(N,1); end %scrsz = get(0,'ScreenSize'); set(gcf,'Position',[1, 100, 1500, 800]) axis([0 1 0 1]); set(gca,'XTick',[],'YTick',[],'box','on'); %set(gcf,'Position',[1, 100, 1500, 800]) % axis('square'); %colormap(flipud(gray)); [x y] = treeLayout(adj,root,edge_weight); idx1 = find(node_t==0); h1 = []; wd1=[]; if ~isempty(idx1) [h1 wd1] = textoval(x(idx1), y(idx1), labels(idx1), varargin{:}); end; idx2 = find(node_t~=0); h2 = []; wd2 = []; if ~isempty(idx2) [h2 wd2] = textbox(x(idx2), y(idx2), labels(idx2), varargin{:}); end; wd = zeros(size(wd1,1)+size(wd2,1),2); if ~isempty(idx1), wd(idx1, :) = wd1; end; if ~isempty(idx2), wd(idx2, :) = wd2; end; % bug: this code assumes [x y] is the center of each box and oval, which % isn't exactly true. %h_edge = []; for i=1:N, j = find(adj(i,:)==1); for k=j, if x(k)-x(i)==0, sign = 1; if y(i)>y(k), alpha = -pi/2; else alpha = pi/2; end; else alpha = atan((y(k)-y(i))/(x(k)-x(i))); if x(i)<x(k), sign = 1; else sign = -1; end; end; dy1 = sign.*wd(i,2).*sin(alpha); dx1 = sign.*wd(i,1).*cos(alpha); dy2 = sign.*wd(k,2).*sin(alpha); dx2 = sign.*wd(k,1).*cos(alpha); if adj(k,i)==0, % if directed edge h = arrow([x(i)+dx1 y(i)+dy1],[x(k)-dx2 y(k)-dy2],'BaseAngle',30); else h = line([x(i)+dx1 x(k)-dx2],[y(i)+dy1 y(k)-dy2]); adj(k,i)=-1; % Prevent drawing lines twice end; %h_edge = [h_edge h]; weight = 10*edge_weight(i,k); if(weight > 0) line_color = 'blue'; else line_color = 'red'; end set(h, 'LineWidth', max(0.1,abs(weight)), 'Color',line_color); end; end; color.box = 'black'; color.text = color.box; %color.edge = [1 1 1]*3/4; %color.edge = 'green'; if ~isempty(idx1) set(h1(:,1),'Color',color.text) set(h1(:,2),'EdgeColor',color.box) end if ~isempty(idx2) set(h2(:,1),'Color',color.text) set(h2(:,2),'EdgeColor',color.box) end %set(h_edge,'Color',color.edge) if nargout>2, h = zeros(length(wd),2); if ~isempty(idx1), h(idx1,:) = h1; end; if ~isempty(idx2), h(idx2,:) = h2; end; end; %%%%% function [t, wd] = textoval(x, y, str, varargin) % TEXTOVAL Draws an oval around text objects % % [T, WIDTH] = TEXTOVAL(X, Y, STR) % [..] = TEXTOVAL(STR) % Interactive % % Inputs : % X, Y : Coordinates % TXT : Strings % % Outputs : % T : Object Handles % WIDTH : x and y Width of ovals % % Usage Example : [t] = textoval('Visit to Asia?'); % % % Note : % See also TEXTBOX % Uses : % Change History : % Date Time Prog Note % 15-Jun-1998 10:36 AM ATC Created under MATLAB 5.1.0.421 % 12-Mar-2004 10:00 AM minka Changed placement/sizing. % % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] temp = []; textProperties = {'BackgroundColor','Color','FontAngle','FontName','FontSize','FontUnits','FontWeight','Rotation'}; varargin = argfilter(varargin,textProperties); if nargin == 1 str = x; end if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, if nargin == 1 [x, y] = ginput(1); end tx = text(x(i),y(i),str{i},'HorizontalAlignment','center',varargin{:}); % minka [ptc wx wy] = draw_oval(tx); wd(i,:) = [wx wy]; % draw_oval will paint over the text, so need to redraw it delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center',varargin{:}); temp = [temp; tx ptc]; end if nargout>0, t = temp; end; %%%%%%%%% function [ptc, wx, wy] = draw_oval(tx, x, y) % Draws an oval box around a tex object sz = get(tx,'Extent'); % minka wy = 2/3*sz(4); wx = 2/3*sz(3); x = sz(1)+sz(3)/2; y = sz(2)+sz(4)/2; ptc = ellipse(x, y, wx, wy); set(ptc, 'FaceColor','w'); %%%%%%%%%%%%% function [p] = ellipse(x, y, rx, ry, c) % ELLIPSE Draws Ellipse shaped patch objects % % [<P>] = ELLIPSE(X, Y, Rx, Ry, C) % % Inputs : % X : N x 1 vector of x coordinates % Y : N x 1 vector of y coordinates % Rx, Ry : Radii % C : Color index % % % Outputs : % P = Handles of Ellipse shaped path objects % % Usage Example : [] = ellipse(); % % % Note : % See also % Uses : % Change History : % Date Time Prog Note % 27-May-1998 9:55 AM ATC Created under MATLAB 5.1.0.421 % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] if (nargin < 2) error('Usage Example : e = ellipse([0 1],[0 -1],[1 0.5],[2 0.5]); '); end; if (nargin < 3) rx = 0.1; end; if (nargin < 4) ry = rx; end; if (nargin < 5) c = 1; end; if length(c)==1, c = ones(size(x)).*c; end; if length(rx)==1, rx = ones(size(x)).*rx; end; if length(ry)==1, ry = ones(size(x)).*ry; end; n = length(x); p = zeros(size(x)); t = 0:pi/30:2*pi; for i=1:n, px = rx(i)*cos(t)+x(i); py = ry(i)*sin(t)+y(i); p(i) = patch(px,py,c(i)); end; if nargout>0, pp = p; end; %%%%% function [t, wd] = textbox(x,y,str,varargin) % TEXTBOX Draws A Box around the text % % [T, WIDTH] = TEXTBOX(X, Y, STR) % [..] = TEXTBOX(STR) % % Inputs : % X, Y : Coordinates % TXT : Strings % % Outputs : % T : Object Handles % WIDTH : x and y Width of boxes %% % Usage Example : t = textbox({'Ali','Veli','49','50'}); % % % Note : % See also TEXTOVAL % Uses : % Change History : % Date Time Prog Note % 09-Jun-1998 11:43 AM ATC Created under MATLAB 5.1.0.421 % 12-Mar-2004 10:00 AM minka Changed placement/sizing. % % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] temp = []; textProperties = {'BackgroundColor','Color','FontAngle','FontName','FontSize','FontUnits','FontWeight','Rotation'}; varargin = argfilter(varargin,textProperties); if nargin == 1 str = x; end if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, if nargin == 1 [x, y] = ginput(1); end tx = text(x(i),y(i),str{i},'HorizontalAlignment','center',varargin{:}); % minka [ptc wx wy] = draw_box(tx); wd(i,:) = [wx wy]; % draw_box will paint over the text, so need to redraw it delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center',varargin{:}); temp = [temp; tx ptc]; end; if nargout>0, t = temp; end; function [ptc, wx, wy] = draw_box(tx) % Draws a box around a text object sz = get(tx,'Extent'); % minka wy = 1/2*sz(4); wx = 1/2*sz(3); x = sz(1)+sz(3)/2; y = sz(2)+sz(4)/2; ptc = patch([x-wx x+wx x+wx x-wx], [y+wy y+wy y-wy y-wy],'w'); set(ptc, 'FaceColor','w'); function args = argfilter(args,keep) %ARGFILTER Remove unwanted arguments. % ARGFILTER(ARGS,KEEP), where ARGS = {'arg1',value1,'arg2',value2,...}, % returns a new argument list where only the arguments named in KEEP are % retained. KEEP is a character array or cell array of strings. % Written by Tom Minka if ischar(keep) keep = cellstr(keep); end i = 1; while i < length(args) if ~ismember(args{i},keep) args = args(setdiff(1:length(args),[i i+1])); else i = i + 2; end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
forrest_ll2.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/toolbox/forrest_ll2.m
2,850
utf_8
a284d701978ee08905a2c299a206516a
function [l, missed] = forrest_ll2(data, atree, verbose); % calculuate the log-likelihood of data under a forrest model % % Copyright (C) 2006 - 2009 by Stefan Harmeling (2009-06-26). if ~exist('verbose', 'var') || isempty(verbose) verbose = 0; end if isempty(atree) error('[%s.m] tree is empty', mfilename); end l = 0; % log-likelihood ignored = 0; min_ll_datum = inf; %%%fprintf('[%s.m] calculating the log-likelihood of the data\n'); for i = 1:size(data.x, 2) if verbose > 1 fprintf('[%s.m] %d/%d\n', mfilename, i, size(data.x, 2)); end datum = data.x(:, i); ll_datum = 0; for j = 1:length(atree.t0) % loop over all roots msg = gen_message(atree.t0(j), datum, atree); ll_datum = ll_datum + log(msg * atree.p0{j}); % sum out the root variable end if ll_datum == -Inf ignored = ignored + 1; else min_ll_datum = min(min_ll_datum,ll_datum); l = l + ll_datum; end end if ignored > 0 warning(sprintf('[%s.m] %d of %d data points had zero prob.', mfilename, ... ignored, size(data.x, 2))); fprintf('Using the minimum lilkelihood %f instead of -Inf\n',min_ll_datum); l = l+ignored*min_ll_datum; end missed = ignored; function msg = gen_message(subtree, datum, atree); % the message is a likelihood of the leaves of the current subtree fixed % given all values of the root of the current subtree % % e.g. for the tree (x1 x2 (x3 x4 x5)) % % x1 % / \ % x2 x3 % / \ % x4 x5 % % p(<none> | x5) = gen_message(5, ...); % = (0 0 1 0 0); % int x5 determining position of 1 % p(<none> | x4) = gen_message(4, ...); % = (0 0 1 0 0); % int x4 determining position of 1 % p(x4, x5 | x3) = gen_message(3, ...); % = p(x4|x3) p(x5|x3) % = (p(x4|x3)*p(<none>|x4)) .* (p(x5|x3)*p(<none>|x5)) % p(<none> | x2) = gen_message(2, ...); % = (0 0 0 1 0); % int x2 determining position of 1 % p(x2, x4, x5 | x1) = gen_message(1, ...); % = p(x2|x1)*sum_x3 p(x3|x1) p(x4,x5|x3) % do we have data at the current node? if subtree > atree.nobs % NOT OBSERVED % create a vector with ones that allows all values msg = ones(1, atree.nsyms(subtree)); else % OBSERVED % create a vector with zeros and a single one, which will pick out the % correct row from the CPT of the parent msg = zeros(1, atree.nsyms(subtree)); msg(datum(subtree)) = 1; end % does subtree has kids? nkids = size(atree.t{subtree}, 2); if nkids > 0 % ask for the messages of the kids for j = 1:nkids kid = atree.t{subtree}(j); kid_msg = gen_message(kid, datum, atree); cpt = atree.p{subtree}{j}; % the matrix product does sum out the kid msg = msg .* (kid_msg*cpt); end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
queryFamiliesClustering.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/toolbox/queryFamiliesClustering.m
5,005
utf_8
8df6181dc3a9864c626905100cb4d562
function [families, parents, avg_log_ratio] = queryFamiliesClustering(distance,numSamples,verbose) % Find family groups by adaptive thresholding if(nargin < 3) verbose = 0; end edgeD_min = -log(0.1); edgeD_max = -log(0.9); m = size(distance,1); %relD_thres = 2*edgeD_min; % For reliable statistics, ignore distances below this threshold relD_thres = -log(0.05)+0.1*log(numSamples); diff_log_ratio = inf*ones(m); avg_log_ratio = sparse(m,m); for i=1:m for j=i+1:m if(distance(i,j) > 2*edgeD_min) diff_log_ratio(i,j) = 10; continue; end if(m > 5) other_nodes = (distance(i,:) < relD_thres) & (distance(j,:) < relD_thres); dt = relD_thres; while(sum(other_nodes) <= 5) % Need at least 2 other nodes to identify siblings dt = dt + log(2); other_nodes = (distance(i,:) < dt) & (distance(j,:) < dt); end else other_nodes = true(1,m); end other_nodes([i,j]) = false; log_ratio = distance(i,other_nodes) - distance(j,other_nodes); diff_log_ratio(i,j) = max(log_ratio) - min(log_ratio); avg_log_ratio(i,j) = mean(log_ratio); end end avg_log_ratio = avg_log_ratio - avg_log_ratio'; D = min(diff_log_ratio,diff_log_ratio'); families = kmeansDistance(D,verbose); % Check whether there exists a parent node for each grouping parents = zeros(length(families),1); for f = 1:length(families) members = families{f}; parent_score = zeros(length(members),1); for i=1:length(members) p = members(i); parent_score(i) = sum(abs(avg_log_ratio(p,members) + distance(p,members))); end [min_parent_score, j] = min(parent_score); if(length(members)==1 || min_parent_score < 2*edgeD_max*(length(members)-1)) % d(j,h) > edgeD_max parents(f) = members(j); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function best_clusters = kmeansDistance(D,verbose) m = size(D,1); minD = min(D); [foo,sort_ind_minD] = sort(minD,'descend'); for i=1:m D(i,i) = 0; end %max_mean_silh = max(minD)/max(D(:)); max_mean_silh = -log(0.5)/max(D(:)); best_clusters = {1:m}; if(verbose) fprintf('k = 1, mean silhouette = %f\n',max_mean_silh); end for k = 2:m-2 for init_ite=1:4 % Select the initial center points if (init_ite==1) centers = sort_ind_minD([1:k-1,end])'; elseif(init_ite==2) centers = sort_ind_minD(1:k)'; else randpermm = randperm(m); centers = randpermm(1:k)'; end prev_centers = centers; for ite=1:5 % Assign clusters for each point clusters = mat2cell(centers,ones(k,1)); noncenters = setdiff(1:m,centers); for j=1:length(noncenters) i = noncenters(j); [foo, assignC] = min(D(i,centers)); clusters{assignC}(end+1) = i; end % Pick a new center for each cluster for c=1:k minmaxD = inf; for j=1:length(clusters{c}) i = clusters{c}(j); maxD = max(D(i,clusters{c})); if(maxD < minmaxD) minmaxD = maxD; center = i; end end centers(c) = center; end if(isempty(setdiff(centers,prev_centers))) break; else prev_centers = centers; end end mean_silh = compSilhouette(D, clusters); if(mean_silh > max_mean_silh) max_mean_silh = mean_silh; best_clusters = clusters; if(verbose) fprintf('* '); %fprintf('k = %d, mean silhouette = %f\n',k,mean_silh); disp(clusters) end end if(verbose) fprintf('k = %d, mean silhouette = %f\n',k,mean_silh); end end end %fprintf('*\n'); function mean_silh = compSilhouette(D, clusters) m = size(D,1); k = length(clusters); sumDcluster = zeros(m,k); % maxinD = zeros(k,1); for c=1:k sumDcluster(:,c) = mean(D(:,clusters{c}),2); % %disp(clusters{c}) maxinD(c) = max(max(D(clusters{c},clusters{c}))); end maxa = max(maxinD); silh = zeros(m,1); for c=1:k numMembers = length(clusters{c}); otherClusterMembers = true(1,m); otherClusterMembers(clusters{c}) = false; for j=1:numMembers; i = clusters{c}(j); if(numMembers > 1) a = sumDcluster(i,c)*numMembers/(numMembers-1); %a = max(D(i,clusters{c})); else a = maxa; %silh(i) = 0; end b = min(sumDcluster(i,[1:c-1,c+1:end])); %b = min(D(i,otherClusterMembers)); silh(i) = (b-a)/max(a,b); end end %mean_silh = mean(silh(silh~=0)); mean_silh = mean(silh);
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
treeLayout.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/toolbox/treeLayout.m
2,812
utf_8
a3b707653d47e879ac3e0006f320963f
function [x,y] = treeLayout(adj,root,edge_weight) % Similar to make_layout but specialized for a tree. if nargin < 2 root = 1; end if nargin < 3 edge_weight = adj; end N = size(adj,1); level = poset(adj,root)'-1; y = (level+1)./(max(level)+2); y = 1-y; % neighbors = find(adj(root,:)); % [temp1, sorted_index] = sort(edge_weight(root,neighbors),'descend'); % neighbors = neighbors(sorted_index); % if(length(neighbors) > 20) % neighbors1 = neighbors(1:2:end); % neighbors2 = neighbors(2:2:end); % y(neighbors1) = y(neighbors1)+0.03; % y(neighbors2) = y(neighbors2)-0.03; % end x = zeros(size(y)); for i=0:max(level), idx = find(level==i); if(i<1) x(idx) = 0.5; child_order = (1:length(idx)); else offset=0; pidx = find(level==i-1); [v, ind] = sort(child_order); pidx = pidx(ind); child_order = zeros(length(idx),1); for j=1:length(pidx) [tf,child_nodes] = ismember(find(adj(pidx(j),:)),idx); child_nodes = child_nodes(tf); % Sort child with edge weights %child_edge_weights = edge_weight(pidx(j),idx(child_nodes)); %[temp1, edge_weight_order] = sort(child_edge_weights,'ascend'); %[temp2, siblings_order] = sort(edge_weight_order, 'ascend'); siblings_order = 1:length(child_nodes); child_order(child_nodes) = siblings_order+offset; offset = offset + length(child_nodes); end x(idx) = child_order./(length(idx)+1); if(length(idx)>20) [tmp,co_sorted] = sort(child_order,'ascend'); idx_co = idx(co_sorted); y(idx_co(1:2:end)) = y(idx_co(1:2:end))+0.03; y(idx_co(2:2:end)) = y(idx_co(2:2:end))-0.03; end end end; %%%%%%% function [depth] = poset(adj, root) % POSET Identify a partial ordering among the nodes of a graph % % [DEPTH] = POSET(ADJ,ROOT) % % Inputs : % ADJ : Adjacency Matrix % ROOT : Node to start with % % Outputs : % DEPTH : Depth of the Node % % Usage Example : [depth] = poset(adj,12); % % % Note : All Nodes must be connected % See also % Uses : % Change History : % Date Time Prog Note % 17-Jun-1998 12:01 PM ATC Created under MATLAB 5.1.0.421 % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] adj = adj+adj'; N = size(adj,1); depth = zeros(N,1); depth(root) = 1; queue = root; while 1, if isempty(queue), if all(depth), break; else root = find(depth==0); root = root(1); depth(root) = 1; queue = root; end; end; r = queue(1); queue(1) = []; idx = find(adj(r,:)); idx2 = find(~depth(idx)); idx = idx(idx2); queue = [queue idx]; depth(idx) = depth(r)+1; end;
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
treeMsgOrder.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/toolbox/treeMsgOrder.m
1,545
utf_8
1d7c7a885cd6c01b2ab00e3df5baee6f
function msg = treeMsgOrder(adj, root) %treeMsgOrder Find message scheduling for inference on a tree. % Determines a sequence of message updates by which BP produces optimal % smoothed estimates on a tree-structured undirected graph. % % msg = treeMsgOrder(adj, root) % % PARAMETERS: % adj = adjacency matrix of tree-structured graph with N nodes % root = index of root node used to define scheduling (DEFAULT=1) % OUTPUTS: % msg = 2(N-1)-by-2 matrix such that row i gives the source and % destination nodes for the i^th message passing % Erik Sudderth % May 16, 2003 - Initial version % Check and process input arguments if (nargin < 1) error('Invalid number of arguments'); end if (nargin < 2) root = 1; end N = length(adj); if (root > N | root < 1) error('Invalid root node'); end msg = zeros(2*(N-1),2); % Recurse from root to define outgoing (scale-recursive) message pass msgIndex = N; prevNodes = []; crntNodes = root; while (msgIndex <= 2*(N-1)) allNextNodes = []; for (i = 1:length(crntNodes)) nextNodes = setdiff(find(adj(crntNodes(i),:)),prevNodes); Nnext = length(nextNodes); msg(msgIndex:msgIndex+Nnext-1,:) = ... [repmat(crntNodes(i),Nnext,1), nextNodes']; msgIndex = msgIndex + Nnext; allNextNodes = [allNextNodes, nextNodes]; end prevNodes = [prevNodes, crntNodes]; crntNodes = allNextNodes; end % Incoming messages are reverse of outgoing msg(1:N-1,:) = fliplr(flipud(msg(N:end,:)));
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
myProcessOptions.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/misc/myProcessOptions.m
674
utf_8
b94d252a960faa95a3074129247619e6
function [varargout] = myProcessOptions(options,varargin) % Similar to processOptions, but case insensitive and % using a struct instead of a variable length list options = toUpper(options); for i = 1:2:length(varargin) if isfield(options,upper(varargin{i})) v = getfield(options,upper(varargin{i})); if isempty(v) varargout{(i+1)/2}=varargin{i+1}; else varargout{(i+1)/2}=v; end else varargout{(i+1)/2}=varargin{i+1}; end end end function [o] = toUpper(o) if ~isempty(o) fn = fieldnames(o); for i = 1:length(fn) o = setfield(o,upper(fn{i}),getfield(o,fn{i})); end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
myProcessOptions.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/minConf/myProcessOptions.m
674
utf_8
b94d252a960faa95a3074129247619e6
function [varargout] = myProcessOptions(options,varargin) % Similar to processOptions, but case insensitive and % using a struct instead of a variable length list options = toUpper(options); for i = 1:2:length(varargin) if isfield(options,upper(varargin{i})) v = getfield(options,upper(varargin{i})); if isempty(v) varargout{(i+1)/2}=varargin{i+1}; else varargout{(i+1)/2}=v; end else varargout{(i+1)/2}=varargin{i+1}; end end end function [o] = toUpper(o) if ~isempty(o) fn = fieldnames(o); for i = 1:length(fn) o = setfield(o,upper(fn{i}),getfield(o,fn{i})); end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
minConf_TMP.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/minConf/minConf/minConf_TMP.m
8,550
utf_8
6983e0de62f07b14b5a7e0f3b9d6b3df
function [x,f,funEvals] = minConF_BC(funObj,x,LB,UB,options) % function [x,f] = minConF_BC(funObj,x,LB,UB,options) % % Function for using Two-Metric Projection to solve problems of the form: % min funObj(x) % s.t. LB_i <= x_i <= UB_i % % @funObj(x): function to minimize (returns gradient as second argument) % % options: % verbose: level of verbosity (0: no output, 1: final, 2: iter (default), 3: % debug) % optTol: tolerance used to check for progress (default: 1e-7) % maxIter: maximum number of calls to funObj (default: 250) % numDiff: compute derivatives numerically (0: use user-supplied % derivatives (default), 1: use finite differences, 2: use complex % differentials) % method: 'sd', 'lbfgs', 'newton' nVars = length(x); % Set Parameters if nargin < 5 options = []; end [verbose,numDiff,optTol,maxIter,suffDec,interp,method,corrections,damped] = ... myProcessOptions(... options,'verbose',3,'numDiff',0,'optTol',1e-6,'maxIter',500,'suffDec',1e-4,... 'interp',1,'method','lbfgs','corrections',100,'damped',0); % Output Log if verbose >= 3 fprintf('%10s %10s %15s %15s %15s\n','Iteration','FunEvals','Step Length','Function Val','Opt Cond'); end % Make objective function (if using numerical derivatives) funEvalMultiplier = 1; if numDiff if numDiff == 2 useComplex = 1; else useComplex = 0; end funObj = @(x)autoGrad(x,useComplex,funObj); funEvalMultiplier = nVars+1-useComplex; end % Evaluate Initial Point x = projectBounds(x,LB,UB); if strcmp(method,'newton') [f,g,H] = funObj(x); secondOrder = 1; else [f,g] = funObj(x); secondOrder = 0; end funEvals = 1; % Compute Working Set working = ones(nVars,1); working((x < LB+optTol*2) & g >= 0) = 0; working((x > UB-optTol*2) & g <= 0) = 0; working = find(working); % Check Optimality if isempty(working) if verbose >= 1 fprintf('All variables are at their bound and no further progress is possible at initial point\n'); end return; elseif norm(g(working)) <= optTol if verbose >=1 fprintf('All working variables satisfy optimality condition at initial point\n'); end return; end if verbose >= 3 switch method case 'sd' fprintf('Steepest Descent\n'); case 'lbfgs' fprintf('L-BFGS\n'); case 'bfgs' fprintf('BFGS\n'); case 'newton' fprintf('Newton\n'); end end i = 1; while funEvals <= maxIter % Compute Step Direction d = zeros(nVars,1); switch(method) case 'sd' d(working) = -g(working); case 'lbfgs' if i == 1 d(working) = -g(working); old_dirs = zeros(nVars,0); old_stps = zeros(nVars,0); Hdiag = 1; else if damped [old_dirs,old_stps,Hdiag] = dampedUpdate(g-g_old,x-x_old,corrections,verbose==3,old_dirs,old_stps,Hdiag); else [old_dirs,old_stps,Hdiag] = lbfgsUpdate(g-g_old,x-x_old,corrections,verbose==3,old_dirs,old_stps,Hdiag); end curvSat = sum(old_dirs(working,:).*old_stps(working,:)) > 1e-10; d(working) = lbfgs(-g(working),old_dirs(working,curvSat),old_stps(working,curvSat),Hdiag); end g_old = g; x_old = x; case 'bfgs' if i == 1 d(working) = -g(working); B = eye(nVars); else y = g-g_old; s = x-x_old; ys = y'*s; if i == 2 if ys > 1e-10 B = ((y'*y)/(y'*s))*eye(nVars); end end if ys > 1e-10 B = B + (y*y')/(y'*s) - (B*s*s'*B)/(s'*B*s); else if verbose == 2 fprintf('Skipping Update\n'); end end d(working) = -B(working,working)\g(working); end g_old = g; x_old = x; case 'newton' [R,posDef] = chol(H(working,working)); if posDef == 0 d(working) = -R\(R'\g(working)); else if verbose == 3 fprintf('Adjusting Hessian\n'); end H(working,working) = H(working,working) + eye(length(working)) * max(0,1e-12 - min(real(eig(H(working,working))))); d(working) = -H(working,working)\g(working); end otherwise fprintf('Unrecognized Method: %s\n',method); break; end % Check that Progress can be made along the direction f_old = f; gtd = g'*d; if gtd > -optTol if verbose >= 2 fprintf('Directional Derivative below optTol\n'); end break; end % Select Initial Guess to step length if i == 1 && ~secondOrder t = min(1,1/sum(abs(g(working)))); else t = 1; end % Evaluate the Objective and Projected Gradient at the Initial Step x_new = projectBounds(x+t*d,LB,UB); if secondOrder [f_new,g_new,H] = funObj(x_new); else [f_new,g_new] = funObj(x_new); end funEvals = funEvals+1; % Backtracking Line Search lineSearchIters = 1; while f_new > f + suffDec*g'*(x_new-x) || ~isLegal(f_new) temp = t; if interp == 0 || ~isLegal(f_new) || ~isLegal(g_new) if verbose == 3 fprintf('Halving Step Size\n'); end t = .5*t; else if verbose == 3 fprintf('Cubic Backtracking\n'); end t = polyinterp([0 f gtd; t f_new g_new'*d]); end % Adjust if change is too small if t < temp*1e-3 if verbose == 3 fprintf('Interpolated value too small, Adjusting\n'); end t = temp*1e-3; elseif t > temp*0.6 if verbose == 3 fprintf('Interpolated value too large, Adjusting\n'); end t = temp*0.6; end % Check whether step has become too small if sum(abs(t*d)) < optTol if verbose == 3 fprintf('Line Search failed\n'); end t = 0; f_new = f; g_new = g; break; end % Evaluate New Point x_new = projectBounds(x+t*d,LB,UB); [f_new,g_new] = funObj(x_new); funEvals = funEvals+1; lineSearchIters = lineSearchIters+1; end % Take Step x = x_new; f = f_new; g = g_new; % Compute Working Set working = ones(nVars,1); working((x < LB+optTol*2) & g >= 0) = 0; working((x > UB-optTol*2) & g <= 0) = 0; working = find(working); % Output Log if verbose >= 2 fprintf('%10d %10d %15.5e %15.5e %15.5e\n',i,funEvals*funEvalMultiplier,t,f,sum(abs(g(working)))); end % Check Optimality if isempty(working) if verbose >= 1 fprintf('All variables are at their bound and no further progress is possible\n'); end break; elseif norm(g(working)) <= optTol if verbose >=1 fprintf('All working variables satisfy optimality condition\n'); end break; end % Check for lack of progress if sum(abs(t*d)) < optTol if verbose >= 1 fprintf('Step size below optTol\n'); end break; end if abs(f-f_old) < optTol if verbose >= 1 fprintf('Function value changing by less than optTol\n'); end break; end if funEvals*funEvalMultiplier > maxIter if verbose >= 1 fprintf('Function Evaluations exceeds maxIter\n'); end break; end % If necessary, compute Hessian if secondOrder && lineSearchIters > 1 [f_new,g_new,H] = funObj(x); end i = i + 1; end end function [x] = projectBounds(x,LB,UB) x(x < LB) = LB(x < LB); x(x > UB) = UB(x > UB); end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
minConf_PQN.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/minConf/minConf/minConf_PQN.m
8,743
utf_8
833730ebce2f402d389c4ad511129e60
function [x,f,funEvals] = minConf_PQN(funObj,x,funProj,options) % function [x,f] = minConf_PQN(funObj,funProj,x,options) % % Function for using a limited-memory projected quasi-Newton to solve problems of the form % min funObj(x) s.t. x in C % % The projected quasi-Newton sub-problems are solved the spectral projected % gradient algorithm % % @funObj(x): function to minimize (returns gradient as second argument) % @funProj(x): function that returns projection of x onto C % % options: % verbose: level of verbosity (0: no output, 1: final, 2: iter (default), 3: % debug) % optTol: tolerance used to check for optimality (default: 1e-5) % progTol: tolerance used to check for progress (default: 1e-9) % maxIter: maximum number of calls to funObj (default: 500) % maxProject: maximum number of calls to funProj (default: 100000) % numDiff: compute derivatives numerically (0: use user-supplied % derivatives (default), 1: use finite differences, 2: use complex % differentials) % suffDec: sufficient decrease parameter in Armijo condition (default: 1e-4) % corrections: number of lbfgs corrections to store (default: 10) % adjustStep: use quadratic initialization of line search (default: 0) % bbInit: initialize sub-problem with Barzilai-Borwein step (default: 1) % SPGoptTol: optimality tolerance for SPG direction finding (default: 1e-6) % SPGiters: maximum number of iterations for SPG direction finding (default:10) nVars = length(x); % Set Parameters if nargin < 4 options = []; end [verbose,numDiff,optTol,progTol,maxIter,maxProject,suffDec,corrections,adjustStep,bbInit,... SPGoptTol,SPGprogTol,SPGiters,SPGtestOpt] = ... myProcessOptions(... options,'verbose',2,'numDiff',0,'optTol',1e-5,'progTol',1e-9,'maxIter',500,'maxProject',100000,'suffDec',1e-4,... 'corrections',10,'adjustStep',0,'bbInit',0,'SPGoptTol',1e-6,'SPGprogTol',1e-10,'SPGiters',10,'SPGtestOpt',0); % Output Parameter Settings if verbose >= 3 fprintf('Running PQN...\n'); fprintf('Number of L-BFGS Corrections to store: %d\n',corrections); fprintf('Spectral initialization of SPG: %d\n',bbInit); fprintf('Maximum number of SPG iterations: %d\n',SPGiters); fprintf('SPG optimality tolerance: %.2e\n',SPGoptTol); fprintf('SPG progress tolerance: %.2e\n',SPGprogTol); fprintf('PQN optimality tolerance: %.2e\n',optTol); fprintf('PQN progress tolerance: %.2e\n',progTol); fprintf('Quadratic initialization of line search: %d\n',adjustStep); fprintf('Maximum number of function evaluations: %d\n',maxIter); fprintf('Maximum number of projections: %d\n',maxProject); end % Output Log if verbose >= 2 fprintf('%10s %10s %10s %15s %15s %15s\n','Iteration','FunEvals','Projections','Step Length','Function Val','Opt Cond'); end % Make objective function (if using numerical derivatives) funEvalMultiplier = 1; if numDiff if numDiff == 2 useComplex = 1; else useComplex = 0; end funObj = @(x)autoGrad(x,useComplex,funObj); funEvalMultiplier = nVars+1-useComplex; end % Project initial parameter vector x = funProj(x); projects = 1; % Evaluate initial parameters [f,g] = funObj(x); funEvals = 1; % Check Optimality of Initial Point projects = projects+1; if max(abs(funProj(x-g)-x)) < optTol if verbose >= 1 fprintf('First-Order Optimality Conditions Below optTol at Initial Point\n'); end return; end i = 1; while funEvals <= maxIter % Compute Step Direction if i == 1 p = funProj(x-g); projects = projects+1; S = zeros(nVars,0); Y = zeros(nVars,0); Hdiag = 1; else y = g-g_old; s = x-x_old; [S,Y,Hdiag] = lbfgsUpdate(y,s,corrections,verbose==3,S,Y,Hdiag); % Make Compact Representation k = size(Y,2); L = zeros(k); for j = 1:k L(j+1:k,j) = S(:,j+1:k)'*Y(:,j); end N = [S/Hdiag Y]; M = [S'*S/Hdiag L;L' -diag(diag(S'*Y))]; HvFunc = @(v)lbfgsHvFunc2(v,Hdiag,N,M); if bbInit % Use Barzilai-Borwein step to initialize sub-problem alpha = (s'*s)/(s'*y); if alpha <= 1e-10 || alpha > 1e10 alpha = min(1,1/sum(abs(g))); end % Solve Sub-problem xSubInit = x-alpha*g; feasibleInit = 0; else xSubInit = x; feasibleInit = 1; end % Solve Sub-problem [p,subProjects] = solveSubProblem(x,g,HvFunc,funProj,SPGoptTol,SPGprogTol,SPGiters,SPGtestOpt,feasibleInit,xSubInit); projects = projects+subProjects; end d = p-x; g_old = g; x_old = x; % Check that Progress can be made along the direction gtd = g'*d; if gtd > -progTol if verbose >= 1 fprintf('Directional Derivative below progTol\n'); end break; end % Select Initial Guess to step length if i == 1 || adjustStep == 0 t = 1; else t = min(1,2*(f-f_old)/gtd); end % Bound Step length on first iteration if i == 1 t = min(1,1/sum(abs(g))); end % Evaluate the Objective and Gradient at the Initial Step if t == 1 x_new = p; else x_new = x + t*d; end [f_new,g_new] = funObj(x_new); funEvals = funEvals+1; % Backtracking Line Search f_old = f; while f_new > f + suffDec*g'*(x_new-x) || ~isLegal(f_new) temp = t; % Backtrack to next trial value if ~isLegal(f_new) || ~isLegal(g_new) if verbose == 3 fprintf('Halving Step Size\n'); end t = t/2; else if verbose == 3 fprintf('Cubic Backtracking\n'); end t = polyinterp([0 f gtd; t f_new g_new'*d]); end % Adjust if change is too small/large if t < temp*1e-3 if verbose == 3 fprintf('Interpolated value too small, Adjusting\n'); end t = temp*1e-3; elseif t > temp*0.6 if verbose == 3 fprintf('Interpolated value too large, Adjusting\n'); end t = temp*0.6; end % Check whether step has become too small if sum(abs(t*d)) < progTol || t == 0 if verbose == 3 fprintf('Line Search failed\n'); end t = 0; f_new = f; g_new = g; break; end % Evaluate New Point f_prev = f_new; t_prev = temp; x_new = x + t*d; [f_new,g_new] = funObj(x_new); funEvals = funEvals+1; end % Take Step x = x_new; f = f_new; g = g_new; optCond = max(abs(funProj(x-g)-x)); projects = projects+1; % Output Log if verbose >= 2 fprintf('%10d %10d %10d %15.5e %15.5e %15.5e\n',i,funEvals*funEvalMultiplier,projects,t,f,optCond); end % Check optimality if optCond < optTol fprintf('First-Order Optimality Conditions Below optTol\n'); break; end if max(abs(t*d)) < progTol if verbose >= 1 fprintf('Step size below progTol\n'); end break; end if abs(f-f_old) < progTol if verbose >= 1 fprintf('Function value changing by less than progTol\n'); end break; end if funEvals*funEvalMultiplier > maxIter if verbose >= 1 fprintf('Function Evaluations exceeds maxIter\n'); end break; end if projects > maxProject if verbose >= 1 fprintf('Number of projections exceeds maxProject\n'); end break; end i = i + 1; % pause end end function [p,subProjects] = solveSubProblem(x,g,H,funProj,optTol,progTol,maxIter,testOpt,feasibleInit,x_init) % Uses SPG to solve for projected quasi-Newton direction options.verbose = 0; options.optTol = optTol; options.progTol = progTol; options.maxIter = maxIter; options.testOpt = testOpt; options.feasibleInit = feasibleInit; funObj = @(p)subHv(p,x,g,H); [p,f,funEvals,subProjects] = minConf_SPG(funObj,x_init,funProj,options); end function [f,g] = subHv(p,x,g,HvFunc) d = p-x; Hd = HvFunc(d); f = g'*d + (1/2)*d'*Hd; g = g + Hd; end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_TreeBP.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/misc/UGM_TreeBP.m
2,745
utf_8
baa995f7edc3145b6631c22a4890e471
function [messages] = UGM_TreeBP(nodePot,edgePot,edgeStruct,maximize) [nNodes,maxState] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; nStates = edgeStruct.nStates; V = edgeStruct.V; E = edgeStruct.E; nodeDone = zeros(nNodes,1); sent = zeros(nEdges*2,1); messages = zeros(maxState,nEdges*2); waiting = ones(nEdges*2,1); done = 0; while ~done done = 1; for n = 1:nNodes if nodeDone(n) == 1 continue; end wait = waiting(V(n):V(n+1)-1); sending = sent(V(n):V(n+1)-1); nWaiting = sum(wait==1); if nWaiting == 0 % Send messages %fprintf('Sending final messages\n'); for sendEdge = [V(n)+find(sending==0)-1]' %fprintf('Sending\n'); sent(sendEdge) = 1; [messages,waiting] = send(n,sendEdge,nodePot,edgePot,messages,waiting,edgeStruct,maximize); done = 0; end %fprintf('Node %d is done\n',n); nodeDone(n) = 1; elseif nWaiting > 1 %fprintf('Node %d is waiting for more than 1, skipping\n',n); continue; else %fprintf('Node %d is waiting for 1 neighbor, trying to send to this 1\n',n); remainingEdge = V(n)+find(wait==1)-1; if ~sent(remainingEdge) %fprintf('Sending\n'); sent(remainingEdge) = 1; [messages,waiting] = send(n,remainingEdge,nodePot,edgePot,messages,waiting,edgeStruct,maximize); done = 0; end end end end end function [messages,waiting] = send(n,e,nodePot,edgePot,messages,waiting,edgeStruct,maximize) edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; nEdges = size(edgeEnds,1); edge = E(e); if n == edgeEnds(edge,1) nei = edgeEnds(edge,2); else nei = edgeEnds(edge,1); end %fprintf('Sending from %d to %d\n',n,nei); for tmp = V(nei):V(nei+1)-1 if tmp ~= e && E(tmp) == E(e) waiting(tmp) = 0; end end e = edge; % Compute Product of node potential with all incoming messages except % along e temp = nodePot(n,1:nStates(n))'; neighbors = E(V(n):V(n+1)-1); for e2 = neighbors(:)' if e ~= e2 if n == edgeEnds(e2,2) temp = temp .* messages(1:nStates(n),e2); else temp = temp .* messages(1:nStates(n),e2+nEdges); end end end n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,2) pot_ij = edgePot(1:nStates(n1),1:nStates(n2),e); else pot_ij = edgePot(1:nStates(n1),1:nStates(n2),e)'; end if maximize newm = max_mult(pot_ij,temp); else newm = pot_ij*temp; end if n == edgeEnds(e,2); messages(1:nStates(n1),e+nEdges) = newm./sum(newm); else messages(1:nStates(n2),e) = newm./sum(newm); end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Sample_VarMCMC.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/sample/UGM_Sample_VarMCMC.m
2,625
utf_8
b61803b06589d39b8589ddf7e705bdf6
function [samples] = UGM_Sample_VarMCMC(nodePot,edgePot,edgeStruct,burnIn,varProb) % MCMC sampler that switches between random walk MH and variational MF % sampling % % varProb is the probability of trying the variational move % (set to 0 for purely variational proposals) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; maxIter = edgeStruct.maxIter; % Fit mean-field model MFnodeBel = UGM_Infer_MeanField(nodePot,edgePot,edgeStruct); % Initialize y = meanFieldSample(MFnodeBel); samples = zeros(nNodes,maxIter); for i= 1:burnIn+maxIter if rand < varProb % Do variational Metropolis-Hastings step %fprintf('Computing Variational Sample\n'); logPot = UGM_LogConfigurationPotential(y,nodePot,edgePot,edgeEnds); mfLogPot = 0; for n = 1:nNodes mfLogPot = mfLogPot + log(MFnodeBel(n,y(n))); end y_new = meanFieldSample(MFnodeBel); logPot_new = UGM_LogConfigurationPotential(y_new,nodePot,edgePot,edgeEnds); mfLogPot_new = 0; for n = 1:nNodes mfLogPot_new = mfLogPot_new + log(MFnodeBel(n,y_new(n))); end %imagesc([reshape(y,32,32) reshape(y_new,32,32)]) %colormap gray logAcceptance = logPot_new + mfLogPot - logPot - mfLogPot_new; acceptance = exp(logAcceptance); if rand < acceptance y = y_new; %fprintf('Accepted\n'); else %fprintf('Rejected\n'); end %pause else % Do Gibbs step %fprintf('Computing Gibbs Sample\n'); y = gibbsSample(y,nodePot,edgePot,nStates,edgeEnds,V,E); end if i > burnIn samples(:,i-burnIn) = y; end end end function [y] = meanFieldSample(nodeBel) [nNodes,maxStates] = size(nodeBel); y = zeros(nNodes,1); for n = 1:nNodes y(n) = sampleDiscrete(nodeBel(n,:)); end end function [y] = gibbsSample(y,nodePot,edgePot,nStates,edgeEnds,V,E) [nNodes,maxState] = size(nodePot); for n = 1:nNodes % Compute Node Potential pot = nodePot(n,1:nStates(n)); % Find Neighbors edges = E(V(n):V(n+1)-1); % Multiply Edge Potentials for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,1) ep = edgePot(1:nStates(n1),y(n2),e)'; else ep = edgePot(y(n1),1:nStates(n2),e); end pot = pot .* ep; end % Sample State; y(n) = sampleDiscrete(pot./sum(pot)); end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Sample_Gibbs.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/sample/UGM_Sample_Gibbs.m
1,475
utf_8
fc98ab2b4b0110d00bef783f438a7cb3
function [samples] = UGM_Sample_Gibbs(nodePot,edgePot,edgeStruct,burnIn,y) % [samples] = UGM_Sample_Gibbs(nodePot,edgePot,edgeStruct,burnIn,y) % Single Site Gibbs Sampling if nargin < 5 % Initialize [junk y] = max(nodePot,[],2); end if edgeStruct.useMex samples = UGM_Sample_GibbsC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(edgeStruct.V),int32(edgeStruct.E),edgeStruct.maxIter,burnIn,int32(y)); else samples = Sample_Gibbs(nodePot,edgePot,edgeStruct,burnIn,y); end end function [samples] = Sample_Gibbs(nodePot,edgePot,edgeStruct,burnIn,y) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; maxIter = edgeStruct.maxIter; samples = zeros(nNodes,0); for i = 1:burnIn+maxIter for n = 1:nNodes % Compute Node Potential pot = nodePot(n,1:nStates(n)); % Find Neighbors edges = E(V(n):V(n+1)-1); % Multiply Edge Potentials for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,1) ep = edgePot(1:nStates(n1),y(n2),e)'; else ep = edgePot(y(n1),1:nStates(n2),e); end pot = pot .* ep; end % Sample State; y(n) = sampleDiscrete(pot./sum(pot)); end if i > burnIn samples(:,i-burnIn) = y; end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Sample_Exact.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/sample/UGM_Sample_Exact.m
2,003
utf_8
a154b2b69704368d50fb3f106f13340b
function [samples] = UGM_Sample_Exact(nodePot,edgePot,edgeStruct) % Exact sampling assert(prod(edgeStruct.nStates) < 50000000,'Brute Force Exact Sampling not recommended for models with > 50 000 000 states'); [nNodes,maxState] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; nStates = edgeStruct.nStates; maxIter= edgeStruct.maxIter; samples = zeros(nNodes,0); Z = computeZ(nodePot,edgePot,edgeEnds,nStates); for s = 1:maxIter samples(:,s) = sampleY(nodePot,edgePot,edgeEnds,nStates,Z); end end function [Z] = computeZ(nodePot,edgePot,edgeEnds,nStates) nEdges = size(edgePot,3); [nNodes maxStates] = size(nodePot); y = ones(1,nNodes); Z = 0; while 1 pot = 1; % Nodes for n = 1:nNodes pot = pot*nodePot(n,y(n)); end % Edges for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); pot = pot*edgePot(y(n1),y(n2),e); end % Update Z Z = Z + pot; % Go to next y for yInd = 1:nNodes y(yInd) = y(yInd) + 1; if y(yInd) <= nStates(yInd) break; else y(yInd) = 1; end end % Stop when we are done all y combinations if sum(y==1) == nNodes break; end end end function [y] = sampleY(nodePot,edgePot,edgeEnds,nStates,Z) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); y = ones(1,nNodes); cumulativePot = 0; U = rand; while 1 pot = 1; % Nodes for n = 1:nNodes pot = pot*nodePot(n,y(n)); end % Edges for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); pot = pot*edgePot(y(n1),y(n2),e); end % Update cumulative potential cumulativePot = cumulativePot + pot; if cumulativePot/Z > U % Take this y break; end % Go to next y for yInd = 1:nNodes y(yInd) = y(yInd) + 1; if y(yInd) <= nStates(yInd) break; else y(yInd) = 1; end end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Infer_Exact.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/infer/UGM_Infer_Exact.m
1,876
utf_8
ee20f10625b7e182499b0d93e3434775
function [nodeBel, edgeBel, logZ] = UGM_Infer_Exact(nodePot, edgePot, edgeStruct) % INPUT % nodePot(node,class) % edgePot(class,class,edge) where e is referenced by V,E (must be the same % between feature engine and inference engine) % % OUTPUT % nodeBel(node,class) - marginal beliefs % edgeBel(class,class,e) - pairwise beliefs % logZ - negative of free energy assert(prod(edgeStruct.nStates) < 50000000,'Brute Force Exact Inference not recommended for models with > 50 000 000 states'); if edgeStruct.useMex [nodeBel,edgeBel,logZ] = UGM_Infer_ExactC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates)); else [nodeBel,edgeBel,logZ] = Infer_Exact(nodePot,edgePot,edgeStruct); end end function [nodeBel, edgeBel, logZ] = Infer_Exact(nodePot, edgePot, edgeStruct) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; nStates = edgeStruct.nStates; % Initialize nodeBel = zeros(size(nodePot)); edgeBel = zeros(size(edgePot)); y = ones(1,nNodes); Z = 0; i = 1; while 1 pot = UGM_ConfigurationPotential(y,nodePot,edgePot,edgeEnds); % Update nodeBel for n = 1:nNodes nodeBel(n,y(n)) = nodeBel(n,y(n))+pot; end % Update edgeBel for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); edgeBel(y(n1),y(n2),e) = edgeBel(y(n1),y(n2),e)+pot; end % Update Z Z = Z + pot; % Go to next y for yInd = 1:nNodes y(yInd) = y(yInd) + 1; if y(yInd) <= nStates(yInd) break; else y(yInd) = 1; end end % Stop when we are done all y combinations if yInd == nNodes && y(end) == 1 break; end end nodeBel = nodeBel./Z; edgeBel = edgeBel./Z; logZ = log(Z); end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Infer_TRBP.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/infer/UGM_Infer_TRBP.m
4,237
utf_8
eee0c6b71628076316fbde2d253256e7
function [nodeBel, edgeBel, logZ] = UGM_Infer_TRBP(nodePot,edgePot,edgeStruct) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); % Compute Edge Appearance Probabilities if 0 %nEdges == nNodes*(nNodes-1)/2 mu = ((nNodes-1)/nEdges)*ones(nEdges,1); elseif 1 % Generate Random Spanning Trees until all edges are covered [nNodes,maxState] = size(nodePot); edgeEnds = edgeStruct.edgeEnds; i = 0; edgeAppears = zeros(nEdges,1); while 1 i = i+1; edgeAppears = edgeAppears+minSpan(nNodes,[edgeEnds rand(nEdges,1)]); if all(edgeAppears > 0) break; end end mu = edgeAppears/i; else mu = ones(nEdges,1); % Ordinary BP end [nodeBel, edgeBel, logZ] = Infer_TRBP(nodePot,edgePot,edgeStruct,mu); end %% function [nodeBel, edgeBel, logZ] = Infer_TRBP(nodePot,edgePot,edgeStruct,mu) [nNodes,maxState] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; maximize = 0; new_msg = UGM_TRBP(nodePot,edgePot,edgeStruct,maximize,mu); %% Compute nodeBel nodeBel = zeros(nNodes,maxState); for n = 1:nNodes edges = E(V(n):V(n+1)-1); prod_of_msgs(1:nStates(n),n) = nodePot(n,1:nStates(n))'; for e = edges(:)' if n == edgeEnds(e,2) prod_of_msgs(1:nStates(n),n) = prod_of_msgs(1:nStates(n),n) .* (new_msg(1:nStates(n),e).^mu(e)); else prod_of_msgs(1:nStates(n),n) = prod_of_msgs(1:nStates(n),n) .* (new_msg(1:nStates(n),e+nEdges).^mu(e)); end end nodeBel(n,1:nStates(n)) = prod_of_msgs(1:nStates(n),n)'./sum(prod_of_msgs(1:nStates(n),n)); end %% Compute edgeBel if nargout > 1 edgeBel = zeros(maxState,maxState,nEdges); for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); % nodePot by all messages to n1 except from n2 edges = E(V(n1):V(n1+1)-1); temp1 = nodePot(n1,1:nStates(n1))'; for e2 = edges(:)' if n1 == edgeEnds(e2,2) incoming = new_msg(1:nStates(n1),e2); else incoming = new_msg(1:nStates(n1),e2+nEdges); end if e ~= e2 temp1 = temp1 .* incoming.^mu(e2); else temp1 = temp1 ./ incoming.^(1-mu(e2)); end end % nodePot by all messages to n2 except from n1 edges = E(V(n2):V(n2+1)-1); temp2 = nodePot(n2,1:nStates(n2))'; for e2 = edges(:)' if n2 == edgeEnds(e2,2) incoming = new_msg(1:nStates(n2),e2); else incoming = new_msg(1:nStates(n2),e2+nEdges); end if e ~= e2 temp2 = temp2 .* incoming.^mu(e2); else temp2 = temp2 ./ incoming.^(1-mu(e2)); end end eb = repmat(temp1,[1 nStates(n2)]).*repmat(temp2',[nStates(n1) 1]).*(edgePot(1:nStates(n1),1:nStates(n2),e).^(1/mu(e))); edgeBel(1:nStates(n1),1:nStates(n2),e) = eb./sum(eb(:)); end end %% Compute Free Energy if nargout > 2 Energy1 = 0; Energy2 = 0; Entropy1 = 0; Entropy2 = 0; nodeBel = nodeBel+eps; edgeBel = edgeBel+eps; for n = 1:nNodes edges = E(V(n):V(n+1)-1); nNbrs = length(edges); % Node Entropy (note: different weighting than in Bethe) Entropy1 = Entropy1 + (sum(mu(edges))-1)*sum(nodeBel(n,1:nStates(n)).*log(nodeBel(n,1:nStates(n)))); % Node Energy Energy1 = Energy1 - sum(nodeBel(n,1:nStates(n)).*log(nodePot(n,1:nStates(n)))); end for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); % Pairwise Entropy (note: different weighting than in Bethe) eb = edgeBel(1:nStates(n1),1:nStates(n2),e); Entropy2 = Entropy2 - mu(e)*sum(eb(:).*log(eb(:))); % Pairwise Energy ep = edgePot(1:nStates(n1),1:nStates(n2),e); Energy2 = Energy2 - sum(eb(:).*log(ep(:))); end F = (Energy1+Energy2) - (Entropy1+Entropy2); logZ = -F; end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Infer_LBP.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/infer/UGM_Infer_LBP.m
2,799
utf_8
5101f62b8c2760b27424c72e3f8746c5
function [nodeBel, edgeBel, logZ] = UGM_Infer_LBP(nodePot,edgePot,edgeStruct) if edgeStruct.useMex [nodeBel,edgeBel,logZ] = UGM_Infer_LBPC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(edgeStruct.V),int32(edgeStruct.E),edgeStruct.maxIter); else [nodeBel, edgeBel, logZ] = Infer_LBP(nodePot,edgePot,edgeStruct); end end function [nodeBel, edgeBel, logZ] = Infer_LBP(nodePot,edgePot,edgeStruct) [nNodes,maxState] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; maximize = 0; new_msg = UGM_LoopyBP(nodePot,edgePot,edgeStruct,maximize); % Compute nodeBel for n = 1:nNodes edges = E(V(n):V(n+1)-1); prod_of_msgs(1:nStates(n),n) = nodePot(n,1:nStates(n))'; for e = edges(:)' if n == edgeEnds(e,2) prod_of_msgs(1:nStates(n),n) = prod_of_msgs(1:nStates(n),n) .* new_msg(1:nStates(n),e); else prod_of_msgs(1:nStates(n),n) = prod_of_msgs(1:nStates(n),n) .* new_msg(1:nStates(n),e+nEdges); end end nodeBel(n,1:nStates(n)) = prod_of_msgs(1:nStates(n),n)'./sum(prod_of_msgs(1:nStates(n),n)); end if nargout > 1 % Compute edge beliefs edgeBel = zeros(maxState,maxState,nEdges); for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); belN1 = nodeBel(n1,1:nStates(n1))'./new_msg(1:nStates(n1),e+nEdges); belN2 = nodeBel(n2,1:nStates(n2))'./new_msg(1:nStates(n2),e); b1=repmatC(belN1,1,nStates(n2)); b2=repmatC(belN2',nStates(n1),1); eb = b1.*b2.*edgePot(1:nStates(n1),1:nStates(n2),e); edgeBel(1:nStates(n1),1:nStates(n2),e) = eb./sum(eb(:)); end end if nargout > 2 % Compute Bethe free energy Energy1 = 0; Energy2 = 0; Entropy1 = 0; Entropy2 = 0; nodeBel = nodeBel+eps; edgeBel = edgeBel+eps; for n = 1:nNodes edges = E(V(n):V(n+1)-1); nNbrs = length(edges); % Node Entropy (can get divide by zero if beliefs at 0) Entropy1 = Entropy1 + (nNbrs-1)*sum(nodeBel(n,1:nStates(n)).*log(nodeBel(n,1:nStates(n)))); % Node Energy Energy1 = Energy1 - sum(nodeBel(n,1:nStates(n)).*log(nodePot(n,1:nStates(n)))); end for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); % Pairwise Entropy (can get divide by zero if beliefs at 0) eb = edgeBel(1:nStates(n1),1:nStates(n2),e); Entropy2 = Entropy2 - sum(eb(:).*log(eb(:))); % Pairwise Energy ep = edgePot(1:nStates(n1),1:nStates(n2),e); Energy2 = Energy2 - sum(eb(:).*log(ep(:))); end F = (Energy1+Energy2) - (Entropy1+Entropy2); logZ = -F; end end